nat's own mod, loaded into every Claude Code session nat launches with --plugin-dir and nowhere else.

nat's own Claude Code mod. nat loads it into every agent session it launches with claude --plugin-dir, for that one session only; it is never installed and never reaches a session nat did not start. Nothing here is meant to be loaded by hand.
Tested with Claude Code 2.1.296.
hooks/register.ts — the hooks, which quiet the pane's chrome by rewriting Claude Code's own render-site props: the prompt hint (? for shortcuts, which is also how a load shows in the pane) and the run-in-background pill draw empty, the turn duration line and the notices under the logo draw nothing, and the spinner says Working. The session modes are left alone. They also set the pane's waiting flag (nat agent waiting / nat agent working) while an AskUserQuestion dialog, a permission prompt or an MCP elicitation waits on the user, or a turn ended on an error or a refusal. A main-loop turn that ends normally waits too, unless one of its Bash calls handed something in (nat slice complete, slice followups or plan propose), since the app shows each of those in its own place; an interrupted turn and a subagent's mark nothing. No prompt tells an agent to run either command: the mod alone marks the wait, and the next turn or prompt clears it. And they deliver what nat sends the session: from session.start, once a second, each file in the inbox NAT_INBOX names, in name order, is removed and then submitted with $.prompt.submit({ text, asUser: true }) — a turn of its own once idle, no composer involved. And they record a resume: a prompt the user typed (origin.kind composer or bridge) on a session with NAT_SLICE and NAT_PROJECT set runs nat slice resume with the prompt on stdin before it goes on. And they hand the session its brief: prompt.submit attaches the file NAT_BRIEF names to the conversation's opening prompt (no turn before it) as context wrapped in <natBrief> tags, which the model reads and the pane never draws; nat starts the session on one opening line pointing at it. prompt.context appends it as a natBrief block to the context blocks a compaction or /clear computes afresh, passing over the opening prompt's own. Not prompt.context alone: on a Team or Enterprise plan, or with managed settings, Claude Code's own guard sec-default@builtin sits ahead of every user mod and its prompt.context hook skips the user tier, so the brief never arrived; it leaves prompt.submit to a person's mods. Checked live on 2.1.296: hidden in the pane and under ctrl+o, briefed once, re-read from the file on /compact, kept as recorded (not re-read) on claude --resume. Behind the guard, a compaction keeps only what its summary says of it. A session whose mod never loads (an older Claude Code) has the opening line alone and asks what to work. And they report the account's rate limits: session.measure writes the five-hour and seven-day windows to the file NAT_USAGE names (temp file, then mv), which nat usage answers from while any agent is live. And they record the session for a relaunch to resume: session.start writes the session id, its directory and its start time to the file NAT_SESSION_RECORD names (temp file, then mv).types/index.d.ts — the $.state contract: the wait last written, so a hot reload neither forgets it nor writes the flag again.tests/ — claude plugin test suites.Check it with ./scripts/mod-check.sh from the repository root (claude plugin validate --strict and claude plugin test; claude on PATH, no sign-in or network). Write against the public mods reference (https://code.claude.com/docs/en/plugins/mods/reference) and the declarations the installed build lays beside a loaded mod (.claude-plugin/types/claude-code/index.d.ts, gitignored with the tsconfig.json beside it), never one build's quirks.
The contract — how nat embeds, writes and loads this folder — is docs/design/embedded-mod/README.md.
hooks/register.ts 410 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PromptSubmitInput, Register, SessionRateLimit, StateDollar } from 'claude-code'
3
4import type { Wait } from '../types'
5
6type Engine = StateDollar & Pick<EngineInterface, 'process' | 'ui'>
7type InboxEngine = Pick<EngineInterface, 'clock' | 'fs' | 'process' | 'prompt' | 'ui'>
8type ResumeEngine = Pick<EngineInterface, 'env' | 'process' | 'ui'>
9type RecordEngine = Pick<EngineInterface, 'clock' | 'env' | 'fs' | 'process' | 'session' | 'ui'>
10
11// What the mod last wrote on the pane, held by the host so a hot reload (a
12// fresh module) neither forgets a wait it marked nor writes the flag again.
13const wait = atom({ plugin: 'nat-embedded', key: 'wait' } as const, null)
14
15// Whether the main agent's current turn has handed something in, held by the
16// host for the same reason.
17const handedIn = atom({ plugin: 'nat-embedded', key: 'handedIn' } as const, false)
18
19// A Bash command that hands something in: a hand-back or blocked note, a batch
20// of follow-ups, a proposed plan. The app shows the user each of those in its
21// own place, so a turn that ran one is no wait. Matched as `nat` (or a path
22// ending in it) at the start of a command, `--project` and the rest after.
23const handIn = /(?:^|[\s;&|(/])nat\s+(?:slice\s+(?:complete|followups)|plan\s+propose)(?:\s|$)/m
24
25type HandInEngine = StateDollar & Pick<EngineInterface, 'ui'>
26
27// Notes, for the turn under way, whether a main-loop Bash call ran a hand-in.
28// A failure is logged: the turn then reads as nothing handed in, a wait.
29async function noteHandIn($: HandInEngine, value: boolean): Promise<void> {
30 try {
31 await update($, handedIn, () => value)
32 } catch (err) {
33 $.ui.log(`hand-in not noted: ${String(err)}`, { to: 'debug' })
34 }
35}
36
37// Whether the turn under way handed something in; one that cannot be read
38// is logged and reads as not, so the user is asked to look rather than not.
39async function handedInThisTurn($: HandInEngine): Promise<boolean> {
40 try {
41 return await read($, handedIn)
42 } catch (err) {
43 $.ui.log(`hand-in not read: ${String(err)}`, { to: 'debug' })
44 return false
45 }
46}
47
48// Sets the pane's waiting flag to `to` — what the agent's own `nat
49// agent waiting` / `nat agent working` set — only where it changes; a wait
50// for one thing becoming a wait for another rewrites nothing. `from` limits a
51// clear to the waits it names. The session carries nat's PATH and the pane's
52// TMUX_PANE, which is how the command finds the pane. Nothing here throws: a
53// failure goes to the debug log, never the transcript, and never costs the
54// hook calling it — the flag is a hint, not the work.
55async function mark($: Engine, to: Wait | null, from?: readonly Wait[]): Promise<void> {
56 try {
57 let was: Wait | null = null
58 const now = await update($, wait, value => {
59 was = value
60 return to !== null || !from || (value !== null && from.includes(value)) ? to : value
61 })
62 if ((was === null) === (now === null)) return
63 const command = now === null ? 'working' : 'waiting'
64 const { exitCode, stderr } = await $.process.run(['nat', 'agent', command], { timeoutMs: 10_000 })
65 if (exitCode !== 0) $.ui.log(`nat agent ${command} exited ${exitCode}: ${stderr.trim()}`, { to: 'debug' })
66 } catch (err) {
67 $.ui.log(`waiting flag (${to ?? 'working'}) not written: ${String(err)}`, { to: 'debug' })
68 }
69}
70
71// One prompt nat sent, as `nat agent send` (and every other sender) names it:
72// the send's Unix time in nanoseconds, so name order is send order. A temp
73// file still being written has another name and is never read.
74const inboxFile = /^\d+\.md$/
75
76// Delivers what nat left in this session's inbox (`NAT_INBOX`, set by nat on
77// the launch) as the user's own prompts, each a turn of its own once the
78// session is idle — no composer, so no dialog, permission prompt or draft in
79// the pane can take it. Each file is removed before it is submitted, and only
80// a removal that worked submits: a file nat took back after giving up on the
81// mod (and pasted instead) is never sent twice. `busy` keeps a tick from
82// starting while the last is still at it; a reload starts both afresh.
83// Failures go to the debug log; the next tick tries again.
84function pollInbox($: InboxEngine, dir: string): void {
85 let busy = false
86 $.clock.every(1000, async () => {
87 if (busy) return
88 busy = true
89 try {
90 if (!(await $.fs.exists(dir))) return
91 const names = (await $.fs.list(dir))
92 .filter(entry => entry.kind === 'file' && inboxFile.test(entry.name))
93 .map(entry => entry.name)
94 .sort()
95 for (const name of names) {
96 const path = `${dir}/${name}`
97 const text = await $.fs.read(path)
98 const { exitCode } = await $.process.run(['rm', path], { timeoutMs: 10_000 })
99 if (exitCode !== 0) continue
100 // Resolves once the turn starts: not awaited, so the next file is not
101 // held behind a running turn.
102 void $.prompt.submit({ text, asUser: true })
103 }
104 } catch (err) {
105 $.ui.log(`agent inbox not read: ${String(err)}`, { to: 'debug' })
106 } finally {
107 busy = false
108 }
109 })
110}
111
112// Records this Claude Code session in the file nat named (`NAT_SESSION_RECORD`,
113// set on every launch), so a relaunch after the session has gone can resume
114// its transcript (`claude --resume`) rather than brief a fresh one. Written
115// under a temp name and moved into place, as nat's own writers do, so nat
116// never reads half a record. A resume or a `/clear` starts the session again
117// and rewrites it. Nothing here throws: a record not written is a relaunch
118// that starts fresh.
119async function record($: RecordEngine, cwd: string): Promise<void> {
120 try {
121 const path = await $.env.get('NAT_SESSION_RECORD')
122 if (!path) return
123 const text = JSON.stringify({
124 session_id: await $.session.id(),
125 cwd,
126 started_at: new Date(await $.clock.now()).toISOString(),
127 })
128 const tmp = `${path}.tmp`
129 await $.fs.write(tmp, text)
130 const { exitCode, stderr } = await $.process.run(['mv', tmp, path], { timeoutMs: 10_000 })
131 if (exitCode !== 0) $.ui.log(`session record not moved into place: ${stderr.trim()}`, { to: 'debug' })
132 } catch (err) {
133 $.ui.log(`session record not written: ${String(err)}`, { to: 'debug' })
134 }
135}
136
137// The origins of a prompt the user wrote themselves: Enter in the pane (gnat's
138// typing reaches it so) or a message through Remote Control. Every other
139// origin — nat's own sends through the inbox (a plugin's), a background
140// task's notification, a schedule, a peer — is not the user asking for more.
141const typed: ReadonlySet<string> = new Set(['composer', 'bridge'])
142
143// Puts a prompt the user typed at a slice's agent on the record as
144// `nat slice resume`, the prompt its note, before the agent reads it — what
145// every nat send does itself before it sends. `slice resume` writes nothing
146// where the slice is not handed back, so every typed prompt runs it; where it
147// is, the slice's board card reads as work in progress again. `NAT_SLICE` and
148// `NAT_PROJECT` are set by nat on a slice's launch alone. Nothing here throws:
149// a failure goes to the debug log, never the transcript, and never holds the
150// prompt.
151async function resume($: ResumeEngine, text: string): Promise<void> {
152 try {
153 const slice = await $.env.get('NAT_SLICE')
154 const project = await $.env.get('NAT_PROJECT')
155 if (!slice || !project) return
156 const { exitCode, stderr } = await $.process.run(
157 ['nat', 'slice', 'resume', slice, '--project', project, '--note', '-'],
158 { stdin: text, timeoutMs: 30_000 },
159 )
160 if (exitCode !== 0) $.ui.log(`nat slice resume exited ${exitCode}: ${stderr.trim()}`, { to: 'debug' })
161 } catch (err) {
162 $.ui.log(`resume not recorded: ${String(err)}`, { to: 'debug' })
163 }
164}
165
166type BriefEngine = Pick<EngineInterface, 'env' | 'fs' | 'session' | 'ui'>
167
168// The session's brief, from the file nat leaves it in (`NAT_BRIEF`) rather
169// than argv; null for a session nat gave none. One that cannot be read is
170// logged and is null too — the agent then has the opening line alone and
171// asks, a visible failure.
172async function readBrief($: BriefEngine): Promise<string | null> {
173 const path = await $.env.get('NAT_BRIEF')
174 if (!path) return null
175 try {
176 return await $.fs.read(path)
177 } catch (err) {
178 $.ui.log(`agent brief not read: ${String(err)}`, { to: 'debug' })
179 return null
180 }
181}
182
183// The brief rides the conversation's opening prompt as context, wrapped as
184// the `natBrief` block the opening line points at: the model reads it and the
185// pane never draws it. It goes with the prompt, not as a `prompt.context`
186// block alone: on a Team or Enterprise plan, or a machine with managed
187// settings, Claude Code seats its own guard (`sec-default@builtin`) ahead of
188// every user mod, and its `prompt.context` hook passes straight past the user
189// tier a `--plugin-dir` mod sits in, while `prompt.submit` and the context it
190// attaches are left to a person's mods.
191//
192// Only a prompt the conversation has no turn before is briefed: the opening
193// line, which arrives as `composer` like a typed prompt, so its origin cannot
194// tell it apart. A `claude --resume` (which nat starts with a prompt and
195// `NAT_BRIEF` set) already carries the brief in its transcript and is not
196// briefed twice; the count is the engine's, so a hot reload changes nothing.
197// A count that cannot be read is logged and briefs nothing.
198async function briefed($: BriefEngine, e: PromptSubmitInput): Promise<PromptSubmitInput> {
199 if (!(await $.env.get('NAT_BRIEF'))) return e
200 if ((await turns($)) !== 0) return e
201 const text = await readBrief($)
202 if (text === null) return e
203 return { ...e, context: [...(e.context ?? []), `<natBrief>\n${text}\n</natBrief>`] }
204}
205
206// How many prompts the conversation has had; null, logged, where the engine
207// cannot say.
208async function turns($: BriefEngine): Promise<number | null> {
209 try {
210 return await $.session.turns()
211 } catch (err) {
212 $.ui.log(`turns not read for the agent brief: ${String(err)}`, { to: 'debug' })
213 return null
214 }
215}
216
217// The rate-limit windows `nat usage` reads, by the name the statusline payload
218// gives them; any other kind (a gateway's spend limit) is not one it shows.
219const windows: ReadonlySet<string> = new Set(['five_hour', 'seven_day'])
220
221type UsageEngine = Pick<EngineInterface, 'clock' | 'env' | 'fs' | 'process' | 'ui'>
222
223// Writes the account's rate-limit windows, as this session last measured them,
224// to the file nat named at launch (`NAT_USAGE`), for `nat usage` to answer
225// from while any agent is live instead of starting a session of its own. Each
226// window is written only where the measurement carries it, and a measurement
227// carrying none (off a subscription, or before the first reading) writes
228// nothing. `$.fs.write` is not atomic, so the file goes through a temp name
229// and an `mv`, as the statusline tee does: nat never reads half of one.
230// Nothing here throws: a failure goes to the debug log.
231async function writeUsage($: UsageEngine, rateLimits: readonly SessionRateLimit[]): Promise<void> {
232 try {
233 const path = await $.env.get('NAT_USAGE')
234 if (!path) return
235 const limits: Record<string, { used_percentage: number; resets_at?: string }> = {}
236 for (const limit of rateLimits) {
237 if (!windows.has(limit.kind)) continue
238 limits[limit.kind] = { used_percentage: limit.percentUsed, ...(limit.resetsAt ? { resets_at: limit.resetsAt } : {}) }
239 }
240 if (Object.keys(limits).length === 0) return
241 const readAt = new Date(await $.clock.now()).toISOString()
242 const tmp = `${path}.tmp`
243 await $.fs.write(tmp, JSON.stringify({ read_at: readAt, rate_limits: limits }))
244 const { exitCode, stderr } = await $.process.run(['mv', tmp, path], { timeoutMs: 10_000 })
245 if (exitCode !== 0) $.ui.log(`usage file not moved into place: mv exited ${exitCode}: ${stderr.trim()}`, { to: 'debug' })
246 } catch (err) {
247 $.ui.log(`usage file not written: ${String(err)}`, { to: 'debug' })
248 }
249}
250
251// nat's hooks into the Claude Code sessions it launches. Written against the
252// public mods reference and the declarations the installed build writes beside
253// a loaded mod; a hook that fails is skipped and a tree that does not validate
254// is replaced by Claude Code's own drawing, so a drift costs a feature, never
255// a session.
256//
257// An agent's pane in gnat is a viewport onto the agent, not a terminal the
258// user is learning key by key, so the chrome that teaches or decorates is
259// quieted. Each hook rewrites the engine's own props rather than drawing a
260// tree of its own, so Claude Code keeps drawing everything it knows; the
261// mode labels (`SessionMode`) are information and are left alone.
262export const register: Register = on => {
263 // Prompts nat sends this session arrive through its inbox; a session nat
264 // launched with none (an older tmux) is sent them by a paste instead. The
265 // session is recorded for a later relaunch to resume.
266 on('session.start', async ($, e, next) => {
267 const dir = await $.env.get('NAT_INBOX')
268 if (dir) pollInbox($, dir)
269 await record($, e.cwd)
270 return next(e)
271 })
272
273 // Where nothing seated ahead of the mod skips it, the brief also rides the
274 // context blocks the engine computes for a conversation's first user
275 // message beside CLAUDE.md's, which the next request after a compaction or
276 // a `/clear` computes afresh — the brief a summary would otherwise leave
277 // behind. The opening prompt's own blocks, computed with no turn yet and
278 // just after it was briefed, are passed over; a count that cannot be read
279 // briefs the blocks, so the model reads it twice rather than not at all.
280 on('prompt.context', async ($, e, next) => {
281 if ((await turns($)) === 0) return next(e)
282 const text = await readBrief($)
283 if (text === null) return next(e)
284 return next({ ...e, blocks: [...e.blocks, { name: 'natBrief', text }] })
285 })
286
287 // After each turn, and whenever a window moves a whole point, the account's
288 // rate limits go where `nat usage` reads them.
289 on('session.measure', async ($, e, next) => {
290 await writeUsage($, e.rateLimits)
291 return next(e)
292 })
293
294 // The dim `? for shortcuts` / `esc to interrupt` line under the prompt
295 // draws empty. It is also the one visible mark that a session loaded this
296 // mod.
297 on('ui.render', { component: 'PromptHint' }, ($, e, next) =>
298 next({ ...e, props: { ...e.props, hint: '' } }),
299 )
300
301 // The `Baked for 3s` line closing each turn draws nothing.
302 on('ui.render', { component: 'TurnDuration' }, ($, e) => {
303 const { Box } = $.ui.resolve(e)
304 return h(Box, {})
305 })
306
307 // The dim notices under the logo (model source, experiment enrolment,
308 // settings hint) draw nothing.
309 on('ui.render', { component: 'InfoNotice' }, ($, e) => {
310 const { Box } = $.ui.resolve(e)
311 return h(Box, {})
312 })
313
314 // The `(ctrl+b to run in background)` pill under a tool call draws
315 // nothing: the user does not drive the agent's pane by key.
316 on('ui.render', { component: 'ToolProgress', props: { kind: 'background_hint' } }, ($, e, next) =>
317 next({ ...e, props: { ...e.props, hint: '' } }),
318 )
319
320 // The spinner says `Working` in place of the sampled flavour word; the
321 // message, suffix and mode stay the engine's, and so do the elapsed time
322 // and token count drawn after them.
323 on('ui.render', { component: 'Spinner' }, ($, e, next) =>
324 next({ ...e, props: { ...e.props, word: 'Working' } }),
325 )
326
327 // The waiting flag gnat's star, dock badge and Active rail read, set and
328 // cleared at the moments the engine itself knows are a wait on the user. No
329 // prompt tells the agent to run `nat agent waiting` itself: once a turn
330 // ends the agent does nothing until someone types, so a main-loop turn that
331 // ends normally with nothing handed in is a wait — a question in prose, or
332 // the agent stopped short. An `idle_prompt` notification marks nothing.
333 on('turn.start', async ($, e, next) => {
334 await noteHandIn($, false)
335 await mark($, null)
336 return next(e)
337 })
338
339 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
340 if (!e.agentId && handIn.test(e.command)) await noteHandIn($, true)
341 return next(e)
342 })
343
344 // A prompt also puts a typed one on the record as a resume, and the
345 // conversation's opening one carries the brief.
346 on('prompt.submit', async ($, e, next) => {
347 await mark($, null)
348 if (typed.has(e.origin.kind)) await resume($, e.text)
349 return next(await briefed($, e))
350 })
351
352 // An AskUserQuestion dialog waits from before it is drawn until it is
353 // answered, however it ends.
354 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
355 await mark($, 'ask')
356 try {
357 return await next(e)
358 } finally {
359 await mark($, null, ['ask'])
360 }
361 })
362
363 // A permission prompt is over once a tool call settles or the model is
364 // asked again.
365 on('tool.call', async ($, e, next) => {
366 try {
367 return await next(e)
368 } finally {
369 await mark($, null, ['permission'])
370 }
371 })
372
373 on('turn.step', async function* ($, e, next) {
374 await mark($, null, ['permission'])
375 return yield* next(e)
376 })
377
378 // A permission dialog is shown only where nothing beneath decided it.
379 on('classic.PermissionRequest', async ($, e, next) => {
380 const decided = await next(e)
381 if (!decided.decision) await mark($, 'permission')
382 return decided
383 })
384
385 on('classic.Notification', async ($, e, next) => {
386 if (e.notification_type === 'permission_prompt') await mark($, 'permission')
387 return next(e)
388 })
389
390 on('classic.Elicitation', async ($, e, next) => {
391 await mark($, 'elicitation')
392 return next(e)
393 })
394
395 on('classic.ElicitationResult', async ($, e, next) => {
396 await mark($, null, ['elicitation'])
397 return next(e)
398 })
399
400 // A main-loop turn that died on an API error or a refusal leaves the agent
401 // stuck until the user steps in; one that answered waits unless it handed
402 // something in. An interrupted turn marks nothing (the user is at the
403 // pane), and a subagent's is its spawner's to handle.
404 on('turn.complete', async ($, e, next) => {
405 if (!e.agentId && (e.reason === 'error' || e.reason === 'refusal')) await mark($, 'stuck')
406 else if (!e.agentId && e.reason === 'answer' && !(await handedInThisTurn($))) await mark($, 'idle')
407 return next(e)
408 })
409}
410types/index.d.ts 14 lines1// What the agent is waiting on the user for, as the engine itself knows it:
2// an AskUserQuestion dialog, a permission prompt, an MCP elicitation, a turn
3// that ended stuck (an API error, a refusal), or a turn that ended with
4// nothing handed in (`idle`) — a question in prose, or the agent stopped short.
5export type Wait = 'ask' | 'permission' | 'elicitation' | 'stuck' | 'idle'
6
7declare module 'claude-code' {
8 interface PluginState {
9 // `wait` is the flag the mod last wrote on the pane: null for working.
10 // `handedIn` is whether the main agent's current turn has run a hand-in.
11 'nat-embedded': { wait: Wait | null; handedIn: boolean }
12 }
13}
14