spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / mods / types / claude-code.d.ts
13,186 lines · 495.6 KBRaw
1// Written by Claude Code 2.1.277.
2// Claude Code function hooks: the plugin API's TypeScript declarations.
3//
4// EARLY ACCESS: this surface may change between releases without notice.
5// Written by `/plugin-types`; regenerate with that command after an update
6// rather than editing. The first line names the Claude Code version that
7// wrote it. TypeScript 5.4 or newer reads it. `claude plugin validate <dir>`
8// is the other half: it reads a plugin's manifest and its hooks module's
9// source the way the engine will and reports what the module hooks and
10// calls and everything the engine would refuse, before any session loads it.
11//
12// What is here: the module a hooks module may import types from,
13// import type { Register, On, EngineInterface } from 'claude-code'
14// (at run time the import is empty), and the globals a hooks module has:
15// `h` and `Fragment` (what JSX compiles against), the JSX namespace, and
16// the environment's web APIs (URL, TextEncoder, AbortController,
17// crypto.subtle, ...). A hooks module runs in an environment of its own:
18// no DOM, no Node. The module, and every file it imports from the plugin,
19// is named .ts, .tsx, .jsx, .js, .mjs, .cjs, .mts or .cts (a file named
20// otherwise is not loaded) and is an ES module whatever its suffix: there
21// is no `require`. The elements a render hook draws with (`Box`, `Text`,
22// `Button`, ...) are not globals: they come from the surface's table,
23// const { Box, Text } = $.ui.resolve(e)
24//
25// Also here: 'claude-code/testing', the kit a plugin's *.test.ts and
26// *.test.tsx files import under `claude plugin test <dir>`, which runs each
27// in an environment like the one a plugin's hooks run in (no fs, network or
28// process), the plugin loaded from the folder by the engine's own host:
29// `test(name, async ($, on) => { ... })`, where `$` is the engine's own
30// and the hooks `on` registers sit beneath every plugin; with describe,
31// expect, tier, and `mock`, whose clock, store and env answer those nouns
32// beneath the plugins from memory. `$.ui.mount` draws a component through
33// the plugin on the surface the test names (terminal, desktop, vscode or
34// mobile: never assumed) and hands back the drawing to read and act on by
35// key: find an element, press a Button, type into an Input, drive a
36// `Client`'s module (keys, pointer, posts, its frame clock), each act typed
37// by that surface's element table, so one test body run over several
38// surfaces covers the mod's hooks and description on each. It exercises
39// the mod (its hooks, the tree they return under each surface's rules, its
40// `Client` modules), never a surface's paint (Ink's, the desktop page's):
41//
42// test('notes add up on every surface that takes input', async $ => {
43// for (const surface of ['terminal', 'desktop'] as const) {
44// const ui = await $.ui.mount({ plugin: 'notes', surface, ...BAND })
45// await ui.input({ key: 'new', text: 'milk' })
46// expect((await ui.find({ key: 'count' }))?.text).toBe('1 note')
47// await ui.key({ key: 'down', in: 'list' })
48// await ui.unmount()
49// }
50// for (const surface of ['terminal', 'desktop', 'vscode', 'mobile'] as const) {
51// const ui = await $.ui.mount({ plugin: 'notes', surface, ...HINT })
52// expect(await ui.find({ type: 'Text', text: /notes/ })).toBeDefined()
53// await ui.press({ key: 'dismiss' })
54// }
55// })
56//
57// Typing a plugin against it:
58// export const register: Register = (on, options) => { ... }
59// or, in a .js module,
60// /** @type {import('claude-code').Register} */
61// export const register = (on, options) => { ... }
62//
63// A tsconfig.json (or jsconfig.json) that fits a hooks module:
64// {
65// "compilerOptions": {
66// "target": "es2023", "lib": ["es2023"], "types": [],
67// "module": "esnext", "moduleResolution": "bundler",
68// "strict": true, "noUncheckedIndexedAccess": true,
69// "noEmit": true, "skipLibCheck": true,
70// "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment"
71// },
72// "include": [".claude/types", "hooks", "tests"]
73// }
74// ".claude/types" is where /plugin-types writes this file and, beside it,
75// claude-code-mcp.d.ts and claude-code-plugins.d.ts, the index of the
76// enabled plugins' type contracts, each copied to claude-code-plugins/
77// <plugin>.d.ts: what a plugin adds to `$` in engine.create, so a plugin
78// you depend on is typed with nothing copied (the include above takes the
79// whole folder). "hooks" is the plugin's hooks/ folder and "tests" its test
80// files. `lib` names no DOM: the environment has none, and its `Text`
81// would shadow the element.
82//
83// A plugin that adds a noun to `$` ships its own contract: a .d.ts its
84// plugin.json names as "types", exporting the noun's types at its top level
85// and declaring the noun on the engine's interface,
86// export type Topo = { ... }
87// declare module 'claude-code' {
88// interface EngineInterface { topo: Topo }
89// }
90// with no import or reference, its exported names led by the noun's
91// PascalCase name; the plugin's own hooks module imports them from it.
92
93declare module 'claude-code' {
94 /**
95 * What an Agent call a plugin raised (`$.tool.call({ tool: "Agent", ... })`)
96 * answers as `result` once the agent settles; `text` is its final answer.
97 *
98 * A plugin's spawn always runs in the background, so the call resolves with
99 * this record and not the Agent tool's own (BuiltinToolResults), which is
100 * what a model's Agent call carries at `tool.call`.
101 */
102 export type AgentCallRecord = {
103 /**
104 * The spawned agent's id, as `$.agent.list()` names it.
105 */
106 agentId: string;
107 /**
108 * The model the agent resolved to, when one is known.
109 */
110 resolvedModel?: string;
111 };
112
113 /**
114 * One agent loop of this session as `$.agent.list()` returns it: a subagent
115 * or an in-process teammate.
116 */
117 export type AgentInfo = {
118 /**
119 * The agent's id: the same string its loop's `tool.call` events carry as
120 * `agentId`, and a spawn inside it as `parentAgentId`.
121 */
122 id: string;
123 /**
124 * Its row's label.
125 */
126 description: string;
127 /**
128 * The agent definition it runs as (`general-purpose`, `Explore`, ...), or
129 * `teammate` for an in-process teammate.
130 */
131 type: string;
132 /**
133 * `running`, `completed`, `failed`, `killed`, or another of the engine's task
134 * statuses.
135 */
136 status: string;
137 /**
138 * The id of the subagent whose loop spawned it; absent when the main loop
139 * did.
140 */
141 parentId?: string;
142 /**
143 * The plugin whose `$.agent.spawn` (or Agent `$.tool.call`) started it;
144 * absent when the model or the person did.
145 *
146 * The origin axis: which plugin caused it, whichever loop that hook ran in.
147 */
148 spawnedBy?: string;
149 /**
150 * What SendMessage addresses it by (`Agent({ name })`, or the engine's own
151 * for a background agent), when it has one; not `description` or `type`.
152 */
153 name?: string;
154 };
155
156 /**
157 * Which model loop an event happened in: the loop's agent id inside a
158 * subagent's or a teammate's loop, absent on the main loop.
159 *
160 * The agent axis, not the origin axis: `next.origin` names the plugin whose
161 * hook frame caused the dispatch (the recursion skip), whichever loop it ran
162 * in; `agentId` names the loop, whoever caused the call.
163 */
164 export type AgentLoop = {
165 /**
166 * The id of the loop this call runs in: for a subagent or a teammate, the
167 * `id` `$.agent.list()` gives it; absent on the main loop.
168 *
169 * A workflow's agents and the engine's own forks (compaction, memory) carry
170 * ids no list names. Pinned: a different value is refused, one left out is
171 * kept. Which loop, not which plugin caused it (that is `next.origin`).
172 */
173 agentId?: string;
174 };
175
176 /**
177 * The input of `agent.offer`: one agent type, at the moment the engine
178 * offers it to the model.
179 *
180 * Listed for the model (the agent listing) or named by it at dispatch
181 * (`subagent_type`): the same event at each. Model-facing only: a plugin's
182 * own `$.agent.spawn` of a type is no offer, and `agent.spawn` governs it.
183 */
184 export type AgentOfferInput = {
185 /**
186 * Which type (`Explore`, `Plan`, a plugin's agent); the key a matcher
187 * narrows on.
188 */
189 agent: string;
190 /**
191 * Its listing line's text as the definition states it (`whenToUse`).
192 */
193 description: string;
194 /**
195 * Where the definition came from (`built-in`, `plugin`, a settings
196 * source), so a matcher tells a built-in from a user's agent of its name.
197 */
198 source: string;
199 /**
200 * Who provides this agent: the plugin and its tier; `{ plugin: "engine",
201 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
202 */
203 provider: Origin;
204 };
205
206 /**
207 * What an `agent.offer` hook returns: whether the model is offered the agent
208 * type, in its listing and at dispatch.
209 */
210 export type AgentOfferResult = {
211 isOffered: boolean;
212 };
213
214 /**
215 * `agent.spawn`'s input as the call takes it: what the Agent tool's caller
216 * says; the engine fills the rest.
217 *
218 * A call's spawn runs in the background: it resolves once the subagent
219 * started, and nothing holds it in the foreground.
220 */
221 export type AgentSpawnArgs = Pick<AgentSpawnInput, 'prompt'> & Partial<Pick<AgentSpawnInput, 'description' | 'subagentType' | 'model' | 'name' | 'cwd'>>;
222
223 /**
224 * The input of `agent.spawn`: what the Agent tool decided about the
225 * subagent it is about to start, before its model is resolved.
226 *
227 * A hook rewrites content (prompt, description, subagentType, model,
228 * background, cwd), read back as the tool's parameters; tool_use_id, name,
229 * fork, parentModel, permissionMode, parentAgentId and provider are pinned.
230 */
231 export type AgentSpawnInput = {
232 /**
233 * The Agent tool call this spawn belongs to (for `$.ui.notice`). Pinned:
234 * the spawn's identity.
235 */
236 tool_use_id: string;
237 /**
238 * The task the subagent is given: the Agent tool's `prompt` parameter. A
239 * rewrite is the prompt the subagent runs with.
240 */
241 prompt: string;
242 /**
243 * The Agent tool's short `description` of the task (a few words). A rewrite
244 * is what the task shows as.
245 */
246 description: string;
247 /**
248 * The resolved agent type (`general-purpose`, `Explore`, a plugin's agent,
249 * `fork`). A rewrite names another agent this call can dispatch, exactly.
250 *
251 * That definition is the one spawned; a name matching none refuses the
252 * spawn, and a fork dispatches no other.
253 */
254 subagentType: string;
255 /**
256 * Who provides this agent: the plugin and its tier; `{ plugin: "engine",
257 * tier: "core" }` for a built-in. Pinned with the spawn's identity.
258 */
259 provider: Origin;
260 /**
261 * The Agent tool's `model` parameter as given, an alias (`haiku`) or a
262 * full id; undefined lets the agent's own model, then the parent's, decide.
263 *
264 * Ignored for forks, which always inherit. A hook sets this to pick the
265 * subagent's model.
266 */
267 model?: string;
268 /**
269 * The parent's effective model, what `inherit` resolves to. Pinned: a fact
270 * of the parent (set `model` to change what the subagent runs on).
271 */
272 parentModel: string;
273 /**
274 * The id of the loop the spawn happens in (its `tool.call` `agentId`; for a
275 * subagent or teammate its `$.agent.list()` id); absent from main.
276 *
277 * Pinned: a different value is refused, one left out is kept. The agent
278 * axis, not the origin: `next.origin` names the plugin whose hook frame
279 * caused the spawn, this names the model loop it happened in.
280 */
281 parentAgentId?: string;
282 /**
283 * The parent's permission mode (`default`, `acceptEdits`, `plan`, ...), which
284 * the subagent inherits. Pinned: a fact of the parent.
285 */
286 permissionMode?: string;
287 /**
288 * True when the subagent will run in the background (or remotely). A
289 * rewrite is read back as the call's `run_in_background`.
290 *
291 * The agent's own definition and remote isolation can still force it on,
292 * and disabled background tasks force it off.
293 */
294 background: boolean;
295 /**
296 * True for a fork of the parent: it inherits the parent's context and model,
297 * and `model` is ignored. Pinned: the spawn's identity.
298 */
299 fork: boolean;
300 /**
301 * Given by the call (`Agent({ name })`, addressable by SendMessage);
302 * undefined when unnamed. Pinned: the address the parent routes by.
303 */
304 name?: string;
305 /**
306 * The directory the subagent runs in when the call set one (`cwd`); undefined
307 * means the parent's. A rewrite is where the subagent runs.
308 */
309 cwd?: string;
310 };
311
312 /**
313 * What an `agent.spawn` hook returns and what `next(e)` resolves to: the
314 * started subagent's `{ model, agentId }`, or `{ deny: reason }`, refusing it.
315 *
316 * It and `$.agent.spawn(input)` resolve once the subagent started; its answer
317 * is its own `turn.complete`, carrying this `agentId`. Keep the id and set
318 * `got[agentId]` to what waits; a `turn.complete` hook resolves it:
319 *
320 * @example
321 * on("turn.complete", ($, e, next) => (got[e.agentId]?.(e.answer), next(e)))
322 */
323 export type AgentSpawnResult = {
324 /**
325 * What the subagent runs on: from core the resolved id; from a hook an
326 * alias (`haiku`) or an id.
327 */
328 model: string;
329 /**
330 * The started subagent's id: the same string its loop's `tool.call`
331 * events carry as `agentId` and `$.agent.list()` lists it by.
332 *
333 * Set by core; a hook that answers without `next` started none.
334 */
335 agentId?: string;
336 deny?: undefined;
337 } | {
338 /**
339 * Refuses the spawn, so nothing starts; the model sees the text as the
340 * Agent tool's error.
341 */
342 deny: string;
343 model?: undefined;
344 agentId?: undefined;
345 };
346
347 /**
348 * What `$.agent.register` takes: an agent type this plugin defines, spelled
349 * as an agent definition in settings JSON is, plus its `name`.
350 *
351 * Every field an agent file or `--agents` entry may carry is here and takes
352 * effect as it does there; the engine validates it with the same schema.
353 */
354 type AgentSpec = {
355 /**
356 * The type's short name (letters, digits, `_`, `-`; up to 64); the type is
357 * `<plugin>:<name>`, as a plugin's agent file `agents/<name>.md` names one.
358 */
359 name: string;
360 /**
361 * When to delegate to this agent: the line the model reads in its listing
362 * of agent types, and `agent.offer`'s `description`.
363 */
364 description: string;
365 /**
366 * The agent's system prompt, whole: it replaces the session's.
367 */
368 prompt: string;
369 /**
370 * What the agent may call, by tool name (`Read`, `Bash`, `mcp__x__y`); a
371 * call to any other is refused. Left out: every tool the parent has.
372 */
373 tools?: readonly string[];
374 /**
375 * Tools withheld from the agent, by name, out of whatever `tools` allows.
376 */
377 disallowedTools?: readonly string[];
378 /**
379 * The agent's model: an alias (`haiku`, `sonnet`, `opus`), a full id, or
380 * `inherit` for the parent's. Left out: the session's subagent default.
381 */
382 model?: string;
383 /**
384 * The agent's effort: a level (`low`, `medium`, `high`, `xhigh`, `max`)
385 * or an integer budget.
386 */
387 effort?: string | number;
388 /**
389 * How the agent's permission asks are decided, a mode: `default`,
390 * `acceptEdits`, `plan`, `auto`, `dontAsk` or `bypassPermissions`.
391 *
392 * Left out: the parent's.
393 */
394 permissionMode?: string;
395 /**
396 * Servers connected over MCP for the agent's run: a configured server's
397 * name, or `{ "<name>": { command, args } }`, one server's config inline.
398 */
399 mcpServers?: readonly (string | Record<string, unknown>)[];
400 /**
401 * Settings hooks in force while the agent runs, in settings.json's `hooks`
402 * shape (`{ PreToolUse: [{ matcher, hooks: [...] }] }`).
403 */
404 hooks?: Record<string, unknown>;
405 /**
406 * The most turns the agent takes before it stops.
407 */
408 maxTurns?: number;
409 /**
410 * Preloaded into the agent's context before its first turn: skill names.
411 */
412 skills?: readonly string[];
413 /**
414 * The agent's first user turn; `{{intent}}` in it takes the spawn's prompt.
415 * Left out: the spawn's prompt is the first turn.
416 */
417 initialPrompt?: string;
418 /**
419 * A persistent memory the agent keeps between runs, and where: `user`,
420 * `project` or `local`.
421 */
422 memory?: 'user' | 'project' | 'local';
423 /**
424 * Set so that every spawn of the agent runs in the background.
425 */
426 background?: true;
427 /**
428 * Set so that the agent's context carries no CLAUDE.md block (the person's,
429 * the project's, the rules): it takes what it needs from its prompt.
430 */
431 omitClaudeMd?: true;
432 /**
433 * Where the agent runs apart from the session: `worktree`, a git worktree
434 * of its own; `remote`, a cloud session where the build allows one.
435 */
436 isolation?: 'worktree' | 'remote';
437 };
438
439 /**
440 * The hook `on("*", hook)` takes: it runs on every event, plugin nouns no
441 * declaration names included, so `e` is `unknown` and `next` is StarNext.
442 *
443 * Until `next.is(pattern, e)` narrows `e`, all a hook can do with it is pass
444 * it on, time it, log it, or fail it; once narrowed it is an ordinary hook on
445 * those events.
446 *
447 * @param $ the engine interface; at `engine.create` the empty table, so a hook
448 * that reads `$` tests `next.is("engine.create", e)` first
449 */
450 export type AnyEventHook = ($: EngineInterface, e: unknown, next: StarNext) => unknown;
451
452 /**
453 * Every key of every variant, index signatures included.
454 */
455 type AnyKeyOf<I> = I extends unknown ? keyof I : never;
456
457 /**
458 * The argument of event `N`: `e` in its hooks, and what its call takes. For a
459 * union of names, the union of their arguments.
460 */
461 export type Args<N extends EventName = EventName> = EventOf[N];
462
463 /**
464 * Options of `$.ui.ask`.
465 */
466 export type AskOptions = {
467 /**
468 * 2-4 option labels; fewer than two are padded with Yes/No; free text is the
469 * dialog's Other.
470 */
471 options?: readonly string[];
472 /**
473 * A short chip beside the question (`Approach`, 12 characters at most).
474 */
475 header?: string;
476 /**
477 * Allow several options; the answer comes back comma-joined.
478 */
479 multiSelect?: true;
480 };
481
482 /**
483 * The input of `attribution.text`: one text the engine asks the model to
484 * write into a commit or a pull request, at the moment it is composed.
485 *
486 * Composed for the Bash description, the commit skills, a PR's body, the
487 * pre-ship mandate and the commit gate's deny: the same event at each.
488 */
489 export type AttributionTextInput = {
490 /**
491 * Which text (`commit`, `pr`, `exemption`, `remedy`); the key a matcher
492 * narrows on.
493 */
494 kind: AttributionTextKind;
495 /**
496 * As the engine composed it, the settings applied.
497 */
498 text: string;
499 };
500
501 /**
502 * Which git text `attribution.text` carries: the commit trailer, the PR
503 * footer, the mandate's or the commit gate's sentence naming the exemption.
504 */
505 export type AttributionTextKind = 'commit' | 'pr' | 'exemption' | 'remedy';
506
507 /**
508 * What an `attribution.text` hook returns: the text the model reads in
509 * that place.
510 */
511 export type AttributionTextResult = {
512 text: string;
513 };
514
515 /**
516 * What `$.audio.play` plays: a URL the engine fetches, or the bytes.
517 */
518 export type AudioClip = {
519 /**
520 * A file of the calling plugin's own, relative to the plugin's
521 * directory (`fx/open.wav`); no `.`, no leading slash.
522 *
523 * The engine resolves it and loads the file from disk.
524 */
525 asset: string;
526 url?: undefined;
527 base64?: undefined;
528 mime?: undefined;
529 } | {
530 /**
531 * The clip's URL; the engine fetches it (never the plugin).
532 */
533 url: string;
534 asset?: undefined;
535 base64?: undefined;
536 mime?: undefined;
537 } | {
538 /**
539 * The clip's bytes, base64.
540 */
541 base64: string;
542 /**
543 * What the bytes are (`audio/mpeg`, `audio/wav`).
544 */
545 mime: string;
546 asset?: undefined;
547 url?: undefined;
548 };
549
550 type BackgroundTaskSummary = {
551 id: string;
552 /**
553 * Friendly task-type label (e.g. 'shell', 'subagent', 'monitor', 'workflow'). Falls back to the raw discriminant for unknown types.
554 */
555 type: string;
556 status: string;
557 /**
558 * Free-text description. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
559 */
560 description: string;
561 /**
562 * Shell command line. Only present for 'shell' tasks. Capped at 1000 chars with the same "... [+N chars]" marker.
563 */
564 command?: string;
565 /**
566 * Subagent type name. Only present for 'subagent' tasks.
567 */
568 agent_type?: string;
569 /**
570 * MCP server name. Only present for 'monitor' / 'MCP task' tasks.
571 */
572 server?: string;
573 /**
574 * MCP tool name. Only present for 'monitor' / 'MCP task' tasks.
575 */
576 tool?: string;
577 /**
578 * Workflow name. Only present for 'workflow' tasks.
579 */
580 name?: string;
581 };
582
583 type BaseHookInput = {
584 session_id: string;
585 transcript_path: string;
586 cwd: string;
587 /**
588 * UUID correlating a user prompt with all subsequent events until the next prompt. Same value emitted on OpenTelemetry events as the `prompt.id` attribute, so hook output can be joined to OTel events at prompt grain. Absent until the first user input of the process lifetime.
589 */
590 prompt_id?: string;
591 permission_mode?: string;
592 /**
593 * Subagent identifier. Present only when the hook fires from within a subagent (e.g., a tool called by an AgentTool worker). Absent for the main thread, even in --agent sessions. Use this field (not agent_type) to distinguish subagent calls from main-thread calls.
594 */
595 agent_id?: string;
596 /**
597 * Agent type name (e.g., "general-purpose", "code-reviewer"). Present when the hook fires from within a subagent (alongside agent_id), or on the main thread of a session started with --agent (without agent_id).
598 */
599 agent_type?: string;
600 /**
601 * Reasoning effort applied to the current turn. Same shape as StatusLineCommandInput.effort. Present for hooks that fire within a tool-use context (PreToolUse, PostToolUse, Stop, SubagentStop, etc.) on a model that supports the effort parameter; absent for session-lifecycle hooks and models without effort support.
602 */
603 effort?: {
604 /**
605 * Active effort level for the current turn (e.g., "low", "medium", "high", "xhigh", "max"), after any silent downgrade for the selected model. Also exposed to hook commands and Bash as the CLAUDE_EFFORT env var.
606 */
607 level: string;
608 };
609 };
610
611 /**
612 * The `Box` props a `hover` may override, none of which moves the Box's
613 * siblings, and `scope`, which names the hover group the Box joins.
614 *
615 * `display` is `"flex"` alone, on a Box drawn `display: "none"`: with a
616 * `scope`, every member of the lit group is revealed, in whichever site it
617 * sits, so a pointer on a glyph in the transcript can swap an entry into a
618 * fixed row of the band, or reveal an absolutely positioned card.
619 * `borderStyle` only restyles a border the Box has; the offsets move a Box
620 * drawn `position: "absolute"`, none in the flow. The surface applies a
621 * hover as the pointer moves, so a reveal that moves what the pointer rests
622 * on is drawn once, not in a loop.
623 */
624 export type BoxHoverProps = {
625 /**
626 * Names a hover group of this plugin's: every element it draws with the
627 * same `scope`, in any site, lights while any is hovered, reveals included.
628 *
629 * A Pane row and a mark on a transcript message can share one. Another
630 * plugin's elements under the same string are a different group. One to
631 * 64 characters, no control characters; no keyed Box needed; no hook runs.
632 */
633 scope?: string;
634 borderStyle?: string;
635 borderColor?: string;
636 borderDimColor?: boolean;
637 backgroundColor?: string;
638 display?: 'flex';
639 top?: number;
640 left?: number;
641 right?: number;
642 bottom?: number;
643 };
644
645 /**
646 * The props of `Box`: the layout, position, margin, padding and border props
647 * of Ink's Box a tree may set, and the two of hover.
648 */
649 export type BoxProps = {
650 /**
651 * Makes the Box a hover scope: while the pointer is anywhere over it, its
652 * own `hover` and that of every element beneath it apply.
653 *
654 * A nested Box with a `key` of its own scopes what is beneath it, a placed
655 * card outside its rows included. A key a sibling Box already took, or one
656 * that is no plain string, names no scope: hovers beneath it stay inert.
657 */
658 key?: string;
659 /**
660 * Style overrides applied by the surface while the pointer is over the
661 * nearest keyed `Box`, this one included, or, given a `scope`, its group.
662 *
663 * No hook runs and nothing crosses to the plugin. To reveal on hover, draw
664 * the Box `display: "none"` with `hover: { display: "flex" }` in a visible
665 * keyed Box or under a `scope`; on a `position: "absolute"` Box, no reflow.
666 */
667 hover?: BoxHoverProps;
668 /**
669 * `"absolute"` leaves the flow, as in CSS: placed against its parent by
670 * the offsets, no room among its siblings, painted over those before it.
671 *
672 * So showing or moving it (a hover may) moves nothing; the pointer on it is
673 * on its parent. Clipped, pointer and paint, by the region its site is in
674 * (viewport, pane, band), by the site itself on the main screen or export.
675 *
676 * @example <Box key="k"><Text>glyph</Text><Box position="absolute" top={-2}
677 * left={2} display="none" hover={{ display: 'flex' }}>the card</Box></Box>
678 */
679 position?: 'relative' | 'absolute';
680 /**
681 * Rows from the parent's top edge, in character cells: an integer,
682 * negative above the edge.
683 *
684 * With `bottom` and no `height` the Box spans the two.
685 */
686 top?: number;
687 /**
688 * Columns from the parent's left edge, in character cells: an integer,
689 * negative left of the edge.
690 *
691 * With `right` and no `width` the Box spans the two.
692 */
693 left?: number;
694 /**
695 * Columns from the parent's right edge, in character cells: an integer,
696 * negative right of the edge.
697 */
698 right?: number;
699 /**
700 * Rows from the parent's bottom edge, in character cells: an integer,
701 * negative below the edge.
702 */
703 bottom?: number;
704 flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';
705 flexGrow?: number;
706 flexShrink?: number;
707 flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse';
708 alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch';
709 alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto';
710 justifyContent?: 'flex-start' | 'center' | 'flex-end' | 'space-between' | 'space-around' | 'space-evenly';
711 gap?: number;
712 columnGap?: number;
713 rowGap?: number;
714 width?: number | string;
715 height?: number | string;
716 minWidth?: number | string;
717 minHeight?: number | string;
718 margin?: number;
719 marginX?: number;
720 marginY?: number;
721 marginTop?: number;
722 marginBottom?: number;
723 marginLeft?: number;
724 marginRight?: number;
725 padding?: number;
726 paddingX?: number;
727 paddingY?: number;
728 paddingTop?: number;
729 paddingBottom?: number;
730 paddingLeft?: number;
731 paddingRight?: number;
732 borderStyle?: string;
733 borderColor?: string;
734 borderDimColor?: boolean;
735 backgroundColor?: string;
736 overflow?: 'visible' | 'hidden';
737 display?: 'flex' | 'none';
738 };
739
740 /**
741 * One variant per built-in tool; with none in the table (a plugin author's
742 * project before `/plugin-types` ran), one loose variant over every name.
743 */
744 export type BuiltinToolCallInput = [BuiltinToolName] extends [never] ? BuiltinToolCallInputFallback : {
745 [N in BuiltinToolName]: ToolInputOf<N, BuiltinToolInputs[N]>;
746 }[BuiltinToolName];
747
748 /**
749 * The built-in branch's answer when no built-in tool is declared: every
750 * name, its args unconstrained.
751 */
752 type BuiltinToolCallInputFallback = {
753 /**
754 * The name of the tool being called (`Bash`); comparing it narrows `e` once
755 * the table has entries. Reserved: a rewrite of it is ignored by core.
756 */
757 tool: string;
758 /**
759 * The tool_use block's id: the same at every event of the call and in
760 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
761 */
762 tool_use_id: string;
763 [argument: string]: unknown;
764 };
765
766 /**
767 * The arguments of each built-in tool by name, for declaration merging;
768 * empty until a declaration file adds entries, then `e.tool === "Bash"`
769 * narrows `e` to Bash's arguments.
770 *
771 * `/plugin-types` writes this build's set beneath the engine's declarations
772 * (claude-code.d.ts), from each tool's input schema.
773 *
774 * @example
775 * interface BuiltinToolInputs { Bash: { command: string; timeout?: number } }
776 */
777 export interface BuiltinToolInputs {
778 }
779
780 /**
781 * The names of the built-in tools.
782 */
783 export type BuiltinToolName = keyof BuiltinToolInputs & string;
784
785 /**
786 * The structured result of each built-in tool by name, for declaration
787 * merging; empty until a declaration file adds entries, then after
788 * `e.tool === "Bash"` the `result` of `next(e)` is Bash's record.
789 *
790 * `/plugin-types` writes this build's set beneath the engine's declarations
791 * (claude-code.d.ts), from each tool's output schema; a tool without one is
792 * `unknown`.
793 *
794 * @example
795 * interface BuiltinToolResults { Bash: { stdout: string; stderr: string } }
796 */
797 export interface BuiltinToolResults {
798 }
799
800 /**
801 * The props of `Button`, every surface's pressable leaf: an address, a
802 * label, the closure a press runs, and the label styles a hover overrides.
803 *
804 * The terminal draws `[ label ]` (when `plain`, `1: label` or the label
805 * alone), a desktop a native button; a click, a `hotkey`, the chord for its
806 * `action`, or Enter under the focus raises `ui.press`, its bottom `onPress`.
807 */
808 export type ButtonProps = {
809 /**
810 * The element's address: `e.element` at `ui.press`, what a matcher names.
811 * Defaults to the label.
812 */
813 key?: string;
814 /**
815 * The text drawn on the button; or the one string child.
816 */
817 label?: string;
818 /**
819 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it while
820 * the plugin's site holds the focus; anything else is refused.
821 *
822 * The band after ctrl+x tab or a click, a focused `Pane`; never from the
823 * composer, save a bare digit in an empty one pressing a band Button, as a
824 * survey is answered. Shift+w matches `"w"`; two on one key, the later wins.
825 */
826 hotkey?: string;
827 /**
828 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord, as the
829 * person bound it, presses this from the prompt; unknown names refused.
830 *
831 * Chords, or a modified key Global or an active context binds, on the
832 * terminal while mounted, no dialog up and no engine handler of the action
833 * mounted; a pane's over the band's over another's, then the last drawn.
834 */
835 action?: string;
836 /**
837 * Drawn without chrome: the hotkey in the accent color, a colon, the
838 * label (`1: Yes`), as a survey's row reads; no `hotkey`, the label alone.
839 *
840 * A one-glyph label (`'\u{1F50A}'`, a speaker) is then a control by
841 * itself: the focus and the pointer still invert it, `dimColor` and `hover`
842 * still apply. A desktop draws its native button either way.
843 */
844 plain?: true;
845 /**
846 * The label drawn dim at rest, as `Text`'s `dimColor`, and at full strength
847 * under the pointer or the focus: a secondary control, a path in a list.
848 */
849 dimColor?: boolean;
850 /**
851 * The site's focus ring starts here when the site takes the keyboard,
852 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
853 *
854 * A pane opened with `focus`, or the person's focus chord or click, is the
855 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
856 * origin this plugin. A ring the person has moved stays where it was put.
857 */
858 autoFocus?: true;
859 /**
860 * Label style overrides (the `Text` set) applied by the surface while the
861 * nearest enclosing keyed `Box`, or given a `scope` its group, is hovered.
862 *
863 * No hook runs and nothing crosses to the plugin; under the pointer itself
864 * the button inverts as it always has. Refused outside a keyed Box unless
865 * it names a `scope`.
866 */
867 hover?: TextHoverProps;
868 /**
869 * What the press runs, in the plugin's own environment: the bottom of the
870 * `ui.press` chain. The host holds only a handle, for the drawing's life.
871 */
872 onPress: () => void;
873 };
874
875 /**
876 * The handler `on(...).catch(handler)` takes for a hook of type `F`: the
877 * hook's `($, e, next)`, run afresh when it throws, misreturns or overruns.
878 *
879 * `next` carries `error` and `called` (Caught) and is replay-safe; a return
880 * within the grace is the hook's result, `undefined` the hook absent. On a
881 * streaming event the handler is a generator too, continuing the stream.
882 */
883 export type CatchHandler<F> = F extends ($: infer D, e: infer E, next: infer N) => infer R ? [R] extends [AsyncGenerator<unknown, unknown, unknown>] ? ($: D, e: E, next: N & Caught) => R : ($: D, e: E, next: N & Caught) => R | undefined | Promise<Awaited<R> | undefined> : never;
884
885 /**
886 * What `next` carries into a `.catch` handler and nowhere else: why the
887 * hook failed, and whether it had called `next` before it did.
888 *
889 * There `next` is replay-safe: when `called`, `next(e)` resolves to what the
890 * hook's last call settled to, nothing beneath running again, the argument
891 * unread; when not, it runs the hooks beneath once and a later call replays.
892 */
893 export type Caught = {
894 /**
895 * Why the hook failed (HookFailure); undefined on an ordinary hook's
896 * `next`, so its presence says a handler is running.
897 */
898 readonly error: HookFailure;
899 /**
900 * True when the failed hook had called `next()` or `next.to()` at least
901 * once, settled or in flight; the handler runs once that call settled.
902 */
903 readonly called: boolean;
904 };
905
906 /**
907 * What a hook on streaming event `N` yields, and what its `next(e)` yields
908 * to it (ChunkOf by name).
909 */
910 export type Chunk<N extends StreamingEventName = StreamingEventName> = ChunkOf[N];
911
912 /**
913 * The chunk type of each streaming event, by name: what its stream yields.
914 */
915 export type ChunkOf = {
916 /**
917 * One piece of the model's response (TurnStepChunk).
918 */
919 'turn.step': TurnStepChunk;
920 };
921
922 /**
923 * What every `turn.step` chunk may carry: the engine's handle on the item
924 * of its own stream the chunk was read off, absent on a chunk a hook made.
925 *
926 * A hook that passes a chunk on, or rewrites it by spreading it, keeps the
927 * handle, and whatever it left unchanged reaches the engine as the engine
928 * streamed it; a chunk built afresh has none and is taken at its word.
929 */
930 type ChunkRef = {
931 /**
932 * The engine's handle on its own streamed item; opaque, this step's only.
933 */
934 ref?: number;
935 };
936
937 /**
938 * The name of a classic hook event as a function-hooks event: the settings
939 * hook's own name under `classic` (`classic.Stop`, `classic.PreToolUse`).
940 */
941 export type ClassicEventName = `classic.${ClassicHookEvent}`;
942
943 /**
944 * The classic (settings) hook events, one per classic event name: `e` is
945 * what the classic hook receives on stdin for that event.
946 *
947 * The chain is [managed settings hooks, ...hooks modules, the other settings
948 * hooks as core], so a managed block ends it above every module. In shape
949 * `classic.PreToolUse` alone differs: its `e` is ToolCallEnvelope, no more.
950 */
951 export type ClassicEventOf = {
952 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? ToolCallEnvelope : ClassicHookInputs[E];
953 };
954
955 /**
956 * The name of a classic hook event: `PreToolUse`, `Stop`, and the rest.
957 */
958 export type ClassicHookEvent = HookInput['hook_event_name'];
959
960 /**
961 * What a classic hook receives on stdin for each event, by event name: the
962 * Agent SDK's `<Event>HookInput`.
963 */
964 export type ClassicHookInputs = {
965 [I in HookInput as I['hook_event_name']]: I;
966 };
967
968 /**
969 * Everything a classic hook event's answer can carry, named as the classic
970 * hook's JSON output names it; each event reads its subset (ClassicResultOf).
971 *
972 * The settings hooks below fold into one of these (last write wins, contexts
973 * concatenate); a hooks module returns `next(e)`, a copy with fields changed,
974 * or its own. A field of the wrong shape fails the hook, which is skipped.
975 */
976 export type ClassicResult = {
977 /**
978 * `decision: "block"` with this text as `reason` (a command hook's exit
979 * code 2): the event's block, veto or re-prompt.
980 */
981 block?: string;
982 /**
983 * `continue: false`: the session stops after this event.
984 */
985 preventContinuation?: true;
986 /**
987 * Shown when `preventContinuation` stops the session (`stopReason`).
988 */
989 stopReason?: string;
990 /**
991 * `hookSpecificOutput.additionalContext`, one entry per hook: text handed
992 * to the model with the event.
993 */
994 additionalContext?: string[];
995 /**
996 * `hookSpecificOutput.sessionTitle` (UserPromptSubmit, SessionStart).
997 */
998 sessionTitle?: string;
999 /**
1000 * `hookSpecificOutput.suppressOriginalPrompt` (UserPromptSubmit,
1001 * UserPromptExpansion).
1002 */
1003 suppressOriginalPrompt?: true;
1004 /**
1005 * `hookSpecificOutput.initialUserMessage` (SessionStart).
1006 */
1007 initialUserMessage?: string;
1008 /**
1009 * `hookSpecificOutput.watchPaths` (SessionStart).
1010 */
1011 watchPaths?: string[];
1012 /**
1013 * `hookSpecificOutput.reloadSkills` (SessionStart).
1014 */
1015 reloadSkills?: true;
1016 /**
1017 * `hookSpecificOutput.permissionDecision` (PreModelSwitch).
1018 */
1019 permissionDecision?: 'allow' | 'deny' | 'ask';
1020 /**
1021 * `hookSpecificOutput.permissionDecisionReason` (PreModelSwitch).
1022 */
1023 permissionDecisionReason?: string;
1024 /**
1025 * `hookSpecificOutput.decision` (PermissionRequest).
1026 */
1027 decision?: PermissionRequestDecision;
1028 /**
1029 * `hookSpecificOutput.updatedToolOutput` (PostToolUse): replaces what the
1030 * model sees of the tool's result.
1031 */
1032 updatedToolOutput?: unknown;
1033 /**
1034 * `hookSpecificOutput.updatedMCPToolOutput` (PostToolUse, MCP tools only).
1035 */
1036 updatedMCPToolOutput?: unknown;
1037 /**
1038 * `hookSpecificOutput.retry` (PermissionDenied).
1039 */
1040 retry?: true;
1041 /**
1042 * `hookSpecificOutput.displayContent` (MessageDisplay).
1043 */
1044 displayContent?: string;
1045 /**
1046 * `hookSpecificOutput.worktreePath` (WorktreeCreate; a command hook prints
1047 * it): the worktree the hook created, absolute or relative to its cwd.
1048 *
1049 * Left unset, the session creates its git worktree as it would unhooked.
1050 */
1051 worktreePath?: string;
1052 };
1053
1054 /**
1055 * The event-specific fields of ClassicResult each classic event reads (its
1056 * `hookSpecificOutput`), by event; an event absent here reads none of them.
1057 *
1058 * `block`, `preventContinuation` and `stopReason` are every event's.
1059 */
1060 export type ClassicResultFields = {
1061 UserPromptSubmit: 'additionalContext' | 'sessionTitle' | 'suppressOriginalPrompt';
1062 UserPromptExpansion: 'additionalContext' | 'suppressOriginalPrompt';
1063 SessionStart: 'additionalContext' | 'initialUserMessage' | 'sessionTitle' | 'watchPaths' | 'reloadSkills';
1064 Setup: 'additionalContext';
1065 PreModelSwitch: 'permissionDecision' | 'permissionDecisionReason';
1066 PostModelSwitch: 'additionalContext';
1067 SubagentStart: 'additionalContext';
1068 PostToolUse: 'additionalContext' | 'updatedToolOutput' | 'updatedMCPToolOutput';
1069 PostToolUseFailure: 'additionalContext';
1070 PostToolBatch: 'additionalContext';
1071 Stop: 'additionalContext';
1072 SubagentStop: 'additionalContext';
1073 PermissionDenied: 'retry';
1074 PermissionRequest: 'decision';
1075 MessageDisplay: 'displayContent';
1076 WorktreeCreate: 'worktreePath';
1077 };
1078
1079 /**
1080 * What each classic hook event's hook returns and its `next(e)` resolves to:
1081 * the event's own subset of ClassicResult.
1082 *
1083 * `classic.PreToolUse` keeps its `allow` / `ask` / `deny` result
1084 * (PreToolUseResult).
1085 */
1086 export type ClassicResultOf = {
1087 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? PreToolUseResult : Pick<ClassicResult, 'block' | 'preventContinuation' | 'stopReason' | (E extends keyof ClassicResultFields ? ClassicResultFields[E] : never)>;
1088 };
1089
1090 /**
1091 * Options of `$.model.classify`.
1092 */
1093 export type ClassifyOptions = {
1094 /**
1095 * An alias (`haiku`) or a full model id; default the engine's small fast
1096 * model.
1097 */
1098 model?: string;
1099 };
1100
1101 /**
1102 * The element table a surface module draws with, `surface.elements`: the
1103 * terminal's (Elements) less `Client` (none nests), `Raster` and `Image`.
1104 *
1105 * What `$.ui.resolve(e)` is to a hooks module; a Button, Input or Select
1106 * keeps its handler here. A tree of them keeps every tree's bounds (20,000
1107 * nodes, 32 deep, 100,000 characters serialized) or the instance unmounts.
1108 */
1109 export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster' | 'Image'>;
1110
1111 /**
1112 * One key the person pressed while a `Client` had the focus, as
1113 * `surface.onKey` hands it. Escape never arrives: it returns the focus.
1114 */
1115 export type ClientKeyEvent = {
1116 /**
1117 * A special key's name (`up`, `down`, `left`, `right`, `return`, `tab`,
1118 * `backspace`, `delete`, `pageup`, `home`, ...) or the character typed.
1119 */
1120 key: string;
1121 /**
1122 * Modifier keys held with it, each present only when true.
1123 */
1124 ctrl?: true;
1125 shift?: true;
1126 meta?: true;
1127 };
1128
1129 /**
1130 * The component a surface module exports (default, or its one PascalCase
1131 * export): from props and surface to the tree drawn (no nested `Client`).
1132 *
1133 * Runs on the drawing thread, a second per call at most; `h` and `Fragment`
1134 * are the environment's, so nothing of the module's takes those names. A
1135 * throw, an overrun or a tree past the bounds (ClientElements) unmounts it.
1136 *
1137 * @example
1138 * const Tag: ClientModule<string> = (t, s) => s.elements.Text({ children: t })
1139 */
1140 export type ClientModule<P extends JsonValue = JsonValue, S = unknown> = (props: P, surface: ClientSurface<S>) => RenderElement;
1141
1142 /**
1143 * One pointer event over a `Client`'s region, as `surface.onPointer` hands
1144 * it: region-relative cells, and the sub-cell position where known.
1145 *
1146 * After a `down` in the region the instance holds the pointer until the
1147 * `up`: every `move` reaches it, past the edges too (negative, or beyond
1148 * `columns`/`rows`), and the transcript neither selects nor scrolls.
1149 */
1150 export type ClientPointerEvent = {
1151 type: ClientPointerType;
1152 /**
1153 * The column under the pointer, 0 at the region's left edge; on `enter`
1154 * and `leave`, the last column a move reported.
1155 */
1156 x: number;
1157 /**
1158 * The row under the pointer, 0 at the region's top edge.
1159 */
1160 y: number;
1161 /**
1162 * The same position with the fraction of a cell kept (`x: 12`, `fine.x:
1163 * 12.375`), where the surface knows it: a terminal that reports pixels.
1164 *
1165 * kitty, Ghostty, iTerm2, WezTerm and foot do; tmux passes none through.
1166 * Absent elsewhere and on `enter`/`leave`; present, a `move` comes within
1167 * a cell too. What a module showing another program's pixels forwards.
1168 *
1169 * @example
1170 * surface.onPointer(e => click((e.fine?.x ?? e.x + 0.5) * pixelsPerCell))
1171 */
1172 fine?: {
1173 x: number;
1174 y: number;
1175 };
1176 /**
1177 * Which button is down (`down`, `move` while held) or came up (`up`);
1178 * absent on a hover `move`, `enter` and `leave`.
1179 */
1180 button?: 'left' | 'middle' | 'right';
1181 /**
1182 * Modifier keys the terminal reported held, each present only when true.
1183 */
1184 shift?: true;
1185 alt?: true;
1186 ctrl?: true;
1187 };
1188
1189 /**
1190 * What the pointer did over a `Client`'s region: a button went down, the
1191 * pointer moved, the button came up, or the pointer crossed the region's edge.
1192 */
1193 export type ClientPointerType = 'down' | 'move' | 'up' | 'enter' | 'leave';
1194
1195 /**
1196 * The props of `Client`: which of the plugin's surface modules draws here,
1197 * under what key, with what data, in how much room.
1198 */
1199 export type ClientProps = {
1200 /**
1201 * The instance's address within the drawing: two `Client`s of one plugin in
1202 * one tree take two keys. What `e.element` carries at `ui.message`.
1203 *
1204 * The engine keeps the instance (its local state, its timers) across the
1205 * plugin's redraws while a `Client` under this key stays in the tree.
1206 */
1207 key: string;
1208 /**
1209 * The surface module's path, a string literal relative to this file:
1210 * `module: "./<name>.tsx"` (or `.jsx`, `.ts`, `.js`, `.mjs`).
1211 *
1212 * Read off the source: a variable there is refused at load, as is a path
1213 * outside the plugin or naming no file. Its default export draws, else
1214 * its one PascalCase export; loaded, the tree carries the plugin's path.
1215 */
1216 module: string;
1217 /**
1218 * Plain data (JsonValue) handed to the module function; a new value on a
1219 * redraw reaches the running instance, its state kept.
1220 *
1221 * Bounded as a tree's text is; not a channel for closures.
1222 * Typed `unknown` so a matcher over a tree stays shallow.
1223 */
1224 props?: unknown;
1225 /**
1226 * Columns the instance's region takes: a count, or a percentage of the
1227 * parent. Absent, the region is as wide as what the module draws.
1228 */
1229 width?: number | string;
1230 /**
1231 * Rows the instance's region takes: a count, or a percentage of the parent.
1232 * Absent, the region is as tall as what the module draws.
1233 */
1234 height?: number | string;
1235 /**
1236 * How the region grows into free room along the parent's direction, as a
1237 * Box's `flexGrow`.
1238 */
1239 flexGrow?: number;
1240 };
1241
1242 /**
1243 * What a surface module's function receives as its second argument: its
1244 * elements, the instance's local state, its region, input, clock and port.
1245 *
1246 * Called again (same `surface`, same `state`) on new props, after
1247 * `setState`, and on a resize; what it returns is drawn in the region. No
1248 * `$` here: the hooks module has it, and `post` is the way to reach it.
1249 */
1250 export type ClientSurface<S = unknown> = {
1251 /**
1252 * The surface's element table (ClientElements), the tags the module draws
1253 * with: `const { Box, Text } = surface.elements`. No `Client` in it.
1254 */
1255 readonly elements: ClientElements;
1256 /**
1257 * The instance's local state: `undefined` until the first `setState`.
1258 * Kept across the plugin's redraws; dropped with the instance.
1259 */
1260 readonly state: S | undefined;
1261 /**
1262 * Replaces the local state and schedules one more call of the function on
1263 * the next frame; several calls before it coalesce into one redraw.
1264 *
1265 * A `setState` on each of three renders in a row with no key, pointer,
1266 * tick, press or props between is a render loop: the instance unmounts.
1267 */
1268 setState: (next: S) => void;
1269 /**
1270 * The region's width in cells, as last laid out (0 before the first
1271 * layout).
1272 */
1273 readonly columns: number;
1274 /**
1275 * The region's height in cells, as last laid out (0 before the first
1276 * layout).
1277 */
1278 readonly rows: number;
1279 /**
1280 * Calls `fn` every `ms` milliseconds on the surface's frame clock until
1281 * the returned function is called or the instance unmounts.
1282 *
1283 * Start it once (while `state` is still undefined), not on every call.
1284 */
1285 every: (ms: number, fn: () => void) => () => void;
1286 /**
1287 * Sets the instance's pointer listener (one; a later call replaces it)
1288 * and returns what clears it. See ClientPointerEvent for capture.
1289 */
1290 onPointer: (fn: (event: ClientPointerEvent) => void) => () => void;
1291 /**
1292 * Sets the instance's key listener (one; a later call replaces it),
1293 * reached while a click has given it the focus; Escape returns that.
1294 */
1295 onKey: (fn: (event: ClientKeyEvent) => void) => () => void;
1296 /**
1297 * Sends plain data to the plugin's hooks module: `e.data` of a
1298 * `ui.message` only that plugin's hooks see, one per frame at most.
1299 *
1300 * A later post in the same frame replaces an undelivered one; a hook
1301 * answering `{ props }` hands this instance its next props. At most
1302 * 20,000 values, 32 deep, 100,000 characters, or the post is not sent.
1303 */
1304 post: (data: JsonValue) => void;
1305 };
1306
1307 /**
1308 * The argument of the `$.clock` waits (`sleep`, `after`, `every`): how long,
1309 * in milliseconds, before the dispatch resolves.
1310 */
1311 type ClockWait = {
1312 /**
1313 * The wait, a non-negative number of milliseconds.
1314 */
1315 ms: number;
1316 };
1317
1318 /**
1319 * The props of `Code`, source text every surface draws with the engine's own
1320 * highlighter: coloured tokens, a line gutter on request, or a unified diff.
1321 *
1322 * A leaf: no children. `source` is the element's data as a string is a
1323 * Text's, bounded and free of control characters the same way; the colour
1324 * on screen is the engine's, never the plugin's.
1325 */
1326 export type CodeProps = {
1327 /**
1328 * The text drawn: source code, or under `format: 'diff'` one or more
1329 * unified-diff hunks.
1330 *
1331 * At most 10000 characters; tab and newline are the only control
1332 * characters it may hold.
1333 */
1334 source: string;
1335 /**
1336 * A highlighter language id or alias (`typescript`, `ts`, `py`), a
1337 * plugin-contributed grammar's included.
1338 *
1339 * Absent, the language is inferred from `path`; when neither resolves,
1340 * the text is drawn plain.
1341 */
1342 language?: string;
1343 /**
1344 * A file path the language is inferred from when `language` is absent:
1345 * its extension or name, else a shebang on the first line.
1346 *
1347 * Drawn nowhere and never read: nothing touches the disk.
1348 */
1349 path?: string;
1350 /**
1351 * The 1-based number of the first line of `source`: present, a dim
1352 * right-aligned gutter numbers the lines from it; absent, no gutter.
1353 *
1354 * Ignored under `format: 'diff'`, whose hunks carry their own numbers.
1355 */
1356 startLine?: number;
1357 /**
1358 * `'source'` (the default) draws `source` as code; `'diff'` reads it as
1359 * unified-diff hunks and draws gutters, markers, add and remove colouring.
1360 *
1361 * A hunk is `@@ -a,b +c,d @@` then lines starting ` `, `+` or `-`; a
1362 * leading `---`/`+++` pair and `\ No newline at end of file` are read
1363 * past. A source that does not parse as hunks is refused.
1364 */
1365 format?: 'source' | 'diff';
1366 /**
1367 * What a line wider than the room does, in Text's `wrap` vocabulary:
1368 * `'wrap'` (the default) continues it on rows under the gutter.
1369 *
1370 * `'truncate-end'` cuts it at the edge with an ellipsis; Text's other
1371 * spellings are refused, since a gutter leaves them no sense here.
1372 */
1373 wrap?: 'wrap' | 'truncate-end';
1374 };
1375
1376 /**
1377 * The input of `command.describe`: how one slash command presents in the
1378 * typeahead and `/help`, at the moment the engine lists it.
1379 */
1380 export type CommandDescribeInput = {
1381 /**
1382 * Names the command without its slash; the key a matcher narrows on. A
1383 * rewrite is refused.
1384 */
1385 command: string;
1386 /**
1387 * The one-line description the menu shows, as the command declares it.
1388 */
1389 description: string;
1390 /**
1391 * The hint drawn dim after the name (`[name]`), when the command has one.
1392 */
1393 argumentHint?: string;
1394 /**
1395 * Whether the typeahead and `/help` leave the command out; a hidden
1396 * command still runs when typed in full.
1397 */
1398 isHidden: boolean;
1399 /**
1400 * Whether the command declares it runs at once when typed mid-turn,
1401 * instead of waiting for the turn to end.
1402 *
1403 * One that decides per invocation reads false. Read only: not part of
1404 * what a hook answers, and a rewrite is refused.
1405 */
1406 immediate: boolean;
1407 /**
1408 * Who provides this command: the plugin and its tier; `{ plugin: "engine",
1409 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
1410 */
1411 provider: Origin;
1412 };
1413
1414 /**
1415 * What a `command.describe` hook returns: the description, hint and hidden
1416 * flag the menu uses; the name, `immediate` and `provider` stay as they were.
1417 */
1418 export type CommandDescribeResult = Omit<CommandDescribeInput, 'command' | 'immediate' | 'provider'>;
1419
1420 /**
1421 * One slash command as `$.command.list()` returns it.
1422 */
1423 export type CommandInfo = {
1424 /**
1425 * What the person runs it by, without the slash.
1426 */
1427 name: string;
1428 /**
1429 * The one line the typeahead shows for it.
1430 */
1431 description: string;
1432 /**
1433 * Where it comes from (CommandSource).
1434 */
1435 source: CommandSource;
1436 /**
1437 * Which plugin added it, when `source` is `plugin` and the engine knows:
1438 * the one that registered it, or whose manifest carries it.
1439 */
1440 plugin?: string;
1441 };
1442
1443 /**
1444 * Where a command's answer will show: which of the terminal's two layouts
1445 * the surface renders, and how wide it is when the command runs.
1446 *
1447 * A fact the engine stamps on `command.run`, so a command that draws (opens
1448 * a pane, prints a wide table) can suit the room it has: the fullscreen
1449 * layout docks a pane beside the transcript from 110 columns, the main
1450 * screen places it inline above the prompt at any width.
1451 */
1452 export type CommandPresentation = {
1453 /**
1454 * True under the fullscreen (alternate-screen) layout; false on the main
1455 * screen (`CLAUDE_CODE_NO_FLICKER=0`, tmux by default) and headless.
1456 *
1457 * The fact `RenderViewport`'s `isFullscreen` carries on every terminal
1458 * drawing, from the same source: the two agree.
1459 */
1460 isFullscreen: boolean;
1461 /**
1462 * The terminal's width in cells as the command runs; 80 where no terminal
1463 * has measured (headless with no tty).
1464 */
1465 columns: number;
1466 };
1467
1468 /**
1469 * `command.run`'s input as a plugin's `$.command.run` takes it: `args` may
1470 * be left out (`/command`, bare); `origin` and `presentation` the engine sets.
1471 */
1472 export type CommandRunArgs = Omit<CommandRunInput, 'origin' | 'args' | 'presentation'> & {
1473 /**
1474 * Everything after the name, as the person would type it; left out, `""`.
1475 */
1476 args?: string;
1477 };
1478
1479 /**
1480 * The input of `command.run`: one slash command about to run, the way the
1481 * person typed it (`/name args`), and where the run came from.
1482 */
1483 export type CommandRunInput = {
1484 /**
1485 * Names the command without its slash (`compact`, `hello`), aliases and
1486 * folds resolved; the key a matcher narrows on. A rewrite is refused.
1487 */
1488 command: string;
1489 /**
1490 * Everything after the name, as typed (`""` when nothing was); a hook
1491 * rewrites it with `next({ ...e, args })`.
1492 */
1493 args: string;
1494 /**
1495 * Where the run came from, in `prompt.submit`'s words (PromptOrigin):
1496 * the person's Enter (`composer`), the bridge, the SDK, or a plugin.
1497 *
1498 * A plugin's `$.command.run` reads `{ kind: 'plugin', name }`. `next(e)`
1499 * passes it on as received.
1500 */
1501 origin: PromptOrigin;
1502 /**
1503 * Where the command's answer will show (CommandPresentation): the
1504 * fullscreen layout or the main screen, and the terminal's width.
1505 *
1506 * Pinned: the engine stamps it, `next(e)` passes it on, a rewrite that
1507 * leaves it out keeps it and one that changes it is refused.
1508 */
1509 presentation: CommandPresentation;
1510 };
1511
1512 /**
1513 * What a `command.run` hook returns and what `next(e)` and `$.command.run`
1514 * resolve to: the command's output text and the notes it leaves the model.
1515 *
1516 * From core, `text` is what the command printed (a `local` command's
1517 * returned text; a panel command may print nothing), `context` what it
1518 * recorded for the model beside that, and `ref` names the run.
1519 *
1520 * A hook's own answer without `next` runs no command: its `text` is shown
1521 * as the command's output, under the names of the plugins hooking the
1522 * command unless each is bundled with Claude Code, whose answer reads as
1523 * the built-in command's own, and its `context` is recorded after it.
1524 *
1525 * Both are the plugin's to size, as a core command's output is; what bounds
1526 * them is what bounds any transcript row where a surface draws it.
1527 */
1528 export type CommandRunResult = {
1529 /**
1530 * The command's output as a transcript line, or undefined when the
1531 * command showed nothing as text (a panel, a prompt for the model).
1532 */
1533 text?: string;
1534 /**
1535 * What the model reads after the command's output and the person never
1536 * sees, each entry one hidden user message recorded after the output row.
1537 *
1538 * From core, the notes the command left the model, absent when none. Kept
1539 * whole from `next`: left out after `next`, the last answer's notes ride
1540 * along; written, it keeps every entry that answer had (none empty).
1541 */
1542 context?: readonly string[];
1543 /**
1544 * Set by core on what `next(e)` resolves to: names the engine's run of
1545 * the command (its result stays on the host side).
1546 *
1547 * A hook that returns the object it got makes the engine use that run
1548 * verbatim. Absent on a hook's own `{ text }` and on `$.command.run`'s.
1549 */
1550 ref?: number;
1551 };
1552
1553 /**
1554 * Where a slash command comes from, as `$.command.list()` tells them apart.
1555 *
1556 * `builtin` ships with Claude Code; `plugin` is a plugin's markdown command,
1557 * skill or `$.command.register`; `user` is the user's or project's own
1558 * file; `mcp` an MCP server's prompt.
1559 */
1560 export type CommandSource = 'builtin' | 'plugin' | 'user' | 'mcp';
1561
1562 /**
1563 * What `$.command.register` takes: the slash command this plugin serves.
1564 */
1565 export type CommandSpec = {
1566 /**
1567 * The command's name without the slash (letters, digits, `_`, `-`; up to
1568 * 64); the person runs it as `/<name>`.
1569 */
1570 name: string;
1571 /**
1572 * The one line the typeahead and `/help` show for it.
1573 */
1574 description: string;
1575 /**
1576 * The hint drawn dim after the name (`[name]`), when it takes arguments.
1577 */
1578 argumentHint?: string;
1579 /**
1580 * Set so that `/<name>` typed while a turn is in flight runs at once
1581 * instead of waiting for the turn to end, as it does when left out.
1582 *
1583 * Its `command.run` hook then runs while a turn may still be streaming and
1584 * must not assume the turn's state (what the transcript holds, whether a
1585 * tool is mid-call); its `{ text }` prints as an idle run's does.
1586 */
1587 immediate?: true;
1588 };
1589
1590 type ConfigChangeHookInput = BaseHookInput & {
1591 hook_event_name: 'ConfigChange';
1592 source: 'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills';
1593 file_path?: string;
1594 };
1595
1596 /**
1597 * The input of `config.describe`: how one `/config` row presents, at the
1598 * moment the menu lists it (and for `$.config.list`).
1599 */
1600 export type ConfigDescribeInput = {
1601 /**
1602 * Names the row, as `config.set`'s `key` does; the key a matcher narrows
1603 * on. Pinned: a rewrite is refused.
1604 */
1605 key: string;
1606 /**
1607 * What the menu draws for the row, before its value.
1608 */
1609 label: string;
1610 /**
1611 * The help text beneath the label, when the row has one (a plugin
1612 * field's `description`); absent for the panel's own rows.
1613 */
1614 description?: string;
1615 /**
1616 * Whether the menu leaves the row out; a hidden row still answers
1617 * `$.config.set` and `/config key=value`.
1618 */
1619 isHidden: boolean;
1620 /**
1621 * Who owns the row, as `config.set`'s `provider`. Pinned.
1622 */
1623 provider: Origin;
1624 };
1625
1626 /**
1627 * What a `config.describe` hook returns: the label, help text and hidden
1628 * flag the menu uses; the key and provider stay as they were.
1629 */
1630 export type ConfigDescribeResult = Omit<ConfigDescribeInput, 'key' | 'provider'>;
1631
1632 /**
1633 * How a `/config` row takes its value: `boolean` toggles, `choice` picks one
1634 * of its `options`, `text` takes a string, `number` a number.
1635 */
1636 export type ConfigKind = 'boolean' | 'choice' | 'text' | 'number';
1637
1638 /**
1639 * Where a `config.set` came from, in `prompt.submit`'s words: the person
1640 * in the `/config` menu (`composer`), the bridge, or a plugin, named.
1641 *
1642 * Set by the engine; `next(e)` passes it on as received and none sets it.
1643 */
1644 export type ConfigOrigin = {
1645 /**
1646 * The person's own change in the `/config` menu (a toggle, a pick, a
1647 * typed value), or their `/config key=value`.
1648 */
1649 kind: 'composer';
1650 } | {
1651 /**
1652 * A `/config key=value` that arrived over the Remote Control bridge (a
1653 * phone or web client, or a relay): not attestably the owner's hand.
1654 */
1655 kind: 'bridge';
1656 } | {
1657 /**
1658 * A plugin's `$.config.set`; that plugin's own hooks do not see it.
1659 */
1660 kind: 'plugin';
1661 /**
1662 * The calling plugin's name.
1663 */
1664 name: string;
1665 };
1666
1667 /**
1668 * One `/config` row as `$.config.list()` returns it: what the menu would
1669 * draw now, after every `config.describe` hook, a hidden row left out.
1670 */
1671 export type ConfigRow = {
1672 /**
1673 * Names the row: the panel's id for a built-in, `<plugin>.<field>` for a
1674 * plugin's `userConfig` field; what `$.config.set` takes.
1675 */
1676 key: string;
1677 /**
1678 * What the menu draws for the row, before its value.
1679 */
1680 label: string;
1681 /**
1682 * The help text under the label, when the row has one.
1683 */
1684 description?: string;
1685 /**
1686 * How the row takes its value (ConfigKind).
1687 */
1688 kind: ConfigKind;
1689 /**
1690 * What the row holds now.
1691 */
1692 value: ConfigValue;
1693 /**
1694 * The values a `choice` row takes, in order (a plugin string field's
1695 * declared `options` for its row); absent otherwise.
1696 */
1697 options?: readonly string[];
1698 /**
1699 * Who owns the row: the engine for the panel's own, else the plugin.
1700 */
1701 provider: Origin;
1702 /**
1703 * Whether a trusted source (managed settings, the organization's policy)
1704 * owns the value, so the menu shows it and refuses a change.
1705 */
1706 isLocked: boolean;
1707 };
1708
1709 /**
1710 * `config.set`'s input as a plugin's `$.config.set(args)` takes it: the
1711 * row's key and the value; the engine fills the rest.
1712 */
1713 export type ConfigSetArgs = Pick<ConfigSetInput, 'key' | 'value'>;
1714
1715 /**
1716 * The input of `config.set`: one `/config` row about to change, from the
1717 * menu or a plugin's `$.config.set`, with what it holds now and who owns it.
1718 */
1719 export type ConfigSetInput = {
1720 /**
1721 * Names the row: the panel's own id for a built-in (`theme`, `verbose`,
1722 * `autoCompact`), `<plugin>.<field>` for a plugin's `userConfig` field.
1723 *
1724 * The key a matcher narrows on; pinned: a rewrite is refused.
1725 */
1726 key: string;
1727 /**
1728 * What the row is being set to; `next({ ...e, value })` clamps or
1729 * replaces it, held to the row's kind (a toggle takes a boolean).
1730 */
1731 value: ConfigValue;
1732 /**
1733 * What the row holds before the change, as the menu shows it. Pinned.
1734 */
1735 previous: ConfigValue;
1736 /**
1737 * Who owns the row: `{ plugin: "engine", tier: "core" }` for the panel's
1738 * own, the plugin and its tier for a `userConfig` field. Pinned.
1739 */
1740 provider: Origin;
1741 /**
1742 * Where the change came from (ConfigOrigin): the person in the menu
1743 * (`composer`) or a plugin's `$.config.set`. Pinned.
1744 */
1745 origin: ConfigOrigin;
1746 };
1747
1748 /**
1749 * What a `config.set` hook returns and what `next(e)` resolves to:
1750 * `{ value }` once written, or `{ deny: reason }`, the row left as it was.
1751 *
1752 * The menu shows a deny's reason beside the row; a plugin's `$.config.set`
1753 * resolves with it.
1754 */
1755 export type ConfigSetResult = {
1756 value: ConfigValue;
1757 deny?: undefined;
1758 } | {
1759 deny: string;
1760 value?: undefined;
1761 };
1762
1763 /**
1764 * A `/config` row's value as a hook and `$.config` see it: a toggle's
1765 * boolean, a choice's or a text's string, a number, or a list of strings.
1766 */
1767 export type ConfigValue = boolean | string | number | readonly string[];
1768
1769 /**
1770 * One custom agent whose description the Agent tool's prompt carries;
1771 * built-in agents are left out.
1772 */
1773 export type ContextAgent = {
1774 /**
1775 * The agent's type, as the Agent tool names it.
1776 */
1777 agentType: string;
1778 /**
1779 * Where it was defined, by the engine's word (`projectSettings`,
1780 * `userSettings`, `plugin`); the display label is the renderer's.
1781 */
1782 source: string;
1783 /**
1784 * The description's estimated tokens.
1785 */
1786 tokens: number;
1787 };
1788
1789 /**
1790 * The token counts the last API response of the live window reported, as
1791 * the API spells them; the breakdown's `Messages` row is reconciled to it.
1792 */
1793 export type ContextApiUsage = {
1794 /**
1795 * Uncached input tokens the response was answered over.
1796 */
1797 input_tokens: number;
1798 /**
1799 * Tokens the response generated.
1800 */
1801 output_tokens: number;
1802 /**
1803 * Input tokens written to the prompt cache by the request.
1804 */
1805 cache_creation_input_tokens: number;
1806 /**
1807 * Input tokens read from the prompt cache by the request.
1808 */
1809 cache_read_input_tokens: number;
1810 };
1811
1812 /**
1813 * How a context breakdown is counted: `full` with the token-count API per
1814 * category, `summary` from the last response's usage and local estimates.
1815 *
1816 * The SDK's `get_context_usage` takes the same two words as its `detail`.
1817 */
1818 export type ContextBreakdownDetail = 'summary' | 'full';
1819
1820 /**
1821 * One row of the breakdown, as /context lists it beside the grid (`System
1822 * prompt`, `Messages`, `Free space`, `Autocompact buffer`).
1823 */
1824 export type ContextCategory = {
1825 /**
1826 * The row's label as /context prints it.
1827 */
1828 name: string;
1829 /**
1830 * The row's estimated tokens; a `deferred` row's do not count toward the
1831 * total.
1832 */
1833 tokens: number;
1834 /**
1835 * The theme colour /context draws the row and its squares in, by its key
1836 * in the theme (`promptBorder`, `inactive`, `permission`).
1837 */
1838 color: string;
1839 /**
1840 * Whether the row is tool schemas loaded on demand, which the grid leaves
1841 * out; the same fact as `kind` `deferred`.
1842 */
1843 isDeferred: boolean;
1844 /**
1845 * What the row is (ContextCategoryKind), stamped by the engine.
1846 */
1847 kind: ContextCategoryKind;
1848 };
1849
1850 /**
1851 * What a breakdown row is; branch on this, never on the row's `name`.
1852 *
1853 * `used` content occupies the window, `free` is the window left, `buffer`
1854 * the compaction reserve, `deferred` tool schemas loaded on demand and
1855 * outside the window.
1856 */
1857 export type ContextCategoryKind = 'used' | 'free' | 'buffer' | 'deferred';
1858
1859 /**
1860 * One square of the grid /context draws: which row it belongs to and how
1861 * full it is.
1862 */
1863 export type ContextGridSquare = {
1864 /**
1865 * The theme colour of the square's row, by its key in the theme.
1866 */
1867 color: string;
1868 /**
1869 * Whether the square holds any of its row's tokens.
1870 */
1871 isFilled: boolean;
1872 /**
1873 * The `name` of the row the square belongs to (`Free space` for the
1874 * window left).
1875 */
1876 categoryName: string;
1877 /**
1878 * The row's tokens, repeated on each of its squares.
1879 */
1880 tokens: number;
1881 /**
1882 * The row's share of the window as a whole percentage, repeated likewise.
1883 */
1884 percentage: number;
1885 /**
1886 * How full this one square is, 0 to 1: a row's last square is the partial
1887 * one (/context draws it hollow under 0.7).
1888 */
1889 squareFullness: number;
1890 };
1891
1892 /**
1893 * One MCP tool's schema as the context carries it.
1894 */
1895 export type ContextMcpTool = {
1896 /**
1897 * The tool's wire name (`mcp__linear__create_issue`).
1898 */
1899 name: string;
1900 /**
1901 * The server it belongs to, as /mcp lists it.
1902 */
1903 serverName: string;
1904 /**
1905 * The schema's estimated tokens.
1906 */
1907 tokens: number;
1908 /**
1909 * Whether the schema is inside the window now: always, unless tool
1910 * schemas load on demand and this one has not been searched for yet.
1911 */
1912 isLoaded: boolean;
1913 };
1914
1915 /**
1916 * One memory file the context carries (a CLAUDE.md, a rules file, an
1917 * auto-memory entry).
1918 */
1919 export type ContextMemoryFile = {
1920 /**
1921 * The file's path, absolute.
1922 */
1923 path: string;
1924 /**
1925 * The display label of where it was loaded from (`Project`, `User`,
1926 * `Local`, `Managed`, `AutoMem`).
1927 */
1928 type: string;
1929 /**
1930 * The file's estimated tokens.
1931 */
1932 tokens: number;
1933 };
1934
1935 /**
1936 * One skill whose listing the context carries.
1937 */
1938 export type ContextSkill = {
1939 /**
1940 * The skill's name as `/skills` lists it.
1941 */
1942 name: string;
1943 /**
1944 * Where it came from, by the engine's word (`userSettings`, `plugin`,
1945 * `built-in`, `mcp`, `syncedSkills`); the display label is the renderer's.
1946 */
1947 source: string;
1948 /**
1949 * The providing plugin's name, when the skill comes from one.
1950 */
1951 pluginName?: string;
1952 /**
1953 * The listing's estimated tokens.
1954 */
1955 tokens: number;
1956 };
1957
1958 /**
1959 * The skills the context lists for the model: how many there are, how many
1960 * fit the listing's budget, and each one's share.
1961 */
1962 export type ContextSkills = {
1963 /**
1964 * How many skills the session has.
1965 */
1966 totalSkills: number;
1967 /**
1968 * How many the listing included within its token budget.
1969 */
1970 includedSkills: number;
1971 /**
1972 * The listing's tokens in all.
1973 */
1974 tokens: number;
1975 /**
1976 * One entry per listed skill.
1977 */
1978 skillFrontmatter: ContextSkill[];
1979 };
1980
1981 /**
1982 * The slash commands the Skill tool's prompt lists, counted.
1983 */
1984 export type ContextSlashCommands = {
1985 /**
1986 * How many commands the session has.
1987 */
1988 totalCommands: number;
1989 /**
1990 * How many the listing included.
1991 */
1992 includedCommands: number;
1993 /**
1994 * The listing's tokens in all.
1995 */
1996 tokens: number;
1997 };
1998
1999 /**
2000 * How the window the breakdown measures against was settled; /context
2001 * prints its `Auto-compact window` line off this.
2002 *
2003 * `auto` is the model's own limit; the rest name a compaction window by who
2004 * set it: the `CLAUDE_CODE_AUTO_COMPACT_WINDOW` variable, the settings, the
2005 * account, an experiment, the model's default, or an unrecognised model's.
2006 */
2007 export type ContextWindowSource = 'env' | 'settings' | 'clientdata' | 'experiment' | 'model-default' | 'unknown-model' | 'auto';
2008
2009 /**
2010 * The plugin's identity (`plugin`) and the nouns core contributes to `$` as
2011 * the innermost step of the `engine.create` fold.
2012 *
2013 * A plugin's finished `$` (EngineInterface) has every core noun an outer
2014 * step did not withhold, and every noun the plugins' steps added.
2015 */
2016 export interface CoreEngineInterface {
2017 /**
2018 * This plugin, as loaded: its manifest name and its directory.
2019 */
2020 plugin: {
2021 /**
2022 * From plugin.json; debug-log and `$.ui.log` lines carry it.
2023 */
2024 name: string;
2025 /**
2026 * The plugin's directory (the one holding plugin.json), absolute.
2027 */
2028 root: string;
2029 };
2030 /**
2031 * Display: a line under an open dialog, a redraw or a repaint, a
2032 * transcript or debug line, panes the surface places, a window or ring.
2033 */
2034 ui: {
2035 /**
2036 * Shows `text` as one line under the dialog open for `tool_use_id`, or
2037 * removes the line when `text` is undefined.
2038 *
2039 * Core removes the line when the call resolves. A call that is not open
2040 * is refused, as is another plugin's `$.tool.call` run.
2041 *
2042 * @param tool_use_id the call whose open dialog gets the line
2043 * @param text the line to show; undefined removes it
2044 * @example
2045 * $.ui.notice(e.tool_use_id, "checked by my-plugin"); return next(e)
2046 */
2047 notice: (tool_use_id: string, text: string | undefined) => void;
2048 /**
2049 * Re-runs an event whose results the engine caches: `ui.render` draws the
2050 * instances this plugin may draw again; the others drop the cached answers.
2051 *
2052 * A render hook whose state changed (a countdown) calls it for a redraw, at
2053 * most ten a second, thirty for the shown pane and the band (calls sooner
2054 * fold); a prompt section, context or attachment hook: dropped next turn.
2055 *
2056 * @param event `ui.render`, or a cached-answer event: `prompt.section`,
2057 * `prompt.context`, `prompt.attachment`, `tool/command/config.describe`
2058 */
2059 invalidate: (event: InvalidatableEventName) => void;
2060 /**
2061 * Repaints a mounted `Raster` this plugin's own render hook drew with new
2062 * cells, or swaps a keyed `Image` it drew to a new source; no redraw.
2063 *
2064 * The surface paints the cells or source at its next frame, so blits
2065 * between frames fold into one: up to 120 a second taken, some sixty
2066 * shown. An Image swap sends one small command; a resize is a redraw.
2067 *
2068 * @param args `requestId` (the site), `key`, and `cells` (RasterProps) or
2069 * `source` (ImageSource); `columns`, `rows` (the mounted size)
2070 * @returns `{}` once the cells or source are its next frame, or `{ deny }`
2071 * (not mounted, not this plugin's, another size, cells that do
2072 * not decode, a bad source, or an Image drawing its alt there:
2073 * no placeholder images, or a file this terminal cannot read)
2074 * @example
2075 * $.clock.every(33, () => $.ui.blit({ requestId, key, cells: frame() }))
2076 * @example
2077 * await $.ui.blit({ requestId: 'browser', key: 'view',
2078 * source: { shm: name, format: 'rgb', width, height } })
2079 */
2080 blit: (args: UiBlitArgs) => Promise<UiBlitResult>;
2081 /**
2082 * The elements of the surface `e` is drawn on (Elements[e.surface]): a
2083 * frozen table of constructors, the JSX tags a render hook draws with.
2084 *
2085 * A read, not a dispatch: the engine ran `ui.resolve` (the other hooks,
2086 * then core) at load, per surface and component. Narrowed `e.surface`:
2087 * that table exactly; unnarrowed: the union, so shared names type-check.
2088 *
2089 * @param e this hook's own `ui.render` argument (its surface and
2090 * component pick the table)
2091 * @returns the surface's frozen element table (`Elements[e.surface]`)
2092 * @example
2093 * const { Box, Text } = $.ui.resolve(e)
2094 * return <Box>{await next(e)}<Text dimColor>done</Text></Box>
2095 */
2096 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
2097 /**
2098 * Appends one line to the transcript, drawn like a system notice (dim;
2099 * not sent to the model), or with `{ to: "debug" }` to the debug log alone.
2100 *
2101 * A row of its own at the next frame, in logging order; a `-p` or SDK
2102 * host receives it as `ui_log`; the debug log has every line under this
2103 * plugin's name. Raised as `ui.log`: a hook above may rewrite `e.to`.
2104 *
2105 * @param text the line's text
2106 * @param options `to`: `transcript` (the default) or `debug`
2107 * @example
2108 * $.ui.log(`prompt from ${e.origin.kind}: ${e.text.length} chars`)
2109 * @example
2110 * $.ui.log(`cache miss for ${e.tool_use_id}`, { to: "debug" })
2111 */
2112 log: (text: string, options?: UiLogOptions) => void;
2113 /**
2114 * Asks the user `question` in the engine's own AskUserQuestion dialog and
2115 * resolves to the label they chose, or the text typed under "Other".
2116 *
2117 * A `tool.call` of `AskUserQuestion` through every hook but the calling
2118 * one, drawn by `ui.render` on `AskUserQuestion`; a multi-select answer is
2119 * comma-joined. Rejects when dismissed, and in a `-p` run (no one to ask).
2120 *
2121 * @param question the question, ending in a question mark
2122 * @param options 2-4 option labels, or `{ options, header, multiSelect }`
2123 * @returns the label chosen, the chosen labels comma-joined, or free text
2124 * typed under "Other" (so compare it with the labels exactly)
2125 * @example
2126 * const mood = await $.ui.ask("How careful?", ["Bold", "Careful"])
2127 */
2128 ask: (question: string, options?: readonly string[] | AskOptions) => Promise<string>;
2129 /**
2130 * Shows `text` on the notification bar under the prompt for a few
2131 * seconds, the way the engine's own "context left" notice appears.
2132 *
2133 * It leaves the transcript and the model untouched.
2134 *
2135 * @param text the line to show; an unpaired surrogate half in it is drawn
2136 * as U+FFFD
2137 * @param options `timeoutMs`: how long it stays (default 4000)
2138 * @example
2139 * $.ui.toast(`turn took ${Math.round(e.durationMs / 1000)} s`)
2140 */
2141 toast: (text: string, options?: ToastOptions) => void;
2142 /**
2143 * Pins `text` as this plugin's status line under the prompt, beside the
2144 * engine's own pinned notices, until the next call replaces it.
2145 *
2146 * One per plugin; `undefined` removes it.
2147 *
2148 * @param text the line to keep on screen (an unpaired surrogate half is
2149 * drawn as U+FFFD); undefined clears it
2150 * @example
2151 * $.ui.status("thinking..."); return next(e)
2152 */
2153 status: (text: string | undefined) => void;
2154 /**
2155 * Opens a pane: a framed region the surface places, whose body this
2156 * plugin draws by hooking `ui.render` for `{ component: "Pane" }`.
2157 *
2158 * One instance per id (`requestId`): opening an open id retitles it; a hook
2159 * on `ui.open` may refuse it. The keyboard is the person's; unasked, it
2160 * waits undrawn below 144 columns (110 once asked), judged at each open.
2161 *
2162 * @param pane `id` (1-64 of letters, digits, `_`, `-`), `title`, `focus`,
2163 * `closeOnEscape` and `holdToasts` (a dialog), `rows` / `columns` wanted
2164 * @returns settles once the pane is open (or retitled)
2165 * @example
2166 * await $.ui.open({ id: "clock", title: "Clock" })
2167 * @example
2168 * await $.ui.open({ id: "ask", focus: true, closeOnEscape: true, rows: 9 })
2169 */
2170 open: (pane: PaneOpenArgs) => Promise<void>;
2171 /**
2172 * Closes one of the open panes; an id that is not open is left alone.
2173 *
2174 * Every close raises `ui.close`, `e.origin` naming whose it is: this call
2175 * (`plugin`), the person's mark or key (`person`), an unload (`unload`).
2176 * A hook answering without `next` keeps the pane open, save on an unload.
2177 *
2178 * @param pane `id`: the id the pane was opened under
2179 * @returns settles once the pane is gone or a hook answered for it;
2180 * rejects on a hook's `{ deny }`
2181 * @example
2182 * onPress: () => $.ui.close({ id: "clock" })
2183 */
2184 close: (pane: PaneCloseArgs) => Promise<void>;
2185 /**
2186 * Lists this plugin's own open panes (UiPane): each one's id and title,
2187 * and whether it is shown, holds the keyboard, and is placed.
2188 *
2189 * The engine's record, not the module's: a module reloaded while its
2190 * pane stayed up finds it here. Another plugin's panes are not listed.
2191 *
2192 * @returns the panes in open order, placed ones first; empty with none
2193 * @example
2194 * const isUp = (await $.ui.panes()).some(pane => pane.id === "clock")
2195 * if (!isUp) await $.ui.open({ id: "clock", title: "Clock" })
2196 */
2197 panes: () => Promise<readonly UiPane[]>;
2198 /**
2199 * Scrolls something into view as the DOM's `scrollIntoView` would: a
2200 * render instance by `requestId`, an element by `key`, a site's edge.
2201 *
2202 * A site of this plugin's (its pane, the band it draws into) moves under
2203 * the event `ui.scroll`, origin `plugin`. A transcript row moves only
2204 * while this call answers the person's own input, where one scrolls.
2205 *
2206 * @param args `to` (what), `in` (which site, required for `start` and
2207 * `end`), `block` (where it lands; `nearest` by default)
2208 * @returns `{}` once it moved, or `{ deny }` saying why not
2209 * @example
2210 * onPress: () => $.ui.scroll({ in: "log", to: "end" })
2211 */
2212 scroll: (args: UiScrollArgs) => Promise<UiScrollResult>;
2213 /**
2214 * Moves the focus ring of one of this plugin's sites onto an element it
2215 * drew there, as the DOM's `element.focus()`, while it holds the keys.
2216 *
2217 * Raised as the event `ui.focus`, origin `plugin`; the engine's inverse
2218 * marks the element. The keyboard is the person's to give: a site not
2219 * holding it, or holding it on another plugin's element, is `{ deny }`.
2220 *
2221 * @param args `requestId` (which site: a pane's id, the band's) and `key`
2222 * (the element's, as drawn)
2223 * @returns `{}` once it moved, or `{ deny }` saying why not
2224 * @example
2225 * onPress: () => $.ui.focus({ requestId: "files", key: "row:0" })
2226 */
2227 focus: (args: UiFocusArgs) => Promise<UiFocusResult>;
2228 };
2229 /**
2230 * Completions through the session's own client and credentials.
2231 */
2232 model: {
2233 /**
2234 * Runs one text completion through the session's own API client and
2235 * resolves to the reply's text.
2236 *
2237 * No tools, no history, no system prompt beyond the CLI's identity block
2238 * and `request.system`.
2239 *
2240 * @param request the model (an alias such as `haiku`, or a full id,
2241 * resolved like a `--model` value), the prompt, and a token cap
2242 * @returns the reply's text
2243 * @example
2244 * const reply = await $.model.complete({ model: "haiku", prompt: "Hi." })
2245 */
2246 complete: (request: ModelCompleteRequest) => Promise<string>;
2247 /**
2248 * Runs one tool-less completion over the session's OWN transcript, sharing
2249 * the main thread's prompt cache; the reply's text and the fork's usage.
2250 *
2251 * Not `complete`: sharing the cache prefix means the model and system
2252 * prompt are the session's, read from its last turn's cache-safe snapshot,
2253 * and tools are denied. Null on a cold snapshot or an API error.
2254 *
2255 * @param request the one user message the fork answers
2256 * @returns the reply's text with the fork's usage, or null on a cold
2257 * snapshot or an API error
2258 * @example
2259 * const reply = await $.model.fork({ prompt: "One line to learn?" })
2260 * if (reply !== null) $.ui.log(`${reply.usage.output_tokens} tokens`)
2261 */
2262 fork: (request: ModelForkRequest) => Promise<ModelForkResult | null>;
2263 /**
2264 * Picks one of `labels` for `text` with one completion over
2265 * `$.model.complete` and a fixed classifier prompt.
2266 *
2267 * `text` is data; the model answers with a label alone. It resolves
2268 * `undefined` when the answer named none of `labels`. A failed request,
2269 * an abort or a reply with no text rejects, naming the cause.
2270 *
2271 * @param text what to classify
2272 * @param labels the labels to choose from (2 or more)
2273 * @param options `model`: an alias or id; default the engine's small
2274 * fast model
2275 * @returns the label the model named, or undefined when it named none;
2276 * rejects when the request fails or the reply has no text
2277 * @example
2278 * const kind = await $.model.classify(e.text, ["bug", "feature"])
2279 * if (kind === undefined) return next(e)
2280 */
2281 classify: (text: string, labels: readonly string[], options?: ClassifyOptions) => Promise<string | undefined>;
2282 };
2283 /**
2284 * Sound: clip playback and platform speech.
2285 */
2286 audio: {
2287 /**
2288 * Plays one audio clip, starting now; clips are not queued, so two calls
2289 * play together (a bed under speech).
2290 *
2291 * `{ asset }` is the plugin's own file, loaded by the engine and played
2292 * through the platform's player (`afplay` on macOS). Resolves when
2293 * playback ends; rejects, naming the cause, when the clip cannot play.
2294 *
2295 * @param clip the plugin's own file (`{ asset }`), a URL the engine
2296 * fetches, or the bytes as base64 with their MIME type
2297 * @param options `shouldLoop`, `gain`, and an AbortSignal that stops the
2298 * clip
2299 */
2300 play: (clip: AudioClip, options?: PlayOptions) => Promise<void>;
2301 /**
2302 * Speaks `text` with the platform's own synthesizer (`say` on macOS).
2303 * Plain text.
2304 *
2305 * Utterances are queued among themselves; clips are not. Resolves when
2306 * the utterance has ended; rejects, naming the cause, when there is no
2307 * synthesizer, the voice is not installed, or the utterance failed.
2308 *
2309 * @param text what to say, as plain text
2310 * @param options `voice`: the system voice's exact name (`Samantha`);
2311 * absent, the synthesizer's default
2312 * @returns which synthesizer spoke, once the utterance has ended
2313 */
2314 speak: (text: string, options?: SpeakOptions) => Promise<SpeakResult>;
2315 };
2316 /**
2317 * The engine's connected MCP servers.
2318 */
2319 mcp: {
2320 /**
2321 * Calls `tool` on one of the engine's connected MCP servers with the
2322 * engine's own connection and credentials.
2323 *
2324 * A `cached` server is dialed on first use. No permission prompt: the
2325 * plugin's call, seen by the hooks above it, is the grant. Positional, not
2326 * the `{ tool: "mcp__server__tool", ... }` shape a `tool.call` hook sees.
2327 *
2328 * @param server the server's name as /mcp lists it (`claude.ai Gmail`;
2329 * the tool-name spelling `claude_ai_Gmail` is accepted too)
2330 * @param tool the tool's name on that server (`create_draft`)
2331 * @param args the tool's arguments; none when absent
2332 * @returns the tool's result as MCP returns it: `content` blocks and
2333 * `isError`
2334 * @example
2335 * const { content } = await $.mcp.call("claude.ai Gmail", "create_draft", {
2336 * to: "team@example.com",
2337 * subject: "Release notes",
2338 * })
2339 */
2340 call: (server: string, tool: string, args?: Record<string, unknown>) => Promise<McpToolResult>;
2341 };
2342 /**
2343 * The running session, read as plain data, and compacting it.
2344 */
2345 session: {
2346 /**
2347 * Returns the transcript so far, one entry per user or assistant
2348 * message; progress rows, `$.ui.log` lines and notices are not messages.
2349 *
2350 * Each entry is a SessionMessage, `{ role, text, toolUses }` (a user
2351 * message may add `toolResults`; a `toolUses` entry adds its `result` and
2352 * `text` once answered). A long transcript answers its newest 4096.
2353 *
2354 * @example
2355 * const last = (await $.session.messages()).at(-1)
2356 */
2357 messages: () => Promise<SessionMessage[]>;
2358 /**
2359 * Returns the directory the session runs in, absolute.
2360 */
2361 cwd: () => Promise<string>;
2362 /**
2363 * Returns the session's project root, absolute: where it started, or
2364 * where `/cd`, a host's directory change or a worktree move took it.
2365 *
2366 * A shell `cd` during the session does not move it; nested instruction
2367 * files are read only beneath it.
2368 */
2369 root: () => Promise<string>;
2370 /**
2371 * Returns the main loop's model, as `/model` shows it.
2372 */
2373 model: () => Promise<string>;
2374 /**
2375 * Returns how many prompts the user has sent this session (user turns in
2376 * the transcript).
2377 */
2378 turns: () => Promise<number>;
2379 /**
2380 * Returns the session's id (the transcript file's name).
2381 */
2382 id: () => Promise<string>;
2383 /**
2384 * Returns the git repository the session runs in, read from the working
2385 * copy on each call; null when the directory is not inside one.
2386 *
2387 * @example
2388 * const repo = await $.session.repo(); const publicRepo = !repo?.internal
2389 */
2390 repo: () => Promise<SessionRepo | null>;
2391 /**
2392 * Returns every surface the session draws on, each once: `terminal` under
2393 * the REPL first, then the remote ones in the order they attached.
2394 *
2395 * A session may draw on several at once (a terminal and two phones):
2396 * clients attach (`session.attach`) and detach, and a render hook still
2397 * reads `e.surface` per ask. Empty in a plain -p run; never rejects.
2398 *
2399 * @example
2400 * const inApp = (await $.session.surfaces()).some(s => s !== "terminal")
2401 */
2402 surfaces: () => Promise<readonly RenderSurface[]>;
2403 /**
2404 * Returns the first of `$.session.surfaces()`, or null where nothing
2405 * draws.
2406 *
2407 * @deprecated use `surfaces()`; a session may draw on several surfaces at
2408 * once
2409 */
2410 surface: () => Promise<RenderSurface | null>;
2411 /**
2412 * Returns the context window's fill, the rate-limit windows and the
2413 * cost, as the status line has them; with `breakdown`, by category too.
2414 *
2415 * The plain call costs nothing; `"full"` counts each category with the
2416 * token-count API as /context does, `"summary"` estimates locally, and
2417 * `context.breakdown` comes back in the SDK's `get_context_usage` shape.
2418 *
2419 * @param args `{ breakdown, columns }`: how the breakdown is counted and
2420 * the width its grid is drawn in; nothing for the status line's figures
2421 * @returns `{ context, rateLimits, cost }` as the status line has them
2422 * @example
2423 * const { context } = await $.session.usage()
2424 * if ((context.percent ?? 0) >= 85) await $.session.compact()
2425 * @example
2426 * const usage = await $.session.usage({ breakdown: "full", columns })
2427 * for (const row of usage.context.breakdown?.gridRows ?? []) draw(row)
2428 */
2429 usage: (args?: SessionUsageArgs) => Promise<SessionUsage>;
2430 /**
2431 * Returns the version of the engine the session runs on, the release it
2432 * is built from, and when it was built.
2433 *
2434 * The same three values the engine's own analytics rows carry, answered
2435 * in every mode and build; `base` is absent when the version is not
2436 * spelled as a release, `builtAt` in a run from source that stamps none.
2437 *
2438 * @returns `{ version, base, builtAt }`: the full version, its release
2439 * (`2.1.280`, or `2.1.280-dev` for a development build) and an
2440 * ISO 8601 build time
2441 * @example
2442 * const { version, base, builtAt } = await $.session.version()
2443 * row.env = { version, version_base: base, build_time: builtAt }
2444 * @example
2445 * const isDevelopmentBuild = (await $.session.version()).base?.endsWith("-dev")
2446 */
2447 version: () => Promise<SessionVersion>;
2448 /**
2449 * Compacts the conversation: the event `session.compact` with `trigger`
2450 * `plugin`, the same call `/compact` makes, between turns.
2451 *
2452 * It runs through every hook but the calling one, then core: a summary
2453 * and the kept messages in the transcript's place. Resolves `{ skip }`
2454 * when a hook vetoed it; rejects while a turn runs.
2455 *
2456 * @example
2457 * const { skip } = await $.session.compact({ instructions: "the plan" })
2458 */
2459 compact: EventCalls['session']['compact'];
2460 /**
2461 * Holds the session's Anthropic credential on the host and answers an
2462 * opaque handle and its kind; the secret never reaches the plugin.
2463 *
2464 * The handle is spent through `$.http.fetch(url, { auth: handle })`,
2465 * which sets the credential header, only for a first-party host. Null
2466 * where the build or the provider has no first-party credential to hold.
2467 *
2468 * @example
2469 * await $.http.fetch(url, { auth: (await $.session.authorize())?.handle })
2470 */
2471 authorize: () => Promise<SessionAuthorization>;
2472 };
2473 /**
2474 * The running model turn: ending it.
2475 */
2476 turn: {
2477 /**
2478 * Cancels the running model turn: the one whose id `turn.start` handed
2479 * this plugin, its running tools stopped, no interruption marker.
2480 *
2481 * The event `turn.abort`, seen by the hooks above; the prompt this
2482 * plugin submits next is the context. Rejects, naming both ids, when
2483 * `turnId` is not the running turn's; a hook may end its own turn.
2484 *
2485 * @param input `turnId`: the id `turn.start` carried
2486 * @example
2487 * on("turn.start", ($, e, next) => { held = e.turnId; return next(e) })
2488 */
2489 abort: (input: OpEventOf['turn.abort']) => Promise<void>;
2490 };
2491 /**
2492 * Submitting a prompt the model reads as a user turn, and the person's
2493 * prompt box: read as it stands, written, or proposed into.
2494 */
2495 prompt: {
2496 /**
2497 * Submits a prompt: the event `prompt.submit`, the same call the engine
2498 * makes for a typed prompt; `input.text` runs when the session is idle.
2499 *
2500 * It goes through every hook but the calling one (the plugin's others
2501 * see it) with `e.origin` `{ kind: 'plugin', name }`, the name the
2502 * model reads it under unless a hook leaves it out of its answer.
2503 *
2504 * @example
2505 * void $.prompt.submit({ text: "List the TODOs you just mentioned." })
2506 */
2507 submit: EventCalls['prompt']['submit'];
2508 /**
2509 * Returns the prompt box as it stands, the draft typed so far and the
2510 * cursor's offset into it, so a `fill` can keep what the person typed.
2511 *
2512 * Never rejects: `{ text: '', cursor: 0 }` where the session draws no box
2513 * (a -p run, an SDK host) or none is mounted yet.
2514 *
2515 * @example
2516 * const { text, cursor } = await $.prompt.read()
2517 */
2518 read: () => Promise<PromptBox>;
2519 /**
2520 * Puts `input.text` in the prompt box as the draft, by `mode`: `replace`
2521 * (the default) over it, `append` after it, `insert` at the cursor.
2522 *
2523 * The event `prompt.fill` through the other plugins' hooks; `isFilled:
2524 * false` under a dialog or headless. To hand the model text WITH the next
2525 * prompt instead, a `prompt.submit` hook adds `context` (second example).
2526 *
2527 * @example
2528 * await $.prompt.fill({ text: `> ${quote}\n`, mode: "insert" })
2529 * @example
2530 * ($, e, next) => next({ ...e, context: [...(e.context ?? []), hunk] })
2531 */
2532 fill: (input: PromptFillArgs) => Promise<PromptFilled>;
2533 /**
2534 * Proposes `input.text` as the prompt box's dim suggestion, Tab to take:
2535 * the event `prompt.suggest`, as the engine's own guess after a turn.
2536 *
2537 * It goes through every other plugin's hook with `e.origin` `{ kind:
2538 * 'plugin', name }`, the engine's own suggestions on or off; `{ isShown:
2539 * false }` while the box holds text, a turn runs, or headless (no box).
2540 *
2541 * @example
2542 * void $.prompt.suggest({ text: "run the tests you just wrote" })
2543 */
2544 suggest: EventCalls['prompt']['suggest'];
2545 /**
2546 * Returns the system prompt's sections for `facts`: the event
2547 * `prompt.compose`, the call the engine makes for every prompt it sends.
2548 *
2549 * A fact left out is the session's own (its model, its tools). Through
2550 * every other plugin's hook, over the engine's own composition; composed
2551 * for nobody to send, so nothing the session holds is written.
2552 *
2553 * @example
2554 * const ids = (await $.prompt.compose()).sections.map(s => s.id)
2555 */
2556 compose: EventCalls['prompt']['compose'];
2557 };
2558 /**
2559 * The tools the model has in this session, and running one.
2560 */
2561 tool: {
2562 /**
2563 * Returns the tools the model can call now, built-in and MCP alike, in
2564 * the order the model sees them.
2565 *
2566 * @example
2567 * const names = (await $.tool.list()).map(t => t.name)
2568 */
2569 list: () => Promise<ToolInfo[]>;
2570 /**
2571 * Calls a tool: the event `tool.call`, the same call the engine makes for
2572 * the model's tool calls, under a `tool_use_id` of its own.
2573 *
2574 * It runs through every hook but the calling one (the plugin's others
2575 * see it), the permission check and its dialog, then the tool. Rejects
2576 * when no tool has that name or the call is aborted.
2577 *
2578 * @example
2579 * const { text } = await $.tool.call({ tool: "Read", file_path: "a.md" })
2580 */
2581 call: EventCalls['tool']['call'];
2582 /**
2583 * Asks the engine's permission decision for a tool call now: the event
2584 * `tool.check`, resolved to `{ decision, reason?, rule? }`.
2585 *
2586 * The hooks run (the calling hook's own frame skipped, `next.origin` this
2587 * plugin, no `tool_use_id`); nothing runs, no dialog opens, no PreToolUse
2588 * hook or classifier is asked.
2589 *
2590 * @example
2591 * const { decision } = await $.tool.check({ tool: "Read", input })
2592 */
2593 check: EventCalls['tool']['check'];
2594 /**
2595 * Declares a tool the model can call from the next prompt on: the name,
2596 * description and input schema of `mcp__<plugin>__<name>`.
2597 *
2598 * Serve it with a `tool.call` hook on `{ tool: "mcp__<plugin>__<name>" }`
2599 * that returns the result (a call no hook answers fails); a name registered
2600 * again is replaced. Rejects until the session binds, at `session.start`.
2601 *
2602 * @param tool `name`, `description` (what the model reads), `inputSchema`
2603 * (a JSON schema object; default `{ type: "object" }`)
2604 * @returns `{ tool }`, the registered tool's full name
2605 * `mcp__<plugin>__<name>`
2606 * @example
2607 * await $.tool.register({ name: "weather", description: "Weather." })
2608 */
2609 register: (tool: ToolSpec) => Promise<OpValueOf['tool.register']>;
2610 };
2611 /**
2612 * The slash commands the person can run in this session, and running one.
2613 */
2614 command: {
2615 /**
2616 * Returns the slash commands the person can run now, built-in, plugin
2617 * and MCP alike, in the order the typeahead lists them.
2618 *
2619 * @example
2620 * const names = (await $.command.list()).map(c => c.name)
2621 */
2622 list: () => Promise<CommandInfo[]>;
2623 /**
2624 * Runs a slash command as if the person typed `/command args`: the
2625 * event `command.run`, queued and run once the session is idle.
2626 *
2627 * It runs through every hook but the calling one with `e.origin`
2628 * `{ kind: 'plugin', name }`, its lines in the transcript. Rejects an
2629 * unknown name, and inside a hook the turn is waiting on.
2630 *
2631 * @example
2632 * const { text } = await $.command.run({ command: "status" })
2633 */
2634 run: EventCalls['command']['run'];
2635 /**
2636 * Declares the slash command `/<name>` for this session, listed in the
2637 * typeahead from the next keystroke on.
2638 *
2639 * Serve it with a `command.run` hook on `{ command: "<name>" }` that
2640 * returns `{ text }`; a run no hook answers says so as its output.
2641 * Registering a name again replaces it; a built-in's name is refused.
2642 *
2643 * @param command `name`, `description` (what the menu shows),
2644 * `argumentHint` (dim after the name), `immediate` (runs mid-turn)
2645 * @returns `{ command }`, the registered name
2646 * @example
2647 * await $.command.register({ name: "hello", description: "Says hi." })
2648 */
2649 register: (command: CommandSpec) => Promise<OpValueOf['command.register']>;
2650 };
2651 /**
2652 * Every row of the settings menu (`/config`), the panel's own and each
2653 * enabled plugin's `userConfig` fields alike: listing and changing them.
2654 */
2655 config: {
2656 /**
2657 * Returns the rows the `/config` menu would draw now, in its order,
2658 * each with its current value, its kind, its owner and its lock.
2659 *
2660 * After every `config.describe` hook: a hidden row is left out, a
2661 * relabelled one carries the new label.
2662 *
2663 * @example
2664 * const theme = (await $.config.list()).find(row => row.key === "theme")
2665 */
2666 list: () => Promise<ConfigRow[]>;
2667 /**
2668 * Changes one row as if the person did in the menu: the event
2669 * `config.set` with `origin` `{ kind: 'plugin', name }`, then the writer.
2670 *
2671 * Through the other plugins' hooks, this plugin's own skipped; `{ deny }`
2672 * when a hook refused, the value does not fit, a trusted source owns the
2673 * row or only its dialog changes it. Rejects a key no row has.
2674 *
2675 * @param args `key` (as `list` names it) and `value` (the row's kind)
2676 * @returns `{ value }` once written, or `{ deny }`
2677 * @example
2678 * const { deny } = await $.config.set({ key: "verbose", value: true })
2679 */
2680 set: EventCalls['config']['set'];
2681 };
2682 /**
2683 * Subagents.
2684 */
2685 agent: {
2686 /**
2687 * Spawns a subagent: the event `agent.spawn`, the same call the engine
2688 * makes when the Agent tool starts one; the engine fills the rest.
2689 *
2690 * It runs every hook but the calling one, then the Agent tool in the
2691 * background under this call's origin: `{ model, agentId }` once the
2692 * subagent started (its answer is its `turn.complete`), or `{ deny }`.
2693 *
2694 * @example
2695 * const { agentId } = await $.agent.spawn({ prompt: "Read README.md." })
2696 */
2697 spawn: EventCalls['agent']['spawn'];
2698 /**
2699 * Returns the session's subagents so far, the ones the model spawned and
2700 * the ones plugins did alike.
2701 */
2702 list: () => Promise<AgentInfo[]>;
2703 /**
2704 * Defines an agent type the Agent tool dispatches from the next turn on,
2705 * named `<plugin>:<name>`: the event `agent.register`.
2706 *
2707 * Every field takes effect as in an agent file; re-registered, a name is
2708 * replaced; unloaded, a plugin's types go. `agent.offer` hides it from
2709 * the model alone; any plugin's `$.agent.spawn` answers to `agent.spawn`.
2710 *
2711 * @param spec `name`, `description` (when to delegate), `prompt` (its
2712 * system prompt), and any other field of an agent definition
2713 * @returns `{ agent }`, the full name; rejects until the session binds,
2714 * on a spec the schema refuses (its reason), on a hook's deny
2715 * @example
2716 * await $.agent.register({ name: "runner", description: "Runs a spec",
2717 * prompt: RUNNER_PROMPT, tools: ["Read", "Bash"], omitClaudeMd: true })
2718 * @example
2719 * // runner-only: hidden from the model, spawned by this plugin's tool,
2720 * // answered by the subagent's turn.complete (matched by agentId)
2721 * on("agent.offer", { agent: "lab:runner" }, () => ({ isOffered: false }))
2722 * on("tool.call", { tool: "mcp__lab__run" }, async ($, e) => {
2723 * const { agentId, deny } = await $.agent.spawn({
2724 * subagentType: "lab:runner", prompt: e.spec, description: "run" })
2725 * return { result: deny ?? (await answerOf(agentId)) }
2726 * })
2727 */
2728 register: (spec: AgentSpec) => Promise<OpValueOf['agent.register']>;
2729 };
2730 /**
2731 * The file system as the engine's own process reaches it; a relative path
2732 * is under the session's working directory, and text is UTF-8.
2733 *
2734 * An absolute path is used as given; where one may go is an `fs.*` hook's
2735 * to say. A read or write over 4 MiB rejects, a foreign network location
2736 * as spelled rejects untouched, and an OS refusal rejects with its errno.
2737 */
2738 fs: {
2739 /**
2740 * Reads a file and returns its text, or with `{ as: "bytes" }` its bytes
2741 * as `{ base64 }`.
2742 *
2743 * Rejects when missing, or over 4 MiB, which bounds what one read copies
2744 * into the plugin's environment. A file the plugin ships is under
2745 * `$.plugin.root`.
2746 *
2747 * @param path relative to the working directory, or absolute
2748 * @param options `as`: `"text"` (the default) or `"bytes"`
2749 * @returns the file's text, or `{ base64 }`
2750 * @example
2751 * const readme = await $.fs.read("README.md")
2752 * @example
2753 * const { base64 } = await $.fs.read(
2754 * `${$.plugin.root}/hooks/weights.bin`, { as: "bytes" })
2755 * const weights = Uint8Array.fromBase64(base64)
2756 */
2757 read: FsReadCall;
2758 /**
2759 * Writes `text` to a file, creating it and its directories as needed.
2760 *
2761 * @param path relative to the working directory, or absolute
2762 * @param text the whole new content
2763 */
2764 write: (path: string, text: string) => Promise<void>;
2765 /**
2766 * Lists a directory: `{ name, kind, size, isLink }` per entry, by name,
2767 * each entry as it stands (a symbolic link is `other` with `isLink`).
2768 *
2769 * @param path the directory's path; absent, the working directory
2770 * @returns the entries, `{ name, kind, size, isLink }` each
2771 */
2772 list: (path?: string) => Promise<FsEntry[]>;
2773 /**
2774 * Returns whether the path exists; rejects only a network location as
2775 * spelled, which no `fs` call reaches.
2776 */
2777 exists: (path: string) => Promise<boolean>;
2778 /**
2779 * Returns `{ kind, size, mtimeMs, isLink }` of the path: what it leads to,
2780 * and whether it is itself a symbolic link. Rejects when missing.
2781 *
2782 * With `{ resolve: true }` also `realPath`, where the path lands, absent
2783 * when it leads nowhere; a guard matches it and denies without it, since a
2784 * spelling it cannot resolve (`~`, a file not there yet) the tool may open.
2785 *
2786 * @param path relative to the working directory, or absolute
2787 * @param options `resolve`: also answer `realPath` (one more file system
2788 * call)
2789 * @returns the stat, `realPath` with it when asked and resolvable; rejects
2790 * `ENOENT` for a missing path
2791 * @example
2792 * // ROOT was resolved the same way and SEP is its separator; an
2793 * // allow-list under it is the robust guard, a deny-list on spellings
2794 * // only best effort (a hard link or a case alias keeps its own)
2795 * on("tool.call", { tool: "Read" }, async ($, e, next) => {
2796 * const stat = await $.fs.stat(e.file_path, { resolve: true })
2797 * .catch(() => undefined)
2798 * const real = stat?.realPath
2799 * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
2800 * return isInside ? next(e) : { deny: "outside the project" }
2801 * })
2802 * @example
2803 * // a Write may name a file not there yet: `placed` answers where the
2804 * // path lands or undefined, and the guard denies on undefined or
2805 * // outside ROOT. Unplaceable by spelling first, with no file system
2806 * // call (drive-relative `D:x`, a `\\` or `//` network or device path,
2807 * // a name that is empty, ".", ".." or itself `C:...`); then the file
2808 * // if it stats; else its folder, cut after the last separator and
2809 * // keeping it so a drive or share root stays that root, plus the name
2810 * const placed = async (path) => {
2811 * const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))
2812 * const name = path.slice(cut + 1)
2813 * const isPlaceable = !/^[A-Za-z]:(?![\\/])/.test(path) &&
2814 * !/^[\\/][\\/]/.test(path) && !/^[A-Za-z]:/.test(name) &&
2815 * name !== "" && name !== "." && name !== ".."
2816 * if (!isPlaceable) return undefined
2817 * const own = await $.fs.stat(path, { resolve: true })
2818 * .catch(() => undefined)
2819 * if (own) return own.realPath
2820 * const folder = cut < 0 ? "." : path.slice(0, cut + 1)
2821 * const dir = await $.fs.stat(folder, { resolve: true })
2822 * .catch(() => undefined)
2823 * return dir?.realPath === undefined ? undefined
2824 * : `${dir.realPath.replace(/[\\/]$/, "")}${SEP}${name}`
2825 * }
2826 * const real = await placed(e.file_path)
2827 * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
2828 * return isInside ? next(e) : { deny: "cannot place it, or outside" }
2829 */
2830 stat: (path: string, options?: FsStatOptions) => Promise<FsStat>;
2831 /**
2832 * Reads the named instruction files in every directory above the
2833 * session's original working directory, the way the engine reads CLAUDE.md.
2834 *
2835 * Root first, each `{ dir, name, content }` that exists, the content
2836 * with its `@include`s after it; `of` and `below` together are the
2837 * engine's own walk for a nested CLAUDE.md between root and read file.
2838 *
2839 * @param request `names`, relative `.md` file names (no `..`); `of`, the
2840 * file walked down to; `below`, the directory the walk stays inside
2841 * @returns the files found, root first
2842 * @example
2843 * const found = await $.fs.ancestors({ names: ["AGENTS.md"] })
2844 * const stack = await $.fs.ancestors({ names: ["AGENTS.md"], of: path })
2845 * const nested = await $.fs.ancestors({
2846 * names: ["AGENTS.md"],
2847 * of: e.file_path,
2848 * below: await $.session.root(),
2849 * })
2850 */
2851 ancestors: (request: FsAncestorsRequest) => Promise<readonly FsAncestor[]>;
2852 };
2853 /**
2854 * This plugin's own key-value store, kept between sessions and hot
2855 * reloads; values are JSON data.
2856 *
2857 * A JSON file of the plugin's own under the user's Claude Code
2858 * configuration directory.
2859 */
2860 store: {
2861 /**
2862 * Returns the value under `key`, or `undefined` when unset.
2863 *
2864 * @example
2865 * const count = Number((await $.store.get("count")) ?? 0) + 1
2866 */
2867 get: (key: string) => Promise<unknown>;
2868 /**
2869 * Sets `key` to `value`, which must be JSON data.
2870 *
2871 * `get` reads back `JSON.parse(JSON.stringify(value))`: a Date is its ISO
2872 * string, an `undefined` field is dropped, a Map or Set is `{}`. Rejects
2873 * a function, a cycle, or a store over 4 MiB of JSON text in all.
2874 */
2875 set: (key: string, value: unknown) => Promise<void>;
2876 /**
2877 * Removes `key` from the store.
2878 */
2879 delete: (key: string) => Promise<void>;
2880 /**
2881 * Returns every key set, in insertion order.
2882 */
2883 keys: () => Promise<string[]>;
2884 };
2885 /**
2886 * The time and timers, each an event through the host: `clock.now` reads
2887 * the time; `clock.sleep`, `after` and `every` wait until it has passed.
2888 *
2889 * A timer's callback is the plugin's own function, kept in its environment
2890 * and run there when the wait resolves; a hot reload of the plugin cancels
2891 * its pending waits with the old environment.
2892 */
2893 clock: {
2894 /**
2895 * Resolves milliseconds since the epoch, now.
2896 *
2897 * @example
2898 * const startedAt = await $.clock.now()
2899 */
2900 now: () => Promise<number>;
2901 /**
2902 * Resolves after `ms` milliseconds; rejects at once when `signal` aborts.
2903 *
2904 * @param ms how long, in milliseconds
2905 * @param options `signal`: ends the wait early with a rejection (pass
2906 * `next.signal` so a hook's wait ends with its dispatch)
2907 * @example
2908 * await $.clock.sleep(500, { signal: next.signal })
2909 */
2910 sleep: (ms: number, options?: SleepOptions) => Promise<void>;
2911 /**
2912 * Calls `fn` once after `ms` milliseconds; `cancel()` before then stops it.
2913 *
2914 * One `clock.after` dispatch: `fn` runs when it resolves, and never when
2915 * a hook refuses it.
2916 */
2917 after: TimerCall;
2918 /**
2919 * Calls `fn` every `ms` milliseconds (at least 1) until `cancel()`.
2920 *
2921 * One `clock.every` dispatch per period: `fn` runs when it resolves and
2922 * the next period is asked; a refused period ends the interval.
2923 *
2924 * @example
2925 * const tick = $.clock.every(1000, () => $.ui.status("polling"))
2926 */
2927 every: TimerCall;
2928 };
2929 /**
2930 * The network, through the host.
2931 */
2932 http: {
2933 /**
2934 * Fetches `url` through the host (never the plugin's own network) and
2935 * resolves `{ status, ok, headers, text }` once the body is read.
2936 *
2937 * http or https, to whatever the host process can reach, unless the
2938 * administrator's policy switches refuse it; an `auth` handle from
2939 * `$.session.authorize()` rides https only, to a first-party host.
2940 *
2941 * @param url the URL (http or https)
2942 * @param init `{ method, headers, body, auth, socketPath }` (body a
2943 * string; socketPath a Unix socket to go over instead of TCP)
2944 * @returns `{ status, ok, headers, text }` once the body is read
2945 * @example
2946 * const { ok, text } = await $.http.fetch("https://example.com/status")
2947 * @example
2948 * await $.http.fetch("http://bridge/reload", {
2949 * method: "POST",
2950 * socketPath: `${runDirectory}/bridge.sock`,
2951 * })
2952 */
2953 fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>;
2954 };
2955 /**
2956 * Commands on the host, run as the user the session runs as. CLI only.
2957 *
2958 * Local execution, not a network path: what a command of its own reaches
2959 * is its own, as for the Bash tool and a settings `command` hook.
2960 */
2961 process: {
2962 /**
2963 * Runs a command on the host by its argument vector (no shell) and
2964 * resolves `{ exitCode, stdout, stderr }` once it exits, any exit code.
2965 *
2966 * One shot: the whole output is read, so a background process left
2967 * writing holds the call until the timeout. Rejects when the command
2968 * cannot start or is still running then. Git runs with repo hooks off.
2969 *
2970 * @param argv the command and its arguments, `argv[0]` the executable
2971 * @param init `{ cwd, env, stdin, timeoutMs }` (cwd the session's by
2972 * default; timeout 30 s by default, ten minutes at most)
2973 * @returns `{ exitCode, stdout, stderr }` once the child exits
2974 * @example
2975 * const { exitCode, stdout } = await $.process.run(["git", "status"])
2976 */
2977 run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>;
2978 };
2979 /**
2980 * What the settings files, `--settings` and managed policy hold, as the
2981 * engine runs under it; read only.
2982 *
2983 * Every key crosses as the source holds it, `env` and the helper commands
2984 * included: nothing is filtered. The OAuth session and the global config
2985 * (~/.claude.json) are not settings and are never read.
2986 */
2987 settings: {
2988 /**
2989 * Resolves with the settings merged over every source, as the engine
2990 * reads them, or with one source's settings as loaded (`{ source }`).
2991 *
2992 * A snapshot in plain data each call; a source with no file answers
2993 * `{}`. The sources (SettingsSource) rise in precedence from `user` to
2994 * `policy`: the merge takes a key from the last source that has it.
2995 *
2996 * @param args `{ source }` to read one source; nothing for the merge
2997 * @returns the settings object, keyed as a settings.json is
2998 * @example
2999 * const { permissions } = await $.settings.read()
3000 * const policy = await $.settings.read({ source: "policy" })
3001 */
3002 read: (args?: SettingsReadArgs) => Promise<Settings>;
3003 };
3004 /**
3005 * The environment of this process, the one every Bash child, MCP server
3006 * and `$.process.run` command started after inherits.
3007 *
3008 * `get` and `set` take the variable's name as a string literal, so what a
3009 * module reads and writes is read off its source: `claude plugin validate`
3010 * lists the names, and a name the module does not spell is refused.
3011 */
3012 env: {
3013 /**
3014 * Resolves with the variable's value, or `undefined` when it is unset.
3015 *
3016 * `name` must be a string literal; `claude plugin validate` lists the
3017 * names your module reads and writes.
3018 *
3019 * @example
3020 * const home = await $.env.get("HOME")
3021 */
3022 get: (name: string) => Promise<string | undefined>;
3023 /**
3024 * Sets the variable for this process and everything it starts after, or
3025 * unsets it when `value` is `undefined`.
3026 *
3027 * `name` must be a string literal; `claude plugin validate` lists the
3028 * names your module reads and writes.
3029 *
3030 * @example
3031 * await $.env.set("GIT_PAGER", "cat")
3032 */
3033 set: (name: string, value: string | undefined) => Promise<void>;
3034 };
3035 }
3036
3037 /**
3038 * The name of an event the engine defines itself (a key of CoreEventOf);
3039 * EventName adds the declared plugin nouns' events.
3040 */
3041 type CoreEventName = keyof CoreEventOf;
3042
3043 /**
3044 * The argument of each event the engine defines itself: its call sites'
3045 * (EngineEventOf), the classic hooks' (ClassicEventOf), the calls on `$`.
3046 */
3047 type CoreEventOf = EngineEventOf & ClassicEventOf & OpEventOf;
3048
3049 type CwdChangedHookInput = BaseHookInput & {
3050 hook_event_name: 'CwdChanged';
3051 old_cwd: string;
3052 new_cwd: string;
3053 };
3054
3055 type DirectoryAddedHookInput = BaseHookInput & {
3056 hook_event_name: 'DirectoryAdded';
3057 /**
3058 * Absolute path of the directory that was added.
3059 */
3060 directory: string;
3061 /**
3062 * How the directory was added: "slash_command" for /add-dir, "register_repo_root" for the SDK control_request.
3063 */
3064 source: 'slash_command' | 'register_repo_root';
3065 };
3066
3067 /**
3068 * The `children` field every element constructor's props carry, appended
3069 * beside its own props type: one child, or a list that may nest.
3070 *
3071 * JSX types a lone child as the child itself (`<Text dimColor>done</Text>`
3072 * passes the string, `<Text>{count}</Text>` the number), and a mapped list
3073 * beside a sibling as a nested list (`<Box>{rows.map(row)}<Text>ok</Text>`).
3074 */
3075 export type ElementChildren = {
3076 children?: RenderChildren;
3077 };
3078
3079 /**
3080 * An element as `$.ui.resolve(e)` hands it out: a constructor from props to
3081 * the frozen plain-data element, `children` among the props as JSX passes.
3082 *
3083 * `const { Box } = $.ui.resolve(e)` then `<Box gap={1}>...</Box>` compiles to
3084 * `h(Box, { gap: 1 }, ...children)`, and `h` calls a function tag with its
3085 * props, so the table's constructors are the JSX tags.
3086 */
3087 export type ElementConstructor<P> = (props: P & ElementChildren) => RenderElement;
3088
3089 /**
3090 * Every element name of every surface: what a table handed out is completed to
3091 * (an omitted one draws a fragment; see `ui.resolve`).
3092 */
3093 export type ElementName = {
3094 [P in RenderSurface]: keyof Elements[P];
3095 }[RenderSurface];
3096
3097 /**
3098 * The element constructors each surface draws, by `e.surface`: what
3099 * `$.ui.resolve(e)` returns and a `ui.resolve` hook passes on; no globals.
3100 *
3101 * All carry `Box`, `Text`, `Button`, `Link`, `Code`, `Markdown`; every remote
3102 * surface `Svg`; all but mobile `Input` and `Select`; terminal and desktop
3103 * `Client`; terminal `Raster` and `Image`. Narrowed on `e.surface`, that table.
3104 */
3105 export type Elements = {
3106 terminal: {
3107 Box: ElementConstructor<BoxProps>;
3108 Text: ElementConstructor<TextProps>;
3109 Button: ElementConstructor<ButtonProps>;
3110 Input: ElementConstructor<InputProps>;
3111 Select: ElementConstructor<SelectProps>;
3112 Link: ElementConstructor<LinkProps>;
3113 Code: ElementConstructor<CodeProps>;
3114 Markdown: ElementConstructor<MarkdownProps>;
3115 /**
3116 * A region one of the plugin's surface modules draws (ClientModule), named
3117 * by `module`: a string literal, the module's path relative to this file.
3118 *
3119 * The engine reads the surface module off the hooks module's source
3120 * before anything runs, so a variable, a template with a substitution or
3121 * a computed path as `module` is refused at load, naming the line.
3122 */
3123 Client: ElementConstructor<ClientProps>;
3124 Raster: ElementConstructor<RasterProps>;
3125 Image: ElementConstructor<ImageProps>;
3126 };
3127 desktop: {
3128 Box: ElementConstructor<BoxProps>;
3129 Text: ElementConstructor<TextProps>;
3130 Button: ElementConstructor<ButtonProps>;
3131 Input: ElementConstructor<InputProps>;
3132 Select: ElementConstructor<SelectProps>;
3133 Svg: ElementConstructor<SvgProps>;
3134 Link: ElementConstructor<LinkProps>;
3135 Code: ElementConstructor<CodeProps>;
3136 Markdown: ElementConstructor<MarkdownProps>;
3137 Client: ElementConstructor<ClientProps>;
3138 };
3139 /**
3140 * No `Input` or `Select`: the control protocol carries presses (ui_press)
3141 * but no ui_input or ui_select yet; not a limit of the device.
3142 *
3143 * The table grows when those messages exist.
3144 */
3145 mobile: {
3146 Box: ElementConstructor<BoxProps>;
3147 Text: ElementConstructor<TextProps>;
3148 Button: ElementConstructor<ButtonProps>;
3149 Svg: ElementConstructor<SvgProps>;
3150 Link: ElementConstructor<LinkProps>;
3151 Code: ElementConstructor<CodeProps>;
3152 Markdown: ElementConstructor<MarkdownProps>;
3153 };
3154 /**
3155 * The desktop's table without `Client`: a remote `Client`'s module, presses
3156 * and posts (ui_client_module, ui_client_press, ui_message) name no surface.
3157 *
3158 * They are the desktop's alone today, not a limit of the editor's webview:
3159 * the table gains `Client` when those asks name a surface.
3160 */
3161 vscode: {
3162 Box: ElementConstructor<BoxProps>;
3163 Text: ElementConstructor<TextProps>;
3164 Button: ElementConstructor<ButtonProps>;
3165 Input: ElementConstructor<InputProps>;
3166 Select: ElementConstructor<SelectProps>;
3167 Svg: ElementConstructor<SvgProps>;
3168 Link: ElementConstructor<LinkProps>;
3169 Code: ElementConstructor<CodeProps>;
3170 Markdown: ElementConstructor<MarkdownProps>;
3171 };
3172 };
3173
3174 /**
3175 * The table `ui.resolve` answers for an argument of surface `P`.
3176 */
3177 export type ElementTable<P extends RenderSurface = RenderSurface> = Elements[P];
3178
3179 /**
3180 * Hook input for the Elicitation event. Fired when an MCP server requests user input. Hooks can auto-respond (accept/decline) instead of showing the dialog.
3181 */
3182 type ElicitationHookInput = BaseHookInput & {
3183 hook_event_name: 'Elicitation';
3184 mcp_server_name: string;
3185 message: string;
3186 mode?: 'form' | 'url';
3187 url?: string;
3188 elicitation_id?: string;
3189 requested_schema?: Record<string, unknown>;
3190 };
3191
3192 /**
3193 * Hook input for the ElicitationResult event. Fired after the user responds to an MCP elicitation. Hooks can observe or override the response before it is sent to the server.
3194 */
3195 type ElicitationResultHookInput = BaseHookInput & {
3196 hook_event_name: 'ElicitationResult';
3197 mcp_server_name: string;
3198 elicitation_id?: string;
3199 mode?: 'form' | 'url';
3200 action: 'accept' | 'decline' | 'cancel';
3201 content?: Record<string, unknown>;
3202 };
3203
3204 /**
3205 * The input of `engine.create`: the fold that builds `$`, once per load,
3206 * core innermost.
3207 *
3208 * A hook is written in post-order: `const built = await next(e)` is `$` as
3209 * built so far; `return { ...built, voice: { say } }` adds this plugin's noun.
3210 * See EngineEventOf's `engine.create` for what a step may and may not do.
3211 */
3212 export type EngineCreateInput = {
3213 /**
3214 * The modules this fold builds, in list order, first outermost (managed
3215 * plugins first, so an org plugin's withholding wins).
3216 *
3217 * The whole set at a load, this plugin alone at its reload, the ones added
3218 * or changed at a refresh that keeps the rest: a module added later that
3219 * does not hook this event is built against the table as it stands.
3220 */
3221 plugins: readonly string[];
3222 };
3223
3224 /**
3225 * What an `engine.create` hook returns: `$` as built so far with this
3226 * plugin's nouns added, less any it withheld.
3227 *
3228 * Every declared noun is optional here. Between hooks it crosses the chain
3229 * as interface descriptors; a hook sees objects (EngineInterfaceBuilt).
3230 */
3231 export type EngineCreateResult = Partial<EngineInterface> & {
3232 readonly [noun: string]: unknown;
3233 };
3234
3235 /**
3236 * The events the engine raises at its call sites, and `engine.create`; the
3237 * classic settings hooks' events are ClassicEventOf.
3238 *
3239 * At every one, a hook that fails (throws, overruns its budget: HookBudget,
3240 * answers a wrong shape) is skipped: the hooks beneath and core run in its
3241 * place, or its last `next` result stands; the failure is reported by name.
3242 */
3243 export type EngineEventOf = {
3244 /**
3245 * Fires when the engine is about to run a tool. `next(e)` runs the hooks
3246 * beneath, then core (the permission prompt, the tool itself).
3247 *
3248 * Return `{ deny: reason }` to refuse or `{ result }` to answer yourself; a
3249 * hook that returns while its `next` is pending aborts what runs beneath.
3250 * The managed-settings hooks run first: their deny is the call's result.
3251 */
3252 'tool.call': ToolCallInput;
3253 /**
3254 * Fires when the engine decides whether a tool call may run, after the
3255 * `tool.call` and PreToolUse hooks and before the mode settles an ask.
3256 *
3257 * `next(e)` resolves to the engine's verdict (rules, mode, the tool's own
3258 * check, PreToolUse's decision); return any `{ decision }`. `$.tool.check`
3259 * runs the same chain and executes nothing.
3260 *
3261 * @example
3262 * on("tool.check", { tool: "Read" }, () => ({ decision: "allow" }))
3263 */
3264 'tool.check': ToolCheckInput;
3265 /**
3266 * Fires when the engine is about to draw a component: once per input value
3267 * (props, viewport width), plugin load or `$.ui.invalidate("ui.render")`.
3268 *
3269 * A repaint reuses the answer; a clock invalidates. `next(e)` resolves to the
3270 * drawing: return it, wrap it, draw your own, or rewrite `props`. A tree that
3271 * does not validate draws the engine's own; `--plugin-dir` is told why.
3272 */
3273 'ui.render': RenderInput;
3274 /**
3275 * Fires when the plugins load (not per draw), once per surface, component
3276 * and plugin: `e` names the surface and component, never the props.
3277 *
3278 * `next(e)` resolves to the surface's table, which `$.ui.resolve(e)` then
3279 * reads. Return it, one with an element restyled for every other plugin,
3280 * or one with a key left out (a fragment there); own table: hook skipped.
3281 */
3282 'ui.resolve': ResolveInput;
3283 /**
3284 * Fires when a `Button` a render hook drew is pressed on a surface; `e` is
3285 * `{ plugin, element, component, surface }`, `element` the button's `key`.
3286 *
3287 * `next(e)` runs the hooks beneath, then core: the element's own `onPress`
3288 * closure, in its plugin's environment, resolving to `{ element }`. Return
3289 * `next(e)` to let the press through, or `{ element }` to take it.
3290 */
3291 'ui.press': UiPressArgument;
3292 /**
3293 * Fires when an `Input` a render hook drew changes or is submitted; `e` is
3294 * `{ plugin, element, component, surface, kind, value }`.
3295 *
3296 * `next(e)` runs the hooks beneath, then the element's own `onInput` or
3297 * `onSubmit` with `e.value` as the chain left it, resolving to `{ element,
3298 * value }`; `next({ ...e, value })` rewrites the typing, an answer takes it.
3299 */
3300 'ui.input': UiInputArgument;
3301 /**
3302 * Fires when a `Select` a render hook drew is picked from; `e` is
3303 * `{ plugin, element, component, surface, value }`.
3304 *
3305 * `next(e)` runs the hooks beneath, then the element's own `onSelect` with
3306 * `e.value` as the chain left it, resolving to `{ element, value }`;
3307 * `next({ ...e, value })` rewrites the pick, an answer takes it.
3308 */
3309 'ui.select': UiSelectArgument;
3310 /**
3311 * Fires when a `Client` THIS plugin drew posts from its surface module
3312 * (`surface.post(data)`); only this plugin's hooks see it.
3313 *
3314 * `next.origin` names `client`: `data` came from code. Core answers `{}`;
3315 * `next({ ...e, data })` rewrites the data; `{ props }` hands the posting
3316 * instance its next props without a redraw. One per instance per frame.
3317 */
3318 'ui.message': UiMessageArgument;
3319 /**
3320 * Fires before a site's window moves: the person's wheel or scroll keys on
3321 * a `Pane` body or the `AbovePrompt` band, at its edges too; `$.ui.scroll`.
3322 *
3323 * `next(e)` moves it to `e.offset` and draws: `{}`; `next({ ...e, offset
3324 * })` elsewhere; no `next` (`{}` or `{ deny }`) leaves it undrawn, so a hook
3325 * drawing its own rows under a header moves them by `e.by` and invalidates.
3326 *
3327 * @example
3328 * on("ui.scroll", { requestId: "log" }, ($, e) => (scrollOwnRows(e.by), {}))
3329 */
3330 'ui.scroll': UiScrollInput;
3331 /**
3332 * Fires before a site's focus ring moves: the person's Tab, arrows or click
3333 * in a `Pane` or the band; an `autoFocus` element taking it; `$.ui.focus`.
3334 *
3335 * `next(e)` lands it on `e.element` (absent: one of the engine's stops) and
3336 * draws: `{}`; `next({ ...e, element })` on another of `e.plugin`'s; no
3337 * `next` (`{}` or `{ deny }`) keeps it where it was, drawn as it was.
3338 *
3339 * @example
3340 * on("ui.focus", { requestId: "list" }, ($, e, next) => (mark(e), next(e)))
3341 */
3342 'ui.focus': UiFocusInput;
3343 /**
3344 * Fires when the engine offers an agent type to the model, in the agent
3345 * listing and again at dispatch; `next(e)` resolves to `{ isOffered: true }`.
3346 *
3347 * Return `{ isOffered: false }` to keep the type out of the listing and
3348 * refuse its dispatch. A hook that fails passes it through.
3349 *
3350 * @example
3351 * on("agent.offer", { agent: "Plan" }, () => ({ isOffered: false }))
3352 */
3353 'agent.offer': AgentOfferInput;
3354 /**
3355 * Fires when the Agent tool is about to start a subagent, everything
3356 * decided and its model not yet resolved.
3357 *
3358 * `next(e)` resolves to `{ model }`. Return it, `next({ ...e, model })`,
3359 * `{ model }` of your own (an alias resolves like the tool's parameter), or
3360 * `{ deny: reason }`.
3361 */
3362 'agent.spawn': AgentSpawnInput;
3363 /**
3364 * Fires when a prompt is submitted, before the turn starts. `next(e)` runs
3365 * the hooks beneath and the UserPromptSubmit settings hooks.
3366 *
3367 * Rewrite with `next({ ...e, text })` (the user message on screen follows)
3368 * or stop it with `{ drop: reason }`; a broken plugin never blocks a prompt.
3369 * A prompt typed while a turn ran fires at Enter, with that turn's id.
3370 */
3371 'prompt.submit': PromptSubmitInput;
3372 /**
3373 * Fires when a text is about to be put in the prompt box as the person's
3374 * draft (a plugin's `$.prompt.fill`); `next(e)` writes it by `e.mode`.
3375 *
3376 * `replace` over the draft, `append` after it, `insert` at the cursor;
3377 * rewrite `text` or `mode` going down, or answer `{ isFilled: false }`
3378 * without `next` to keep it out, as core does under a dialog or headless.
3379 *
3380 * @example
3381 * on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
3382 */
3383 'prompt.fill': PromptFillInput;
3384 /**
3385 * Fires when a text is proposed as the prompt box's dim suggestion, Tab to
3386 * take: the engine's guess after a turn, or a plugin's `$.prompt.suggest`.
3387 *
3388 * `next(e)` shows it: `{ isShown }`. Rewrite with `next({ ...e, text })`,
3389 * or answer `{ isShown: false }` without `next` to drop it; core answers
3390 * that too while the box holds text or a turn runs.
3391 *
3392 * @example
3393 * on("prompt.suggest", { origin: { kind: "suggestion" } }, hide)
3394 */
3395 'prompt.suggest': PromptSuggestInput;
3396 /**
3397 * Fires when the person edits the main prompt box: a key the editor took as
3398 * an edit, or a paste; `next(e)` resolves the box the editor shows.
3399 *
3400 * `e` is the draft before and the splice (`start`, `end`, `inputText`); a
3401 * burst of keys is one edit. Rewrite `inputText` going down or the box
3402 * coming up; `{ text: e.text, cursor: e.cursor }` without `next` consumes.
3403 *
3404 * @example
3405 * on("prompt.edit", ($, e, next) => next({ ...e, inputText: up(e) }))
3406 */
3407 'prompt.edit': PromptEditInput;
3408 /**
3409 * Fires once per named section of the system prompt, when the engine
3410 * assembles it; `next(e)` resolves to `{ text }` as core computed it.
3411 *
3412 * Sections are cached by name for the session until
3413 * `$.ui.invalidate("prompt.section")`: an unstable answer spends the
3414 * model's prompt cache on every call. A hook that fails passes it through.
3415 *
3416 * @example
3417 * on("prompt.section", { name: "memory" }, () => ({ text: null }))
3418 */
3419 'prompt.section': PromptSectionInput;
3420 /**
3421 * Fires once per conversation, when the engine computes the context blocks
3422 * its first user message carries; `next(e)` resolves to `{ blocks }`.
3423 *
3424 * Append, drop, reorder or rewrite with `next({ ...e, blocks })`; the
3425 * engine renders what comes back, in order, until
3426 * `$.ui.invalidate("prompt.context")` or a re-read (compaction, `/clear`).
3427 *
3428 * @example
3429 * on("prompt.context", () => ({ blocks: [] }))
3430 */
3431 'prompt.context': PromptContextInput;
3432 /**
3433 * Fires when the engine renders a system prompt; `next(e)` resolves to
3434 * `{ sections }`, each `{ id, text, scope }`, in the order they are sent.
3435 *
3436 * The bottom is the engine's own composition (`intro`, `tools`, `memory`,
3437 * ...). Append, replace by id, reorder or drop what `next(e)` answered;
3438 * answer without `next` to replace it all. The engine places each cache mark.
3439 *
3440 * @example
3441 * on("prompt.compose", async ($, e, next) => dropped(await next(e), "tone"))
3442 */
3443 'prompt.compose': PromptComposeInput;
3444 /**
3445 * Fires once per message the engine injects for the model on its own (a
3446 * reminder, a mode transition, a mentioned file), as a request carries it.
3447 *
3448 * `next(e)` resolves to `{ text }`; `{ text: null }` leaves it out. The
3449 * answer holds per attachment for the process (asked again on resume or
3450 * `$.ui.invalidate`); the transcript keeps the engine's record.
3451 *
3452 * @example
3453 * on("prompt.attachment", { type: "todo_reminder" }, () => ({ text: null }))
3454 */
3455 'prompt.attachment': PromptAttachmentInput;
3456 /**
3457 * Fires once per tool, when the engine first renders the tool's schema in
3458 * a session; `next(e)` resolves to `{ description, isDeferred? }`.
3459 *
3460 * Cached for the session until `$.ui.invalidate("tool.describe")`: an
3461 * unstable answer spends the model's prompt cache. An explicit `isDeferred`
3462 * moves the tool behind ToolSearch (true) or into the prompt's list (false).
3463 *
3464 * @example
3465 * on("tool.describe", { tool: "Bash" }, ($, e) => ({ ...e, description }))
3466 * @example
3467 * on("tool.describe", { tool: "Monitor" }, pin) // {...e, isDeferred: false}
3468 */
3469 'tool.describe': ToolDescribeInput;
3470 /**
3471 * Fires when a slash command is about to run (`/name args` typed, or a
3472 * plugin's `$.command.run`); `next(e)` resolves to `{ text }`, its output.
3473 *
3474 * Core is the engine's command (a registered one has none). Rewrite `args`
3475 * with `next`, or return `{ text }` without it to answer in its place; one
3476 * after `next` replaces a printed output, not a panel or prompt it opened.
3477 *
3478 * @example
3479 * on("command.run", { command: "hello" }, () => ({ text: "hello" }))
3480 */
3481 'command.run': CommandRunInput;
3482 /**
3483 * Fires once per command, when the engine lists it for the typeahead and
3484 * `/help`; `next(e)` resolves to `{ description, argumentHint, isHidden }`.
3485 *
3486 * Listed answers are cached for the session until
3487 * `$.ui.invalidate("command.describe")`. A hook that fails passes it
3488 * through.
3489 *
3490 * @example
3491 * on("command.describe", ($, e, next) => next({ ...e, isHidden: true }))
3492 */
3493 'command.describe': CommandDescribeInput;
3494 /**
3495 * Fires when a `/config` row is about to change, from the menu or a
3496 * plugin's `$.config.set`; `next(e)` resolves to `{ value }` once written.
3497 *
3498 * Return `{ deny: reason }` to leave the row as it is (the menu says why),
3499 * or `next({ ...e, value })` to clamp it; a value of the wrong kind for
3500 * the row is refused. A row a trusted source owns is core's to refuse.
3501 *
3502 * @example
3503 * on("config.set", { key: "theme" }, () => ({ deny: "the theme stays" }))
3504 */
3505 'config.set': ConfigSetInput;
3506 /**
3507 * Fires once per `/config` row, when the menu lists it and for
3508 * `$.config.list`; `next(e)` resolves to `{ label, description, isHidden }`.
3509 *
3510 * Relabel, re-describe or hide with `next({ ...e, isHidden: true })`; the
3511 * answers are cached until `$.ui.invalidate("config.describe")` or the
3512 * loaded plugins change. A hook that fails passes the row through.
3513 *
3514 * @example
3515 * on("config.describe", { key: "tips" }, hide) // answers isHidden: true
3516 */
3517 'config.describe': ConfigDescribeInput;
3518 /**
3519 * Fires when the engine expands a skill's prompt for the model (`/name`,
3520 * the Skill tool, a preload); `next(e)` resolves to `{ text }` as computed.
3521 *
3522 * Return `{ text }` with the text the model reads instead. A hook that
3523 * fails passes it through.
3524 *
3525 * @example
3526 * on("skill.prompt", { skill: "commit" }, () => ({ text: "A haiku." }))
3527 */
3528 'skill.prompt': SkillPromptInput;
3529 /**
3530 * Fires when the engine composes a git text the model is to write (`kind`:
3531 * `commit`, `pr`, `exemption`, `remedy`); `next(e)` resolves to `{ text }`.
3532 *
3533 * Return `{ text }` with the text the model reads instead. A hook that
3534 * fails passes it through.
3535 *
3536 * @example
3537 * on("attribution.text", { kind: "commit" }, () => ({ text: "" }))
3538 */
3539 'attribution.text': AttributionTextInput;
3540 /**
3541 * Fires once per process for each loaded plugin, before the first prompt,
3542 * then once per fresh load of one (never `/clear`); `next(e)` is `{ cwd }`.
3543 *
3544 * Observe. The first is awaited: a `$.tool.register` is listed by turn one.
3545 * A later one runs its hooks alone: an enable, a worker respawn, or a reload
3546 * (changed modules only; all if one hooks `engine.create`/`plugin.register`).
3547 *
3548 * @example
3549 * on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
3550 */
3551 'session.start': SessionStartInput;
3552 /**
3553 * Fires when a delivery reaches the session (a relay's event, a peer's
3554 * message, a Remote Control prompt), before it is queued; `{ text }`.
3555 *
3556 * Rewrite with `next({ ...e, text })`, or return `{ consumed: reason }` to
3557 * take it: nothing is queued, shown or read by the model. `origin` and
3558 * `event` pass on as received; `session.send`, its dual, is reserved.
3559 *
3560 * @example
3561 * on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
3562 */
3563 'session.receive': SessionReceiveInput;
3564 /**
3565 * Fires when the conversation is about to be compacted (`/compact`, the
3566 * threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
3567 *
3568 * Rewrite `instructions` or `messages` on the way down, the messages on
3569 * the way up, or answer `{ messages }` of your own; `{ skip: reason }`
3570 * leaves the conversation as it is. `trigger` passes on as received.
3571 *
3572 * @example
3573 * on("session.compact", { trigger: "precompute" }, () => ({ skip: "off" }))
3574 */
3575 'session.compact': SessionCompactInput;
3576 /**
3577 * Fires when a remote client joins the session's roster of attached
3578 * surfaces: it said so (ui_attach), or it first asked to draw.
3579 *
3580 * Observe (a phone joined: draw the lobby); `next(e)` resolves to
3581 * `{ clientId }`, a different return changes nothing. `$.session.surfaces()`
3582 * reads the roster; a render hook still reads `e.surface` per ask.
3583 *
3584 * @example
3585 * on("session.attach", { surface: "mobile" }, ($, e, next) => next(e))
3586 */
3587 'session.attach': SessionAttachInput;
3588 /**
3589 * Fires when a client leaves the roster: it detached, or the session ended
3590 * with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
3591 */
3592 'session.detach': SessionDetachInput;
3593 /**
3594 * Fires when the engine measures the session and a unit moved: after each
3595 * main-thread turn, and when a rate-limit window moves a whole point.
3596 *
3597 * Observe; `next(e)` echoes `{ changed }`. `$.session.usage()`'s figures,
3598 * pushed, not polled: compare them with your own threshold here, call the
3599 * op for the breakdown. One at a time, a burst folding into one more.
3600 *
3601 * @example
3602 * on("session.measure", ($, e, next) => (toastPast90(e.rateLimits), next(e)))
3603 */
3604 'session.measure': SessionMeasureInput;
3605 /**
3606 * Fires once when the session ends (exit, /clear, resume, logout, signal, a
3607 * `-p` run done), after its SessionEnd settings hooks; `e.reason` says which.
3608 *
3609 * `e.resume.id` is `--resume`'s id; `next(e)` runs the engine's end step for
3610 * the plugins (at an exit the attached clients leave): `{ sessionId }`. The
3611 * SessionEnd bound afresh, 1.5 s by default; a `kill -9` raises nothing.
3612 *
3613 * @example
3614 * on("session.end", async ($, e, next) => (await keep(e.resume), next(e)))
3615 */
3616 'session.end': SessionEndInput;
3617 /**
3618 * Fires once per hooks module about to join the chain, at load (the set
3619 * folded and built, nothing swapped in) and at reload; core allows.
3620 *
3621 * Return `{ refuse: reason }` and it never joins: no hook, no noun, no tool
3622 * of it; the transcript names who refused. Its judges, `$` whole, are the
3623 * plugins admitted before it and the binary's; judge by `tier` and `uses`.
3624 *
3625 * @example
3626 * on("plugin.register", { tier: "user" }, () => ({ refuse: "managed only" }))
3627 */
3628 'plugin.register': PluginRegisterInput;
3629 /**
3630 * Fires when a model turn begins, before its first model call; `next(e)`
3631 * resolves to `{ turnId }`. Observe: a different return changes nothing.
3632 */
3633 'turn.start': TurnStartInput;
3634 /**
3635 * Fires when the engine is about to send a model request of a turn, main's
3636 * or a subagent's (`e.agentId`); `next(e)` resolves to the whole response.
3637 *
3638 * `next({ ...e, model })` or `effort` sends another; the turn, the index and
3639 * the message count are pinned. An answer without `next` sends no request.
3640 * It streams (StreamNext): the hook's budget counts its own code alone.
3641 */
3642 'turn.step': TurnStepInput;
3643 /**
3644 * Fires when a model turn has ended, at the point its duration is reported;
3645 * `next(e)` resolves to `{ text }`, the answer. `e.reason` says why.
3646 *
3647 * Return `{ text }` with a different text to show it beneath the answer (a
3648 * synopsis, a TL;DR line); the transcript's record is never rewritten. A
3649 * hook that fails leaves the answer as it was.
3650 */
3651 'turn.complete': TurnCompleteInput;
3652 /**
3653 * Runs while `$` is being built, once per load or reload of this plugin
3654 * and before any other hook of it; `next(e)` resolves to `$` built so far.
3655 *
3656 * A step may ADD nouns and WITHHOLD nouns (leave one out, or return without
3657 * `next`); it may NOT REPLACE one another step added: the step fails, named
3658 * with both plugins. A step that fails unloads its plugin; `$` is rebuilt.
3659 */
3660 'engine.create': EngineCreateInput;
3661 };
3662
3663 /**
3664 * `$`, the first parameter of every hook. Frozen; core's interface plus
3665 * every noun the plugins' `engine.create` steps added.
3666 *
3667 * Flat, `<noun>.<event>`; it does not carry `on`, since registration happens
3668 * before `$` exists. An interface so a plugin types the noun it provides by
3669 * declaration merging, the way a jQuery plugin types `$.fn`.
3670 *
3671 * @example
3672 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
3673 */
3674 export interface EngineInterface extends CoreEngineInterface {
3675 }
3676
3677 /**
3678 * What `next(e)` resolves to at `engine.create`: `$` as the steps beneath
3679 * built it, typed as `$` is, open to nouns no declaration names yet.
3680 *
3681 * A withheld noun is on it as a stub (a step inside withheld it, or the
3682 * last fold did and this is a reload), and the host refuses an op on one a
3683 * step outside withholds later; a typed module bootstraps at load on it.
3684 */
3685 export type EngineInterfaceBuilt = EngineInterface & {
3686 readonly [noun: string]: unknown;
3687 };
3688
3689 /**
3690 * The engine's events' results.
3691 */
3692 export type EngineResultOf = {
3693 /**
3694 * `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`.
3695 */
3696 'tool.call': ToolCallResult;
3697 /**
3698 * `{ decision, reason?, rule? }`.
3699 */
3700 'tool.check': ToolCheckResult;
3701 /**
3702 * The tree to draw; `{ type: "engine", ref }` is core's own drawing.
3703 */
3704 'ui.render': RenderElement;
3705 /**
3706 * The surface's element table (Elements[e.surface]): constructors from props
3707 * to a RenderElement.
3708 */
3709 'ui.resolve': ElementTable;
3710 /**
3711 * `{ element }`: the element whose handler the press reached.
3712 */
3713 'ui.press': UiPressResult;
3714 /**
3715 * `{ element, value }`: the field whose handler the input reached, and
3716 * the text it received.
3717 */
3718 'ui.input': UiInputResult;
3719 /**
3720 * `{ element, value }`: the picker whose handler the pick reached, and
3721 * the value it received.
3722 */
3723 'ui.select': UiSelectResult;
3724 /**
3725 * `{ props? }`: the posting instance's next props, when a hook hands some.
3726 */
3727 'ui.message': UiMessageResult;
3728 /**
3729 * `{}` once the window moved, or `{ deny }`.
3730 */
3731 'ui.scroll': UiScrollResult;
3732 /**
3733 * `{}` once the ring moved, or `{ deny }`.
3734 */
3735 'ui.focus': UiFocusResult;
3736 /**
3737 * `{ isOffered }`.
3738 */
3739 'agent.offer': AgentOfferResult;
3740 /**
3741 * `{ model }` or `{ deny }`.
3742 */
3743 'agent.spawn': AgentSpawnResult;
3744 /**
3745 * `{ text, context? }` or `{ drop }`.
3746 */
3747 'prompt.submit': PromptSubmitResult;
3748 /**
3749 * `{ isFilled }`.
3750 */
3751 'prompt.fill': PromptFillResult;
3752 /**
3753 * `{ isShown }`.
3754 */
3755 'prompt.suggest': PromptSuggestResult;
3756 /**
3757 * `{ text, cursor }`, the box the editor shows next.
3758 */
3759 'prompt.edit': PromptEditResult;
3760 /**
3761 * `{ text }` (null leaves the section out).
3762 */
3763 'prompt.section': PromptSectionResult;
3764 /**
3765 * `{ blocks }` (a block left out is not sent).
3766 */
3767 'prompt.context': PromptContextResult;
3768 /**
3769 * `{ sections }`, every `shared` one ahead of every `session` one (a
3770 * section left out is not sent).
3771 */
3772 'prompt.compose': PromptComposeResult;
3773 /**
3774 * `{ text }` (null leaves the attachment out).
3775 */
3776 'prompt.attachment': PromptAttachmentResult;
3777 /**
3778 * `{ description, isDeferred? }`.
3779 */
3780 'tool.describe': ToolDescribeResult;
3781 /**
3782 * `{ text }` (the command's output, when it printed one).
3783 */
3784 'command.run': CommandRunResult;
3785 /**
3786 * `{ description, argumentHint, isHidden }`.
3787 */
3788 'command.describe': CommandDescribeResult;
3789 /**
3790 * `{ value }` once written, or `{ deny }`.
3791 */
3792 'config.set': ConfigSetResult;
3793 /**
3794 * `{ label, description, isHidden }`.
3795 */
3796 'config.describe': ConfigDescribeResult;
3797 /**
3798 * `{ text }`.
3799 */
3800 'skill.prompt': SkillPromptResult;
3801 /**
3802 * `{ text }`.
3803 */
3804 'attribution.text': AttributionTextResult;
3805 /**
3806 * `{ cwd }`.
3807 */
3808 'session.start': SessionStartResult;
3809 /**
3810 * `{ text }`, or `{ consumed }`.
3811 */
3812 'session.receive': SessionReceiveResult;
3813 /**
3814 * `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
3815 */
3816 'session.compact': SessionCompactResult;
3817 /**
3818 * `{ clientId }`.
3819 */
3820 'session.attach': SessionAttachResult;
3821 /**
3822 * `{ clientId }`.
3823 */
3824 'session.detach': SessionDetachResult;
3825 /**
3826 * `{ changed }`.
3827 */
3828 'session.measure': SessionMeasureResult;
3829 /**
3830 * `{ sessionId }`.
3831 */
3832 'session.end': SessionEndResult;
3833 /**
3834 * `{ allow: true }`, or `{ refuse }`.
3835 */
3836 'plugin.register': PluginRegisterResult;
3837 /**
3838 * `{ turnId }`.
3839 */
3840 'turn.start': TurnStartResult;
3841 /**
3842 * The response: `{ turnId, index, answer, toolUses, stopReason, usage }`.
3843 */
3844 'turn.step': TurnStepResult;
3845 /**
3846 * `{ text }`.
3847 */
3848 'turn.complete': TurnCompleteResult;
3849 /**
3850 * `$` as built so far, with this plugin's interface added and any it
3851 * withheld left out; `next(e)` resolves to EngineInterfaceBuilt.
3852 */
3853 'engine.create': EngineCreateResult;
3854 };
3855
3856 /**
3857 * The engine's own events as calls on `$`, one signature each:
3858 * `$.<noun>.<event>(input)` resolves to its result, or to its stream.
3859 *
3860 * The engine raises its events through these same calls; a plugin's call
3861 * runs the same chain with the calling hook alone skipped. `input` may leave
3862 * out what the engine fills (`tool_use_id`, the parent agent).
3863 */
3864 export type EventCalls = {
3865 tool: {
3866 call: ToolCallOverloads;
3867 check: (input: ToolCheckArgs) => Promise<ToolCheckResult>;
3868 describe: (input: ToolDescribeInput) => Promise<ToolDescribeResult>;
3869 };
3870 command: {
3871 run: (input: CommandRunArgs) => Promise<CommandRunResult>;
3872 describe: (input: CommandDescribeInput) => Promise<CommandDescribeResult>;
3873 };
3874 config: {
3875 set: (input: ConfigSetArgs) => Promise<ConfigSetResult>;
3876 describe: (input: ConfigDescribeInput) => Promise<ConfigDescribeResult>;
3877 };
3878 prompt: {
3879 submit: (input: PromptSubmitArgs) => Promise<PromptSubmitResult>;
3880 fill: (input: PromptFillArgs) => Promise<PromptFillResult>;
3881 suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
3882 section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
3883 context: (input: PromptContextInput) => Promise<PromptContextResult>;
3884 attachment: (input: PromptAttachmentInput) => Promise<PromptAttachmentResult>;
3885 compose: (input?: PromptComposeArgs) => Promise<PromptComposeResult>;
3886 };
3887 skill: {
3888 prompt: (input: SkillPromptInput) => Promise<SkillPromptResult>;
3889 };
3890 attribution: {
3891 text: (input: AttributionTextInput) => Promise<AttributionTextResult>;
3892 };
3893 agent: {
3894 offer: (input: AgentOfferInput) => Promise<AgentOfferResult>;
3895 spawn: (input: AgentSpawnArgs) => Promise<AgentSpawnResult>;
3896 };
3897 session: {
3898 start: (input: SessionStartInput) => Promise<SessionStartResult>;
3899 receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
3900 compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
3901 attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
3902 detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
3903 measure: (input: SessionMeasureInput) => Promise<SessionMeasureResult>;
3904 end: (input: SessionEndInput) => Promise<SessionEndResult>;
3905 };
3906 turn: {
3907 start: (input: TurnStartInput) => Promise<TurnStartResult>;
3908 step: (input: TurnStepInput) => HookStream<TurnStepChunk, TurnStepResult>;
3909 complete: (input: TurnCompleteInput) => Promise<TurnCompleteResult>;
3910 };
3911 ui: {
3912 render: <C extends RenderComponent>(input: RenderInput<C>) => Promise<RenderElement>;
3913 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
3914 scroll: (input: UiScrollArgs) => Promise<UiScrollResult>;
3915 focus: (input: UiFocusArgs) => Promise<UiFocusResult>;
3916 };
3917 };
3918
3919 /**
3920 * The name of an event: a key of EventOf, the engine's own (CoreEventName)
3921 * and the declared plugin nouns' (NounEventName).
3922 */
3923 export type EventName = keyof EventOf;
3924
3925 /**
3926 * The argument of each event, by event name: what a hook receives as `e`
3927 * and what the call on `$` takes. Plain data, frozen to every depth.
3928 *
3929 * The engine's own events (CoreEventOf: a plugin's `$.fs.write(...)` is
3930 * a dispatch the hooks above it see) and the methods of the plugin nouns
3931 * declared on EngineInterface (NounEventOf).
3932 */
3933 export type EventOf = CoreEventOf & NounEventOf;
3934
3935 /**
3936 * The result of event `N`: what its hooks return and what their `next(e)`
3937 * resolves to.
3938 */
3939 export type EventResult<N extends EventName = EventName> = ResultOf[N];
3940
3941 /**
3942 * The hook signature of each event, `($, e, next)`, as one mapped type over
3943 * EventOf; a streaming event's is the generator form (StreamHook).
3944 *
3945 * With one handler type per event, `Events[E]` for a generic E would be a
3946 * union; as one mapped type it stays a single function type the engine
3947 * calls without a cast (TS 4.6 correlated unions).
3948 *
3949 * @param $ the engine interface, frozen, the same object at every invocation;
3950 * at `engine.create` the empty table, since `$` exists after the fold
3951 * @param e the event's argument, frozen to every depth (`e.command = "ls"`
3952 * is a type error and throws); a rewrite is a copy passed to `next`
3953 * @param next the rest of the chain; a chain a hook raises through `$` skips
3954 * this hook and runs every other, its plugin's others too
3955 */
3956 export type Events = {
3957 [E in keyof EventOf]: E extends StreamingEventName ? StreamHook<E> : ($: E extends 'engine.create' ? NoEngineInterface : EngineInterface, e: Frozen<Args<E>>, next: Next<E>) => EventResult<E> | Promise<EventResult<E>>;
3958 };
3959
3960 type ExitReason = 'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other';
3961
3962 type FileChangedHookInput = BaseHookInput & {
3963 hook_event_name: 'FileChanged';
3964 file_path: string;
3965 event: 'change' | 'add' | 'unlink';
3966 };
3967
3968 /**
3969 * `T` with every property read-only to every depth, arrays and tuples kept
3970 * as declared: how a hook's `e` is typed.
3971 *
3972 * `e.command = 'x'` is a type error; `next({ ...e, command: 'x' })` compiles.
3973 */
3974 export type Frozen<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? {
3975 [K in keyof T]: Frozen<T[K]>;
3976 } : T extends object ? {
3977 readonly [K in keyof T]: Frozen<T[K]>;
3978 } : T;
3979
3980 /**
3981 * One file `$.fs.ancestors` found: the directory it stands in, the name it
3982 * was asked for by, and its text as the engine's memory loader reads it.
3983 */
3984 export type FsAncestor = {
3985 /**
3986 * The directory the file stands in, absolute.
3987 */
3988 dir: string;
3989 /**
3990 * The spelling the caller asked for it by.
3991 */
3992 name: string;
3993 /**
3994 * The file's text, with what its `@include`s bring after it.
3995 */
3996 content: string;
3997 /**
3998 * The file and then each file its `@` imports brought, in load order,
3999 * path and text apiece; `content` is these texts joined.
4000 */
4001 parts: readonly FsAncestorPart[];
4002 };
4003
4004 /**
4005 * One file of an ancestor entry: the file itself or one it imported.
4006 */
4007 export type FsAncestorPart = {
4008 /**
4009 * The file's path, absolute.
4010 */
4011 path: string;
4012 /**
4013 * Its text as the engine's memory loader reads it.
4014 */
4015 content: string;
4016 };
4017
4018 /**
4019 * The argument of `$.fs.ancestors`: the file names to look for in each
4020 * directory, the file to walk down to, and the directory to walk beneath.
4021 */
4022 export type FsAncestorsRequest = {
4023 /**
4024 * Relative `.md` file names, each looked for in every directory.
4025 */
4026 names: readonly string[];
4027 /**
4028 * The file the walk goes on down to the directory of, relative to the
4029 * working directory or absolute; absent, it ends at the working directory.
4030 */
4031 of?: string;
4032 /**
4033 * The directory the walk starts beneath, relative to the working directory
4034 * or absolute; absent, the walk starts at the filesystem root.
4035 *
4036 * Only directories strictly inside it are read, so with `of` a file under
4037 * the project root the walk reads the directories between the two, as the
4038 * engine reads a nested CLAUDE.md; a file not inside it finds nothing.
4039 */
4040 below?: string;
4041 };
4042
4043 /**
4044 * What `$.fs.read(path, { as: "bytes" })` resolves with: the file's bytes,
4045 * base64, since only plain data crosses into a plugin's environment.
4046 */
4047 export type FsBytes = {
4048 /**
4049 * The file's content, standard padded base64;
4050 * `Uint8Array.fromBase64(base64)` gives the bytes back.
4051 */
4052 base64: string;
4053 };
4054
4055 /**
4056 * One entry of `$.fs.list`: the entry itself, a link not followed.
4057 */
4058 export type FsEntry = {
4059 /**
4060 * The entry's name (no directory part).
4061 */
4062 name: string;
4063 /**
4064 * `file`, `dir`, or `other`, of the entry itself: a symbolic link is
4065 * `other` (`$.fs.stat` says what it leads to, and with `resolve` where).
4066 */
4067 kind: 'file' | 'dir' | 'other';
4068 /**
4069 * Bytes, for a file.
4070 */
4071 size: number;
4072 /**
4073 * True when the entry is a symbolic link.
4074 */
4075 isLink: boolean;
4076 };
4077
4078 /**
4079 * How `$.fs.read` answers: `text` (UTF-8, the default) or `bytes` (base64).
4080 */
4081 export type FsReadAs = 'text' | 'bytes';
4082
4083 /**
4084 * The options of `$.fs.read` that ask for the bytes: the call answers
4085 * `{ base64 }`.
4086 */
4087 export type FsReadBytesOptions = {
4088 /**
4089 * `bytes`.
4090 */
4091 as: 'bytes';
4092 };
4093
4094 /**
4095 * `$.fs.read`: the file's text, or with `{ as: "bytes" }` its bytes as
4096 * `{ base64 }`.
4097 */
4098 export type FsReadCall = {
4099 (path: string): Promise<string>;
4100 (path: string, options: FsReadBytesOptions): Promise<FsBytes>;
4101 (path: string, options: FsReadOptions): Promise<string | FsBytes>;
4102 };
4103
4104 /**
4105 * The options of `$.fs.read`.
4106 */
4107 export type FsReadOptions = {
4108 /**
4109 * `bytes` answers `{ base64 }` for a binary file; `text` (the default) the
4110 * file's text.
4111 */
4112 as: FsReadAs;
4113 };
4114
4115 /**
4116 * What `$.fs.stat` resolves with: what the path leads to, whether the path
4117 * itself is a symbolic link, and where it lands when asked.
4118 */
4119 export type FsStat = {
4120 /**
4121 * `file`, `dir`, or `other`, of what the path leads to: a link is
4122 * followed, and one that leads nowhere is `other`.
4123 */
4124 kind: 'file' | 'dir' | 'other';
4125 /**
4126 * Bytes, for a file.
4127 */
4128 size: number;
4129 /**
4130 * Last modification, milliseconds since the epoch.
4131 */
4132 mtimeMs: number;
4133 /**
4134 * True when the path itself is a symbolic link; `kind`, `size` and
4135 * `mtimeMs` then describe what it points at, or the link when that is gone.
4136 */
4137 isLink: boolean;
4138 /**
4139 * Where the path landed when asked with `{ resolve: true }`: absolute,
4140 * every symbolic link followed, `.` and `..` folded; else absent.
4141 *
4142 * Absent too when the path leads nowhere or a hook above withheld it, so
4143 * a guard denies without it; and a hard link, a volume or file-id spelling
4144 * (macOS `/.vol/`) or a case alias keeps its own spelling, `isLink` false.
4145 *
4146 * @remarks a deny-list on spellings is thus best effort; an allow-list on
4147 * `realPath` under a root resolved the same way is the robust guard.
4148 */
4149 realPath?: string;
4150 };
4151
4152 /**
4153 * The options of `$.fs.stat`.
4154 */
4155 export type FsStatOptions = {
4156 /**
4157 * True to resolve where the path lands as well.
4158 *
4159 * The answer then carries `realPath` when the path leads somewhere, at
4160 * the cost of one more file system call: where it landed then, not a hold
4161 * on what a tool opens afterwards.
4162 */
4163 resolve: boolean;
4164 };
4165
4166 /**
4167 * Every event (`*`), or every event under a namespace (`classic.*`: each
4168 * one whose name starts with `classic.`).
4169 */
4170 export type Glob = '*' | `${Namespace}.*`;
4171
4172 /**
4173 * The hook `on(pattern, hook)` takes for a glob or a negation: one function
4174 * placed on every selected event, `e` and the result typed as their union.
4175 *
4176 * `next.event` says which event a run is; `next.is(pattern, e)` narrows `e`
4177 * to one of them. At `engine.create` (a negation may select it) `$` is the
4178 * empty table and the hook observes the fold, as a `*` hook does.
4179 */
4180 export type GlobHook<P extends Pattern, N extends EventName = Selected<P>> = ($: EngineInterface, e: Frozen<Args<N>>, next: GlobNext<P>) => EventResult<N> | Promise<EventResult<N>>;
4181
4182 /**
4183 * `next` in a hook on a glob or a negation: an overload per selected event,
4184 * then one over their union for an `e` not yet narrowed.
4185 *
4186 * `is` narrows `e` to the selected events its pattern names; `event` is one
4187 * of the selected names.
4188 */
4189 export type GlobNext<P extends Pattern, N extends EventName = Selected<P>> = OrderedOverloads<N> & {
4190 (e: Args<N>): Promise<GlobNextResult<N>>;
4191 /**
4192 * Continues this dispatch at a tier, as Next's `to` (a managed hook's),
4193 * over the selected events' union for an `e` not yet narrowed.
4194 */
4195 readonly to: (e: Args<N>, tier: TargetTier) => Promise<GlobNextResult<N>>;
4196 readonly signal: AbortSignal;
4197 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<Args<Extract<N, Selected<M>>>>;
4198 readonly event: N;
4199 readonly origin: Origin;
4200 readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
4201 readonly budget: NextBudget;
4202 };
4203
4204 /**
4205 * What `next(e)` resolves to in a glob hook before `e` is narrowed: the
4206 * NextResult of each selected event, as a union.
4207 */
4208 type GlobNextResult<N extends EventName> = {
4209 [K in N]: NextResult<K>;
4210 }[N];
4211
4212 /**
4213 * One hook, `($, e, next)`, on event `E`.
4214 */
4215 export type Hook<E extends EventName = EventName> = Events[E];
4216
4217 /**
4218 * The time bounds every hook runs under, in milliseconds: the engine's own
4219 * constants are typed by these members, and `next.budget` reads the live one.
4220 *
4221 * Each bounds the hook's OWN time: the clock stops while a `next(e)` call or
4222 * any `$` call of the hook's is in flight (a `$.clock` wait excepted), so a
4223 * slow chain beneath or a minute-long `$.model.complete` costs it nothing.
4224 *
4225 * @example
4226 * await $.model.complete(ask) // a minute; next.budget.remainingMs unmoved
4227 */
4228 export type HookBudget = {
4229 /**
4230 * A hook's budget per dispatch, from its call to its return; past it the
4231 * hook is absent (its `.catch` asked, else `next(e)` run on its behalf).
4232 *
4233 * A streaming hook's (`turn.step`, an async generator) spans its whole
4234 * run and counts only while its own code runs: never at a `yield`, never
4235 * while it reads the stream beneath. Not per chunk: the sum of its work.
4236 */
4237 readonly ms: 10_000;
4238 /**
4239 * A `.catch` handler's grace: a fresh budget from the moment it is called,
4240 * on the same clock (its `next` replay and its `$` calls are free).
4241 *
4242 * Past it the hook is absent as if it had no handler; `next.error.budget`
4243 * and `next.budget.ms` both read it there. `engine.create` has no budget.
4244 */
4245 readonly catchMs: 1_000;
4246 /**
4247 * How long a hook may keep running after `next.signal` aborted (the person
4248 * interrupted, a hook above settled first, its own budget ran out).
4249 *
4250 * Past it the hook is reported as lingering; the dispatch had already gone
4251 * on without it when the signal aborted.
4252 */
4253 readonly lingerMs: 5_000;
4254 };
4255
4256 /**
4257 * Why a hook failed, as its `.catch` handler reads it on `next.error`: plain
4258 * frozen data.
4259 *
4260 * `throw`: the hook threw, or returned what the site refuses, `message`
4261 * saying what; `timeout`: it outran its budget, `message` then what its last
4262 * `next()` rejected with, if it did. `budget` is the handler's own grace.
4263 */
4264 export type HookFailure = {
4265 readonly kind: 'throw' | 'timeout';
4266 /**
4267 * The thrown error's message, or for a timeout what the hook's last
4268 * `next()` rejected with; absent for a timeout with nothing rejected.
4269 */
4270 readonly message?: string;
4271 /**
4272 * The grace the handler runs under, in milliseconds; past it, the hook is
4273 * absent as if it had no handler.
4274 */
4275 readonly budget: number;
4276 };
4277
4278 /**
4279 * The hook type per pattern: an event's own (Events), `*`'s (AnyEventHook),
4280 * or a glob's over the events it selects (GlobHook), as one conditional type.
4281 *
4282 * One type, so the two-argument `on` stays ONE generic signature: as an
4283 * overload set the language service offers no tool-name completions inside
4284 * `e.tool === "`; as an index into a table TS intersects every argument.
4285 */
4286 export type HookFor<P extends Pattern> = P extends '*' ? AnyEventHook : P extends EventName ? Events[P] : GlobHook<P>;
4287
4288 type HookInput = PreToolUseHookInput | PostToolUseHookInput | PostToolUseFailureHookInput | PostToolBatchHookInput | PermissionDeniedHookInput | NotificationHookInput | UserPromptSubmitHookInput | UserPromptExpansionHookInput | SessionStartHookInput | SessionEndHookInput | StopHookInput | StopFailureHookInput | SubagentStartHookInput | SubagentStopHookInput | PreCompactHookInput | PostCompactHookInput | PreModelSwitchHookInput | PostModelSwitchHookInput | PermissionRequestHookInput | SetupHookInput | TeammateIdleHookInput | TaskCreatedHookInput | TaskCompletedHookInput | ElicitationHookInput | ElicitationResultHookInput | ConfigChangeHookInput | InstructionsLoadedHookInput | WorktreeCreateHookInput | WorktreeRemoveHookInput | CwdChangedHookInput | FileChangedHookInput | DirectoryAddedHookInput | MessageDisplayHookInput;
4289
4290 /**
4291 * The hook event `E` takes: an async generator over its chunks for a
4292 * streaming event (`turn.step`), `($, e, next) => result` for every other.
4293 */
4294 export type HookOf<E extends EventName> = Events[E];
4295
4296 /**
4297 * What a hooks module exports: `register`, and nothing the loader reads
4298 * besides.
4299 */
4300 export type HooksModule = {
4301 register: Register;
4302 };
4303
4304 /**
4305 * What `next(e)` returns on a streaming event: the stream of everything
4306 * beneath, chunk by chunk, whose return value is the result from beneath.
4307 *
4308 * `yield* next(e)` forwards the chunks and evaluates to that result; a
4309 * transforming hook reads `for await (const chunk of stream)` and then
4310 * `await stream.result`. Each call runs what is beneath afresh.
4311 */
4312 export type HookStream<C, R> = AsyncGenerator<C, R> & {
4313 /**
4314 * Settles with what beneath returned once the stream has been read to
4315 * its end; rejects if the stream is closed before that.
4316 */
4317 readonly result: Promise<R>;
4318 };
4319
4320 /**
4321 * Options of `$.http.fetch`.
4322 */
4323 export type HttpInit = {
4324 /**
4325 * `GET` (default), `POST`, ...
4326 */
4327 method?: string;
4328 /**
4329 * Request headers.
4330 */
4331 headers?: Record<string, string>;
4332 /**
4333 * The request body, as text.
4334 */
4335 body?: string;
4336 /**
4337 * The handle `$.session.authorize()` answered: the engine sets the
4338 * session's credential header itself, only for a first-party host.
4339 */
4340 auth?: string;
4341 /**
4342 * The absolute path of a Unix domain socket the request goes over instead
4343 * of TCP (near 100 B at most): one per session, in a private directory.
4344 *
4345 * The URL still gives path, query and Host; redirects stay on it; no proxy;
4346 * `https:` is TLS verified against the URL's host (always, once `auth`
4347 * rides), so a credential reaches only its host. No relative path, no NUL.
4348 *
4349 * @example
4350 * await $.http.fetch(url, { socketPath: `${runDirectory}/bridge.sock` })
4351 */
4352 socketPath?: string;
4353 };
4354
4355 /**
4356 * What `$.http.fetch` resolves with.
4357 */
4358 export type HttpResponse = {
4359 /**
4360 * The HTTP status code.
4361 */
4362 status: number;
4363 /**
4364 * True for a 2xx status.
4365 */
4366 ok: boolean;
4367 /**
4368 * Response headers, lower-cased names.
4369 */
4370 headers: Record<string, string>;
4371 /**
4372 * The body, as text.
4373 */
4374 text: string;
4375 };
4376
4377 /**
4378 * A `$.ui.blit` argument swapping one of the caller's mounted keyed Images
4379 * to its next picture; every call sends it, so a stream needs no generation.
4380 *
4381 * The surface writes them with its frames, some sixty a second: byte and
4382 * `file` sources fold to the last per frame; every `shm` source reaches the
4383 * terminal (it unlinks each), and is denied while frames are not written.
4384 *
4385 * @example await $.ui.blit({ requestId: 'browser', key: 'view',
4386 * source: { shm: '/tb-4', format: 'rgb', width: 1280, height: 720 } })
4387 */
4388 export type ImageBlitArgs = {
4389 /**
4390 * The site the Image is drawn in, by the `requestId` this plugin draws it
4391 * under.
4392 */
4393 requestId: string;
4394 /**
4395 * The Image's `key` in that drawing.
4396 */
4397 key: string;
4398 /**
4399 * The next picture (ImageSource): bytes, or a name the terminal reads.
4400 */
4401 source: ImageSource;
4402 /**
4403 * Refused unless it is the mounted Image's width in cells. Absent, that.
4404 */
4405 columns?: number;
4406 /**
4407 * Refused unless it is the mounted Image's height in cells. Absent, that.
4408 */
4409 rows?: number;
4410 };
4411
4412 /**
4413 * The props of `Image`, the terminal surface's picture leaf: pixels over a
4414 * box of cells where the terminal can (kitty, Ghostty), the `alt` elsewhere.
4415 *
4416 * A leaf: no children, `hover` or `onPress`; the cells are text, so the
4417 * picture scrolls and clips as a word does. Drawn again with another `source`
4418 * it is replaced in place; keyed, `$.ui.blit` swaps it at the frame rate.
4419 *
4420 * @example const { bytes } = await $.fs.read('chart.png', { as: 'bytes' })
4421 * <Image source={{ png: bytes.toBase64() }} columns={40} rows={12} alt="p95" />
4422 * @example <Image key="view" source={{ shm: '/tb-7', format: 'rgb', width: 960,
4423 * height: 600 }} columns={80} rows={25} alt="the page" />
4424 */
4425 export type ImageProps = {
4426 /**
4427 * The element's address within the drawing: what `$.ui.blit` names to swap.
4428 *
4429 * Unique among the Images of one tree; absent, only a redraw changes it.
4430 */
4431 key?: string;
4432 /**
4433 * The picture (ImageSource): `{ png }` or `{ rgba, width, height }` bytes,
4434 * or `{ file, format }` / `{ shm, format, width, height }` read here.
4435 */
4436 source: ImageSource;
4437 /** How many terminal columns wide, 1 to 255; the picture is scaled to fill
4438 * the box and the site clips what its body cannot show. */
4439 columns: number;
4440 /**
4441 * How many terminal rows tall, 1 to 255.
4442 */
4443 rows: number;
4444 /**
4445 * What the picture says, drawn dim in its place where the picture cannot
4446 * be (and read by a screen reader); required, may be a single space.
4447 */
4448 alt: string;
4449 };
4450
4451 /**
4452 * The picture an `Image` shows: base64 bytes the plugin holds (at most 2 MiB
4453 * decoded), or the name of a file or POSIX shared-memory object it does not.
4454 *
4455 * A name is one another process on this machine wrote; the terminal, running
4456 * as the person, opens, reads and decodes it itself, so no pixel crosses `$`
4457 * and the engine never touches it. One it will not read (not a regular file,
4458 * under `/proc`, `/sys` or `/dev`, gone, across ssh) draws a blank box, its
4459 * words in the debug log; it unlinks a shared-memory object once read, so
4460 * each frame is a fresh one. A source equal to the last drawn sends nothing;
4461 * `generation` makes new content under an unchanged name a new source.
4462 *
4463 * @example { rgba: pixels.toBase64(), width: 64, height: 32 }
4464 * @example { file: '/dev/shm/frame-3.rgba', format: 'rgba', width: 640,
4465 * height: 400 }
4466 * @example { shm: '/tb-view-2', format: 'rgb', width: 1280, height: 720 }
4467 */
4468 export type ImageSource = {
4469 /**
4470 * A whole PNG file, base64.
4471 */
4472 png: string;
4473 } | {
4474 /**
4475 * `width * height` RGBA pixels, 4 bytes each, base64.
4476 */
4477 rgba: string;
4478 /**
4479 * Pixels per row, 1 to 2048.
4480 */
4481 width: number;
4482 /**
4483 * Rows of pixels, 1 to 2048.
4484 */
4485 height: number;
4486 } | {
4487 /**
4488 * The absolute path of a regular file holding a whole PNG, at most
4489 * 3072 bytes of path; read by the terminal, left in place.
4490 */
4491 file: string;
4492 /**
4493 * The file is a whole PNG; the terminal decodes it and sizes it itself.
4494 */
4495 format: 'png';
4496 /**
4497 * A whole number that changes when the file's content does under the
4498 * same path, so a redraw reads it again; absent, the path alone tells.
4499 */
4500 generation?: number;
4501 } | {
4502 /**
4503 * The absolute path of a regular file of `width * height` raw pixels, at
4504 * most 3072 bytes of path; read by the terminal, left in place.
4505 *
4506 * On Linux a file under `/dev/shm` is memory.
4507 */
4508 file: string;
4509 /**
4510 * `rgba`, 4 bytes a pixel, or `rgb`, 3.
4511 */
4512 format: 'rgba' | 'rgb';
4513 /**
4514 * Pixels per row, 1 to 4096.
4515 */
4516 width: number;
4517 /**
4518 * Rows of pixels, 1 to 4096.
4519 */
4520 height: number;
4521 /**
4522 * A whole number that changes when the file's content does under the
4523 * same path, so a redraw reads it again; absent, the path alone tells.
4524 */
4525 generation?: number;
4526 } | {
4527 /**
4528 * The name of a POSIX shared-memory object of `width * height` raw
4529 * pixels: `/` then up to 254 of `A-Z a-z 0-9 . _ -` (macOS takes 30).
4530 *
4531 * The terminal unlinks it after reading, so a name feeds one Image
4532 * drawn once and is never sent again on a redraw; POSIX terminals only.
4533 */
4534 shm: string;
4535 /**
4536 * `rgba`, 4 bytes a pixel, or `rgb`, 3.
4537 */
4538 format: 'rgba' | 'rgb';
4539 /**
4540 * Pixels per row, 1 to 4096.
4541 */
4542 width: number;
4543 /**
4544 * Rows of pixels, 1 to 4096.
4545 */
4546 height: number;
4547 /**
4548 * A whole number that changes when a fresh object reuses a name, so a
4549 * redraw reads it again; absent, the name alone tells.
4550 */
4551 generation?: number;
4552 };
4553
4554 /**
4555 * The keys of object pattern `P` that object member `E` cannot satisfy, `D`
4556 * levels down; `never` when there is none, which is what keeps the member.
4557 *
4558 * A key `E` does not have (an open record has every string key), or one
4559 * whose value `P` narrows to nothing.
4560 */
4561 type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
4562 [K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
4563 }[keyof P];
4564
4565 /**
4566 * The props of `Input`, every surface's one-line text field: an address,
4567 * optional texts, and the closures a change and a submit run. A leaf.
4568 *
4569 * Focused through the same ring as `Button` (`abovePrompt:focus`); while it
4570 * has focus every printable key reaches it alone and Esc returns them; a
4571 * change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
4572 */
4573 export type InputProps = {
4574 /**
4575 * The element's address: `e.element` at `ui.input`, what a matcher names.
4576 */
4577 key: string;
4578 /**
4579 * Text drawn before the field.
4580 */
4581 label?: string;
4582 /**
4583 * Text drawn dim in an empty field.
4584 */
4585 placeholder?: string;
4586 /**
4587 * The text the field holds when drawn; the person's typing replaces it
4588 * until the hook draws another.
4589 */
4590 value?: string;
4591 /**
4592 * What Enter does, in a word or two, drawn beside the field while it has
4593 * focus (`send`). Defaults to `submit`.
4594 */
4595 submitLabel?: string;
4596 /**
4597 * The site's focus ring starts here when the site takes the keyboard,
4598 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
4599 *
4600 * A pane opened with `focus`, or the person's focus chord or click, is the
4601 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
4602 * origin this plugin. A ring the person has moved stays where it was put.
4603 */
4604 autoFocus?: true;
4605 /**
4606 * Runs on every change of the text, in the plugin's own environment: the
4607 * bottom of a `ui.input` chain of kind `change`.
4608 */
4609 onInput?: (value: string, e: UiInputArgument) => void;
4610 /**
4611 * Runs on Enter with the text, in the plugin's own environment: the bottom
4612 * of a `ui.input` chain of kind `submit`. No model turn unless it asks one.
4613 */
4614 onSubmit: (value: string, e: UiInputArgument) => void;
4615 };
4616
4617 /**
4618 * Every tier an instruction file can belong to, for checking a hook's
4619 * answer; the kind type is derived from this list.
4620 */
4621 const INSTRUCTION_FILE_KINDS: readonly ["managed", "user", "project", "local", "memory"];
4622
4623 /**
4624 * One instruction file behind the `claudeMd` block: where it was read, its
4625 * tier, its text as loaded, and the file that `@`-imported it if one did.
4626 */
4627 export type InstructionFile = {
4628 /**
4629 * The file's path, absolute.
4630 */
4631 path: string;
4632 /**
4633 * Its tier.
4634 */
4635 kind: InstructionFileKind;
4636 /**
4637 * The text as loaded (comments and frontmatter already stripped).
4638 */
4639 content: string;
4640 /**
4641 * The path of the file whose `@` import brought this one, when one did.
4642 */
4643 parent?: string;
4644 };
4645
4646 /**
4647 * What tier an instruction file belongs to: the organization's managed
4648 * policy, the person's own, the project's checked-in or private ones, memory.
4649 */
4650 export type InstructionFileKind = (typeof INSTRUCTION_FILE_KINDS)[number];
4651
4652 type InstructionsLoadedHookInput = BaseHookInput & {
4653 hook_event_name: 'InstructionsLoaded';
4654 file_path: string;
4655 memory_type: 'User' | 'Project' | 'Local' | 'Managed';
4656 load_reason: 'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact';
4657 globs?: string[];
4658 trigger_file_path?: string;
4659 parent_file_path?: string;
4660 };
4661
4662 /**
4663 * What `$.ui.invalidate` takes: a render event, or one of the six events
4664 * whose answers the engine caches for the session.
4665 */
4666 export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'prompt.attachment' | 'tool.describe' | 'command.describe' | 'config.describe';
4667
4668 /**
4669 * Whether tag key `K` selects members of `I`: it does when each member gives
4670 * it ONE literal (`component: "ToolUse"` on the ToolUse variant).
4671 *
4672 * A key that is the same union on every member is a filter at runtime; it
4673 * is left out of the selection so that it cannot defeat the narrowing the
4674 * other keys give.
4675 */
4676 type IsDiscriminant<I, K> = I extends unknown ? K extends KnownKeys<I> ? IsSingleLiteral<I[K]> : true : never;
4677
4678 /**
4679 * Whether `V` is made of literals only: `"a" | "b"` is, `string` is not.
4680 */
4681 type IsLiteralValued<V> = string extends V ? false : number extends V ? false : boolean extends V ? false : [V] extends [string | number | boolean] ? true : false;
4682
4683 /**
4684 * Whether `V` is exactly one string, number or boolean literal.
4685 */
4686 type IsSingleLiteral<V> = [V] extends [string | number | boolean] ? IsUnion<V> extends true ? false : true : false;
4687
4688 /**
4689 * Whether `T` is a union of two or more members.
4690 */
4691 type IsUnion<T, U = T> = T extends unknown ? [U] extends [T] ? false : true : never;
4692
4693 /**
4694 * Plain data: what JSON holds, and what crosses between a plugin's hooks
4695 * module and its surface module whole (a `Client`'s props, a post's data).
4696 *
4697 * A function, a class instance, `undefined` or a cycle is not plain data;
4698 * the engine refuses one where it checks, and drops it where it clones.
4699 */
4700 export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
4701 readonly [key: string]: JsonValue;
4702 };
4703
4704 /**
4705 * What `next` takes in a matched hook: the variants of `e` the matcher can
4706 * match (KeptMembers), as declared, so a rewrite of a pinned field passes.
4707 */
4708 type KeptEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? KeptMembers<Args<N>, M> : never : never;
4709
4710 /**
4711 * The members of the argument union `E` matcher `P` can match, as declared;
4712 * what `next` takes, so a rewrite may change a field the matcher pinned.
4713 *
4714 * A member is dropped when `P` names a key it lacks, or gives a key, at any
4715 * depth, a value none of that key's values can equal (ImpossibleKeys).
4716 */
4717 type KeptMembers<E, P> = E extends unknown ? [ImpossibleKeys<E, P, []>] extends [never] ? E : never : never;
4718
4719 /**
4720 * The declared keys of `T`, the string and number index signatures left out.
4721 */
4722 type KnownKeys<T> = keyof {
4723 [K in keyof T as string extends K ? never : number extends K ? never : K]: 0;
4724 };
4725
4726 /**
4727 * The events whose overload must come after the rest, lest it shadow them.
4728 *
4729 * `classic.PreToolUse` shares `tool.call`'s envelope, `turn.abort` every
4730 * turn event's `turnId`, and an object of any shape is assignable to NoArgs.
4731 */
4732 type LateOverload = 'classic.PreToolUse' | 'turn.abort' | NoArgsEvent;
4733
4734 /**
4735 * The props of `Link`, a hyperlink every surface draws: an OSC 8 span on the
4736 * terminal (else its text then the URL in dim), an anchor on desktop.
4737 *
4738 * An inline element: its children are the text, strings and inline
4739 * elements; absent children the `label`, absent both the URL. The engine
4740 * bounds `href` before the tree crosses.
4741 */
4742 export type LinkProps = {
4743 /**
4744 * Where the link goes: an `https:` URL (or `http://localhost`), at most
4745 * 2048 characters of printable ASCII, spelled as `new URL(href).href`.
4746 *
4747 * No `user@host` part, no raw `@`, space or non-ASCII letter (encode them);
4748 * anything else refuses the tree the Link is in.
4749 */
4750 href: string;
4751 /**
4752 * The text drawn when the element has no children; absent both, the URL
4753 * itself is the text.
4754 */
4755 label?: string;
4756 };
4757
4758 /**
4759 * What a matcher value selects by: itself, or `unknown` for a RegExp, which
4760 * selects nothing.
4761 */
4762 type Literal<X> = X extends RegExp ? unknown : X;
4763
4764 /**
4765 * What a `Markdown` carries across the boundary: its address, text, dimness
4766 * and which links it answers; `onLinkPress` stays behind, a `press` instead.
4767 */
4768 export type MarkdownLeafProps = {
4769 /**
4770 * The element's address: what `e.element` carries and what a matcher
4771 * names; present whenever the element carries a `press`.
4772 */
4773 key?: string;
4774 /**
4775 * The markdown drawn, bounded as a Text's string is.
4776 */
4777 text: string;
4778 /**
4779 * The whole block dim, as `Text`'s `dimColor`; absent draws as false.
4780 */
4781 dimColor?: boolean;
4782 /**
4783 * Which links a press belongs to, by `href` as written; absent, with a
4784 * `press`, every link drawn. Compared with the pressed target only.
4785 */
4786 pressableLinks?: readonly string[];
4787 };
4788
4789 /**
4790 * The props of `Markdown`, a block of markdown every surface draws as it
4791 * draws an assistant reply's text: its own renderer, links, tables, fences.
4792 *
4793 * A leaf: no children. `text` is the element's data as a `Text`'s string is,
4794 * bounded the same way. With `onLinkPress` the links it draws are the
4795 * plugin's to answer: a press on one raises `ui.press` addressed to `key`.
4796 */
4797 export type MarkdownProps = {
4798 /**
4799 * The element's address: `e.element` at `ui.press`, what a matcher names.
4800 * Required with `onLinkPress`, since a press needs one; else optional.
4801 */
4802 key?: string;
4803 /**
4804 * The markdown drawn, as an assistant reply would write it.
4805 *
4806 * At most 10000 characters, tab and newline its only control characters;
4807 * a link whose scheme is not `https:`, `http:` or `file:` draws as text,
4808 * never clickable. Not drawn around the approval dialog.
4809 */
4810 text: string;
4811 /**
4812 * The whole block dim, as `Text`'s `dimColor`: a thought, an aside.
4813 */
4814 dimColor?: boolean;
4815 /**
4816 * What a press on a link in `text` runs, in the plugin's own environment:
4817 * the bottom of a `ui.press` chain whose `e.link` names the link.
4818 *
4819 * A press is a plain single click where the surface reports clicks (the
4820 * fullscreen terminal): it opens nothing and lands once no double-click
4821 * followed; a ctrl, alt or terminal-kept cmd click opens it as before.
4822 */
4823 onLinkPress?: (link: PressedLink, e: UiPressArgument) => void;
4824 /**
4825 * Which links in `text` a press belongs to, by `href` as the markdown
4826 * writes it; absent, every link drawn. Only with `onLinkPress`.
4827 *
4828 * A link left out keeps the surface's own behaviour. At most 256 entries
4829 * of at most 2048 characters; compared with the pressed link's target,
4830 * never opened.
4831 */
4832 pressableLinks?: readonly string[];
4833 };
4834
4835 /**
4836 * The argument a matched hook receives: `e` narrowed by `M` (Narrowed), per
4837 * event the registration covers.
4838 */
4839 export type MatchedEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Narrowed<Args<N>, M> : never : never;
4840
4841 /**
4842 * The hook `on(pattern, matcher, hook)` takes: `($, e, next)` with `e`
4843 * narrowed by the matcher (MatchedEvent), and a tagged result the same way.
4844 *
4845 * On a streaming event it is the generator form (MatchedStreamHook). `next`
4846 * takes the variants the matcher keeps, as declared (KeptEvent); `next.is`
4847 * names the events the registration covers and narrows as the matcher does.
4848 */
4849 export type MatchedHook<P extends Pattern, M> = P extends StreamingEventName ? MatchedStreamHook<P, M> : ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: Next<MatchedNames<P, M>, KeptEvent<P, M>, MatchedResult<P, M>, {
4850 [K in MatchedNames<P, M>]: Narrowed<Args<K>, M>;
4851 }>) => MatchedResult<P, M> | Promise<MatchedResult<P, M>>;
4852
4853 /**
4854 * The events a matched registration on `P` covers: the event named, or for a
4855 * glob every selected event whose input has each key the matcher names.
4856 */
4857 type MatchedNames<P, M = never> = P extends EventName ? P : {
4858 [N in Selected<P & string>]: [M] extends [never] ? N : keyof M extends AnyKeyOf<Args<N>> ? N : never;
4859 }[Selected<P & string>];
4860
4861 /**
4862 * What a matched hook returns: the event's result, narrowed by `M` where the
4863 * result is a union tagged by the matcher's tag keys.
4864 */
4865 export type MatchedResult<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Select<EventResult<N>, Selection<Args<N>, M>> : never : never;
4866
4867 /**
4868 * The hook `on(event, matcher, hook)` takes on a streaming event: the
4869 * generator form, `e` narrowed by the matcher, `next(e)` the stream beneath.
4870 */
4871 export type MatchedStreamHook<P extends StreamingEventName, M> = ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: MatchedStreamNext<P, M>) => StreamHookBody<Chunk<P>, MatchedResult<P, M>>;
4872
4873 /**
4874 * What a matched streaming hook's `next.is(pattern, e)` narrows `e` to:
4875 * the streaming event's argument narrowed by the matcher.
4876 */
4877 type MatchedStreamNarrowings<P extends StreamingEventName, M> = {
4878 [K in P]: Narrowed<Args<K>, M>;
4879 };
4880
4881 /**
4882 * A matched streaming hook's `next`: the variants the matcher keeps, the
4883 * result tagged the same way, `next.is` narrowing as the matcher does.
4884 */
4885 type MatchedStreamNext<P extends StreamingEventName, M> = StreamNext<P, KeptEvent<P, M>, MatchedResult<P, M>, MatchedStreamNarrowings<P, M>>;
4886
4887 /**
4888 * What `on(event, matcher, hook)` takes for an argument of type `I`: the
4889 * shape of the `e` the hook wants, a partial of it at any depth.
4890 *
4891 * A leaf is `===` or a RegExp (`{ command: /^p4 / }`); an array is any-of;
4892 * an object is a partial of an OBJECT, so `{ command: { startsWith } }` is
4893 * a type error where `e` is typed and free where it is `unknown`.
4894 */
4895 export type Matcher<I, All = I> = I extends unknown ? {
4896 readonly [K in KnownKeys<I>]?: MatcherValue<I[K], MatcherValueOf<All, K>>;
4897 } & (string extends keyof I ? OpenMatcher<I, All> : unknown) : never;
4898
4899 /**
4900 * Any matcher at all, for a field typed `unknown` (a tool's input, a
4901 * result's output): the kinds the engine accepts, unchecked there.
4902 *
4903 * The four kinds: a scalar is `===`; a RegExp tests the value as a string
4904 * (`{ command: /^p4 / }`); an array matches if any element does; an object
4905 * is a partial of an object. `{ startsWith: 'p4' }` never matches a string.
4906 */
4907 type MatcherData = string | number | boolean | null | RegExp | readonly MatcherData[] | {
4908 readonly [key: string]: MatcherData;
4909 };
4910
4911 /**
4912 * The declared keys of every variant of `I` (index signatures aside).
4913 */
4914 type MatcherKeys<I> = I extends unknown ? KnownKeys<I> : never;
4915
4916 /**
4917 * What matches one value of type `V`, by the runtime's kinds:
4918 * a scalar leaf takes the value or a RegExp; an object, a partial of it.
4919 *
4920 * For an array, what matches one ELEMENT of it, since a pattern against an
4921 * array value holds when some element matches; for `unknown`, any matcher.
4922 * A scalar matches by `===`, a RegExp tests the value as a string.
4923 */
4924 type MatcherOne<V> = unknown extends V ? MatcherData : V extends readonly (infer Item)[] ? MatcherOne<Item> : V extends string | number | boolean | null ? V | RegExp : V extends object ? Matcher<V> : V extends undefined ? never : unknown;
4925
4926 /**
4927 * What a matcher gives a key whose value is `V` on this variant and `Across`
4928 * over every variant: one MatcherOne, or an array of them matched as one-of.
4929 *
4930 * The one-of is typed over every variant, so `{ tool: ['Bash', 'Read'] }`
4931 * types on the Bash variant; with a nested pattern beside it, the pattern is
4932 * checked against a variant the one-of names, not against each of them.
4933 */
4934 type MatcherValue<V, Across = V> = MatcherOne<V> | readonly MatcherOne<Across>[];
4935
4936 /**
4937 * The type of key `K` across the variants of `I` that declare it.
4938 */
4939 type MatcherValueOf<I, K> = I extends unknown ? K extends KnownKeys<I> ? I[K] : never : never;
4940
4941 /**
4942 * One block of an MCP result: `type` and the fields that kind of block carries.
4943 */
4944 export type McpContentBlock = {
4945 /**
4946 * The block's kind: `text`, `image`, `audio`, `resource`, `resource_link`.
4947 */
4948 type: string;
4949 /**
4950 * Set on a `text` block.
4951 */
4952 text?: string;
4953 /**
4954 * Set on a `resource_link` (or embedded `resource`) block.
4955 */
4956 uri?: string;
4957 /**
4958 * Declared by an image, audio or resource block.
4959 */
4960 mimeType?: string;
4961 [field: string]: unknown;
4962 };
4963
4964 /**
4965 * The MCP server serving this tool, for `mcp__*` tools: `name` is the server's config key (for `source: "sdk"`, exactly the name the SDK host registered in `sdkMcpServers` / `mcp_set_servers`; for any other source, the key as authored in that configuration - untrusted text, the same value `mcp_status` and system/init report, to be escaped before display), `source` is where its definition came from - `sdk` (an in-process server the SDK host runs; only the host can register one, so a configured server of the same name never reads `sdk`), `plugin` (a server a plugin ships or registers at runtime), or a config scope (`user`, `project`, `local`, `dynamic` for --mcp-config / `mcp_set_servers` process servers, `managed`, `enterprise`, `claudeai`, `agent`). Key trust on `source`, not on the name or the tool-name prefix. Absent for non-MCP tools.
4966 */
4967 type McpServerProvenance = {
4968 name: string;
4969 /**
4970 * sdk | plugin | user | project | local | dynamic | managed | enterprise | claudeai | agent - an open set; treat unknown values as an unrecognized configured source, never as sdk.
4971 */
4972 source: string;
4973 };
4974
4975 /**
4976 * The MCP branch of a `tool.call` hook's `e` (and of `$.tool.call`'s input):
4977 * one variant per declared tool, else the loose McpToolCallInputFallback.
4978 *
4979 * `$.mcp.call(server, tool, args)` takes none of these: its parameters are
4980 * positional, the server and tool by name, then the arguments object.
4981 */
4982 export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
4983 [N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
4984 }[keyof McpToolInputs & string];
4985
4986 /**
4987 * The `e` a `tool.call` (or `classic.PreToolUse`) hook receives for an MCP
4988 * tool while no MCP tool is declared: every `mcp__*` name, loose arguments.
4989 *
4990 * McpToolInputs has no entries until `/plugin-types` writes the connected
4991 * tools' declarations; also the `input` of `$.tool.call({ tool:
4992 * "mcp__<server>__<tool>", ... })`. Not `$.mcp.call`'s, which is positional:
4993 *
4994 * @example
4995 * on("tool.call", { tool: "mcp__gh__issue" }, ($, e, next) => audit(e.title))
4996 */
4997 type McpToolCallInputFallback = {
4998 /**
4999 * The name of the tool being called (`mcp__<server>__<tool>`); comparing
5000 * it narrows `e`. Reserved: a rewrite of it is ignored by core.
5001 */
5002 tool: McpToolName;
5003 /**
5004 * The tool_use block's id: the same at every event of the call and in
5005 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
5006 */
5007 tool_use_id: string;
5008 [argument: string]: unknown;
5009 };
5010
5011 /**
5012 * The inputs of the MCP tools this project knows, keyed by full tool name,
5013 * for declaration merging; empty by default, then every MCP tool is loose.
5014 *
5015 * A `.d.ts` in the plugin author's project (written by `/plugin-types <dir>`
5016 * from the connected servers' JSON Schemas, or by hand) adds entries under
5017 * `declare module "claude-code"`; `e.tool === <name>` then narrows to them.
5018 *
5019 * @example
5020 * interface McpToolInputs { "mcp__my_server__send": { to: string } }
5021 */
5022 export interface McpToolInputs {
5023 }
5024
5025 /**
5026 * The name of an MCP tool as the engine spells it: `mcp__<server>__<tool>`.
5027 */
5028 export type McpToolName = `mcp__${string}__${string}`;
5029
5030 /**
5031 * An MCP tools/call result as the SDK returns it, plain data.
5032 */
5033 export type McpToolResult = {
5034 /**
5035 * The result's content blocks, in order (text, image, resource,
5036 * resource_link, ...).
5037 */
5038 content: McpContentBlock[];
5039 /**
5040 * True when the server reported the call as failed; the blocks then describe
5041 * the error.
5042 */
5043 isError: boolean;
5044 /**
5045 * The server's structured result, when its tool declares an output schema.
5046 */
5047 structuredContent?: unknown;
5048 };
5049
5050 /**
5051 * Hook input for the MessageDisplay event. Fired with each batch of newly completed lines while an assistant message streams. Display-only: the stored message and what the model sees are untouched.
5052 */
5053 type MessageDisplayHookInput = BaseHookInput & {
5054 hook_event_name: 'MessageDisplay';
5055 /**
5056 * UUID of the current turn.
5057 */
5058 turn_id: string;
5059 /**
5060 * UUID of the assistant message being displayed. Stable across every flush of the same message. Not the API msg_... id.
5061 */
5062 message_id: string;
5063 /**
5064 * Zero-based index of this delta within the message. Increments by one per flush.
5065 */
5066 index: number;
5067 /**
5068 * True on the message's last flush. Exactly one flush per message has it.
5069 */
5070 final: boolean;
5071 /**
5072 * The newly completed lines since the prior flush. Always whole lines, except on the final flush which may end mid-line. The delta of the final flush is empty when the message ends on a newline; treat final as the end-of-message signal regardless.
5073 */
5074 delta: string;
5075 };
5076
5077 /**
5078 * What `$.model.complete` takes.
5079 */
5080 export type ModelCompleteRequest = {
5081 /**
5082 * An alias (`haiku`) or a full model id; resolved and allowlist-checked like
5083 * a `--model` value.
5084 */
5085 model: string;
5086 /**
5087 * The one user message; the reply's text comes back.
5088 */
5089 prompt: string;
5090 /**
5091 * Precedes the completion as its system prompt, after the CLI's identity
5092 * block. Default none.
5093 */
5094 system?: string;
5095 /**
5096 * The reply's token cap: any positive integer up to what one reply can
5097 * hold, the model's own output limit or 64000, whichever is lower.
5098 *
5099 * Default 1024. The reply comes back whole, not streamed, and a provider
5100 * ends such a request at ten minutes, hence the 64000. One past the limit
5101 * is refused, naming it.
5102 */
5103 maxTokens?: number;
5104 };
5105
5106 /**
5107 * What `$.model.fork` takes.
5108 */
5109 export type ModelForkRequest = {
5110 /**
5111 * The one user message, appended to the session's own transcript.
5112 *
5113 * The reply's text and usage come back, or null on an API error or a cold
5114 * transcript.
5115 */
5116 prompt: string;
5117 };
5118
5119 /**
5120 * What `$.model.fork` resolves to when the fork answered: the reply's text
5121 * and what the fork cost.
5122 */
5123 export type ModelForkResult = {
5124 /**
5125 * The non-error replies' text, joined by newlines.
5126 */
5127 text: string;
5128 /**
5129 * The fork's token counts, so a plugin can account for what it spent.
5130 */
5131 usage: ModelForkUsage;
5132 };
5133
5134 /**
5135 * What one fork cost, as the API counted it: the four token counts of the
5136 * fork's completions summed.
5137 */
5138 export type ModelForkUsage = {
5139 input_tokens: number;
5140 output_tokens: number;
5141 cache_read_input_tokens: number;
5142 cache_creation_input_tokens: number;
5143 };
5144
5145 /**
5146 * The prefixes a glob may name: one or more whole leading segments of an
5147 * event name (`tool` of `tool.call`), derived, plugin nouns included.
5148 */
5149 export type Namespace<N extends string = EventName> = N extends `${infer Head}.${infer Rest}` ? Head | `${Head}.${Namespace<Rest>}` : never;
5150
5151 /**
5152 * How many object or array levels a matcher narrows `e` through, counted as
5153 * a tuple's length: the runtime's own limit, which refuses a deeper matcher.
5154 *
5155 * Past it a field keeps its declared type; nothing becomes `any`.
5156 */
5157 type NarrowDepth = 8;
5158
5159 /**
5160 * `e` in a matched hook: the members of the argument union `E` matcher `P`
5161 * can match, each with the keys `P` names narrowed to what a match implies.
5162 *
5163 * A scalar narrows to the literal, a one-of to what its alternatives give,
5164 * an object key recursively, an array some element of which must match to
5165 * a non-empty tuple; other keys, `unknown` and RegExp-matched fields keep.
5166 */
5167 export type Narrowed<E, P> = E extends unknown ? NarrowedMember<E, P, []> : never;
5168
5169 /**
5170 * A value of declared type `V` under a one-of, folded over the tuple into
5171 * `Found`: the union of what each alternative narrows `V` to (NarrowedByOne).
5172 *
5173 * An alternative that cannot match adds nothing, so a one-of none of whose
5174 * alternatives can is `never`; a one-of typed as a plain array rather than
5175 * a tuple narrows by the union of its elements at once.
5176 */
5177 type NarrowedByAny<V, Alternatives extends readonly unknown[], D extends readonly unknown[], Found = never> = Alternatives extends readonly [infer First, ...infer Rest] ? NarrowedByAny<V, Rest, D, Found | NarrowedByOne<V, First, D>> : Alternatives extends readonly [] ? Found : Found | NarrowedByOne<V, Alternatives[number], D>;
5178
5179 /**
5180 * A value of declared type `V` under one matcher node `Q` that is not a
5181 * one-of, member of `V` by member; a member that cannot match is `never`.
5182 *
5183 * An array some element of which must match becomes NonEmpty; a RegExp
5184 * keeps the member; an object pattern recurses into an object member, one
5185 * level down; a scalar keeps a member as narrow, and replaces a wider one.
5186 */
5187 type NarrowedByOne<V, Q, D extends readonly unknown[]> = V extends readonly (infer Item)[] ? [NarrowedValue<Item, Q, [...D, unknown]>] extends [never] ? never : NonEmpty<V, Item> : Q extends RegExp ? V : Q extends object ? V extends object ? NarrowedMember<V, Q, [...D, unknown]> : never : V extends Q ? V : Q extends V ? Q : never;
5188
5189 /**
5190 * One object member `E` under object pattern `P`, `D` levels down: `never`
5191 * when a key of `P` is impossible on it (ImpossibleKeys), else `E` narrowed.
5192 *
5193 * Each key `P` names is narrowed (NarrowedValue); every other key, and each
5194 * key's optionality, stays as declared.
5195 */
5196 type NarrowedMember<E, P, D extends readonly unknown[]> = [
5197 ImpossibleKeys<E, P, D>
5198 ] extends [never] ? {
5199 [K in keyof E]: K extends keyof P ? NarrowedValue<E[K], P[K], D> : E[K];
5200 } : never;
5201
5202 /**
5203 * A value of declared type `V` where the matcher gives `Q`, `D` levels
5204 * down: NarrowedByAny under a one-of (an array), NarrowedByOne otherwise.
5205 *
5206 * As declared once `D` reaches NarrowDepth, or for a field typed `unknown`
5207 * (a tool's input), which no pattern narrows.
5208 */
5209 type NarrowedValue<V, Q, D extends readonly unknown[]> = D['length'] extends NarrowDepth ? V : unknown extends V ? V : Q extends readonly unknown[] ? NarrowedByAny<V, Q, D> : NarrowedByOne<V, Q, D>;
5210
5211 /**
5212 * `!` before a name or a glob: every event except the ones it selects. `!*`
5213 * would select none, so it is no pattern.
5214 */
5215 type Negation = `!${Exclude<EventName | Glob, '*'>}`;
5216
5217 /**
5218 * The rest of the chain, as one hook receives it: made once per dispatch per
5219 * hook, frozen; `next(e)` resolves to the downstream result.
5220 *
5221 * Each call runs the hooks below again; core is the last, and below it `next`
5222 * rejects. Called with no argument it rejects, naming the hook. A hook that
5223 * returns without calling it ends the chain; returning nothing is a failure.
5224 *
5225 * @template S what `next.is(pattern, e)` narrows `e` to, per event: the event's
5226 * argument, or, under a matcher, that argument narrowed by it (MatchedHook)
5227 * @template T the tool `e` names, when it names one: on `tool.call` it types
5228 * the result (NextResultFor); an `e` without `tool` takes the line beneath
5229 */
5230 export type Next<N extends EventName = EventName, E = Args<N>, O = NextResult<N>, S extends {
5231 [K in N]?: unknown;
5232 } = {
5233 [K in N]: Args<K>;
5234 }> = {
5235 <T extends string>(e: E & ToolNamed<T>): Promise<NextResultFor<N, O, T>>;
5236 (e: E): Promise<O>;
5237 /**
5238 * Continues this dispatch at a tier: `next(e)` with every link between
5239 * this hook's own tier and that one skipped, by tier and narrowing only.
5240 *
5241 * A managed hook's: prepend may name append, builtin or core, append core;
5242 * it never skips a tier with more authority, so no user hook skips the
5243 * org's. A literal on the hook's own `next`; skipped links are traced.
5244 */
5245 readonly to: {
5246 <T extends string>(e: E & ToolNamed<T>, tier: TargetTier): Promise<NextResultFor<N, O, T>>;
5247 (e: E, tier: TargetTier): Promise<O>;
5248 };
5249 /**
5250 * Aborts when the call this dispatch belongs to is abandoned: the user
5251 * interrupted, a hook above settled first, or this hook ran out of budget.
5252 *
5253 * Anything the hook started (timers, requests) should stop on it. It is an
5254 * AbortSignal of the plugin's own environment, driven by the chain's.
5255 */
5256 readonly signal: AbortSignal;
5257 /**
5258 * Whether this dispatch's event is selected by `pattern` (a name, a glob,
5259 * a negation), as a type predicate on `e`: `next.is("tool.call", e)`.
5260 *
5261 * Under a matcher the narrowing includes it. `pattern` names events this
5262 * hook covers (PatternOver); a name outside them is a compile error.
5263 */
5264 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<S[Extract<N, Selected<M>>]>;
5265 /**
5266 * The name of this dispatch's event, as a value, for a glob hook to log or
5267 * switch on.
5268 */
5269 readonly event: N;
5270 /**
5271 * Who raised this dispatch: the calling plugin's name and the tier it sits
5272 * in (Origin); the engine reads `{ plugin: "engine", tier: "core" }`.
5273 *
5274 * Set by the host alone, from the environment the call came from (its own
5275 * MessagePort) and that plugin's seat; nothing a plugin writes reaches it.
5276 * Every hook of one dispatch sees the same origin, and `next.to` keeps it.
5277 *
5278 * @example
5279 * return next.origin.tier === "prepend" ? next.to(e, "append") : next(e)
5280 */
5281 readonly origin: Origin;
5282 /**
5283 * What settled beneath this hook on its latest `next()` call, the one
5284 * started last: an entry per link beneath, nearest first, the engine's last.
5285 *
5286 * Empty before `next` is called; filled even when `next` rejected; a link
5287 * still running joins in place later, nothing listed leaves; it ends short
5288 * of the engine at a link that answered its last call itself. Data, frozen.
5289 */
5290 readonly trace: readonly TraceEntry<N, E, O>[];
5291 /**
5292 * How much time this hook runs under and how much is left (NextBudget),
5293 * read fresh on each access; HookBudget says what the clock counts.
5294 *
5295 * It stands still while a `next` or `$` call of the hook's is in flight;
5296 * in a `.catch` handler it is the grace, `ms` being `next.error.budget`.
5297 *
5298 * @example
5299 * if (next.budget.remainingMs < 2_000) return next(e) // skip the polish
5300 */
5301 readonly budget: NextBudget;
5302 };
5303
5304 /**
5305 * The budget the code reading `next.budget` runs under: the whole allowance
5306 * and what is left of it now, plain data read fresh on each access.
5307 *
5308 * In a hook `ms` is HookBudget's `ms`; in a `.catch` handler its `catchMs`
5309 * (equal to `next.error.budget`); on a `next` nothing meters (the engine's
5310 * own, a test's root one) `ms` is 0 and `remainingMs` Infinity.
5311 *
5312 * @example
5313 * if (next.budget.remainingMs < 2_000) return next(e) // skip the slow path
5314 */
5315 export type NextBudget = {
5316 /**
5317 * The whole budget in milliseconds; 0 where nothing meters this `next`.
5318 */
5319 readonly ms: number;
5320 /**
5321 * What is left of it now, in milliseconds, never below 0; Infinity where
5322 * nothing meters. It stands still while a `next` or `$` call is in flight.
5323 */
5324 readonly remainingMs: number;
5325 };
5326
5327 /**
5328 * What `next(e)` resolves to for event `N`: the event's result, except at
5329 * `engine.create`, where the steps beneath return `$` as built so far.
5330 *
5331 * A withheld noun is on that `$` as a stub, so the built table is typed
5332 * whole where what a hook returns (EngineCreateResult) is partial.
5333 */
5334 export type NextResult<N extends EventName> = N extends 'engine.create' ? EngineInterfaceBuilt : EventResult<N>;
5335
5336 /**
5337 * What `next(e)` resolves to once `e.tool` is the literal `T`: on `tool.call`
5338 * the result typed for that tool; on every other event, `O` as declared.
5339 *
5340 * `result` is Bash's record after `e.tool === "Bash"`; an un-narrowed `e`
5341 * names every tool, and `result` stays `unknown`.
5342 */
5343 export type NextResultFor<N extends EventName, O, T extends string> = [
5344 N
5345 ] extends ['tool.call'] ? ToolCallResult<T> : O;
5346
5347 /**
5348 * The argument of a call on `$` that takes nothing (`$.session.cwd()`): an
5349 * object with no keys.
5350 */
5351 type NoArgs = Record<never, never>;
5352
5353 /**
5354 * The events whose argument is exactly NoArgs (`session.cwd`, a declared
5355 * plugin noun's `() => ...`); their overloads come last (LateOverload).
5356 */
5357 type NoArgsEvent = {
5358 [N in EventName]: Args<N> extends NoArgs ? NoArgs extends Args<N> ? N : never : never;
5359 }[EventName];
5360
5361 /**
5362 * What an `engine.create` hook receives as `$`: nothing. Every property
5363 * reads as `never`, so `$.model` inside the hook is a compile error.
5364 */
5365 export type NoEngineInterface = {
5366 readonly [noun: string]: never;
5367 };
5368
5369 /**
5370 * Array type `V`, of element `Item`, once some element of it is known to
5371 * match: a tuple of at least one `Item`, readonly when `V` is.
5372 *
5373 * So `e` still passes wherever the declared array is taken; a `V` that is
5374 * already a non-empty tuple is kept as it is.
5375 */
5376 type NonEmpty<V, Item> = V extends readonly [unknown, ...unknown[]] ? V : V extends Item[] ? [Item, ...Item[]] : readonly [Item, ...Item[]];
5377
5378 type NotificationHookInput = BaseHookInput & {
5379 hook_event_name: 'Notification';
5380 message: string;
5381 title?: string;
5382 notification_type: string;
5383 };
5384
5385 /**
5386 * The declared plugin nouns' methods as event rows (NounEventRow), one per
5387 * `<noun>.<method>` that is a function; a member that is not is no event.
5388 */
5389 type NounEvent = {
5390 [K in PluginNoun]: {
5391 [M in keyof EngineInterface[K] & string]: EngineInterface[K][M] extends (...args: infer Parameters) => infer Result ? NounEventRow<`${K}.${M}`, Parameters extends readonly [] ? NoArgs : Parameters[0], Awaited<Result>> : never;
5392 }[keyof EngineInterface[K] & string];
5393 }[PluginNoun];
5394
5395 /**
5396 * The name of a declared plugin noun's event (`voice.speak`).
5397 */
5398 type NounEventName = keyof NounEventOf & string;
5399
5400 /**
5401 * The events of the plugin nouns declared on EngineInterface, by name: the
5402 * argument of each `<noun>.<method>`. Empty until a plugin declares a noun.
5403 *
5404 * @example
5405 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
5406 */
5407 export type NounEventOf = {
5408 [E in NounEvent as E['name']]: E['args'];
5409 };
5410
5411 /**
5412 * The result of a declared plugin noun's event as its hooks see it:
5413 * `{ value }` (the method's answer) or `{ deny }`.
5414 */
5415 type NounEventResult<N extends NounEventName> = ValueOrDeny<NounValueOf[N]>;
5416
5417 /**
5418 * One method of a declared plugin noun as an event row: its event's name,
5419 * argument (the method's first parameter) and value (its awaited result).
5420 */
5421 type NounEventRow<Name extends string, Args, Value> = {
5422 name: Name;
5423 args: Args;
5424 value: Value;
5425 };
5426
5427 /**
5428 * What each declared plugin noun's method answers (the `value` of its
5429 * event's result), by event name.
5430 */
5431 type NounValueOf = {
5432 [E in NounEvent as E['name']]: E['value'];
5433 };
5434
5435 /**
5436 * Registers `hook` on the events `pattern` selects: one by name, every one
5437 * under a namespace (`classic.*`), all (`*`), or all but some (`!tool.*`).
5438 *
5439 * One function stands on every selected event (`next.event` says which),
5440 * under a matcher for the inputs it matches; a plugin's registrations nest
5441 * in order, first outermost; a repeat throws. Returns the Registration.
5442 *
5443 * @see HookBudget the time each hook has per dispatch (its own time: waits
5444 * on `next` and `$` are free), read live from `next.budget`
5445 */
5446 export type On = {
5447 <P extends Pattern>(pattern: P, hook: NoInfer<HookFor<P>>): Registration<HookFor<P>>;
5448 <P extends Pattern, const M extends Matcher<Args<MatchedNames<P>>>>(pattern: P, matcher: M, hook: NoInfer<MatchedHook<P, M>>): Registration<MatchedHook<P, M>>;
5449 };
5450
5451 /**
5452 * The part of a transcript message the surface that drew it has on screen:
5453 * units `first` to `last` of the message's `of`, counted from its start.
5454 *
5455 * The terminal counts the rows the site laid out, from its first (the blank
5456 * row the engine draws above a message is its row 0; a hook's tree starts at
5457 * its own); other surfaces count in their unit, so compare `first / of` there.
5458 *
5459 * @remarks While `null` the terminal holds the site at the rows it last laid
5460 * out (a scroller's geometry needs real rows); on screen, draw anything.
5461 * @example if (e.props.onScreen) shown.set(e.requestId, e.props.onScreen)
5462 * else shown.delete(e.requestId) // the band's legend lists `shown`
5463 */
5464 type OnScreen = {
5465 /**
5466 * The unit inside the viewport, from 0: on the terminal, `7` when the
5467 * message's top seven rows are scrolled away.
5468 */
5469 first: number;
5470 /**
5471 * The unit inside the viewport, inclusive; at least `first`.
5472 */
5473 last: number;
5474 /**
5475 * The message's whole extent in the same unit, as laid out (a hook's tree
5476 * taller than the engine's counts its own rows); more than `last`.
5477 *
5478 * One surface's numbers say nothing of another's: what the phone shows the
5479 * terminal may not, and each `ui.render` carries its own surface's.
5480 */
5481 of: number;
5482 };
5483
5484 /**
5485 * The keys a variant with a string index signature (an MCP tool's input)
5486 * takes beyond its own: another variant's key as typed there; others free.
5487 *
5488 * So a misspelt value for a key some variant declares (`command: 5`) is
5489 * refused on every variant, not admitted by the open one.
5490 */
5491 type OpenMatcher<I, All> = {
5492 readonly [K in Exclude<MatcherKeys<All>, KnownKeys<I>>]?: MatcherValue<MatcherValueOf<All, K>>;
5493 } & Readonly<Record<string, unknown>>;
5494
5495 /**
5496 * The name of a call on `$` the host serves, as an event.
5497 */
5498 export type OpEventName = keyof OpEventOf;
5499
5500 /**
5501 * The calls on `$` the host serves, as events: `e` is the call's argument as
5502 * it crosses to the host, and every one is hookable by name and by `on("*")`.
5503 *
5504 * A hook above the caller passes it on, rewrites it, refuses it with
5505 * `{ deny }` or answers with `{ value }`; core is the host's implementation.
5506 * The calling hook alone is skipped, and `next.origin` names the caller.
5507 */
5508 export type OpEventOf = {
5509 /**
5510 * The argument of `$.model.complete(request)`.
5511 */
5512 'model.complete': ModelCompleteRequest;
5513 /**
5514 * The argument of `$.model.classify(text, labels, options)`.
5515 */
5516 'model.classify': {
5517 text: string;
5518 labels: readonly string[];
5519 options?: ClassifyOptions;
5520 };
5521 /**
5522 * The argument of `$.model.fork(request)`.
5523 */
5524 'model.fork': ModelForkRequest;
5525 /**
5526 * The clip and how to play it (`shouldLoop`, `gain`); the signal does not
5527 * cross.
5528 */
5529 'audio.play': {
5530 clip: AudioClip;
5531 shouldLoop: boolean;
5532 gain?: number;
5533 };
5534 /**
5535 * The argument of `$.audio.speak(text, { voice })`.
5536 */
5537 'audio.speak': SpeakRequest;
5538 /**
5539 * The argument of `$.mcp.call(server, tool, args)`.
5540 */
5541 'mcp.call': {
5542 server: string;
5543 tool: string;
5544 args: Record<string, unknown>;
5545 };
5546 /**
5547 * The argument of `$.session.cwd()`.
5548 */
5549 'session.cwd': NoArgs;
5550 /**
5551 * The argument of `$.session.root()`.
5552 */
5553 'session.root': NoArgs;
5554 /**
5555 * The argument of `$.session.model()`.
5556 */
5557 'session.model': NoArgs;
5558 /**
5559 * The argument of `$.session.turns()`.
5560 */
5561 'session.turns': NoArgs;
5562 /**
5563 * The argument of `$.session.id()`.
5564 */
5565 'session.id': NoArgs;
5566 /**
5567 * The argument of `$.session.messages()`.
5568 */
5569 'session.messages': NoArgs;
5570 /**
5571 * The argument of `$.session.repo()`.
5572 */
5573 'session.repo': NoArgs;
5574 /**
5575 * The argument of `$.session.surface()`.
5576 *
5577 * @deprecated with `$.session.surface()`; hook `session.surfaces`
5578 */
5579 'session.surface': NoArgs;
5580 /**
5581 * The argument of `$.session.surfaces()`.
5582 */
5583 'session.surfaces': NoArgs;
5584 /**
5585 * The argument of `$.session.authorize()`.
5586 */
5587 'session.authorize': NoArgs;
5588 /**
5589 * The argument of `$.session.usage({ breakdown, columns })`.
5590 */
5591 'session.usage': SessionUsageArgs;
5592 /**
5593 * The argument of `$.session.version()`.
5594 */
5595 'session.version': NoArgs;
5596 /**
5597 * The argument of `$.turn.abort({ turnId })`.
5598 */
5599 'turn.abort': {
5600 turnId: string;
5601 };
5602 /**
5603 * The argument of `$.prompt.read()`.
5604 */
5605 'prompt.read': NoArgs;
5606 /**
5607 * The argument of `$.tool.list()`.
5608 */
5609 'tool.list': NoArgs;
5610 /**
5611 * The argument of `$.tool.register(spec)`.
5612 */
5613 'tool.register': Required<ToolSpec>;
5614 /**
5615 * The argument of `$.command.list()`.
5616 */
5617 'command.list': NoArgs;
5618 /**
5619 * The argument of `$.command.register(spec)`.
5620 */
5621 'command.register': CommandSpec;
5622 /**
5623 * The argument of `$.config.list()`.
5624 */
5625 'config.list': NoArgs;
5626 /**
5627 * The argument of `$.agent.list()`.
5628 */
5629 'agent.list': NoArgs;
5630 /**
5631 * The argument of `$.agent.register(spec)`: the agent type as the plugin
5632 * defined it. A hook above rewrites any of it; the type stays the caller's.
5633 */
5634 'agent.register': AgentSpec;
5635 /**
5636 * The argument of `$.ui.toast(text, { timeoutMs })`.
5637 */
5638 'ui.toast': {
5639 text: string;
5640 timeoutMs?: number;
5641 };
5642 /**
5643 * The argument of `$.ui.status(text)`; `text` undefined clears the line.
5644 */
5645 'ui.status': {
5646 text: string | undefined;
5647 };
5648 /**
5649 * The argument of `$.ui.log(text, { to })`; `to` is always present
5650 * (UiLogSink), and `next({ ...e, to: "debug" })` keeps a line off screen.
5651 */
5652 'ui.log': {
5653 text: string;
5654 to: UiLogSink;
5655 };
5656 /**
5657 * The argument of `$.ui.notice(tool_use_id, text)`.
5658 */
5659 'ui.notice': {
5660 tool_use_id: string;
5661 text: string | undefined;
5662 };
5663 /**
5664 * The argument of `$.ui.invalidate(event)`.
5665 */
5666 'ui.invalidate': {
5667 event: InvalidatableEventName;
5668 };
5669 /**
5670 * The argument of `$.ui.open({ id, title, focus })`; a hook above the
5671 * opener may retitle it or refuse it with `{ deny }`, never rename it.
5672 */
5673 'ui.open': PaneOpenArgs;
5674 /**
5675 * The argument of `$.ui.close({ id })` with `origin` `plugin`; the engine
5676 * raises it too, for the person (`person`) and an unload (`unload`).
5677 */
5678 'ui.close': PaneCloseInput;
5679 /**
5680 * The argument of `$.ui.panes()`.
5681 */
5682 'ui.panes': NoArgs;
5683 /**
5684 * The argument of `$.ui.blit(...)`: a Raster's `cells` or a keyed Image's
5685 * `source`; a hook above may rewrite either with `next`, or `{ deny }`.
5686 */
5687 'ui.blit': UiBlitArgs;
5688 /**
5689 * The argument of `$.fs.read(path, { as })`: `as` is `text` unless the
5690 * caller asked for `bytes`.
5691 */
5692 'fs.read': {
5693 path: string;
5694 as: FsReadAs;
5695 };
5696 /**
5697 * The argument of `$.fs.write(path, text)`.
5698 */
5699 'fs.write': {
5700 path: string;
5701 text: string;
5702 };
5703 /**
5704 * The argument of `$.fs.list(path)`.
5705 */
5706 'fs.list': {
5707 path: string;
5708 };
5709 /**
5710 * The argument of `$.fs.exists(path)`.
5711 */
5712 'fs.exists': {
5713 path: string;
5714 };
5715 /**
5716 * The argument of `$.fs.stat(path, { resolve })`: `resolve` is false
5717 * unless the caller asked where the path lands.
5718 */
5719 'fs.stat': {
5720 path: string;
5721 resolve: boolean;
5722 };
5723 /**
5724 * The argument of `$.fs.ancestors({ names, of, below })`.
5725 */
5726 'fs.ancestors': FsAncestorsRequest;
5727 /**
5728 * The argument of `$.store.get(key)`.
5729 */
5730 'store.get': {
5731 key: string;
5732 };
5733 /**
5734 * The argument of `$.store.set(key, value)`.
5735 */
5736 'store.set': {
5737 key: string;
5738 value: unknown;
5739 };
5740 /**
5741 * The argument of `$.store.delete(key)`.
5742 */
5743 'store.delete': {
5744 key: string;
5745 };
5746 /**
5747 * The argument of `$.store.keys()`.
5748 */
5749 'store.keys': NoArgs;
5750 /**
5751 * The argument of `$.clock.now()`.
5752 */
5753 'clock.now': NoArgs;
5754 /**
5755 * The argument of `$.clock.sleep(ms, { signal })`; the signal does not
5756 * cross, it aborts the dispatch.
5757 */
5758 'clock.sleep': ClockWait;
5759 /**
5760 * The argument of `$.clock.after(ms, fn)`: the wait before `fn`, which
5761 * stays in the plugin's environment and runs once the dispatch resolves.
5762 */
5763 'clock.after': ClockWait;
5764 /**
5765 * The argument of `$.clock.every(ms, fn)`, dispatched once per period:
5766 * `fn` runs each time a dispatch resolves, and the next period is asked.
5767 */
5768 'clock.every': ClockWait;
5769 /**
5770 * The argument of `$.http.fetch(url, init)`.
5771 */
5772 'http.fetch': {
5773 url: string;
5774 init?: HttpInit;
5775 };
5776 /**
5777 * The argument of `$.process.run(argv, init)`.
5778 */
5779 'process.run': {
5780 argv: readonly string[];
5781 init?: ProcessRunInit;
5782 };
5783 /**
5784 * The argument of `$.settings.read({ source })`.
5785 */
5786 'settings.read': SettingsReadArgs;
5787 /**
5788 * The argument of `$.env.get(name)`; `name` is identity, pinned.
5789 */
5790 'env.get': {
5791 name: string;
5792 };
5793 /**
5794 * The argument of `$.env.set(name, value)`; `name` is identity, pinned,
5795 * and no `value` unsets.
5796 */
5797 'env.set': {
5798 name: string;
5799 value?: string;
5800 };
5801 };
5802
5803 /**
5804 * The result of a call on `$` as its event's hooks see it: `{ value }` (the
5805 * call's answer) or `{ deny }`.
5806 */
5807 export type OpEventResult<N extends OpEventName = OpEventName> = ValueOrDeny<OpValueOf[N]>;
5808
5809 /**
5810 * What each call on `$` answers (the `value` of its event's result), by event
5811 * name.
5812 */
5813 export type OpValueOf = {
5814 'model.complete': string;
5815 'model.classify': string | undefined;
5816 'model.fork': ModelForkResult | null;
5817 'audio.play': void;
5818 'audio.speak': SpeakResult;
5819 'mcp.call': McpToolResult;
5820 'session.cwd': string;
5821 'session.root': string;
5822 'session.model': string;
5823 'session.turns': number;
5824 'session.id': string;
5825 'session.messages': SessionMessage[];
5826 'session.repo': SessionRepo | null;
5827 'session.surface': RenderSurface | null;
5828 'session.surfaces': readonly RenderSurface[];
5829 /**
5830 * The credential handle, or null where the build or the provider has no
5831 * first-party credential to hold.
5832 */
5833 'session.authorize': SessionAuthorization;
5834 'session.usage': SessionUsage;
5835 /**
5836 * The engine's version, its release, and its build time when stamped.
5837 */
5838 'session.version': SessionVersion;
5839 'turn.abort': void;
5840 /**
5841 * The box as it stands; the empty box where the session draws none.
5842 */
5843 'prompt.read': PromptBox;
5844 'tool.list': ToolInfo[];
5845 'tool.register': {
5846 tool: string;
5847 };
5848 'command.list': CommandInfo[];
5849 'command.register': {
5850 command: string;
5851 };
5852 'config.list': ConfigRow[];
5853 'agent.list': AgentInfo[];
5854 'agent.register': {
5855 agent: string;
5856 };
5857 'ui.toast': void;
5858 'ui.status': void;
5859 'ui.log': void;
5860 'ui.notice': void;
5861 'ui.invalidate': void;
5862 'ui.open': void;
5863 'ui.close': void;
5864 /**
5865 * The calling plugin's open panes, placed then unplaced, in open order.
5866 */
5867 'ui.panes': readonly UiPane[];
5868 'ui.blit': UiBlitResult;
5869 /**
5870 * The text; `{ base64 }` when asked for bytes.
5871 */
5872 'fs.read': string | FsBytes;
5873 'fs.write': void;
5874 'fs.list': FsEntry[];
5875 'fs.exists': boolean;
5876 'fs.stat': FsStat;
5877 'fs.ancestors': readonly FsAncestor[];
5878 'store.get': unknown;
5879 'store.set': void;
5880 'store.delete': void;
5881 'store.keys': string[];
5882 /**
5883 * Milliseconds since the epoch.
5884 */
5885 'clock.now': number;
5886 'clock.sleep': void;
5887 'clock.after': void;
5888 'clock.every': void;
5889 'http.fetch': HttpResponse;
5890 'process.run': ProcessRunResult;
5891 'settings.read': Settings;
5892 'env.get': string | undefined;
5893 'env.set': void;
5894 };
5895
5896 /**
5897 * One call signature per event in `Names`, intersected, the ambiguous ones
5898 * (LateOverload) after the rest: `next` for a hook covering several events.
5899 *
5900 * An empty group contributes nothing (Overloads<never> is unknown).
5901 */
5902 type OrderedOverloads<Names extends EventName> = Overloads<Exclude<Names, LateOverload>> & Overloads<Extract<Names, 'classic.PreToolUse'>> & Overloads<Extract<Names, 'turn.abort'>> & Overloads<Extract<Names, NoArgsEvent>>;
5903
5904 /**
5905 * Who raised a dispatch, as `next.origin` holds it: the calling plugin's
5906 * name and the tier it sits in; the engine reads `engine` in `core`.
5907 *
5908 * The same pair a `next.trace` entry names its link by, and an event's
5909 * `provider` its subject's definer by. Set by the host from where the call
5910 * came from and where that plugin was seated; nothing a plugin writes.
5911 */
5912 export type Origin = {
5913 /**
5914 * Whose hook made the `$` call, by name; `"engine"` for a call site,
5915 * `"client"` for a `Client` surface module's `ui.message` post.
5916 */
5917 readonly plugin: string;
5918 /**
5919 * Where that plugin sits among the chain's tiers (Tier); `"core"` for the
5920 * engine, the owning plugin's for a `client` post.
5921 */
5922 readonly tier: Tier;
5923 };
5924
5925 /**
5926 * One call signature per event in `Names`, intersected into an overload set.
5927 */
5928 type Overloads<Names extends EventName> = UnionToIntersection<{
5929 [N in Names]: (e: Args<N>) => Promise<NextResult<N>>;
5930 }[Names]>;
5931
5932 /**
5933 * The argument of `$.ui.close`: the pane to close (`{ id }`). `origin` is
5934 * the engine's to set: a plugin's call reads `plugin` at the hooks.
5935 */
5936 export type PaneCloseArgs = Omit<PaneCloseInput, 'origin'>;
5937
5938 /**
5939 * The input of `ui.close`: the pane closing and why (PaneCloseOrigin).
5940 * Closing an id that is not open does nothing.
5941 */
5942 export type PaneCloseInput = {
5943 /**
5944 * What `$.ui.open` named the pane; pinned: `next(e)` passes it on.
5945 */
5946 id: string;
5947 /**
5948 * Who closes it, set by the engine: a hook that answers without `next`
5949 * keeps the pane open on `plugin` and `person`, never on `unload`.
5950 */
5951 origin: PaneCloseOrigin;
5952 };
5953
5954 /**
5955 * Why a pane closes, as the engine stamped it at `ui.close`.
5956 *
5957 * `unload` drops a pane nothing draws any more (its plugin unloaded, or its
5958 * drawing threw): it is gone before the hooks hear of it, and its opener's
5959 * hooks do not run. `next(e)` passes the origin on as received; none sets it.
5960 */
5961 export type PaneCloseOrigin = {
5962 /**
5963 * `plugin`, a plugin's `$.ui.close`; `person`, the person's close mark or
5964 * close key; `unload`, the engine's own.
5965 */
5966 kind: 'plugin' | 'person' | 'unload';
5967 };
5968
5969 /**
5970 * The argument of `$.ui.open`: which pane, its title, whether it asks the
5971 * person's keyboard, its dialog manners, its size: rows inline, columns docked.
5972 *
5973 * An open answering the person's input (a command or prompt they entered, a
5974 * press) is placed at any width; one the plugin makes on its own waits
5975 * undrawn below 144 terminal columns, 110 once they asked for that id.
5976 */
5977 export type PaneOpenArgs = {
5978 /**
5979 * Names the pane: 1-64 of letters, digits, `_` and `-`. One pane per id:
5980 * opening an open id delivers the new title, never a second instance.
5981 *
5982 * Pinned at the hooks: `next(e)` passes it on; the title and focus rewrite.
5983 */
5984 id: string;
5985 /**
5986 * The pane's tab while more than one pane is open (with one, no title is
5987 * drawn), and the `title` its hook sees; the id when omitted.
5988 *
5989 * An unpaired surrogate half (a `.slice()` through an emoji) is drawn as
5990 * U+FFFD; a control character is refused.
5991 */
5992 title?: string;
5993 /**
5994 * A request, not a grant: the surface focuses (and raises) the pane only
5995 * while the prompt has the keys over an empty composer.
5996 *
5997 * An element of the band or a pane the person holds, text in the
5998 * composer, a dialog or a survey each refuse it: the pane opens without
5999 * the keyboard.
6000 */
6001 focus?: true;
6002 /**
6003 * While the pane holds the keyboard, the key that hands it back (Escape)
6004 * also closes it as the person's close does: `ui.close`, origin `person`.
6005 *
6006 * So does Escape at an idle, empty prompt once the prompt has the keys
6007 * again (the person typed, or `focus` was refused); over text, a running
6008 * turn, a dialog, a footer selection, a viewed agent's transcript or a
6009 * prompt mode of its own the key stays theirs.
6010 *
6011 * A hook may refuse that close and keep it open. Left out, Escape returns
6012 * the keys to the prompt and the pane stays. Each open sets it anew, as it
6013 * sets the title.
6014 */
6015 closeOnEscape?: true;
6016 /**
6017 * While the pane is on screen the surface holds its transient toasts (the
6018 * notification line under the prompt) and shows them once it closes.
6019 *
6020 * As it does behind the engine's own side panel; pinned warnings still
6021 * show. Left out, toasts show as they come. Each open sets it anew.
6022 */
6023 holdToasts?: true;
6024 /**
6025 * The body rows the pane's content wants while seated inline above the
6026 * prompt: it opens that tall, up to what the layout spares, not a third.
6027 *
6028 * A request, not a grant: a size the person dragged or keyed the block
6029 * to wins, this session's or a kept one, and the dock ignores it. A
6030 * positive whole number; left out, a third. Each open sets it anew.
6031 */
6032 rows?: number;
6033 /**
6034 * The body columns the pane's content wants while docked beside a
6035 * fullscreen transcript: the dock opens that wide, floor to ceiling.
6036 *
6037 * A request, not a grant: a width the person dragged or keyed the dock
6038 * to wins, this session's or a kept one, and the inline block ignores
6039 * it. A positive whole number; left out, the share. Each open sets it anew.
6040 *
6041 * @example
6042 * await $.ui.open({ id: "browser", focus: true, rows: 24, columns: 100 })
6043 */
6044 columns?: number;
6045 };
6046
6047 /**
6048 * What `on(pattern, hook)` and `next.is(pattern, e)` take: an event's name,
6049 * a glob (`*`, `classic.*`), or a negation of either (`!tool.describe`).
6050 */
6051 export type Pattern = EventName | Glob | Negation;
6052
6053 /**
6054 * The patterns `next.is` takes in a hook covering the events `N`: their
6055 * names, `*`, a glob over one of their namespaces, or a negation.
6056 *
6057 * A name none of them has is a compile error, as is a glob over a namespace
6058 * none is under; a negation that selects none of them narrows `e` to never.
6059 */
6060 type PatternOver<N extends EventName> = N | '*' | `${Namespace<N>}.*` | Negation;
6061
6062 type PermissionBehavior = 'allow' | 'deny' | 'ask';
6063
6064 type PermissionDeniedHookInput = BaseHookInput & {
6065 hook_event_name: 'PermissionDenied';
6066 tool_name: string;
6067 tool_input: unknown;
6068 tool_use_id: string;
6069 reason: string;
6070 mcp_server?: McpServerProvenance;
6071 };
6072
6073 /**
6074 * Permission mode for controlling how tool executions are handled. 'default' - Standard behavior, prompts for dangerous operations. 'acceptEdits' - Auto-accept file edit operations. 'bypassPermissions' - Bypass all permission checks (requires allowDangerouslySkipPermissions). 'plan' - Planning mode, no actual tool execution. 'dontAsk' - Don't prompt for permissions, deny if not pre-approved. 'auto' - Use a model classifier to approve/deny permission prompts.
6075 */
6076 type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';
6077
6078 /**
6079 * A `classic.PermissionRequest` answer's `decision`, as the classic hook's
6080 * `hookSpecificOutput.decision`: allow (with a rewrite or rules) or deny.
6081 */
6082 export type PermissionRequestDecision = {
6083 behavior: 'allow';
6084 updatedInput?: Record<string, unknown>;
6085 updatedPermissions?: PermissionUpdates;
6086 } | {
6087 behavior: 'deny';
6088 message?: string;
6089 interrupt?: true;
6090 };
6091
6092 type PermissionRequestHookInput = BaseHookInput & {
6093 hook_event_name: 'PermissionRequest';
6094 tool_name: string;
6095 tool_input: unknown;
6096 permission_suggestions?: PermissionUpdate[];
6097 mcp_server?: McpServerProvenance;
6098 };
6099
6100 type PermissionRuleValue = {
6101 toolName: string;
6102 ruleContent?: string;
6103 };
6104
6105 type PermissionUpdate = {
6106 type: 'addRules';
6107 rules: PermissionRuleValue[];
6108 behavior: PermissionBehavior;
6109 destination: PermissionUpdateDestination;
6110 } | {
6111 type: 'replaceRules';
6112 rules: PermissionRuleValue[];
6113 behavior: PermissionBehavior;
6114 destination: PermissionUpdateDestination;
6115 } | {
6116 type: 'removeRules';
6117 rules: PermissionRuleValue[];
6118 behavior: PermissionBehavior;
6119 destination: PermissionUpdateDestination;
6120 } | {
6121 type: 'setMode';
6122 mode: PermissionMode;
6123 destination: PermissionUpdateDestination;
6124 } | {
6125 type: 'addDirectories';
6126 directories: string[];
6127 destination: PermissionUpdateDestination;
6128 } | {
6129 type: 'removeDirectories';
6130 directories: string[];
6131 destination: PermissionUpdateDestination;
6132 };
6133
6134 type PermissionUpdateDestination = 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg';
6135
6136 /**
6137 * The permission rules a PermissionRequest allow may add: the shape of the
6138 * request's own `permission_suggestions` (the SDK's PermissionUpdate list).
6139 */
6140 type PermissionUpdates = NonNullable<ClassicHookInputs['PermissionRequest']['permission_suggestions']>;
6141
6142 /**
6143 * How `$.audio.play` plays a clip: looped until `signal` aborts, or once.
6144 *
6145 * A loop needs the signal that ends it; a single play takes one as an option.
6146 */
6147 export type PlayOptions = {
6148 /**
6149 * Repeat the clip until `signal` aborts (the promise then resolves).
6150 */
6151 shouldLoop: true;
6152 /**
6153 * Linear gain, from 0 to 4; default 1.
6154 */
6155 gain?: number;
6156 /**
6157 * Stops the clip: playback ends at once and the promise resolves.
6158 */
6159 signal: AbortSignal;
6160 } | {
6161 /**
6162 * Play once.
6163 */
6164 shouldLoop?: false;
6165 /**
6166 * Linear gain, from 0 to 4; default 1.
6167 */
6168 gain?: number;
6169 /**
6170 * Stops the clip early, as above.
6171 */
6172 signal?: AbortSignal;
6173 };
6174
6175 /**
6176 * The nouns a plugin declared on `$` by merging into EngineInterface; never
6177 * one the engine's own events are under (`tool`, `session`, `ui`).
6178 */
6179 type PluginNoun = Exclude<keyof EngineInterface & string, keyof CoreEngineInterface | Namespace<CoreEventName>>;
6180
6181 /**
6182 * A plugin's options as `register(on, options)` receives them: the values of
6183 * the fields its manifest's `userConfig` declares, defaults filled in.
6184 *
6185 * Stored in settings.json `pluginConfigs[<plugin>].options` (sensitive ones
6186 * in secure storage), validated against the declared `type` before the module
6187 * loads; a required field with no value fails the load, naming the field. A
6188 * string field that declares `options` holds one of them: `/config` draws it
6189 * as a picker over them, and a stored value outside them counts as unset, so
6190 * its default applies. A `--plugin-dir` plugin's key is its plugin.json
6191 * `<name>` (or `<name>@inline`).
6192 */
6193 export type PluginOptions = Readonly<Record<string, string | number | boolean | readonly string[]>>;
6194
6195 /**
6196 * The input of `plugin.register`: one hooks module the engine is about to
6197 * load, read off its manifest and its scanned source. Every field is pinned.
6198 *
6199 * `tier` and `uses` are the host's reading of the module, what a gate holds
6200 * it to; `name`, `root`, `version` and `provenance` are its own word (its
6201 * manifest, its place), so a rule keyed on them is one a rename walks past.
6202 */
6203 export type PluginRegisterInput = {
6204 /**
6205 * The plugin's name, as its own plugin.json declares it.
6206 */
6207 name: string;
6208 /**
6209 * Where its hooks would stand among the chain's tiers (Tier); never
6210 * `core`, the engine's own.
6211 */
6212 tier: Exclude<Tier, 'core'>;
6213 /**
6214 * The plugin's directory (the one holding plugin.json), absolute.
6215 */
6216 root: string;
6217 /**
6218 * Its manifest's `version`, when it states one.
6219 */
6220 version?: string;
6221 /**
6222 * Where the plugin came from, as the loader keys it: `<name>@<marketplace>`
6223 * installed, `<name>@inline` by `--plugin-dir`, `<name>@builtin` bundled.
6224 */
6225 provenance: string;
6226 /**
6227 * What the module hooks and calls, as scanned (PluginRegisterUses).
6228 */
6229 uses: PluginRegisterUses;
6230 };
6231
6232 /**
6233 * What a `plugin.register` hook returns and what `next(e)` resolves to:
6234 * `{ allow: true }` from core, or `{ refuse: reason }`.
6235 */
6236 export type PluginRegisterResult = {
6237 /**
6238 * The module loads: its `engine.create` step runs and its hooks join.
6239 */
6240 allow: true;
6241 refuse?: undefined;
6242 } | {
6243 /**
6244 * The module does not load: no step, no hooks, no tools or commands;
6245 * the transcript names the plugin that refused and this reason.
6246 */
6247 refuse: string;
6248 allow?: undefined;
6249 };
6250
6251 /**
6252 * What a hooks module uses, as the host scanned its source before loading it:
6253 * the same lists `claude plugin validate` prints and the host's rule reads.
6254 *
6255 * Exact, since a module that spells `on`, `$` or `$.env` other than literally
6256 * does not load.
6257 */
6258 export type PluginRegisterUses = {
6259 /**
6260 * The patterns its `on(...)` registrations name, as written (`tool.call`,
6261 * `*`, `classic.*`, `!tool.describe`), in registration order, each once.
6262 */
6263 events: readonly string[];
6264 /**
6265 * What it calls on `$`, spelled `noun.method` (`fs.write`, `http.fetch`),
6266 * sorted, each once.
6267 */
6268 calls: readonly string[];
6269 /**
6270 * The environment variables its `$.env.get` and `$.env.set` calls name;
6271 * absent when it calls neither.
6272 */
6273 env?: {
6274 /**
6275 * The names its `$.env.get` calls spell, sorted, each once.
6276 */
6277 reads: readonly string[];
6278 /**
6279 * The names its `$.env.set` calls spell, sorted, each once.
6280 */
6281 writes: readonly string[];
6282 };
6283 };
6284
6285 /**
6286 * Whose element: the plugin whose hook drew it, stamped by the runtime as the
6287 * tree leaves it; a Box's or Text's `group`, a Client's or Raster's own.
6288 *
6289 * A Button's `press` names its plugin the same way, beside its handle. Two
6290 * plugins under one `hover.scope` string never share a group.
6291 */
6292 type PluginStamp = {
6293 plugin: string;
6294 };
6295
6296 type PostCompactHookInput = BaseHookInput & {
6297 hook_event_name: 'PostCompact';
6298 trigger: 'manual' | 'auto';
6299 /**
6300 * The conversation summary produced by compaction
6301 */
6302 compact_summary: string;
6303 };
6304
6305 type PostModelSwitchHookInput = (BaseHookInput & {
6306 hook_event_name: 'PostModelSwitch';
6307 }) & {
6308 /**
6309 * Resolved model id the session was running before the switch
6310 */
6311 from_model: string;
6312 /**
6313 * Resolved model id the session runs after the switch
6314 */
6315 to_model: string;
6316 /**
6317 * What was asked for (alias such as "opus", a full id, or null for "default")
6318 */
6319 requested_model: string | null;
6320 /**
6321 * command: /model <name>, the /config Model row, or enabling fast mode when that promotes the model; picker: an interactive model picker; sdk: headless set_model (SDK, Remote Control, IDE); auto: automatic fallback or other programmatic change; resume: model restored while resuming a session
6322 */
6323 source: 'command' | 'picker' | 'sdk' | 'auto' | 'resume';
6324 /**
6325 * Prompt tokens the next request re-sends: the last main-thread response's input + cache_read + cache_creation + output tokens (0 before the first response; for a server-side tool loop, its last iteration's window, not the summed totals)
6326 */
6327 context_tokens: number;
6328 /**
6329 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
6330 */
6331 prompt_cache_warm: boolean;
6332 cache_ttl: '5m' | '1h';
6333 /**
6334 * Estimated cost of re-caching context_tokens on to_model at its cache-write rate - the managed modelPricing when set, otherwise list price; excludes the response
6335 */
6336 estimated_cache_write_usd: number;
6337 /**
6338 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
6339 */
6340 pricing: 'configured' | 'catalog' | 'default';
6341 };
6342
6343 /**
6344 * Hook input for the PostToolBatch event. Fired once after every tool call in a batch has resolved, before the next model request. PostToolUse fires per-tool and may run concurrently for parallel tool calls; PostToolBatch fires exactly once with the full batch.
6345 */
6346 type PostToolBatchHookInput = BaseHookInput & {
6347 hook_event_name: 'PostToolBatch';
6348 tool_calls: PostToolBatchToolCall[];
6349 };
6350
6351 type PostToolBatchToolCall = {
6352 tool_name: string;
6353 tool_input: unknown;
6354 tool_use_id: string;
6355 tool_response?: unknown;
6356 };
6357
6358 type PostToolUseFailureHookInput = BaseHookInput & {
6359 hook_event_name: 'PostToolUseFailure';
6360 tool_name: string;
6361 tool_input: unknown;
6362 tool_use_id: string;
6363 error: string;
6364 is_interrupt?: boolean;
6365 /**
6366 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
6367 */
6368 duration_ms?: number;
6369 mcp_server?: McpServerProvenance;
6370 };
6371
6372 type PostToolUseHookInput = BaseHookInput & {
6373 hook_event_name: 'PostToolUse';
6374 tool_name: string;
6375 tool_input: unknown;
6376 tool_response: unknown;
6377 tool_use_id: string;
6378 /**
6379 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
6380 */
6381 duration_ms?: number;
6382 mcp_server?: McpServerProvenance;
6383 };
6384
6385 type PreCompactHookInput = BaseHookInput & {
6386 hook_event_name: 'PreCompact';
6387 trigger: 'manual' | 'auto';
6388 custom_instructions: string | null;
6389 };
6390
6391 type PreModelSwitchHookInput = (BaseHookInput & {
6392 hook_event_name: 'PreModelSwitch';
6393 }) & {
6394 /**
6395 * Resolved model id the session was running before the switch
6396 */
6397 from_model: string;
6398 /**
6399 * Resolved model id the session runs after the switch
6400 */
6401 to_model: string;
6402 /**
6403 * What was asked for (alias such as "opus", a full id, or null for "default")
6404 */
6405 requested_model: string | null;
6406 /**
6407 * command: /model <name>, the /config Model row, or enabling fast mode when that promotes the model; picker: an interactive model picker; sdk: headless set_model (SDK, Remote Control, IDE)
6408 */
6409 source: 'command' | 'picker' | 'sdk';
6410 /**
6411 * Prompt tokens the next request re-sends: the last main-thread response's input + cache_read + cache_creation + output tokens (0 before the first response; for a server-side tool loop, its last iteration's window, not the summed totals)
6412 */
6413 context_tokens: number;
6414 /**
6415 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
6416 */
6417 prompt_cache_warm: boolean;
6418 cache_ttl: '5m' | '1h';
6419 /**
6420 * Estimated cost of re-caching context_tokens on to_model at its cache-write rate - the managed modelPricing when set, otherwise list price; excludes the response
6421 */
6422 estimated_cache_write_usd: number;
6423 /**
6424 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
6425 */
6426 pricing: 'configured' | 'catalog' | 'default';
6427 };
6428
6429 /**
6430 * The link a press landed on: one a `Markdown` drew, pressed where the
6431 * surface reports presses (a plain click in the fullscreen terminal).
6432 *
6433 * What the surface knows of the cell pressed, not which occurrence: two
6434 * links written with one target read the same here.
6435 */
6436 export type PressedLink = {
6437 /**
6438 * The link's target as the surface drew it: for an `https:` link, the
6439 * href as the markdown wrote it.
6440 */
6441 href: string;
6442 };
6443
6444 /**
6445 * The decision of a `classic.PreToolUse` result: `allow`, `ask`, `deny`, or
6446 * none.
6447 */
6448 export type PreToolUseDecision = {
6449 /**
6450 * Lets the call run without a permission prompt (the managed-settings
6451 * hooks ran first; a deny from them ended the chain above).
6452 */
6453 allow: true;
6454 ask?: undefined;
6455 deny?: undefined;
6456 } | {
6457 /**
6458 * Asks the user before the call runs; the text is shown as the reason.
6459 */
6460 ask: string;
6461 allow?: undefined;
6462 deny?: undefined;
6463 } | {
6464 /**
6465 * Refuses the call; the model receives the text as the reason.
6466 */
6467 deny: string;
6468 allow?: undefined;
6469 ask?: undefined;
6470 } | {
6471 allow?: undefined;
6472 ask?: undefined;
6473 deny?: undefined;
6474 };
6475
6476 type PreToolUseHookInput = BaseHookInput & {
6477 hook_event_name: 'PreToolUse';
6478 tool_name: string;
6479 tool_input: unknown;
6480 tool_use_id: string;
6481 mcp_server?: McpServerProvenance;
6482 };
6483
6484 /**
6485 * What a `classic.PreToolUse` hook returns: one of `allow`, `ask`, `deny`,
6486 * or none of them, which passes the call on to the normal permission flow.
6487 */
6488 export type PreToolUseResult = PreToolUseDecision & {
6489 /**
6490 * Replaces the tool's arguments; validated against the tool's schema before
6491 * the tool runs.
6492 */
6493 updatedInput?: Record<string, unknown>;
6494 /**
6495 * Extra context handed to the model with the call, one entry per note.
6496 */
6497 additionalContext?: string[];
6498 };
6499
6500 /**
6501 * Options of `$.process.run`.
6502 */
6503 export type ProcessRunInit = {
6504 /**
6505 * The child's working directory, relative to the session's or absolute;
6506 * absent, the session's working directory.
6507 */
6508 cwd?: string;
6509 /**
6510 * Variables set over the host process's own environment.
6511 */
6512 env?: Record<string, string>;
6513 /**
6514 * Text written to the child's standard input, then closed.
6515 */
6516 stdin?: string;
6517 /**
6518 * How long the child may run before it is killed and the call rejects,
6519 * in milliseconds; 30 seconds when absent, ten minutes at most.
6520 */
6521 timeoutMs?: number;
6522 };
6523
6524 /**
6525 * What `$.process.run` resolves with once the child has exited.
6526 */
6527 export type ProcessRunResult = {
6528 /**
6529 * The child's exit status; a child ended by a signal reads as 1.
6530 */
6531 exitCode: number;
6532 /**
6533 * What the child wrote to standard output, as text, cut at the output
6534 * limit.
6535 */
6536 stdout: string;
6537 /**
6538 * What the child wrote to standard error, as text, cut at the output
6539 * limit.
6540 */
6541 stderr: string;
6542 };
6543
6544 /**
6545 * The input of `prompt.attachment`: one message the engine injects into the
6546 * conversation for the model on its own, as a request is about to carry it.
6547 *
6548 * A reminder, a mode transition, a listing, a mentioned file, a hook's
6549 * context: the person never typed it and mostly never sees it. Only an
6550 * attachment that carries text for the model is raised.
6551 */
6552 export type PromptAttachmentInput = {
6553 /**
6554 * As the engine names the attachment's kind; the key a matcher narrows on.
6555 * Pinned. Builds add and retire kinds: match by name.
6556 *
6557 * Among them `todo_reminder`, `plan_mode`, `plan_mode_exit`, `auto_mode`,
6558 * `auto_mode_exit`, `instructions`, `nested_memory`, `skill_listing`,
6559 * `deferred_tools_delta`, `edited_text_file`, `file`, `queued_command`.
6560 */
6561 type: string;
6562 /**
6563 * What the model reads for this attachment, inside the engine's framing;
6564 * rewritable with `next({ ...e, text })`.
6565 *
6566 * The `<system-reminder>` wrapper (or the system channel that replaces it)
6567 * goes around what the chain answers, never inside it. An attachment
6568 * rendered as several text blocks hands them joined by newlines.
6569 */
6570 text: string;
6571 /**
6572 * Who authored the text (PromptAttachmentOrigin): the engine, a settings
6573 * hook, or a plugin's chain context.
6574 *
6575 * Pinned: a different value is refused, one left out is kept.
6576 */
6577 origin: PromptAttachmentOrigin;
6578 /**
6579 * The loop whose request carries the attachment: a subagent's id, the `id`
6580 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
6581 *
6582 * Pinned: a different value is refused, one left out is kept. A subagent
6583 * a hook spawned through `$.agent.spawn` is resolved past that hook.
6584 */
6585 agentId?: string;
6586 };
6587
6588 /**
6589 * Who authored the text an injected attachment carries, as the engine knows
6590 * it from the attachment itself; a closed set, pinned on the event.
6591 *
6592 * A hooks module reads `e.origin.kind` to tell the engine's own prose from a
6593 * settings hook's output or another plugin's context. `next(e)` passes it on
6594 * as received; one left out is put back; no hook sets one.
6595 */
6596 export type PromptAttachmentOrigin = {
6597 /**
6598 * The engine's own prose or framing: a reminder, a mode transition, a
6599 * listing, a notice, an announced context block.
6600 *
6601 * A file the person mentioned, as the engine presents it, and a prompt
6602 * or notification delivered into a running turn are the engine's too.
6603 */
6604 kind: 'engine';
6605 } | {
6606 /**
6607 * A settings hook's output the engine injects for the model: its
6608 * additional context, a blocking error's note, a stopped continuation.
6609 */
6610 kind: 'hook';
6611 /**
6612 * The settings hook event that produced it (`SessionStart`,
6613 * `UserPromptSubmit`, `PostToolUse`, ...).
6614 */
6615 event: string;
6616 } | {
6617 /**
6618 * Text a plugin's hook attached through a chain's `context`
6619 * (`prompt.submit`, `tool.call`), as the model reads it.
6620 */
6621 kind: 'plugin';
6622 /**
6623 * The chain's event that attached it.
6624 */
6625 event: string;
6626 };
6627
6628 /**
6629 * What a `prompt.attachment` hook returns: the text the model reads for that
6630 * attachment, or null to leave the attachment out of the request.
6631 */
6632 export type PromptAttachmentResult = {
6633 text: string | null;
6634 };
6635
6636 /**
6637 * The person's prompt box as it stands: the draft and where the cursor is in
6638 * it; what `$.prompt.read()` resolves and `$.prompt.fill` hands back.
6639 *
6640 * No selection: the terminal's box has none of its own, and a surface that
6641 * binds one adds it here.
6642 */
6643 export type PromptBox = {
6644 /**
6645 * The draft as typed so far; `''` where the session draws no box.
6646 */
6647 text: string;
6648 /**
6649 * Where the next typed character lands: an offset into `text` in UTF-16
6650 * code units, 0 at the start, `text.length` at the end.
6651 */
6652 cursor: number;
6653 };
6654
6655 /**
6656 * What a plugin passes `$.prompt.compose`: the facts it wants composed for,
6657 * each one it leaves out read off the session (its model, its tools).
6658 */
6659 export type PromptComposeArgs = Partial<PromptComposeInput>;
6660
6661 /**
6662 * The input of `prompt.compose`: the facts a system prompt is composed from,
6663 * each already resolved by the engine, at the moment it renders one.
6664 */
6665 export type PromptComposeInput = {
6666 /**
6667 * The id of the model the request is for; pinned, the field a matcher
6668 * narrows on.
6669 */
6670 model: string;
6671 /**
6672 * The model whose prompt is rendered: `model`, unless the engine renders
6673 * another model's prompt for it (a model it holds no prompt of its own for).
6674 */
6675 promptModel: string;
6676 /**
6677 * Where the session draws at this render, as `$.session.surfaces()`
6678 * answers: `terminal` first under the REPL; empty where nothing draws.
6679 */
6680 surfaces: readonly RenderSurface[];
6681 /**
6682 * The names of the tools the request offers the model; the engine's own
6683 * composition reads them against the session's, an unknown name ignored.
6684 */
6685 tools: readonly string[];
6686 /**
6687 * What the person chose in place of the default way of answering, and
6688 * whether it keeps the coding instructions; null for the default style.
6689 */
6690 outputStyle: {
6691 name: string;
6692 isKeepingCodingInstructions: boolean;
6693 } | null;
6694 traits: readonly PromptComposeTrait[];
6695 };
6696
6697 /**
6698 * What a `prompt.compose` hook returns: the sections of the system prompt,
6699 * in order, every `shared` one ahead of every `session` one.
6700 *
6701 * A section left out is not sent; a hook that never calls `next` answers
6702 * the whole list. The engine joins each side, places the cache boundary
6703 * between them and every cache marker itself.
6704 */
6705 export type PromptComposeResult = {
6706 sections: readonly PromptComposeSection[];
6707 };
6708
6709 /**
6710 * Which side of the prompt cache's boundary a section of the system prompt
6711 * sits on: `shared` before it, `session` after it.
6712 *
6713 * `shared` is text that reads the same for every person on this build and
6714 * model: it is sent in the block the API may cache across organizations.
6715 * `session` is text that varies with the person, the machine or the session.
6716 *
6717 * The engine places the one boundary and every cache marker itself,
6718 * whatever a list says; `shared` text that varies hits that cache for nobody.
6719 */
6720 export type PromptComposeScope = 'shared' | 'session';
6721
6722 /**
6723 * One section of the system prompt as `prompt.compose` answers it: a stable
6724 * id, the text the model reads, and the side of the cache boundary it is on.
6725 *
6726 * @example
6727 * const POLICY = { id: "acme:policy", text: "# Policy\n...", scope: "session" }
6728 */
6729 export type PromptComposeSection = {
6730 /**
6731 * What a hook above finds the section by, to replace, move or drop it;
6732 * never empty, and unique in one list.
6733 *
6734 * A section a plugin adds is named `<plugin>:<name>`; the bare names are
6735 * the engine's own composition's (`intro`, `tools`, `memory`, ...).
6736 */
6737 id: string;
6738 /**
6739 * The section's text, sent as written; sections on one side of the
6740 * boundary are joined by a blank line, in the list's order.
6741 */
6742 text: string;
6743 scope: PromptComposeScope;
6744 };
6745
6746 /**
6747 * One branch the engine's own composition of the system prompt takes on the
6748 * request or the session before it computes any section: a closed set.
6749 *
6750 * `bare`: the session runs with the one-line prompt (`--bare`). `lean`: the
6751 * prompt model takes the short body. `sdk-preset`: the SDK's `claude_code`
6752 * preset, whose per-person sections ride the first user message instead.
6753 *
6754 * `teammate`: an in-process teammate's render of its lead's prompt.
6755 * `analysis`: a render that measures the prompt (`/context`) and sends
6756 * nothing. `print`: a session with no terminal behind it (`-p`, the SDK).
6757 *
6758 * `skills`: the Skill tool has commands to list. `send-user-message`: the
6759 * session speaks to the person through a message tool.
6760 *
6761 * Rewritten going down, `sdk-preset`, `teammate` and `analysis` steer the
6762 * engine's composition; the rest it derives itself, so they tell a hook what
6763 * it will do. What one section's own text turns on (a flag) is not here.
6764 */
6765 export type PromptComposeTrait = 'bare' | 'lean' | 'sdk-preset' | 'teammate' | 'analysis' | 'print' | 'skills' | 'send-user-message';
6766
6767 /**
6768 * One block of the context the first user message carries: a name the
6769 * engine keys it by and the text under it.
6770 */
6771 export type PromptContextBlock = {
6772 /**
6773 * The key the block renders under (`# name`): `claudeMd`, `userEmail`,
6774 * `attachedProject`, `currentDate`, or a plugin's own.
6775 *
6776 * The field a matcher narrows on; unique among one context's blocks.
6777 */
6778 name: string;
6779 /**
6780 * The block's text; `claudeMd`'s is the instruction files framed as the
6781 * engine frames them, empty when it announces none.
6782 */
6783 text: string;
6784 };
6785
6786 /**
6787 * The context blocks of a conversation's first user message, in the order
6788 * the engine renders them: what `prompt.context` takes and answers alike.
6789 */
6790 export type PromptContextBlocks = {
6791 /**
6792 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
6793 * `attachedProject`, `currentDate`, each only when present.
6794 */
6795 blocks: readonly PromptContextBlock[];
6796 };
6797
6798 /**
6799 * The input of `prompt.context`: the context blocks the engine prepends to a
6800 * conversation's first user message, and the files behind `claudeMd`.
6801 */
6802 export type PromptContextInput = {
6803 /**
6804 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
6805 * `attachedProject`, `currentDate`, each only when present.
6806 */
6807 blocks: readonly PromptContextBlock[];
6808 /**
6809 * The files behind `claudeMd`, in the order it renders them, `@` imports
6810 * included; empty when it renders none.
6811 *
6812 * Undefined when a hook above rewrote the `claudeMd` text: the files
6813 * behind that text are then unknown, and a hook adds none of its own.
6814 */
6815 instructionFiles?: readonly InstructionFile[];
6816 };
6817
6818 /**
6819 * What a `prompt.context` hook returns: the blocks the conversation
6820 * carries, in order; one left out is not sent.
6821 */
6822 export type PromptContextResult = {
6823 /**
6824 * What the conversation carries, in order.
6825 */
6826 blocks: readonly PromptContextBlock[];
6827 /**
6828 * The files now behind `claudeMd`; left out, the ones from below stand.
6829 *
6830 * Kept in step with the `claudeMd` text at every link: a changed list
6831 * renders the text the next reader gets, a rewritten text makes the files
6832 * unknown from there on. Every kind is the hook's to add, drop or rewrite.
6833 */
6834 instructionFiles?: readonly InstructionFile[];
6835 };
6836
6837 /**
6838 * The input of `prompt.edit` (prompt-edit/): one edit the person makes in the
6839 * prompt box, as the draft before it and the splice the editor made of it.
6840 */
6841 export type PromptEditInput = {
6842 /**
6843 * Who edits (PromptEditOrigin): the person at the composer. Pinned:
6844 * `next(e)` passes it on as received.
6845 */
6846 origin: PromptEditOrigin;
6847 /**
6848 * The one key that made the edit, in `Client` `onKey`'s shape, when one
6849 * did; absent for a paste and for a burst of keys folded into one edit.
6850 *
6851 * Pinned: which key the person pressed is a fact, not the hook's to change.
6852 */
6853 key?: ClientKeyEvent;
6854 /**
6855 * The draft before the edit. `next({ ...e, text })` applies the edit to
6856 * another draft instead.
6857 */
6858 text: string;
6859 /**
6860 * Where the person's caret stood in `text` before the edit, 0 to
6861 * `text.length`.
6862 */
6863 cursor: number;
6864 /**
6865 * Where in `text` the edit begins: the start of the span it replaces, or
6866 * where what was typed goes in; a bare cursor move begins where it lands.
6867 */
6868 start: number;
6869 /**
6870 * Where the replaced span of `text` ends: `start` for an insertion or a
6871 * move, past it for a deletion (Backspace, a kill).
6872 */
6873 end: number;
6874 /**
6875 * What goes in between `start` and `end`: the typed or pasted text, `''` for
6876 * a deletion or a move.
6877 *
6878 * `next({ ...e, inputText })` puts in another; the cursor lands after it.
6879 */
6880 inputText: string;
6881 };
6882
6883 /**
6884 * Who edits the prompt box at `prompt.edit`, as the engine stamps it where
6885 * the edit starts; a closed set a matcher narrows on.
6886 *
6887 * `next(e)` passes it on as received; no hook sets one.
6888 */
6889 export type PromptEditOrigin = {
6890 /**
6891 * The person, typing or pasting into the main prompt box.
6892 */
6893 kind: 'composer';
6894 };
6895
6896 /**
6897 * What a `prompt.edit` hook returns and what `next(e)` resolves to: the box
6898 * after the edit (PromptBox), which the editor then shows.
6899 *
6900 * From core, `e.text` with the splice applied and the cursor after what went
6901 * in. Rewrite it (`{ ...r, text, cursor }`) to change what lands; answer
6902 * `{ text: e.text, cursor: e.cursor }` without `next` to consume the key.
6903 */
6904 export type PromptEditResult = PromptBox;
6905
6906 /**
6907 * `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it: no
6908 * `origin` (the engine sets the calling plugin's), `mode` optional.
6909 */
6910 export type PromptFillArgs = {
6911 /**
6912 * What the box is to take (PromptFillInput `text`).
6913 */
6914 text: string;
6915 /**
6916 * Where it goes (PromptFillMode); `replace` when left out.
6917 */
6918 mode?: PromptFillMode;
6919 };
6920
6921 /**
6922 * What `$.prompt.fill` resolves to: whether the box took the text, and the
6923 * box afterwards (PromptBox) as the caller's own `$.prompt.read()` reads it.
6924 *
6925 * The box goes to a plugin whose module calls `$.prompt.read`, through the
6926 * hooks on it; one that never does, or is refused there, gets the empty box.
6927 */
6928 export type PromptFilled = {
6929 /**
6930 * True once the box holds the text; false where no box could take it or a
6931 * hook kept it out (PromptFillResult).
6932 */
6933 isFilled: boolean;
6934 /**
6935 * The draft after the fill; unchanged when `isFilled` is false; `''` where
6936 * no box is drawn or the caller may not read it (see above).
6937 */
6938 text: string;
6939 /**
6940 * Where the person types next: an offset into `text`, past the fill's text
6941 * for `insert`, at the end for `replace` and `append`.
6942 */
6943 cursor: number;
6944 };
6945
6946 /**
6947 * The input of `prompt.fill` (prompt-fill/): a text about to be put in the
6948 * prompt box as the person's draft, over it, after it, or at the cursor.
6949 */
6950 export type PromptFillInput = {
6951 /**
6952 * What the box takes; the person edits it or presses Enter.
6953 * `next({ ...e, text })` writes another.
6954 */
6955 text: string;
6956 /**
6957 * Where the text goes (PromptFillMode): over the draft, after it, or in at
6958 * the cursor. `next({ ...e, mode })` moves it; left out of a rewrite, kept.
6959 */
6960 mode: PromptFillMode;
6961 /**
6962 * Who writes (PromptFillOrigin), set by the engine where the write
6963 * starts. Pinned: `next(e)` passes it on as received.
6964 */
6965 origin: PromptFillOrigin;
6966 };
6967
6968 /**
6969 * Where a `prompt.fill` puts its text: over the whole draft, after it, or
6970 * into it at the cursor.
6971 *
6972 * `replace` empties the box first and leaves the cursor at the text's end;
6973 * `append` keeps the draft and adds the text after it, cursor at the end;
6974 * `insert` splices the text in at the cursor and moves the cursor past it,
6975 * so what the person had typed stays on either side.
6976 */
6977 export type PromptFillMode = 'replace' | 'append' | 'insert';
6978
6979 /**
6980 * Who writes the prompt box at `prompt.fill`, as the engine stamps it where
6981 * the write starts; a closed set a matcher narrows on.
6982 *
6983 * `next(e)` passes it on as received; no hook sets one.
6984 */
6985 export type PromptFillOrigin = {
6986 /**
6987 * The engine writing the box on its own account; reserved for its own
6988 * sites, none of which raises `prompt.fill` as shipped.
6989 */
6990 kind: 'engine';
6991 } | {
6992 /**
6993 * A plugin's `$.prompt.fill`.
6994 */
6995 kind: 'plugin';
6996 /**
6997 * The filling plugin's name.
6998 */
6999 name: string;
7000 };
7001
7002 /**
7003 * What a `prompt.fill` hook returns and what `next(e)` resolves to: whether
7004 * the text went into the prompt box.
7005 */
7006 export type PromptFillResult = {
7007 /**
7008 * True once the box holds the text; false where no box can take it (a
7009 * dialog holds the keys, a headless session has none).
7010 *
7011 * A hook answering `{ isFilled: false }` without `next` keeps the text
7012 * out.
7013 */
7014 isFilled: boolean;
7015 };
7016
7017 /**
7018 * Where a `prompt.submit` submission came from, as the engine knows it at
7019 * the site it was queued from; a closed set, never a text prefix.
7020 *
7021 * A hooks module reads `e.origin.kind` to tell the user's own Enter from a
7022 * notification, a peer session, a schedule or another plugin. `next(e)`
7023 * passes it on as received; an answer may leave it out; no hook sets one.
7024 */
7025 export type PromptOrigin = {
7026 /**
7027 * The user's own gesture at the terminal, as the engine stamped it
7028 * (never presumed from an unstamped command).
7029 *
7030 * Enter at the prompt, typed or queued, or a click on a transcript
7031 * link; a channel the engine cannot attest (a same-user socket) is
7032 * never stamped, and arrives as `unclassified`.
7033 */
7034 kind: 'composer';
7035 } | {
7036 /**
7037 * The user's message through the Remote Control bridge (a phone or
7038 * web client).
7039 */
7040 kind: 'bridge';
7041 } | {
7042 /**
7043 * The SDK host's own turn (`claude -p`, the Agent SDK), not typed at
7044 * a terminal.
7045 */
7046 kind: 'sdk';
7047 } | {
7048 /**
7049 * A background task's notification, dequeued when the session went
7050 * idle or delivered into a running turn (`turnId` set).
7051 */
7052 kind: 'task-notification';
7053 } | {
7054 /**
7055 * A scheduled task, routine or /loop firing its stored prompt.
7056 */
7057 kind: 'scheduled-trigger';
7058 } | {
7059 /**
7060 * Another Claude session's message ("Another Claude session sent a
7061 * message"), as a turn of its own or delivered into a running one.
7062 */
7063 kind: 'peer';
7064 } | {
7065 /**
7066 * Another session's SendMessage delivery, model-authored and framed
7067 * as a notification.
7068 */
7069 kind: 'peer-send-message';
7070 } | {
7071 /**
7072 * A delivery a coordinating session composed for one of its threads.
7073 */
7074 kind: 'projects-relay';
7075 } | {
7076 /**
7077 * A message from a channel an MCP server relays (Slack, Telegram).
7078 */
7079 kind: 'channel';
7080 /**
7081 * The channel server's name.
7082 */
7083 server: string;
7084 } | {
7085 /**
7086 * A coordinating session's hand-off to a worker session.
7087 */
7088 kind: 'coordinator';
7089 } | {
7090 /**
7091 * A background observer agent's report to the agent it observes.
7092 */
7093 kind: 'observer';
7094 } | {
7095 /**
7096 * An activity digest delivered to an observer agent.
7097 */
7098 kind: 'observer-activity';
7099 } | {
7100 /**
7101 * A programmatic follow-up to a user's UI action, user-initiated but
7102 * not typed this turn.
7103 */
7104 kind: 'auto-continuation';
7105 } | {
7106 /**
7107 * A turn with no provenance the engine can name: one the ingress
7108 * could not classify, or a command queued with no stamp at all.
7109 *
7110 * An idle notice or a delivery receipt the engine queued isMeta with
7111 * no stamp is one too; the engine frames that shape as a non-user
7112 * source.
7113 */
7114 kind: 'unclassified';
7115 } | {
7116 /**
7117 * The session's owner pinging it from Slack.
7118 */
7119 kind: 'slack-ping';
7120 } | {
7121 /**
7122 * A plugin's `$.prompt.submit`; the model reads the prompt under the
7123 * plugin's name unless a hook leaves the origin out of its answer.
7124 */
7125 kind: 'plugin';
7126 /**
7127 * The submitting plugin's name.
7128 */
7129 name: string;
7130 };
7131
7132 /**
7133 * The input of `prompt.section`: one named section of the system prompt, at
7134 * the moment the engine assembles it.
7135 */
7136 export type PromptSectionInput = {
7137 /**
7138 * As the engine names the section (`env_info_simple`, `memory`, ...); the
7139 * key a matcher narrows on.
7140 */
7141 name: string;
7142 /**
7143 * The section's text as core computed it, or null when core omits it.
7144 */
7145 text: string | null;
7146 };
7147
7148 /**
7149 * What a `prompt.section` hook returns: the text the prompt carries for that
7150 * section, or null to leave it out.
7151 */
7152 export type PromptSectionResult = {
7153 text: string | null;
7154 };
7155
7156 /**
7157 * `prompt.submit`'s input as a plugin's call takes it: `origin`, `turnId`
7158 * and `wait` are the engine's to set, `context` the hooks' to attach.
7159 *
7160 * `origin` is the calling plugin's name; `turnId` is the turn a prompt typed
7161 * mid-turn ran over; `wait` is false, as a plugin's prompt runs once idle.
7162 */
7163 export type PromptSubmitArgs = Omit<PromptSubmitInput, 'origin' | 'turnId' | 'wait' | 'context'>;
7164
7165 /**
7166 * A pasted or attached non-text item of a submitted prompt; its kind, never
7167 * its bytes.
7168 */
7169 export type PromptSubmitAttachment = {
7170 /**
7171 * The item's kind.
7172 */
7173 type: 'image' | 'audio' | 'document';
7174 /**
7175 * The item's MIME type (`image/png`), when known.
7176 */
7177 mediaType?: string;
7178 /**
7179 * The pasted file's name, when it had one.
7180 */
7181 filename?: string;
7182 };
7183
7184 /**
7185 * The input of `prompt.submit`: the prompt as typed, after the input became
7186 * a user message and before it enters the session.
7187 */
7188 export type PromptSubmitInput = {
7189 /**
7190 * The prompt's text as it will reach the model (pastes already expanded).
7191 */
7192 text: string;
7193 /**
7194 * Present only when the submission carried images or other non-text items.
7195 */
7196 attachments?: readonly PromptSubmitAttachment[];
7197 /**
7198 * What the model reads beside the prompt and the user never sees, each
7199 * entry one block after the prompt as typed; absent as the engine raises it.
7200 *
7201 * A hook attaches on the way down: `next({ ...e, context: [...(e.context
7202 * ?? []), mine] })`, keeping which it likes; none empty, any length: past
7203 * 100,000 characters (200,000 together) the model reads a head and path.
7204 */
7205 context?: readonly string[];
7206 /**
7207 * The id of the model turn that was running when the prompt was submitted
7208 * (`turn.start`'s `turnId`): typed over that turn, or delivered into it.
7209 *
7210 * A queued delivery (a peer session's message) reaches the model inside a
7211 * running turn. Absent for a prompt submitted while the session was idle,
7212 * and for a plugin's own (`$.prompt.submit`), which runs once it is idle.
7213 */
7214 turnId?: string;
7215 /**
7216 * Whether the user asked the prompt to wait its turn (`chat:queueSubmit`,
7217 * `ctrl+x enter` by default): true for that submission, false otherwise.
7218 *
7219 * The engine queues every prompt typed mid-turn either way; the flag is
7220 * for hooks, so one that cancels the running turn on a plain Enter can
7221 * leave a waiting prompt alone. False for a prompt a plugin submitted.
7222 */
7223 wait: boolean;
7224 /**
7225 * Where the submission came from (PromptOrigin), set by the engine where
7226 * it was queued: the user's Enter, a notification, a peer, a plugin.
7227 *
7228 * `next(e)` passes it on as received; no hook may set one.
7229 */
7230 origin: PromptOrigin;
7231 };
7232
7233 /**
7234 * What a `prompt.submit` hook returns and what `next(e)` resolves to: the
7235 * prompt that entered, `{ text, context?, origin? }`, or `{ drop: reason }`.
7236 *
7237 * `next(e)` resolves once the prompt entered the session and its turn
7238 * started, or it was queued behind the running one; not when the turn ends,
7239 * which is `turn.complete`. A hook answering without `next` enters nothing.
7240 */
7241 export type PromptSubmitResult = {
7242 /**
7243 * The prompt that entered; from core, the text that arrived at the
7244 * bottom. A rewrite passes it down, `next({ ...e, text })`.
7245 */
7246 text: string;
7247 /**
7248 * What entered beside the prompt for the model, never shown the user:
7249 * from core, the context that arrived (`e.context`).
7250 *
7251 * Each entry is one block after the prompt as typed. A hook attaches
7252 * context on the way down; one put here after `next` resolved is not
7253 * attached (the prompt had entered), and is logged.
7254 */
7255 context?: readonly string[];
7256 /**
7257 * Where the prompt entered from: from core, `e.origin` as received;
7258 * absent, the prompt is the user's own.
7259 *
7260 * A hook may put back the origin it received; it may not set another.
7261 */
7262 origin?: PromptOrigin;
7263 drop?: undefined;
7264 } | {
7265 /**
7266 * The prompt did not enter: a hook's refusal, answered without `next`,
7267 * or a settings hook's block beneath.
7268 *
7269 * The text is shown to the user as the reason.
7270 */
7271 drop: string;
7272 text?: undefined;
7273 context?: undefined;
7274 origin?: undefined;
7275 };
7276
7277 /**
7278 * `prompt.suggest`'s input as a plugin's `$.prompt.suggest(args)` takes it:
7279 * `origin` is the engine's to set (the calling plugin's name).
7280 */
7281 export type PromptSuggestArgs = Omit<PromptSuggestInput, 'origin'>;
7282
7283 /**
7284 * The input of `prompt.suggest` (prompt-suggest/): a text about to be shown
7285 * dim in the empty prompt box, for Tab (or the right arrow) to take.
7286 */
7287 export type PromptSuggestInput = {
7288 /**
7289 * The proposed prompt: shown, not written; taking it puts it in the box
7290 * for editing. `next({ ...e, text })` proposes another.
7291 */
7292 text: string;
7293 /**
7294 * Who proposes (PromptSuggestOrigin), set by the engine where the
7295 * proposal starts. Pinned: `next(e)` passes it on as received.
7296 */
7297 origin: PromptSuggestOrigin;
7298 };
7299
7300 /**
7301 * Who proposes the text at `prompt.suggest`, as the engine stamps it where
7302 * the proposal starts; a closed set a matcher narrows on.
7303 *
7304 * `next(e)` passes it on as received; no hook sets one.
7305 */
7306 export type PromptSuggestOrigin = {
7307 /**
7308 * The engine's own guess at the person's next prompt, generated after
7309 * a turn (the prompt-suggestion service).
7310 */
7311 kind: 'suggestion';
7312 } | {
7313 /**
7314 * A plugin's `$.prompt.suggest`.
7315 */
7316 kind: 'plugin';
7317 /**
7318 * The proposing plugin's name.
7319 */
7320 name: string;
7321 };
7322
7323 /**
7324 * What a `prompt.suggest` hook returns and what `next(e)` resolves to:
7325 * whether the text is now the box's dim suggestion.
7326 */
7327 export type PromptSuggestResult = {
7328 /**
7329 * True once the box has the suggestion to show, at once or as soon as a
7330 * dialog gives the box back; false where it cannot show.
7331 *
7332 * It cannot while the box holds text, a turn runs, the text is blank, or
7333 * the session is headless. A hook answering `{ isShown: false }` without
7334 * `next` keeps it from showing.
7335 */
7336 isShown: boolean;
7337 };
7338
7339 /**
7340 * A `$.ui.blit` argument repainting one of the caller's mounted Rasters.
7341 *
7342 * `columns` and `rows`, when given, must be the mounted size (a resize is a
7343 * redraw, `$.ui.invalidate("ui.render")`, not a blit).
7344 */
7345 export type RasterBlitArgs = {
7346 /**
7347 * The site the Raster is drawn in, by the `requestId` this plugin draws
7348 * it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
7349 */
7350 requestId: string;
7351 /**
7352 * The Raster's `key` in that drawing.
7353 */
7354 key: string;
7355 /**
7356 * The new cells, encoded as the element's `cells` are (RasterProps), for
7357 * the mounted `columns * rows`.
7358 */
7359 cells: string;
7360 /**
7361 * The width the cells are laid out for; refused unless it is the mounted
7362 * Raster's. Absent, the mounted width.
7363 */
7364 columns?: number;
7365 /**
7366 * The height the cells are laid out for; refused unless it is the mounted
7367 * Raster's. Absent, the mounted height.
7368 */
7369 rows?: number;
7370 };
7371
7372 /**
7373 * The props of `Raster`, the terminal surface's cell-grid leaf: a fixed box
7374 * of cells, each a glyph, a foreground and a background, packed in `cells`.
7375 *
7376 * A leaf: no children, `hover` or `onPress` yet; repainted in place by
7377 * `$.ui.blit`. Terminal only for now (elsewhere a fragment); its palette
7378 * paints 1024 distinct color pairs at once and the rest as their nearest.
7379 */
7380 export type RasterProps = {
7381 /**
7382 * The element's address within the drawing: what `$.ui.blit` names to
7383 * repaint it, unique among the Rasters of one tree.
7384 */
7385 key: string;
7386 /**
7387 * How many terminal columns wide, 1 to 512; the site clips what its body
7388 * cannot show.
7389 */
7390 columns: number;
7391 /**
7392 * How many terminal rows tall, 1 to 256.
7393 */
7394 rows: number;
7395 /**
7396 * Every cell, row-major: standard padded base64 of `columns * rows`
7397 * little-endian u32 triplets `[codePoint, foreground, background]`.
7398 *
7399 * A code point is one printable width-1 BMP character (blocks, box drawing,
7400 * braille too), or the tree is refused naming the cell's index; a color is
7401 * `0x00RRGGBB`, or `0x01000000` (bit 24 alone) for the terminal's default.
7402 *
7403 * @example const words = Uint32Array.of(0x2588, 0xff8800, 0x01000000)
7404 * const cells = new Uint8Array(words.buffer).toBase64() // one orange cell
7405 */
7406 cells: string;
7407 };
7408
7409 /**
7410 * The hooks module's entry: `export function register(on, options)`. `on`
7411 * registers hooks; `options` is the plugin's configuration (PluginOptions).
7412 *
7413 * The options are fixed for this activation: a change to them reloads the
7414 * plugin and `register` runs again with the new object. Hooks close over it.
7415 * Its return is dropped, a promise awaited: `on => on(...)` is a module.
7416 *
7417 * @example
7418 * on("tool.call", ($, e, next) => e.tool === "Bash" ? { deny: "no" } : next(e))
7419 */
7420 export type Register = (on: On, options: PluginOptions) => unknown;
7421
7422 /**
7423 * What `on(...)` returns for a hook of type `F`: the registration, which
7424 * takes one `.catch` (CatchHandler); without it a failed hook is absent.
7425 *
7426 * A second `.catch` on one registration throws, as does one after
7427 * register() returned and one on `engine.create`, whose hook has no budget
7428 * and whose failure is the load's.
7429 */
7430 export type Registration<F> = {
7431 /**
7432 * Sets the handler run when the hook throws or overruns its budget; its
7433 * answer within the grace stands as the hook's result for the dispatch.
7434 *
7435 * The budget is HookBudget's `ms` and the grace its `catchMs`, both on
7436 * the clock that stops while the code waits on `next` or `$`.
7437 */
7438 readonly catch: (handler: CatchHandler<F>) => void;
7439 };
7440
7441 /**
7442 * What an element takes as `children`, as JSX passes them: a node, a number
7443 * (drawn as its string), a value the factory drops, or a list that may nest.
7444 *
7445 * `false`, `null` and `undefined` are dropped, so `{ok && <Text>hi</Text>}`
7446 * and `{n > 0 ? <Text>{n}</Text> : null}` type; a mapped list beside a
7447 * sibling nests. The element holds the flat, normalized list of RenderNode.
7448 */
7449 export type RenderChildren = RenderNode | number | boolean | null | undefined | readonly RenderChildren[];
7450
7451 /**
7452 * Everything `ui.render` can draw: one name per component that has a render
7453 * site; a matcher narrows on it.
7454 *
7455 * The permission dialog is drawn by the engine alone, since its answer
7456 * authorises an action; a plugin adds context with `$.ui.notice`. `Pane` is
7457 * the one component whose instances a plugin opens (`$.ui.open`).
7458 */
7459 export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'ToolProgress' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
7460
7461 /**
7462 * What a render hook returns, and what `next(e)` resolves to: a plain-data
7463 * tree of elements (a Box or Text is a StyledElement), strings as children.
7464 *
7465 * Props are an allowlisted subset of Ink's Box/Text props (the ones
7466 * ElementProps declares); a tree with any other prop fails validation as a
7467 * whole and the engine's own component is drawn with the original props.
7468 */
7469 export type RenderElement = StyledElement<'Box', BoxHoverProps> | StyledElement<'Text', TextHoverProps> | {
7470 /**
7471 * A button, on every surface: `[ label ]` on the terminal, a native
7472 * button on a desktop; a press raises `ui.press` (`e.element` the key).
7473 *
7474 * Built by `<Button>` or the table's `t.Button`. The `onPress` closure
7475 * stays in the plugin's own environment under `press.handle`; the host
7476 * holds the handle for the lifetime of the drawing. A leaf: no children.
7477 */
7478 type: 'Button';
7479 props: {
7480 /**
7481 * The element's address: what `e.element` carries and what a matcher
7482 * names (`{ element: "explain" }`).
7483 */
7484 key: string;
7485 /**
7486 * The text drawn on the button.
7487 */
7488 label: string;
7489 /**
7490 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it
7491 * while the plugin's site holds the focus; anything else is refused.
7492 *
7493 * The band after ctrl+x tab or a click, a focused `Pane`: on keydown,
7494 * lowercased; never from the composer, save a bare digit in an empty
7495 * one pressing a band Button. Two on one hotkey: the later wins.
7496 */
7497 hotkey?: string;
7498 /**
7499 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord
7500 * presses the Button from the prompt; an unknown name is refused.
7501 *
7502 * Chords, or a modified key Global or an active context binds, on
7503 * the terminal while mounted, no dialog up, no engine handler of it
7504 * mounted; a pane's over the band's over another's, the last drawn.
7505 */
7506 action?: string;
7507 /**
7508 * Drawn without chrome: the hotkey in the accent color, a colon,
7509 * then the label (`1: Yes`); without a `hotkey`, the label alone.
7510 *
7511 * The focus still inverts it. In JSX the label may be the one string
7512 * child (`<Button hotkey="1" plain onPress={...}>Yes</Button>`); the
7513 * key defaults to the label.
7514 */
7515 plain?: true;
7516 /**
7517 * The label dim at rest, as `Text`'s `dimColor`, and at full strength
7518 * under the pointer or the focus; absent draws as false.
7519 */
7520 dimColor?: TextProps['dimColor'];
7521 /**
7522 * The site's ring starts on this element when the site takes the
7523 * keyboard; the first drawn of several. Absent draws as before.
7524 */
7525 autoFocus?: true;
7526 };
7527 /**
7528 * Where the handler lives: the plugin whose hook drew the element, and
7529 * the handle its environment keeps the `onPress` closure under.
7530 *
7531 * The runtime stamps the plugin as the tree leaves that hook.
7532 */
7533 press: {
7534 plugin: string;
7535 handle: number;
7536 };
7537 /**
7538 * Label style overrides (the Text set) the surface applies while the
7539 * nearest keyed Box, or the group `scope` names, is hovered; plain data.
7540 */
7541 hover?: TextHoverProps;
7542 } | {
7543 /**
7544 * A one-line text field on every surface; a change and Enter raise
7545 * `ui.input` (`e.element` the key, `e.kind` which, `e.value` the text).
7546 *
7547 * Built by `<Input>` or the table's `t.Input`. The `onInput` and
7548 * `onSubmit` closures stay in the plugin's own environment under
7549 * `press.handle`, held as a Button's is. A leaf: no children.
7550 */
7551 type: 'Input';
7552 props: {
7553 /**
7554 * The element's address: what `e.element` carries and what a matcher
7555 * names (`{ element: "reply" }`).
7556 */
7557 key: string;
7558 /**
7559 * Text drawn before the field.
7560 */
7561 label?: string;
7562 /**
7563 * Text drawn dim in an empty field.
7564 */
7565 placeholder?: string;
7566 /**
7567 * The text the field holds when drawn.
7568 */
7569 value?: string;
7570 /**
7571 * What Enter does, drawn beside the field while it has focus.
7572 */
7573 submitLabel?: string;
7574 /**
7575 * The site's ring starts on this element when the site takes the
7576 * keyboard; the first drawn of several. Absent draws as before.
7577 */
7578 autoFocus?: true;
7579 };
7580 /**
7581 * Where the handlers live: the plugin whose hook drew the element, and
7582 * the handle its environment keeps the closures under.
7583 *
7584 * The runtime stamps the plugin as the tree leaves that hook.
7585 */
7586 press: {
7587 plugin: string;
7588 handle: number;
7589 };
7590 children?: undefined;
7591 } | {
7592 /**
7593 * A one-of-several picker on every surface; a pick raises `ui.select`
7594 * (`e.element` the key, `e.value` the option's value).
7595 *
7596 * Built by `<Select>` or the table's `t.Select`. The `onSelect` closure
7597 * stays in the plugin's own environment under `press.handle`, held as
7598 * a Button's is. A leaf: no children.
7599 */
7600 type: 'Select';
7601 props: {
7602 /**
7603 * The element's address: what `e.element` carries and what a matcher
7604 * names (`{ element: "peer" }`).
7605 */
7606 key: string;
7607 /**
7608 * Text drawn before the current value.
7609 */
7610 label?: string;
7611 /**
7612 * What can be picked, in the order drawn: each a value and the text
7613 * drawn for it.
7614 */
7615 options: readonly SelectOption[];
7616 /**
7617 * Which option is selected when drawn.
7618 */
7619 value?: string;
7620 /**
7621 * The site's ring starts on this element when the site takes the
7622 * keyboard; the first drawn of several. Absent draws as before.
7623 */
7624 autoFocus?: true;
7625 };
7626 /**
7627 * Where the handler lives: the plugin whose hook drew the element, and
7628 * the handle its environment keeps the closure under.
7629 *
7630 * The runtime stamps the plugin as the tree leaves that hook.
7631 */
7632 press: {
7633 plugin: string;
7634 handle: number;
7635 };
7636 children?: undefined;
7637 } | {
7638 /**
7639 * A hyperlink every surface draws: an OSC 8 span on the terminal (its
7640 * text then the URL in dim where unsupported), an anchor on desktop.
7641 *
7642 * Inline: its children are the text, strings and inline elements;
7643 * absent children the label, absent both the URL. `href` is `https:`
7644 * (or `http://localhost`) and bounded, or the tree is refused.
7645 */
7646 type: 'Link';
7647 props: LinkProps;
7648 children?: RenderNode[];
7649 } | {
7650 /**
7651 * Source code every surface draws with the engine's highlighter, tokens
7652 * coloured by language; under `format: 'diff'`, unified-diff hunks.
7653 *
7654 * A leaf: a dim gutter numbers the lines from `startLine`; a diff has
7655 * both gutters, markers, add and remove backgrounds. `source` is
7656 * bounded as a Text's string is, or the tree is refused.
7657 */
7658 type: 'Code';
7659 props: CodeProps;
7660 children?: undefined;
7661 } | {
7662 /**
7663 * A block of markdown every surface draws as it draws an assistant
7664 * reply's text: its own renderer, theme, hyperlinks and highlighting.
7665 *
7666 * Built by `<Markdown>` or the table's `t.Markdown`. A leaf: `text` is
7667 * bounded as a Text's string is, or the tree is refused. Without a
7668 * `press` its links are the surface's own, opened as it opens links.
7669 */
7670 type: 'Markdown';
7671 props: MarkdownLeafProps;
7672 children?: undefined;
7673 } | {
7674 /**
7675 * A `Markdown` whose plugin answers the links it drew (`onLinkPress`):
7676 * a press on one raises `ui.press` with `e.link`, the surface opens none.
7677 */
7678 type: 'Markdown';
7679 props: MarkdownLeafProps;
7680 /**
7681 * Where the `onLinkPress` handler lives: the plugin whose hook drew
7682 * the element, and the handle its environment keeps the closure under.
7683 *
7684 * The runtime stamps the plugin as the tree leaves that hook.
7685 */
7686 press: {
7687 plugin: string;
7688 handle: number;
7689 };
7690 children?: undefined;
7691 } | {
7692 /**
7693 * A region one of the plugin's SURFACE MODULES, named by path, draws and
7694 * handles input for on the drawing thread, without `$` (ClientModule).
7695 *
7696 * `Client` from the table. One instance per plugin, drawing and `key`
7697 * lives while the node stays in the tree, and talks to the plugin's
7698 * hooks through `ui.message`. The desktop carries it as data.
7699 */
7700 type: 'Client';
7701 props: ClientProps;
7702 /**
7703 * Whose surface module `props.module` names: the plugin whose hook
7704 * drew the element, stamped by the runtime as the tree leaves it.
7705 */
7706 client: {
7707 plugin: string;
7708 };
7709 children?: undefined;
7710 } | {
7711 /**
7712 * A vector drawing, the remote surfaces' alone: the SVG markup is the
7713 * element's data, drawn in an isolated box, off the page.
7714 *
7715 * A leaf: hooks above wrap or replace it whole, nothing reaches inside;
7716 * a press other plugins should see goes on an enclosing Button. On a
7717 * surface whose table lacks it the tree is refused.
7718 */
7719 type: 'Svg';
7720 props: SvgProps;
7721 children?: undefined;
7722 } | {
7723 /**
7724 * A grid of terminal cells, the terminal surface's alone: each cell a
7725 * glyph, a foreground and a background, packed in `props.cells`.
7726 *
7727 * A leaf, one node however many cells; hooks above wrap or replace it
7728 * whole. A mounted one is repainted in place by its plugin's
7729 * `$.ui.blit`. On a surface whose table lacks it the tree is refused.
7730 */
7731 type: 'Raster';
7732 props: RasterProps;
7733 /**
7734 * Whose Raster: the plugin whose hook drew the element, stamped by the
7735 * runtime as the tree leaves it; the one plugin whose blit reaches it.
7736 */
7737 raster: {
7738 plugin: string;
7739 };
7740 children?: undefined;
7741 } | {
7742 /**
7743 * A picture, the terminal surface's alone: `props.source` drawn over a
7744 * box of cells where the terminal can, `props.alt` where it cannot.
7745 *
7746 * A leaf: hooks above wrap or replace it whole; a press other plugins
7747 * should see goes on an enclosing Button; keyed, its plugin's
7748 * `$.ui.blit` swaps it. On a surface without it the tree is refused.
7749 */
7750 type: 'Image';
7751 props: ImageProps;
7752 /**
7753 * Whose Image: the plugin whose hook drew the element, stamped by the
7754 * runtime as the tree leaves it; the one plugin whose blit reaches it.
7755 */
7756 image: {
7757 plugin: string;
7758 };
7759 children?: undefined;
7760 } | {
7761 /**
7762 * The component core draws itself, with the props held under `ref`.
7763 */
7764 type: 'engine';
7765 /**
7766 * Which drawing: the number core answered from `next(e)`, under which
7767 * it holds the props it received; 0 draws the original props.
7768 */
7769 ref: number;
7770 };
7771
7772 /**
7773 * The render event: `ui.render`, one event for every component that has a
7774 * render site.
7775 */
7776 export type RenderEventName = 'ui.render';
7777
7778 /**
7779 * The input of `ui.render`: a union discriminated by `component`, one member
7780 * per RenderComponent and per RenderSurface.
7781 */
7782 export type RenderInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = C extends RenderComponent ? P extends RenderSurface ? RenderInputOf<C, P> : never : never;
7783
7784 /**
7785 * One `ui.render` input, for a component narrowed to one surface.
7786 */
7787 export type RenderInputOf<C extends RenderComponent, P extends RenderSurface> = {
7788 /**
7789 * Where the tree will be drawn; one literal per member, so
7790 * `if (e.surface === "terminal")` narrows `e` and `$.ui.resolve(e)`.
7791 *
7792 * Over the wire it is what the client declared, a rendering fact and not a
7793 * trust signal: do not key policy on it.
7794 */
7795 surface: P;
7796 /**
7797 * Which component this instance is; the key a matcher narrows on.
7798 */
7799 component: C;
7800 /**
7801 * The instance: the tool_use_id for a dialog or tool row, the message id
7802 * for a message, the agent id for a spinner.
7803 *
7804 * Two drawings of one component are two instances.
7805 */
7806 requestId: string;
7807 /**
7808 * The size of what the surface draws into, in character cells, and whether
7809 * its layout docks a pane; absent where no surface has measured.
7810 *
7811 * Part of the envelope: a rewrite keeps it. On the terminal, the interactive
7812 * screen's, where a change of width re-draws every hooked site once the
7813 * resize settles; on a remote surface, what it reported.
7814 */
7815 viewport?: RenderViewport;
7816 /**
7817 * The component's plain-data props.
7818 */
7819 props: RenderPropsOf[C];
7820 };
7821
7822 /**
7823 * A node of a render tree: an element, or a string (text).
7824 */
7825 export type RenderNode = RenderElement | string;
7826
7827 /**
7828 * The plain-data props of each renderable component, as `ui.render` sees
7829 * them under `e.props`; a hook rewrites them with `next({ ...e, props })`.
7830 *
7831 * A rewrite is validated by the component and an invalid one draws the
7832 * original. This table is the plugin-facing render contract; the author's
7833 * file notes which surfaces raise each member (RENDER_SURFACES_OF).
7834 */
7835 export type RenderPropsOf = {
7836 /**
7837 * The dialog the AskUserQuestion tool opens.
7838 *
7839 * Raised on every surface.
7840 */
7841 AskUserQuestion: {
7842 /**
7843 * The name of the tool whose call opened the dialog (`AskUserQuestion`).
7844 */
7845 tool: string;
7846 /**
7847 * The tool's `questions` input, as the dialog will draw them; a rewrite
7848 * must still fit the tool's schema or the original is drawn.
7849 */
7850 questions: unknown[];
7851 /**
7852 * The call's `metadata.source` (who asked) when the model gave one.
7853 * Analytics only; never drawn.
7854 */
7855 metadataSource?: string;
7856 };
7857 /**
7858 * A user-role transcript row: the person's prompt (`> ...`), a background
7859 * task's notification, or a message another agent, teammate or session sent.
7860 *
7861 * `origin`, `task` and `from` tell them apart and are read-only; a rewrite
7862 * of `text` draws in the row alone: the stored message, and the model's
7863 * framing of another party's words as that party's, stay as they were.
7864 *
7865 * Raised on every surface.
7866 */
7867 UserMessage: {
7868 /**
7869 * What the row shows: the prompt as typed, a notification's summary, or
7870 * a message's body less the engine's framing (summary line included).
7871 *
7872 * A rewrite is printable, bounded text and draws where the engine draws
7873 * the body; a teammate block of several frames or with a summary line
7874 * keeps the engine's drawing, one string not being those parts.
7875 */
7876 text: string;
7877 /**
7878 * Where the stored message came from, as `prompt.submit` named it: the
7879 * composer's, a task notification's, a peer's, a channel's, a plugin's.
7880 *
7881 * `unclassified` for a teammate's (its drain stamps none) and for a
7882 * message stored before stamps. Read-only.
7883 */
7884 origin: PromptOrigin;
7885 /**
7886 * Whether the view draws the row in full: the ctrl+o transcript,
7887 * `--verbose`, a surface with no ctrl+o (an export). Read-only.
7888 *
7889 * False, a message row is one dim line naming its sender; a hook that
7890 * draws a compact row of its own passes when true, so ctrl+o shows all.
7891 */
7892 isExpanded: boolean;
7893 /**
7894 * What a notification row (`origin.kind` `task-notification`) reports
7895 * on: its background task; absent on every other row. Read-only.
7896 */
7897 task?: UserMessageTask;
7898 /**
7899 * Who sent the message the row carries: another agent of this session, a
7900 * teammate, another session, a channel; absent otherwise. Read-only.
7901 */
7902 from?: UserMessageFrom;
7903 /**
7904 * Which of its rows the transcript's viewport shows now: `null` while
7905 * drawn outside it, absent where the surface does not say. Read-only.
7906 *
7907 * Reported once drawn and again when it changes: on a scroll, for the
7908 * messages at the viewport's edges only. A rewrite carries it on as
7909 * received; one that changes or drops it is refused.
7910 */
7911 onScreen?: OnScreen | null;
7912 };
7913 /**
7914 * One text block of an assistant reply in the transcript; a rewrite
7915 * changes the drawing and leaves the stored message alone (ctrl+o).
7916 *
7917 * Raised on every surface.
7918 */
7919 AssistantMessage: {
7920 /**
7921 * The block's text, markdown, as the transcript will draw it.
7922 */
7923 text: string;
7924 /**
7925 * True on the block that draws the bullet opening a reply.
7926 */
7927 isFirstOfReply: boolean;
7928 /**
7929 * Which of its rows the transcript's viewport shows now: `null` while
7930 * drawn outside it, absent where the surface does not say. Read-only.
7931 *
7932 * Reported once drawn and again when it changes: on a scroll, for the
7933 * messages at the viewport's edges only. A rewrite carries it on as
7934 * received; one that changes or drops it is refused.
7935 */
7936 onScreen?: OnScreen | null;
7937 };
7938 /**
7939 * A tool call's row in the transcript (`Bash(ls -la)` and its result); the
7940 * call was decided by `tool.call`, so a rewrite here changes the row alone.
7941 *
7942 * Raised on every surface.
7943 */
7944 ToolUse: {
7945 /**
7946 * The id `tool.call` carried for this call (`e.tool_use_id` there); the
7947 * same value as the row's `requestId`, where it is looked for. Read-only.
7948 */
7949 tool_use_id: string;
7950 /**
7951 * Which one the row draws (`Bash`, `Read`, a plugin's tool), as
7952 * `tool.call` named it.
7953 */
7954 tool: string;
7955 /**
7956 * The call's input, as the model sent it.
7957 */
7958 input: unknown;
7959 /**
7960 * True while the call is still running.
7961 */
7962 isRunning: boolean;
7963 /**
7964 * True when the call ended in an error (a refusal at the dialog is one).
7965 */
7966 isErrored: boolean;
7967 /**
7968 * True when an abort ended the call: the user's Esc or a plugin's
7969 * `$.turn.abort` cut it while it ran, or dropped it before it ran.
7970 *
7971 * The row draws `Interrupted` for it, as the transcript marker does.
7972 */
7973 isInterrupted: boolean;
7974 /**
7975 * The stored result once the call has resolved (`{ stdout, stderr, ... }`
7976 * for Bash: `BuiltinToolResults[tool]`); undefined while it runs.
7977 *
7978 * For a call that errored, was refused or an abort cut, it is the text
7979 * the model read (an `isInterrupted` call: the abort's own). An expanded
7980 * group's rows draw it inline; a standalone row's is its own `ToolResult`.
7981 */
7982 output?: unknown;
7983 /**
7984 * Which of its rows the transcript's viewport shows now: `null` while
7985 * drawn outside it, absent where the surface does not say. Read-only.
7986 *
7987 * Reported once drawn and again when it changes: on a scroll, for the
7988 * messages at the viewport's edges only. A rewrite carries it on as
7989 * received; one that changes or drops it is refused.
7990 */
7991 onScreen?: OnScreen | null;
7992 };
7993 /**
7994 * The result block drawn under a standalone tool row in the transcript,
7995 * which the tool's own result renderer draws from `output`.
7996 *
7997 * A rewrite of `output` is checked against the tool's output schema (one
7998 * that does not fit draws nothing; one the renderer cannot read hits the
7999 * row's error boundary). The stored result is untouched.
8000 *
8001 * Raised on every surface.
8002 */
8003 ToolResult: {
8004 /**
8005 * The id `tool.call` carried for the call this result belongs to
8006 * (`e.tool_use_id` there); the same value as `requestId`. Read-only.
8007 */
8008 tool_use_id: string;
8009 /**
8010 * Which one the result belongs to (`Bash`, `Read`, a plugin's tool).
8011 * Read-only.
8012 */
8013 tool: string;
8014 /**
8015 * The tool's own result object (`{ stdout, stderr, interrupted, ... }` for
8016 * Bash), the same one `ToolUse.output` carries; a rewrite is drawn.
8017 *
8018 * A built-in tool's is `BuiltinToolResults[tool]`, the record
8019 * `tool.call` resolved as `result`.
8020 */
8021 output: unknown;
8022 /**
8023 * True when the call ended in an error, which draws the error text and not
8024 * `output`. Read-only.
8025 */
8026 isErrored: boolean;
8027 /**
8028 * Which of its rows the transcript's viewport shows now: `null` while
8029 * drawn outside it, absent where the surface does not say. Read-only.
8030 *
8031 * Reported once drawn and again when it changes: on a scroll, for the
8032 * messages at the viewport's edges only. A rewrite carries it on as
8033 * received; one that changes or drops it is refused.
8034 */
8035 onScreen?: OnScreen | null;
8036 };
8037 /**
8038 * A run of tool calls the transcript folds into one count line (`Read 3
8039 * files, ran 2 shell commands`): reads, searches, listings.
8040 *
8041 * A hook that sets `isExpanded` unfolds the group where it is, and each row
8042 * it unfolds into is a `ToolUse` drawing a `ToolUse` hook then sees.
8043 *
8044 * Raised on every surface.
8045 */
8046 ToolGroup: {
8047 /**
8048 * In the order the model made them.
8049 */
8050 calls: ReadonlyArray<ToolGroupCall>;
8051 /**
8052 * True while the group is the live one: a call in it may still be
8053 * running and the model's next call may join it.
8054 */
8055 isActive: boolean;
8056 /**
8057 * Whether each call draws as its own `ToolUse` row (true under
8058 * `--verbose` and in the ctrl+o transcript) or the group draws one line.
8059 *
8060 * The one prop of the three a rewrite changes on the screen.
8061 */
8062 isExpanded: boolean;
8063 /**
8064 * Which of its rows the transcript's viewport shows now: `null` while
8065 * drawn outside it, absent where the surface does not say. Read-only.
8066 *
8067 * Reported once drawn and again when it changes: on a scroll, for the
8068 * messages at the viewport's edges only. A rewrite carries it on as
8069 * received; one that changes or drops it is refused.
8070 */
8071 onScreen?: OnScreen | null;
8072 };
8073 /**
8074 * The output row a slash command printed in the transcript, under its echo
8075 * (`/cost`'s lines, the `text` a `command.run` hook answered).
8076 *
8077 * What the run resolved as text, a `local` command's or a plugin's alike. A
8078 * rewrite of `text` draws there and the stored row keeps what the model
8079 * reads; a hook's own tree draws in the row's place, the transcript's width.
8080 *
8081 * Raised on every surface.
8082 */
8083 CommandOutput: {
8084 /**
8085 * Which one printed the row, as `command.run` named it (no slash); a
8086 * hook on its own command matches by it.
8087 *
8088 * Read-only: a rewrite carries it on as received; one that changes or
8089 * drops it is refused and the engine draws its own row.
8090 */
8091 command: string;
8092 /**
8093 * The arguments the run had, as the echo above the row shows them
8094 * (`***` for a command that marks its arguments sensitive). Read-only.
8095 */
8096 args: string;
8097 /**
8098 * The row's text: what the command printed, or the `text` a hook
8099 * answered under its plugin's name; markdown, as the row draws it.
8100 */
8101 text: string;
8102 /**
8103 * True when the row is the run's error line (a command that threw),
8104 * which draws in the error colour and not dim. Read-only.
8105 */
8106 isErrored: boolean;
8107 /**
8108 * Which of its rows the transcript's viewport shows now: `null` while
8109 * drawn outside it, absent where the surface does not say. Read-only.
8110 *
8111 * Reported once drawn and again when it changes: on a scroll, for the
8112 * messages at the viewport's edges only. A rewrite carries it on as
8113 * received; one that changes or drops it is refused.
8114 */
8115 onScreen?: OnScreen | null;
8116 };
8117 /**
8118 * One row of the live tool-progress region under a running tool call; today
8119 * the run-in-background pill. One instance per row.
8120 *
8121 * A union on `kind`: other progress kinds join as their props become plain
8122 * data, each with its own fields, so a hook matches `{ props: { kind:
8123 * "background_hint" } }` or branches on `e.props.kind` and stays right.
8124 *
8125 * Raised on the terminal surface only.
8126 */
8127 ToolProgress: {
8128 /**
8129 * The tool call the row belongs to, as `tool.call` and the `ToolUse` row
8130 * carry it. Read-only: a rewrite carries it on as received.
8131 *
8132 * While several foreground calls share one pill, the first of them.
8133 */
8134 tool_use_id: string;
8135 /**
8136 * Which progress row: the run-in-background pill. Read-only.
8137 */
8138 kind: 'background_hint';
8139 /**
8140 * The pill's text as the engine draws it, dim, under the tool call:
8141 * `(ctrl+b to run in background)`, or with the person's own binding.
8142 *
8143 * A rewrite is drawn in its place, dim; `""` draws nothing. A hook that
8144 * returns a tree draws that instead.
8145 */
8146 hint: string;
8147 };
8148 /**
8149 * The line that animates while a turn runs (`Sauteing... (12s, 300
8150 * tokens)`); a remote surface draws its own.
8151 *
8152 * The row reads `word` (or `message` while one overrides it), then
8153 * `suffix`, then the dim parenthetical the engine keeps (elapsed time,
8154 * tokens, effort); a hook rewrites the first three or draws its own tree.
8155 *
8156 * Raised on the terminal surface only.
8157 */
8158 Spinner: {
8159 /**
8160 * Animated by the line (`Sauteing`), as sampled for this turn.
8161 */
8162 word: string;
8163 /**
8164 * The text drawn instead of the word while a state overrides it, else null.
8165 */
8166 message: string | null;
8167 /**
8168 * What the engine draws right after the word or message to say the turn is
8169 * still going: one ellipsis character.
8170 *
8171 * Left off a text that already ends in an ellipsis, so a rewritten
8172 * `message` ending in one shows one. A rewrite is drawn as given (`""`
8173 * draws the text bare, `" ~"` draws `Sauteing ~`); left out, the engine's.
8174 */
8175 suffix: string;
8176 /**
8177 * What the turn is doing.
8178 */
8179 mode: 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use';
8180 };
8181 /**
8182 * The line that closes a turn in the transcript (`Baked for 3s`); a
8183 * remote surface draws its own footer.
8184 *
8185 * Raised on the terminal surface only.
8186 */
8187 TurnDuration: {
8188 /**
8189 * The past-tense word the line drew (`Baked`), as sampled for this line.
8190 */
8191 word: string;
8192 /**
8193 * The turn's duration in milliseconds, as the line formats it (`3s`,
8194 * `1m 4s`).
8195 */
8196 durationMs: number;
8197 /**
8198 * Which of its rows the transcript's viewport shows now: `null` while
8199 * drawn outside it, absent where the surface does not say. Read-only.
8200 *
8201 * Reported once drawn and again when it changes: on a scroll, for the
8202 * messages at the viewport's edges only. A rewrite carries it on as
8203 * received; one that changes or drops it is refused.
8204 */
8205 onScreen?: OnScreen | null;
8206 };
8207 /**
8208 * One dim status line under the logo (the model source, an experiment
8209 * enrollment, a settings hint), with a trailing `/command`.
8210 *
8211 * Raised on the terminal surface only.
8212 */
8213 InfoNotice: {
8214 /**
8215 * The notice's text, flattened to one string.
8216 */
8217 text: string;
8218 /**
8219 * The slash command appended after the text, or null when the notice has
8220 * none.
8221 */
8222 command: string | null;
8223 /**
8224 * Which of its rows the transcript's viewport shows now: `null` while
8225 * drawn outside it, absent where the surface does not say. Read-only.
8226 *
8227 * Reported once drawn and again when it changes: on a scroll, for the
8228 * messages at the viewport's edges only. A rewrite carries it on as
8229 * received; one that changes or drops it is refused.
8230 */
8231 onScreen?: OnScreen | null;
8232 };
8233 /**
8234 * The dim mode labels at the right of the prompt footer (`focus`, `memory
8235 * paused`), joined by ` & `. One instance.
8236 *
8237 * A hook adds a mode by rewriting `modes`, removes one by filtering, or
8238 * draws its own tree.
8239 *
8240 * Raised on the terminal and desktop surfaces only.
8241 */
8242 SessionMode: {
8243 /**
8244 * The labels the footer shows, in order; empty when there are none.
8245 */
8246 modes: readonly string[];
8247 };
8248 /**
8249 * The dim hint line under the prompt (`? for shortcuts`, `esc to
8250 * interrupt`, the pills beside them). One instance.
8251 *
8252 * A hook rewrites `hint` and the rewrite is drawn in the line's place, or
8253 * draws its own tree; `isDraft` and `isWorking` say what the line is for.
8254 *
8255 * Raised on the terminal surface only.
8256 */
8257 PromptHint: {
8258 /**
8259 * True while the prompt holds typed text. Read-only.
8260 */
8261 isDraft: boolean;
8262 /**
8263 * True while a model turn is running. Read-only.
8264 */
8265 isWorking: boolean;
8266 /**
8267 * The line's text as the engine draws it; one string, so a rewrite
8268 * replaces the line.
8269 *
8270 * Read from the drawn line the way the screen reader reads it, one space
8271 * between parts.
8272 */
8273 hint: string;
8274 };
8275 /**
8276 * The band directly above the prompt input, where the surveys draw; the
8277 * engine draws nothing of its own here.
8278 *
8279 * A hook draws a tree, or passes; one instance. The person collapses it
8280 * (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab): an Input
8281 * types, a Button arms the hotkeys, a tree taller than it scrolls.
8282 *
8283 * Raised on the terminal surface only.
8284 */
8285 AbovePrompt: {
8286 /**
8287 * True while a survey holds the band; a hook yields to it. Read-only.
8288 */
8289 hasSurvey: boolean;
8290 /**
8291 * True while a model turn is running. Read-only.
8292 */
8293 isWorking: boolean;
8294 /**
8295 * Rows the band may take: in fullscreen, what the bottom slot has left
8296 * above the prompt; otherwise the terminal's height. Read-only.
8297 *
8298 * That slot is capped at half the terminal's rows, the prompt's included.
8299 * A tree of at most `maxRows` rows shows whole; a taller one scrolls in a
8300 * window of `scroll.bodyRows`, and a bare digit arms no Button's hotkey.
8301 */
8302 maxRows: number;
8303 /**
8304 * Cells across the band: the terminal's width, or the transcript
8305 * column's while a `Pane` is docked beside it. Read-only.
8306 *
8307 * A tree wider than this wraps or truncates as its Text props say; size
8308 * a table or a rule to it rather than to `viewport.columns`.
8309 */
8310 bodyColumns: number;
8311 /**
8312 * The band's window over a tree taller than `maxRows`: engine-owned,
8313 * moved by the wheel, and by the person's keys while the band is focused.
8314 *
8315 * `bodyRows` is `maxRows` less the `n more` row. Read-only.
8316 */
8317 scroll: SiteScroll;
8318 /**
8319 * Which transcript is on screen above the band: the main conversation's
8320 * (no `agentId`) or one agent's, opened from the tasks list.
8321 *
8322 * The same band under either; a switch re-runs the hook with the new
8323 * view. Read-only: a rewrite carries it on as received; one that changes
8324 * or drops it is refused, the hook that passed it failing.
8325 */
8326 view: SiteView;
8327 };
8328 /**
8329 * The framed region a plugin opened with `$.ui.open({ id })`: one instance
8330 * per id (`requestId`), its body the hook's tree, one shown, the rest tabs.
8331 *
8332 * Placed by the surface (docked in fullscreen, else above the prompt) and
8333 * keyed by the person (ctrl+x tab, Esc), who closes it from the engine's mark
8334 * or ctrl+x x: `ui.close` with origin `person`, which a hook may refuse.
8335 *
8336 * Raised on every surface.
8337 */
8338 Pane: {
8339 /**
8340 * Its tab's label while more than one pane is open (with one, the engine
8341 * draws no title): the `title` it was opened with, or its id.
8342 *
8343 * A click on a tab, or Tab onto it and Enter, shows that pane. Read-only
8344 * here; another `$.ui.open` (or a hook on `ui.open`) retitles.
8345 */
8346 title: string;
8347 /**
8348 * True while the person has given the pane the keyboard: Tab walks its
8349 * elements, a Button's `hotkey` presses it, the arrows scroll. Read-only.
8350 */
8351 isFocused: boolean;
8352 /**
8353 * Cells across the body, inside the frame. Read-only.
8354 */
8355 bodyColumns: number;
8356 /**
8357 * Where the surface seated the pane: `dock` beside the transcript (the
8358 * terminal in fullscreen from 110 columns), or `inline` above the prompt.
8359 *
8360 * Read-only: a rewrite carries it on as received; one that changes or
8361 * drops it is refused, the hook that passed it failing.
8362 */
8363 placement: 'dock' | 'inline';
8364 /**
8365 * The body's window over the tree: engine-owned, moved by the person's
8366 * keys while the pane is focused. Read-only.
8367 */
8368 scroll: SiteScroll;
8369 /**
8370 * Which transcript is on screen beside the pane: the main conversation's
8371 * (no `agentId`) or one agent's, opened from the tasks list.
8372 *
8373 * The pane stays open across a switch, one instance re-rendered for the
8374 * view, so a hook draws for the agent in view. Read-only: a rewrite carries
8375 * it on as received; one that changes or drops it is refused.
8376 */
8377 view: SiteView;
8378 };
8379 };
8380
8381 /**
8382 * What a `ui.render` hook returns and what `next(e)` resolves to: a
8383 * RenderElement tree, the same for every component.
8384 */
8385 export type RenderResultOf = {
8386 [C in RenderComponent]: RenderElement;
8387 };
8388
8389 /**
8390 * Where a render event's component is drawn: `terminal` is Ink, which draws
8391 * the hook's whole tree; the rest are remote surfaces drawing it themselves.
8392 *
8393 * `desktop` is Claude Code Desktop, `mobile` the Claude mobile app, `vscode`
8394 * Claude Code for VS Code. A remote surface asks over the wire (ui_render),
8395 * draws with the props the hook handed core, and draws the tree where it has
8396 * a slot for it.
8397 *
8398 * Each surface's ask is its own evaluation, since a tree may hold an element
8399 * only some surfaces draw (Svg, Client).
8400 */
8401 export type RenderSurface = 'terminal' | 'desktop' | 'mobile' | 'vscode';
8402
8403 /**
8404 * The size of what a surface draws into, in character cells of the
8405 * surface's monospace metric, and whether its layout docks a pane.
8406 *
8407 * On the terminal, the conversation's columns and screen rows; on a remote
8408 * surface, the pane's width and height over the advance and line height of
8409 * its code font. Cell-based until the first element lays out in pixels.
8410 */
8411 export type RenderViewport = {
8412 /**
8413 * Cells across. A tree wider than this wraps or truncates, as its Text
8414 * props say.
8415 */
8416 columns: number;
8417 /**
8418 * Cells down the whole surface, not the room left for this component.
8419 *
8420 * Informational: a change of height alone re-draws nothing and keys no
8421 * new evaluation, so a hook reads it as of the last width or props change.
8422 */
8423 rows: number;
8424 /**
8425 * Whether this surface docks a pane beside the transcript, so a pane a
8426 * plugin opens unasked is a sidebar, not a takeover; absent is unknown.
8427 *
8428 * What `command.run`'s `presentation.isFullscreen` says. The terminal always
8429 * says: `true` fullscreen, `false` on the main screen, fixed per session; a
8430 * remote surface once its client reports it with the size, absent before.
8431 *
8432 * @remarks The desktop and VS Code report it once they place panes; the
8433 * mobile app, which has no dock, `false`. A change re-draws the sites.
8434 * @example if (e.viewport?.isFullscreen === true) void $.ui.open({ id })
8435 */
8436 isFullscreen?: boolean;
8437 };
8438
8439 /**
8440 * The input of `ui.resolve`: which surface's elements, for which component;
8441 * a union with one member per surface (ResolveInputOf).
8442 *
8443 * Resolved when the plugins load, ahead of any drawing, so it names the
8444 * surface and the component and not the props; a `ui.render` argument is
8445 * one (it carries both), which is what `$.ui.resolve(e)` takes.
8446 */
8447 export type ResolveInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = P extends RenderSurface ? ResolveInputOf<C, P> : never;
8448
8449 /**
8450 * One `ui.resolve` input, for a component on one surface.
8451 */
8452 export type ResolveInputOf<C extends RenderComponent, P extends RenderSurface> = {
8453 /**
8454 * Where the table draws; one literal per member, so a hook that narrows
8455 * it narrows the table `next(e)` resolves to.
8456 */
8457 surface: P;
8458 /**
8459 * Which drawing the table is resolved for; the key a matcher narrows on.
8460 */
8461 component: C;
8462 };
8463
8464 /**
8465 * What each event's hook returns, and what its `next(e)` resolves to, by event
8466 * name.
8467 */
8468 export type ResultOf = EngineResultOf & ClassicResultOf & {
8469 [N in OpEventName]: OpEventResult<N>;
8470 } & {
8471 [N in NounEventName]: NounEventResult<N>;
8472 };
8473
8474 type SDKAssistantMessageError = 'authentication_failed' | 'oauth_org_not_allowed' | 'account_on_hold' | 'verification_required' | 'billing_error' | 'rate_limit' | 'overloaded' | 'invalid_request' | 'model_not_found' | 'server_error' | 'unknown' | 'max_output_tokens' | 'cloud_credential_error';
8475
8476 /**
8477 * The members of `T` assignable to `S`; all of `T` when none is.
8478 */
8479 type Select<T, S> = [Extract<T, S>] extends [never] ? T : Extract<T, S>;
8480
8481 /**
8482 * The events a pattern selects, as a union of names: the one named, every
8483 * one under a glob's namespace, or every one a negation does not exclude.
8484 */
8485 export type Selected<P extends string> = P extends '*' ? EventName : P extends `!${infer Negated}` ? Exclude<EventName, Selected<Negated>> : P extends `${infer Prefix}.*` ? Extract<EventName, `${Prefix}.${string}`> : Extract<EventName, P>;
8486
8487 /**
8488 * The literal each tag key of `I` is held to by matcher `M`: one-of arrays
8489 * flattened, RegExps widened to `unknown`.
8490 */
8491 type Selection<I, M> = {
8492 [K in keyof M & TagKeys<I>]: Literal<M[K] extends readonly (infer One)[] ? One : M[K]>;
8493 };
8494
8495 /**
8496 * One option of a `Select`: the value `onSelect` and `ui.select` carry, and
8497 * the text drawn for it (the value when absent).
8498 */
8499 export type SelectOption = {
8500 value: string;
8501 label?: string;
8502 };
8503
8504 /**
8505 * The props of `Select`, every surface's one-of-several picker: an address,
8506 * a label, the options, the one selected, the closure a pick runs. A leaf.
8507 *
8508 * Focused through the same ring as `Button` (`abovePrompt:focus`); keys reach
8509 * it only while it has focus (arrows move, Enter picks) and Esc always
8510 * returns to the prompt; a pick raises `ui.select`, its bottom `onSelect`.
8511 */
8512 export type SelectProps = {
8513 /**
8514 * The element's address: `e.element` at `ui.select`, what a matcher names.
8515 */
8516 key: string;
8517 /**
8518 * Text drawn before the current value.
8519 */
8520 label?: string;
8521 /**
8522 * What can be picked, in the order drawn; at least one, values unique.
8523 */
8524 options: readonly SelectOption[];
8525 /**
8526 * Which option is selected when drawn; the person's pick replaces it
8527 * until the hook draws another.
8528 */
8529 value?: string;
8530 /**
8531 * The site's focus ring starts here when the site takes the keyboard,
8532 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
8533 *
8534 * A pane opened with `focus`, or the person's focus chord or click, is the
8535 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
8536 * origin this plugin. A ring the person has moved stays where it was put.
8537 */
8538 autoFocus?: true;
8539 /**
8540 * Runs on a pick with the option's value, in the plugin's own environment:
8541 * the bottom of a `ui.select` chain. No model turn unless it asks one.
8542 */
8543 onSelect: (value: string, e: UiSelectArgument) => void;
8544 };
8545
8546 /**
8547 * The input of `session.attach`: a surface joined the session's roster of
8548 * attached clients (a phone opened the session; the desktop app connected).
8549 *
8550 * A remote client attaches by saying so (ui_attach) or by its first ask to
8551 * draw; the terminal's attachment is the REPL's binding and raises nothing.
8552 * Every field is the engine's: a hook observes, `next(e)` passes them on.
8553 */
8554 export type SessionAttachInput = {
8555 /**
8556 * Where the client draws: what it declared, a rendering fact.
8557 */
8558 surface: RenderSurface;
8559 /**
8560 * The client's own id, unique in the roster; two phones are two clients on
8561 * one surface. A client that never named itself is `<surface>:default`.
8562 */
8563 clientId: string;
8564 /**
8565 * The size the client draws into, in character cells, and whether its
8566 * layout docks a pane, when it said.
8567 */
8568 viewport?: RenderViewport;
8569 };
8570
8571 /**
8572 * What a `session.attach` hook returns and what `next(e)` resolves to:
8573 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
8574 */
8575 export type SessionAttachResult = {
8576 clientId: string;
8577 };
8578
8579 /**
8580 * What `$.session.authorize()` answers: an opaque handle for the session's
8581 * Anthropic credential and its kind, or null when there is none to hold.
8582 *
8583 * The secret itself stays with the engine; the handle is its plugin-side
8584 * face, spent through `$.http.fetch(url, { auth: handle })`.
8585 */
8586 export type SessionAuthorization = {
8587 handle: string;
8588 kind: 'bearer' | 'api-key';
8589 } | null;
8590
8591 /**
8592 * `session.compact`'s input as a plugin's `$.session.compact(args)` takes
8593 * it: `trigger` (`plugin`), `messages` and `agentId` are the engine's.
8594 */
8595 export type SessionCompactArgs = {
8596 /**
8597 * What the summary should keep or stress, as typed after `/compact`;
8598 * absent, the engine's own compaction prompt alone.
8599 */
8600 instructions?: string;
8601 };
8602
8603 /**
8604 * A compaction that stands: the conversation as it reads afterwards, and
8605 * the token counts the engine recorded when it was the one compacting.
8606 */
8607 export type SessionCompacted = {
8608 /**
8609 * The conversation after the compaction, oldest first: from core, its
8610 * summary and the messages it kept; from a hook, whatever it hands up.
8611 *
8612 * What the transcript becomes (kept, on `precompute`, for the compaction
8613 * that comes). A message with the engine's `handle` stands as the engine
8614 * has it; one without is built from its `role`, `text` and tool blocks.
8615 */
8616 messages: readonly SessionMessage[];
8617 /**
8618 * The conversation's size before, in tokens; absent when core did not
8619 * record it.
8620 */
8621 tokensBefore?: number;
8622 /**
8623 * Its size afterwards, in tokens; absent on `precompute` and when core
8624 * did not record it.
8625 */
8626 tokensAfter?: number;
8627 skip?: undefined;
8628 };
8629
8630 /**
8631 * The input of `session.compact`: one compaction of the conversation, about
8632 * to run; `messages` is the transcript it runs over.
8633 */
8634 export type SessionCompactInput = {
8635 /**
8636 * What is compacting (SessionCompactTrigger); the key a matcher narrows
8637 * on. Pinned: `next(e)` passes it on as received.
8638 */
8639 trigger: SessionCompactTrigger;
8640 /**
8641 * The id of the loop compacting, for a subagent's or a fork's own
8642 * transcript; absent for the main conversation (tool.call's `agentId`).
8643 *
8644 * Pinned: left out of a rewrite it is put back, changed it fails the hook.
8645 * `$.session.messages()` is the main conversation whatever this names.
8646 */
8647 agentId?: string;
8648 /**
8649 * What the summary should keep or stress: the text after `/compact`, a
8650 * plugin's, or absent.
8651 *
8652 * `next({ ...e, instructions })` changes what the summarizer is told.
8653 */
8654 instructions?: string;
8655 /**
8656 * The transcript being compacted, in `$.session.messages()`'s shape, each
8657 * message carrying the engine's `handle`; a subagent's own under `agentId`.
8658 *
8659 * `next({ ...e, messages })` changes what is summarized: a message kept
8660 * with its handle is the engine's own, whole; one without is read as built.
8661 */
8662 messages: readonly SessionMessage[];
8663 };
8664
8665 /**
8666 * What a `session.compact` hook returns and what `next(e)` resolves to: the
8667 * compaction (`{ messages, tokensBefore?, tokensAfter? }`) or `{ skip }`.
8668 *
8669 * There is no summary string: the summary is a message.
8670 */
8671 export type SessionCompactResult = SessionCompacted | SessionCompactSkipped;
8672
8673 /**
8674 * A compaction vetoed: on `precompute` nothing is computed or kept; on any
8675 * other trigger the conversation stays as it is and one line says why.
8676 *
8677 * Core answers it too, when a classic PreCompact hook blocks.
8678 */
8679 export type SessionCompactSkipped = {
8680 /**
8681 * Why, as the notice reads.
8682 */
8683 skip: string;
8684 messages?: undefined;
8685 };
8686
8687 /**
8688 * Who compacts: the person's `/compact` (`manual`), the engine at its
8689 * threshold or on a prompt too long (`auto`), a plugin, or a `precompute`.
8690 *
8691 * `precompute` is the one dispatch that installs nothing: its result is kept
8692 * for the compaction that comes, if the conversation it ran over still leads.
8693 */
8694 export type SessionCompactTrigger = 'manual' | 'auto' | 'plugin' | 'precompute';
8695
8696 /**
8697 * The context window broken down as /context breaks it down: the rows, the
8698 * grid and the lists beneath it, in the SDK's `get_context_usage` shape.
8699 *
8700 * Less that reply's internal-build sections. Token counts are the engine's
8701 * estimates as numbers, never formatted: a `full` breakdown counts with the
8702 * token-count API where it can, a `summary` one estimates throughout.
8703 */
8704 export type SessionContextBreakdown = {
8705 /**
8706 * One row per category, the free space and the compaction buffer among
8707 * them; `kind` says which is which.
8708 */
8709 categories: ContextCategory[];
8710 /**
8711 * Tokens in use, unclamped: past `rawMaxTokens` when over the window.
8712 */
8713 totalTokens: number;
8714 /**
8715 * The window measured against, the same figure as `rawMaxTokens`.
8716 */
8717 maxTokens: number;
8718 /**
8719 * The window measured against, in tokens: the model's limit, or a smaller
8720 * compaction window (`autocompactSource` says which).
8721 */
8722 rawMaxTokens: number;
8723 /**
8724 * How that window was settled (ContextWindowSource); the SDK's reply
8725 * carries it under this name too, outside its typed schema.
8726 */
8727 autocompactSource: ContextWindowSource;
8728 /**
8729 * `totalTokens` over `rawMaxTokens` as a whole percentage, 0 to 100 and
8730 * past it when over.
8731 */
8732 percentage: number;
8733 /**
8734 * The grid, row by row: 10 by 10, 20 by 10 for a window of a million or
8735 * more, 5 wide when asked for under 80 `columns`.
8736 */
8737 gridRows: ContextGridSquare[][];
8738 /**
8739 * Which model the breakdown was computed for, as `/model` shows it.
8740 */
8741 model: string;
8742 /**
8743 * Each memory file in the context, with its path and tokens.
8744 */
8745 memoryFiles: ContextMemoryFile[];
8746 /**
8747 * Each MCP tool's schema, with its server and tokens.
8748 */
8749 mcpTools: ContextMcpTool[];
8750 /**
8751 * The custom agents the Agent tool describes, each with its tokens.
8752 */
8753 agents: ContextAgent[];
8754 /**
8755 * The slash-command listing, counted; absent when the session lists none.
8756 */
8757 slashCommands?: ContextSlashCommands;
8758 /**
8759 * The skill listing, counted, with one entry per skill; absent when the
8760 * session lists none.
8761 */
8762 skills?: ContextSkills;
8763 /**
8764 * The token count at which auto-compaction runs; absent when it is off.
8765 */
8766 autoCompactThreshold?: number;
8767 /**
8768 * Whether auto-compaction is on for the session.
8769 */
8770 isAutoCompactEnabled: boolean;
8771 /**
8772 * The last response's own token counts, or null before one came back.
8773 */
8774 apiUsage: ContextApiUsage | null;
8775 };
8776
8777 /**
8778 * The live context window as the status line reads it, and by category as
8779 * /context breaks it down when the call asked (`{ breakdown }`).
8780 *
8781 * `tokens` and `percent` are the last API response's input side against the
8782 * model's window, absent until the first response of the live window: a
8783 * fresh session, or one just compacted, until its next response.
8784 */
8785 export type SessionContextUsage = {
8786 /**
8787 * Input tokens the last response was answered over: uncached, cache-written
8788 * and cache-read together (the status line's `total_input_tokens`).
8789 */
8790 tokens?: number;
8791 /**
8792 * The context window of the session's model, in tokens (the status line's
8793 * `context_window_size`).
8794 */
8795 window: number;
8796 /**
8797 * `tokens` over `window` as a whole percentage, 0 to 100 (the status
8798 * line's `used_percentage`).
8799 */
8800 percent?: number;
8801 /**
8802 * The window by category, as /context breaks it down: present only when
8803 * the call passed `breakdown`, and only with a session bound.
8804 *
8805 * It measures against the compaction window (`rawMaxTokens`), which may be
8806 * smaller than `window`, and estimates every category, so its
8807 * `totalTokens` need not equal `tokens`.
8808 */
8809 breakdown?: SessionContextBreakdown;
8810 };
8811
8812 /**
8813 * What the session has cost, as `/cost` and the status line total it.
8814 */
8815 export type SessionCost = {
8816 /**
8817 * US dollars, summed over every priced API response this session.
8818 */
8819 usd: number;
8820 };
8821
8822 type SessionCronSummary = {
8823 id: string;
8824 /**
8825 * Cron expression, e.g. "0 9 * * 1-5".
8826 */
8827 schedule: string;
8828 /**
8829 * False for one-shot wakeups whose cron field encodes a single fire time; true for tasks that re-fire on every match.
8830 */
8831 recurring: boolean;
8832 /**
8833 * Prompt text submitted when the cron fires. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
8834 */
8835 prompt: string;
8836 };
8837
8838 /**
8839 * The input of `session.detach`: a client left the session's roster. Every
8840 * field is the engine's: a hook observes, and `next(e)` passes them on.
8841 */
8842 export type SessionDetachInput = {
8843 /**
8844 * Where the client drew.
8845 */
8846 surface: RenderSurface;
8847 /**
8848 * The id it attached under.
8849 */
8850 clientId: string;
8851 /**
8852 * Why it left: it detached, or the session ended under it.
8853 */
8854 reason: SessionDetachReason;
8855 };
8856
8857 /**
8858 * Why a client left the roster: `detach`, it said so (ui_detach); `end`, the
8859 * session ended with it still attached.
8860 */
8861 export type SessionDetachReason = 'detach' | 'end';
8862
8863 /**
8864 * What a `session.detach` hook returns and what `next(e)` resolves to:
8865 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
8866 */
8867 export type SessionDetachResult = {
8868 clientId: string;
8869 };
8870
8871 type SessionEndHookInput = BaseHookInput & {
8872 hook_event_name: 'SessionEnd';
8873 reason: ExitReason;
8874 };
8875
8876 /**
8877 * The input of `session.end`: the session is ending, why, and how to come back
8878 * to it.
8879 *
8880 * Every field is the engine's: a hook observes, and `next(e)` passes them on.
8881 */
8882 export type SessionEndInput = {
8883 /**
8884 * Why it ends (SessionEndReason), the word the classic SessionEnd hook
8885 * receives as its `reason`.
8886 */
8887 reason: SessionEndReason;
8888 /**
8889 * The ending session's id (`$.session.id()` until now); after a `/clear`
8890 * or a resume the process goes on under another.
8891 */
8892 sessionId: string;
8893 /**
8894 * What `claude --resume` takes to return to it.
8895 */
8896 resume: SessionResume;
8897 };
8898
8899 /**
8900 * Why the session ended: the classic SessionEnd hook's own `reason`, word for
8901 * word.
8902 *
8903 * `prompt_input_exit`, the person left (/exit, ctrl+c, ctrl+d); `clear`, a
8904 * /clear started a fresh one; `resume`, another took its place; `logout`;
8905 * `other`, a `-p` run finished or the process got SIGINT, SIGTERM or SIGHUP.
8906 */
8907 export type SessionEndReason = ClassicHookInputs['SessionEnd']['reason'];
8908
8909 /**
8910 * What a `session.end` hook returns and what `next(e)` resolves to:
8911 * `{ sessionId }`, echoed by core; a hook's own value changes nothing.
8912 */
8913 export type SessionEndResult = {
8914 sessionId: string;
8915 };
8916
8917 /**
8918 * The input of `session.measure`: what `$.session.usage()` answers at this
8919 * moment, and which of its units moved since the last measurement a hook saw.
8920 *
8921 * The same figures the op reads, without `context.breakdown`: call
8922 * `$.session.usage({ breakdown })` from the hook when the categories matter.
8923 * Every field is the engine's: a hook observes, and `next(e)` passes them on.
8924 */
8925 export type SessionMeasureInput = {
8926 /**
8927 * The live context window (`$.session.usage()`'s `context`): the window,
8928 * and its fill once a response of the live window reported one.
8929 *
8930 * Never carries `breakdown` here.
8931 */
8932 context: SessionContextUsage;
8933 /**
8934 * The rate-limit windows the last response reported, each with its
8935 * `percentUsed`; empty off a subscription or before the first reading.
8936 */
8937 rateLimits: SessionRateLimit[];
8938 /**
8939 * What the session has cost so far; absent where the host keeps no ledger.
8940 */
8941 cost?: SessionCost;
8942 /**
8943 * Which units differ from the last measurement raised (UsageUnit), never
8944 * empty; the first measurement names every unit it has a figure for.
8945 *
8946 * `context`: the fill moved; `rateLimits`: a window moved a whole point,
8947 * appeared or left, or the account's limit status changed; `cost`: the
8948 * total grew.
8949 */
8950 changed: UsageUnit[];
8951 };
8952
8953 /**
8954 * What a `session.measure` hook returns and what `next(e)` resolves to:
8955 * `{ changed }`, echoed by core; a hook's own value changes nothing.
8956 */
8957 export type SessionMeasureResult = {
8958 changed: UsageUnit[];
8959 };
8960
8961 /**
8962 * One message of the transcript as `$.session.messages()` returns it.
8963 */
8964 export type SessionMessage = {
8965 /**
8966 * Who wrote it.
8967 */
8968 role: 'user' | 'assistant';
8969 /**
8970 * Its text blocks joined; '' when it has none.
8971 */
8972 text: string;
8973 /**
8974 * The tool_use blocks of an assistant message, each with its outcome
8975 * (`result`, `text`, `isError`) once the transcript holds it.
8976 */
8977 toolUses: ToolUseSummary[];
8978 /**
8979 * The tool_result blocks of a user message: `{ tool_use_id, text, isError,
8980 * result }`.
8981 */
8982 toolResults?: ToolResultSummary[];
8983 /**
8984 * An opaque token the engine stamps on a message it hands a
8985 * `session.compact` hook, so a list handed back maps to its own messages.
8986 *
8987 * Absent on `$.session.messages()` and on a message a hook built.
8988 */
8989 handle?: string;
8990 };
8991
8992 /**
8993 * One rate-limit window as the rate-limit notices read it.
8994 */
8995 export type SessionRateLimit = {
8996 /**
8997 * Which window: `five_hour`, `seven_day`, or a Claude gateway's
8998 * `spend_limit`.
8999 */
9000 kind: string;
9001 /**
9002 * How much of the window is used, 0 to 100 with at most one decimal:
9003 * 23.5, or 7, never 7.000000000000001; past 100 on an exceeded spend limit.
9004 */
9005 percentUsed: number;
9006 /**
9007 * When the window resets, as an ISO 8601 timestamp.
9008 */
9009 resetsAt?: string;
9010 };
9011
9012 /**
9013 * An external-event wake the delivery's text parsed as (a GitHub relay
9014 * event, a signal's notice): the envelope's attributes and its JSON body.
9015 */
9016 export type SessionReceiveEvent = {
9017 /**
9018 * The producing service (`github`).
9019 */
9020 source: string;
9021 /**
9022 * The event's discriminator (`pull_request.closed`, `check_suite`).
9023 */
9024 kind: string;
9025 /**
9026 * The envelope's JSON body (`{ pr: "acme/app#12", outcome: "merged" }`).
9027 */
9028 data: Record<string, unknown>;
9029 /**
9030 * The `data` keys whose values are free text a third party wrote (a
9031 * commenter's `author` and `comment`), as the producer marked them.
9032 *
9033 * Empty when none; the server asserts every other key's value, not these.
9034 */
9035 untrustedKeys: readonly string[];
9036 };
9037
9038 /**
9039 * The input of `session.receive`: one inbound delivery (a relay's event, a
9040 * peer's message, a Remote Control prompt), sanitized, before it is queued.
9041 */
9042 export type SessionReceiveInput = {
9043 /**
9044 * Where the delivery came from, as the bridge classified it; the key a
9045 * matcher narrows on. `next(e)` passes it on as received.
9046 */
9047 origin: SessionReceiveOrigin;
9048 /**
9049 * The delivery's body as the model would read it (a content-block
9050 * delivery's text blocks, joined).
9051 */
9052 text: string;
9053 /**
9054 * The external-event wake the text parsed as (`source` `github` for a
9055 * subscribed pull request's event); passed on as received.
9056 *
9057 * Present only for a delivery the server itself rendered as a wake (a
9058 * webhook relay, the session inbox), by its asserted origin; anyone else's
9059 * wake-shaped text stays `text`. Its `untrustedKeys` name third-party text.
9060 */
9061 event?: SessionReceiveEvent;
9062 };
9063
9064 /**
9065 * Where an inbound delivery came from, as the bridge classified it from the
9066 * server's stamps: `prompt.submit`'s `e.origin`, less what never arrives.
9067 */
9068 export type SessionReceiveOrigin = {
9069 /**
9070 * `bridge` the user's own from a Remote Control client; `peer` another
9071 * session; `unclassified` one the bridge could not place.
9072 *
9073 * `task-notification` a relay's event (a GitHub webhook) or a trigger;
9074 * `scheduled-trigger` a routine; `peer-send-message` another session's
9075 * SendMessage; `projects-relay` and `slack-ping` as at `prompt.submit`.
9076 */
9077 kind: 'bridge' | 'task-notification' | 'scheduled-trigger' | 'peer' | 'peer-send-message' | 'projects-relay' | 'slack-ping' | 'unclassified';
9078 };
9079
9080 /**
9081 * What a `session.receive` hook returns and what `next(e)` resolves to: the
9082 * delivery that was queued, `{ text }`, or `{ consumed: reason }`.
9083 *
9084 * `next(e)` resolves once the delivery is queued; a hook answering without
9085 * `next` queues nothing.
9086 */
9087 export type SessionReceiveResult = {
9088 /**
9089 * The body the delivery was queued with; from core, `e.text` as it
9090 * arrived at the bottom.
9091 *
9092 * A rewrite passes it down, `next({ ...e, text })`.
9093 */
9094 text: string;
9095 consumed?: undefined;
9096 } | {
9097 /**
9098 * Takes the delivery, answered without `next`: it is not queued, not
9099 * written to the transcript and never reaches the model.
9100 *
9101 * The reason is logged, the plugin named.
9102 */
9103 consumed: string;
9104 text?: undefined;
9105 };
9106
9107 /**
9108 * What `$.session.repo()` answers: the repository's root and its origin remote,
9109 * when the session is in one.
9110 */
9111 export type SessionRepo = {
9112 /**
9113 * The repository's root, absolute: the main working tree's for a worktree.
9114 */
9115 root: string;
9116 /**
9117 * The `origin` remote's URL as git has it (push URL preferred), or null when
9118 * the repository has none.
9119 */
9120 remote: string | null;
9121 /**
9122 * Whether the remote is one of the repositories this build treats as its
9123 * own; false in a build that has none or when the remote is unrecognized.
9124 *
9125 * The engine matches the build's own list of repositories with its
9126 * hardened remote parser. A plugin reads this to behave differently in a
9127 * public repository; which repositories are the build's is its to say.
9128 */
9129 internal: boolean;
9130 /**
9131 * The repository the allowlist matched, as `owner/name`; null when
9132 * `internal` is false.
9133 *
9134 * A working copy without a remote that the engine still recognises is
9135 * named by its own checkout configuration; a remote's name is its path.
9136 */
9137 name: string | null;
9138 };
9139
9140 /**
9141 * How to come back to the session that ended: what `claude --resume` takes.
9142 */
9143 export type SessionResume = {
9144 /**
9145 * What `claude --resume <id>` takes, the ending session's own.
9146 *
9147 * It resumes a session that wrote a transcript: one that never ran a
9148 * prompt, or ran with persistence off, left nothing under this id.
9149 */
9150 id: string;
9151 };
9152
9153 type SessionStartHookInput = BaseHookInput & {
9154 hook_event_name: 'SessionStart';
9155 source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork';
9156 agent_type?: string;
9157 model?: string;
9158 session_title?: string;
9159 /**
9160 * resume/fork: seconds since the resumed transcript's last assistant response
9161 */
9162 seconds_since_last_response?: number;
9163 /**
9164 * resume/fork: the resumed transcript's last response input + cache_read + cache_creation + output tokens (for a server-side tool loop, its last iteration's window, not the summed totals)
9165 */
9166 context_tokens?: number;
9167 /**
9168 * resume/fork: seconds_since_last_response exceeds the prompt-cache TTL, so the first request re-caches context_tokens
9169 */
9170 prompt_cache_likely_expired?: boolean;
9171 /**
9172 * resume/fork: estimated cost of re-caching context_tokens on the session model - the managed modelPricing when set, otherwise list price; excludes the response
9173 */
9174 estimated_cache_write_usd?: number;
9175 };
9176
9177 /**
9178 * The input of `session.start`: the session the process starts with, read the
9179 * way `$.session` reads it at that moment.
9180 */
9181 export type SessionStartInput = {
9182 /**
9183 * The directory the session runs in, absolute (`$.session.cwd()`).
9184 */
9185 cwd: string;
9186 /**
9187 * Where the session draws at start (`$.session.surfaces()[0]`): `terminal`
9188 * under the REPL; null for a `-p` run or the SDK, which draw nowhere yet.
9189 */
9190 surface: RenderSurface | null;
9191 /**
9192 * Whether a person is at the prompt: true under the REPL, false for a `-p`
9193 * run or the SDK.
9194 */
9195 isInteractive: boolean;
9196 };
9197
9198 /**
9199 * What a `session.start` hook returns and what `next(e)` resolves to:
9200 * `{ cwd }`, echoed by core; a hook's own value does not change the session.
9201 */
9202 export type SessionStartResult = {
9203 cwd: string;
9204 };
9205
9206 /**
9207 * What `$.session.usage()` answers: the context window's fill, the account's
9208 * rate-limit windows and the session's cost, as the status line has them.
9209 *
9210 * A figure the engine does not have is left out, never zeroed: `rateLimits`
9211 * is empty off a subscription, `cost` absent where the host keeps no ledger.
9212 */
9213 export type SessionUsage = {
9214 /**
9215 * The live context window: the status line's `context_window` figures.
9216 */
9217 context: SessionContextUsage;
9218 /**
9219 * The rate-limit windows the last API response reported (`five_hour`,
9220 * `seven_day`, a gateway's `spend_limit`); empty when none has a reading.
9221 */
9222 rateLimits: SessionRateLimit[];
9223 /**
9224 * What the session has cost so far, as /cost totals it; absent only where
9225 * the host keeps no cost ledger (the CLI always has one).
9226 */
9227 cost?: SessionCost;
9228 };
9229
9230 /**
9231 * What `$.session.usage(args)` takes: nothing for the status line's figures
9232 * alone; `breakdown` to have the window broken down as /context breaks it.
9233 */
9234 export type SessionUsageArgs = {
9235 /**
9236 * Asks for `context.breakdown` and says how it is counted
9237 * (ContextBreakdownDetail); absent, none is computed and the call is free.
9238 *
9239 * `full` sends one token-count request per tool and memory file, as
9240 * /context does; `summary` estimates locally and sends none.
9241 */
9242 breakdown?: ContextBreakdownDetail;
9243 /**
9244 * The width the breakdown's grid will be drawn in, in terminal columns;
9245 * absent, the full-width grid. Read only with `breakdown`.
9246 *
9247 * Under 80 the grid is the narrow one /context draws there, 5 wide. A thin
9248 * client's breakdown is the remote workspace's, whose grid ignores this.
9249 */
9250 columns?: number;
9251 };
9252
9253 /**
9254 * What `$.session.version()` answers: the version of the engine the session
9255 * runs on, the release that version is built from, and when it was built.
9256 *
9257 * The three are what the engine's own analytics rows carry as `version`,
9258 * `version_base` and `build_time`, so a row a plugin sends and a row the
9259 * engine sends from the same binary agree.
9260 */
9261 export type SessionVersion = {
9262 /**
9263 * The engine's full version, as `claude --version` prints it: a release's
9264 * (`2.1.280`) or a development build's, which adds the build's date, time
9265 * and commit (`2.1.280-dev.20260920.t101500.sha1a2b3c4`).
9266 */
9267 version: string;
9268 /**
9269 * The release the version is built from, its semantic core and channel:
9270 * `2.1.280` for that release, `2.1.280-dev` for a development build of it.
9271 * Absent when the version is not spelled as a release.
9272 */
9273 base?: string;
9274 /**
9275 * When the binary was built, an ISO 8601 timestamp
9276 * (`2026-09-20T10:15:00Z`). Absent in a run from source that stamps none.
9277 */
9278 builtAt?: string;
9279 };
9280
9281 /**
9282 * What `$.settings.read` answers: an object keyed as a settings.json is
9283 * (`permissions`, `env`, `hooks`, `model`, `enabledPlugins`, ...).
9284 *
9285 * Each key is as https://code.claude.com/docs/en/settings documents it and
9286 * https://json.schemastore.org/claude-code-settings.json types it. A
9287 * snapshot in plain data: a write to it changes nothing the engine reads.
9288 */
9289 export type Settings = Readonly<Record<string, unknown>>;
9290
9291 /**
9292 * What `$.settings.read(args)` takes.
9293 */
9294 export type SettingsReadArgs = {
9295 /**
9296 * The one source read, as loaded; absent, the settings merged over every
9297 * source, as the engine runs under them.
9298 */
9299 source?: SettingsSource;
9300 };
9301
9302 /**
9303 * One source of settings by the name a plugin gives it, lowest precedence
9304 * first; the engine's own name is the same word with `Settings` appended.
9305 *
9306 * `user` is ~/.claude/settings.json, `project` .claude/settings.json,
9307 * `local` .claude/settings.local.json, `flag` what `--settings` and the
9308 * SDK's inline settings carry, and `policy` the managed settings, every
9309 * managed tier merged.
9310 */
9311 export type SettingsSource = 'user' | 'project' | 'local' | 'flag' | 'policy';
9312
9313 type SetupHookInput = BaseHookInput & {
9314 hook_event_name: 'Setup';
9315 trigger: 'init' | 'maintenance';
9316 };
9317
9318 /**
9319 * Where a site's window sits over the tree a hook drew in it (a pane's body,
9320 * the band): the engine's to move (the person scrolls), the plugin's to read.
9321 */
9322 export type SiteScroll = {
9323 /**
9324 * The first row of the tree the window shows; 0 at the top. Read-only.
9325 */
9326 offset: number;
9327 /**
9328 * How many rows of the tree the window shows at once: the rows the
9329 * surface gave the body. Read-only.
9330 */
9331 bodyRows: number;
9332 };
9333
9334 /**
9335 * Which transcript the person has on screen where a site draws: the main
9336 * conversation's, or one agent's, opened from the tasks list.
9337 *
9338 * The person's to switch, the plugin's to read: a switch re-runs the site's
9339 * hooks with the new view, the site itself staying where it is.
9340 */
9341 export type SiteView = {
9342 /**
9343 * The agent whose transcript is in view: the `id` `$.agent.list()` gives
9344 * it, the `agentId` its `turn.step` and `tool.call` events carry.
9345 *
9346 * Absent while the main conversation is in view. Read-only.
9347 */
9348 agentId?: string;
9349 };
9350
9351 /**
9352 * The input of `skill.prompt`: one skill's prompt, at the moment the engine
9353 * expanded it for the model.
9354 *
9355 * Typed as `/name`, called through the Skill tool, or preloaded into a
9356 * subagent: the same event at each.
9357 */
9358 export type SkillPromptInput = {
9359 /**
9360 * Which skill (`commit`); the key a matcher narrows on.
9361 */
9362 skill: string;
9363 /**
9364 * The prompt's text as the skill computed it (its text blocks, joined).
9365 */
9366 text: string;
9367 };
9368
9369 /**
9370 * What a `skill.prompt` hook returns: the text the model reads for that
9371 * skill.
9372 */
9373 export type SkillPromptResult = {
9374 text: string;
9375 };
9376
9377 /**
9378 * Options of `$.clock.sleep`.
9379 */
9380 export type SleepOptions = {
9381 /**
9382 * Aborting it rejects the sleep at once.
9383 */
9384 signal?: AbortSignal;
9385 };
9386
9387 /**
9388 * Options of `$.audio.speak`.
9389 */
9390 export type SpeakOptions = {
9391 /**
9392 * The system voice's exact name as the platform lists it (`Samantha`, or the
9393 * name of a voice you installed). Absent: the synthesizer's default voice.
9394 */
9395 voice?: string;
9396 };
9397
9398 /**
9399 * The argument of `$.audio.speak(text, options)` as the event carries it.
9400 */
9401 type SpeakRequest = SpeakOptions & {
9402 /**
9403 * What to say, as plain text, of at most 4096 characters.
9404 */
9405 text: string;
9406 };
9407
9408 /**
9409 * What `$.audio.speak` resolves with once the utterance has ended.
9410 */
9411 export type SpeakResult = {
9412 /**
9413 * Which synthesizer spoke: `system`, the platform's own (`say` on macOS).
9414 */
9415 via: 'system';
9416 };
9417
9418 /**
9419 * `next` in a `*` hook: the set of events is open at runtime, so `e` is
9420 * `unknown` until `next.is(pattern, e)` narrows it to events it knows.
9421 *
9422 * The callable is an overload per known event (OrderedOverloads), then
9423 * `(e: unknown) => Promise<unknown>` last: `next(e)` with `e` still unknown
9424 * resolves to `unknown`.
9425 */
9426 export type StarNext = OrderedOverloads<EventName> & {
9427 (e: unknown): Promise<unknown>;
9428 /**
9429 * Continues this dispatch at a tier, as Next's `to` (a managed hook's):
9430 * `e` still unknown resolves to `unknown`.
9431 */
9432 readonly to: (e: unknown, tier: TargetTier) => Promise<unknown>;
9433 readonly signal: AbortSignal;
9434 readonly is: <M extends Pattern>(pattern: M, e: unknown) => e is Frozen<Args<Selected<M>>>;
9435 readonly event: EventName;
9436 readonly origin: Origin;
9437 readonly trace: readonly TraceEntry<EventName, unknown, unknown>[];
9438 readonly budget: NextBudget;
9439 };
9440
9441 type StopFailureHookInput = BaseHookInput & {
9442 hook_event_name: 'StopFailure';
9443 error: SDKAssistantMessageError;
9444 error_details?: string;
9445 last_assistant_message?: string;
9446 };
9447
9448 type StopHookInput = BaseHookInput & {
9449 hook_event_name: 'Stop';
9450 stop_hook_active: boolean;
9451 /**
9452 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
9453 */
9454 last_assistant_message?: string;
9455 /**
9456 * In-flight background work (running/pending + backgrounded) registered in this session. Lets hooks distinguish "session is done" from "session is paused waiting for background work to wake it". Empty array when nothing is in flight.
9457 */
9458 background_tasks?: BackgroundTaskSummary[];
9459 /**
9460 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
9461 */
9462 session_crons?: SessionCronSummary[];
9463 };
9464
9465 /**
9466 * The hook a streaming event takes: `async function* ($, e, next) {}`,
9467 * yielding the event's chunks and returning its result.
9468 *
9469 * `return yield* next(e)` passes; `for await (const c of next(e)) yield
9470 * f(c)` transforms; yielding without `next` answers alone. A chunk yielded
9471 * stays: a hook that fails mid-stream is left, the rest from beneath it.
9472 *
9473 * @example on('turn.step', async function* ($, e, next) {
9474 * const r = yield* next(e); return { ...r } })
9475 */
9476 export type StreamHook<N extends StreamingEventName> = ($: EngineInterface, e: Frozen<Args<N>>, next: StreamNext<N>) => StreamHookBody<Chunk<N>, EventResult<N>>;
9477
9478 /**
9479 * What a hook on a streaming event evaluates to: the async generator an
9480 * `async function*` makes, yielding `C` and returning `R` or nothing.
9481 *
9482 * Returning nothing lets its last `next(e)`'s result stand. A plain
9483 * function is a type error here even when it returns `next(e)`: the hook
9484 * is the generator, not a function that hands one back.
9485 */
9486 export type StreamHookBody<C, R> = AsyncGenerator<C, R | void> & {
9487 /**
9488 * Absent on a generator; present on `next(e)`, which is not a hook body.
9489 */
9490 readonly result?: never;
9491 };
9492
9493 /**
9494 * The events that stream: their hooks are async generators, `next(e)` is
9495 * the stream of everything beneath, and the result is what it returns.
9496 *
9497 * `turn.step` alone: the model's response arrives in pieces, and a hook
9498 * that saw it whole could not change what had already been shown.
9499 */
9500 export type StreamingEventName = 'turn.step';
9501
9502 /**
9503 * The rest of the chain as a hook on a streaming event receives it: Next,
9504 * except that `next(e)` is the stream beneath (HookStream), not a promise.
9505 *
9506 * Each call opens a fresh stream; for `turn.step` each is a model request,
9507 * so a hook that calls it twice makes two. Not calling it yields the hook's
9508 * own chunks and returns its own result, and nothing beneath runs.
9509 *
9510 * @template S what `next.is(pattern, e)` narrows `e` to, as Next's
9511 * @see HookBudget `ms`: the hook's budget counts its own code, never a wait
9512 * at a `yield` or on this stream, however long the response beneath takes
9513 */
9514 export type StreamNext<N extends StreamingEventName = StreamingEventName, E = Args<N>, O = NextResult<N>, S extends {
9515 [K in N]?: unknown;
9516 } = {
9517 [K in N]: Args<K>;
9518 }> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin' | 'budget'> & {
9519 (e: E): HookStream<Chunk<N>, O>;
9520 /**
9521 * Continues this dispatch at a tier, as Next's `to`: the stream beneath
9522 * with the links between this hook's tier and that one skipped.
9523 */
9524 readonly to: (e: E, tier: TargetTier) => HookStream<Chunk<N>, O>;
9525 /**
9526 * What settled beneath on the latest `next()` stream, as Next's; a
9527 * streaming link's entry counts the chunks it yielded up (`chunks`).
9528 */
9529 readonly trace: readonly TraceEntry<N, E, O>[];
9530 };
9531
9532 /**
9533 * The shape a `Box` and a `Text` share in a render tree: allowlisted props,
9534 * an optional `hover`, the group stamp a `hover.scope` earns, and children.
9535 *
9536 * `Tag` is which of the two; `Hover` is that element's hover props. Every
9537 * surface draws both: Ink's Box and Text on the terminal, a flex div and a
9538 * styled span on the desktop.
9539 */
9540 type StyledElement<Tag extends 'Box' | 'Text', Hover> = {
9541 type: Tag;
9542 /**
9543 * A Box's layout, position, spacing and border props and the `key` that
9544 * makes it a hover scope; a Text's colors and styles. Others are refused.
9545 */
9546 props?: Record<string, string | number | boolean>;
9547 /**
9548 * Style overrides the surface applies while the pointer is over the
9549 * nearest keyed Box, or over any member of the group `scope` names.
9550 *
9551 * Plain data, no hook. Nothing that moves a sibling: `borderStyle`
9552 * restyles a border the Box has, `display` only reveals a Box drawn
9553 * `"none"` (under a keyed Box or in a scope), an offset moves a placed Box.
9554 */
9555 hover?: Hover;
9556 /**
9557 * Whose group `hover.scope` names; absent without a `scope`.
9558 */
9559 group?: PluginStamp;
9560 /**
9561 * In order: a Box holds elements and strings (core wraps each string in
9562 * a Text); a Text holds strings and inline elements, never an engine node.
9563 */
9564 children?: RenderNode[];
9565 };
9566
9567 type SubagentStartHookInput = BaseHookInput & {
9568 hook_event_name: 'SubagentStart';
9569 agent_id: string;
9570 agent_type: string;
9571 };
9572
9573 type SubagentStopHookInput = BaseHookInput & {
9574 hook_event_name: 'SubagentStop';
9575 stop_hook_active: boolean;
9576 agent_id: string;
9577 agent_transcript_path: string;
9578 agent_type: string;
9579 /**
9580 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
9581 */
9582 last_assistant_message?: string;
9583 /**
9584 * In-flight background work (running/pending + backgrounded) registered in this session. Lets hooks distinguish "session is done" from "session is paused waiting for background work to wake it". Empty array when nothing is in flight.
9585 */
9586 background_tasks?: BackgroundTaskSummary[];
9587 /**
9588 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
9589 */
9590 session_crons?: SessionCronSummary[];
9591 };
9592
9593 /**
9594 * The props of `Svg`, the remote surfaces' vector leaf: the markup is the
9595 * element's data, as a string is a Text's, drawn isolated.
9596 *
9597 * A leaf: no children. The surface never lets the markup reach the page
9598 * (the engine bounds it; the desktop and the editor draw it as an image, or
9599 * in a sandboxed frame when `isInteractive`; the mobile app in a web view).
9600 */
9601 export type SvgProps = {
9602 /**
9603 * The SVG document, `<svg ...>...</svg>`, at most 131072 characters.
9604 */
9605 source: string;
9606 /**
9607 * What the drawing says, for a reader that cannot see it; required, since
9608 * a surface without the element draws nothing else of it.
9609 */
9610 alt: string;
9611 /**
9612 * CSS pixels; absent, the box takes the markup's own width up to the slot.
9613 */
9614 width?: number;
9615 /**
9616 * CSS pixels; absent, the markup's own height at the drawn width.
9617 */
9618 height?: number;
9619 /**
9620 * `true` draws the SVG in a script-less sandboxed frame so hover, CSS
9621 * `:hover`, SMIL animation and `<title>` tooltips work; absent, an image.
9622 *
9623 * It never enables script or event-handler attributes (the frame has no
9624 * allow-scripts and the scrub strips them); presses that other plugins
9625 * should observe go on an enclosing element.
9626 */
9627 isInteractive?: boolean;
9628 };
9629
9630 /**
9631 * The keys of `I` a matcher may select variants by: literal-valued in every
9632 * variant, and one literal per variant (IsDiscriminant).
9633 */
9634 type TagKeys<I> = {
9635 [K in MatcherKeys<I>]: IsLiteralValued<MatcherValueOf<I, K>> extends true ? IsDiscriminant<I, K> extends true ? K : never : never;
9636 }[MatcherKeys<I>];
9637
9638 /**
9639 * A tier `next.to(e, tier)` may name: one a floor can reach past a tier of
9640 * less authority to, so never `prepend` or `user`, which nothing skips to.
9641 */
9642 export type TargetTier = Exclude<Tier, 'prepend' | 'user'>;
9643
9644 type TaskCompletedHookInput = BaseHookInput & {
9645 hook_event_name: 'TaskCompleted';
9646 task_id: string;
9647 task_subject: string;
9648 task_description?: string;
9649 teammate_name?: string;
9650 /**
9651 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9652 */
9653 team_name?: string;
9654 };
9655
9656 type TaskCreatedHookInput = BaseHookInput & {
9657 hook_event_name: 'TaskCreated';
9658 task_id: string;
9659 task_subject: string;
9660 task_description?: string;
9661 teammate_name?: string;
9662 /**
9663 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9664 */
9665 team_name?: string;
9666 };
9667
9668 type TeammateIdleHookInput = BaseHookInput & {
9669 hook_event_name: 'TeammateIdle';
9670 teammate_name: string;
9671 /**
9672 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9673 */
9674 team_name: string;
9675 };
9676
9677 /**
9678 * The `Text` props a `hover` may override (its colors and styles, not its
9679 * wrapping) and `scope`, the hover group it joins; a `Button`'s label too.
9680 */
9681 export type TextHoverProps = {
9682 /**
9683 * Names a hover group of this plugin's: every element it draws with the
9684 * same `scope`, in any site on the surface, lights while any is hovered.
9685 *
9686 * Another plugin's elements under the same string are a different group.
9687 * One to 64 characters, no control characters; no keyed Box needed. On the
9688 * terminal a Text nested in a Text follows its group but cannot heat it.
9689 */
9690 scope?: string;
9691 color?: string;
9692 backgroundColor?: string;
9693 dimColor?: boolean;
9694 bold?: boolean;
9695 italic?: boolean;
9696 underline?: boolean;
9697 strikethrough?: boolean;
9698 inverse?: boolean;
9699 };
9700
9701 /**
9702 * The props of `Text`: the color and style props of Ink's Text a tree may
9703 * set. Colors are a theme key or a raw color.
9704 */
9705 export type TextProps = {
9706 /**
9707 * Style overrides applied by the surface while the pointer is over the
9708 * nearest enclosing keyed `Box`, or, given a `scope`, over its group.
9709 *
9710 * No hook runs and nothing crosses to the plugin. Refused outside a keyed
9711 * Box unless it names a `scope`.
9712 */
9713 hover?: TextHoverProps;
9714 color?: string;
9715 backgroundColor?: string;
9716 dimColor?: boolean;
9717 bold?: boolean;
9718 italic?: boolean;
9719 underline?: boolean;
9720 strikethrough?: boolean;
9721 inverse?: boolean;
9722 wrap?: 'wrap' | 'end' | 'middle' | 'truncate' | 'truncate-start' | 'truncate-middle' | 'truncate-end';
9723 };
9724
9725 /**
9726 * One of the chain's five tiers (TIERS), outermost first; on every
9727 * `next.trace` entry, and what `next.to(e, tier)` names.
9728 *
9729 * `prepend` and `append` are the managed plugins an administrator lists,
9730 * `user` everything a person installs, `builtin` the plugins bundled in the
9731 * binary, `core` the engine's innermost link.
9732 */
9733 export type Tier = (typeof TIERS)[number];
9734
9735 /**
9736 * The chain's five tiers, outermost first: earlier is outer is more
9737 * authority, and same-event hooks nest in this order and no other way.
9738 *
9739 * The managed plugins an administrator prepends, everything a person
9740 * installs, the managed plugins appended, the plugins bundled in the binary,
9741 * the engine's innermost link; a built-in's `$` calls still raise everywhere.
9742 */
9743 const TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
9744
9745 /**
9746 * A pending timer from `$.clock.after` / `$.clock.every`.
9747 */
9748 export type Timer = {
9749 /**
9750 * Stops it; a stopped timer never fires again.
9751 */
9752 cancel: () => void;
9753 };
9754
9755 /**
9756 * A timer on `$.clock` (`after`, `every`): `fn` runs after `ms` milliseconds,
9757 * once or until `cancel()`.
9758 */
9759 export type TimerCall = (ms: number, fn: () => void) => Timer;
9760
9761 /**
9762 * Options of `$.ui.toast`.
9763 */
9764 export type ToastOptions = {
9765 /**
9766 * How long the line stays, in milliseconds; default 4000.
9767 */
9768 timeoutMs?: number;
9769 };
9770
9771 /**
9772 * `tool.call`'s input as the call takes it: `tool_use_id` and `agentId` may
9773 * ride along (a hook passing its event's input on) and are dropped.
9774 *
9775 * The run gets its own id and runs in the session's loop.
9776 */
9777 export type ToolCallArgs = ToolCallEnvelope extends infer I ? I extends ToolCallEnvelope ? Omit<I, 'tool_use_id'> & ToolCallReserved<I['tool']> : never : never;
9778
9779 /**
9780 * The envelope the two tool events share: the tool, the id of this call, and
9781 * the tool's arguments spread beside them (`e.command` for Bash).
9782 *
9783 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
9784 * is a string and a rewrite is checked against Bash's schema. The `e` of
9785 * `classic.PreToolUse` exactly; `tool.call`'s adds the loop (ToolCallInput).
9786 */
9787 export type ToolCallEnvelope = BuiltinToolCallInput | McpToolCallInput;
9788
9789 /**
9790 * The input of `tool.call`: the tool, the id of this call, the tool's
9791 * arguments beside them (`e.command` for Bash), and `agentId` in a subagent.
9792 *
9793 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
9794 * is a string and a rewrite is checked against Bash's schema. `tool`,
9795 * `tool_use_id` and `agentId` are reserved: a rewrite of any is refused.
9796 */
9797 export type ToolCallInput = ToolCallEnvelope & AgentLoop;
9798
9799 /**
9800 * `$.tool.call(input)`: resolves with `result` typed for the tool `input`
9801 * names (ToolCallResult), or loosely for an input that names none literally.
9802 */
9803 type ToolCallOverloads = {
9804 <T extends string>(input: ToolCallArgs & ToolNamed<T>): Promise<ToolCallResult<T>>;
9805 (input: ToolCallArgs): Promise<ToolCallResult>;
9806 };
9807
9808 /**
9809 * The keys `tool.call`'s input carries beside the tool's own arguments, none
9810 * of which the tool sees (the engine strips them before the tool runs).
9811 *
9812 * `consent` is the person's own words for the press that raised the call
9813 * (`The user pressed "1: Yes" on ...`): the run's context carries it as a human
9814 * turn, which the permission path reads as the user's request.
9815 */
9816 export type ToolCallReserved<T> = {
9817 tool: T;
9818 tool_use_id?: string;
9819 consent?: string;
9820 };
9821
9822 /**
9823 * What a `tool.call` hook returns and what `next(e)` and `$.tool.call(input)`
9824 * resolve to: the tool's result (`{ result, context? }`) or `{ deny }`.
9825 *
9826 * From core the result is `{ ref, result, text }` or, when the tool reported
9827 * an error, `{ ref, result, text, isError }`; `ref` names core's messages.
9828 *
9829 * @template Name the tool the call went to, typing `result` per built-in
9830 * tool (BuiltinToolResults) once `e.tool` is narrowed; else `unknown`
9831 */
9832 export type ToolCallResult<Name extends string = string> = {
9833 /**
9834 * Refuses the call: the model receives the text as an error result.
9835 * Absent when the call was answered.
9836 */
9837 deny: string;
9838 result?: undefined;
9839 context?: undefined;
9840 ref?: undefined;
9841 text?: undefined;
9842 isError?: undefined;
9843 } | {
9844 /**
9845 * The tool's output: from core the tool's record, typed per built-in
9846 * tool once `e.tool` and `isError` are narrowed; from a hook, its own.
9847 *
9848 * Core validates a hook's answer against the tool's output schema when
9849 * it has one, maps it for the model with the tool's own mapper, and
9850 * records it in the transcript as the tool's result. Absent on a deny.
9851 */
9852 result: ToolResultOf<Name>;
9853 /**
9854 * What the model reads after the tool's result and the user never
9855 * sees. From core, none.
9856 *
9857 * One reminder, as a PostToolUse hook's is, after the managed tier's
9858 * review; none on a plugin's own `$.tool.call`. Kept whole from `next`,
9859 * none empty, any length: past 100,000 (200,000 together) head + path.
9860 */
9861 context?: readonly string[];
9862 /**
9863 * Set by core on what `next(e)` resolves to: names the messages core
9864 * produced for the call (they stay on the host side).
9865 *
9866 * A hook that returns the object it got makes core use them verbatim.
9867 * Absent on a hook's own `{ result }` and on a deny.
9868 */
9869 ref?: number;
9870 /**
9871 * Set by core: the result as the model reads it (text blocks joined),
9872 * present whatever the tool, where `result`'s shape varies per tool.
9873 *
9874 * Absent on a hook's own `{ result }`.
9875 */
9876 text?: string;
9877 isError?: undefined;
9878 deny?: undefined;
9879 } | {
9880 /**
9881 * Set by core, present only when the tool reported an error (it threw,
9882 * was interrupted, or answered an error): `text` is what the model read.
9883 */
9884 isError: true;
9885 /**
9886 * What the transcript stored for the errored call: the error text, or
9887 * undefined when nothing was stored; never the tool's typed record.
9888 */
9889 result: unknown;
9890 /**
9891 * The error as the model reads it.
9892 */
9893 text?: string;
9894 /**
9895 * As on an answered result: names the messages core produced.
9896 */
9897 ref?: number;
9898 /**
9899 * As on an answered result.
9900 */
9901 context?: readonly string[];
9902 deny?: undefined;
9903 };
9904
9905 /**
9906 * `tool.check`'s input as `$.tool.check` takes it: the tool and its
9907 * arguments; `tool_use_id` is the engine's to set, never a query's.
9908 */
9909 type ToolCheckArgs = Pick<ToolCheckInput, 'tool' | 'input'>;
9910
9911 /**
9912 * The verdict of `tool.check`: run the tool, put it to the mode's decider
9913 * (the dialog, the auto-mode classifier, a headless host), or refuse it.
9914 */
9915 type ToolCheckDecision = 'allow' | 'ask' | 'deny';
9916
9917 /**
9918 * The input of `tool.check`: the tool, its arguments, and the call's id when
9919 * the engine is deciding a real call.
9920 *
9921 * All three are the question's identity and are pinned: a hook decides
9922 * about this call, it does not change it (`tool.call` rewrites a call).
9923 */
9924 type ToolCheckInput = {
9925 /**
9926 * As the model names it (`Bash`, `mcp__server__tool`); the key a matcher
9927 * narrows on.
9928 */
9929 tool: string;
9930 /**
9931 * The tool's arguments as the permission decision reads them
9932 * (`{ command }` for Bash, `{ file_path, ... }` for the file tools).
9933 */
9934 input: unknown;
9935 /**
9936 * The call being decided, on a real call only; absent on a query.
9937 *
9938 * `next.origin` names who raised it: `{ plugin: 'engine', tier: 'core' }`
9939 * for the model's own call, the plugin for its `$.tool.call` or its query.
9940 */
9941 tool_use_id?: string;
9942 };
9943
9944 /**
9945 * What a `tool.check` hook returns and what `next(e)` resolves to: the
9946 * verdict, why, and the settings rule behind it when one decided.
9947 *
9948 * From core, the engine's declarative decision for the session's mode and
9949 * rules. A hook may answer any verdict in either direction; the last word up
9950 * the chain is the decision.
9951 */
9952 type ToolCheckResult = {
9953 /**
9954 * `allow` runs the tool; `ask` puts it to the mode's decider; `deny`
9955 * refuses it, the reason the model's error.
9956 */
9957 decision: ToolCheckDecision;
9958 /**
9959 * Why, in a sentence: from core the rule or check that decided; from a
9960 * hook, what the model reads on a deny and the dialog shows on an ask.
9961 */
9962 reason?: string;
9963 /**
9964 * The settings rule that decided, as written (`Bash(git push:*)`).
9965 *
9966 * Absent for a mode or a tool's own check.
9967 */
9968 rule?: string;
9969 };
9970
9971 /**
9972 * Where a `tool.describe` answer places the tool: `true` behind ToolSearch
9973 * (its schema loads when the model asks for it), `false` in the prompt's list.
9974 *
9975 * Left out of an answer, the placement beneath stands.
9976 */
9977 export type ToolDeferral = boolean;
9978
9979 /**
9980 * The input of `tool.describe`: one tool's description, at the moment the
9981 * engine first renders the tool's schema for the model.
9982 */
9983 export type ToolDescribeInput = {
9984 /**
9985 * As the model sees the name (`Bash`, `mcp__server__tool`); the key a
9986 * matcher narrows on.
9987 */
9988 tool: string;
9989 /**
9990 * The tool's description as it computed it.
9991 */
9992 description: string;
9993 /**
9994 * Present, and true, when the engine lists the tool behind ToolSearch (its
9995 * schema loads when the model asks for it by name); absent for one listed.
9996 *
9997 * By the engine's rule an MCP server's tool, or one that asks to be,
9998 * unless a rule keeps it in front.
9999 */
10000 isDeferred?: true;
10001 /**
10002 * Who provides this tool: the plugin and its tier; `{ plugin: "engine",
10003 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
10004 *
10005 * A configured MCP server's tool is `mcp:<server>`, in `prepend` when the
10006 * policy settings source configures the server, else `user`.
10007 */
10008 provider: Origin;
10009 };
10010
10011 /**
10012 * What a `tool.describe` hook returns: the description the model sees for that
10013 * tool and, when the hook moves it, where the tool waits (ToolDeferral).
10014 *
10015 * `{ description }` alone, or `{ ...(await next(e)), description }`, changes
10016 * the text and keeps the engine's placement; `isDeferred: true` puts the tool
10017 * behind ToolSearch, `isDeferred: false` puts its schema in the prompt's list.
10018 */
10019 export type ToolDescribeResult = {
10020 description: string;
10021 isDeferred?: ToolDeferral;
10022 };
10023
10024 /**
10025 * `{ tool, tool_use_id, ...args }` as one flat object type, generic over
10026 * the tool name and its parsed arguments.
10027 */
10028 type ToolEnvelope<Name, Arguments> = {
10029 /**
10030 * The name of the tool being called (`Bash`, `mcp__<server>__<tool>`);
10031 * comparing it narrows `e`. Reserved: a rewrite of it is ignored by core.
10032 */
10033 tool: Name;
10034 /**
10035 * The tool_use block's id: the same at every event of the call and in
10036 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
10037 */
10038 tool_use_id: string;
10039 } & Arguments;
10040
10041 /**
10042 * One tool call of a ToolGroup, as `ui.render` sees it under `calls`.
10043 */
10044 export type ToolGroupCall = {
10045 /**
10046 * The id `tool.call` carried for this call (`e.tool_use_id` there), so a
10047 * hook that saw the call finds its row in the group. Read-only.
10048 *
10049 * Absent on a desktop host that predates it.
10050 */
10051 tool_use_id?: string;
10052 /**
10053 * Which one the call ran (`Bash`, `Read`, `Grep`, ...).
10054 */
10055 tool: string;
10056 /**
10057 * The call's input, as the model sent it.
10058 */
10059 input: unknown;
10060 /**
10061 * True while the call is still running.
10062 */
10063 isRunning: boolean;
10064 /**
10065 * True when the call ended in an error.
10066 */
10067 isErrored: boolean;
10068 /**
10069 * True when an abort ended the call, as on `ToolUse`.
10070 */
10071 isInterrupted: boolean;
10072 /**
10073 * As on `ToolUse`; undefined while the call runs.
10074 */
10075 output?: unknown;
10076 };
10077
10078 /**
10079 * One tool as `$.tool.list()` returns it.
10080 */
10081 export type ToolInfo = {
10082 /**
10083 * What the model calls it by.
10084 */
10085 name: string;
10086 /**
10087 * What it does, in the tool's own words (its description; a first sentence at
10088 * most for MCP tools without one).
10089 */
10090 description: string;
10091 /**
10092 * True for an MCP server's tool.
10093 */
10094 mcp: boolean;
10095 };
10096
10097 /**
10098 * `{ tool, tool_use_id, ...args }` as one flat object type.
10099 *
10100 * The docs of `tool` and `tool_use_id` live on the `keyof` operand: a mapped
10101 * type takes its properties' docs from there.
10102 */
10103 export type ToolInputOf<Name extends string, Arguments> = {
10104 [K in keyof ToolEnvelope<Name, Arguments>]: ToolEnvelope<Name, Arguments>[K];
10105 };
10106
10107 /**
10108 * An input that names its tool as the literal `T`: what `next` and
10109 * `$.tool.call` read to type the call's result per tool (NextResultFor).
10110 */
10111 type ToolNamed<T extends string> = {
10112 /**
10113 * The name of the tool being called (`Bash`).
10114 */
10115 readonly tool: T;
10116 };
10117
10118 /**
10119 * The structured result of the tool named `Name`: its BuiltinToolResults
10120 * entry for a built-in tool, else `unknown`.
10121 *
10122 * Agent's is its entry or an AgentCallRecord (what a plugin-raised call
10123 * answers). `unknown` covers an MCP tool, a name the results table lacks
10124 * (one merged into the inputs table alone too), and `Name` left at `string`.
10125 */
10126 export type ToolResultOf<Name extends string> = string extends Name ? unknown : Name extends keyof BuiltinToolResults & string ? BuiltinToolResults[Name] | (Name extends 'Agent' ? AgentCallRecord : never) : unknown;
10127
10128 /**
10129 * One tool_result block of a user message.
10130 */
10131 export type ToolResultSummary = {
10132 /**
10133 * The id of the call this result answers (`tool.call`'s `e.tool_use_id`).
10134 */
10135 tool_use_id: string;
10136 /**
10137 * The result as the model read it (text blocks joined).
10138 */
10139 text: string;
10140 /**
10141 * True when the tool reported an error.
10142 */
10143 isError: boolean;
10144 /**
10145 * What the transcript stored for the call: the tool's record on an answered
10146 * one (`tool.call`'s `result`), the error text when `isError`.
10147 *
10148 * Absent when nothing was stored. Headless (`-p`), a tool may store the
10149 * record less its bulk (Bash blanks `stdout`); `text` is what the model
10150 * read either way.
10151 */
10152 result?: unknown;
10153 };
10154
10155 /**
10156 * What `$.tool.register` takes.
10157 */
10158 export type ToolSpec = {
10159 /**
10160 * The tool's short name (letters, digits, `_`, `-`; up to 64); the model
10161 * calls it as `mcp__<plugin>__<name>`.
10162 */
10163 name: string;
10164 /**
10165 * What the tool does, for the model (and the person where tools are
10166 * listed); an unpaired surrogate half in it is drawn as U+FFFD.
10167 */
10168 description: string;
10169 /**
10170 * A JSON schema object for the input (`{ type: "object", properties,
10171 * required }`); default `{ type: "object" }`.
10172 */
10173 inputSchema?: Record<string, unknown>;
10174 };
10175
10176 /**
10177 * One tool_use block of an assistant message, with its outcome once the
10178 * transcript holds the call's tool_result (paired by `tool_use_id`).
10179 */
10180 export type ToolUseSummary = {
10181 /**
10182 * The call's id, as `tool.call` carried it (`e.tool_use_id` there).
10183 */
10184 tool_use_id: string;
10185 /**
10186 * Which one was called (`Read`, `Bash`, `mcp__server__tool`), as
10187 * `tool.call` named it (`e.tool` there).
10188 */
10189 tool: string;
10190 /**
10191 * The arguments the model gave it.
10192 */
10193 input: Record<string, unknown>;
10194 /**
10195 * What the transcript stored for the call: the tool's record on an answered
10196 * one (`tool.call`'s `result`), the error text on a refused or errored one.
10197 *
10198 * Absent while the call is in flight or when nothing was stored. Headless
10199 * (`-p`), a tool may store the record less its bulk (Bash blanks `stdout`);
10200 * `text` holds either way.
10201 */
10202 result?: unknown;
10203 /**
10204 * The result as the model read it; absent while the call is in flight.
10205 */
10206 text?: string;
10207 /**
10208 * Present only when the tool reported an error, as on `tool.call`'s result.
10209 */
10210 isError?: true;
10211 };
10212
10213 /**
10214 * One settled run of a link beneath the caller, as `next.trace` lists it:
10215 * data, not a handle.
10216 *
10217 * `received` and `returned` are the live references where the hook runs
10218 * beside the chain; in a hooks module its own copies, as `e` is.
10219 */
10220 export type TraceEntry<N extends EventName = EventName, E = Args<N>, O = NextResult<N>> = {
10221 /**
10222 * The link's place in the chain, 0 the outermost.
10223 */
10224 readonly index: number;
10225 /**
10226 * The hook's plugin; `"engine"` for the engine's own core or bottom.
10227 */
10228 readonly plugin: string;
10229 /**
10230 * The link's tier (Tier); `"core"` for the engine's own core or bottom.
10231 */
10232 readonly tier: Tier;
10233 readonly event: N;
10234 readonly outcome: TraceOutcome;
10235 /**
10236 * Why the link was skipped without running, when it was: `bypassed by
10237 * <plugin>`, whose `next.to` went beneath this tier. Absent when it ran.
10238 */
10239 readonly reason?: string;
10240 /**
10241 * Its own wall time, its `next()` calls' time in flight taken out.
10242 *
10243 * The engine entry's is everything beneath the last hook: in a hooks
10244 * module, the host round trip.
10245 */
10246 readonly ms: number;
10247 /**
10248 * How many chunks the link yielded up, on a streaming event; absent on
10249 * every other. A link left mid-stream counts what it yielded before.
10250 */
10251 readonly chunks?: number;
10252 readonly received: E;
10253 /**
10254 * What the link settled on; undefined when it was skipped or rejected.
10255 */
10256 readonly returned: O | undefined;
10257 };
10258
10259 /**
10260 * What the chain decided for one link, as `next.trace` names it.
10261 *
10262 * `returned`: its result stood; `passed`: it returned, by reference, what its
10263 * last `next()` resolved to (a hooks module's hook answers with a copy of its
10264 * own, so it reads `returned`); `skipped`: it failed before `next`, or a
10265 * `next.to` above continued beneath its tier (`reason` says which), and
10266 * beneath ran in its place; `kept`: it failed after `next`, and that run's
10267 * result stands; `expired`: its budget ran out (what stands follows
10268 * skipped/kept); `caught`: it threw or its budget ran out, and its `.catch`
10269 * handler's result stands; `rejected`: the link rejected; the deepest such
10270 * entry is where the rejection came from, and the ones above it let it pass.
10271 */
10272 export type TraceOutcome = 'caught' | 'expired' | 'kept' | 'passed' | 'rejected' | 'returned' | 'skipped';
10273
10274 /**
10275 * What every `turn.complete` carries whatever its reason: the answer, the
10276 * duration, the interrupt flag, the turn's id, its loop and what it cost.
10277 */
10278 type TurnCompleteFields = {
10279 /**
10280 * The assistant's final visible text this turn ("" if none, e.g.
10281 * thinking-only).
10282 */
10283 answer: string;
10284 /**
10285 * Wall-clock length of the turn in milliseconds.
10286 */
10287 durationMs: number;
10288 /**
10289 * True when the turn ended by interruption (`reason === 'aborted'`).
10290 */
10291 isAborted: boolean;
10292 /**
10293 * The turn's id, the same one its `turn.start` and every `turn.step`
10294 * carried; a subagent's run raises no `turn.start`, its steps carry it.
10295 */
10296 turnId: string;
10297 /**
10298 * The loop the turn ran in: a subagent's id, as `$.agent.spawn` resolves
10299 * it, each run of its loop one turn; absent on the main loop.
10300 *
10301 * Pinned: a different value is refused, one left out is kept. Every hook
10302 * sees a subagent's turn, so a hook that spawns sees its children's turns
10303 * too and bounds itself.
10304 */
10305 agentId?: string;
10306 /**
10307 * What the turn cost: its responses' token counts summed and the model of
10308 * the last, read off the API responses the engine already holds.
10309 *
10310 * Absent when the turn got no response (interrupted before one, an API
10311 * error).
10312 */
10313 usage?: TurnUsage;
10314 };
10315
10316 /**
10317 * The input of `turn.complete`: the assistant's final message of a turn, at
10318 * the moment the turn ends (where the turn's duration is reported).
10319 *
10320 * `reason` says why it ended; `refusal` exists on a refusal alone.
10321 */
10322 export type TurnCompleteInput = TurnCompleteFields & (TurnCompleteRefused | TurnCompleteUnrefused);
10323
10324 /**
10325 * Why a turn ended: the model answered, the user interrupted it, the model
10326 * refused with no fallback model to retry on, or an API error ended it.
10327 */
10328 export type TurnCompleteReason = 'answer' | 'aborted' | 'refusal' | 'error';
10329
10330 /**
10331 * The end of a turn the model refused with no fallback model to retry on:
10332 * what the API said of the refusal rides along.
10333 */
10334 type TurnCompleteRefused = {
10335 reason: 'refusal';
10336 refusal: TurnRefusal;
10337 };
10338
10339 /**
10340 * What a `turn.complete` hook returns and what `next(e)` resolves to:
10341 * `{ text }`; a text other than a main-loop answer's is shown beneath it.
10342 *
10343 * Core fills `usage` from `e.usage` when the turn had one; a hook above reads
10344 * it, and one that answers its own may leave it out.
10345 */
10346 export type TurnCompleteResult = {
10347 text: string;
10348 usage?: TurnUsage;
10349 };
10350
10351 /**
10352 * The end of a turn that was not a refusal: answered, interrupted, or dead
10353 * on an API error (retries exhausted, the context limit), nothing more.
10354 */
10355 type TurnCompleteUnrefused = {
10356 reason: Exclude<TurnCompleteReason, 'refusal'>;
10357 };
10358
10359 /**
10360 * What the API said about a refusal that ended a turn: the classifier's
10361 * category and its explanation, each null when the API sent none.
10362 */
10363 export type TurnRefusal = {
10364 category: string | null;
10365 explanation: string | null;
10366 };
10367
10368 /**
10369 * The input of `turn.start`: the prompt a model turn begins with, after
10370 * `prompt.submit` settled the text and the UserPromptSubmit settings hooks ran.
10371 */
10372 export type TurnStartInput = {
10373 /**
10374 * The user's text as the turn proceeds with it ("" for a turn started without
10375 * a typed prompt, e.g. a continuation).
10376 */
10377 text: string;
10378 /**
10379 * The turn's id, minted here; the same one every `turn.step` and the
10380 * `turn.complete` of this turn carry.
10381 */
10382 turnId: string;
10383 };
10384
10385 /**
10386 * What a `turn.start` hook returns and what `next(e)` resolves to:
10387 * `{ turnId }`, echoed by core; a hook's own value does not change the turn.
10388 */
10389 export type TurnStartResult = {
10390 turnId: string;
10391 };
10392
10393 /**
10394 * One piece of a `turn.step` response as it streams through the chain:
10395 * what a hook's `next(e)` yields and what the hook yields up in turn.
10396 *
10397 * Text, thinking, a tool call's start and arguments, and the stop are
10398 * plain data a hook reads and rewrites; `engine` is the rest, passed on
10399 * unread. What leaves the outermost hook is what is shown and recorded.
10400 */
10401 export type TurnStepChunk = TurnStepTextChunk | TurnStepThinkingChunk | TurnStepToolChunk | TurnStepInputChunk | TurnStepStopChunk | TurnStepEngineChunk;
10402
10403 /**
10404 * An item of the engine's stream the other chunk kinds do not model (the
10405 * envelope, a block's start and end, a retry marker), opaque by `ref`.
10406 *
10407 * Pass it on where it came. A hook that yields its own response has none
10408 * to yield, and the engine supplies what the response needs around the
10409 * chunks it does yield.
10410 */
10411 export type TurnStepEngineChunk = {
10412 kind: 'engine';
10413 /**
10414 * The engine's handle on the item; opaque, this step's only.
10415 */
10416 ref: number;
10417 };
10418
10419 /**
10420 * The input of `turn.step`: one model request inside a turn, at the moment
10421 * the engine is about to send it; the bottom of the chain sends it.
10422 *
10423 * The transcript is not on it: `messageCount` says how many messages the
10424 * request carries, and `$.session.messages()` reads them. A hook rewrites
10425 * `model` or `effort` going down; the rest is pinned.
10426 */
10427 export type TurnStepInput = {
10428 /**
10429 * The turn this step belongs to (`turn.start`'s id; inside a subagent's
10430 * loop, the id the run's `turn.complete` will carry). Pinned.
10431 */
10432 turnId: string;
10433 /**
10434 * The step's position in the turn, from 0. Pinned.
10435 */
10436 index: number;
10437 /**
10438 * Which model the request names, as the engine resolved it for this step
10439 * (the session's, a fallback's). `next({ ...e, model })` names another.
10440 */
10441 model: string;
10442 /**
10443 * How hard the request asks the model to think: the session's setting or
10444 * the model's default, absent for a model without effort; rewritable.
10445 */
10446 effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number;
10447 /**
10448 * How many messages the request carries (the conversation so far, the
10449 * turn's tool results included). Pinned: the messages are the engine's.
10450 */
10451 messageCount: number;
10452 /**
10453 * The loop the request is made in: a subagent's id, the `id`
10454 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
10455 *
10456 * Pinned: a different value is refused, one left out is kept. A subagent
10457 * a hook spawned through `$.agent.spawn` steps past that hook, as its tool
10458 * calls do; every other hook sees its steps.
10459 */
10460 agentId?: string;
10461 };
10462
10463 /**
10464 * A piece of a tool call's arguments as they arrive: JSON text, partial,
10465 * for the `tool` chunk of the same `index`.
10466 *
10467 * The arguments the tool runs with are the pieces concatenated and parsed
10468 * once the block ends; pieces that do not parse leave the call without
10469 * arguments it can run on, as a model that wrote broken JSON would.
10470 */
10471 export type TurnStepInputChunk = ChunkRef & {
10472 kind: 'input';
10473 index: number;
10474 /**
10475 * The next piece of the arguments' JSON text.
10476 */
10477 json: string;
10478 };
10479
10480 /**
10481 * What a `turn.step` hook returns and what `next(e)` resolves to: the
10482 * model's response to the step's request, once its blocks are all in.
10483 *
10484 * From the bottom, the response the engine streamed; a hook's own value
10485 * changes what the hooks above it read, never what the engine streamed.
10486 */
10487 export type TurnStepResult = {
10488 /**
10489 * The turn this step belongs to, as received.
10490 */
10491 turnId: string;
10492 /**
10493 * The step's position in the turn, as received.
10494 */
10495 index: number;
10496 /**
10497 * The visible text of the response ("" when it only called tools, only
10498 * thought, or no request was made).
10499 */
10500 answer: string;
10501 /**
10502 * The tool calls the response made, in order; empty for a text-only step.
10503 */
10504 toolUses: readonly TurnStepToolUse[];
10505 /**
10506 * Why the model stopped; null when no response arrived (the request
10507 * failed or was interrupted before a message, or no request was made).
10508 */
10509 stopReason: TurnStopReason;
10510 /**
10511 * What the request cost as the API reported it, and the model that
10512 * answered; null when no response arrived or it carried no usage.
10513 */
10514 usage: TurnUsage | null;
10515 };
10516
10517 /**
10518 * The response is whole: why the model stopped and what the request cost,
10519 * as the step's result will carry them. The last chunk of one response.
10520 */
10521 export type TurnStepStopChunk = ChunkRef & {
10522 kind: 'stop';
10523 stopReason: TurnStopReason;
10524 usage: TurnUsage | null;
10525 };
10526
10527 /**
10528 * A piece of the response's visible text as it arrives, in block `index`.
10529 *
10530 * The text the person watches stream and the text the transcript records
10531 * are both the concatenation of these, in order, per block: a hook that
10532 * rewrites them rewrites both, one that drops them all drops the block.
10533 */
10534 export type TurnStepTextChunk = ChunkRef & {
10535 kind: 'text';
10536 /**
10537 * The content block the piece belongs to, from 0 within one response.
10538 */
10539 index: number;
10540 text: string;
10541 };
10542
10543 /**
10544 * A piece of the model's thinking as it arrives, in block `index`: what
10545 * the person sees of it live.
10546 *
10547 * The thinking block the transcript keeps is the one the model signed, as
10548 * the engine received it; thinking a hook streams without the engine's
10549 * block behind it is shown and not recorded.
10550 */
10551 export type TurnStepThinkingChunk = ChunkRef & {
10552 kind: 'thinking';
10553 index: number;
10554 text: string;
10555 };
10556
10557 /**
10558 * The model begins a tool call in block `index`: the tool's name and the
10559 * call's id; its arguments follow as `input` chunks of the same index.
10560 *
10561 * A block whose `tool` chunk never comes out of the chain is no tool call:
10562 * the engine records none and runs none.
10563 */
10564 export type TurnStepToolChunk = ChunkRef & {
10565 kind: 'tool';
10566 index: number;
10567 /**
10568 * The call's `tool_use_id`.
10569 */
10570 id: string;
10571 /**
10572 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
10573 */
10574 name: string;
10575 };
10576
10577 /**
10578 * One tool call the model asked for in a step: the tool's name and its
10579 * arguments.
10580 */
10581 export type TurnStepToolUse = {
10582 /**
10583 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
10584 */
10585 name: string;
10586 /**
10587 * The arguments the model gave it, as the tool schema shapes them.
10588 */
10589 input: unknown;
10590 };
10591
10592 /**
10593 * Why the model stopped, as a `turn.step` result and its stop chunk carry
10594 * it: one of the API's stop reasons, or null when no response arrived.
10595 */
10596 type TurnStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'compaction' | 'refusal' | 'model_context_window_exceeded' | null;
10597
10598 /**
10599 * What a model turn, or one response inside it, cost as the API reported it:
10600 * the four token counts (`$.model.fork`'s usage shape) and the model's id.
10601 *
10602 * A turn's counts are its responses' summed; its model is the last response's.
10603 */
10604 export type TurnUsage = ModelForkUsage & {
10605 /**
10606 * Which model answered, by the id the API reports.
10607 */
10608 model: string;
10609 };
10610
10611 /**
10612 * What a plugin's `$.ui.blit(args)` takes: a Raster's next `cells`
10613 * (RasterBlitArgs) or a keyed Image's next `source` (ImageBlitArgs).
10614 *
10615 * Either names an element this plugin's own `ui.render` hook drew, still
10616 * mounted; a hook above may rewrite the cells or the source, never the
10617 * address or which kind it is.
10618 */
10619 export type UiBlitArgs = RasterBlitArgs | ImageBlitArgs;
10620
10621 /**
10622 * What `$.ui.blit` resolves to and what a `ui.blit` hook's `{ value }`
10623 * holds: `{}` once the cells or source are the next frame's, or why not.
10624 */
10625 export type UiBlitResult = {
10626 /**
10627 * Absent when the cells or source were taken; else why not.
10628 *
10629 * Nothing of this plugin's is mounted there (another plugin's reads so),
10630 * the size is not the mounted one, the cells or source are bad, or the
10631 * Image draws its `alt` there, the reason spelled out for a fallback.
10632 */
10633 deny?: string;
10634 };
10635
10636 /**
10637 * What a plugin's `$.ui.focus(args)` takes: one of its own elements, by the
10638 * `key` it drew it under, in one of its sites that holds the keyboard now.
10639 *
10640 * The engine resolves it to that site's ring and raises `ui.focus` under
10641 * the plugin's origin; the keyboard is the person's to give, so a site that
10642 * does not hold it, or holds it on another plugin's element, is `{ deny }`.
10643 */
10644 export type UiFocusArgs = {
10645 /**
10646 * The site, by the `requestId` this plugin draws it under: one of its
10647 * panes' ids, or the band's.
10648 */
10649 requestId: string;
10650 /**
10651 * The element's `key`: a `Button`, `Input` or `Select` this plugin drew in
10652 * that site; of several under one key, the first in document order.
10653 */
10654 key: string;
10655 };
10656
10657 /**
10658 * The render components whose site keeps a focus ring: a pane's body and
10659 * the band above the prompt, each a ring over the elements hooks drew there.
10660 */
10661 export type UiFocusComponent = 'Pane' | 'AbovePrompt';
10662
10663 /**
10664 * The input of `ui.focus`: a site's focus ring about to move onto one of the
10665 * elements a hook drew in it (a `Button`, `Input` or `Select`), or off them.
10666 *
10667 * Every key but `element` is the engine's word, pinned: `next(e)` passes
10668 * them on, a rewrite that leaves one out keeps it, one that changes it fails
10669 * the hook. `element` is the hook's to rewrite; the ring has not moved yet.
10670 */
10671 export type UiFocusInput = {
10672 /**
10673 * Which site: a `Pane` body or the `AbovePrompt` band.
10674 */
10675 component: UiFocusComponent;
10676 /**
10677 * The instance the `ui.render` hook drawing the site sees: the pane's id,
10678 * or the band's one id.
10679 */
10680 requestId: string;
10681 /**
10682 * Whose `ui.render` hook drew the element taking the ring; absent with
10683 * `element`. Read-only.
10684 */
10685 plugin?: string;
10686 /**
10687 * The `key` of the element taking the ring, as `ui.press` names it; absent
10688 * for one of the engine's own stops (a pane's close mark or another's tab).
10689 *
10690 * `next({ ...e, element })` lands it on another element `plugin` drew in
10691 * the site instead; one not drawn there is core's `{ deny }`.
10692 */
10693 element?: string;
10694 /**
10695 * Who moves it (UiFocusOrigin), set by the engine where the move starts.
10696 */
10697 origin: UiFocusOrigin;
10698 };
10699
10700 /**
10701 * Who moves the ring at `ui.focus`, as the engine stamps it where the move
10702 * starts; a closed set a matcher narrows on.
10703 *
10704 * `next(e)` passes it on as received; no hook sets one.
10705 */
10706 export type UiFocusOrigin = {
10707 /**
10708 * The person, by Tab, the arrows or a click while the site holds the
10709 * keyboard.
10710 */
10711 kind: 'person';
10712 } | {
10713 /**
10714 * A plugin's `$.ui.focus`, or its `autoFocus` element taking the ring
10715 * as the site takes the keyboard.
10716 */
10717 kind: 'plugin';
10718 /**
10719 * The focusing plugin's name.
10720 */
10721 name: string;
10722 };
10723
10724 /**
10725 * What a `ui.focus` hook returns, what `next(e)` resolves to, and what
10726 * `$.ui.focus` hands back: `{}` once the ring moved, or why it did not.
10727 *
10728 * As `ui.scroll` spells it.
10729 */
10730 export type UiFocusResult = {
10731 /**
10732 * Absent when the ring is where the chain left it; else why nothing
10733 * moved.
10734 *
10735 * A hook kept the ring (no `next`); the site is not this plugin's, does
10736 * not hold the keyboard, or another plugin's element holds it; no element
10737 * of `plugin` is drawn under `element`; another move landed first.
10738 */
10739 deny?: string;
10740 };
10741
10742 /**
10743 * The argument of `ui.input`: a change of, or a submit from, an `Input` a
10744 * render hook drew. Flat and frozen like every event's.
10745 *
10746 * Another plugin addresses one field by matcher:
10747 * `on("ui.input", { plugin: "roster", element: "reply" }, ...)`.
10748 */
10749 export type UiInputArgument = {
10750 /**
10751 * Whose `ui.render` hook drew the element.
10752 */
10753 plugin: string;
10754 /**
10755 * The `key` the hook gave its `Input`: its address, what a matcher names.
10756 */
10757 element: string;
10758 /**
10759 * The render component the element was drawn in (`AbovePrompt`,
10760 * `ToolUse`, ...).
10761 */
10762 component: RenderComponent;
10763 /**
10764 * The instance the element was drawn in: the `requestId` the `ui.render`
10765 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
10766 */
10767 requestId: string;
10768 /**
10769 * Where the typing came from, one literal per member, so
10770 * `if (e.surface === "terminal")` narrows `e`.
10771 */
10772 surface: RenderSurface;
10773 /**
10774 * `change` after every edit of the text; `submit` on Enter.
10775 */
10776 kind: 'change' | 'submit';
10777 /**
10778 * The field's whole text at that moment; a hook above may rewrite it for
10779 * the plugins beneath and the element's own handler.
10780 */
10781 value: string;
10782 };
10783
10784 /**
10785 * What a `ui.input` hook returns and what `next(e)` resolves to.
10786 *
10787 * Beneath every hook, core runs the element's `onInput` (kind `change`) or
10788 * `onSubmit` (kind `submit`) closure in its plugin's environment with the
10789 * value as the chain left it, and answers `{ element, value }`.
10790 */
10791 export type UiInputResult = {
10792 /**
10793 * Which handler the input reached, by its Input's `key`.
10794 */
10795 element: string;
10796 /**
10797 * The text the handler received.
10798 */
10799 value: string;
10800 };
10801
10802 /**
10803 * Options of `$.ui.log`.
10804 */
10805 export type UiLogOptions = {
10806 /**
10807 * Where the line goes (UiLogSink); `transcript` when left out. A hook on
10808 * `ui.log` reads it as `e.to` and may send the line elsewhere.
10809 */
10810 to?: UiLogSink;
10811 };
10812
10813 /**
10814 * Where a `$.ui.log` line goes: `transcript`, a dim row of its own (and the
10815 * debug log, as every line); `debug`, the debug log alone, nothing on screen.
10816 *
10817 * The debug log is `claude --debug` or the `--debug-file`; either way the
10818 * line is led by the plugin's name.
10819 */
10820 export type UiLogSink = 'transcript' | 'debug';
10821
10822 /**
10823 * The argument of `ui.message`: what a `Client` instance's surface module
10824 * posted (`surface.post(data)`), addressed by where the instance is drawn.
10825 *
10826 * The origin is `client`: code sent it, on nobody's behalf, so `data` is
10827 * input to validate, not a fact. Everything but `data` is the engine's word
10828 * and a hook may not rewrite it.
10829 */
10830 export type UiMessageArgument = {
10831 /**
10832 * Where the instance is drawn: `terminal`, or `desktop` once it has them.
10833 */
10834 surface: RenderSurface;
10835 /**
10836 * The render component the `Client` was drawn in (`AbovePrompt`, `Pane`,
10837 * ...).
10838 */
10839 component: RenderComponent;
10840 /**
10841 * The engine's id for the drawing the `Client` sits in: the `requestId` the
10842 * `ui.render` hook that drew it saw.
10843 */
10844 requestId: string;
10845 /**
10846 * The `Client`'s `key`: which instance posted.
10847 */
10848 element: string;
10849 /**
10850 * The `Client`'s `module`: which surface module runs there, as its path
10851 * under the plugin's folder.
10852 */
10853 module: string;
10854 /**
10855 * What the instance posted: plain data (JsonValue), bounded as a tree's
10856 * text is; typed `unknown` since it came from code. Rewritable.
10857 */
10858 data: unknown;
10859 };
10860
10861 /**
10862 * What a `ui.message` hook returns and what `next(e)` resolves to.
10863 *
10864 * Core answers `{}`: the message was heard and nothing changes. A hook that
10865 * answers `{ props }` hands the posting instance its next props directly, its
10866 * local state kept, with no `ui.render` run; the plugin's next redraw hands
10867 * props again as usual.
10868 */
10869 export type UiMessageResult = {
10870 /**
10871 * The instance's next props, plain data (JsonValue) bounded as a `Client`'s
10872 * props are; absent leaves the instance's props as they were.
10873 */
10874 props?: unknown;
10875 };
10876
10877 /**
10878 * One of this plugin's open panes as `$.ui.panes()` lists it: the pane's
10879 * id and title, and where it stands with the person right now.
10880 *
10881 * Where a surface seated it (`dock` or `inline`) is that surface's to say, on
10882 * the `Pane` render props (`placement`); a session may draw on several.
10883 */
10884 export type UiPane = {
10885 /**
10886 * What `$.ui.open({ id })` named it, which `$.ui.close` and its
10887 * `ui.render` `requestId` name too.
10888 */
10889 id: string;
10890 /**
10891 * Its tab's label: the `title` of its latest open, or the id.
10892 */
10893 title: string;
10894 /**
10895 * True for the one pane the surface shows; the rest are tabs behind it.
10896 */
10897 isShown: boolean;
10898 /**
10899 * True while the person has given it the keyboard.
10900 */
10901 isFocused: boolean;
10902 /**
10903 * False while it waits undrawn: opened unasked on a terminal too narrow
10904 * for an unrequested pane, until an open the width or the person admits.
10905 */
10906 isPlaced: boolean;
10907 };
10908
10909 /**
10910 * The argument of `ui.press`: a press on a `Button` a render hook drew, or
10911 * on an answered `Markdown` link. Flat and frozen like every event's.
10912 *
10913 * Another plugin addresses one button by matcher:
10914 * `on("ui.press", { plugin: "explainer", element: "explain" }, ...)`.
10915 */
10916 export type UiPressArgument = {
10917 /**
10918 * Whose `ui.render` hook drew the element.
10919 */
10920 plugin: string;
10921 /**
10922 * The `key` the hook gave its `Button` or `Markdown`: its address, what a
10923 * matcher names.
10924 */
10925 element: string;
10926 /**
10927 * The render component the element was drawn in (`ToolUse`,
10928 * `AssistantMessage`, ...).
10929 */
10930 component: RenderComponent;
10931 /**
10932 * The instance the element was drawn in: the `requestId` the `ui.render`
10933 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
10934 */
10935 requestId: string;
10936 /**
10937 * Where the press came from, one literal per member, so
10938 * `if (e.surface === "terminal")` narrows `e`.
10939 */
10940 surface: RenderSurface;
10941 /**
10942 * Where the press landed, when the element is a `Markdown` whose links
10943 * its plugin answers (`onLinkPress`); absent for a `Button`.
10944 *
10945 * A hook may rewrite its `href` for the hooks and the closure beneath; one
10946 * that adds or drops it fails, and the press goes on beneath it.
10947 */
10948 link?: PressedLink;
10949 };
10950
10951 /**
10952 * What a `ui.press` hook returns and what `next(e)` resolves to.
10953 *
10954 * Beneath every hook, core runs the element's `onPress` closure in its
10955 * plugin's environment with `e` as the chain left it, and answers
10956 * `{ element }`.
10957 */
10958 export type UiPressResult = {
10959 /**
10960 * Which handler the press reached, by its Button's `key`.
10961 */
10962 element: string;
10963 };
10964
10965 /**
10966 * What a plugin's `$.ui.scroll(args)` takes: what to bring into view, in
10967 * which of its sites, and where in the window it lands.
10968 *
10969 * The engine resolves it to a window and an offset and raises `ui.scroll`
10970 * under the plugin's origin; a transcript row is the person's to move, so
10971 * it is revealed only while the plugin answers the person's own input.
10972 */
10973 export type UiScrollArgs = {
10974 /**
10975 * What to reveal (UiScrollTarget): a render instance by `requestId`, one
10976 * of this plugin's elements by `key`, or the `start` or `end` of `in`.
10977 */
10978 to: UiScrollTarget;
10979 /**
10980 * The site to scroll, by the `requestId` this plugin draws it under: one
10981 * of its panes' ids, or the band's.
10982 *
10983 * Required with `start` and `end`; with `{ key }` it picks the site when
10984 * the key is drawn in several.
10985 */
10986 in?: string;
10987 /**
10988 * Where the target lands in the window (UiScrollBlock); `nearest` when
10989 * left out, so a row already showing does not move.
10990 */
10991 block?: UiScrollBlock;
10992 };
10993
10994 /**
10995 * Where in its scrollable a revealed row lands, as the DOM's
10996 * `scrollIntoView({ block })` names it.
10997 *
10998 * `nearest` moves the least that shows the row whole, and not at all when
10999 * it already shows; `start`, `center` and `end` put its top, middle or
11000 * bottom at that edge of the window. A row taller than the window shows
11001 * its top.
11002 */
11003 export type UiScrollBlock = 'start' | 'center' | 'end' | 'nearest';
11004
11005 /**
11006 * The render components whose site the engine scrolls: a pane's body and
11007 * the band above the prompt, each a window over the tree a hook drew there.
11008 */
11009 export type UiScrollComponent = 'Pane' | 'AbovePrompt';
11010
11011 /**
11012 * The input of `ui.scroll`: a site's window asked to move over the tree a
11013 * hook drew in it (a pane's body, the band above the prompt).
11014 *
11015 * Every key but `offset` is the engine's word, pinned: `next(e)` passes
11016 * them on, a rewrite that leaves one out keeps it, one that changes or adds
11017 * one fails the hook. `offset` is the hook's to rewrite; nothing moved yet.
11018 */
11019 export type UiScrollInput = {
11020 /**
11021 * Which site: a `Pane` body or the `AbovePrompt` band.
11022 */
11023 component: UiScrollComponent;
11024 /**
11025 * The instance the `ui.render` hook drawing the site sees: the pane's id,
11026 * or the band's one id.
11027 */
11028 requestId: string;
11029 /**
11030 * The first row the window is to show, 0 at the top: the row it shows
11031 * now plus `by`, clamped to the tree, or where `$.ui.scroll` resolved.
11032 *
11033 * `next({ ...e, offset })` moves it elsewhere (a clamp); one past the
11034 * tree's end lands at the end. Nothing has moved when a hook reads it.
11035 */
11036 offset: number;
11037 /**
11038 * The rows the move asks for, signed, negative toward the top; what the
11039 * DOM's `scrollBy` takes. Read-only.
11040 *
11041 * The person's: a wheel tick `-1` or `1` at rest, more as ticks crowd or
11042 * summed in flight; an arrow a row while the engine has rows to scroll, a
11043 * page key `bodyRows`, Home and End `contentRows`. A plugin's: its distance.
11044 */
11045 by: number;
11046 /**
11047 * How many rows of the tree the window shows at once, as drawn now.
11048 * Read-only.
11049 */
11050 bodyRows: number;
11051 /**
11052 * How many rows the tree has, as drawn now: the window's last offset is
11053 * `contentRows - bodyRows`, none when the tree fits. Read-only.
11054 */
11055 contentRows: number;
11056 /**
11057 * Who moves it (UiScrollOrigin), set by the engine where the move starts.
11058 */
11059 origin: UiScrollOrigin;
11060 /**
11061 * The body cell the person's wheel or trackpad was over (UiScrollPointer);
11062 * absent for the scroll keys and for `$.ui.scroll`. Read-only.
11063 *
11064 * Moves summed while a dispatch was in flight carry the latest one's. A
11065 * hook pinning a list over rows it scrolls itself tells a tick over the
11066 * list (`row` among its list's rows) from one over the body.
11067 */
11068 pointer?: UiScrollPointer;
11069 };
11070
11071 /**
11072 * Who moves the window at `ui.scroll`, as the engine stamps it where the
11073 * move starts; a closed set a matcher narrows on.
11074 *
11075 * `next(e)` passes it on as received; no hook sets one.
11076 */
11077 export type UiScrollOrigin = {
11078 /**
11079 * The person, by the wheel over the site or its scroll keys while
11080 * they hold it.
11081 */
11082 kind: 'person';
11083 } | {
11084 /**
11085 * A plugin's `$.ui.scroll`.
11086 */
11087 kind: 'plugin';
11088 /**
11089 * The scrolling plugin's name.
11090 */
11091 name: string;
11092 };
11093
11094 /**
11095 * The cell the pointer was over when the person's wheel raised `ui.scroll`,
11096 * in the site's body: the box its `ui.render` hook draws into, as painted.
11097 *
11098 * The DOM's `clientY - body.top` in cells, the window's offset not added: a
11099 * hook drawing its own window reads `row` as its tree's row, one the engine
11100 * scrolls adds the `scroll.offset` it drew with. The frame lies outside.
11101 */
11102 export type UiScrollPointer = {
11103 /**
11104 * 0 at the body's left edge, as `bodyColumns` counts them; negative, or
11105 * `bodyColumns` and past, over an inline pane's side borders.
11106 */
11107 column: number;
11108 /**
11109 * 0 at the body's first showing row, as `bodyRows` counts them.
11110 *
11111 * The tree's row is `scroll.offset + row` under the engine's window, and
11112 * `row` itself under a hook's own (offset 0); negative over a pane's top
11113 * border or tab row, `bodyRows` or more over its bottom border.
11114 */
11115 row: number;
11116 };
11117
11118 /**
11119 * What a `ui.scroll` hook returns, what `next(e)` resolves to, and what
11120 * `$.ui.scroll` hands back: `{}` once the window moved, or why it did not.
11121 */
11122 export type UiScrollResult = {
11123 /**
11124 * Absent when the window is where the chain left it; else why nothing
11125 * moved, as `tool.call` and `config.set` spell a refusal.
11126 *
11127 * A hook kept the window (no `next`); the target is not this plugin's;
11128 * another move landed first (`the window moved meanwhile`); a transcript
11129 * row is not the person's ask (`not person-initiated`) or none scrolls.
11130 */
11131 deny?: string;
11132 };
11133
11134 /**
11135 * What `$.ui.scroll` brings into view: never a row number, always a thing
11136 * drawn somewhere.
11137 *
11138 * `{ requestId }` names a render instance by the id its `ui.render` hook
11139 * saw (a transcript message's, a tool row's tool_use_id), scrolled into view
11140 * inside whatever scrolls it. `{ key }` names an element this plugin drew
11141 * with that `key`, inside the site it drew it in. `start` and `end` are the
11142 * top and bottom of the site `in` names; `end` keeps up with a tree that
11143 * grows (rows the plugin just added count) until anything next moves it.
11144 */
11145 export type UiScrollTarget = {
11146 requestId: string;
11147 } | {
11148 key: string;
11149 } | 'start' | 'end';
11150
11151 /**
11152 * The argument of `ui.select`: a pick from a `Select` a render hook drew.
11153 * Flat and frozen like every event's.
11154 *
11155 * Another plugin addresses one picker by matcher:
11156 * `on("ui.select", { plugin: "roster", element: "peer" }, ...)`.
11157 */
11158 export type UiSelectArgument = {
11159 /**
11160 * Whose `ui.render` hook drew the element.
11161 */
11162 plugin: string;
11163 /**
11164 * The `key` the hook gave its `Select`: its address, what a matcher names.
11165 */
11166 element: string;
11167 /**
11168 * The render component the element was drawn in (`AbovePrompt`,
11169 * `ToolUse`, ...).
11170 */
11171 component: RenderComponent;
11172 /**
11173 * The instance the element was drawn in: the `requestId` the `ui.render`
11174 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
11175 */
11176 requestId: string;
11177 /**
11178 * Where the pick came from, one literal per member, so
11179 * `if (e.surface === "terminal")` narrows `e`.
11180 */
11181 surface: RenderSurface;
11182 /**
11183 * The picked option's value; a hook above may rewrite it for the plugins
11184 * beneath and the element's own handler.
11185 */
11186 value: string;
11187 };
11188
11189 /**
11190 * What a `ui.select` hook returns and what `next(e)` resolves to.
11191 *
11192 * Beneath every hook, core runs the element's `onSelect` closure in its
11193 * plugin's environment with the value as the chain left it, and answers
11194 * `{ element, value }`.
11195 */
11196 export type UiSelectResult = {
11197 /**
11198 * Which handler the pick reached, by its Select's `key`.
11199 */
11200 element: string;
11201 /**
11202 * What the handler received: the option's value as the chain left it.
11203 */
11204 value: string;
11205 };
11206
11207 /**
11208 * The intersection of a union's members (`A | B` to `A & B`), by inferring
11209 * one parameter type from the contravariant positions.
11210 */
11211 type UnionToIntersection<U> = (U extends unknown ? (member: U) => void : never) extends (member: infer I) => void ? I : never;
11212
11213 /**
11214 * One unit of what `$.session.usage()` answers, by its key there: the
11215 * context window's fill, the rate-limit windows, the session's cost.
11216 */
11217 export type UsageUnit = 'context' | 'rateLimits' | 'cost';
11218
11219 /**
11220 * Who sent the message a `UserMessage` row carries, when someone other than
11221 * the person did: another agent, a teammate, another session, a channel.
11222 *
11223 * Read-only. The sender's words are not the person's: the model reads them
11224 * framed as that sender's whatever a hook draws for the row.
11225 */
11226 type UserMessageFrom = {
11227 /**
11228 * The sender's name as the row shows it: a subagent's name, else its type;
11229 * a teammate's; another session's title; a channel's sender, else server.
11230 *
11231 * One printable line: control and format characters stripped, whitespace
11232 * collapsed, length bounded. Absent (no `from`) for a teammate block whose
11233 * frames name different senders or none.
11234 */
11235 name: string;
11236 };
11237
11238 /**
11239 * The background task a `UserMessage` notification row reports on: a
11240 * subagent, a background shell, a workflow, a remote agent, a monitor.
11241 *
11242 * Every field is the notification's own, so the row names the same task on
11243 * every draw, a resumed session's included; the session's record of it
11244 * (name, type, description) is `$.agent.list()`'s, by `id`. Each string is
11245 * one printable line, bounded (a forged envelope's bytes capped). Read-only.
11246 */
11247 type UserMessageTask = {
11248 /**
11249 * The task's id as the notification names it; for a subagent, the
11250 * `agentId` its `turn.complete` carried and `$.agent.list()` keys.
11251 */
11252 id?: string;
11253 /**
11254 * How the task ended: `completed`, `failed` or `killed` (stopped, by the
11255 * person or by Claude), or another word its producer wrote.
11256 */
11257 status?: string;
11258 /**
11259 * What kind of task, when the notification says (`remote_agent`, an
11260 * artifact watch's kind); a subagent's and a shell's leave it out.
11261 */
11262 type?: string;
11263 /**
11264 * Which call started the task: its `tool_use_id`, when the notification
11265 * carries it.
11266 */
11267 toolUseId?: string;
11268 /**
11269 * How long the task ran, in milliseconds, when the notification says; the
11270 * row draws it after the summary (`2m 2s`).
11271 */
11272 durationMs?: number;
11273 };
11274
11275 type UserPromptExpansionHookInput = BaseHookInput & {
11276 hook_event_name: 'UserPromptExpansion';
11277 expansion_type: 'slash_command' | 'mcp_prompt';
11278 command_name: string;
11279 command_args: string;
11280 command_source?: string;
11281 prompt: string;
11282 };
11283
11284 type UserPromptSubmitHookInput = BaseHookInput & {
11285 hook_event_name: 'UserPromptSubmit';
11286 prompt: string;
11287 /**
11288 * Who authored/injected the prompt: `user` = submitted from the interactive composer, `sdk` = non-interactive entrypoint (`-p` / Agent SDK), `loop_wakeup` = dynamic /loop wakeup, `schedule_wakeup` = scheduled-task fire (CronCreate/routine), `system` = other machine-injected turns (peer/channel messages, task notifications, auto-continuation), `poll_event` = the poll-event channel enqueue-time pass (the hook fires when the host submits an event, before its delivery ack exists - a blocking verdict rejects the event). Payloads may omit it while the field rolls out.
11289 */
11290 source?: 'user' | 'sdk' | 'system' | 'loop_wakeup' | 'schedule_wakeup' | 'poll_event';
11291 session_title?: string;
11292 };
11293
11294 /**
11295 * The result of a call on `$` as the hooks on its event see it: `{ value }`,
11296 * the call's answer, or `{ deny }`, the reason the caller's promise rejects.
11297 */
11298 type ValueOrDeny<Value> = {
11299 value: Value;
11300 deny?: undefined;
11301 } | {
11302 deny: string;
11303 value?: undefined;
11304 };
11305
11306 type WorktreeCreateHookInput = BaseHookInput & {
11307 hook_event_name: 'WorktreeCreate';
11308 name: string;
11309 };
11310
11311 type WorktreeRemoveHookInput = BaseHookInput & {
11312 hook_event_name: 'WorktreeRemove';
11313 worktree_path: string;
11314 };
11315
11316 /**
11317 * The globals of a hooks module's environment: these and no others (no DOM,
11318 * no Node). No code generation either: `eval` and `new Function` over a
11319 * string throw, and there is no `WebAssembly` (deliberately; a module that
11320 * needs compiled code runs it in a process of its own through `$.process.run`).
11321 * A surface module's environment (Client) has the same globals and a
11322 * `console`; neither has timers (a hooks module waits on `$.clock`, a
11323 * surface module on `surface.every`).
11324 */
11325 global {
11326 /**
11327 * The JSX factory (classic runtime, `@jsx h`; the engine prepends the
11328 * pragma): a plain-data element from a string tag or a component.
11329 *
11330 * JSX compiles to bare `h(...)` calls resolved by name, so a module (hooks or
11331 * surface) never declares, imports or takes as a parameter anything named
11332 * `h` or `Fragment` where it writes JSX, and carries no `@jsx` pragma of its
11333 * own: either silently points its JSX away from this factory, and a
11334 * `<Client>` tag written under another factory is not found when the
11335 * module's surface modules are read off its source.
11336 */
11337 const h: (
11338 tag: string | ((props: never) => RenderNode | null | undefined),
11339 props: Record<string, unknown> | null | undefined,
11340 ...children: unknown[]
11341 ) => RenderNode | null | undefined
11342
11343 /**
11344 * `<>...</>`: a column Box around the children.
11345 */
11346 const Fragment: (props: { children?: RenderNode[] }) => RenderElement
11347
11348 /**
11349 * JSX over the element table: every tag is a constructor from
11350 * `$.ui.resolve(e)` (`const { Box, Text } = $.ui.resolve(e)`), typed by
11351 * its props; there are no intrinsic (string) tags.
11352 */
11353 namespace JSX {
11354 type Element = RenderElement
11355 type Children = RenderChildren
11356 type ElementType = (props: never) => RenderNode | null | undefined
11357 interface IntrinsicElements {}
11358 interface ElementChildrenAttribute {
11359 children: unknown
11360 }
11361 interface IntrinsicAttributes {
11362 key?: string
11363 }
11364 }
11365
11366 interface AbortSignal {
11367 readonly aborted: boolean
11368 readonly reason: unknown
11369 throwIfAborted(): void
11370 addEventListener(
11371 type: 'abort',
11372 listener: () => void,
11373 options?: { once?: boolean },
11374 ): void
11375 removeEventListener(type: 'abort', listener: () => void): void
11376 }
11377 var AbortSignal: {
11378 prototype: AbortSignal
11379 abort(reason?: unknown): AbortSignal
11380 timeout(milliseconds: number): AbortSignal
11381 any(signals: AbortSignal[]): AbortSignal
11382 }
11383 interface AbortController {
11384 readonly signal: AbortSignal
11385 abort(reason?: unknown): void
11386 }
11387 var AbortController: {
11388 prototype: AbortController
11389 new (): AbortController
11390 }
11391 interface TextEncoder {
11392 readonly encoding: string
11393 encode(input?: string): Uint8Array
11394 }
11395 var TextEncoder: { prototype: TextEncoder; new (): TextEncoder }
11396 interface TextDecoder {
11397 readonly encoding: string
11398 decode(input?: ArrayBufferView | ArrayBuffer): string
11399 }
11400 var TextDecoder: { prototype: TextDecoder; new (label?: string): TextDecoder }
11401 interface URLSearchParams {
11402 append(name: string, value: string): void
11403 delete(name: string): void
11404 get(name: string): string | null
11405 getAll(name: string): string[]
11406 has(name: string): boolean
11407 set(name: string, value: string): void
11408 toString(): string
11409 forEach(callback: (value: string, key: string) => void): void
11410 }
11411 var URLSearchParams: {
11412 prototype: URLSearchParams
11413 new (init?: string | Record<string, string> | string[][]): URLSearchParams
11414 }
11415 interface URL {
11416 hash: string
11417 host: string
11418 hostname: string
11419 href: string
11420 readonly origin: string
11421 password: string
11422 pathname: string
11423 port: string
11424 protocol: string
11425 search: string
11426 readonly searchParams: URLSearchParams
11427 username: string
11428 toString(): string
11429 toJSON(): string
11430 }
11431 var URL: {
11432 prototype: URL
11433 new (url: string, base?: string | URL): URL
11434 canParse(url: string, base?: string): boolean
11435 }
11436 function atob(data: string): string
11437 function btoa(data: string): string
11438 function structuredClone<T>(value: T): T
11439 var crypto: {
11440 readonly subtle: {
11441 digest(
11442 algorithm: string | { name: string },
11443 data: ArrayBufferView | ArrayBuffer,
11444 ): Promise<ArrayBuffer>
11445 }
11446 randomUUID(): string
11447 getRandomValues<T extends ArrayBufferView>(array: T): T
11448 }
11449 var performance: { now(): number }
11450 }
11451}
11452
11453declare module 'claude-code/testing' {
11454 import type { Args } from 'claude-code';
11455 import type { Chunk } from 'claude-code';
11456 import type { ClientKeyEvent } from 'claude-code';
11457 import type { ClientPointerEvent } from 'claude-code';
11458 import type { Elements } from 'claude-code';
11459 import type { EventCalls } from 'claude-code';
11460 import type { EventName } from 'claude-code';
11461 import type { HookStream } from 'claude-code';
11462 import type { JsonValue } from 'claude-code';
11463 import type { On } from 'claude-code';
11464 import type { PressedLink } from 'claude-code';
11465 import type { Register } from 'claude-code';
11466 import type { RenderComponent } from 'claude-code';
11467 import type { RenderElement } from 'claude-code';
11468 import type { RenderPropsOf } from 'claude-code';
11469 import type { RenderSurface } from 'claude-code';
11470 import type { RenderViewport } from 'claude-code';
11471 import type { ResultOf } from 'claude-code';
11472 import type { StreamingEventName } from 'claude-code';
11473 import type { Tier } from 'claude-code';
11474 import type { UiInputArgument } from 'claude-code';
11475 import type { UiInputResult } from 'claude-code';
11476 import type { UiPressResult } from 'claude-code';
11477 import type { UiSelectResult } from 'claude-code';
11478
11479 /**
11480 * A value that matches by a rule inside `toEqual` and its kin
11481 * (`expect.any`, `expect.objectContaining`), known by its text in a failure.
11482 */
11483 export type AsymmetricMatcher = {
11484 readonly text: string;
11485 };
11486
11487 /**
11488 * The same checks on what a promise received settles with, each resolving
11489 * once the promise has settled and the check passed.
11490 */
11491 export type AsyncMatchers = {
11492 [K in keyof Matchers]: (...args: Parameters<Matchers[K]>) => Promise<void>;
11493 };
11494
11495 /**
11496 * Which `Client` of a mounted drawing an act or a read means, by the `key`
11497 * its element carries; optional while the drawing holds exactly one.
11498 */
11499 export type ClientScope = {
11500 in?: string;
11501 };
11502
11503 /**
11504 * A class, as `toThrow`, `toBeInstanceOf` and `expect.any` take it.
11505 */
11506 export type Constructor = abstract new (...args: never[]) => unknown;
11507
11508 /**
11509 * A group of tests: its name leads the title of each test declared inside,
11510 * and its body runs at once, while the file loads.
11511 *
11512 * @param name the group's name
11513 * @param body declares the group's tests
11514 */
11515 export const describe: (name: string, body: () => void) => void;
11516
11517 /**
11518 * The element each surface-dependent act of a mounted drawing reaches: a
11519 * handle carries the act only where the surface's table has the element.
11520 *
11521 * `input` needs `Input` and `select` needs `Select` (every surface but
11522 * mobile today); `key`, `pointer`, `post`, `advance` and `resize` reach a
11523 * `Client` (terminal and desktop today). The rest need nothing but a tree.
11524 */
11525 export type ElementOfAct = {
11526 input: 'Input';
11527 select: 'Select';
11528 key: 'Client';
11529 pointer: 'Client';
11530 post: 'Client';
11531 advance: 'Client';
11532 resize: 'Client';
11533 };
11534
11535 /**
11536 * What a mounted drawing's `find` and `findAll` match an element on, every
11537 * field given at once: its tag, its `key`, and the text it shows.
11538 *
11539 * `text` matches the element's whole shown text (string children, a Button
11540 * or Link's label, a Markdown's text, a Code's source, an Input's value):
11541 * a string by inclusion, a RegExp by test.
11542 *
11543 * @example
11544 * await ui.findAll({ type: 'Text', text: /overdue/, in: 'board' })
11545 */
11546 export type ElementQuery = {
11547 type?: string;
11548 key?: string;
11549 text?: string | RegExp;
11550 /**
11551 * Searches what this `Client`'s surface module drew (by the `Client`'s
11552 * key) instead of the plugin's own tree.
11553 */
11554 in?: string;
11555 };
11556
11557 /**
11558 * What a test holds as `$`, the engine's own: every call on it is made as
11559 * the REPL, the query loop and the render sites make theirs, over every plugin.
11560 *
11561 * `next.origin` is the engine, and the whole chain runs over the plugins
11562 * loaded. A tool call's `tool_use_id` is minted when left out; `$.ui.mount`
11563 * is a surface the test names drawing an instance, `$.ui.press` a press on it.
11564 */
11565 export type Engine = {
11566 [N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress & EngineMount : EngineNoun<N>;
11567 };
11568
11569 /**
11570 * One call on the engine's `$`: the event's input whole, as an engine call
11571 * site passes it, to its result, or for a streaming event to its stream.
11572 */
11573 export type EngineCall<E extends EventName> = E extends StreamingEventName ? (e: Args<E>) => HookStream<Chunk<E>, ResultOf[E]> : (e: Args<E>) => Promise<ResultOf[E]>;
11574
11575 /**
11576 * A surface drawing a component instance through the plugins, then driven
11577 * by key through a handle typed by that surface (Mounted).
11578 *
11579 * `ui.render` raised there for those props, the tree validated by that
11580 * table, its `Client`s running; the reads and `press` on every surface,
11581 * `input` where the table has `Input`, the `Client` acts where `Client`.
11582 *
11583 * @example
11584 * for (const surface of SURFACES) run(await $.ui.mount({ ...HINT, surface }))
11585 */
11586 export type EngineMount = {
11587 /**
11588 * Raises the plugins' drawing of the component on the surface and holds
11589 * it, as that surface showing the instance does.
11590 *
11591 * Resolves once the tree validated and every `Client` in it drew once.
11592 *
11593 * @param target whose elements, the surface, the component, its props,
11594 * the instance's requestId, and what the surface measured
11595 * @returns the mounted drawing; rejects when no `surface` (or an unknown
11596 * one) is named, when the surface cannot draw the tree the chain
11597 * returned (with the reason: an element its table lacks, a prop not
11598 * allowed), or when a `Client`'s module failed or drew nothing
11599 */
11600 mount: <P extends RenderSurface, C extends RenderComponent>(target: MountTarget<P, C>) => Promise<Mounted<P, C>>;
11601 };
11602
11603 /**
11604 * One noun of the engine's `$`: each of its events as the engine calls it,
11605 * `tool.call` and `ui.render` typed per tool and component, `ui.resolve` out.
11606 */
11607 export type EngineNoun<N extends keyof EventCalls> = {
11608 [V in EngineNounEvent<N>]: `${N}.${V}` extends 'tool.call' | 'ui.render' ? EventCalls[N][V] : EngineCall<`${N}.${V}` & EventName>;
11609 };
11610
11611 /**
11612 * The events of one noun a test's `$` carries: every one but `ui.resolve`,
11613 * which a render hook calls on its own `$` and the engine never raises.
11614 */
11615 export type EngineNounEvent<N extends keyof EventCalls> = Exclude<keyof EventCalls[N] & string, `${N}.resolve` extends 'ui.resolve' ? 'resolve' : never>;
11616
11617 /**
11618 * A surface pressing a Button a test rendered, or a Markdown's link: the
11619 * `ui.press` chain over every plugin hooked on it, its own closure last.
11620 */
11621 export type EnginePress = {
11622 /**
11623 * Presses the Button, as a click or its hotkey does; with `link`, the
11624 * Markdown's link, as a click on it does.
11625 *
11626 * `e.surface` is the surface of the drawing that holds it.
11627 *
11628 * @param target whose element, its key, the instance and surface when
11629 * several hold it, and for a Markdown the link
11630 * @returns what the chain settled on; rejects when no such element is
11631 * drawn, or several are and neither instance nor surface tells them apart
11632 */
11633 press: (target: PressTarget) => Promise<UiPressResult | undefined>;
11634 };
11635
11636 /**
11637 * The checks on a value (`expect(received)`), and with them the matchers
11638 * that stand inside an expected value (`expect.any(Number)`).
11639 */
11640 export type Expect = Expecting & Matching;
11641
11642 /**
11643 * Checks a value: `expect(received).toEqual(expected)` throws an
11644 * AssertionError naming both sides when it fails, a message given leading.
11645 *
11646 * `.not` negates; `.resolves` and `.rejects` check what a promise settles
11647 * with; `expect.any(Number)` and its kin stand inside an expected value.
11648 */
11649 export const expect: Expect;
11650
11651 /**
11652 * What `expect(received)` answers: the checks, their negation, and the
11653 * checks on what a promise received resolves or rejects with.
11654 */
11655 export type Expectation = Negatable<Matchers> & {
11656 /**
11657 * The checks on what the promise received resolves with; a rejection
11658 * fails them.
11659 */
11660 resolves: Negatable<AsyncMatchers>;
11661 /**
11662 * The checks on what the promise received rejects with; a resolution
11663 * fails them.
11664 */
11665 rejects: Negatable<AsyncMatchers>;
11666 };
11667
11668 /**
11669 * `expect(received, message?)`: the checks on a value, a message of the
11670 * test's own leading a failure's.
11671 */
11672 export type Expecting = (received: unknown, message?: string) => Expectation;
11673
11674 /**
11675 * One element of a mounted drawing as `find` returns it: the description
11676 * the plugin's hook (or a `Client`'s module) built, read as plain data.
11677 *
11678 * What every surface is handed to draw, not what any surface painted: the
11679 * same on the terminal, the desktop, VS Code and mobile.
11680 */
11681 export type FoundElement = {
11682 /**
11683 * The element's tag: `Box`, `Text`, `Button`, `Input`, `Client`, ...
11684 */
11685 type: string;
11686 /**
11687 * What its props carry as `key`, when they do.
11688 */
11689 key: string | undefined;
11690 /**
11691 * Its props, plain data: a Button's `label`, a Text's `color`, ...;
11692 * handlers never cross (a Button's `onPress` is not here).
11693 */
11694 props: Record<string, unknown>;
11695 /**
11696 * What it shows: its string children in document order and, for the
11697 * leaves that draw a prop as text, that prop (ElementQuery `text`).
11698 */
11699 text: string;
11700 /**
11701 * Its children as drawn: strings and element descriptions.
11702 */
11703 children: unknown[];
11704 };
11705
11706 /**
11707 * The checks `expect(received)` offers; each throws an AssertionError when
11708 * it fails, naming what was expected and what was received.
11709 */
11710 export type Matchers = {
11711 /**
11712 * Passes when received is the value, by `Object.is`.
11713 *
11714 * @param expected the value
11715 */
11716 toBe: (expected: unknown) => void;
11717 /**
11718 * Passes when received equals the value in structure, properties holding
11719 * undefined ignored; `expect.any` and its kin match inside it.
11720 *
11721 * @param expected the value
11722 */
11723 toEqual: (expected: unknown) => void;
11724 /**
11725 * As `toEqual`, but undefined properties and prototypes count.
11726 *
11727 * @param expected the value
11728 */
11729 toStrictEqual: (expected: unknown) => void;
11730 /**
11731 * Passes when received holds at least the object's properties, equal.
11732 *
11733 * @param expected the object
11734 */
11735 toMatchObject: (expected: object) => void;
11736 /**
11737 * Passes when a string received includes the item, or an iterable
11738 * received has an element that is it.
11739 *
11740 * @param item the substring or element
11741 */
11742 toContain: (item: unknown) => void;
11743 /**
11744 * Passes when an iterable received has an element equal to the item.
11745 *
11746 * @param item the element
11747 */
11748 toContainEqual: (item: unknown) => void;
11749 /**
11750 * Passes when received's `length` is the number.
11751 *
11752 * @param length the number
11753 */
11754 toHaveLength: (length: number) => void;
11755 /**
11756 * Passes when received holds a property at the path (`a.b`, or the keys
11757 * in order), equal to the value when one is given.
11758 *
11759 * @param path the property's path
11760 * @param value what it must equal, when given
11761 */
11762 toHaveProperty: (path: string | readonly string[], value?: unknown) => void;
11763 /**
11764 * Passes when received is undefined.
11765 */
11766 toBeUndefined: () => void;
11767 /**
11768 * Passes when received is anything but undefined.
11769 */
11770 toBeDefined: () => void;
11771 /**
11772 * Passes when received is null.
11773 */
11774 toBeNull: () => void;
11775 /**
11776 * Passes when received is truthy.
11777 */
11778 toBeTruthy: () => void;
11779 /**
11780 * Passes when received is falsy.
11781 */
11782 toBeFalsy: () => void;
11783 /**
11784 * Passes when received is NaN.
11785 */
11786 toBeNaN: () => void;
11787 /**
11788 * Passes when received is greater than the bound.
11789 *
11790 * @param bound the bound
11791 */
11792 toBeGreaterThan: (bound: number | bigint) => void;
11793 /**
11794 * Passes when received is the bound or greater.
11795 *
11796 * @param bound the bound
11797 */
11798 toBeGreaterThanOrEqual: (bound: number | bigint) => void;
11799 /**
11800 * Passes when received is less than the bound.
11801 *
11802 * @param bound the bound
11803 */
11804 toBeLessThan: (bound: number | bigint) => void;
11805 /**
11806 * Passes when received is the bound or less.
11807 *
11808 * @param bound the bound
11809 */
11810 toBeLessThanOrEqual: (bound: number | bigint) => void;
11811 /**
11812 * Passes when a string received includes the text, or the pattern matches
11813 * it.
11814 *
11815 * @param pattern the text or pattern
11816 */
11817 toMatch: (pattern: string | RegExp) => void;
11818 /**
11819 * Passes when a string received starts with the prefix.
11820 *
11821 * @param prefix the prefix
11822 */
11823 toStartWith: (prefix: string) => void;
11824 /**
11825 * Passes when a string received ends with the suffix.
11826 *
11827 * @param suffix the suffix
11828 */
11829 toEndWith: (suffix: string) => void;
11830 /**
11831 * Passes when received is an instance of the class.
11832 *
11833 * @param expected the class
11834 */
11835 toBeInstanceOf: (expected: Constructor) => void;
11836 /**
11837 * Passes when calling received throws (or, under `rejects`, the rejection
11838 * is) an error as described: by substring, pattern, class or message.
11839 *
11840 * @param expected the description; any throw passes without one
11841 */
11842 toThrow: (expected?: ThrowExpectation) => void;
11843 };
11844
11845 /**
11846 * The matchers that stand inside an expected value, each matching received
11847 * there by a rule instead of by equality.
11848 */
11849 export type Matching = {
11850 /**
11851 * Matches any instance of the class, a primitive by its wrapper
11852 * (`expect.any(Number)`).
11853 *
11854 * @param expected the class
11855 * @returns the matcher
11856 */
11857 any: (expected: Constructor) => AsymmetricMatcher;
11858 /**
11859 * Matches anything but null and undefined.
11860 *
11861 * @returns the matcher
11862 */
11863 anything: () => AsymmetricMatcher;
11864 /**
11865 * Matches a string that includes the text.
11866 *
11867 * @param text the substring
11868 * @returns the matcher
11869 */
11870 stringContaining: (text: string) => AsymmetricMatcher;
11871 /**
11872 * Matches a string the pattern matches.
11873 *
11874 * @param pattern the pattern, or the source of one
11875 * @returns the matcher
11876 */
11877 stringMatching: (pattern: string | RegExp) => AsymmetricMatcher;
11878 /**
11879 * Matches an object holding at least the shape's properties, equal.
11880 *
11881 * @param shape the properties
11882 * @returns the matcher
11883 */
11884 objectContaining: (shape: object) => AsymmetricMatcher;
11885 /**
11886 * Matches an array holding an element equal to each of the items.
11887 *
11888 * @param items the elements
11889 * @returns the matcher
11890 */
11891 arrayContaining: (items: readonly unknown[]) => AsymmetricMatcher;
11892 };
11893
11894 /**
11895 * The world beneath the plugins, mocked noun by noun: each member registers
11896 * hooks of the test's on `on`, visible where the test calls it.
11897 */
11898 export type Mock = {
11899 /**
11900 * Answers `$.clock` from a clock in memory that moves only when the test
11901 * moves it: `clock.now` reads it, and each wait is held.
11902 *
11903 * A held wait resolves when an advance crosses the time it is due, and is
11904 * dropped when its dispatch aborts; one held past a hook's budget (ten
11905 * seconds of real time) is let go, as a hook that overran.
11906 *
11907 * @param on the test's `on`
11908 * @param options where the clock starts (`now`, 0 when not given)
11909 * @returns the clock: its time, and the calls that move it
11910 */
11911 clock: (on: On, options?: MockClockOptions) => MockClock;
11912 /**
11913 * Answers `$.store` from a store in memory: `get`, `set`, `delete` and
11914 * `keys` over it, as the engine keeps a plugin's own.
11915 *
11916 * @param on the test's `on`
11917 * @param entries what the store holds at the start (nothing when not given)
11918 */
11919 store: (on: On, entries?: Readonly<Record<string, unknown>>) => void;
11920 /**
11921 * Answers `$.env.get` from a set of variables; one not listed is unset.
11922 *
11923 * @param on the test's `on`
11924 * @param variables the environment the plugins read
11925 */
11926 env: (on: On, variables: Readonly<Record<string, string>>) => void;
11927 };
11928
11929 /**
11930 * The world beneath the plugins, mocked noun by noun: `mock.clock`,
11931 * `mock.store` and `mock.env`.
11932 *
11933 * Each registers hooks of the test's on the `on` it is handed, visible where
11934 * the test calls it, and answers its noun from memory.
11935 */
11936 export const mock: Mock;
11937
11938 /**
11939 * The clock `mock.clock` hands back: the time its hooks answer, and the only
11940 * ways it moves.
11941 */
11942 export type MockClock = {
11943 /**
11944 * The time now, in milliseconds: what `$.clock.now()` resolves beneath the
11945 * plugins.
11946 *
11947 * @returns the time
11948 */
11949 now: () => number;
11950 /**
11951 * Moves the clock on, resolving each wait due on the way (`$.clock.sleep`,
11952 * `after`, `every`, this clock's `sleep`) in the order it comes due.
11953 *
11954 * The clock reads each wait's time as it resolves, and what one started
11955 * runs before the next resolves.
11956 *
11957 * @param ms how far to move, in milliseconds
11958 * @returns resolves once the clock is there and the event loop settled
11959 */
11960 advance: (ms: number) => Promise<void>;
11961 /**
11962 * Moves the clock to a time at or past now, as `advance` would.
11963 *
11964 * @param ms the time, in milliseconds
11965 * @returns resolves once the clock is there and the event loop settled
11966 */
11967 set: (ms: number) => Promise<void>;
11968 /**
11969 * Lets what is already under way run as far as it can without the clock
11970 * moving: every wait due now resolves and the event loop settles.
11971 *
11972 * The same as `advance(0)`; the name for the step between starting a
11973 * dispatch unawaited and looking at what it did.
11974 *
11975 * @returns resolves once the event loop settled, the time where it was
11976 */
11977 settle: () => Promise<void>;
11978 /**
11979 * Resolves once the clock has moved this far past now: how a hook of the
11980 * test's answers late.
11981 *
11982 * @param ms how far, in milliseconds
11983 * @returns resolves when an advance crosses that time
11984 */
11985 sleep: (ms: number) => Promise<void>;
11986 };
11987
11988 /**
11989 * Where a mocked clock starts: `now`, in milliseconds (0 when not given).
11990 */
11991 export type MockClockOptions = {
11992 now?: number;
11993 };
11994
11995 /**
11996 * A drawing of component `C` the test mounted on surface `P`: reads over its
11997 * description, acts on its elements by key, `Client` acts where `P` has one.
11998 *
11999 * Narrowed by the `surface` the test passed, as `e.surface` narrows
12000 * `$.ui.resolve(e)`: no `input` on `mobile`, no `key` on `vscode`, whose
12001 * tables (Elements) lack `Input` and `Client`; over a union, their meet.
12002 */
12003 export type Mounted<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
12004 [K in keyof MountedMembers<P, C> as K extends keyof ElementOfAct ? ElementOfAct[K] extends keyof Elements[P] ? K : never : K]: MountedMembers<P, C>[K];
12005 };
12006
12007 /**
12008 * Every member a mounted drawing of component `C` can have; `Mounted<P, C>`
12009 * keeps the ones surface `P` has the element for (ElementOfAct).
12010 *
12011 * Each act resolves once the loop settled and what a plugin invalidated
12012 * was drawn again. The kit exercises the mod (its hooks, its description
12013 * under the surface's rules, its `Client` modules), never a surface's paint.
12014 */
12015 export type MountedMembers<P extends RenderSurface, C extends RenderComponent = RenderComponent> = {
12016 /**
12017 * Where this drawing is, as the test named it.
12018 */
12019 readonly surface: P;
12020 /**
12021 * The tree as last drawn: what the plugins' `ui.render` chain returned
12022 * for this instance, validated by the surface's table, as plain data.
12023 *
12024 * With `in`, what that `Client`'s surface module last drew instead.
12025 *
12026 * @param scope `{ in }`: a `Client`'s key, to read its module's tree
12027 * @returns the tree; rejects with the refusal when the surface could not
12028 * draw what the chain returned, or with a `Client`'s fault line
12029 * @example
12030 * expect(await ui.drawn()).toMatchObject({ type: 'Box' })
12031 */
12032 drawn: (scope?: ClientScope) => Promise<RenderElement>;
12033 /**
12034 * The first element matching the query, outermost first in document
12035 * order, or undefined.
12036 *
12037 * @param query tag, key and shown text to match; `in` to search a Client
12038 * @returns the element's description, or undefined when none matches
12039 * @example
12040 * expect((await ui.find({ key: 'count' }))?.text).toBe('3 notes')
12041 */
12042 find: (query: ElementQuery) => Promise<FoundElement | undefined>;
12043 /**
12044 * Every element matching the query, in document order.
12045 *
12046 * @param query tag, key and shown text to match; `in` to search a Client
12047 * @returns the matching elements' descriptions
12048 * @example
12049 * expect(await ui.findAll({ type: 'Button' })).toHaveLength(2)
12050 */
12051 findAll: (query: ElementQuery) => Promise<FoundElement[]>;
12052 /**
12053 * Presses the Button keyed `key`, as the person activating it on this
12054 * surface does: the `ui.press` chain, the Button's own `onPress` last.
12055 *
12056 * `e.surface` is this drawing's. With `link`, presses that link of the
12057 * Markdown keyed `key` instead. A Button a `Client`'s module drew is
12058 * pressed the same way, by its key.
12059 *
12060 * @param target the key; another plugin's name to press its Button; a link
12061 * @returns what the chain settled on
12062 * @example
12063 * await ui.press({ key: 'save' })
12064 */
12065 press: (target: MountPressTarget) => Promise<UiPressResult | undefined>;
12066 /**
12067 * Types into the Input keyed `key`: the `ui.input` chain with the text as
12068 * `e.value`, the Input's own handler last.
12069 *
12070 * `kind` `submit` (the default) is Enter with that text, `change` an edit
12071 * that leaves it in the field.
12072 *
12073 * @param target the key and the text; `kind`; another plugin's name
12074 * @returns what the chain settled on
12075 * @example
12076 * await ui.input({ key: 'title', text: 'groceries' })
12077 */
12078 input: (target: MountInputTarget) => Promise<UiInputResult | undefined>;
12079 /**
12080 * Picks `value` in the Select keyed `key`: the `ui.select` chain, the
12081 * Select's own `onSelect` last.
12082 *
12083 * @param target the key and the option's value; another plugin's name
12084 * @returns what the chain settled on
12085 * @example
12086 * await ui.select({ key: 'sort', value: 'date' })
12087 */
12088 select: (target: MountSelectTarget) => Promise<UiSelectResult | undefined>;
12089 /**
12090 * Hands a `Client`'s `onKey` listener one key, as a key pressed while
12091 * its region has the focus does.
12092 *
12093 * `in` names the `Client` by key; optional when the drawing holds one.
12094 *
12095 * @param event the key (`{ key: 'right' }`, `{ key: 'a', ctrl: true }`)
12096 * @example
12097 * await ui.key({ key: 'return', in: 'board' })
12098 */
12099 key: (event: MountKeyEvent) => Promise<void>;
12100 /**
12101 * Hands a `Client`'s `onPointer` listener one event, in the cells of its
12102 * region as every surface that draws a `Client` reports them.
12103 *
12104 * @param event the event (`{ type: 'down', x: 3, y: 0, button: 'left' }`)
12105 * @example
12106 * await ui.pointer({ type: 'down', x: 2, y: 0, button: 'left' })
12107 */
12108 pointer: (event: MountPointerEvent) => Promise<void>;
12109 /**
12110 * Posts as a `Client`'s own `surface.post(data)` does: the plugin's
12111 * `ui.message` hooks run with `e.data`, `e.surface` this drawing's.
12112 *
12113 * A `{ props }` they answer reaches the instance, which redraws with
12114 * its state kept.
12115 *
12116 * @param data plain data (JsonValue)
12117 * @param scope `{ in }`: which `Client`, when the drawing holds several
12118 * @example
12119 * await ui.post({ pick: 2 })
12120 */
12121 post: (data: JsonValue, scope?: ClientScope) => Promise<void>;
12122 /**
12123 * Moves the drawing's frame clock on: each `surface.every(ms, fn)` timer
12124 * of its `Client`s fires at every interval of its own the move crosses.
12125 *
12126 * @param ms how far, in milliseconds
12127 * @example
12128 * await ui.advance(250)
12129 */
12130 advance: (ms: number) => Promise<void>;
12131 /**
12132 * Lays a `Client`'s region out at a size, as the surface measuring it
12133 * does: what its module reads as `surface.columns` and `surface.rows`.
12134 *
12135 * @param size cells across and down; `in`: which `Client`
12136 * @example
12137 * await ui.resize({ columns: 40, rows: 3 })
12138 */
12139 resize: (size: MountResizeTarget) => Promise<void>;
12140 /**
12141 * Draws the instance again, as the engine does when its props change (a
12142 * tool row's output arrived): the `ui.render` chain with the next props.
12143 *
12144 * A plugin's own `$.ui.invalidate` needs no call: the drawing follows it
12145 * before the next read.
12146 *
12147 * @param props the component's next props; the current ones when absent
12148 * @example
12149 * await ui.redraw({ ...TOOL_ROW, isRunning: false, output: 'done' })
12150 */
12151 redraw: (props?: RenderPropsOf[C]) => Promise<void>;
12152 /**
12153 * Lets the drawing go, as the surface dropping the instance does: its
12154 * `Client`s and their timers end. Later acts on the handle reject.
12155 *
12156 * @example
12157 * await ui.unmount()
12158 */
12159 unmount: () => Promise<void>;
12160 };
12161
12162 /**
12163 * What a mounted drawing's `input` takes: the Input's key, the text, which
12164 * of the two inputs it is (`submit` when unsaid), another plugin's name.
12165 */
12166 export type MountInputTarget = {
12167 key: string;
12168 text: string;
12169 kind?: UiInputArgument['kind'];
12170 plugin?: string;
12171 };
12172
12173 /**
12174 * What a mounted drawing's `key` takes: the key as a `Client`'s `onKey`
12175 * listener receives it (ClientKeyEvent), and which `Client` when several.
12176 */
12177 export type MountKeyEvent = ClientKeyEvent & ClientScope;
12178
12179 /**
12180 * What a mounted drawing's `pointer` takes: the event as a `Client`'s
12181 * `onPointer` listener receives it, in its region's cells, and which one.
12182 */
12183 export type MountPointerEvent = ClientPointerEvent & ClientScope;
12184
12185 /**
12186 * What a mounted drawing's `press` takes: the Button's key, another
12187 * plugin's name when the Button is not the mounted plugin's, a link.
12188 */
12189 export type MountPressTarget = {
12190 key: string;
12191 plugin?: string;
12192 /**
12193 * Presses this link of the Markdown keyed `key` instead of a Button.
12194 */
12195 link?: PressedLink;
12196 };
12197
12198 /**
12199 * What a mounted drawing's `resize` takes: a `Client` region's size in
12200 * cells, as the surface measuring it hands it, and which `Client`.
12201 */
12202 export type MountResizeTarget = {
12203 columns: number;
12204 rows: number;
12205 in?: string;
12206 };
12207
12208 /**
12209 * What a mounted drawing's `select` takes: the Select's key, the picked
12210 * option's value, another plugin's name when the Select is not its own.
12211 */
12212 export type MountSelectTarget = {
12213 key: string;
12214 value: string;
12215 plugin?: string;
12216 };
12217
12218 /**
12219 * What `$.ui.mount` takes: whose elements the test will act on, the surface
12220 * that draws, and the component instance the engine asks the plugins for.
12221 *
12222 * The envelope a `ui.render` hook sees as `e` (`surface`, `component`,
12223 * `requestId`, `viewport`, `props`) plus `plugin`. `surface` is never
12224 * defaulted: one body run over several surfaces is what shows independence.
12225 *
12226 * @example
12227 * $.ui.mount({ plugin: 'notes', surface, component: 'Pane', props: PANE })
12228 */
12229 export type MountTarget<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
12230 /**
12231 * Whose elements the handle's acts address by bare `key`: the plugin
12232 * under test, usually. An act names another plugin to reach its element.
12233 */
12234 plugin: string;
12235 /**
12236 * What draws: its element table validates every tree the plugins
12237 * return, and every dispatch the handle raises carries it as `e.surface`.
12238 *
12239 * One of `terminal`, `desktop`, `vscode`, `mobile`.
12240 */
12241 surface: P;
12242 /**
12243 * Which component the engine asks the plugins to draw (`Pane`,
12244 * `AbovePrompt`, `ToolUse`, ...): what a `ui.render` matcher narrows on.
12245 */
12246 component: C;
12247 /**
12248 * The component's props, what the hook reads as `e.props`.
12249 */
12250 props: RenderPropsOf[C];
12251 /**
12252 * The instance drawn (a pane's id, a tool row's tool_use_id); one is
12253 * minted when absent. Two mounts of one component are two instances.
12254 */
12255 requestId?: string;
12256 /**
12257 * What the surface measured, as the hook reads it under `e.viewport`;
12258 * absent when the surface has not measured, as on `e`.
12259 *
12260 * Cells across and down in the surface's monospace metric and whether it
12261 * docks a pane. A `Client` in the drawing starts laid out at this size
12262 * (0 by 0 when absent) until the handle's `resize` lays its region out.
12263 */
12264 viewport?: RenderViewport;
12265 };
12266
12267 /**
12268 * A set of checks and, under `not`, the same set passing where they fail.
12269 */
12270 export type Negatable<M> = M & {
12271 /**
12272 * The checks negated.
12273 */
12274 not: M;
12275 };
12276
12277 /**
12278 * Written inline in a test and loaded as a plugin folder is: its name, the
12279 * tier it loads in (`user` when not given), and its hooks module's `register`.
12280 *
12281 * `register` is written `register(on) { ... }` and is self-contained, as a
12282 * module's is: it closes over nothing of the test file.
12283 */
12284 export type Plugin = {
12285 name: string;
12286 tier?: PluginTier;
12287 register: Register;
12288 };
12289
12290 /**
12291 * A tier a plugin loads in: every tier but the engine's own.
12292 */
12293 export type PluginTier = Exclude<Tier, 'core'>;
12294
12295 /**
12296 * What `$.ui.press` takes: the plugin whose `ui.render` hook drew the element,
12297 * the `key` it gave it, the instance and surface when several, a `link`.
12298 */
12299 export type PressTarget = {
12300 plugin: string;
12301 key: string;
12302 /**
12303 * Which instance holds it, when the plugin drew the key in several.
12304 */
12305 requestId?: string;
12306 /**
12307 * Which surface's drawing, when the key is drawn on more than one; the
12308 * press carries the surface of the drawing it lands in either way.
12309 */
12310 surface?: RenderSurface;
12311 /**
12312 * For a Markdown answering its links: which of them the press lands on.
12313 */
12314 link?: PressedLink;
12315 };
12316
12317 /**
12318 * One test: it passes when its body returns or resolves, and fails when it
12319 * throws, rejects or outlasts its time (5000 ms, or `timeoutMs`).
12320 *
12321 * The body gets the engine's `$` and an `on` whose hooks sit beneath every
12322 * plugin; `plugins` load inline plugins beside the one under test. A failure
12323 * carries what the engine reported meanwhile: each hook it skipped, and why.
12324 *
12325 * @param name the test's name, led in its title by the describes around it
12326 * @param rest the body, `($, on) => ...`, or the options then the body
12327 */
12328 export const test: (name: string, ...rest: TestRest) => void;
12329
12330 /**
12331 * A test: the engine's `$`, and `on`, a plugin's registrar, whose hooks sit
12332 * beneath every plugin; beneath them the bottom hook throws, naming its event.
12333 *
12334 * The plugins load at the test's first call on `$`, so a test registers its
12335 * hooks before it, as a module registers its own in `register()`.
12336 */
12337 export type TestBody = ($: Engine, on: On) => unknown;
12338
12339 /**
12340 * What `test` takes beside its name: the inline plugins it loads beside the
12341 * one under test, and how long it may run (5000 ms when not given).
12342 */
12343 export type TestOptions = {
12344 plugins?: readonly Plugin[];
12345 timeoutMs?: number;
12346 };
12347
12348 /**
12349 * What follows a test's name: its body, or its options then its body.
12350 */
12351 export type TestRest = readonly [body: TestBody] | readonly [options: TestOptions, body: TestBody];
12352
12353 /**
12354 * What `toThrow` compares the thrown error with: a substring or pattern of
12355 * its message, its class, a value carrying the whole message, or nothing.
12356 */
12357 export type ThrowExpectation = string | RegExp | Constructor | WithMessage;
12358
12359 /**
12360 * Says which tier the plugin under test loads in, once, at the top of the
12361 * file: `prepend`, `user` (when unsaid), `append` or `builtin`.
12362 *
12363 * @param tier the tier
12364 */
12365 export const tier: (tier: PluginTier) => void;
12366
12367 /**
12368 * An error-like value `toThrow` compares by its whole message.
12369 */
12370 export type WithMessage = {
12371 message: string;
12372 };
12373}
12374
12375// The inputs of the built-in tools this build has, from each tool's
12376// input schema. Merges into ToolCallInput (BuiltinToolInputs) so
12377// `e.tool === "Bash"` narrows to the tool's arguments.
12378declare module 'claude-code' {
12379 interface BuiltinToolInputs {
12380 Agent: {
12381 /** A short (3-5 word) description of the task */
12382 description: string
12383 /** The task for the agent to perform */
12384 prompt: string
12385 /** The type of specialized agent to use for this task */
12386 subagent_type?: string
12387 /** Optional model override for this agent. Takes precedence over the agent definition's model frontmatter and the configured default subagent model. If omitted, uses the agent definition's model, else the default (inherits from the parent unless a default subagent model is configured). Ignored for subagent_type: "fork" — forks always inherit the parent model. */
12388 model?: "sonnet" | "opus" | "haiku" | "fable"
12389 /** Agents run in the background by default; you will be notified when one completes. Set to false only when your very next action depends on this agent's result and nothing else could usefully happen while it runs — otherwise leave it in the background so the user can hand you other work. */
12390 run_in_background?: boolean
12391 /** Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running. */
12392 name?: string
12393 /** Deprecated; ignored. The session has a single implicit team. */
12394 team_name?: string
12395 /** Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it. */
12396 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"
12397 /** Isolation mode. "worktree" creates a temporary git worktree so the agent works on an isolated copy of the repo. "remote" launches the agent in a remote cloud environment (always runs in background; availability is gated). */
12398 isolation?: "worktree" | "remote"
12399 }
12400 Bash: {
12401 /** The command to execute */
12402 command: string
12403 /** Optional timeout in milliseconds (max 600000) */
12404 timeout?: number
12405 /** Clear, concise description of what this command does in active voice. Never use words like "complex" or "risk" in the description - just describe what it does. Say what the command does in plain words: do not echo the command's text, its flags, or file paths - the user reads this description, often without seeing the command. For simple commands (git, npm, standard CLI tools), keep it brief (5-10 words): - ls → "List files in current directory" - git status → "Show working tree status" - npm install → "Install package dependencies" For commands that are harder to parse at a glance (piped commands, obscure flags, etc.), add enough context to clarify what it does: - find . -name "*.tmp" -exec rm {} \; → "Find and delete all .tmp files recursively" - git reset --hard origin/main → "Discard all local changes and match remote main" - curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements" */
12406 description?: string
12407 /** Set to true to run this command in the background. */
12408 run_in_background?: boolean
12409 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
12410 dangerouslyDisableSandbox?: boolean
12411 }
12412 CronCreate: {
12413 /** Standard 5-field cron expression in local time: "M H DoM Mon DoW" (e.g. "* /5 * * * *" = every 5 minutes, "30 14 28 2 *" = Feb 28 at 2:30pm local once). */
12414 cron: string
12415 /** The prompt to enqueue at each fire time. */
12416 prompt: string
12417 /** true (default) = fire on every cron match until deleted or auto-expired after 7 days. false = fire once at the next match, then auto-delete. Use false for "remind me at X" one-shot requests with pinned minute/hour/dom/month. */
12418 recurring?: boolean
12419 /** true = persist to .claude/scheduled_tasks.json and survive restarts. false (default) = in-memory only, dies when this Claude session ends. Use true only when the user asks the task to survive across sessions. */
12420 durable?: boolean
12421 }
12422 CronDelete: {
12423 /** Job ID returned by CronCreate. */
12424 id: string
12425 }
12426 CronList: {}
12427 Edit: {
12428 /** The absolute path to the file to modify */
12429 file_path: string
12430 /** The text to replace */
12431 old_string: string
12432 /** The text to replace it with (must be different from old_string) */
12433 new_string: string
12434 /** Replace all occurrences of old_string (default false) */
12435 replace_all?: boolean
12436 }
12437 EnterWorktree: {
12438 /** Optional name for a new worktree. Each "/"-separated segment may contain only letters, digits, dots, underscores, and dashes; max 64 chars total. A random name is generated if not provided. Mutually exclusive with `path`. */
12439 name?: string
12440 /** Path to an existing worktree to switch into instead of creating a new one. Must appear in `git worktree list` for the current repo — or, on first entry from the launch directory, for a repo nested inside it (multi-repo workspace). Mutually exclusive with `name`. */
12441 path?: string
12442 }
12443 ExitWorktree: {
12444 /** "keep" leaves the worktree and branch on disk; "remove" deletes both. */
12445 action: "keep" | "remove"
12446 /** Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise. */
12447 discard_changes?: boolean
12448 }
12449 ListAgents: {
12450 /** Not available in this build; leave unset. */
12451 channel?: string
12452 /** Not available in this build; leave unset. */
12453 q?: string
12454 }
12455 NotebookEdit: {
12456 /** The absolute path to the Jupyter notebook file to edit (must be absolute, not relative) */
12457 notebook_path: string
12458 /** The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified. */
12459 cell_id?: string
12460 /** The new source for the cell */
12461 new_source: string
12462 /** The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required. */
12463 cell_type?: "code" | "markdown"
12464 /** The type of edit to make (replace, insert, delete). Defaults to replace. */
12465 edit_mode?: "replace" | "insert" | "delete"
12466 }
12467 PowerShell: {
12468 /** The PowerShell command to execute */
12469 command: string
12470 /** Optional timeout in milliseconds (max 600000) */
12471 timeout?: number
12472 /** Clear, concise description of what this command does in active voice. */
12473 description?: string
12474 /** Set to true to run this command in the background. */
12475 run_in_background?: boolean
12476 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
12477 dangerouslyDisableSandbox?: boolean
12478 }
12479 Read: {
12480 /** The absolute path to the file to read */
12481 file_path: string
12482 /** The line number to start reading from. Only provide if the file is too large to read at once */
12483 offset?: number
12484 /** The number of lines to read. Only provide if the file is too large to read at once. */
12485 limit?: number
12486 /** Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum 20 pages per request. */
12487 pages?: string
12488 }
12489 ReportFindings: {
12490 /** Effort level the review ran at */
12491 level?: "low" | "medium" | "high" | "xhigh" | "max"
12492 /** Verified findings, most-severe first; empty if none survived */
12493 findings: Array<{
12494 /** Repo-relative path of the file the finding is in */
12495 file: string
12496 /** 1-indexed line the finding anchors to */
12497 line?: number
12498 /** One-sentence statement of the defect */
12499 summary: string
12500 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
12501 short_summary?: string
12502 /** Concrete inputs/state → wrong output/crash */
12503 failure_scenario: string
12504 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
12505 category?: string
12506 /** Set when a verify pass ran; absent on inline-only reviews */
12507 verdict?: "CONFIRMED" | "PLAUSIBLE"
12508 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
12509 outcome?: "fixed" | "skipped" | "no_change_needed"
12510 }>
12511 }
12512 ScheduleWakeup: {
12513 /** Seconds from now to wake up. Clamped to [60, 3600] by the runtime. Required unless `stop` is true. */
12514 delaySeconds?: number
12515 /** One short sentence explaining the chosen delay. Goes to telemetry and is shown to the user. Be specific. Required unless `stop` is true. */
12516 reason?: string
12517 /** The /loop input to fire on wake-up. Pass the same /loop input verbatim each turn so the next firing re-enters the skill and continues the loop. For autonomous /loop (no user prompt), pass the literal sentinel `<<autonomous-loop-dynamic>>` instead (the dynamic-pacing variant, not the CronCreate-mode `<<autonomous-loop>>`). Required unless `stop` is true. */
12518 prompt?: string
12519 /** Set to true to end the dynamic loop immediately instead of scheduling another wakeup. When true, all other fields are ignored and no further wakeups fire. */
12520 stop?: boolean
12521 /** true = nothing changed (you checked and there is nothing to report). false = something happened worth keeping (edited a file, posted a message, advanced state, surfaced a finding). Consecutive noop:true ticks are collapsed in the user's terminal view and tracked as a streak. Required unless `stop` is true. */
12522 noop?: boolean
12523 }
12524 SendMessage: {
12525 /** Recipient: a name from ListAgents (append its " [ref]" only when a listing or an error shows one), a teammate name, "main", or a background agent's agentId */
12526 to: unknown & unknown
12527 /** A 5-10 word label for your own transcript row (not transmitted — the recipient previews the first line of `message`). Truncated to 200 characters rather than rejected. */
12528 summary?: string
12529 /** Plain text message content. The recipient's human sees only the FIRST LINE as a one-line preview until they expand it, so make the first line a clear, self-contained sentence saying what this is about — not a greeting, preamble, or bare @-mention. */
12530 message: string
12531 /** Ask a session ON THIS MACHINE to send you ONE notice when it next goes idle (finishes its turn with nothing queued) or exits — opt-in, one-shot, no polling. With a message: deliver it now AND subscribe. Without a message (omit it): a pure subscription that costs the other session nothing. */
12532 notify_when_idle?: boolean
12533 }
12534 Skill: {
12535 /** The name of a skill from the available-skills list. Do not guess names. */
12536 skill: string
12537 /** Optional arguments for the skill */
12538 args?: string
12539 }
12540 TaskOutput: {
12541 /** The task ID to get output from */
12542 task_id: string
12543 /** Whether to wait for completion */
12544 block: boolean
12545 /** Max wait time in ms */
12546 timeout: number
12547 }
12548 TaskStop: {
12549 /** The ID of the background task to stop. Agent-team teammates and named background agents are also accepted by agent ID or name. */
12550 task_id?: string
12551 /** Deprecated: use task_id instead */
12552 shell_id?: string
12553 }
12554 ToolSearch: {
12555 /** Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search. */
12556 query: string
12557 /** Maximum number of results to return (default: 5) */
12558 max_results: number
12559 }
12560 WebFetch: {
12561 /** The URL to fetch content from */
12562 url: string
12563 /** The prompt to run on the fetched content */
12564 prompt: string
12565 }
12566 WebSearch: {
12567 /** The search query to use */
12568 query: string
12569 /** Only include search results from these domains */
12570 allowed_domains?: string[]
12571 /** Never include search results from these domains */
12572 blocked_domains?: string[]
12573 }
12574 Workflow: {
12575 /** Self-contained workflow script. Must begin with `export const meta = { name, description, phases }` (pure literal, no computed values) followed by the script body using agent()/parallel()/pipeline()/phase(). */
12576 script?: string
12577 /** Name of a predefined workflow (built-in or from .claude/workflows/). Resolves to a self-contained script. */
12578 name?: string
12579 /** Ignored — set the workflow description in the script's `meta` block. */
12580 description?: string
12581 /** Ignored — set the workflow title in the script's `meta` block. */
12582 title?: string
12583 /** Optional input value exposed to the script as the global `args`, verbatim. Pass arrays/objects as actual JSON values, NOT as a JSON-encoded string — a stringified list breaks `args.filter`/`args.map` in the script. Use for parameterized named workflows (e.g. a research question). */
12584 args?: unknown
12585 /** Path to a workflow script file on disk. Every Workflow invocation persists its script under the session directory and returns the path in the tool result. To iterate, edit that file with Write/Edit and re-invoke Workflow with the same `scriptPath` instead of re-sending the full script. Takes precedence over `script` and `name`. */
12586 scriptPath?: string
12587 /** Run ID of a prior Workflow invocation to resume from. Completed agent() calls with unchanged (prompt, opts) return their cached results instantly; only edited or new calls re-run. Same-session only. Stop the prior run first (TaskStop) before resuming. */
12588 resumeFromRunId?: string
12589 }
12590 Write: {
12591 /** The absolute path to the file to write (must be absolute, not relative) */
12592 file_path: string
12593 /** The content to write to the file */
12594 content: string
12595 }
12596 }
12597}
12598
12599// The structured results of the same tools, from each tool's output
12600// schema. Merges into ToolCallResult (BuiltinToolResults) so after
12601// `e.tool === "Bash"` the `result` of `next(e)` is the tool's record.
12602declare module 'claude-code' {
12603 interface BuiltinToolResults {
12604 Agent: {
12605 agentId: string
12606 /** @internal Count of leading harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
12607 harnessNoteCount?: number
12608 /** @internal Count of trailing harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
12609 harnessTailCount?: number
12610 /** @internal Fingerprint binding the harness section counts to the exact content they were computed against; a hook rewrite invalidates the counts rather than misplacing rewritten bytes */
12611 harnessSectionHash?: string
12612 agentType?: string
12613 /** @internal How the report reached this result under the subagent hand-back contract: 'send' = the child's classified SubagentHandback delivery, 'flagged' = that delivery under a SECURITY WARNING, 'withheld' = nothing was delivered (not a stable consumer field) */
12614 handback?: "send" | "flagged" | "withheld"
12615 content: Array<{
12616 type: "text"
12617 text: string
12618 citations?: unknown[] | null
12619 }>
12620 resolvedModel?: string
12621 modelsUsed?: string[]
12622 totalToolUseCount: number
12623 totalDurationMs: number
12624 totalTokens: number
12625 usage: {
12626 input_tokens: number
12627 output_tokens: number
12628 cache_creation_input_tokens: number | null
12629 cache_read_input_tokens: number | null
12630 server_tool_use: {
12631 web_search_requests: number
12632 web_fetch_requests: number
12633 } | null
12634 service_tier: string | null
12635 cache_creation: {
12636 ephemeral_1h_input_tokens: number
12637 ephemeral_5m_input_tokens: number
12638 } | null
12639 inference_geo?: string | null
12640 speed?: string | null
12641 iterations?: unknown
12642 output_tokens_details?: {
12643 thinking_tokens?: number | null
12644 } | null
12645 }
12646 toolStats?: {
12647 readCount: number
12648 searchCount: number
12649 bashCount: number
12650 editFileCount: number
12651 linesAdded: number
12652 linesRemoved: number
12653 otherToolCount: number
12654 frameCount?: number
12655 }
12656 status: "completed"
12657 prompt: string
12658 worktreePath?: string
12659 worktreeBranch?: string
12660 } | {
12661 status: "async_launched"
12662 isAsync?: true
12663 /** The ID of the async agent */
12664 agentId: string
12665 /** The description of the task */
12666 description: string
12667 /** Model in use at the backgrounding transition (a pre-background swap is reflected here) */
12668 resolvedModel?: string
12669 /** Ordered distinct models used before backgrounding (length > 1 means a mid-run swap) */
12670 modelsUsed?: string[]
12671 /** The prompt for the agent */
12672 prompt: string
12673 /** Path to the output file for checking agent progress */
12674 outputFile: string
12675 /** Whether the calling agent has Read/Bash tools to check progress */
12676 canReadOutputFile?: boolean
12677 } | {
12678 status: "remote_launched"
12679 /** The ID of the remote agent task */
12680 taskId: string
12681 /** The URL of the cloud session */
12682 sessionUrl: string
12683 /** The description of the task */
12684 description: string
12685 /** The prompt for the agent */
12686 prompt: string
12687 /** Path to the output file for checking agent progress */
12688 outputFile: string
12689 }
12690 Bash: {
12691 /** The standard output of the command */
12692 stdout: string
12693 /** The standard error output of the command */
12694 stderr: string
12695 /** Path to raw output file for large MCP tool outputs */
12696 rawOutputPath?: string
12697 /** Whether the command was interrupted */
12698 interrupted: boolean
12699 /** Flag to indicate if stdout contains image data */
12700 isImage?: boolean
12701 /** ID of the background task if command is running in background */
12702 backgroundTaskId?: string
12703 /** True if the user manually backgrounded the command with Ctrl+B */
12704 backgroundedByUser?: boolean
12705 /** @internal True if a plugin's turn abort moved the running command to the background */
12706 backgroundedByTurnAbort?: boolean
12707 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
12708 backgroundedToDeliverMessage?: boolean
12709 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
12710 timedOutAfterMs?: number
12711 /** Model-facing note that the session cwd was not changed by a backgrounded command containing a directory-change builtin (cd/pushd/popd/chdir) */
12712 backgroundCwdHint?: string
12713 /** True when this backgrounded command is owned by a synchronous subagent and is therefore terminated when that agent gives its final response; absent when the command survives (main loop, async subagents) */
12714 backgroundEndsWithFinalResponse?: true
12715 /** Flag to indicate if sandbox mode was overridden */
12716 dangerouslyDisableSandbox?: boolean
12717 /** Semantic interpretation for non-error exit codes with special meaning */
12718 returnCodeInterpretation?: string
12719 /** Whether the command is expected to produce no output on success */
12720 noOutputExpected?: boolean
12721 /** Structured content blocks */
12722 structuredContent?: unknown[]
12723 /** Path to the persisted full output in tool-results dir (set when output is too large for inline) */
12724 persistedOutputPath?: string
12725 /** Total size of the output in bytes (set when output is too large for inline) */
12726 persistedOutputSize?: number
12727 /** Model-facing note listing readFileState entries whose mtime bumped during this command (set when WRITE_COMMAND_MARKERS matches) */
12728 staleReadFileStateHint?: string
12729 /** Model-facing system-reminder appended when a gh command reports a GitHub API rate-limit error */
12730 ghRateLimitHint?: string
12731 /** Structured classification of git/gh operations detected in this command (commit/push/merge/rebase/PR). Client-facing — lets clients render git activity without re-parsing stdout; not surfaced to the model. */
12732 gitOperation?: {
12733 commit?: {
12734 sha: string
12735 kind: "committed" | "amended" | "cherry-picked"
12736 branch?: string
12737 }
12738 push?: {
12739 branch: string
12740 }
12741 branch?: {
12742 ref: string
12743 action: "merged" | "rebased"
12744 }
12745 pr?: {
12746 number: number
12747 url?: string
12748 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
12749 }
12750 }
12751 /** @internal Per-file diff of the working-tree changes this command made, for rendering and for PostToolUse Bash hooks (changedFiles: absolute paths of every changed file known, shown or not, at most 200; cut when shorter than files.length + moreFiles); not surfaced to the model. */
12752 bashEditDiff?: {
12753 files: {
12754 filePath: string
12755 hunks: {
12756 oldStart: number
12757 oldLines: number
12758 newStart: number
12759 newLines: number
12760 lines: string[]
12761 }[]
12762 created?: true
12763 deleted?: true
12764 }[]
12765 moreFiles: number
12766 changedFiles?: string[]
12767 unavailable?: true
12768 skipped?: true
12769 shared?: true
12770 }
12771 }
12772 CronCreate: {
12773 id: string
12774 humanSchedule: string
12775 recurring: boolean
12776 durable?: boolean
12777 }
12778 CronDelete: {
12779 id: string
12780 }
12781 CronList: {
12782 jobs: {
12783 id: string
12784 cron: string
12785 humanSchedule: string
12786 prompt: string
12787 recurring?: boolean
12788 durable?: boolean
12789 }[]
12790 }
12791 Edit: {
12792 /** The file path that was edited */
12793 filePath: string
12794 /** The original string that was replaced */
12795 oldString: string
12796 /** The new string that replaced it */
12797 newString: string
12798 /** The original file contents before editing */
12799 originalFile: string | null
12800 /** Diff patch showing the changes */
12801 structuredPatch: {
12802 oldStart: number
12803 oldLines: number
12804 newStart: number
12805 newLines: number
12806 lines: string[]
12807 }[]
12808 /** Whether the user modified the proposed changes */
12809 userModified: boolean
12810 /** Whether all occurrences were replaced */
12811 replaceAll: boolean
12812 gitDiff?: {
12813 filename: string
12814 status: "modified" | "added"
12815 additions: number
12816 deletions: number
12817 changes: number
12818 patch: string
12819 /** GitHub owner/repo when available */
12820 repository?: string | null
12821 }
12822 /** True when the edit was held for the machine owner to review instead of written; the file is unchanged */
12823 staged?: boolean
12824 }
12825 EnterWorktree: {
12826 worktreePath: string
12827 worktreeBranch?: string
12828 message: string
12829 }
12830 ExitWorktree: {
12831 action: "keep" | "remove"
12832 originalCwd: string
12833 worktreePath: string
12834 worktreeBranch?: string
12835 tmuxSessionName?: string
12836 discardedFiles?: number
12837 discardedCommits?: number
12838 message: string
12839 }
12840 ListAgents: {
12841 /** Formatted list of reachable agents */
12842 listing: string
12843 }
12844 NotebookEdit: {
12845 /** The new source code that was written to the cell */
12846 new_source: string
12847 /** The previous cell source (replace/delete only). Enables cell-relative diff rendering without re-reading the notebook. */
12848 old_source?: string
12849 /** The ID of the cell that was edited */
12850 cell_id?: string
12851 /** The type of the cell */
12852 cell_type: "code" | "markdown"
12853 /** The programming language of the notebook */
12854 language: string
12855 /** The edit mode that was used */
12856 edit_mode: string
12857 /** Error message if the operation failed */
12858 error?: string
12859 /** The path to the notebook file */
12860 notebook_path: string
12861 /** The original notebook content before modification */
12862 original_file: string
12863 /** The updated notebook content after modification */
12864 updated_file: string
12865 }
12866 PowerShell: {
12867 /** The standard output of the command */
12868 stdout: string
12869 /** The standard error output of the command */
12870 stderr: string
12871 /** Whether the command was interrupted */
12872 interrupted: boolean
12873 /** Semantic interpretation for non-error exit codes with special meaning */
12874 returnCodeInterpretation?: string
12875 /** Flag to indicate if stdout contains image data */
12876 isImage?: boolean
12877 /** Path to persisted full output when too large for inline */
12878 persistedOutputPath?: string
12879 /** Total output size in bytes when persisted */
12880 persistedOutputSize?: number
12881 /** ID of the background task if command is running in background */
12882 backgroundTaskId?: string
12883 /** True if the user manually backgrounded the command with Ctrl+B */
12884 backgroundedByUser?: boolean
12885 /** @internal True if a plugin's turn abort moved the running command to the background */
12886 backgroundedByTurnAbort?: boolean
12887 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
12888 backgroundedToDeliverMessage?: boolean
12889 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
12890 timedOutAfterMs?: number
12891 /** True when this backgrounded command is owned by a synchronous subagent and is therefore terminated when that agent gives its final response; absent when the command survives (main loop, async subagents) */
12892 backgroundEndsWithFinalResponse?: true
12893 /** Structured classification of git/gh operations detected in this command (commit/push/merge/rebase/PR). Client-facing — lets clients render git activity without re-parsing stdout; not surfaced to the model. */
12894 gitOperation?: {
12895 commit?: {
12896 sha: string
12897 kind: "committed" | "amended" | "cherry-picked"
12898 branch?: string
12899 }
12900 push?: {
12901 branch: string
12902 }
12903 branch?: {
12904 ref: string
12905 action: "merged" | "rebased"
12906 }
12907 pr?: {
12908 number: number
12909 url?: string
12910 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
12911 }
12912 }
12913 }
12914 Read: {
12915 type: "text"
12916 file: {
12917 /** The path to the file that was read */
12918 filePath: string
12919 /** The content of the file */
12920 content: string
12921 /** Number of lines in the returned content */
12922 numLines: number
12923 /** The starting line number */
12924 startLine: number
12925 /** Total number of lines in the file */
12926 totalLines: number
12927 /** True when a whole-file read was auto-paginated because it exceeded the token cap (the content is a partial first page). A programmatic signal for internal consumers; survives output reconstruction (unlike the render-time banner). */
12928 truncatedByTokenCap?: boolean
12929 }
12930 /** Set when this Read completed a saved Artifact source file: the Artifact and the version of it that now counts as viewed. */
12931 artifactRead?: {
12932 slug: string
12933 ver: string
12934 }
12935 } | {
12936 type: "image"
12937 file: {
12938 /** Base64-encoded image data */
12939 base64: string
12940 /** The MIME type of the image */
12941 type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
12942 /** Original file size in bytes */
12943 originalSize: number
12944 /** Image dimension info for coordinate mapping */
12945 dimensions?: {
12946 /** Original image width in pixels */
12947 originalWidth?: number
12948 /** Original image height in pixels */
12949 originalHeight?: number
12950 /** Displayed image width in pixels (after resizing) */
12951 displayWidth?: number
12952 /** Displayed image height in pixels (after resizing) */
12953 displayHeight?: number
12954 }
12955 }
12956 } | {
12957 type: "notebook"
12958 file: {
12959 /** The path to the notebook file */
12960 filePath: string
12961 /** Array of notebook cells */
12962 cells: unknown[]
12963 }
12964 } | {
12965 type: "pdf"
12966 file: {
12967 /** The path to the PDF file */
12968 filePath: string
12969 /** Base64-encoded PDF data */
12970 base64: string
12971 /** Original file size in bytes */
12972 originalSize: number
12973 }
12974 } | {
12975 type: "parts"
12976 file: {
12977 /** The path to the PDF file */
12978 filePath: string
12979 /** Original file size in bytes */
12980 originalSize: number
12981 /** Number of pages extracted */
12982 count: number
12983 /** Directory containing extracted page images */
12984 outputDir: string
12985 }
12986 /** Document page number of the first extracted page (1 when no range was requested); labels the page images in the model-facing tool_result */
12987 firstPage?: number
12988 /** Extracted page images, in page order. Present only transiently in-process: the page image bytes are delivered solely as image blocks in the model-facing tool_result content and are not retained on the tool_use_result, so this key is absent on the emitted/persisted result */
12989 pages?: Array<{
12990 /** Base64-encoded page image; empty when the page could not be processed */
12991 base64: string
12992 /** The MIME type of the image */
12993 mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
12994 /** Why the page could not be processed as an image; set only when base64 is empty */
12995 error?: string
12996 }>
12997 } | {
12998 type: "file_unchanged"
12999 file: {
13000 /** The path to the file */
13001 filePath: string
13002 }
13003 /** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result */
13004 source?: "seeded"
13005 }
13006 ReportFindings: {
13007 /** Number of findings reported */
13008 count: number
13009 /** Effort level the review ran at */
13010 level?: "low" | "medium" | "high" | "xhigh" | "max"
13011 /** Echoed for the result body */
13012 findings: Array<{
13013 /** Repo-relative path of the file the finding is in */
13014 file: string
13015 /** 1-indexed line the finding anchors to */
13016 line?: number
13017 /** One-sentence statement of the defect */
13018 summary: string
13019 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
13020 short_summary?: string
13021 /** Concrete inputs/state → wrong output/crash */
13022 failure_scenario: string
13023 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
13024 category?: string
13025 /** Set when a verify pass ran; absent on inline-only reviews */
13026 verdict?: "CONFIRMED" | "PLAUSIBLE"
13027 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
13028 outcome?: "fixed" | "skipped" | "no_change_needed"
13029 }>
13030 }
13031 ScheduleWakeup: {
13032 /** Epoch ms timestamp when the next wakeup will fire */
13033 scheduledFor: number
13034 /** Actual delay used after clamping to runtime bounds */
13035 clampedDelaySeconds: number
13036 /** True if the requested delaySeconds was outside [60, 3600] */
13037 wasClamped: boolean
13038 /** True when the model ended the loop via `stop: true` */
13039 stopped?: boolean
13040 /** How many pending dynamic-loop wakeups stop:true cancelled. 0 means nothing was pending — a recurring /loop cron is not cancelled by stop:true. */
13041 cancelledWakeups?: number
13042 }
13043 SendMessage: unknown
13044 Skill: {
13045 /** Whether the skill is valid */
13046 success: boolean
13047 /** The name of the skill */
13048 commandName: string
13049 /** Tools allowed by this skill */
13050 allowedTools?: string[]
13051 /** Resolved model the skill turn runs on when a frontmatter model override took effect; omitted otherwise */
13052 model?: string
13053 /** Execution status */
13054 status?: "inline"
13055 /** True when the skill instructions were loaded read-only (nothing was executed) */
13056 readOnly?: boolean
13057 } | {
13058 /** Whether the skill completed successfully */
13059 success: boolean
13060 /** The name of the skill */
13061 commandName: string
13062 /** Execution status */
13063 status: "forked"
13064 /** The ID of the sub-agent that executed the skill */
13065 agentId: string
13066 /** The result from the forked skill execution */
13067 result: string
13068 /** True when the sub-agent was launched in the background: `result` describes the launch, and the skill outcome arrives later as a task notification. */
13069 background?: boolean
13070 }
13071 TaskOutput: unknown
13072 TaskStop: {
13073 /** Status message about the operation */
13074 message: string
13075 /** The ID of the task that was stopped */
13076 task_id: string
13077 /** The type of the task that was stopped */
13078 task_type: string
13079 /** The command or description of the stopped task */
13080 command?: string
13081 }
13082 ToolSearch: {
13083 matches: string[]
13084 query: string
13085 total_deferred_tools: number
13086 pending_mcp_servers?: string[]
13087 failed_mcp_servers?: {
13088 name: string
13089 errorCode?: string
13090 error?: string
13091 }[]
13092 }
13093 WebFetch: {
13094 /** Size of the fetched content in bytes */
13095 bytes: number
13096 /** HTTP response code */
13097 code: number
13098 /** HTTP response code text */
13099 codeText: string
13100 /** Processed result from applying the prompt to the content */
13101 result: string
13102 /** Time taken to fetch and process the content */
13103 durationMs: number
13104 /** The URL that was fetched */
13105 url: string
13106 artifactRead?: {
13107 slug: string
13108 ver?: string
13109 seeded?: false
13110 }
13111 }
13112 WebSearch: {
13113 /** The search query that was executed */
13114 query: string
13115 /** Search results and/or text commentary from the model */
13116 results: Array<{
13117 /** ID of the tool use */
13118 tool_use_id: string
13119 /** Array of search hits */
13120 content: Array<{
13121 /** The title of the search result */
13122 title: string
13123 /** The URL of the search result */
13124 url: string
13125 }>
13126 } | string>
13127 /** Time taken to complete the search operation */
13128 durationSeconds: number
13129 /** Number of web searches performed */
13130 searchCount?: number
13131 }
13132 Workflow: {
13133 status: "async_launched" | "remote_launched"
13134 taskId: string
13135 /** TaskType of the registered background task — 'local_workflow' for in-process runs, 'remote_agent' when remote:true dispatches to CCR. Set on all new writes; absent only on transcripts written before this field existed. */
13136 taskType?: "local_workflow" | "remote_agent"
13137 /** meta.name from the workflow script — same value as task_started.workflow_name. Set on all new writes; absent only on transcripts written before this field existed. */
13138 workflowName?: string
13139 /** Local workflow run identifier for resumeFromRunId. Absent for remote_launched (the CCR session URL is the resume handle there) and on transcripts written before this field existed. */
13140 runId?: string
13141 summary?: string
13142 /** Directory where subagent transcripts are written during execution */
13143 transcriptDir?: string
13144 /** Path to the persisted workflow script for this invocation. Editable via Write/Edit; pass back as `scriptPath` to re-run without resending the script. */
13145 scriptPath?: string
13146 /** CCR session URL when status is remote_launched */
13147 sessionUrl?: string
13148 /** Non-blocking heads-up (e.g. local git state diverges from the pushed branch the cloud session will clone) */
13149 warning?: string
13150 /** Set if syntax check failed */
13151 error?: string
13152 }
13153 Write: {
13154 /** Whether a new file was created or an existing file was updated */
13155 type: "create" | "update"
13156 /** The path to the file that was written */
13157 filePath: string
13158 /** The content that was written to the file */
13159 content: string
13160 /** Diff patch showing the changes (empty when nothing changed, the diff timed out, or — with originalFile null on an update — the previous content was too large to diff) */
13161 structuredPatch: {
13162 oldStart: number
13163 oldLines: number
13164 newStart: number
13165 newLines: number
13166 lines: string[]
13167 }[]
13168 /** The original file content before the write (null for new files, or when the previous content was too large to include) */
13169 originalFile: string | null
13170 gitDiff?: {
13171 filename: string
13172 status: "modified" | "added"
13173 additions: number
13174 deletions: number
13175 changes: number
13176 patch: string
13177 /** GitHub owner/repo when available */
13178 repository?: string | null
13179 }
13180 /** True when the user edited the proposed content in the permission dialog before accepting */
13181 userModified?: boolean
13182 /** True when the write was held for the machine owner to review instead of written; the file is unchanged */
13183 staged?: boolean
13184 }
13185 }
13186}