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,207 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 * One content block of a message in Messages API form: `type` names its kind
459 * (`text`, `tool_use`, `tool_result`, `image`, `document`, `thinking`, ...).
460 *
461 * The other fields are that kind's as the Messages API defines them (see its
462 * reference); the engine hands the block over as it holds it, nothing renamed
463 * or dropped.
464 */
465 export type ApiContentBlock = {
466 /**
467 * The block's kind; the rest of the block is that kind's fields.
468 */
469 type: string;
470 [field: string]: unknown;
471 };
472
473 /**
474 * The argument of event `N`: `e` in its hooks, and what its call takes. For a
475 * union of names, the union of their arguments.
476 */
477 export type Args<N extends EventName = EventName> = EventOf[N];
478
479 /**
480 * Options of `$.ui.ask`.
481 */
482 export type AskOptions = {
483 /**
484 * 2-4 option labels; fewer than two are padded with Yes/No; free text is the
485 * dialog's Other.
486 */
487 options?: readonly string[];
488 /**
489 * A short chip beside the question (`Approach`, 12 characters at most).
490 */
491 header?: string;
492 /**
493 * Allow several options; the answer comes back comma-joined.
494 */
495 multiSelect?: true;
496 };
497
498 /**
499 * The input of `attribution.text`: one text the engine asks the model to
500 * write into a commit or a pull request, at the moment it is composed.
501 *
502 * Composed for the Bash description, the commit skills, a PR's body, the
503 * pre-ship mandate and the commit gate's deny: the same event at each.
504 */
505 export type AttributionTextInput = {
506 /**
507 * Which text (`commit`, `pr`, `exemption`, `remedy`); the key a matcher
508 * narrows on.
509 */
510 kind: AttributionTextKind;
511 /**
512 * As the engine composed it, the settings applied.
513 */
514 text: string;
515 };
516
517 /**
518 * Which git text `attribution.text` carries: the commit trailer, the PR
519 * footer, the mandate's or the commit gate's sentence naming the exemption.
520 */
521 export type AttributionTextKind = 'commit' | 'pr' | 'exemption' | 'remedy';
522
523 /**
524 * What an `attribution.text` hook returns: the text the model reads in
525 * that place.
526 */
527 export type AttributionTextResult = {
528 text: string;
529 };
530
531 /**
532 * What `$.audio.play` plays: a URL the engine fetches, or the bytes.
533 */
534 export type AudioClip = {
535 /**
536 * A file of the calling plugin's own, relative to the plugin's
537 * directory (`fx/open.wav`); no `.`, no leading slash.
538 *
539 * The engine resolves it and loads the file from disk.
540 */
541 asset: string;
542 url?: undefined;
543 base64?: undefined;
544 mime?: undefined;
545 } | {
546 /**
547 * The clip's URL; the engine fetches it (never the plugin).
548 */
549 url: string;
550 asset?: undefined;
551 base64?: undefined;
552 mime?: undefined;
553 } | {
554 /**
555 * The clip's bytes, base64.
556 */
557 base64: string;
558 /**
559 * What the bytes are (`audio/mpeg`, `audio/wav`).
560 */
561 mime: string;
562 asset?: undefined;
563 url?: undefined;
564 };
565
566 type BackgroundTaskSummary = {
567 id: string;
568 /**
569 * Friendly task-type label (e.g. 'shell', 'subagent', 'monitor', 'workflow'). Falls back to the raw discriminant for unknown types.
570 */
571 type: string;
572 status: string;
573 /**
574 * Free-text description. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
575 */
576 description: string;
577 /**
578 * Shell command line. Only present for 'shell' tasks. Capped at 1000 chars with the same "... [+N chars]" marker.
579 */
580 command?: string;
581 /**
582 * Subagent type name. Only present for 'subagent' tasks.
583 */
584 agent_type?: string;
585 /**
586 * MCP server name. Only present for 'monitor' / 'MCP task' tasks.
587 */
588 server?: string;
589 /**
590 * MCP tool name. Only present for 'monitor' / 'MCP task' tasks.
591 */
592 tool?: string;
593 /**
594 * Workflow name. Only present for 'workflow' tasks.
595 */
596 name?: string;
597 };
598
599 type BaseHookInput = {
600 session_id: string;
601 transcript_path: string;
602 cwd: string;
603 /**
604 * 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.
605 */
606 prompt_id?: string;
607 permission_mode?: string;
608 /**
609 * 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.
610 */
611 agent_id?: string;
612 /**
613 * 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).
614 */
615 agent_type?: string;
616 /**
617 * 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.
618 */
619 effort?: {
620 /**
621 * 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.
622 */
623 level: string;
624 };
625 };
626
627 /**
628 * The `Box` props a `hover` may override, none of which moves the Box's
629 * siblings, and `scope`, which names the hover group the Box joins.
630 *
631 * `display` is `"flex"` alone, on a Box drawn `display: "none"`: with a
632 * `scope`, every member of the lit group is revealed, in whichever site it
633 * sits, so a pointer on a glyph in the transcript can swap an entry into a
634 * fixed row of the band, or reveal an absolutely positioned card.
635 * `borderStyle` only restyles a border the Box has; the offsets move a Box
636 * drawn `position: "absolute"`, none in the flow. The surface applies a
637 * hover as the pointer moves, so a reveal that moves what the pointer rests
638 * on is drawn once, not in a loop.
639 */
640 export type BoxHoverProps = {
641 /**
642 * Names a hover group of this plugin's: every element it draws with the
643 * same `scope`, in any site, lights while any is hovered, reveals included.
644 *
645 * A Pane row and a mark on a transcript message can share one. Another
646 * plugin's elements under the same string are a different group. One to
647 * 64 characters, no control characters; no keyed Box needed; no hook runs.
648 */
649 scope?: string;
650 borderStyle?: string;
651 borderColor?: string;
652 borderDimColor?: boolean;
653 backgroundColor?: string;
654 display?: 'flex';
655 top?: number;
656 left?: number;
657 right?: number;
658 bottom?: number;
659 };
660
661 /**
662 * The props of `Box`: the layout, position, margin, padding and border props
663 * of Ink's Box a tree may set, and the two of hover.
664 */
665 export type BoxProps = {
666 /**
667 * Makes the Box a hover scope: while the pointer is anywhere over it, its
668 * own `hover` and that of every element beneath it apply.
669 *
670 * A nested Box with a `key` of its own scopes what is beneath it, a placed
671 * card outside its rows included. A key a sibling Box already took, or one
672 * that is no plain string, names no scope: hovers beneath it stay inert.
673 */
674 key?: string;
675 /**
676 * Style overrides applied by the surface while the pointer is over the
677 * nearest keyed `Box`, this one included, or, given a `scope`, its group.
678 *
679 * No hook runs and nothing crosses to the plugin. To reveal on hover, draw
680 * the Box `display: "none"` with `hover: { display: "flex" }` in a visible
681 * keyed Box or under a `scope`; on a `position: "absolute"` Box, no reflow.
682 */
683 hover?: BoxHoverProps;
684 /**
685 * `"absolute"` leaves the flow, as in CSS: placed against its parent by
686 * the offsets, no room among its siblings, painted over those before it.
687 *
688 * So showing or moving it (a hover may) moves nothing; the pointer on it is
689 * on its parent. Clipped, pointer and paint, by the region its site is in
690 * (viewport, pane, band), by the site itself on the main screen or export.
691 *
692 * @example <Box key="k"><Text>glyph</Text><Box position="absolute" top={-2}
693 * left={2} display="none" hover={{ display: 'flex' }}>the card</Box></Box>
694 */
695 position?: 'relative' | 'absolute';
696 /**
697 * Rows from the parent's top edge, in character cells: an integer,
698 * negative above the edge.
699 *
700 * With `bottom` and no `height` the Box spans the two.
701 */
702 top?: number;
703 /**
704 * Columns from the parent's left edge, in character cells: an integer,
705 * negative left of the edge.
706 *
707 * With `right` and no `width` the Box spans the two.
708 */
709 left?: number;
710 /**
711 * Columns from the parent's right edge, in character cells: an integer,
712 * negative right of the edge.
713 */
714 right?: number;
715 /**
716 * Rows from the parent's bottom edge, in character cells: an integer,
717 * negative below the edge.
718 */
719 bottom?: number;
720 flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';
721 flexGrow?: number;
722 flexShrink?: number;
723 flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse';
724 alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch';
725 alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto';
726 justifyContent?: 'flex-start' | 'center' | 'flex-end' | 'space-between' | 'space-around' | 'space-evenly';
727 gap?: number;
728 columnGap?: number;
729 rowGap?: number;
730 width?: number | string;
731 height?: number | string;
732 minWidth?: number | string;
733 minHeight?: number | string;
734 margin?: number;
735 marginX?: number;
736 marginY?: number;
737 marginTop?: number;
738 marginBottom?: number;
739 marginLeft?: number;
740 marginRight?: number;
741 padding?: number;
742 paddingX?: number;
743 paddingY?: number;
744 paddingTop?: number;
745 paddingBottom?: number;
746 paddingLeft?: number;
747 paddingRight?: number;
748 borderStyle?: string;
749 borderColor?: string;
750 borderDimColor?: boolean;
751 backgroundColor?: string;
752 overflow?: 'visible' | 'hidden';
753 display?: 'flex' | 'none';
754 };
755
756 /**
757 * One variant per built-in tool; with none in the table (a plugin author's
758 * project before `/plugin-types` ran), one loose variant over every name.
759 */
760 export type BuiltinToolCallInput = [BuiltinToolName] extends [never] ? BuiltinToolCallInputFallback : {
761 [N in BuiltinToolName]: ToolInputOf<N, BuiltinToolInputs[N]>;
762 }[BuiltinToolName];
763
764 /**
765 * The built-in branch's answer when no built-in tool is declared: every
766 * name, its args unconstrained.
767 */
768 type BuiltinToolCallInputFallback = {
769 /**
770 * The name of the tool being called (`Bash`); comparing it narrows `e` once
771 * the table has entries. Reserved: a rewrite of it is ignored by core.
772 */
773 tool: string;
774 /**
775 * The tool_use block's id: the same at every event of the call and in
776 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
777 */
778 tool_use_id: string;
779 [argument: string]: unknown;
780 };
781
782 /**
783 * The arguments of each built-in tool by name, for declaration merging;
784 * empty until a declaration file adds entries, then `e.tool === "Bash"`
785 * narrows `e` to Bash's arguments.
786 *
787 * `/plugin-types` writes this build's set beneath the engine's declarations
788 * (claude-code.d.ts), from each tool's input schema.
789 *
790 * @example
791 * interface BuiltinToolInputs { Bash: { command: string; timeout?: number } }
792 */
793 export interface BuiltinToolInputs {
794 }
795
796 /**
797 * The names of the built-in tools.
798 */
799 export type BuiltinToolName = keyof BuiltinToolInputs & string;
800
801 /**
802 * The structured result of each built-in tool by name, for declaration
803 * merging; empty until a declaration file adds entries, then after
804 * `e.tool === "Bash"` the `result` of `next(e)` is Bash's record.
805 *
806 * `/plugin-types` writes this build's set beneath the engine's declarations
807 * (claude-code.d.ts), from each tool's output schema; a tool without one is
808 * `unknown`.
809 *
810 * @example
811 * interface BuiltinToolResults { Bash: { stdout: string; stderr: string } }
812 */
813 export interface BuiltinToolResults {
814 }
815
816 /**
817 * The props of `Button`, every surface's pressable leaf: an address, a
818 * label, the closure a press runs, and the label styles a hover overrides.
819 *
820 * The terminal draws `[ label ]` (when `plain`, `1: label` or the label
821 * alone), a desktop a native button; a click, a `hotkey`, the chord for its
822 * `action`, or Enter under the focus raises `ui.press`, its bottom `onPress`.
823 */
824 export type ButtonProps = {
825 /**
826 * The element's address: `e.element` at `ui.press`, what a matcher names.
827 * Defaults to the label.
828 */
829 key?: string;
830 /**
831 * The text drawn on the button; or the one string child.
832 */
833 label?: string;
834 /**
835 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it while
836 * the plugin's site holds the focus; anything else is refused.
837 *
838 * The band after ctrl+x tab or a click, a focused `Pane`; never from the
839 * composer, save a bare digit in an empty one pressing a band Button, as a
840 * survey is answered. Shift+w matches `"w"`; two on one key, the later wins.
841 */
842 hotkey?: string;
843 /**
844 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord, as the
845 * person bound it, presses this from the prompt; unknown names refused.
846 *
847 * Chords, or a modified key Global or an active context binds, on the
848 * terminal while mounted, no dialog up and no engine handler of the action
849 * mounted; a pane's over the band's over another's, then the last drawn.
850 */
851 action?: string;
852 /**
853 * Drawn without chrome: the hotkey in the accent color, a colon, the
854 * label (`1: Yes`), as a survey's row reads; no `hotkey`, the label alone.
855 *
856 * A one-glyph label (`'\u{1F50A}'`, a speaker) is then a control by
857 * itself: the focus and the pointer still invert it, `dimColor` and `hover`
858 * still apply. A desktop draws its native button either way.
859 */
860 plain?: true;
861 /**
862 * The label drawn dim at rest, as `Text`'s `dimColor`, and at full strength
863 * under the pointer or the focus: a secondary control, a path in a list.
864 */
865 dimColor?: boolean;
866 /**
867 * The site's focus ring starts here when the site takes the keyboard,
868 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
869 *
870 * A pane opened with `focus`, or the person's focus chord or click, is the
871 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
872 * origin this plugin. A ring the person has moved stays where it was put.
873 */
874 autoFocus?: true;
875 /**
876 * Label style overrides (the `Text` set) applied by the surface while the
877 * nearest enclosing keyed `Box`, or given a `scope` its group, is hovered.
878 *
879 * No hook runs and nothing crosses to the plugin; under the pointer itself
880 * the button inverts as it always has. Refused outside a keyed Box unless
881 * it names a `scope`.
882 */
883 hover?: TextHoverProps;
884 /**
885 * What the press runs, in the plugin's own environment: the bottom of the
886 * `ui.press` chain. The host holds only a handle, for the drawing's life.
887 */
888 onPress: () => void;
889 };
890
891 /**
892 * The handler `on(...).catch(handler)` takes for a hook of type `F`: the
893 * hook's `($, e, next)`, run afresh when it throws, misreturns or overruns.
894 *
895 * `next` carries `error` and `called` (Caught) and is replay-safe; a return
896 * within the grace is the hook's result, `undefined` the hook absent. On a
897 * streaming event the handler is a generator too, continuing the stream.
898 */
899 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;
900
901 /**
902 * What `next` carries into a `.catch` handler and nowhere else: why the
903 * hook failed, and whether it had called `next` before it did.
904 *
905 * There `next` is replay-safe: when `called`, `next(e)` resolves to what the
906 * hook's last call settled to, nothing beneath running again, the argument
907 * unread; when not, it runs the hooks beneath once and a later call replays.
908 */
909 export type Caught = {
910 /**
911 * Why the hook failed (HookFailure); undefined on an ordinary hook's
912 * `next`, so its presence says a handler is running.
913 */
914 readonly error: HookFailure;
915 /**
916 * True when the failed hook had called `next()` or `next.to()` at least
917 * once, settled or in flight; the handler runs once that call settled.
918 */
919 readonly called: boolean;
920 };
921
922 /**
923 * What a hook on streaming event `N` yields, and what its `next(e)` yields
924 * to it (ChunkOf by name).
925 */
926 export type Chunk<N extends StreamingEventName = StreamingEventName> = ChunkOf[N];
927
928 /**
929 * The chunk type of each streaming event, by name: what its stream yields.
930 */
931 export type ChunkOf = {
932 /**
933 * One piece of the model's response (TurnStepChunk).
934 */
935 'turn.step': TurnStepChunk;
936 };
937
938 /**
939 * What every `turn.step` chunk may carry: the engine's handle on the item
940 * of its own stream the chunk was read off, absent on a chunk a hook made.
941 *
942 * A hook that passes a chunk on, or rewrites it by spreading it, keeps the
943 * handle, and whatever it left unchanged reaches the engine as the engine
944 * streamed it; a chunk built afresh has none and is taken at its word.
945 */
946 type ChunkRef = {
947 /**
948 * The engine's handle on its own streamed item; opaque, this step's only.
949 */
950 ref?: number;
951 };
952
953 /**
954 * The name of a classic hook event as a function-hooks event: the settings
955 * hook's own name under `classic` (`classic.Stop`, `classic.PreToolUse`).
956 */
957 export type ClassicEventName = `classic.${ClassicHookEvent}`;
958
959 /**
960 * The classic (settings) hook events, one per classic event name: `e` is
961 * what the classic hook receives on stdin for that event.
962 *
963 * The chain is [managed settings hooks, ...hooks modules, the other settings
964 * hooks as core], so a managed block ends it above every module. In shape
965 * `classic.PreToolUse` alone differs: its `e` is ToolCallEnvelope, no more.
966 */
967 export type ClassicEventOf = {
968 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? ToolCallEnvelope : ClassicHookInputs[E];
969 };
970
971 /**
972 * The name of a classic hook event: `PreToolUse`, `Stop`, and the rest.
973 */
974 export type ClassicHookEvent = HookInput['hook_event_name'];
975
976 /**
977 * What a classic hook receives on stdin for each event, by event name: the
978 * Agent SDK's `<Event>HookInput`.
979 */
980 export type ClassicHookInputs = {
981 [I in HookInput as I['hook_event_name']]: I;
982 };
983
984 /**
985 * Everything a classic hook event's answer can carry, named as the classic
986 * hook's JSON output names it; each event reads its subset (ClassicResultOf).
987 *
988 * The settings hooks below fold into one of these (last write wins, contexts
989 * concatenate); a hooks module returns `next(e)`, a copy with fields changed,
990 * or its own. A field of the wrong shape fails the hook, which is skipped.
991 */
992 export type ClassicResult = {
993 /**
994 * `decision: "block"` with this text as `reason` (a command hook's exit
995 * code 2): the event's block, veto or re-prompt.
996 */
997 block?: string;
998 /**
999 * `continue: false`: the session stops after this event.
1000 */
1001 preventContinuation?: true;
1002 /**
1003 * Shown when `preventContinuation` stops the session (`stopReason`).
1004 */
1005 stopReason?: string;
1006 /**
1007 * `hookSpecificOutput.additionalContext`, one entry per hook: text handed
1008 * to the model with the event.
1009 */
1010 additionalContext?: string[];
1011 /**
1012 * `hookSpecificOutput.sessionTitle` (UserPromptSubmit, SessionStart).
1013 */
1014 sessionTitle?: string;
1015 /**
1016 * `hookSpecificOutput.suppressOriginalPrompt` (UserPromptSubmit,
1017 * UserPromptExpansion).
1018 */
1019 suppressOriginalPrompt?: true;
1020 /**
1021 * `hookSpecificOutput.initialUserMessage` (SessionStart).
1022 */
1023 initialUserMessage?: string;
1024 /**
1025 * `hookSpecificOutput.watchPaths` (SessionStart).
1026 */
1027 watchPaths?: string[];
1028 /**
1029 * `hookSpecificOutput.reloadSkills` (SessionStart).
1030 */
1031 reloadSkills?: true;
1032 /**
1033 * `hookSpecificOutput.permissionDecision` (PreModelSwitch).
1034 */
1035 permissionDecision?: 'allow' | 'deny' | 'ask';
1036 /**
1037 * `hookSpecificOutput.permissionDecisionReason` (PreModelSwitch).
1038 */
1039 permissionDecisionReason?: string;
1040 /**
1041 * `hookSpecificOutput.decision` (PermissionRequest).
1042 */
1043 decision?: PermissionRequestDecision;
1044 /**
1045 * `hookSpecificOutput.updatedToolOutput` (PostToolUse): replaces what the
1046 * model sees of the tool's result.
1047 */
1048 updatedToolOutput?: unknown;
1049 /**
1050 * `hookSpecificOutput.updatedMCPToolOutput` (PostToolUse, MCP tools only).
1051 */
1052 updatedMCPToolOutput?: unknown;
1053 /**
1054 * `hookSpecificOutput.retry` (PermissionDenied).
1055 */
1056 retry?: true;
1057 /**
1058 * `hookSpecificOutput.displayContent` (MessageDisplay).
1059 */
1060 displayContent?: string;
1061 /**
1062 * `hookSpecificOutput.worktreePath` (WorktreeCreate; a command hook prints
1063 * it): the worktree the hook created, absolute or relative to its cwd.
1064 *
1065 * Left unset, the session creates its git worktree as it would unhooked.
1066 */
1067 worktreePath?: string;
1068 };
1069
1070 /**
1071 * The event-specific fields of ClassicResult each classic event reads (its
1072 * `hookSpecificOutput`), by event; an event absent here reads none of them.
1073 *
1074 * `block`, `preventContinuation` and `stopReason` are every event's.
1075 */
1076 export type ClassicResultFields = {
1077 UserPromptSubmit: 'additionalContext' | 'sessionTitle' | 'suppressOriginalPrompt';
1078 UserPromptExpansion: 'additionalContext' | 'suppressOriginalPrompt';
1079 SessionStart: 'additionalContext' | 'initialUserMessage' | 'sessionTitle' | 'watchPaths' | 'reloadSkills';
1080 Setup: 'additionalContext';
1081 PreModelSwitch: 'permissionDecision' | 'permissionDecisionReason';
1082 PostModelSwitch: 'additionalContext';
1083 SubagentStart: 'additionalContext';
1084 PostToolUse: 'additionalContext' | 'updatedToolOutput' | 'updatedMCPToolOutput';
1085 PostToolUseFailure: 'additionalContext';
1086 PostToolBatch: 'additionalContext';
1087 Stop: 'additionalContext';
1088 SubagentStop: 'additionalContext';
1089 PermissionDenied: 'retry';
1090 PermissionRequest: 'decision';
1091 MessageDisplay: 'displayContent';
1092 WorktreeCreate: 'worktreePath';
1093 };
1094
1095 /**
1096 * What each classic hook event's hook returns and its `next(e)` resolves to:
1097 * the event's own subset of ClassicResult.
1098 *
1099 * `classic.PreToolUse` keeps its `allow` / `ask` / `deny` result
1100 * (PreToolUseResult).
1101 */
1102 export type ClassicResultOf = {
1103 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? PreToolUseResult : Pick<ClassicResult, 'block' | 'preventContinuation' | 'stopReason' | (E extends keyof ClassicResultFields ? ClassicResultFields[E] : never)>;
1104 };
1105
1106 /**
1107 * Options of `$.model.classify`.
1108 */
1109 export type ClassifyOptions = {
1110 /**
1111 * An alias (`haiku`) or a full model id; default the engine's small fast
1112 * model.
1113 */
1114 model?: string;
1115 };
1116
1117 /**
1118 * The element table a surface module draws with, `surface.elements`: the
1119 * terminal's (Elements) less `Client` (none nests), `Raster` and `Image`.
1120 *
1121 * What `$.ui.resolve(e)` is to a hooks module; a Button, Input or Select
1122 * keeps its handler here. A tree of them keeps every tree's bounds (20,000
1123 * nodes, 32 deep, 100,000 characters serialized) or the instance unmounts.
1124 */
1125 export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster' | 'Image'>;
1126
1127 /**
1128 * One key the person pressed while a `Client` had the focus, as
1129 * `surface.onKey` hands it. Escape never arrives: it returns the focus.
1130 */
1131 export type ClientKeyEvent = {
1132 /**
1133 * A special key's name (`up`, `down`, `left`, `right`, `return`, `tab`,
1134 * `backspace`, `delete`, `pageup`, `home`, ...) or the character typed.
1135 */
1136 key: string;
1137 /**
1138 * Modifier keys held with it, each present only when true.
1139 */
1140 ctrl?: true;
1141 shift?: true;
1142 meta?: true;
1143 };
1144
1145 /**
1146 * The component a surface module exports (default, or its one PascalCase
1147 * export): from props and surface to the tree drawn (no nested `Client`).
1148 *
1149 * Runs on the drawing thread, a second per call at most; `h` and `Fragment`
1150 * are the environment's, so nothing of the module's takes those names. A
1151 * throw, an overrun or a tree past the bounds (ClientElements) unmounts it.
1152 *
1153 * @example
1154 * const Tag: ClientModule<string> = (t, s) => s.elements.Text({ children: t })
1155 */
1156 export type ClientModule<P extends JsonValue = JsonValue, S = unknown> = (props: P, surface: ClientSurface<S>) => RenderElement;
1157
1158 /**
1159 * One pointer event over a `Client`'s region, as `surface.onPointer` hands
1160 * it: region-relative cells, and the sub-cell position where known.
1161 *
1162 * After a `down` in the region the instance holds the pointer until the
1163 * `up`: every `move` reaches it, past the edges too (negative, or beyond
1164 * `columns`/`rows`), and the transcript neither selects nor scrolls.
1165 */
1166 export type ClientPointerEvent = {
1167 type: ClientPointerType;
1168 /**
1169 * The column under the pointer, 0 at the region's left edge; on `enter`
1170 * and `leave`, the last column a move reported.
1171 */
1172 x: number;
1173 /**
1174 * The row under the pointer, 0 at the region's top edge.
1175 */
1176 y: number;
1177 /**
1178 * The same position with the fraction of a cell kept (`x: 12`, `fine.x:
1179 * 12.375`), where the surface knows it: a terminal that reports pixels.
1180 *
1181 * kitty, Ghostty, iTerm2, WezTerm and foot do; tmux passes none through.
1182 * Absent elsewhere and on `enter`/`leave`; present, a `move` comes within
1183 * a cell too. What a module showing another program's pixels forwards.
1184 *
1185 * @example
1186 * surface.onPointer(e => click((e.fine?.x ?? e.x + 0.5) * pixelsPerCell))
1187 */
1188 fine?: {
1189 x: number;
1190 y: number;
1191 };
1192 /**
1193 * Which button is down (`down`, `move` while held) or came up (`up`);
1194 * absent on a hover `move`, `enter` and `leave`.
1195 */
1196 button?: 'left' | 'middle' | 'right';
1197 /**
1198 * Modifier keys the terminal reported held, each present only when true.
1199 */
1200 shift?: true;
1201 alt?: true;
1202 ctrl?: true;
1203 };
1204
1205 /**
1206 * What the pointer did over a `Client`'s region: a button went down, the
1207 * pointer moved, the button came up, or the pointer crossed the region's edge.
1208 */
1209 export type ClientPointerType = 'down' | 'move' | 'up' | 'enter' | 'leave';
1210
1211 /**
1212 * The props of `Client`: which of the plugin's surface modules draws here,
1213 * under what key, with what data, in how much room.
1214 */
1215 export type ClientProps = {
1216 /**
1217 * The instance's address within the drawing: two `Client`s of one plugin in
1218 * one tree take two keys. What `e.element` carries at `ui.message`.
1219 *
1220 * The engine keeps the instance (its local state, its timers) across the
1221 * plugin's redraws while a `Client` under this key stays in the tree.
1222 */
1223 key: string;
1224 /**
1225 * The surface module's path, a string literal relative to this file:
1226 * `module: "./<name>.tsx"` (or `.jsx`, `.ts`, `.js`, `.mjs`).
1227 *
1228 * Read off the source: a variable there is refused at load, as is a path
1229 * outside the plugin or naming no file. Its default export draws, else
1230 * its one PascalCase export; loaded, the tree carries the plugin's path.
1231 */
1232 module: string;
1233 /**
1234 * Plain data (JsonValue) handed to the module function; a new value on a
1235 * redraw reaches the running instance, its state kept.
1236 *
1237 * Bounded as a tree's text is; not a channel for closures.
1238 * Typed `unknown` so a matcher over a tree stays shallow.
1239 */
1240 props?: unknown;
1241 /**
1242 * Columns the instance's region takes: a count, or a percentage of the
1243 * parent. Absent, the region is as wide as what the module draws.
1244 */
1245 width?: number | string;
1246 /**
1247 * Rows the instance's region takes: a count, or a percentage of the parent.
1248 * Absent, the region is as tall as what the module draws.
1249 */
1250 height?: number | string;
1251 /**
1252 * How the region grows into free room along the parent's direction, as a
1253 * Box's `flexGrow`.
1254 */
1255 flexGrow?: number;
1256 };
1257
1258 /**
1259 * What a surface module's function receives as its second argument: its
1260 * elements, the instance's local state, its region, input, clock and port.
1261 *
1262 * Called again (same `surface`, same `state`) on new props, after
1263 * `setState`, and on a resize; what it returns is drawn in the region. No
1264 * `$` here: the hooks module has it, and `post` is the way to reach it.
1265 */
1266 export type ClientSurface<S = unknown> = {
1267 /**
1268 * The surface's element table (ClientElements), the tags the module draws
1269 * with: `const { Box, Text } = surface.elements`. No `Client` in it.
1270 */
1271 readonly elements: ClientElements;
1272 /**
1273 * The instance's local state: `undefined` until the first `setState`.
1274 * Kept across the plugin's redraws; dropped with the instance.
1275 */
1276 readonly state: S | undefined;
1277 /**
1278 * Replaces the local state and schedules one more call of the function on
1279 * the next frame; several calls before it coalesce into one redraw.
1280 *
1281 * A `setState` on each of three renders in a row with no key, pointer,
1282 * tick, press or props between is a render loop: the instance unmounts.
1283 */
1284 setState: (next: S) => void;
1285 /**
1286 * The region's width in cells, as last laid out (0 before the first
1287 * layout).
1288 */
1289 readonly columns: number;
1290 /**
1291 * The region's height in cells, as last laid out (0 before the first
1292 * layout).
1293 */
1294 readonly rows: number;
1295 /**
1296 * Calls `fn` every `ms` milliseconds on the surface's frame clock until
1297 * the returned function is called or the instance unmounts.
1298 *
1299 * Start it once (while `state` is still undefined), not on every call.
1300 */
1301 every: (ms: number, fn: () => void) => () => void;
1302 /**
1303 * Sets the instance's pointer listener (one; a later call replaces it)
1304 * and returns what clears it. See ClientPointerEvent for capture.
1305 */
1306 onPointer: (fn: (event: ClientPointerEvent) => void) => () => void;
1307 /**
1308 * Sets the instance's key listener (one; a later call replaces it),
1309 * reached while a click has given it the focus; Escape returns that.
1310 */
1311 onKey: (fn: (event: ClientKeyEvent) => void) => () => void;
1312 /**
1313 * Sends plain data to the plugin's hooks module: `e.data` of a
1314 * `ui.message` only that plugin's hooks see, one per frame at most.
1315 *
1316 * A later post in the same frame replaces an undelivered one; a hook
1317 * answering `{ props }` hands this instance its next props. At most
1318 * 20,000 values, 32 deep, 100,000 characters, or the post is not sent.
1319 */
1320 post: (data: JsonValue) => void;
1321 };
1322
1323 /**
1324 * The argument of the `$.clock` waits (`sleep`, `after`, `every`): how long,
1325 * in milliseconds, before the dispatch resolves.
1326 */
1327 type ClockWait = {
1328 /**
1329 * The wait, a non-negative number of milliseconds.
1330 */
1331 ms: number;
1332 };
1333
1334 /**
1335 * The props of `Code`, source text every surface draws with the engine's own
1336 * highlighter: coloured tokens, a line gutter on request, or a unified diff.
1337 *
1338 * A leaf: no children. `source` is the element's data as a string is a
1339 * Text's, bounded and free of control characters the same way; the colour
1340 * on screen is the engine's, never the plugin's.
1341 */
1342 export type CodeProps = {
1343 /**
1344 * The text drawn: source code, or under `format: 'diff'` one or more
1345 * unified-diff hunks.
1346 *
1347 * At most 10000 characters; tab and newline are the only control
1348 * characters it may hold.
1349 */
1350 source: string;
1351 /**
1352 * A highlighter language id or alias (`typescript`, `ts`, `py`), a
1353 * plugin-contributed grammar's included.
1354 *
1355 * Absent, the language is inferred from `path`; when neither resolves,
1356 * the text is drawn plain.
1357 */
1358 language?: string;
1359 /**
1360 * A file path the language is inferred from when `language` is absent:
1361 * its extension or name, else a shebang on the first line.
1362 *
1363 * Drawn nowhere and never read: nothing touches the disk.
1364 */
1365 path?: string;
1366 /**
1367 * The 1-based number of the first line of `source`: present, a dim
1368 * right-aligned gutter numbers the lines from it; absent, no gutter.
1369 *
1370 * Ignored under `format: 'diff'`, whose hunks carry their own numbers.
1371 */
1372 startLine?: number;
1373 /**
1374 * `'source'` (the default) draws `source` as code; `'diff'` reads it as
1375 * unified-diff hunks and draws gutters, markers, add and remove colouring.
1376 *
1377 * A hunk is `@@ -a,b +c,d @@` then lines starting ` `, `+` or `-`; a
1378 * leading `---`/`+++` pair and `\ No newline at end of file` are read
1379 * past. A source that does not parse as hunks is refused.
1380 */
1381 format?: 'source' | 'diff';
1382 /**
1383 * What a line wider than the room does, in Text's `wrap` vocabulary:
1384 * `'wrap'` (the default) continues it on rows under the gutter.
1385 *
1386 * `'truncate-end'` cuts it at the edge with an ellipsis; Text's other
1387 * spellings are refused, since a gutter leaves them no sense here.
1388 */
1389 wrap?: 'wrap' | 'truncate-end';
1390 };
1391
1392 /**
1393 * The input of `command.describe`: how one slash command presents in the
1394 * typeahead and `/help`, at the moment the engine lists it.
1395 */
1396 export type CommandDescribeInput = {
1397 /**
1398 * Names the command without its slash; the key a matcher narrows on. A
1399 * rewrite is refused.
1400 */
1401 command: string;
1402 /**
1403 * The one-line description the menu shows, as the command declares it.
1404 */
1405 description: string;
1406 /**
1407 * The hint drawn dim after the name (`[name]`), when the command has one.
1408 */
1409 argumentHint?: string;
1410 /**
1411 * Whether the typeahead and `/help` leave the command out; a hidden
1412 * command still runs when typed in full.
1413 */
1414 isHidden: boolean;
1415 /**
1416 * Whether the command declares it runs at once when typed mid-turn,
1417 * instead of waiting for the turn to end.
1418 *
1419 * One that decides per invocation reads false. Read only: not part of
1420 * what a hook answers, and a rewrite is refused.
1421 */
1422 immediate: boolean;
1423 /**
1424 * Who provides this command: the plugin and its tier; `{ plugin: "engine",
1425 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
1426 */
1427 provider: Origin;
1428 };
1429
1430 /**
1431 * What a `command.describe` hook returns: the description, hint and hidden
1432 * flag the menu uses; the name, `immediate` and `provider` stay as they were.
1433 */
1434 export type CommandDescribeResult = Omit<CommandDescribeInput, 'command' | 'immediate' | 'provider'>;
1435
1436 /**
1437 * One slash command as `$.command.list()` returns it.
1438 */
1439 export type CommandInfo = {
1440 /**
1441 * What the person runs it by, without the slash.
1442 */
1443 name: string;
1444 /**
1445 * The one line the typeahead shows for it.
1446 */
1447 description: string;
1448 /**
1449 * Where it comes from (CommandSource).
1450 */
1451 source: CommandSource;
1452 /**
1453 * Which plugin added it, when `source` is `plugin` and the engine knows:
1454 * the one that registered it, or whose manifest carries it.
1455 */
1456 plugin?: string;
1457 };
1458
1459 /**
1460 * Where a command's answer will show: which of the terminal's two layouts
1461 * the surface renders, and how wide it is when the command runs.
1462 *
1463 * A fact the engine stamps on `command.run`, so a command that draws (opens
1464 * a pane, prints a wide table) can suit the room it has: the fullscreen
1465 * layout docks a pane beside the transcript from 110 columns, the main
1466 * screen places it inline above the prompt at any width.
1467 */
1468 export type CommandPresentation = {
1469 /**
1470 * True under the fullscreen (alternate-screen) layout; false on the main
1471 * screen (`CLAUDE_CODE_NO_FLICKER=0`, tmux by default) and headless.
1472 *
1473 * The fact `RenderViewport`'s `isFullscreen` carries on every terminal
1474 * drawing, from the same source: the two agree.
1475 */
1476 isFullscreen: boolean;
1477 /**
1478 * The terminal's width in cells as the command runs; 80 where no terminal
1479 * has measured (headless with no tty).
1480 */
1481 columns: number;
1482 };
1483
1484 /**
1485 * `command.run`'s input as a plugin's `$.command.run` takes it: `args` may
1486 * be left out (`/command`, bare); `origin` and `presentation` the engine sets.
1487 */
1488 export type CommandRunArgs = Omit<CommandRunInput, 'origin' | 'args' | 'presentation'> & {
1489 /**
1490 * Everything after the name, as the person would type it; left out, `""`.
1491 */
1492 args?: string;
1493 };
1494
1495 /**
1496 * The input of `command.run`: one slash command about to run, the way the
1497 * person typed it (`/name args`), and where the run came from.
1498 */
1499 export type CommandRunInput = {
1500 /**
1501 * Names the command without its slash (`compact`, `hello`), aliases and
1502 * folds resolved; the key a matcher narrows on. A rewrite is refused.
1503 */
1504 command: string;
1505 /**
1506 * Everything after the name, as typed (`""` when nothing was); a hook
1507 * rewrites it with `next({ ...e, args })`.
1508 */
1509 args: string;
1510 /**
1511 * Where the run came from, in `prompt.submit`'s words (PromptOrigin):
1512 * the person's Enter (`composer`), the bridge, the SDK, or a plugin.
1513 *
1514 * A plugin's `$.command.run` reads `{ kind: 'plugin', name }`. `next(e)`
1515 * passes it on as received.
1516 */
1517 origin: PromptOrigin;
1518 /**
1519 * Where the command's answer will show (CommandPresentation): the
1520 * fullscreen layout or the main screen, and the terminal's width.
1521 *
1522 * Pinned: the engine stamps it, `next(e)` passes it on, a rewrite that
1523 * leaves it out keeps it and one that changes it is refused.
1524 */
1525 presentation: CommandPresentation;
1526 };
1527
1528 /**
1529 * What a `command.run` hook returns and what `next(e)` and `$.command.run`
1530 * resolve to: the command's output text and the notes it leaves the model.
1531 *
1532 * From core, `text` is what the command printed (a `local` command's
1533 * returned text; a panel command may print nothing), `context` what it
1534 * recorded for the model beside that, and `ref` names the run.
1535 *
1536 * A hook's own answer without `next` runs no command: its `text` is shown
1537 * as the command's output, under the names of the plugins hooking the
1538 * command unless each is bundled with Claude Code, whose answer reads as
1539 * the built-in command's own, and its `context` is recorded after it.
1540 *
1541 * Both are the plugin's to size, as a core command's output is; what bounds
1542 * them is what bounds any transcript row where a surface draws it.
1543 */
1544 export type CommandRunResult = {
1545 /**
1546 * The command's output as a transcript line, or undefined when the
1547 * command showed nothing as text (a panel, a prompt for the model).
1548 */
1549 text?: string;
1550 /**
1551 * What the model reads after the command's output and the person never
1552 * sees, each entry one hidden user message recorded after the output row.
1553 *
1554 * From core, the notes the command left the model, absent when none. Kept
1555 * whole from `next`: left out after `next`, the last answer's notes ride
1556 * along; written, it keeps every entry that answer had (none empty).
1557 */
1558 context?: readonly string[];
1559 /**
1560 * Set by core on what `next(e)` resolves to: names the engine's run of
1561 * the command (its result stays on the host side).
1562 *
1563 * A hook that returns the object it got makes the engine use that run
1564 * verbatim. Absent on a hook's own `{ text }` and on `$.command.run`'s.
1565 */
1566 ref?: number;
1567 };
1568
1569 /**
1570 * Where a slash command comes from, as `$.command.list()` tells them apart.
1571 *
1572 * `builtin` ships with Claude Code; `plugin` is a plugin's markdown command,
1573 * skill or `$.command.register`; `user` is the user's or project's own
1574 * file; `mcp` an MCP server's prompt.
1575 */
1576 export type CommandSource = 'builtin' | 'plugin' | 'user' | 'mcp';
1577
1578 /**
1579 * What `$.command.register` takes: the slash command this plugin serves.
1580 */
1581 export type CommandSpec = {
1582 /**
1583 * The command's name without the slash (letters, digits, `_`, `-`; up to
1584 * 64); the person runs it as `/<name>`.
1585 */
1586 name: string;
1587 /**
1588 * The one line the typeahead and `/help` show for it.
1589 */
1590 description: string;
1591 /**
1592 * The hint drawn dim after the name (`[name]`), when it takes arguments.
1593 */
1594 argumentHint?: string;
1595 /**
1596 * Set so that `/<name>` typed while a turn is in flight runs at once
1597 * instead of waiting for the turn to end, as it does when left out.
1598 *
1599 * Its `command.run` hook then runs while a turn may still be streaming and
1600 * must not assume the turn's state (what the transcript holds, whether a
1601 * tool is mid-call); its `{ text }` prints as an idle run's does.
1602 */
1603 immediate?: true;
1604 };
1605
1606 type ConfigChangeHookInput = BaseHookInput & {
1607 hook_event_name: 'ConfigChange';
1608 source: 'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills';
1609 file_path?: string;
1610 };
1611
1612 /**
1613 * The input of `config.describe`: how one `/config` row presents, at the
1614 * moment the menu lists it (and for `$.config.list`).
1615 */
1616 export type ConfigDescribeInput = {
1617 /**
1618 * Names the row, as `config.set`'s `key` does; the key a matcher narrows
1619 * on. Pinned: a rewrite is refused.
1620 */
1621 key: string;
1622 /**
1623 * What the menu draws for the row, before its value.
1624 */
1625 label: string;
1626 /**
1627 * The help text beneath the label, when the row has one (a plugin
1628 * field's `description`); absent for the panel's own rows.
1629 */
1630 description?: string;
1631 /**
1632 * Whether the menu leaves the row out; a hidden row still answers
1633 * `$.config.set` and `/config key=value`.
1634 */
1635 isHidden: boolean;
1636 /**
1637 * Who owns the row, as `config.set`'s `provider`. Pinned.
1638 */
1639 provider: Origin;
1640 };
1641
1642 /**
1643 * What a `config.describe` hook returns: the label, help text and hidden
1644 * flag the menu uses; the key and provider stay as they were.
1645 */
1646 export type ConfigDescribeResult = Omit<ConfigDescribeInput, 'key' | 'provider'>;
1647
1648 /**
1649 * How a `/config` row takes its value: `boolean` toggles, `choice` picks one
1650 * of its `options`, `text` takes a string, `number` a number.
1651 */
1652 export type ConfigKind = 'boolean' | 'choice' | 'text' | 'number';
1653
1654 /**
1655 * Where a `config.set` came from, in `prompt.submit`'s words: the person
1656 * in the `/config` menu (`composer`), the bridge, or a plugin, named.
1657 *
1658 * Set by the engine; `next(e)` passes it on as received and none sets it.
1659 */
1660 export type ConfigOrigin = {
1661 /**
1662 * The person's own change in the `/config` menu (a toggle, a pick, a
1663 * typed value), or their `/config key=value`.
1664 */
1665 kind: 'composer';
1666 } | {
1667 /**
1668 * A `/config key=value` that arrived over the Remote Control bridge (a
1669 * phone or web client, or a relay): not attestably the owner's hand.
1670 */
1671 kind: 'bridge';
1672 } | {
1673 /**
1674 * A plugin's `$.config.set`; that plugin's own hooks do not see it.
1675 */
1676 kind: 'plugin';
1677 /**
1678 * The calling plugin's name.
1679 */
1680 name: string;
1681 };
1682
1683 /**
1684 * One `/config` row as `$.config.list()` returns it: what the menu would
1685 * draw now, after every `config.describe` hook, a hidden row left out.
1686 */
1687 export type ConfigRow = {
1688 /**
1689 * Names the row: the panel's id for a built-in, `<plugin>.<field>` for a
1690 * plugin's `userConfig` field; what `$.config.set` takes.
1691 */
1692 key: string;
1693 /**
1694 * What the menu draws for the row, before its value.
1695 */
1696 label: string;
1697 /**
1698 * The help text under the label, when the row has one.
1699 */
1700 description?: string;
1701 /**
1702 * How the row takes its value (ConfigKind).
1703 */
1704 kind: ConfigKind;
1705 /**
1706 * What the row holds now.
1707 */
1708 value: ConfigValue;
1709 /**
1710 * The values a `choice` row takes, in order (a plugin string field's
1711 * declared `options` for its row); absent otherwise.
1712 */
1713 options?: readonly string[];
1714 /**
1715 * Who owns the row: the engine for the panel's own, else the plugin.
1716 */
1717 provider: Origin;
1718 /**
1719 * Whether a trusted source (managed settings, the organization's policy)
1720 * owns the value, so the menu shows it and refuses a change.
1721 */
1722 isLocked: boolean;
1723 };
1724
1725 /**
1726 * `config.set`'s input as a plugin's `$.config.set(args)` takes it: the
1727 * row's key and the value; the engine fills the rest.
1728 */
1729 export type ConfigSetArgs = Pick<ConfigSetInput, 'key' | 'value'>;
1730
1731 /**
1732 * The input of `config.set`: one `/config` row about to change, from the
1733 * menu or a plugin's `$.config.set`, with what it holds now and who owns it.
1734 */
1735 export type ConfigSetInput = {
1736 /**
1737 * Names the row: the panel's own id for a built-in (`theme`, `verbose`,
1738 * `autoCompact`), `<plugin>.<field>` for a plugin's `userConfig` field.
1739 *
1740 * The key a matcher narrows on; pinned: a rewrite is refused.
1741 */
1742 key: string;
1743 /**
1744 * What the row is being set to; `next({ ...e, value })` clamps or
1745 * replaces it, held to the row's kind (a toggle takes a boolean).
1746 */
1747 value: ConfigValue;
1748 /**
1749 * What the row holds before the change, as the menu shows it. Pinned.
1750 */
1751 previous: ConfigValue;
1752 /**
1753 * Who owns the row: `{ plugin: "engine", tier: "core" }` for the panel's
1754 * own, the plugin and its tier for a `userConfig` field. Pinned.
1755 */
1756 provider: Origin;
1757 /**
1758 * Where the change came from (ConfigOrigin): the person in the menu
1759 * (`composer`) or a plugin's `$.config.set`. Pinned.
1760 */
1761 origin: ConfigOrigin;
1762 };
1763
1764 /**
1765 * What a `config.set` hook returns and what `next(e)` resolves to:
1766 * `{ value }` once written, or `{ deny: reason }`, the row left as it was.
1767 *
1768 * The menu shows a deny's reason beside the row; a plugin's `$.config.set`
1769 * resolves with it.
1770 */
1771 export type ConfigSetResult = {
1772 value: ConfigValue;
1773 deny?: undefined;
1774 } | {
1775 deny: string;
1776 value?: undefined;
1777 };
1778
1779 /**
1780 * A `/config` row's value as a hook and `$.config` see it: a toggle's
1781 * boolean, a choice's or a text's string, a number, or a list of strings.
1782 */
1783 export type ConfigValue = boolean | string | number | readonly string[];
1784
1785 /**
1786 * One custom agent whose description the Agent tool's prompt carries;
1787 * built-in agents are left out.
1788 */
1789 export type ContextAgent = {
1790 /**
1791 * The agent's type, as the Agent tool names it.
1792 */
1793 agentType: string;
1794 /**
1795 * Where it was defined, by the engine's word (`projectSettings`,
1796 * `userSettings`, `plugin`); the display label is the renderer's.
1797 */
1798 source: string;
1799 /**
1800 * The description's estimated tokens.
1801 */
1802 tokens: number;
1803 };
1804
1805 /**
1806 * The token counts the last API response of the live window reported, as
1807 * the API spells them; the breakdown's `Messages` row is reconciled to it.
1808 */
1809 export type ContextApiUsage = {
1810 /**
1811 * Uncached input tokens the response was answered over.
1812 */
1813 input_tokens: number;
1814 /**
1815 * Tokens the response generated.
1816 */
1817 output_tokens: number;
1818 /**
1819 * Input tokens written to the prompt cache by the request.
1820 */
1821 cache_creation_input_tokens: number;
1822 /**
1823 * Input tokens read from the prompt cache by the request.
1824 */
1825 cache_read_input_tokens: number;
1826 };
1827
1828 /**
1829 * How a context breakdown is counted: `full` with the token-count API per
1830 * category, `summary` from the last response's usage and local estimates.
1831 *
1832 * The SDK's `get_context_usage` takes the same two words as its `detail`.
1833 */
1834 export type ContextBreakdownDetail = 'summary' | 'full';
1835
1836 /**
1837 * One row of the breakdown, as /context lists it beside the grid (`System
1838 * prompt`, `Messages`, `Free space`, `Autocompact buffer`).
1839 */
1840 export type ContextCategory = {
1841 /**
1842 * The row's label as /context prints it.
1843 */
1844 name: string;
1845 /**
1846 * The row's estimated tokens; a `deferred` row's do not count toward the
1847 * total.
1848 */
1849 tokens: number;
1850 /**
1851 * The theme colour /context draws the row and its squares in, by its key
1852 * in the theme (`promptBorder`, `inactive`, `permission`).
1853 */
1854 color: string;
1855 /**
1856 * Whether the row is tool schemas loaded on demand, which the grid leaves
1857 * out; the same fact as `kind` `deferred`.
1858 */
1859 isDeferred: boolean;
1860 /**
1861 * What the row is (ContextCategoryKind), stamped by the engine.
1862 */
1863 kind: ContextCategoryKind;
1864 };
1865
1866 /**
1867 * What a breakdown row is; branch on this, never on the row's `name`.
1868 *
1869 * `used` content occupies the window, `free` is the window left, `buffer`
1870 * the compaction reserve, `deferred` tool schemas loaded on demand and
1871 * outside the window.
1872 */
1873 export type ContextCategoryKind = 'used' | 'free' | 'buffer' | 'deferred';
1874
1875 /**
1876 * One square of the grid /context draws: which row it belongs to and how
1877 * full it is.
1878 */
1879 export type ContextGridSquare = {
1880 /**
1881 * The theme colour of the square's row, by its key in the theme.
1882 */
1883 color: string;
1884 /**
1885 * Whether the square holds any of its row's tokens.
1886 */
1887 isFilled: boolean;
1888 /**
1889 * The `name` of the row the square belongs to (`Free space` for the
1890 * window left).
1891 */
1892 categoryName: string;
1893 /**
1894 * The row's tokens, repeated on each of its squares.
1895 */
1896 tokens: number;
1897 /**
1898 * The row's share of the window as a whole percentage, repeated likewise.
1899 */
1900 percentage: number;
1901 /**
1902 * How full this one square is, 0 to 1: a row's last square is the partial
1903 * one (/context draws it hollow under 0.7).
1904 */
1905 squareFullness: number;
1906 };
1907
1908 /**
1909 * One MCP tool's schema as the context carries it.
1910 */
1911 export type ContextMcpTool = {
1912 /**
1913 * The tool's wire name (`mcp__linear__create_issue`).
1914 */
1915 name: string;
1916 /**
1917 * The server it belongs to, as /mcp lists it.
1918 */
1919 serverName: string;
1920 /**
1921 * The schema's estimated tokens.
1922 */
1923 tokens: number;
1924 /**
1925 * Whether the schema is inside the window now: always, unless tool
1926 * schemas load on demand and this one has not been searched for yet.
1927 */
1928 isLoaded: boolean;
1929 };
1930
1931 /**
1932 * One memory file the context carries (a CLAUDE.md, a rules file, an
1933 * auto-memory entry).
1934 */
1935 export type ContextMemoryFile = {
1936 /**
1937 * The file's path, absolute.
1938 */
1939 path: string;
1940 /**
1941 * The display label of where it was loaded from (`Project`, `User`,
1942 * `Local`, `Managed`, `AutoMem`).
1943 */
1944 type: string;
1945 /**
1946 * The file's estimated tokens.
1947 */
1948 tokens: number;
1949 };
1950
1951 /**
1952 * One skill whose listing the context carries.
1953 */
1954 export type ContextSkill = {
1955 /**
1956 * The skill's name as `/skills` lists it.
1957 */
1958 name: string;
1959 /**
1960 * Where it came from, by the engine's word (`userSettings`, `plugin`,
1961 * `built-in`, `mcp`, `syncedSkills`); the display label is the renderer's.
1962 */
1963 source: string;
1964 /**
1965 * The providing plugin's name, when the skill comes from one.
1966 */
1967 pluginName?: string;
1968 /**
1969 * The listing's estimated tokens.
1970 */
1971 tokens: number;
1972 };
1973
1974 /**
1975 * The skills the context lists for the model: how many there are, how many
1976 * fit the listing's budget, and each one's share.
1977 */
1978 export type ContextSkills = {
1979 /**
1980 * How many skills the session has.
1981 */
1982 totalSkills: number;
1983 /**
1984 * How many the listing included within its token budget.
1985 */
1986 includedSkills: number;
1987 /**
1988 * The listing's tokens in all.
1989 */
1990 tokens: number;
1991 /**
1992 * One entry per listed skill.
1993 */
1994 skillFrontmatter: ContextSkill[];
1995 };
1996
1997 /**
1998 * The slash commands the Skill tool's prompt lists, counted.
1999 */
2000 export type ContextSlashCommands = {
2001 /**
2002 * How many commands the session has.
2003 */
2004 totalCommands: number;
2005 /**
2006 * How many the listing included.
2007 */
2008 includedCommands: number;
2009 /**
2010 * The listing's tokens in all.
2011 */
2012 tokens: number;
2013 };
2014
2015 /**
2016 * How the window the breakdown measures against was settled; /context
2017 * prints its `Auto-compact window` line off this.
2018 *
2019 * `auto` is the model's own limit; the rest name a compaction window by who
2020 * set it: the `CLAUDE_CODE_AUTO_COMPACT_WINDOW` variable, the settings, the
2021 * account, an experiment, the model's default, or an unrecognised model's.
2022 */
2023 export type ContextWindowSource = 'env' | 'settings' | 'clientdata' | 'experiment' | 'model-default' | 'unknown-model' | 'auto';
2024
2025 /**
2026 * The plugin's identity (`plugin`) and the nouns core contributes to `$` as
2027 * the innermost step of the `engine.create` fold.
2028 *
2029 * A plugin's finished `$` (EngineInterface) has every core noun an outer
2030 * step did not withhold, and every noun the plugins' steps added.
2031 */
2032 export interface CoreEngineInterface {
2033 /**
2034 * This plugin, as loaded: its manifest name and its directory.
2035 */
2036 plugin: {
2037 /**
2038 * From plugin.json; debug-log and `$.ui.log` lines carry it.
2039 */
2040 name: string;
2041 /**
2042 * The plugin's directory (the one holding plugin.json), absolute.
2043 */
2044 root: string;
2045 };
2046 /**
2047 * Display: a line under an open dialog, a redraw or a repaint, a
2048 * transcript or debug line, panes the surface places, a window or ring.
2049 */
2050 ui: {
2051 /**
2052 * Shows `text` as one line under the dialog open for `tool_use_id`, or
2053 * removes the line when `text` is undefined.
2054 *
2055 * Core removes the line when the call resolves. A call that is not open
2056 * is refused, as is another plugin's `$.tool.call` run.
2057 *
2058 * @param tool_use_id the call whose open dialog gets the line
2059 * @param text the line to show; undefined removes it
2060 * @example
2061 * $.ui.notice(e.tool_use_id, "checked by my-plugin"); return next(e)
2062 */
2063 notice: (tool_use_id: string, text: string | undefined) => void;
2064 /**
2065 * Re-runs an event whose results the engine caches: `ui.render` draws the
2066 * instances this plugin may draw again; the others drop the cached answers.
2067 *
2068 * A render hook whose state changed (a countdown) calls it for a redraw, at
2069 * most ten a second, thirty for the shown pane and the band (calls sooner
2070 * fold); a prompt section, context or attachment hook: dropped next turn.
2071 *
2072 * @param event `ui.render`, or a cached-answer event: `prompt.section`,
2073 * `prompt.context`, `prompt.attachment`, `tool/command/config.describe`
2074 */
2075 invalidate: (event: InvalidatableEventName) => void;
2076 /**
2077 * Repaints a mounted `Raster` this plugin's own render hook drew with new
2078 * cells, or swaps a keyed `Image` it drew to a new source; no redraw.
2079 *
2080 * The surface paints the cells or source at its next frame, so blits
2081 * between frames fold into one: up to 120 a second taken, some sixty
2082 * shown. An Image swap sends one small command; a resize is a redraw.
2083 *
2084 * @param args `requestId` (the site), `key`, and `cells` (RasterProps) or
2085 * `source` (ImageSource); `columns`, `rows` (the mounted size)
2086 * @returns `{}` once the cells or source are its next frame, or `{ deny }`
2087 * (not mounted, not this plugin's, another size, cells that do
2088 * not decode, a bad source, or an Image drawing its alt there:
2089 * no placeholder images, or a file this terminal cannot read)
2090 * @example
2091 * $.clock.every(33, () => $.ui.blit({ requestId, key, cells: frame() }))
2092 * @example
2093 * await $.ui.blit({ requestId: 'browser', key: 'view',
2094 * source: { shm: name, format: 'rgb', width, height } })
2095 */
2096 blit: (args: UiBlitArgs) => Promise<UiBlitResult>;
2097 /**
2098 * The elements of the surface `e` is drawn on (Elements[e.surface]): a
2099 * frozen table of constructors, the JSX tags a render hook draws with.
2100 *
2101 * A read, not a dispatch: the engine ran `ui.resolve` (the other hooks,
2102 * then core) at load, per surface and component. Narrowed `e.surface`:
2103 * that table exactly; unnarrowed: the union, so shared names type-check.
2104 *
2105 * @param e this hook's own `ui.render` argument (its surface and
2106 * component pick the table)
2107 * @returns the surface's frozen element table (`Elements[e.surface]`)
2108 * @example
2109 * const { Box, Text } = $.ui.resolve(e)
2110 * return <Box>{await next(e)}<Text dimColor>done</Text></Box>
2111 */
2112 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
2113 /**
2114 * Appends one line to the transcript, drawn like a system notice (dim;
2115 * not sent to the model), or with `{ to: "debug" }` to the debug log alone.
2116 *
2117 * A row of its own at the next frame, in logging order; a `-p` or SDK
2118 * host receives it as `ui_log`; the debug log has every line under this
2119 * plugin's name. Raised as `ui.log`: a hook above may rewrite `e.to`.
2120 *
2121 * @param text the line's text
2122 * @param options `to`: `transcript` (the default) or `debug`
2123 * @example
2124 * $.ui.log(`prompt from ${e.origin.kind}: ${e.text.length} chars`)
2125 * @example
2126 * $.ui.log(`cache miss for ${e.tool_use_id}`, { to: "debug" })
2127 */
2128 log: (text: string, options?: UiLogOptions) => void;
2129 /**
2130 * Asks the user `question` in the engine's own AskUserQuestion dialog and
2131 * resolves to the label they chose, or the text typed under "Other".
2132 *
2133 * A `tool.call` of `AskUserQuestion` through every hook but the calling
2134 * one, drawn by `ui.render` on `AskUserQuestion`; a multi-select answer is
2135 * comma-joined. Rejects when dismissed, and in a `-p` run (no one to ask).
2136 *
2137 * @param question the question, ending in a question mark
2138 * @param options 2-4 option labels, or `{ options, header, multiSelect }`
2139 * @returns the label chosen, the chosen labels comma-joined, or free text
2140 * typed under "Other" (so compare it with the labels exactly)
2141 * @example
2142 * const mood = await $.ui.ask("How careful?", ["Bold", "Careful"])
2143 */
2144 ask: (question: string, options?: readonly string[] | AskOptions) => Promise<string>;
2145 /**
2146 * Shows `text` on the notification bar under the prompt for a few
2147 * seconds, the way the engine's own "context left" notice appears.
2148 *
2149 * It leaves the transcript and the model untouched.
2150 *
2151 * @param text the line to show; an unpaired surrogate half in it is drawn
2152 * as U+FFFD
2153 * @param options `timeoutMs`: how long it stays (default 4000)
2154 * @example
2155 * $.ui.toast(`turn took ${Math.round(e.durationMs / 1000)} s`)
2156 */
2157 toast: (text: string, options?: ToastOptions) => void;
2158 /**
2159 * Pins `text` as this plugin's status line under the prompt, beside the
2160 * engine's own pinned notices, until the next call replaces it.
2161 *
2162 * One per plugin; `undefined` removes it.
2163 *
2164 * @param text the line to keep on screen (an unpaired surrogate half is
2165 * drawn as U+FFFD); undefined clears it
2166 * @example
2167 * $.ui.status("thinking..."); return next(e)
2168 */
2169 status: (text: string | undefined) => void;
2170 /**
2171 * Opens a pane: a framed region the surface places, whose body this
2172 * plugin draws by hooking `ui.render` for `{ component: "Pane" }`.
2173 *
2174 * One instance per id (`requestId`): opening an open id retitles it; a hook
2175 * on `ui.open` may refuse it. The keyboard is the person's; unasked, it
2176 * waits undrawn below 144 columns (110 once asked), judged at each open.
2177 *
2178 * @param pane `id` (1-64 of letters, digits, `_`, `-`), `title`, `focus`,
2179 * `closeOnEscape` and `holdToasts` (a dialog), `rows` / `columns` wanted
2180 * @returns settles once the pane is open (or retitled)
2181 * @example
2182 * await $.ui.open({ id: "clock", title: "Clock" })
2183 * @example
2184 * await $.ui.open({ id: "ask", focus: true, closeOnEscape: true, rows: 9 })
2185 */
2186 open: (pane: PaneOpenArgs) => Promise<void>;
2187 /**
2188 * Closes one of the open panes; an id that is not open is left alone.
2189 *
2190 * Every close raises `ui.close`, `e.origin` naming whose it is: this call
2191 * (`plugin`), the person's mark or key (`person`), an unload (`unload`).
2192 * A hook answering without `next` keeps the pane open, save on an unload.
2193 *
2194 * @param pane `id`: the id the pane was opened under
2195 * @returns settles once the pane is gone or a hook answered for it;
2196 * rejects on a hook's `{ deny }`
2197 * @example
2198 * onPress: () => $.ui.close({ id: "clock" })
2199 */
2200 close: (pane: PaneCloseArgs) => Promise<void>;
2201 /**
2202 * Lists this plugin's own open panes (UiPane): each one's id and title,
2203 * and whether it is shown, holds the keyboard, and is placed.
2204 *
2205 * The engine's record, not the module's: a module reloaded while its
2206 * pane stayed up finds it here. Another plugin's panes are not listed.
2207 *
2208 * @returns the panes in open order, placed ones first; empty with none
2209 * @example
2210 * const isUp = (await $.ui.panes()).some(pane => pane.id === "clock")
2211 * if (!isUp) await $.ui.open({ id: "clock", title: "Clock" })
2212 */
2213 panes: () => Promise<readonly UiPane[]>;
2214 /**
2215 * Scrolls something into view as the DOM's `scrollIntoView` would: a
2216 * render instance by `requestId`, an element by `key`, a site's edge.
2217 *
2218 * A site of this plugin's (its pane, the band it draws into) moves under
2219 * the event `ui.scroll`, origin `plugin`. A transcript row moves only
2220 * while this call answers the person's own input, where one scrolls.
2221 *
2222 * @param args `to` (what), `in` (which site, required for `start` and
2223 * `end`), `block` (where it lands; `nearest` by default)
2224 * @returns `{}` once it moved, or `{ deny }` saying why not
2225 * @example
2226 * onPress: () => $.ui.scroll({ in: "log", to: "end" })
2227 */
2228 scroll: (args: UiScrollArgs) => Promise<UiScrollResult>;
2229 /**
2230 * Moves the focus ring of one of this plugin's sites onto an element it
2231 * drew there, as the DOM's `element.focus()`, while it holds the keys.
2232 *
2233 * Raised as the event `ui.focus`, origin `plugin`; the engine's inverse
2234 * marks the element. The keyboard is the person's to give: a site not
2235 * holding it, or holding it on another plugin's element, is `{ deny }`.
2236 *
2237 * @param args `requestId` (which site: a pane's id, the band's) and `key`
2238 * (the element's, as drawn)
2239 * @returns `{}` once it moved, or `{ deny }` saying why not
2240 * @example
2241 * onPress: () => $.ui.focus({ requestId: "files", key: "row:0" })
2242 */
2243 focus: (args: UiFocusArgs) => Promise<UiFocusResult>;
2244 };
2245 /**
2246 * Completions through the session's own client and credentials.
2247 */
2248 model: {
2249 /**
2250 * Runs one text completion through the session's own API client and
2251 * resolves to the reply's text.
2252 *
2253 * No tools, no history, no system prompt beyond the CLI's identity block
2254 * and `request.system`.
2255 *
2256 * @param request the model (an alias such as `haiku`, or a full id,
2257 * resolved like a `--model` value), the prompt, and a token cap
2258 * @returns the reply's text
2259 * @example
2260 * const reply = await $.model.complete({ model: "haiku", prompt: "Hi." })
2261 */
2262 complete: (request: ModelCompleteRequest) => Promise<string>;
2263 /**
2264 * Runs one tool-less completion over the session's OWN transcript, sharing
2265 * the main thread's prompt cache; the reply's text and the fork's usage.
2266 *
2267 * Not `complete`: sharing the cache prefix means the model and system
2268 * prompt are the session's, read from its last turn's cache-safe snapshot,
2269 * and tools are denied. Null on a cold snapshot or an API error.
2270 *
2271 * @param request the one user message the fork answers
2272 * @returns the reply's text with the fork's usage, or null on a cold
2273 * snapshot or an API error
2274 * @example
2275 * const reply = await $.model.fork({ prompt: "One line to learn?" })
2276 * if (reply !== null) $.ui.log(`${reply.usage.output_tokens} tokens`)
2277 */
2278 fork: (request: ModelForkRequest) => Promise<ModelForkResult | null>;
2279 /**
2280 * Picks one of `labels` for `text` with one completion over
2281 * `$.model.complete` and a fixed classifier prompt.
2282 *
2283 * `text` is data; the model answers with a label alone. It resolves
2284 * `undefined` when the answer named none of `labels`. A failed request,
2285 * an abort or a reply with no text rejects, naming the cause.
2286 *
2287 * @param text what to classify
2288 * @param labels the labels to choose from (2 or more)
2289 * @param options `model`: an alias or id; default the engine's small
2290 * fast model
2291 * @returns the label the model named, or undefined when it named none;
2292 * rejects when the request fails or the reply has no text
2293 * @example
2294 * const kind = await $.model.classify(e.text, ["bug", "feature"])
2295 * if (kind === undefined) return next(e)
2296 */
2297 classify: (text: string, labels: readonly string[], options?: ClassifyOptions) => Promise<string | undefined>;
2298 };
2299 /**
2300 * Sound: clip playback and platform speech.
2301 */
2302 audio: {
2303 /**
2304 * Plays one audio clip, starting now; clips are not queued, so two calls
2305 * play together (a bed under speech).
2306 *
2307 * `{ asset }` is the plugin's own file, loaded by the engine and played
2308 * through the platform's player (`afplay` on macOS). Resolves when
2309 * playback ends; rejects, naming the cause, when the clip cannot play.
2310 *
2311 * @param clip the plugin's own file (`{ asset }`), a URL the engine
2312 * fetches, or the bytes as base64 with their MIME type
2313 * @param options `shouldLoop`, `gain`, and an AbortSignal that stops the
2314 * clip
2315 */
2316 play: (clip: AudioClip, options?: PlayOptions) => Promise<void>;
2317 /**
2318 * Speaks `text` with the platform's own synthesizer (`say` on macOS).
2319 * Plain text.
2320 *
2321 * Utterances are queued among themselves; clips are not. Resolves when
2322 * the utterance has ended; rejects, naming the cause, when there is no
2323 * synthesizer, the voice is not installed, or the utterance failed.
2324 *
2325 * @param text what to say, as plain text
2326 * @param options `voice`: the system voice's exact name (`Samantha`);
2327 * absent, the synthesizer's default
2328 * @returns which synthesizer spoke, once the utterance has ended
2329 */
2330 speak: (text: string, options?: SpeakOptions) => Promise<SpeakResult>;
2331 };
2332 /**
2333 * The engine's connected MCP servers.
2334 */
2335 mcp: {
2336 /**
2337 * Calls `tool` on one of the engine's connected MCP servers with the
2338 * engine's own connection and credentials.
2339 *
2340 * A `cached` server is dialed on first use. No permission prompt: the
2341 * plugin's call, seen by the hooks above it, is the grant. Positional, not
2342 * the `{ tool: "mcp__server__tool", ... }` shape a `tool.call` hook sees.
2343 *
2344 * @param server the server's name as /mcp lists it (`claude.ai Gmail`;
2345 * the tool-name spelling `claude_ai_Gmail` is accepted too)
2346 * @param tool the tool's name on that server (`create_draft`)
2347 * @param args the tool's arguments; none when absent
2348 * @returns the tool's result as MCP returns it: `content` blocks and
2349 * `isError`
2350 * @example
2351 * const { content } = await $.mcp.call("claude.ai Gmail", "create_draft", {
2352 * to: "team@example.com",
2353 * subject: "Release notes",
2354 * })
2355 */
2356 call: (server: string, tool: string, args?: Record<string, unknown>) => Promise<McpToolResult>;
2357 };
2358 /**
2359 * The running session, read as plain data, and compacting it.
2360 */
2361 session: {
2362 /**
2363 * Returns the transcript so far, one entry per user or assistant
2364 * message; progress rows, `$.ui.log` lines and notices are not messages.
2365 *
2366 * Each entry is a SessionMessage, `{ role, text, toolUses }` (a user
2367 * message may add `toolResults`; a `toolUses` entry adds its `result` and
2368 * `text` once answered). A long transcript answers its newest 4096.
2369 *
2370 * @example
2371 * const last = (await $.session.messages()).at(-1)
2372 */
2373 messages: () => Promise<SessionMessage[]>;
2374 /**
2375 * Returns the directory the session runs in, absolute.
2376 */
2377 cwd: () => Promise<string>;
2378 /**
2379 * Returns the session's project root, absolute: where it started, or
2380 * where `/cd`, a host's directory change or a worktree move took it.
2381 *
2382 * A shell `cd` during the session does not move it; nested instruction
2383 * files are read only beneath it.
2384 */
2385 root: () => Promise<string>;
2386 /**
2387 * Returns the main loop's model, as `/model` shows it.
2388 */
2389 model: () => Promise<string>;
2390 /**
2391 * Returns how many prompts the user has sent this session (user turns in
2392 * the transcript).
2393 */
2394 turns: () => Promise<number>;
2395 /**
2396 * Returns the session's id (the transcript file's name).
2397 */
2398 id: () => Promise<string>;
2399 /**
2400 * Returns the git repository the session runs in, read from the working
2401 * copy on each call; null when the directory is not inside one.
2402 *
2403 * @example
2404 * const repo = await $.session.repo(); const publicRepo = !repo?.internal
2405 */
2406 repo: () => Promise<SessionRepo | null>;
2407 /**
2408 * Returns every surface the session draws on, each once: `terminal` under
2409 * the REPL first, then the remote ones in the order they attached.
2410 *
2411 * A session may draw on several at once (a terminal and two phones):
2412 * clients attach (`session.attach`) and detach, and a render hook still
2413 * reads `e.surface` per ask. Empty in a plain -p run; never rejects.
2414 *
2415 * @example
2416 * const inApp = (await $.session.surfaces()).some(s => s !== "terminal")
2417 */
2418 surfaces: () => Promise<readonly RenderSurface[]>;
2419 /**
2420 * Returns the first of `$.session.surfaces()`, or null where nothing
2421 * draws.
2422 *
2423 * @deprecated use `surfaces()`; a session may draw on several surfaces at
2424 * once
2425 */
2426 surface: () => Promise<RenderSurface | null>;
2427 /**
2428 * Returns the context window's fill, the rate-limit windows and the
2429 * cost, as the status line has them; with `breakdown`, by category too.
2430 *
2431 * The plain call costs nothing; `"full"` counts each category with the
2432 * token-count API as /context does, `"summary"` estimates locally, and
2433 * `context.breakdown` comes back in the SDK's `get_context_usage` shape.
2434 *
2435 * @param args `{ breakdown, columns }`: how the breakdown is counted and
2436 * the width its grid is drawn in; nothing for the status line's figures
2437 * @returns `{ context, rateLimits, cost }` as the status line has them
2438 * @example
2439 * const { context } = await $.session.usage()
2440 * if ((context.percent ?? 0) >= 85) await $.session.compact()
2441 * @example
2442 * const usage = await $.session.usage({ breakdown: "full", columns })
2443 * for (const row of usage.context.breakdown?.gridRows ?? []) draw(row)
2444 */
2445 usage: (args?: SessionUsageArgs) => Promise<SessionUsage>;
2446 /**
2447 * Returns the version of the engine the session runs on, the release it
2448 * is built from, and when it was built.
2449 *
2450 * The same three values the engine's own analytics rows carry, answered
2451 * in every mode and build; `base` is absent when the version is not
2452 * spelled as a release, `builtAt` in a run from source that stamps none.
2453 *
2454 * @returns `{ version, base, builtAt }`: the full version, its release
2455 * (`2.1.280`, or `2.1.280-dev` for a development build) and an
2456 * ISO 8601 build time
2457 * @example
2458 * const { version, base, builtAt } = await $.session.version()
2459 * row.env = { version, version_base: base, build_time: builtAt }
2460 * @example
2461 * const isDevelopmentBuild = (await $.session.version()).base?.endsWith("-dev")
2462 */
2463 version: () => Promise<SessionVersion>;
2464 /**
2465 * Compacts the conversation: the event `session.compact` with `trigger`
2466 * `plugin`, the same call `/compact` makes, between turns.
2467 *
2468 * It runs through every hook but the calling one, then core: a summary
2469 * and the kept messages in the transcript's place. Resolves `{ skip }`
2470 * when a hook vetoed it; rejects while a turn runs.
2471 *
2472 * @example
2473 * const { skip } = await $.session.compact({ instructions: "the plan" })
2474 */
2475 compact: EventCalls['session']['compact'];
2476 /**
2477 * Holds the session's Anthropic credential on the host and answers an
2478 * opaque handle and its kind; the secret never reaches the plugin.
2479 *
2480 * The handle is spent through `$.http.fetch(url, { auth: handle })`,
2481 * which sets the credential header, only for a first-party host. Null
2482 * where the build or the provider has no first-party credential to hold.
2483 *
2484 * @example
2485 * await $.http.fetch(url, { auth: (await $.session.authorize())?.handle })
2486 */
2487 authorize: () => Promise<SessionAuthorization>;
2488 };
2489 /**
2490 * The running model turn: ending it.
2491 */
2492 turn: {
2493 /**
2494 * Cancels the running model turn: the one whose id `turn.start` handed
2495 * this plugin, its running tools stopped, no interruption marker.
2496 *
2497 * The event `turn.abort`, seen by the hooks above; the prompt this
2498 * plugin submits next is the context. Rejects, naming both ids, when
2499 * `turnId` is not the running turn's; a hook may end its own turn.
2500 *
2501 * @param input `turnId`: the id `turn.start` carried
2502 * @example
2503 * on("turn.start", ($, e, next) => { held = e.turnId; return next(e) })
2504 */
2505 abort: (input: OpEventOf['turn.abort']) => Promise<void>;
2506 };
2507 /**
2508 * Submitting a prompt the model reads as a user turn, and the person's
2509 * prompt box: read as it stands, written, or proposed into.
2510 */
2511 prompt: {
2512 /**
2513 * Submits a prompt: the event `prompt.submit`, the same call the engine
2514 * makes for a typed prompt; `input.text` runs when the session is idle.
2515 *
2516 * It goes through every hook but the calling one (the plugin's others
2517 * see it) with `e.origin` `{ kind: 'plugin', name }`, the name the
2518 * model reads it under unless a hook leaves it out of its answer.
2519 *
2520 * @example
2521 * void $.prompt.submit({ text: "List the TODOs you just mentioned." })
2522 */
2523 submit: EventCalls['prompt']['submit'];
2524 /**
2525 * Returns the prompt box as it stands, the draft typed so far and the
2526 * cursor's offset into it, so a `fill` can keep what the person typed.
2527 *
2528 * Never rejects: `{ text: '', cursor: 0 }` where the session draws no box
2529 * (a -p run, an SDK host) or none is mounted yet.
2530 *
2531 * @example
2532 * const { text, cursor } = await $.prompt.read()
2533 */
2534 read: () => Promise<PromptBox>;
2535 /**
2536 * Puts `input.text` in the prompt box as the draft, by `mode`: `replace`
2537 * (the default) over it, `append` after it, `insert` at the cursor.
2538 *
2539 * The event `prompt.fill` through the other plugins' hooks; `isFilled:
2540 * false` under a dialog or headless. To hand the model text WITH the next
2541 * prompt instead, a `prompt.submit` hook adds `context` (second example).
2542 *
2543 * @example
2544 * await $.prompt.fill({ text: `> ${quote}\n`, mode: "insert" })
2545 * @example
2546 * ($, e, next) => next({ ...e, context: [...(e.context ?? []), hunk] })
2547 */
2548 fill: (input: PromptFillArgs) => Promise<PromptFilled>;
2549 /**
2550 * Proposes `input.text` as the prompt box's dim suggestion, Tab to take:
2551 * the event `prompt.suggest`, as the engine's own guess after a turn.
2552 *
2553 * It goes through every other plugin's hook with `e.origin` `{ kind:
2554 * 'plugin', name }`, the engine's own suggestions on or off; `{ isShown:
2555 * false }` while the box holds text, a turn runs, or headless (no box).
2556 *
2557 * @example
2558 * void $.prompt.suggest({ text: "run the tests you just wrote" })
2559 */
2560 suggest: EventCalls['prompt']['suggest'];
2561 };
2562 /**
2563 * The tools the model has in this session, and running one.
2564 */
2565 tool: {
2566 /**
2567 * Returns the tools the model can call now, built-in and MCP alike, in
2568 * the order the model sees them.
2569 *
2570 * @example
2571 * const names = (await $.tool.list()).map(t => t.name)
2572 */
2573 list: () => Promise<ToolInfo[]>;
2574 /**
2575 * Calls a tool: the event `tool.call`, the same call the engine makes for
2576 * the model's tool calls, under a `tool_use_id` of its own.
2577 *
2578 * It runs through every hook but the calling one (the plugin's others
2579 * see it), the permission check and its dialog, then the tool. Rejects
2580 * when no tool has that name or the call is aborted.
2581 *
2582 * @example
2583 * const { text } = await $.tool.call({ tool: "Read", file_path: "a.md" })
2584 */
2585 call: EventCalls['tool']['call'];
2586 /**
2587 * Asks the engine's permission decision for a tool call now: the event
2588 * `tool.check`, resolved to `{ decision, reason?, rule? }`.
2589 *
2590 * The hooks run (the calling hook's own frame skipped, `next.origin` this
2591 * plugin, no `tool_use_id`); nothing runs, no dialog opens, no PreToolUse
2592 * hook or classifier is asked.
2593 *
2594 * @example
2595 * const { decision } = await $.tool.check({ tool: "Read", input })
2596 */
2597 check: EventCalls['tool']['check'];
2598 /**
2599 * Declares a tool the model can call from the next prompt on: the name,
2600 * description and input schema of `mcp__<plugin>__<name>`.
2601 *
2602 * Serve it with a `tool.call` hook on `{ tool: "mcp__<plugin>__<name>" }`
2603 * that returns the result (a call no hook answers fails); a name registered
2604 * again is replaced. Rejects until the session binds, at `session.start`.
2605 *
2606 * @param tool `name`, `description` (what the model reads), `inputSchema`
2607 * (a JSON schema object; default `{ type: "object" }`)
2608 * @returns `{ tool }`, the registered tool's full name
2609 * `mcp__<plugin>__<name>`
2610 * @example
2611 * await $.tool.register({ name: "weather", description: "Weather." })
2612 */
2613 register: (tool: ToolSpec) => Promise<OpValueOf['tool.register']>;
2614 };
2615 /**
2616 * The slash commands the person can run in this session, and running one.
2617 */
2618 command: {
2619 /**
2620 * Returns the slash commands the person can run now, built-in, plugin
2621 * and MCP alike, in the order the typeahead lists them.
2622 *
2623 * @example
2624 * const names = (await $.command.list()).map(c => c.name)
2625 */
2626 list: () => Promise<CommandInfo[]>;
2627 /**
2628 * Runs a slash command as if the person typed `/command args`: the
2629 * event `command.run`, queued and run once the session is idle.
2630 *
2631 * It runs through every hook but the calling one with `e.origin`
2632 * `{ kind: 'plugin', name }`, its lines in the transcript. Rejects an
2633 * unknown name, and inside a hook the turn is waiting on.
2634 *
2635 * @example
2636 * const { text } = await $.command.run({ command: "status" })
2637 */
2638 run: EventCalls['command']['run'];
2639 /**
2640 * Declares the slash command `/<name>` for this session, listed in the
2641 * typeahead from the next keystroke on.
2642 *
2643 * Serve it with a `command.run` hook on `{ command: "<name>" }` that
2644 * returns `{ text }`; a run no hook answers says so as its output.
2645 * Registering a name again replaces it; a built-in's name is refused.
2646 *
2647 * @param command `name`, `description` (what the menu shows),
2648 * `argumentHint` (dim after the name), `immediate` (runs mid-turn)
2649 * @returns `{ command }`, the registered name
2650 * @example
2651 * await $.command.register({ name: "hello", description: "Says hi." })
2652 */
2653 register: (command: CommandSpec) => Promise<OpValueOf['command.register']>;
2654 };
2655 /**
2656 * Every row of the settings menu (`/config`), the panel's own and each
2657 * enabled plugin's `userConfig` fields alike: listing and changing them.
2658 */
2659 config: {
2660 /**
2661 * Returns the rows the `/config` menu would draw now, in its order,
2662 * each with its current value, its kind, its owner and its lock.
2663 *
2664 * After every `config.describe` hook: a hidden row is left out, a
2665 * relabelled one carries the new label.
2666 *
2667 * @example
2668 * const theme = (await $.config.list()).find(row => row.key === "theme")
2669 */
2670 list: () => Promise<ConfigRow[]>;
2671 /**
2672 * Changes one row as if the person did in the menu: the event
2673 * `config.set` with `origin` `{ kind: 'plugin', name }`, then the writer.
2674 *
2675 * Through the other plugins' hooks, this plugin's own skipped; `{ deny }`
2676 * when a hook refused, the value does not fit, a trusted source owns the
2677 * row or only its dialog changes it. Rejects a key no row has.
2678 *
2679 * @param args `key` (as `list` names it) and `value` (the row's kind)
2680 * @returns `{ value }` once written, or `{ deny }`
2681 * @example
2682 * const { deny } = await $.config.set({ key: "verbose", value: true })
2683 */
2684 set: EventCalls['config']['set'];
2685 };
2686 /**
2687 * Subagents.
2688 */
2689 agent: {
2690 /**
2691 * Spawns a subagent: the event `agent.spawn`, the same call the engine
2692 * makes when the Agent tool starts one; the engine fills the rest.
2693 *
2694 * It runs every hook but the calling one, then the Agent tool in the
2695 * background under this call's origin: `{ model, agentId }` once the
2696 * subagent started (its answer is its `turn.complete`), or `{ deny }`.
2697 *
2698 * @example
2699 * const { agentId } = await $.agent.spawn({ prompt: "Read README.md." })
2700 */
2701 spawn: EventCalls['agent']['spawn'];
2702 /**
2703 * Returns the session's subagents so far, the ones the model spawned and
2704 * the ones plugins did alike.
2705 */
2706 list: () => Promise<AgentInfo[]>;
2707 /**
2708 * Defines an agent type the Agent tool dispatches from the next turn on,
2709 * named `<plugin>:<name>`: the event `agent.register`.
2710 *
2711 * Every field takes effect as in an agent file; re-registered, a name is
2712 * replaced; unloaded, a plugin's types go. `agent.offer` hides it from
2713 * the model alone; any plugin's `$.agent.spawn` answers to `agent.spawn`.
2714 *
2715 * @param spec `name`, `description` (when to delegate), `prompt` (its
2716 * system prompt), and any other field of an agent definition
2717 * @returns `{ agent }`, the full name; rejects until the session binds,
2718 * on a spec the schema refuses (its reason), on a hook's deny
2719 * @example
2720 * await $.agent.register({ name: "runner", description: "Runs a spec",
2721 * prompt: RUNNER_PROMPT, tools: ["Read", "Bash"], omitClaudeMd: true })
2722 * @example
2723 * // runner-only: hidden from the model, spawned by this plugin's tool,
2724 * // answered by the subagent's turn.complete (matched by agentId)
2725 * on("agent.offer", { agent: "lab:runner" }, () => ({ isOffered: false }))
2726 * on("tool.call", { tool: "mcp__lab__run" }, async ($, e) => {
2727 * const { agentId, deny } = await $.agent.spawn({
2728 * subagentType: "lab:runner", prompt: e.spec, description: "run" })
2729 * return { result: deny ?? (await answerOf(agentId)) }
2730 * })
2731 */
2732 register: (spec: AgentSpec) => Promise<OpValueOf['agent.register']>;
2733 };
2734 /**
2735 * The file system as the engine's own process reaches it; a relative path
2736 * is under the session's working directory, and text is UTF-8.
2737 *
2738 * An absolute path is used as given; where one may go is an `fs.*` hook's
2739 * to say. A read or write over 4 MiB rejects, a foreign network location
2740 * as spelled rejects untouched, and an OS refusal rejects with its errno.
2741 */
2742 fs: {
2743 /**
2744 * Reads a file and returns its text, or with `{ as: "bytes" }` its bytes
2745 * as `{ base64 }`.
2746 *
2747 * Rejects when missing, or over 4 MiB, which bounds what one read copies
2748 * into the plugin's environment. A file the plugin ships is under
2749 * `$.plugin.root`.
2750 *
2751 * @param path relative to the working directory, or absolute
2752 * @param options `as`: `"text"` (the default) or `"bytes"`
2753 * @returns the file's text, or `{ base64 }`
2754 * @example
2755 * const readme = await $.fs.read("README.md")
2756 * @example
2757 * const { base64 } = await $.fs.read(
2758 * `${$.plugin.root}/hooks/weights.bin`, { as: "bytes" })
2759 * const weights = Uint8Array.fromBase64(base64)
2760 */
2761 read: FsReadCall;
2762 /**
2763 * Writes `text` to a file, creating it and its directories as needed.
2764 *
2765 * @param path relative to the working directory, or absolute
2766 * @param text the whole new content
2767 */
2768 write: (path: string, text: string) => Promise<void>;
2769 /**
2770 * Lists a directory: `{ name, kind, size, isLink }` per entry, by name,
2771 * each entry as it stands (a symbolic link is `other` with `isLink`).
2772 *
2773 * @param path the directory's path; absent, the working directory
2774 * @returns the entries, `{ name, kind, size, isLink }` each
2775 */
2776 list: (path?: string) => Promise<FsEntry[]>;
2777 /**
2778 * Returns whether the path exists; rejects only a network location as
2779 * spelled, which no `fs` call reaches.
2780 */
2781 exists: (path: string) => Promise<boolean>;
2782 /**
2783 * Returns `{ kind, size, mtimeMs, isLink }` of the path: what it leads to,
2784 * and whether it is itself a symbolic link. Rejects when missing.
2785 *
2786 * With `{ resolve: true }` also `realPath`, where the path lands, absent
2787 * when it leads nowhere; a guard matches it and denies without it, since a
2788 * spelling it cannot resolve (`~`, a file not there yet) the tool may open.
2789 *
2790 * @param path relative to the working directory, or absolute
2791 * @param options `resolve`: also answer `realPath` (one more file system
2792 * call)
2793 * @returns the stat, `realPath` with it when asked and resolvable; rejects
2794 * `ENOENT` for a missing path
2795 * @example
2796 * // ROOT was resolved the same way and SEP is its separator; an
2797 * // allow-list under it is the robust guard, a deny-list on spellings
2798 * // only best effort (a hard link or a case alias keeps its own)
2799 * on("tool.call", { tool: "Read" }, async ($, e, next) => {
2800 * const stat = await $.fs.stat(e.file_path, { resolve: true })
2801 * .catch(() => undefined)
2802 * const real = stat?.realPath
2803 * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
2804 * return isInside ? next(e) : { deny: "outside the project" }
2805 * })
2806 * @example
2807 * // a Write may name a file not there yet: `placed` answers where the
2808 * // path lands or undefined, and the guard denies on undefined or
2809 * // outside ROOT. Unplaceable by spelling first, with no file system
2810 * // call (drive-relative `D:x`, a `\\` or `//` network or device path,
2811 * // a name that is empty, ".", ".." or itself `C:...`); then the file
2812 * // if it stats; else its folder, cut after the last separator and
2813 * // keeping it so a drive or share root stays that root, plus the name
2814 * const placed = async (path) => {
2815 * const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))
2816 * const name = path.slice(cut + 1)
2817 * const isPlaceable = !/^[A-Za-z]:(?![\\/])/.test(path) &&
2818 * !/^[\\/][\\/]/.test(path) && !/^[A-Za-z]:/.test(name) &&
2819 * name !== "" && name !== "." && name !== ".."
2820 * if (!isPlaceable) return undefined
2821 * const own = await $.fs.stat(path, { resolve: true })
2822 * .catch(() => undefined)
2823 * if (own) return own.realPath
2824 * const folder = cut < 0 ? "." : path.slice(0, cut + 1)
2825 * const dir = await $.fs.stat(folder, { resolve: true })
2826 * .catch(() => undefined)
2827 * return dir?.realPath === undefined ? undefined
2828 * : `${dir.realPath.replace(/[\\/]$/, "")}${SEP}${name}`
2829 * }
2830 * const real = await placed(e.file_path)
2831 * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
2832 * return isInside ? next(e) : { deny: "cannot place it, or outside" }
2833 */
2834 stat: (path: string, options?: FsStatOptions) => Promise<FsStat>;
2835 /**
2836 * Reads the named instruction files in every directory above the
2837 * session's original working directory, the way the engine reads CLAUDE.md.
2838 *
2839 * Root first, each `{ dir, name, content }` that exists, the content
2840 * with its `@include`s after it; `of` and `below` together are the
2841 * engine's own walk for a nested CLAUDE.md between root and read file.
2842 *
2843 * @param request `names`, relative `.md` file names (no `..`); `of`, the
2844 * file walked down to; `below`, the directory the walk stays inside
2845 * @returns the files found, root first
2846 * @example
2847 * const found = await $.fs.ancestors({ names: ["AGENTS.md"] })
2848 * const stack = await $.fs.ancestors({ names: ["AGENTS.md"], of: path })
2849 * const nested = await $.fs.ancestors({
2850 * names: ["AGENTS.md"],
2851 * of: e.file_path,
2852 * below: await $.session.root(),
2853 * })
2854 */
2855 ancestors: (request: FsAncestorsRequest) => Promise<readonly FsAncestor[]>;
2856 };
2857 /**
2858 * This plugin's own key-value store, kept between sessions and hot
2859 * reloads; values are JSON data.
2860 *
2861 * A JSON file of the plugin's own under the user's Claude Code
2862 * configuration directory.
2863 */
2864 store: {
2865 /**
2866 * Returns the value under `key`, or `undefined` when unset.
2867 *
2868 * @example
2869 * const count = Number((await $.store.get("count")) ?? 0) + 1
2870 */
2871 get: (key: string) => Promise<unknown>;
2872 /**
2873 * Sets `key` to `value`, which must be JSON data.
2874 *
2875 * `get` reads back `JSON.parse(JSON.stringify(value))`: a Date is its ISO
2876 * string, an `undefined` field is dropped, a Map or Set is `{}`. Rejects
2877 * a function, a cycle, or a store over 4 MiB of JSON text in all.
2878 */
2879 set: (key: string, value: unknown) => Promise<void>;
2880 /**
2881 * Removes `key` from the store.
2882 */
2883 delete: (key: string) => Promise<void>;
2884 /**
2885 * Returns every key set, in insertion order.
2886 */
2887 keys: () => Promise<string[]>;
2888 };
2889 /**
2890 * The time and timers, each an event through the host: `clock.now` reads
2891 * the time; `clock.sleep`, `after` and `every` wait until it has passed.
2892 *
2893 * A timer's callback is the plugin's own function, kept in its environment
2894 * and run there when the wait resolves; a hot reload of the plugin cancels
2895 * its pending waits with the old environment.
2896 */
2897 clock: {
2898 /**
2899 * Resolves milliseconds since the epoch, now.
2900 *
2901 * @example
2902 * const startedAt = await $.clock.now()
2903 */
2904 now: () => Promise<number>;
2905 /**
2906 * Resolves after `ms` milliseconds; rejects at once when `signal` aborts.
2907 *
2908 * @param ms how long, in milliseconds
2909 * @param options `signal`: ends the wait early with a rejection (pass
2910 * `next.signal` so a hook's wait ends with its dispatch)
2911 * @example
2912 * await $.clock.sleep(500, { signal: next.signal })
2913 */
2914 sleep: (ms: number, options?: SleepOptions) => Promise<void>;
2915 /**
2916 * Calls `fn` once after `ms` milliseconds; `cancel()` before then stops it.
2917 *
2918 * One `clock.after` dispatch: `fn` runs when it resolves, and never when
2919 * a hook refuses it.
2920 */
2921 after: TimerCall;
2922 /**
2923 * Calls `fn` every `ms` milliseconds (at least 1) until `cancel()`.
2924 *
2925 * One `clock.every` dispatch per period: `fn` runs when it resolves and
2926 * the next period is asked; a refused period ends the interval.
2927 *
2928 * @example
2929 * const tick = $.clock.every(1000, () => $.ui.status("polling"))
2930 */
2931 every: TimerCall;
2932 };
2933 /**
2934 * The network, through the host.
2935 */
2936 http: {
2937 /**
2938 * Fetches `url` through the host (never the plugin's own network) and
2939 * resolves `{ status, ok, headers, text }` once the body is read.
2940 *
2941 * http or https, to whatever the host process can reach, unless the
2942 * administrator's policy switches refuse it; an `auth` handle from
2943 * `$.session.authorize()` rides https only, to a first-party host.
2944 *
2945 * @param url the URL (http or https)
2946 * @param init `{ method, headers, body, auth, socketPath }` (body a
2947 * string; socketPath a Unix socket to go over instead of TCP)
2948 * @returns `{ status, ok, headers, text }` once the body is read
2949 * @example
2950 * const { ok, text } = await $.http.fetch("https://example.com/status")
2951 * @example
2952 * await $.http.fetch("http://bridge/reload", {
2953 * method: "POST",
2954 * socketPath: `${runDirectory}/bridge.sock`,
2955 * })
2956 */
2957 fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>;
2958 };
2959 /**
2960 * Commands on the host, run as the user the session runs as. CLI only.
2961 *
2962 * Local execution, not a network path: what a command of its own reaches
2963 * is its own, as for the Bash tool and a settings `command` hook.
2964 */
2965 process: {
2966 /**
2967 * Runs a command on the host by its argument vector (no shell) and
2968 * resolves `{ exitCode, stdout, stderr }` once it exits, any exit code.
2969 *
2970 * One shot: the whole output is read, so a background process left
2971 * writing holds the call until the timeout. Rejects when the command
2972 * cannot start or is still running then. Git runs with repo hooks off.
2973 *
2974 * @param argv the command and its arguments, `argv[0]` the executable
2975 * @param init `{ cwd, env, stdin, timeoutMs }` (cwd the session's by
2976 * default; timeout 30 s by default, ten minutes at most)
2977 * @returns `{ exitCode, stdout, stderr }` once the child exits
2978 * @example
2979 * const { exitCode, stdout } = await $.process.run(["git", "status"])
2980 */
2981 run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>;
2982 };
2983 /**
2984 * What the settings files, `--settings` and managed policy hold, as the
2985 * engine runs under it; read only.
2986 *
2987 * Every key crosses as the source holds it, `env` and the helper commands
2988 * included: nothing is filtered. The OAuth session and the global config
2989 * (~/.claude.json) are not settings and are never read.
2990 */
2991 settings: {
2992 /**
2993 * Resolves with the settings merged over every source, as the engine
2994 * reads them, or with one source's settings as loaded (`{ source }`).
2995 *
2996 * A snapshot in plain data each call; a source with no file answers
2997 * `{}`. The sources (SettingsSource) rise in precedence from `user` to
2998 * `policy`: the merge takes a key from the last source that has it.
2999 *
3000 * @param args `{ source }` to read one source; nothing for the merge
3001 * @returns the settings object, keyed as a settings.json is
3002 * @example
3003 * const { permissions } = await $.settings.read()
3004 * const policy = await $.settings.read({ source: "policy" })
3005 */
3006 read: (args?: SettingsReadArgs) => Promise<Settings>;
3007 };
3008 /**
3009 * The environment of this process, the one every Bash child, MCP server
3010 * and `$.process.run` command started after inherits.
3011 *
3012 * `get` and `set` take the variable's name as a string literal, so what a
3013 * module reads and writes is read off its source: `claude plugin validate`
3014 * lists the names, and a name the module does not spell is refused.
3015 */
3016 env: {
3017 /**
3018 * Resolves with the variable's value, or `undefined` when it is unset.
3019 *
3020 * `name` must be a string literal; `claude plugin validate` lists the
3021 * names your module reads and writes.
3022 *
3023 * @example
3024 * const home = await $.env.get("HOME")
3025 */
3026 get: (name: string) => Promise<string | undefined>;
3027 /**
3028 * Sets the variable for this process and everything it starts after, or
3029 * unsets it when `value` is `undefined`.
3030 *
3031 * `name` must be a string literal; `claude plugin validate` lists the
3032 * names your module reads and writes.
3033 *
3034 * @example
3035 * await $.env.set("GIT_PAGER", "cat")
3036 */
3037 set: (name: string, value: string | undefined) => Promise<void>;
3038 };
3039 }
3040
3041 /**
3042 * The name of an event the engine defines itself (a key of CoreEventOf);
3043 * EventName adds the declared plugin nouns' events.
3044 */
3045 type CoreEventName = keyof CoreEventOf;
3046
3047 /**
3048 * The argument of each event the engine defines itself: its call sites'
3049 * (EngineEventOf), the classic hooks' (ClassicEventOf), the calls on `$`.
3050 */
3051 type CoreEventOf = EngineEventOf & ClassicEventOf & OpEventOf;
3052
3053 type CwdChangedHookInput = BaseHookInput & {
3054 hook_event_name: 'CwdChanged';
3055 old_cwd: string;
3056 new_cwd: string;
3057 };
3058
3059 type DirectoryAddedHookInput = BaseHookInput & {
3060 hook_event_name: 'DirectoryAdded';
3061 /**
3062 * Absolute path of the directory that was added.
3063 */
3064 directory: string;
3065 /**
3066 * How the directory was added: "slash_command" for /add-dir, "register_repo_root" for the SDK control_request.
3067 */
3068 source: 'slash_command' | 'register_repo_root';
3069 };
3070
3071 /**
3072 * The `children` field every element constructor's props carry, appended
3073 * beside its own props type: one child, or a list that may nest.
3074 *
3075 * JSX types a lone child as the child itself (`<Text dimColor>done</Text>`
3076 * passes the string, `<Text>{count}</Text>` the number), and a mapped list
3077 * beside a sibling as a nested list (`<Box>{rows.map(row)}<Text>ok</Text>`).
3078 */
3079 export type ElementChildren = {
3080 children?: RenderChildren;
3081 };
3082
3083 /**
3084 * An element as `$.ui.resolve(e)` hands it out: a constructor from props to
3085 * the frozen plain-data element, `children` among the props as JSX passes.
3086 *
3087 * `const { Box } = $.ui.resolve(e)` then `<Box gap={1}>...</Box>` compiles to
3088 * `h(Box, { gap: 1 }, ...children)`, and `h` calls a function tag with its
3089 * props, so the table's constructors are the JSX tags.
3090 */
3091 export type ElementConstructor<P> = (props: P & ElementChildren) => RenderElement;
3092
3093 /**
3094 * Every element name of every surface: what a table handed out is completed to
3095 * (an omitted one draws a fragment; see `ui.resolve`).
3096 */
3097 export type ElementName = {
3098 [P in RenderSurface]: keyof Elements[P];
3099 }[RenderSurface];
3100
3101 /**
3102 * The element constructors each surface draws, by `e.surface`: what
3103 * `$.ui.resolve(e)` returns and a `ui.resolve` hook passes on; no globals.
3104 *
3105 * All carry `Box`, `Text`, `Button`, `Link`, `Code`, `Markdown`; every remote
3106 * surface `Svg`; all but mobile `Input` and `Select`; terminal and desktop
3107 * `Client`; terminal `Raster` and `Image`. Narrowed on `e.surface`, that table.
3108 */
3109 export type Elements = {
3110 terminal: {
3111 Box: ElementConstructor<BoxProps>;
3112 Text: ElementConstructor<TextProps>;
3113 Button: ElementConstructor<ButtonProps>;
3114 Input: ElementConstructor<InputProps>;
3115 Select: ElementConstructor<SelectProps>;
3116 Link: ElementConstructor<LinkProps>;
3117 Code: ElementConstructor<CodeProps>;
3118 Markdown: ElementConstructor<MarkdownProps>;
3119 /**
3120 * A region one of the plugin's surface modules draws (ClientModule), named
3121 * by `module`: a string literal, the module's path relative to this file.
3122 *
3123 * The engine reads the surface module off the hooks module's source
3124 * before anything runs, so a variable, a template with a substitution or
3125 * a computed path as `module` is refused at load, naming the line.
3126 */
3127 Client: ElementConstructor<ClientProps>;
3128 Raster: ElementConstructor<RasterProps>;
3129 Image: ElementConstructor<ImageProps>;
3130 };
3131 desktop: {
3132 Box: ElementConstructor<BoxProps>;
3133 Text: ElementConstructor<TextProps>;
3134 Button: ElementConstructor<ButtonProps>;
3135 Input: ElementConstructor<InputProps>;
3136 Select: ElementConstructor<SelectProps>;
3137 Svg: ElementConstructor<SvgProps>;
3138 Link: ElementConstructor<LinkProps>;
3139 Code: ElementConstructor<CodeProps>;
3140 Markdown: ElementConstructor<MarkdownProps>;
3141 Client: ElementConstructor<ClientProps>;
3142 };
3143 /**
3144 * No `Input` or `Select`: the control protocol carries presses (ui_press)
3145 * but no ui_input or ui_select yet; not a limit of the device.
3146 *
3147 * The table grows when those messages exist.
3148 */
3149 mobile: {
3150 Box: ElementConstructor<BoxProps>;
3151 Text: ElementConstructor<TextProps>;
3152 Button: ElementConstructor<ButtonProps>;
3153 Svg: ElementConstructor<SvgProps>;
3154 Link: ElementConstructor<LinkProps>;
3155 Code: ElementConstructor<CodeProps>;
3156 Markdown: ElementConstructor<MarkdownProps>;
3157 };
3158 /**
3159 * The desktop's table without `Client`: a remote `Client`'s module, presses
3160 * and posts (ui_client_module, ui_client_press, ui_message) name no surface.
3161 *
3162 * They are the desktop's alone today, not a limit of the editor's webview:
3163 * the table gains `Client` when those asks name a surface.
3164 */
3165 vscode: {
3166 Box: ElementConstructor<BoxProps>;
3167 Text: ElementConstructor<TextProps>;
3168 Button: ElementConstructor<ButtonProps>;
3169 Input: ElementConstructor<InputProps>;
3170 Select: ElementConstructor<SelectProps>;
3171 Svg: ElementConstructor<SvgProps>;
3172 Link: ElementConstructor<LinkProps>;
3173 Code: ElementConstructor<CodeProps>;
3174 Markdown: ElementConstructor<MarkdownProps>;
3175 };
3176 };
3177
3178 /**
3179 * The table `ui.resolve` answers for an argument of surface `P`.
3180 */
3181 export type ElementTable<P extends RenderSurface = RenderSurface> = Elements[P];
3182
3183 /**
3184 * 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.
3185 */
3186 type ElicitationHookInput = BaseHookInput & {
3187 hook_event_name: 'Elicitation';
3188 mcp_server_name: string;
3189 message: string;
3190 mode?: 'form' | 'url';
3191 url?: string;
3192 elicitation_id?: string;
3193 requested_schema?: Record<string, unknown>;
3194 };
3195
3196 /**
3197 * 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.
3198 */
3199 type ElicitationResultHookInput = BaseHookInput & {
3200 hook_event_name: 'ElicitationResult';
3201 mcp_server_name: string;
3202 elicitation_id?: string;
3203 mode?: 'form' | 'url';
3204 action: 'accept' | 'decline' | 'cancel';
3205 content?: Record<string, unknown>;
3206 };
3207
3208 /**
3209 * The input of `engine.create`: the fold that builds `$`, once per load,
3210 * core innermost.
3211 *
3212 * A hook is written in post-order: `const built = await next(e)` is `$` as
3213 * built so far; `return { ...built, voice: { say } }` adds this plugin's noun.
3214 * See EngineEventOf's `engine.create` for what a step may and may not do.
3215 */
3216 export type EngineCreateInput = {
3217 /**
3218 * The modules this fold builds, in list order, first outermost (managed
3219 * plugins first, so an org plugin's withholding wins).
3220 *
3221 * The whole set at a load, this plugin alone at its reload, the ones added
3222 * or changed at a refresh that keeps the rest: a module added later that
3223 * does not hook this event is built against the table as it stands.
3224 */
3225 plugins: readonly string[];
3226 };
3227
3228 /**
3229 * What an `engine.create` hook returns: `$` as built so far with this
3230 * plugin's nouns added, less any it withheld.
3231 *
3232 * Every declared noun is optional here. Between hooks it crosses the chain
3233 * as interface descriptors; a hook sees objects (EngineInterfaceBuilt).
3234 */
3235 export type EngineCreateResult = Partial<EngineInterface> & {
3236 readonly [noun: string]: unknown;
3237 };
3238
3239 /**
3240 * The events the engine raises at its call sites, and `engine.create`; the
3241 * classic settings hooks' events are ClassicEventOf.
3242 *
3243 * At every one, a hook that fails (throws, overruns its budget: HookBudget,
3244 * answers a wrong shape) is skipped: the hooks beneath and core run in its
3245 * place, or its last `next` result stands; the failure is reported by name.
3246 */
3247 export type EngineEventOf = {
3248 /**
3249 * Fires when the engine is about to run a tool. `next(e)` runs the hooks
3250 * beneath, then core (the permission prompt, the tool itself).
3251 *
3252 * Return `{ deny: reason }` to refuse or `{ result }` to answer yourself; a
3253 * hook that returns while its `next` is pending aborts what runs beneath.
3254 * The managed-settings hooks run first: their deny is the call's result.
3255 */
3256 'tool.call': ToolCallInput;
3257 /**
3258 * Fires when the engine decides whether a tool call may run, after the
3259 * `tool.call` and PreToolUse hooks and before the mode settles an ask.
3260 *
3261 * `next(e)` resolves to the engine's verdict (rules, mode, the tool's own
3262 * check, PreToolUse's decision); return any `{ decision }`. `$.tool.check`
3263 * runs the same chain and executes nothing.
3264 *
3265 * @example
3266 * on("tool.check", { tool: "Read" }, () => ({ decision: "allow" }))
3267 */
3268 'tool.check': ToolCheckInput;
3269 /**
3270 * Fires when the engine is about to draw a component: once per input value
3271 * (props, viewport width), plugin load or `$.ui.invalidate("ui.render")`.
3272 *
3273 * A repaint reuses the answer; a clock invalidates. `next(e)` resolves to the
3274 * drawing: return it, wrap it, draw your own, or rewrite `props`. A tree that
3275 * does not validate draws the engine's own; `--plugin-dir` is told why.
3276 */
3277 'ui.render': RenderInput;
3278 /**
3279 * Fires when the plugins load (not per draw), once per surface, component
3280 * and plugin: `e` names the surface and component, never the props.
3281 *
3282 * `next(e)` resolves to the surface's table, which `$.ui.resolve(e)` then
3283 * reads. Return it, one with an element restyled for every other plugin,
3284 * or one with a key left out (a fragment there); own table: hook skipped.
3285 */
3286 'ui.resolve': ResolveInput;
3287 /**
3288 * Fires when a `Button` a render hook drew is pressed on a surface; `e` is
3289 * `{ plugin, element, component, surface }`, `element` the button's `key`.
3290 *
3291 * `next(e)` runs the hooks beneath, then core: the element's own `onPress`
3292 * closure, in its plugin's environment, resolving to `{ element }`. Return
3293 * `next(e)` to let the press through, or `{ element }` to take it.
3294 */
3295 'ui.press': UiPressArgument;
3296 /**
3297 * Fires when an `Input` a render hook drew changes or is submitted; `e` is
3298 * `{ plugin, element, component, surface, kind, value }`.
3299 *
3300 * `next(e)` runs the hooks beneath, then the element's own `onInput` or
3301 * `onSubmit` with `e.value` as the chain left it, resolving to `{ element,
3302 * value }`; `next({ ...e, value })` rewrites the typing, an answer takes it.
3303 */
3304 'ui.input': UiInputArgument;
3305 /**
3306 * Fires when a `Select` a render hook drew is picked from; `e` is
3307 * `{ plugin, element, component, surface, value }`.
3308 *
3309 * `next(e)` runs the hooks beneath, then the element's own `onSelect` with
3310 * `e.value` as the chain left it, resolving to `{ element, value }`;
3311 * `next({ ...e, value })` rewrites the pick, an answer takes it.
3312 */
3313 'ui.select': UiSelectArgument;
3314 /**
3315 * Fires when a `Client` THIS plugin drew posts from its surface module
3316 * (`surface.post(data)`); only this plugin's hooks see it.
3317 *
3318 * `next.origin` names `client`: `data` came from code. Core answers `{}`;
3319 * `next({ ...e, data })` rewrites the data; `{ props }` hands the posting
3320 * instance its next props without a redraw. One per instance per frame.
3321 */
3322 'ui.message': UiMessageArgument;
3323 /**
3324 * Fires before a site's window moves: the person's wheel or scroll keys on
3325 * a `Pane` body or the `AbovePrompt` band, at its edges too; `$.ui.scroll`.
3326 *
3327 * `next(e)` moves it to `e.offset` and draws: `{}`; `next({ ...e, offset
3328 * })` elsewhere; no `next` (`{}` or `{ deny }`) leaves it undrawn, so a hook
3329 * drawing its own rows under a header moves them by `e.by` and invalidates.
3330 *
3331 * @example
3332 * on("ui.scroll", { requestId: "log" }, ($, e) => (scrollOwnRows(e.by), {}))
3333 */
3334 'ui.scroll': UiScrollInput;
3335 /**
3336 * Fires before a site's focus ring moves: the person's Tab, arrows or click
3337 * in a `Pane` or the band; an `autoFocus` element taking it; `$.ui.focus`.
3338 *
3339 * `next(e)` lands it on `e.element` (absent: one of the engine's stops) and
3340 * draws: `{}`; `next({ ...e, element })` on another of `e.plugin`'s; no
3341 * `next` (`{}` or `{ deny }`) keeps it where it was, drawn as it was.
3342 *
3343 * @example
3344 * on("ui.focus", { requestId: "list" }, ($, e, next) => (mark(e), next(e)))
3345 */
3346 'ui.focus': UiFocusInput;
3347 /**
3348 * Fires when the engine offers an agent type to the model, in the agent
3349 * listing and again at dispatch; `next(e)` resolves to `{ isOffered: true }`.
3350 *
3351 * Return `{ isOffered: false }` to keep the type out of the listing and
3352 * refuse its dispatch. A hook that fails passes it through.
3353 *
3354 * @example
3355 * on("agent.offer", { agent: "Plan" }, () => ({ isOffered: false }))
3356 */
3357 'agent.offer': AgentOfferInput;
3358 /**
3359 * Fires when the Agent tool is about to start a subagent, everything
3360 * decided and its model not yet resolved.
3361 *
3362 * `next(e)` resolves to `{ model }`. Return it, `next({ ...e, model })`,
3363 * `{ model }` of your own (an alias resolves like the tool's parameter), or
3364 * `{ deny: reason }`.
3365 */
3366 'agent.spawn': AgentSpawnInput;
3367 /**
3368 * Fires when a prompt is submitted, before the turn starts. `next(e)` runs
3369 * the hooks beneath and the UserPromptSubmit settings hooks.
3370 *
3371 * Rewrite with `next({ ...e, text })` (the user message on screen follows)
3372 * or stop it with `{ drop: reason }`; a broken plugin never blocks a prompt.
3373 * A prompt typed while a turn ran fires at Enter, with that turn's id.
3374 */
3375 'prompt.submit': PromptSubmitInput;
3376 /**
3377 * Fires when a text is about to be put in the prompt box as the person's
3378 * draft (a plugin's `$.prompt.fill`); `next(e)` writes it by `e.mode`.
3379 *
3380 * `replace` over the draft, `append` after it, `insert` at the cursor;
3381 * rewrite `text` or `mode` going down, or answer `{ isFilled: false }`
3382 * without `next` to keep it out, as core does under a dialog or headless.
3383 *
3384 * @example
3385 * on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
3386 */
3387 'prompt.fill': PromptFillInput;
3388 /**
3389 * Fires when a text is proposed as the prompt box's dim suggestion, Tab to
3390 * take: the engine's guess after a turn, or a plugin's `$.prompt.suggest`.
3391 *
3392 * `next(e)` shows it: `{ isShown }`. Rewrite with `next({ ...e, text })`,
3393 * or answer `{ isShown: false }` without `next` to drop it; core answers
3394 * that too while the box holds text or a turn runs.
3395 *
3396 * @example
3397 * on("prompt.suggest", { origin: { kind: "suggestion" } }, hide)
3398 */
3399 'prompt.suggest': PromptSuggestInput;
3400 /**
3401 * Fires when the person edits the main prompt box: a key the editor took as
3402 * an edit, or a paste; `next(e)` resolves the box the editor shows.
3403 *
3404 * `e` is the draft before and the splice (`start`, `end`, `inputText`); a
3405 * burst of keys is one edit. Rewrite `inputText` going down or the box
3406 * coming up; `{ text: e.text, cursor: e.cursor }` without `next` consumes.
3407 *
3408 * @example
3409 * on("prompt.edit", ($, e, next) => next({ ...e, inputText: up(e) }))
3410 */
3411 'prompt.edit': PromptEditInput;
3412 /**
3413 * Fires once per named section of the system prompt, when the engine
3414 * assembles it; `next(e)` resolves to `{ text }` as core computed it.
3415 *
3416 * Sections are cached by name for the session until
3417 * `$.ui.invalidate("prompt.section")`: an unstable answer spends the
3418 * model's prompt cache on every call. A hook that fails passes it through.
3419 *
3420 * @example
3421 * on("prompt.section", { name: "memory" }, () => ({ text: null }))
3422 */
3423 'prompt.section': PromptSectionInput;
3424 /**
3425 * Fires once per conversation, when the engine computes the context blocks
3426 * its first user message carries; `next(e)` resolves to `{ blocks }`.
3427 *
3428 * Append, drop, reorder or rewrite with `next({ ...e, blocks })`; the
3429 * engine renders what comes back, in order, until
3430 * `$.ui.invalidate("prompt.context")` or a re-read (compaction, `/clear`).
3431 *
3432 * @example
3433 * on("prompt.context", () => ({ blocks: [] }))
3434 */
3435 'prompt.context': PromptContextInput;
3436 /**
3437 * Fires once per message the engine injects for the model on its own (a
3438 * reminder, a mode transition, a mentioned file), as a request carries it.
3439 *
3440 * `next(e)` resolves to `{ text }`; `{ text: null }` leaves it out. The
3441 * answer holds per attachment for the process (asked again on resume or
3442 * `$.ui.invalidate`); the transcript keeps the engine's record.
3443 *
3444 * @example
3445 * on("prompt.attachment", { type: "todo_reminder" }, () => ({ text: null }))
3446 */
3447 'prompt.attachment': PromptAttachmentInput;
3448 /**
3449 * Fires once per tool, when the engine first renders the tool's schema in
3450 * a session; `next(e)` resolves to `{ description, isDeferred? }`.
3451 *
3452 * Cached for the session until `$.ui.invalidate("tool.describe")`: an
3453 * unstable answer spends the model's prompt cache. An explicit `isDeferred`
3454 * moves the tool behind ToolSearch (true) or into the prompt's list (false).
3455 *
3456 * @example
3457 * on("tool.describe", { tool: "Bash" }, ($, e) => ({ ...e, description }))
3458 * @example
3459 * on("tool.describe", { tool: "Monitor" }, pin) // {...e, isDeferred: false}
3460 */
3461 'tool.describe': ToolDescribeInput;
3462 /**
3463 * Fires when a slash command is about to run (`/name args` typed, or a
3464 * plugin's `$.command.run`); `next(e)` resolves to `{ text }`, its output.
3465 *
3466 * Core is the engine's command (a registered one has none). Rewrite `args`
3467 * with `next`, or return `{ text }` without it to answer in its place; one
3468 * after `next` replaces a printed output, not a panel or prompt it opened.
3469 *
3470 * @example
3471 * on("command.run", { command: "hello" }, () => ({ text: "hello" }))
3472 */
3473 'command.run': CommandRunInput;
3474 /**
3475 * Fires once per command, when the engine lists it for the typeahead and
3476 * `/help`; `next(e)` resolves to `{ description, argumentHint, isHidden }`.
3477 *
3478 * Listed answers are cached for the session until
3479 * `$.ui.invalidate("command.describe")`. A hook that fails passes it
3480 * through.
3481 *
3482 * @example
3483 * on("command.describe", ($, e, next) => next({ ...e, isHidden: true }))
3484 */
3485 'command.describe': CommandDescribeInput;
3486 /**
3487 * Fires when a `/config` row is about to change, from the menu or a
3488 * plugin's `$.config.set`; `next(e)` resolves to `{ value }` once written.
3489 *
3490 * Return `{ deny: reason }` to leave the row as it is (the menu says why),
3491 * or `next({ ...e, value })` to clamp it; a value of the wrong kind for
3492 * the row is refused. A row a trusted source owns is core's to refuse.
3493 *
3494 * @example
3495 * on("config.set", { key: "theme" }, () => ({ deny: "the theme stays" }))
3496 */
3497 'config.set': ConfigSetInput;
3498 /**
3499 * Fires once per `/config` row, when the menu lists it and for
3500 * `$.config.list`; `next(e)` resolves to `{ label, description, isHidden }`.
3501 *
3502 * Relabel, re-describe or hide with `next({ ...e, isHidden: true })`; the
3503 * answers are cached until `$.ui.invalidate("config.describe")` or the
3504 * loaded plugins change. A hook that fails passes the row through.
3505 *
3506 * @example
3507 * on("config.describe", { key: "tips" }, hide) // answers isHidden: true
3508 */
3509 'config.describe': ConfigDescribeInput;
3510 /**
3511 * Fires when the engine expands a skill's prompt for the model (`/name`,
3512 * the Skill tool, a preload); `next(e)` resolves to `{ text }` as computed.
3513 *
3514 * Return `{ text }` with the text the model reads instead. A hook that
3515 * fails passes it through.
3516 *
3517 * @example
3518 * on("skill.prompt", { skill: "commit" }, () => ({ text: "A haiku." }))
3519 */
3520 'skill.prompt': SkillPromptInput;
3521 /**
3522 * Fires when the engine composes a git text the model is to write (`kind`:
3523 * `commit`, `pr`, `exemption`, `remedy`); `next(e)` resolves to `{ text }`.
3524 *
3525 * Return `{ text }` with the text the model reads instead. A hook that
3526 * fails passes it through.
3527 *
3528 * @example
3529 * on("attribution.text", { kind: "commit" }, () => ({ text: "" }))
3530 */
3531 'attribution.text': AttributionTextInput;
3532 /**
3533 * Fires once per process for each loaded plugin, before the first prompt,
3534 * then once per fresh load of one (never `/clear`); `next(e)` is `{ cwd }`.
3535 *
3536 * Observe. The first is awaited: a `$.tool.register` is listed by turn one.
3537 * A later one runs its hooks alone: an enable, a worker respawn, or a reload
3538 * (changed modules only; all if one hooks `engine.create`/`plugin.register`).
3539 *
3540 * @example
3541 * on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
3542 */
3543 'session.start': SessionStartInput;
3544 /**
3545 * Fires when a delivery reaches the session (a relay's event, a peer's
3546 * message, a Remote Control prompt), before it is queued; `{ text }`.
3547 *
3548 * Rewrite with `next({ ...e, text })`, or return `{ consumed: reason }` to
3549 * take it: nothing is queued, shown or read by the model. `origin` and
3550 * `event` pass on as received; `session.send`, its dual, is reserved.
3551 *
3552 * @example
3553 * on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
3554 */
3555 'session.receive': SessionReceiveInput;
3556 /**
3557 * Fires once per row a conversation of this session keeps (a prompt, a
3558 * response block, a tool result, a notice), before it is stored.
3559 *
3560 * `next({ ...e, message })` rewrites `content`: stored and sent after. The
3561 * screen, an SDK stream or Remote Control may show the row just before its
3562 * rewrite; the model and the transcript file never read that form.
3563 *
3564 * @example
3565 * on("session.append", { door: "tool-result" }, ($, e, n) => n(scrub(e)))
3566 */
3567 'session.append': SessionAppendInput;
3568 /**
3569 * Fires when the conversation is about to be compacted (`/compact`, the
3570 * threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
3571 *
3572 * Rewrite `instructions` or `messages` on the way down, the messages on
3573 * the way up, or answer `{ messages }` of your own; `{ skip: reason }`
3574 * leaves the conversation as it is. `trigger` passes on as received.
3575 *
3576 * @example
3577 * on("session.compact", { trigger: "precompute" }, () => ({ skip: "off" }))
3578 */
3579 'session.compact': SessionCompactInput;
3580 /**
3581 * Fires when a remote client joins the session's roster of attached
3582 * surfaces: it said so (ui_attach), or it first asked to draw.
3583 *
3584 * Observe (a phone joined: draw the lobby); `next(e)` resolves to
3585 * `{ clientId }`, a different return changes nothing. `$.session.surfaces()`
3586 * reads the roster; a render hook still reads `e.surface` per ask.
3587 *
3588 * @example
3589 * on("session.attach", { surface: "mobile" }, ($, e, next) => next(e))
3590 */
3591 'session.attach': SessionAttachInput;
3592 /**
3593 * Fires when a client leaves the roster: it detached, or the session ended
3594 * with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
3595 */
3596 'session.detach': SessionDetachInput;
3597 /**
3598 * Fires when the engine measures the session and a unit moved: after each
3599 * main-thread turn, and when a rate-limit window moves a whole point.
3600 *
3601 * Observe; `next(e)` echoes `{ changed }`. `$.session.usage()`'s figures,
3602 * pushed, not polled: compare them with your own threshold here, call the
3603 * op for the breakdown. One at a time, a burst folding into one more.
3604 *
3605 * @example
3606 * on("session.measure", ($, e, next) => (toastPast90(e.rateLimits), next(e)))
3607 */
3608 'session.measure': SessionMeasureInput;
3609 /**
3610 * Fires once when the session ends (exit, /clear, resume, logout, signal, a
3611 * `-p` run done), after its SessionEnd settings hooks; `e.reason` says which.
3612 *
3613 * `e.resume.id` is `--resume`'s id; `next(e)` runs the engine's end step for
3614 * the plugins (at an exit the attached clients leave): `{ sessionId }`. The
3615 * SessionEnd bound afresh, 1.5 s by default; a `kill -9` raises nothing.
3616 *
3617 * @example
3618 * on("session.end", async ($, e, next) => (await keep(e.resume), next(e)))
3619 */
3620 'session.end': SessionEndInput;
3621 /**
3622 * Fires once per hooks module about to join the chain, at load (the set
3623 * folded and built, nothing swapped in) and at reload; core allows.
3624 *
3625 * Return `{ refuse: reason }` and it never joins: no hook, no noun, no tool
3626 * of it; the transcript names who refused. Its judges, `$` whole, are the
3627 * plugins admitted before it and the binary's; judge by `tier` and `uses`.
3628 *
3629 * @example
3630 * on("plugin.register", { tier: "user" }, () => ({ refuse: "managed only" }))
3631 */
3632 'plugin.register': PluginRegisterInput;
3633 /**
3634 * Fires when a model turn begins, before its first model call; `next(e)`
3635 * resolves to `{ turnId }`. Observe: a different return changes nothing.
3636 */
3637 'turn.start': TurnStartInput;
3638 /**
3639 * Fires when the engine is about to send a model request of a turn, main's
3640 * or a subagent's (`e.agentId`); `next(e)` resolves to the whole response.
3641 *
3642 * `next({ ...e, model })` or `effort` sends another; the turn, the index and
3643 * the message count are pinned. An answer without `next` sends no request.
3644 * It streams (StreamNext): the hook's budget counts its own code alone.
3645 */
3646 'turn.step': TurnStepInput;
3647 /**
3648 * Fires when a model turn has ended, at the point its duration is reported;
3649 * `next(e)` resolves to `{ text }`, the answer. `e.reason` says why.
3650 *
3651 * Return `{ text }` with a different text to show it beneath the answer (a
3652 * synopsis, a TL;DR line); the transcript's record is never rewritten. A
3653 * hook that fails leaves the answer as it was.
3654 */
3655 'turn.complete': TurnCompleteInput;
3656 /**
3657 * Runs while `$` is being built, once per load or reload of this plugin
3658 * and before any other hook of it; `next(e)` resolves to `$` built so far.
3659 *
3660 * A step may ADD nouns and WITHHOLD nouns (leave one out, or return without
3661 * `next`); it may NOT REPLACE one another step added: the step fails, named
3662 * with both plugins. A step that fails unloads its plugin; `$` is rebuilt.
3663 */
3664 'engine.create': EngineCreateInput;
3665 };
3666
3667 /**
3668 * `$`, the first parameter of every hook. Frozen; core's interface plus
3669 * every noun the plugins' `engine.create` steps added.
3670 *
3671 * Flat, `<noun>.<event>`; it does not carry `on`, since registration happens
3672 * before `$` exists. An interface so a plugin types the noun it provides by
3673 * declaration merging, the way a jQuery plugin types `$.fn`.
3674 *
3675 * @example
3676 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
3677 */
3678 export interface EngineInterface extends CoreEngineInterface {
3679 }
3680
3681 /**
3682 * What `next(e)` resolves to at `engine.create`: `$` as the steps beneath
3683 * built it, typed as `$` is, open to nouns no declaration names yet.
3684 *
3685 * A withheld noun is on it as a stub (a step inside withheld it, or the
3686 * last fold did and this is a reload), and the host refuses an op on one a
3687 * step outside withholds later; a typed module bootstraps at load on it.
3688 */
3689 export type EngineInterfaceBuilt = EngineInterface & {
3690 readonly [noun: string]: unknown;
3691 };
3692
3693 /**
3694 * The engine's events' results.
3695 */
3696 export type EngineResultOf = {
3697 /**
3698 * `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`.
3699 */
3700 'tool.call': ToolCallResult;
3701 /**
3702 * `{ decision, reason?, rule? }`.
3703 */
3704 'tool.check': ToolCheckResult;
3705 /**
3706 * The tree to draw; `{ type: "engine", ref }` is core's own drawing.
3707 */
3708 'ui.render': RenderElement;
3709 /**
3710 * The surface's element table (Elements[e.surface]): constructors from props
3711 * to a RenderElement.
3712 */
3713 'ui.resolve': ElementTable;
3714 /**
3715 * `{ element }`: the element whose handler the press reached.
3716 */
3717 'ui.press': UiPressResult;
3718 /**
3719 * `{ element, value }`: the field whose handler the input reached, and
3720 * the text it received.
3721 */
3722 'ui.input': UiInputResult;
3723 /**
3724 * `{ element, value }`: the picker whose handler the pick reached, and
3725 * the value it received.
3726 */
3727 'ui.select': UiSelectResult;
3728 /**
3729 * `{ props? }`: the posting instance's next props, when a hook hands some.
3730 */
3731 'ui.message': UiMessageResult;
3732 /**
3733 * `{}` once the window moved, or `{ deny }`.
3734 */
3735 'ui.scroll': UiScrollResult;
3736 /**
3737 * `{}` once the ring moved, or `{ deny }`.
3738 */
3739 'ui.focus': UiFocusResult;
3740 /**
3741 * `{ isOffered }`.
3742 */
3743 'agent.offer': AgentOfferResult;
3744 /**
3745 * `{ model }` or `{ deny }`.
3746 */
3747 'agent.spawn': AgentSpawnResult;
3748 /**
3749 * `{ text, context? }` or `{ drop }`.
3750 */
3751 'prompt.submit': PromptSubmitResult;
3752 /**
3753 * `{ isFilled }`.
3754 */
3755 'prompt.fill': PromptFillResult;
3756 /**
3757 * `{ isShown }`.
3758 */
3759 'prompt.suggest': PromptSuggestResult;
3760 /**
3761 * `{ text, cursor }`, the box the editor shows next.
3762 */
3763 'prompt.edit': PromptEditResult;
3764 /**
3765 * `{ text }` (null leaves the section out).
3766 */
3767 'prompt.section': PromptSectionResult;
3768 /**
3769 * `{ blocks }` (a block left out is not sent).
3770 */
3771 'prompt.context': PromptContextResult;
3772 /**
3773 * `{ text }` (null leaves the attachment out).
3774 */
3775 'prompt.attachment': PromptAttachmentResult;
3776 /**
3777 * `{ description, isDeferred? }`.
3778 */
3779 'tool.describe': ToolDescribeResult;
3780 /**
3781 * `{ text }` (the command's output, when it printed one).
3782 */
3783 'command.run': CommandRunResult;
3784 /**
3785 * `{ description, argumentHint, isHidden }`.
3786 */
3787 'command.describe': CommandDescribeResult;
3788 /**
3789 * `{ value }` once written, or `{ deny }`.
3790 */
3791 'config.set': ConfigSetResult;
3792 /**
3793 * `{ label, description, isHidden }`.
3794 */
3795 'config.describe': ConfigDescribeResult;
3796 /**
3797 * `{ text }`.
3798 */
3799 'skill.prompt': SkillPromptResult;
3800 /**
3801 * `{ text }`.
3802 */
3803 'attribution.text': AttributionTextResult;
3804 /**
3805 * `{ cwd }`.
3806 */
3807 'session.start': SessionStartResult;
3808 /**
3809 * `{ text }`, or `{ consumed }`.
3810 */
3811 'session.receive': SessionReceiveResult;
3812 /**
3813 * `{ message, uuid }`, the row as stored.
3814 */
3815 'session.append': SessionAppendResult;
3816 /**
3817 * `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
3818 */
3819 'session.compact': SessionCompactResult;
3820 /**
3821 * `{ clientId }`.
3822 */
3823 'session.attach': SessionAttachResult;
3824 /**
3825 * `{ clientId }`.
3826 */
3827 'session.detach': SessionDetachResult;
3828 /**
3829 * `{ changed }`.
3830 */
3831 'session.measure': SessionMeasureResult;
3832 /**
3833 * `{ sessionId }`.
3834 */
3835 'session.end': SessionEndResult;
3836 /**
3837 * `{ allow: true }`, or `{ refuse }`.
3838 */
3839 'plugin.register': PluginRegisterResult;
3840 /**
3841 * `{ turnId }`.
3842 */
3843 'turn.start': TurnStartResult;
3844 /**
3845 * The response: `{ turnId, index, answer, toolUses, stopReason, usage }`.
3846 */
3847 'turn.step': TurnStepResult;
3848 /**
3849 * `{ text }`.
3850 */
3851 'turn.complete': TurnCompleteResult;
3852 /**
3853 * `$` as built so far, with this plugin's interface added and any it
3854 * withheld left out; `next(e)` resolves to EngineInterfaceBuilt.
3855 */
3856 'engine.create': EngineCreateResult;
3857 };
3858
3859 /**
3860 * The engine's own events as calls on `$`, one signature each:
3861 * `$.<noun>.<event>(input)` resolves to its result, or to its stream.
3862 *
3863 * The engine raises its events through these same calls; a plugin's call
3864 * runs the same chain with the calling hook alone skipped. `input` may leave
3865 * out what the engine fills (`tool_use_id`, the parent agent).
3866 */
3867 export type EventCalls = {
3868 tool: {
3869 call: ToolCallOverloads;
3870 check: (input: ToolCheckArgs) => Promise<ToolCheckResult>;
3871 describe: (input: ToolDescribeInput) => Promise<ToolDescribeResult>;
3872 };
3873 command: {
3874 run: (input: CommandRunArgs) => Promise<CommandRunResult>;
3875 describe: (input: CommandDescribeInput) => Promise<CommandDescribeResult>;
3876 };
3877 config: {
3878 set: (input: ConfigSetArgs) => Promise<ConfigSetResult>;
3879 describe: (input: ConfigDescribeInput) => Promise<ConfigDescribeResult>;
3880 };
3881 prompt: {
3882 submit: (input: PromptSubmitArgs) => Promise<PromptSubmitResult>;
3883 fill: (input: PromptFillArgs) => Promise<PromptFillResult>;
3884 suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
3885 section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
3886 context: (input: PromptContextInput) => Promise<PromptContextResult>;
3887 attachment: (input: PromptAttachmentInput) => Promise<PromptAttachmentResult>;
3888 };
3889 skill: {
3890 prompt: (input: SkillPromptInput) => Promise<SkillPromptResult>;
3891 };
3892 attribution: {
3893 text: (input: AttributionTextInput) => Promise<AttributionTextResult>;
3894 };
3895 agent: {
3896 offer: (input: AgentOfferInput) => Promise<AgentOfferResult>;
3897 spawn: (input: AgentSpawnArgs) => Promise<AgentSpawnResult>;
3898 };
3899 session: {
3900 start: (input: SessionStartInput) => Promise<SessionStartResult>;
3901 receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
3902 append: (input: SessionAppendInput) => Promise<SessionAppendResult>;
3903 compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
3904 attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
3905 detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
3906 measure: (input: SessionMeasureInput) => Promise<SessionMeasureResult>;
3907 end: (input: SessionEndInput) => Promise<SessionEndResult>;
3908 };
3909 turn: {
3910 start: (input: TurnStartInput) => Promise<TurnStartResult>;
3911 step: (input: TurnStepInput) => HookStream<TurnStepChunk, TurnStepResult>;
3912 complete: (input: TurnCompleteInput) => Promise<TurnCompleteResult>;
3913 };
3914 ui: {
3915 render: <C extends RenderComponent>(input: RenderInput<C>) => Promise<RenderElement>;
3916 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
3917 scroll: (input: UiScrollArgs) => Promise<UiScrollResult>;
3918 focus: (input: UiFocusArgs) => Promise<UiFocusResult>;
3919 };
3920 };
3921
3922 /**
3923 * The name of an event: a key of EventOf, the engine's own (CoreEventName)
3924 * and the declared plugin nouns' (NounEventName).
3925 */
3926 export type EventName = keyof EventOf;
3927
3928 /**
3929 * The argument of each event, by event name: what a hook receives as `e`
3930 * and what the call on `$` takes. Plain data, frozen to every depth.
3931 *
3932 * The engine's own events (CoreEventOf: a plugin's `$.fs.write(...)` is
3933 * a dispatch the hooks above it see) and the methods of the plugin nouns
3934 * declared on EngineInterface (NounEventOf).
3935 */
3936 export type EventOf = CoreEventOf & NounEventOf;
3937
3938 /**
3939 * The result of event `N`: what its hooks return and what their `next(e)`
3940 * resolves to.
3941 */
3942 export type EventResult<N extends EventName = EventName> = ResultOf[N];
3943
3944 /**
3945 * The hook signature of each event, `($, e, next)`, as one mapped type over
3946 * EventOf; a streaming event's is the generator form (StreamHook).
3947 *
3948 * With one handler type per event, `Events[E]` for a generic E would be a
3949 * union; as one mapped type it stays a single function type the engine
3950 * calls without a cast (TS 4.6 correlated unions).
3951 *
3952 * @param $ the engine interface, frozen, the same object at every invocation;
3953 * at `engine.create` the empty table, since `$` exists after the fold
3954 * @param e the event's argument, frozen to every depth (`e.command = "ls"`
3955 * is a type error and throws); a rewrite is a copy passed to `next`
3956 * @param next the rest of the chain; a chain a hook raises through `$` skips
3957 * this hook and runs every other, its plugin's others too
3958 */
3959 export type Events = {
3960 [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>>;
3961 };
3962
3963 type ExitReason = 'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other';
3964
3965 type FileChangedHookInput = BaseHookInput & {
3966 hook_event_name: 'FileChanged';
3967 file_path: string;
3968 event: 'change' | 'add' | 'unlink';
3969 };
3970
3971 /**
3972 * `T` with every property read-only to every depth, arrays and tuples kept
3973 * as declared: how a hook's `e` is typed.
3974 *
3975 * `e.command = 'x'` is a type error; `next({ ...e, command: 'x' })` compiles.
3976 */
3977 export type Frozen<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? {
3978 [K in keyof T]: Frozen<T[K]>;
3979 } : T extends object ? {
3980 readonly [K in keyof T]: Frozen<T[K]>;
3981 } : T;
3982
3983 /**
3984 * One file `$.fs.ancestors` found: the directory it stands in, the name it
3985 * was asked for by, and its text as the engine's memory loader reads it.
3986 */
3987 export type FsAncestor = {
3988 /**
3989 * The directory the file stands in, absolute.
3990 */
3991 dir: string;
3992 /**
3993 * The spelling the caller asked for it by.
3994 */
3995 name: string;
3996 /**
3997 * The file's text, with what its `@include`s bring after it.
3998 */
3999 content: string;
4000 /**
4001 * The file and then each file its `@` imports brought, in load order,
4002 * path and text apiece; `content` is these texts joined.
4003 */
4004 parts: readonly FsAncestorPart[];
4005 };
4006
4007 /**
4008 * One file of an ancestor entry: the file itself or one it imported.
4009 */
4010 export type FsAncestorPart = {
4011 /**
4012 * The file's path, absolute.
4013 */
4014 path: string;
4015 /**
4016 * Its text as the engine's memory loader reads it.
4017 */
4018 content: string;
4019 };
4020
4021 /**
4022 * The argument of `$.fs.ancestors`: the file names to look for in each
4023 * directory, the file to walk down to, and the directory to walk beneath.
4024 */
4025 export type FsAncestorsRequest = {
4026 /**
4027 * Relative `.md` file names, each looked for in every directory.
4028 */
4029 names: readonly string[];
4030 /**
4031 * The file the walk goes on down to the directory of, relative to the
4032 * working directory or absolute; absent, it ends at the working directory.
4033 */
4034 of?: string;
4035 /**
4036 * The directory the walk starts beneath, relative to the working directory
4037 * or absolute; absent, the walk starts at the filesystem root.
4038 *
4039 * Only directories strictly inside it are read, so with `of` a file under
4040 * the project root the walk reads the directories between the two, as the
4041 * engine reads a nested CLAUDE.md; a file not inside it finds nothing.
4042 */
4043 below?: string;
4044 };
4045
4046 /**
4047 * What `$.fs.read(path, { as: "bytes" })` resolves with: the file's bytes,
4048 * base64, since only plain data crosses into a plugin's environment.
4049 */
4050 export type FsBytes = {
4051 /**
4052 * The file's content, standard padded base64;
4053 * `Uint8Array.fromBase64(base64)` gives the bytes back.
4054 */
4055 base64: string;
4056 };
4057
4058 /**
4059 * One entry of `$.fs.list`: the entry itself, a link not followed.
4060 */
4061 export type FsEntry = {
4062 /**
4063 * The entry's name (no directory part).
4064 */
4065 name: string;
4066 /**
4067 * `file`, `dir`, or `other`, of the entry itself: a symbolic link is
4068 * `other` (`$.fs.stat` says what it leads to, and with `resolve` where).
4069 */
4070 kind: 'file' | 'dir' | 'other';
4071 /**
4072 * Bytes, for a file.
4073 */
4074 size: number;
4075 /**
4076 * True when the entry is a symbolic link.
4077 */
4078 isLink: boolean;
4079 };
4080
4081 /**
4082 * How `$.fs.read` answers: `text` (UTF-8, the default) or `bytes` (base64).
4083 */
4084 export type FsReadAs = 'text' | 'bytes';
4085
4086 /**
4087 * The options of `$.fs.read` that ask for the bytes: the call answers
4088 * `{ base64 }`.
4089 */
4090 export type FsReadBytesOptions = {
4091 /**
4092 * `bytes`.
4093 */
4094 as: 'bytes';
4095 };
4096
4097 /**
4098 * `$.fs.read`: the file's text, or with `{ as: "bytes" }` its bytes as
4099 * `{ base64 }`.
4100 */
4101 export type FsReadCall = {
4102 (path: string): Promise<string>;
4103 (path: string, options: FsReadBytesOptions): Promise<FsBytes>;
4104 (path: string, options: FsReadOptions): Promise<string | FsBytes>;
4105 };
4106
4107 /**
4108 * The options of `$.fs.read`.
4109 */
4110 export type FsReadOptions = {
4111 /**
4112 * `bytes` answers `{ base64 }` for a binary file; `text` (the default) the
4113 * file's text.
4114 */
4115 as: FsReadAs;
4116 };
4117
4118 /**
4119 * What `$.fs.stat` resolves with: what the path leads to, whether the path
4120 * itself is a symbolic link, and where it lands when asked.
4121 */
4122 export type FsStat = {
4123 /**
4124 * `file`, `dir`, or `other`, of what the path leads to: a link is
4125 * followed, and one that leads nowhere is `other`.
4126 */
4127 kind: 'file' | 'dir' | 'other';
4128 /**
4129 * Bytes, for a file.
4130 */
4131 size: number;
4132 /**
4133 * Last modification, milliseconds since the epoch.
4134 */
4135 mtimeMs: number;
4136 /**
4137 * True when the path itself is a symbolic link; `kind`, `size` and
4138 * `mtimeMs` then describe what it points at, or the link when that is gone.
4139 */
4140 isLink: boolean;
4141 /**
4142 * Where the path landed when asked with `{ resolve: true }`: absolute,
4143 * every symbolic link followed, `.` and `..` folded; else absent.
4144 *
4145 * Absent too when the path leads nowhere or a hook above withheld it, so
4146 * a guard denies without it; and a hard link, a volume or file-id spelling
4147 * (macOS `/.vol/`) or a case alias keeps its own spelling, `isLink` false.
4148 *
4149 * @remarks a deny-list on spellings is thus best effort; an allow-list on
4150 * `realPath` under a root resolved the same way is the robust guard.
4151 */
4152 realPath?: string;
4153 };
4154
4155 /**
4156 * The options of `$.fs.stat`.
4157 */
4158 export type FsStatOptions = {
4159 /**
4160 * True to resolve where the path lands as well.
4161 *
4162 * The answer then carries `realPath` when the path leads somewhere, at
4163 * the cost of one more file system call: where it landed then, not a hold
4164 * on what a tool opens afterwards.
4165 */
4166 resolve: boolean;
4167 };
4168
4169 /**
4170 * Every event (`*`), or every event under a namespace (`classic.*`: each
4171 * one whose name starts with `classic.`).
4172 */
4173 export type Glob = '*' | `${Namespace}.*`;
4174
4175 /**
4176 * The hook `on(pattern, hook)` takes for a glob or a negation: one function
4177 * placed on every selected event, `e` and the result typed as their union.
4178 *
4179 * `next.event` says which event a run is; `next.is(pattern, e)` narrows `e`
4180 * to one of them. At `engine.create` (a negation may select it) `$` is the
4181 * empty table and the hook observes the fold, as a `*` hook does.
4182 */
4183 export type GlobHook<P extends Pattern, N extends EventName = Selected<P>> = ($: EngineInterface, e: Frozen<Args<N>>, next: GlobNext<P>) => EventResult<N> | Promise<EventResult<N>>;
4184
4185 /**
4186 * `next` in a hook on a glob or a negation: an overload per selected event,
4187 * then one over their union for an `e` not yet narrowed.
4188 *
4189 * `is` narrows `e` to the selected events its pattern names; `event` is one
4190 * of the selected names.
4191 */
4192 export type GlobNext<P extends Pattern, N extends EventName = Selected<P>> = OrderedOverloads<N> & {
4193 (e: Args<N>): Promise<GlobNextResult<N>>;
4194 /**
4195 * Continues this dispatch at a tier, as Next's `to` (a managed hook's),
4196 * over the selected events' union for an `e` not yet narrowed.
4197 */
4198 readonly to: (e: Args<N>, tier: TargetTier) => Promise<GlobNextResult<N>>;
4199 readonly signal: AbortSignal;
4200 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<Args<Extract<N, Selected<M>>>>;
4201 readonly event: N;
4202 readonly origin: Origin;
4203 readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
4204 readonly budget: NextBudget;
4205 };
4206
4207 /**
4208 * What `next(e)` resolves to in a glob hook before `e` is narrowed: the
4209 * NextResult of each selected event, as a union.
4210 */
4211 type GlobNextResult<N extends EventName> = {
4212 [K in N]: NextResult<K>;
4213 }[N];
4214
4215 /**
4216 * One hook, `($, e, next)`, on event `E`.
4217 */
4218 export type Hook<E extends EventName = EventName> = Events[E];
4219
4220 /**
4221 * The time bounds every hook runs under, in milliseconds: the engine's own
4222 * constants are typed by these members, and `next.budget` reads the live one.
4223 *
4224 * Each bounds the hook's OWN time: the clock stops while a `next(e)` call or
4225 * any `$` call of the hook's is in flight (a `$.clock` wait excepted), so a
4226 * slow chain beneath or a minute-long `$.model.complete` costs it nothing.
4227 *
4228 * @example
4229 * await $.model.complete(ask) // a minute; next.budget.remainingMs unmoved
4230 */
4231 export type HookBudget = {
4232 /**
4233 * A hook's budget per dispatch, from its call to its return; past it the
4234 * hook is absent (its `.catch` asked, else `next(e)` run on its behalf).
4235 *
4236 * A streaming hook's (`turn.step`, an async generator) spans its whole
4237 * run and counts only while its own code runs: never at a `yield`, never
4238 * while it reads the stream beneath. Not per chunk: the sum of its work.
4239 */
4240 readonly ms: 10_000;
4241 /**
4242 * A `.catch` handler's grace: a fresh budget from the moment it is called,
4243 * on the same clock (its `next` replay and its `$` calls are free).
4244 *
4245 * Past it the hook is absent as if it had no handler; `next.error.budget`
4246 * and `next.budget.ms` both read it there. `engine.create` has no budget.
4247 */
4248 readonly catchMs: 1_000;
4249 /**
4250 * How long a hook may keep running after `next.signal` aborted (the person
4251 * interrupted, a hook above settled first, its own budget ran out).
4252 *
4253 * Past it the hook is reported as lingering; the dispatch had already gone
4254 * on without it when the signal aborted.
4255 */
4256 readonly lingerMs: 5_000;
4257 };
4258
4259 /**
4260 * Why a hook failed, as its `.catch` handler reads it on `next.error`: plain
4261 * frozen data.
4262 *
4263 * `throw`: the hook threw, or returned what the site refuses, `message`
4264 * saying what; `timeout`: it outran its budget, `message` then what its last
4265 * `next()` rejected with, if it did. `budget` is the handler's own grace.
4266 */
4267 export type HookFailure = {
4268 readonly kind: 'throw' | 'timeout';
4269 /**
4270 * The thrown error's message, or for a timeout what the hook's last
4271 * `next()` rejected with; absent for a timeout with nothing rejected.
4272 */
4273 readonly message?: string;
4274 /**
4275 * The grace the handler runs under, in milliseconds; past it, the hook is
4276 * absent as if it had no handler.
4277 */
4278 readonly budget: number;
4279 };
4280
4281 /**
4282 * The hook type per pattern: an event's own (Events), `*`'s (AnyEventHook),
4283 * or a glob's over the events it selects (GlobHook), as one conditional type.
4284 *
4285 * One type, so the two-argument `on` stays ONE generic signature: as an
4286 * overload set the language service offers no tool-name completions inside
4287 * `e.tool === "`; as an index into a table TS intersects every argument.
4288 */
4289 export type HookFor<P extends Pattern> = P extends '*' ? AnyEventHook : P extends EventName ? Events[P] : GlobHook<P>;
4290
4291 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;
4292
4293 /**
4294 * The hook event `E` takes: an async generator over its chunks for a
4295 * streaming event (`turn.step`), `($, e, next) => result` for every other.
4296 */
4297 export type HookOf<E extends EventName> = Events[E];
4298
4299 /**
4300 * What a hooks module exports: `register`, and nothing the loader reads
4301 * besides.
4302 */
4303 export type HooksModule = {
4304 register: Register;
4305 };
4306
4307 /**
4308 * What `next(e)` returns on a streaming event: the stream of everything
4309 * beneath, chunk by chunk, whose return value is the result from beneath.
4310 *
4311 * `yield* next(e)` forwards the chunks and evaluates to that result; a
4312 * transforming hook reads `for await (const chunk of stream)` and then
4313 * `await stream.result`. Each call runs what is beneath afresh.
4314 */
4315 export type HookStream<C, R> = AsyncGenerator<C, R> & {
4316 /**
4317 * Settles with what beneath returned once the stream has been read to
4318 * its end; rejects if the stream is closed before that.
4319 */
4320 readonly result: Promise<R>;
4321 };
4322
4323 /**
4324 * Options of `$.http.fetch`.
4325 */
4326 export type HttpInit = {
4327 /**
4328 * `GET` (default), `POST`, ...
4329 */
4330 method?: string;
4331 /**
4332 * Request headers.
4333 */
4334 headers?: Record<string, string>;
4335 /**
4336 * The request body, as text.
4337 */
4338 body?: string;
4339 /**
4340 * The handle `$.session.authorize()` answered: the engine sets the
4341 * session's credential header itself, only for a first-party host.
4342 */
4343 auth?: string;
4344 /**
4345 * The absolute path of a Unix domain socket the request goes over instead
4346 * of TCP (near 100 B at most): one per session, in a private directory.
4347 *
4348 * The URL still gives path, query and Host; redirects stay on it; no proxy;
4349 * `https:` is TLS verified against the URL's host (always, once `auth`
4350 * rides), so a credential reaches only its host. No relative path, no NUL.
4351 *
4352 * @example
4353 * await $.http.fetch(url, { socketPath: `${runDirectory}/bridge.sock` })
4354 */
4355 socketPath?: string;
4356 };
4357
4358 /**
4359 * What `$.http.fetch` resolves with.
4360 */
4361 export type HttpResponse = {
4362 /**
4363 * The HTTP status code.
4364 */
4365 status: number;
4366 /**
4367 * True for a 2xx status.
4368 */
4369 ok: boolean;
4370 /**
4371 * Response headers, lower-cased names.
4372 */
4373 headers: Record<string, string>;
4374 /**
4375 * The body, as text.
4376 */
4377 text: string;
4378 };
4379
4380 /**
4381 * A `$.ui.blit` argument swapping one of the caller's mounted keyed Images
4382 * to its next picture; every call sends it, so a stream needs no generation.
4383 *
4384 * The surface writes them with its frames, some sixty a second: byte and
4385 * `file` sources fold to the last per frame; every `shm` source reaches the
4386 * terminal (it unlinks each), and is denied while frames are not written.
4387 *
4388 * @example await $.ui.blit({ requestId: 'browser', key: 'view',
4389 * source: { shm: '/tb-4', format: 'rgb', width: 1280, height: 720 } })
4390 */
4391 export type ImageBlitArgs = {
4392 /**
4393 * The site the Image is drawn in, by the `requestId` this plugin draws it
4394 * under.
4395 */
4396 requestId: string;
4397 /**
4398 * The Image's `key` in that drawing.
4399 */
4400 key: string;
4401 /**
4402 * The next picture (ImageSource): bytes, or a name the terminal reads.
4403 */
4404 source: ImageSource;
4405 /**
4406 * Refused unless it is the mounted Image's width in cells. Absent, that.
4407 */
4408 columns?: number;
4409 /**
4410 * Refused unless it is the mounted Image's height in cells. Absent, that.
4411 */
4412 rows?: number;
4413 };
4414
4415 /**
4416 * The props of `Image`, the terminal surface's picture leaf: pixels over a
4417 * box of cells where the terminal can (kitty, Ghostty), the `alt` elsewhere.
4418 *
4419 * A leaf: no children, `hover` or `onPress`; the cells are text, so the
4420 * picture scrolls and clips as a word does. Drawn again with another `source`
4421 * it is replaced in place; keyed, `$.ui.blit` swaps it at the frame rate.
4422 *
4423 * @example const { bytes } = await $.fs.read('chart.png', { as: 'bytes' })
4424 * <Image source={{ png: bytes.toBase64() }} columns={40} rows={12} alt="p95" />
4425 * @example <Image key="view" source={{ shm: '/tb-7', format: 'rgb', width: 960,
4426 * height: 600 }} columns={80} rows={25} alt="the page" />
4427 */
4428 export type ImageProps = {
4429 /**
4430 * The element's address within the drawing: what `$.ui.blit` names to swap.
4431 *
4432 * Unique among the Images of one tree; absent, only a redraw changes it.
4433 */
4434 key?: string;
4435 /**
4436 * The picture (ImageSource): `{ png }` or `{ rgba, width, height }` bytes,
4437 * or `{ file, format }` / `{ shm, format, width, height }` read here.
4438 */
4439 source: ImageSource;
4440 /** How many terminal columns wide, 1 to 255; the picture is scaled to fill
4441 * the box and the site clips what its body cannot show. */
4442 columns: number;
4443 /**
4444 * How many terminal rows tall, 1 to 255.
4445 */
4446 rows: number;
4447 /**
4448 * What the picture says, drawn dim in its place where the picture cannot
4449 * be (and read by a screen reader); required, may be a single space.
4450 */
4451 alt: string;
4452 };
4453
4454 /**
4455 * The picture an `Image` shows: base64 bytes the plugin holds (at most 2 MiB
4456 * decoded), or the name of a file or POSIX shared-memory object it does not.
4457 *
4458 * A name is one another process on this machine wrote; the terminal, running
4459 * as the person, opens, reads and decodes it itself, so no pixel crosses `$`
4460 * and the engine never touches it. One it will not read (not a regular file,
4461 * under `/proc`, `/sys` or `/dev`, gone, across ssh) draws a blank box, its
4462 * words in the debug log; it unlinks a shared-memory object once read, so
4463 * each frame is a fresh one. A source equal to the last drawn sends nothing;
4464 * `generation` makes new content under an unchanged name a new source.
4465 *
4466 * @example { rgba: pixels.toBase64(), width: 64, height: 32 }
4467 * @example { file: '/dev/shm/frame-3.rgba', format: 'rgba', width: 640,
4468 * height: 400 }
4469 * @example { shm: '/tb-view-2', format: 'rgb', width: 1280, height: 720 }
4470 */
4471 export type ImageSource = {
4472 /**
4473 * A whole PNG file, base64.
4474 */
4475 png: string;
4476 } | {
4477 /**
4478 * `width * height` RGBA pixels, 4 bytes each, base64.
4479 */
4480 rgba: string;
4481 /**
4482 * Pixels per row, 1 to 2048.
4483 */
4484 width: number;
4485 /**
4486 * Rows of pixels, 1 to 2048.
4487 */
4488 height: number;
4489 } | {
4490 /**
4491 * The absolute path of a regular file holding a whole PNG, at most
4492 * 3072 bytes of path; read by the terminal, left in place.
4493 */
4494 file: string;
4495 /**
4496 * The file is a whole PNG; the terminal decodes it and sizes it itself.
4497 */
4498 format: 'png';
4499 /**
4500 * A whole number that changes when the file's content does under the
4501 * same path, so a redraw reads it again; absent, the path alone tells.
4502 */
4503 generation?: number;
4504 } | {
4505 /**
4506 * The absolute path of a regular file of `width * height` raw pixels, at
4507 * most 3072 bytes of path; read by the terminal, left in place.
4508 *
4509 * On Linux a file under `/dev/shm` is memory.
4510 */
4511 file: string;
4512 /**
4513 * `rgba`, 4 bytes a pixel, or `rgb`, 3.
4514 */
4515 format: 'rgba' | 'rgb';
4516 /**
4517 * Pixels per row, 1 to 4096.
4518 */
4519 width: number;
4520 /**
4521 * Rows of pixels, 1 to 4096.
4522 */
4523 height: number;
4524 /**
4525 * A whole number that changes when the file's content does under the
4526 * same path, so a redraw reads it again; absent, the path alone tells.
4527 */
4528 generation?: number;
4529 } | {
4530 /**
4531 * The name of a POSIX shared-memory object of `width * height` raw
4532 * pixels: `/` then up to 254 of `A-Z a-z 0-9 . _ -` (macOS takes 30).
4533 *
4534 * The terminal unlinks it after reading, so a name feeds one Image
4535 * drawn once and is never sent again on a redraw; POSIX terminals only.
4536 */
4537 shm: string;
4538 /**
4539 * `rgba`, 4 bytes a pixel, or `rgb`, 3.
4540 */
4541 format: 'rgba' | 'rgb';
4542 /**
4543 * Pixels per row, 1 to 4096.
4544 */
4545 width: number;
4546 /**
4547 * Rows of pixels, 1 to 4096.
4548 */
4549 height: number;
4550 /**
4551 * A whole number that changes when a fresh object reuses a name, so a
4552 * redraw reads it again; absent, the name alone tells.
4553 */
4554 generation?: number;
4555 };
4556
4557 /**
4558 * The keys of object pattern `P` that object member `E` cannot satisfy, `D`
4559 * levels down; `never` when there is none, which is what keeps the member.
4560 *
4561 * A key `E` does not have (an open record has every string key), or one
4562 * whose value `P` narrows to nothing.
4563 */
4564 type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
4565 [K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
4566 }[keyof P];
4567
4568 /**
4569 * The props of `Input`, every surface's one-line text field: an address,
4570 * optional texts, and the closures a change and a submit run. A leaf.
4571 *
4572 * Focused through the same ring as `Button` (`abovePrompt:focus`); while it
4573 * has focus every printable key reaches it alone and Esc returns them; a
4574 * change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
4575 */
4576 export type InputProps = {
4577 /**
4578 * The element's address: `e.element` at `ui.input`, what a matcher names.
4579 */
4580 key: string;
4581 /**
4582 * Text drawn before the field.
4583 */
4584 label?: string;
4585 /**
4586 * Text drawn dim in an empty field.
4587 */
4588 placeholder?: string;
4589 /**
4590 * The text the field holds when drawn; the person's typing replaces it
4591 * until the hook draws another.
4592 */
4593 value?: string;
4594 /**
4595 * What Enter does, in a word or two, drawn beside the field while it has
4596 * focus (`send`). Defaults to `submit`.
4597 */
4598 submitLabel?: string;
4599 /**
4600 * The site's focus ring starts here when the site takes the keyboard,
4601 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
4602 *
4603 * A pane opened with `focus`, or the person's focus chord or click, is the
4604 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
4605 * origin this plugin. A ring the person has moved stays where it was put.
4606 */
4607 autoFocus?: true;
4608 /**
4609 * Runs on every change of the text, in the plugin's own environment: the
4610 * bottom of a `ui.input` chain of kind `change`.
4611 */
4612 onInput?: (value: string, e: UiInputArgument) => void;
4613 /**
4614 * Runs on Enter with the text, in the plugin's own environment: the bottom
4615 * of a `ui.input` chain of kind `submit`. No model turn unless it asks one.
4616 */
4617 onSubmit: (value: string, e: UiInputArgument) => void;
4618 };
4619
4620 /**
4621 * Every tier an instruction file can belong to, for checking a hook's
4622 * answer; the kind type is derived from this list.
4623 */
4624 const INSTRUCTION_FILE_KINDS: readonly ["managed", "user", "project", "local", "memory"];
4625
4626 /**
4627 * One instruction file behind the `claudeMd` block: where it was read, its
4628 * tier, its text as loaded, and the file that `@`-imported it if one did.
4629 */
4630 export type InstructionFile = {
4631 /**
4632 * The file's path, absolute.
4633 */
4634 path: string;
4635 /**
4636 * Its tier.
4637 */
4638 kind: InstructionFileKind;
4639 /**
4640 * The text as loaded (comments and frontmatter already stripped).
4641 */
4642 content: string;
4643 /**
4644 * The path of the file whose `@` import brought this one, when one did.
4645 */
4646 parent?: string;
4647 };
4648
4649 /**
4650 * What tier an instruction file belongs to: the organization's managed
4651 * policy, the person's own, the project's checked-in or private ones, memory.
4652 */
4653 export type InstructionFileKind = (typeof INSTRUCTION_FILE_KINDS)[number];
4654
4655 type InstructionsLoadedHookInput = BaseHookInput & {
4656 hook_event_name: 'InstructionsLoaded';
4657 file_path: string;
4658 memory_type: 'User' | 'Project' | 'Local' | 'Managed';
4659 load_reason: 'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact';
4660 globs?: string[];
4661 trigger_file_path?: string;
4662 parent_file_path?: string;
4663 };
4664
4665 /**
4666 * What `$.ui.invalidate` takes: a render event, or one of the six events
4667 * whose answers the engine caches for the session.
4668 */
4669 export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'prompt.attachment' | 'tool.describe' | 'command.describe' | 'config.describe';
4670
4671 /**
4672 * Whether tag key `K` selects members of `I`: it does when each member gives
4673 * it ONE literal (`component: "ToolUse"` on the ToolUse variant).
4674 *
4675 * A key that is the same union on every member is a filter at runtime; it
4676 * is left out of the selection so that it cannot defeat the narrowing the
4677 * other keys give.
4678 */
4679 type IsDiscriminant<I, K> = I extends unknown ? K extends KnownKeys<I> ? IsSingleLiteral<I[K]> : true : never;
4680
4681 /**
4682 * Whether `V` is made of literals only: `"a" | "b"` is, `string` is not.
4683 */
4684 type IsLiteralValued<V> = string extends V ? false : number extends V ? false : boolean extends V ? false : [V] extends [string | number | boolean] ? true : false;
4685
4686 /**
4687 * Whether `V` is exactly one string, number or boolean literal.
4688 */
4689 type IsSingleLiteral<V> = [V] extends [string | number | boolean] ? IsUnion<V> extends true ? false : true : false;
4690
4691 /**
4692 * Whether `T` is a union of two or more members.
4693 */
4694 type IsUnion<T, U = T> = T extends unknown ? [U] extends [T] ? false : true : never;
4695
4696 /**
4697 * Plain data: what JSON holds, and what crosses between a plugin's hooks
4698 * module and its surface module whole (a `Client`'s props, a post's data).
4699 *
4700 * A function, a class instance, `undefined` or a cycle is not plain data;
4701 * the engine refuses one where it checks, and drops it where it clones.
4702 */
4703 export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
4704 readonly [key: string]: JsonValue;
4705 };
4706
4707 /**
4708 * What `next` takes in a matched hook: the variants of `e` the matcher can
4709 * match (KeptMembers), as declared, so a rewrite of a pinned field passes.
4710 */
4711 type KeptEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? KeptMembers<Args<N>, M> : never : never;
4712
4713 /**
4714 * The members of the argument union `E` matcher `P` can match, as declared;
4715 * what `next` takes, so a rewrite may change a field the matcher pinned.
4716 *
4717 * A member is dropped when `P` names a key it lacks, or gives a key, at any
4718 * depth, a value none of that key's values can equal (ImpossibleKeys).
4719 */
4720 type KeptMembers<E, P> = E extends unknown ? [ImpossibleKeys<E, P, []>] extends [never] ? E : never : never;
4721
4722 /**
4723 * The declared keys of `T`, the string and number index signatures left out.
4724 */
4725 type KnownKeys<T> = keyof {
4726 [K in keyof T as string extends K ? never : number extends K ? never : K]: 0;
4727 };
4728
4729 /**
4730 * The events whose overload must come after the rest, lest it shadow them.
4731 *
4732 * `classic.PreToolUse` shares `tool.call`'s envelope, `turn.abort` every
4733 * turn event's `turnId`, and an object of any shape is assignable to NoArgs.
4734 */
4735 type LateOverload = 'classic.PreToolUse' | 'turn.abort' | NoArgsEvent;
4736
4737 /**
4738 * The props of `Link`, a hyperlink every surface draws: an OSC 8 span on the
4739 * terminal (else its text then the URL in dim), an anchor on desktop.
4740 *
4741 * An inline element: its children are the text, strings and inline
4742 * elements; absent children the `label`, absent both the URL. The engine
4743 * bounds `href` before the tree crosses.
4744 */
4745 export type LinkProps = {
4746 /**
4747 * Where the link goes: an `https:` URL (or `http://localhost`), at most
4748 * 2048 characters of printable ASCII, spelled as `new URL(href).href`.
4749 *
4750 * No `user@host` part, no raw `@`, space or non-ASCII letter (encode them);
4751 * anything else refuses the tree the Link is in.
4752 */
4753 href: string;
4754 /**
4755 * The text drawn when the element has no children; absent both, the URL
4756 * itself is the text.
4757 */
4758 label?: string;
4759 };
4760
4761 /**
4762 * What a matcher value selects by: itself, or `unknown` for a RegExp, which
4763 * selects nothing.
4764 */
4765 type Literal<X> = X extends RegExp ? unknown : X;
4766
4767 /**
4768 * What a `Markdown` carries across the boundary: its address, text, dimness
4769 * and which links it answers; `onLinkPress` stays behind, a `press` instead.
4770 */
4771 export type MarkdownLeafProps = {
4772 /**
4773 * The element's address: what `e.element` carries and what a matcher
4774 * names; present whenever the element carries a `press`.
4775 */
4776 key?: string;
4777 /**
4778 * The markdown drawn, bounded as a Text's string is.
4779 */
4780 text: string;
4781 /**
4782 * The whole block dim, as `Text`'s `dimColor`; absent draws as false.
4783 */
4784 dimColor?: boolean;
4785 /**
4786 * Which links a press belongs to, by `href` as written; absent, with a
4787 * `press`, every link drawn. Compared with the pressed target only.
4788 */
4789 pressableLinks?: readonly string[];
4790 };
4791
4792 /**
4793 * The props of `Markdown`, a block of markdown every surface draws as it
4794 * draws an assistant reply's text: its own renderer, links, tables, fences.
4795 *
4796 * A leaf: no children. `text` is the element's data as a `Text`'s string is,
4797 * bounded the same way. With `onLinkPress` the links it draws are the
4798 * plugin's to answer: a press on one raises `ui.press` addressed to `key`.
4799 */
4800 export type MarkdownProps = {
4801 /**
4802 * The element's address: `e.element` at `ui.press`, what a matcher names.
4803 * Required with `onLinkPress`, since a press needs one; else optional.
4804 */
4805 key?: string;
4806 /**
4807 * The markdown drawn, as an assistant reply would write it.
4808 *
4809 * At most 10000 characters, tab and newline its only control characters;
4810 * a link whose scheme is not `https:`, `http:` or `file:` draws as text,
4811 * never clickable. Not drawn around the approval dialog.
4812 */
4813 text: string;
4814 /**
4815 * The whole block dim, as `Text`'s `dimColor`: a thought, an aside.
4816 */
4817 dimColor?: boolean;
4818 /**
4819 * What a press on a link in `text` runs, in the plugin's own environment:
4820 * the bottom of a `ui.press` chain whose `e.link` names the link.
4821 *
4822 * A press is a plain single click where the surface reports clicks (the
4823 * fullscreen terminal): it opens nothing and lands once no double-click
4824 * followed; a ctrl, alt or terminal-kept cmd click opens it as before.
4825 */
4826 onLinkPress?: (link: PressedLink, e: UiPressArgument) => void;
4827 /**
4828 * Which links in `text` a press belongs to, by `href` as the markdown
4829 * writes it; absent, every link drawn. Only with `onLinkPress`.
4830 *
4831 * A link left out keeps the surface's own behaviour. At most 256 entries
4832 * of at most 2048 characters; compared with the pressed link's target,
4833 * never opened.
4834 */
4835 pressableLinks?: readonly string[];
4836 };
4837
4838 /**
4839 * The argument a matched hook receives: `e` narrowed by `M` (Narrowed), per
4840 * event the registration covers.
4841 */
4842 export type MatchedEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Narrowed<Args<N>, M> : never : never;
4843
4844 /**
4845 * The hook `on(pattern, matcher, hook)` takes: `($, e, next)` with `e`
4846 * narrowed by the matcher (MatchedEvent), and a tagged result the same way.
4847 *
4848 * On a streaming event it is the generator form (MatchedStreamHook). `next`
4849 * takes the variants the matcher keeps, as declared (KeptEvent); `next.is`
4850 * names the events the registration covers and narrows as the matcher does.
4851 */
4852 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>, {
4853 [K in MatchedNames<P, M>]: Narrowed<Args<K>, M>;
4854 }>) => MatchedResult<P, M> | Promise<MatchedResult<P, M>>;
4855
4856 /**
4857 * The events a matched registration on `P` covers: the event named, or for a
4858 * glob every selected event whose input has each key the matcher names.
4859 */
4860 type MatchedNames<P, M = never> = P extends EventName ? P : {
4861 [N in Selected<P & string>]: [M] extends [never] ? N : keyof M extends AnyKeyOf<Args<N>> ? N : never;
4862 }[Selected<P & string>];
4863
4864 /**
4865 * What a matched hook returns: the event's result, narrowed by `M` where the
4866 * result is a union tagged by the matcher's tag keys.
4867 */
4868 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;
4869
4870 /**
4871 * The hook `on(event, matcher, hook)` takes on a streaming event: the
4872 * generator form, `e` narrowed by the matcher, `next(e)` the stream beneath.
4873 */
4874 export type MatchedStreamHook<P extends StreamingEventName, M> = ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: MatchedStreamNext<P, M>) => StreamHookBody<Chunk<P>, MatchedResult<P, M>>;
4875
4876 /**
4877 * What a matched streaming hook's `next.is(pattern, e)` narrows `e` to:
4878 * the streaming event's argument narrowed by the matcher.
4879 */
4880 type MatchedStreamNarrowings<P extends StreamingEventName, M> = {
4881 [K in P]: Narrowed<Args<K>, M>;
4882 };
4883
4884 /**
4885 * A matched streaming hook's `next`: the variants the matcher keeps, the
4886 * result tagged the same way, `next.is` narrowing as the matcher does.
4887 */
4888 type MatchedStreamNext<P extends StreamingEventName, M> = StreamNext<P, KeptEvent<P, M>, MatchedResult<P, M>, MatchedStreamNarrowings<P, M>>;
4889
4890 /**
4891 * What `on(event, matcher, hook)` takes for an argument of type `I`: the
4892 * shape of the `e` the hook wants, a partial of it at any depth.
4893 *
4894 * A leaf is `===` or a RegExp (`{ command: /^p4 / }`); an array is any-of;
4895 * an object is a partial of an OBJECT, so `{ command: { startsWith } }` is
4896 * a type error where `e` is typed and free where it is `unknown`.
4897 */
4898 export type Matcher<I, All = I> = I extends unknown ? {
4899 readonly [K in KnownKeys<I>]?: MatcherValue<I[K], MatcherValueOf<All, K>>;
4900 } & (string extends keyof I ? OpenMatcher<I, All> : unknown) : never;
4901
4902 /**
4903 * Any matcher at all, for a field typed `unknown` (a tool's input, a
4904 * result's output): the kinds the engine accepts, unchecked there.
4905 *
4906 * The four kinds: a scalar is `===`; a RegExp tests the value as a string
4907 * (`{ command: /^p4 / }`); an array matches if any element does; an object
4908 * is a partial of an object. `{ startsWith: 'p4' }` never matches a string.
4909 */
4910 type MatcherData = string | number | boolean | null | RegExp | readonly MatcherData[] | {
4911 readonly [key: string]: MatcherData;
4912 };
4913
4914 /**
4915 * The declared keys of every variant of `I` (index signatures aside).
4916 */
4917 type MatcherKeys<I> = I extends unknown ? KnownKeys<I> : never;
4918
4919 /**
4920 * What matches one value of type `V`, by the runtime's kinds:
4921 * a scalar leaf takes the value or a RegExp; an object, a partial of it.
4922 *
4923 * For an array, what matches one ELEMENT of it, since a pattern against an
4924 * array value holds when some element matches; for `unknown`, any matcher.
4925 * A scalar matches by `===`, a RegExp tests the value as a string.
4926 */
4927 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;
4928
4929 /**
4930 * What a matcher gives a key whose value is `V` on this variant and `Across`
4931 * over every variant: one MatcherOne, or an array of them matched as one-of.
4932 *
4933 * The one-of is typed over every variant, so `{ tool: ['Bash', 'Read'] }`
4934 * types on the Bash variant; with a nested pattern beside it, the pattern is
4935 * checked against a variant the one-of names, not against each of them.
4936 */
4937 type MatcherValue<V, Across = V> = MatcherOne<V> | readonly MatcherOne<Across>[];
4938
4939 /**
4940 * The type of key `K` across the variants of `I` that declare it.
4941 */
4942 type MatcherValueOf<I, K> = I extends unknown ? K extends KnownKeys<I> ? I[K] : never : never;
4943
4944 /**
4945 * One block of an MCP result: `type` and the fields that kind of block carries.
4946 */
4947 export type McpContentBlock = {
4948 /**
4949 * The block's kind: `text`, `image`, `audio`, `resource`, `resource_link`.
4950 */
4951 type: string;
4952 /**
4953 * Set on a `text` block.
4954 */
4955 text?: string;
4956 /**
4957 * Set on a `resource_link` (or embedded `resource`) block.
4958 */
4959 uri?: string;
4960 /**
4961 * Declared by an image, audio or resource block.
4962 */
4963 mimeType?: string;
4964 [field: string]: unknown;
4965 };
4966
4967 /**
4968 * 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.
4969 */
4970 type McpServerProvenance = {
4971 name: string;
4972 /**
4973 * sdk | plugin | user | project | local | dynamic | managed | enterprise | claudeai | agent - an open set; treat unknown values as an unrecognized configured source, never as sdk.
4974 */
4975 source: string;
4976 };
4977
4978 /**
4979 * The MCP branch of a `tool.call` hook's `e` (and of `$.tool.call`'s input):
4980 * one variant per declared tool, else the loose McpToolCallInputFallback.
4981 *
4982 * `$.mcp.call(server, tool, args)` takes none of these: its parameters are
4983 * positional, the server and tool by name, then the arguments object.
4984 */
4985 export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
4986 [N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
4987 }[keyof McpToolInputs & string];
4988
4989 /**
4990 * The `e` a `tool.call` (or `classic.PreToolUse`) hook receives for an MCP
4991 * tool while no MCP tool is declared: every `mcp__*` name, loose arguments.
4992 *
4993 * McpToolInputs has no entries until `/plugin-types` writes the connected
4994 * tools' declarations; also the `input` of `$.tool.call({ tool:
4995 * "mcp__<server>__<tool>", ... })`. Not `$.mcp.call`'s, which is positional:
4996 *
4997 * @example
4998 * on("tool.call", { tool: "mcp__gh__issue" }, ($, e, next) => audit(e.title))
4999 */
5000 type McpToolCallInputFallback = {
5001 /**
5002 * The name of the tool being called (`mcp__<server>__<tool>`); comparing
5003 * it narrows `e`. Reserved: a rewrite of it is ignored by core.
5004 */
5005 tool: McpToolName;
5006 /**
5007 * The tool_use block's id: the same at every event of the call and in
5008 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
5009 */
5010 tool_use_id: string;
5011 [argument: string]: unknown;
5012 };
5013
5014 /**
5015 * The inputs of the MCP tools this project knows, keyed by full tool name,
5016 * for declaration merging; empty by default, then every MCP tool is loose.
5017 *
5018 * A `.d.ts` in the plugin author's project (written by `/plugin-types <dir>`
5019 * from the connected servers' JSON Schemas, or by hand) adds entries under
5020 * `declare module "claude-code"`; `e.tool === <name>` then narrows to them.
5021 *
5022 * @example
5023 * interface McpToolInputs { "mcp__my_server__send": { to: string } }
5024 */
5025 export interface McpToolInputs {
5026 }
5027
5028 /**
5029 * The name of an MCP tool as the engine spells it: `mcp__<server>__<tool>`.
5030 */
5031 export type McpToolName = `mcp__${string}__${string}`;
5032
5033 /**
5034 * An MCP tools/call result as the SDK returns it, plain data.
5035 */
5036 export type McpToolResult = {
5037 /**
5038 * The result's content blocks, in order (text, image, resource,
5039 * resource_link, ...).
5040 */
5041 content: McpContentBlock[];
5042 /**
5043 * True when the server reported the call as failed; the blocks then describe
5044 * the error.
5045 */
5046 isError: boolean;
5047 /**
5048 * The server's structured result, when its tool declares an output schema.
5049 */
5050 structuredContent?: unknown;
5051 };
5052
5053 /**
5054 * 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.
5055 */
5056 type MessageDisplayHookInput = BaseHookInput & {
5057 hook_event_name: 'MessageDisplay';
5058 /**
5059 * UUID of the current turn.
5060 */
5061 turn_id: string;
5062 /**
5063 * UUID of the assistant message being displayed. Stable across every flush of the same message. Not the API msg_... id.
5064 */
5065 message_id: string;
5066 /**
5067 * Zero-based index of this delta within the message. Increments by one per flush.
5068 */
5069 index: number;
5070 /**
5071 * True on the message's last flush. Exactly one flush per message has it.
5072 */
5073 final: boolean;
5074 /**
5075 * 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.
5076 */
5077 delta: string;
5078 };
5079
5080 /**
5081 * What `$.model.complete` takes.
5082 */
5083 export type ModelCompleteRequest = {
5084 /**
5085 * An alias (`haiku`) or a full model id; resolved and allowlist-checked like
5086 * a `--model` value.
5087 */
5088 model: string;
5089 /**
5090 * The one user message; the reply's text comes back.
5091 */
5092 prompt: string;
5093 /**
5094 * Precedes the completion as its system prompt, after the CLI's identity
5095 * block. Default none.
5096 */
5097 system?: string;
5098 /**
5099 * The reply's token cap: any positive integer up to what one reply can
5100 * hold, the model's own output limit or 64000, whichever is lower.
5101 *
5102 * Default 1024. The reply comes back whole, not streamed, and a provider
5103 * ends such a request at ten minutes, hence the 64000. One past the limit
5104 * is refused, naming it.
5105 */
5106 maxTokens?: number;
5107 };
5108
5109 /**
5110 * What `$.model.fork` takes.
5111 */
5112 export type ModelForkRequest = {
5113 /**
5114 * The one user message, appended to the session's own transcript.
5115 *
5116 * The reply's text and usage come back, or null on an API error or a cold
5117 * transcript.
5118 */
5119 prompt: string;
5120 };
5121
5122 /**
5123 * What `$.model.fork` resolves to when the fork answered: the reply's text
5124 * and what the fork cost.
5125 */
5126 export type ModelForkResult = {
5127 /**
5128 * The non-error replies' text, joined by newlines.
5129 */
5130 text: string;
5131 /**
5132 * The fork's token counts, so a plugin can account for what it spent.
5133 */
5134 usage: ModelForkUsage;
5135 };
5136
5137 /**
5138 * What one fork cost, as the API counted it: the four token counts of the
5139 * fork's completions summed.
5140 */
5141 export type ModelForkUsage = {
5142 input_tokens: number;
5143 output_tokens: number;
5144 cache_read_input_tokens: number;
5145 cache_creation_input_tokens: number;
5146 };
5147
5148 /**
5149 * The prefixes a glob may name: one or more whole leading segments of an
5150 * event name (`tool` of `tool.call`), derived, plugin nouns included.
5151 */
5152 export type Namespace<N extends string = EventName> = N extends `${infer Head}.${infer Rest}` ? Head | `${Head}.${Namespace<Rest>}` : never;
5153
5154 /**
5155 * How many object or array levels a matcher narrows `e` through, counted as
5156 * a tuple's length: the runtime's own limit, which refuses a deeper matcher.
5157 *
5158 * Past it a field keeps its declared type; nothing becomes `any`.
5159 */
5160 type NarrowDepth = 8;
5161
5162 /**
5163 * `e` in a matched hook: the members of the argument union `E` matcher `P`
5164 * can match, each with the keys `P` names narrowed to what a match implies.
5165 *
5166 * A scalar narrows to the literal, a one-of to what its alternatives give,
5167 * an object key recursively, an array some element of which must match to
5168 * a non-empty tuple; other keys, `unknown` and RegExp-matched fields keep.
5169 */
5170 export type Narrowed<E, P> = E extends unknown ? NarrowedMember<E, P, []> : never;
5171
5172 /**
5173 * A value of declared type `V` under a one-of, folded over the tuple into
5174 * `Found`: the union of what each alternative narrows `V` to (NarrowedByOne).
5175 *
5176 * An alternative that cannot match adds nothing, so a one-of none of whose
5177 * alternatives can is `never`; a one-of typed as a plain array rather than
5178 * a tuple narrows by the union of its elements at once.
5179 */
5180 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>;
5181
5182 /**
5183 * A value of declared type `V` under one matcher node `Q` that is not a
5184 * one-of, member of `V` by member; a member that cannot match is `never`.
5185 *
5186 * An array some element of which must match becomes NonEmpty; a RegExp
5187 * keeps the member; an object pattern recurses into an object member, one
5188 * level down; a scalar keeps a member as narrow, and replaces a wider one.
5189 */
5190 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;
5191
5192 /**
5193 * One object member `E` under object pattern `P`, `D` levels down: `never`
5194 * when a key of `P` is impossible on it (ImpossibleKeys), else `E` narrowed.
5195 *
5196 * Each key `P` names is narrowed (NarrowedValue); every other key, and each
5197 * key's optionality, stays as declared.
5198 */
5199 type NarrowedMember<E, P, D extends readonly unknown[]> = [
5200 ImpossibleKeys<E, P, D>
5201 ] extends [never] ? {
5202 [K in keyof E]: K extends keyof P ? NarrowedValue<E[K], P[K], D> : E[K];
5203 } : never;
5204
5205 /**
5206 * A value of declared type `V` where the matcher gives `Q`, `D` levels
5207 * down: NarrowedByAny under a one-of (an array), NarrowedByOne otherwise.
5208 *
5209 * As declared once `D` reaches NarrowDepth, or for a field typed `unknown`
5210 * (a tool's input), which no pattern narrows.
5211 */
5212 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>;
5213
5214 /**
5215 * `!` before a name or a glob: every event except the ones it selects. `!*`
5216 * would select none, so it is no pattern.
5217 */
5218 type Negation = `!${Exclude<EventName | Glob, '*'>}`;
5219
5220 /**
5221 * The rest of the chain, as one hook receives it: made once per dispatch per
5222 * hook, frozen; `next(e)` resolves to the downstream result.
5223 *
5224 * Each call runs the hooks below again; core is the last, and below it `next`
5225 * rejects. Called with no argument it rejects, naming the hook. A hook that
5226 * returns without calling it ends the chain; returning nothing is a failure.
5227 *
5228 * @template S what `next.is(pattern, e)` narrows `e` to, per event: the event's
5229 * argument, or, under a matcher, that argument narrowed by it (MatchedHook)
5230 * @template T the tool `e` names, when it names one: on `tool.call` it types
5231 * the result (NextResultFor); an `e` without `tool` takes the line beneath
5232 */
5233 export type Next<N extends EventName = EventName, E = Args<N>, O = NextResult<N>, S extends {
5234 [K in N]?: unknown;
5235 } = {
5236 [K in N]: Args<K>;
5237 }> = {
5238 <T extends string>(e: E & ToolNamed<T>): Promise<NextResultFor<N, O, T>>;
5239 (e: E): Promise<O>;
5240 /**
5241 * Continues this dispatch at a tier: `next(e)` with every link between
5242 * this hook's own tier and that one skipped, by tier and narrowing only.
5243 *
5244 * A managed hook's: prepend may name append, builtin or core, append core;
5245 * it never skips a tier with more authority, so no user hook skips the
5246 * org's. A literal on the hook's own `next`; skipped links are traced.
5247 */
5248 readonly to: {
5249 <T extends string>(e: E & ToolNamed<T>, tier: TargetTier): Promise<NextResultFor<N, O, T>>;
5250 (e: E, tier: TargetTier): Promise<O>;
5251 };
5252 /**
5253 * Aborts when the call this dispatch belongs to is abandoned: the user
5254 * interrupted, a hook above settled first, or this hook ran out of budget.
5255 *
5256 * Anything the hook started (timers, requests) should stop on it. It is an
5257 * AbortSignal of the plugin's own environment, driven by the chain's.
5258 */
5259 readonly signal: AbortSignal;
5260 /**
5261 * Whether this dispatch's event is selected by `pattern` (a name, a glob,
5262 * a negation), as a type predicate on `e`: `next.is("tool.call", e)`.
5263 *
5264 * Under a matcher the narrowing includes it. `pattern` names events this
5265 * hook covers (PatternOver); a name outside them is a compile error.
5266 */
5267 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<S[Extract<N, Selected<M>>]>;
5268 /**
5269 * The name of this dispatch's event, as a value, for a glob hook to log or
5270 * switch on.
5271 */
5272 readonly event: N;
5273 /**
5274 * Who raised this dispatch: the calling plugin's name and the tier it sits
5275 * in (Origin); the engine reads `{ plugin: "engine", tier: "core" }`.
5276 *
5277 * Set by the host alone, from the environment the call came from (its own
5278 * MessagePort) and that plugin's seat; nothing a plugin writes reaches it.
5279 * Every hook of one dispatch sees the same origin, and `next.to` keeps it.
5280 *
5281 * @example
5282 * return next.origin.tier === "prepend" ? next.to(e, "append") : next(e)
5283 */
5284 readonly origin: Origin;
5285 /**
5286 * What settled beneath this hook on its latest `next()` call, the one
5287 * started last: an entry per link beneath, nearest first, the engine's last.
5288 *
5289 * Empty before `next` is called; filled even when `next` rejected; a link
5290 * still running joins in place later, nothing listed leaves; it ends short
5291 * of the engine at a link that answered its last call itself. Data, frozen.
5292 */
5293 readonly trace: readonly TraceEntry<N, E, O>[];
5294 /**
5295 * How much time this hook runs under and how much is left (NextBudget),
5296 * read fresh on each access; HookBudget says what the clock counts.
5297 *
5298 * It stands still while a `next` or `$` call of the hook's is in flight;
5299 * in a `.catch` handler it is the grace, `ms` being `next.error.budget`.
5300 *
5301 * @example
5302 * if (next.budget.remainingMs < 2_000) return next(e) // skip the polish
5303 */
5304 readonly budget: NextBudget;
5305 };
5306
5307 /**
5308 * The budget the code reading `next.budget` runs under: the whole allowance
5309 * and what is left of it now, plain data read fresh on each access.
5310 *
5311 * In a hook `ms` is HookBudget's `ms`; in a `.catch` handler its `catchMs`
5312 * (equal to `next.error.budget`); on a `next` nothing meters (the engine's
5313 * own, a test's root one) `ms` is 0 and `remainingMs` Infinity.
5314 *
5315 * @example
5316 * if (next.budget.remainingMs < 2_000) return next(e) // skip the slow path
5317 */
5318 export type NextBudget = {
5319 /**
5320 * The whole budget in milliseconds; 0 where nothing meters this `next`.
5321 */
5322 readonly ms: number;
5323 /**
5324 * What is left of it now, in milliseconds, never below 0; Infinity where
5325 * nothing meters. It stands still while a `next` or `$` call is in flight.
5326 */
5327 readonly remainingMs: number;
5328 };
5329
5330 /**
5331 * What `next(e)` resolves to for event `N`: the event's result, except at
5332 * `engine.create`, where the steps beneath return `$` as built so far.
5333 *
5334 * A withheld noun is on that `$` as a stub, so the built table is typed
5335 * whole where what a hook returns (EngineCreateResult) is partial.
5336 */
5337 export type NextResult<N extends EventName> = N extends 'engine.create' ? EngineInterfaceBuilt : EventResult<N>;
5338
5339 /**
5340 * What `next(e)` resolves to once `e.tool` is the literal `T`: on `tool.call`
5341 * the result typed for that tool; on every other event, `O` as declared.
5342 *
5343 * `result` is Bash's record after `e.tool === "Bash"`; an un-narrowed `e`
5344 * names every tool, and `result` stays `unknown`.
5345 */
5346 export type NextResultFor<N extends EventName, O, T extends string> = [
5347 N
5348 ] extends ['tool.call'] ? ToolCallResult<T> : O;
5349
5350 /**
5351 * The argument of a call on `$` that takes nothing (`$.session.cwd()`): an
5352 * object with no keys.
5353 */
5354 type NoArgs = Record<never, never>;
5355
5356 /**
5357 * The events whose argument is exactly NoArgs (`session.cwd`, a declared
5358 * plugin noun's `() => ...`); their overloads come last (LateOverload).
5359 */
5360 type NoArgsEvent = {
5361 [N in EventName]: Args<N> extends NoArgs ? NoArgs extends Args<N> ? N : never : never;
5362 }[EventName];
5363
5364 /**
5365 * What an `engine.create` hook receives as `$`: nothing. Every property
5366 * reads as `never`, so `$.model` inside the hook is a compile error.
5367 */
5368 export type NoEngineInterface = {
5369 readonly [noun: string]: never;
5370 };
5371
5372 /**
5373 * Array type `V`, of element `Item`, once some element of it is known to
5374 * match: a tuple of at least one `Item`, readonly when `V` is.
5375 *
5376 * So `e` still passes wherever the declared array is taken; a `V` that is
5377 * already a non-empty tuple is kept as it is.
5378 */
5379 type NonEmpty<V, Item> = V extends readonly [unknown, ...unknown[]] ? V : V extends Item[] ? [Item, ...Item[]] : readonly [Item, ...Item[]];
5380
5381 type NotificationHookInput = BaseHookInput & {
5382 hook_event_name: 'Notification';
5383 message: string;
5384 title?: string;
5385 notification_type: string;
5386 };
5387
5388 /**
5389 * The declared plugin nouns' methods as event rows (NounEventRow), one per
5390 * `<noun>.<method>` that is a function; a member that is not is no event.
5391 */
5392 type NounEvent = {
5393 [K in PluginNoun]: {
5394 [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;
5395 }[keyof EngineInterface[K] & string];
5396 }[PluginNoun];
5397
5398 /**
5399 * The name of a declared plugin noun's event (`voice.speak`).
5400 */
5401 type NounEventName = keyof NounEventOf & string;
5402
5403 /**
5404 * The events of the plugin nouns declared on EngineInterface, by name: the
5405 * argument of each `<noun>.<method>`. Empty until a plugin declares a noun.
5406 *
5407 * @example
5408 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
5409 */
5410 export type NounEventOf = {
5411 [E in NounEvent as E['name']]: E['args'];
5412 };
5413
5414 /**
5415 * The result of a declared plugin noun's event as its hooks see it:
5416 * `{ value }` (the method's answer) or `{ deny }`.
5417 */
5418 type NounEventResult<N extends NounEventName> = ValueOrDeny<NounValueOf[N]>;
5419
5420 /**
5421 * One method of a declared plugin noun as an event row: its event's name,
5422 * argument (the method's first parameter) and value (its awaited result).
5423 */
5424 type NounEventRow<Name extends string, Args, Value> = {
5425 name: Name;
5426 args: Args;
5427 value: Value;
5428 };
5429
5430 /**
5431 * What each declared plugin noun's method answers (the `value` of its
5432 * event's result), by event name.
5433 */
5434 type NounValueOf = {
5435 [E in NounEvent as E['name']]: E['value'];
5436 };
5437
5438 /**
5439 * Registers `hook` on the events `pattern` selects: one by name, every one
5440 * under a namespace (`classic.*`), all (`*`), or all but some (`!tool.*`).
5441 *
5442 * One function stands on every selected event (`next.event` says which),
5443 * under a matcher for the inputs it matches; a plugin's registrations nest
5444 * in order, first outermost; a repeat throws. Returns the Registration.
5445 *
5446 * @see HookBudget the time each hook has per dispatch (its own time: waits
5447 * on `next` and `$` are free), read live from `next.budget`
5448 */
5449 export type On = {
5450 <P extends Pattern>(pattern: P, hook: NoInfer<HookFor<P>>): Registration<HookFor<P>>;
5451 <P extends Pattern, const M extends Matcher<Args<MatchedNames<P>>>>(pattern: P, matcher: M, hook: NoInfer<MatchedHook<P, M>>): Registration<MatchedHook<P, M>>;
5452 };
5453
5454 /**
5455 * The part of a transcript message the surface that drew it has on screen:
5456 * units `first` to `last` of the message's `of`, counted from its start.
5457 *
5458 * The terminal counts the rows the site laid out, from its first (the blank
5459 * row the engine draws above a message is its row 0; a hook's tree starts at
5460 * its own); other surfaces count in their unit, so compare `first / of` there.
5461 *
5462 * @remarks While `null` the terminal holds the site at the rows it last laid
5463 * out (a scroller's geometry needs real rows); on screen, draw anything.
5464 * @example if (e.props.onScreen) shown.set(e.requestId, e.props.onScreen)
5465 * else shown.delete(e.requestId) // the band's legend lists `shown`
5466 */
5467 type OnScreen = {
5468 /**
5469 * The unit inside the viewport, from 0: on the terminal, `7` when the
5470 * message's top seven rows are scrolled away.
5471 */
5472 first: number;
5473 /**
5474 * The unit inside the viewport, inclusive; at least `first`.
5475 */
5476 last: number;
5477 /**
5478 * The message's whole extent in the same unit, as laid out (a hook's tree
5479 * taller than the engine's counts its own rows); more than `last`.
5480 *
5481 * One surface's numbers say nothing of another's: what the phone shows the
5482 * terminal may not, and each `ui.render` carries its own surface's.
5483 */
5484 of: number;
5485 };
5486
5487 /**
5488 * The keys a variant with a string index signature (an MCP tool's input)
5489 * takes beyond its own: another variant's key as typed there; others free.
5490 *
5491 * So a misspelt value for a key some variant declares (`command: 5`) is
5492 * refused on every variant, not admitted by the open one.
5493 */
5494 type OpenMatcher<I, All> = {
5495 readonly [K in Exclude<MatcherKeys<All>, KnownKeys<I>>]?: MatcherValue<MatcherValueOf<All, K>>;
5496 } & Readonly<Record<string, unknown>>;
5497
5498 /**
5499 * The name of a call on `$` the host serves, as an event.
5500 */
5501 export type OpEventName = keyof OpEventOf;
5502
5503 /**
5504 * The calls on `$` the host serves, as events: `e` is the call's argument as
5505 * it crosses to the host, and every one is hookable by name and by `on("*")`.
5506 *
5507 * A hook above the caller passes it on, rewrites it, refuses it with
5508 * `{ deny }` or answers with `{ value }`; core is the host's implementation.
5509 * The calling hook alone is skipped, and `next.origin` names the caller.
5510 */
5511 export type OpEventOf = {
5512 /**
5513 * The argument of `$.model.complete(request)`.
5514 */
5515 'model.complete': ModelCompleteRequest;
5516 /**
5517 * The argument of `$.model.classify(text, labels, options)`.
5518 */
5519 'model.classify': {
5520 text: string;
5521 labels: readonly string[];
5522 options?: ClassifyOptions;
5523 };
5524 /**
5525 * The argument of `$.model.fork(request)`.
5526 */
5527 'model.fork': ModelForkRequest;
5528 /**
5529 * The clip and how to play it (`shouldLoop`, `gain`); the signal does not
5530 * cross.
5531 */
5532 'audio.play': {
5533 clip: AudioClip;
5534 shouldLoop: boolean;
5535 gain?: number;
5536 };
5537 /**
5538 * The argument of `$.audio.speak(text, { voice })`.
5539 */
5540 'audio.speak': SpeakRequest;
5541 /**
5542 * The argument of `$.mcp.call(server, tool, args)`.
5543 */
5544 'mcp.call': {
5545 server: string;
5546 tool: string;
5547 args: Record<string, unknown>;
5548 };
5549 /**
5550 * The argument of `$.session.cwd()`.
5551 */
5552 'session.cwd': NoArgs;
5553 /**
5554 * The argument of `$.session.root()`.
5555 */
5556 'session.root': NoArgs;
5557 /**
5558 * The argument of `$.session.model()`.
5559 */
5560 'session.model': NoArgs;
5561 /**
5562 * The argument of `$.session.turns()`.
5563 */
5564 'session.turns': NoArgs;
5565 /**
5566 * The argument of `$.session.id()`.
5567 */
5568 'session.id': NoArgs;
5569 /**
5570 * The argument of `$.session.messages()`.
5571 */
5572 'session.messages': NoArgs;
5573 /**
5574 * The argument of `$.session.repo()`.
5575 */
5576 'session.repo': NoArgs;
5577 /**
5578 * The argument of `$.session.surface()`.
5579 *
5580 * @deprecated with `$.session.surface()`; hook `session.surfaces`
5581 */
5582 'session.surface': NoArgs;
5583 /**
5584 * The argument of `$.session.surfaces()`.
5585 */
5586 'session.surfaces': NoArgs;
5587 /**
5588 * The argument of `$.session.authorize()`.
5589 */
5590 'session.authorize': NoArgs;
5591 /**
5592 * The argument of `$.session.usage({ breakdown, columns })`.
5593 */
5594 'session.usage': SessionUsageArgs;
5595 /**
5596 * The argument of `$.session.version()`.
5597 */
5598 'session.version': NoArgs;
5599 /**
5600 * The argument of `$.turn.abort({ turnId })`.
5601 */
5602 'turn.abort': {
5603 turnId: string;
5604 };
5605 /**
5606 * The argument of `$.prompt.read()`.
5607 */
5608 'prompt.read': NoArgs;
5609 /**
5610 * The argument of `$.tool.list()`.
5611 */
5612 'tool.list': NoArgs;
5613 /**
5614 * The argument of `$.tool.register(spec)`.
5615 */
5616 'tool.register': Required<ToolSpec>;
5617 /**
5618 * The argument of `$.command.list()`.
5619 */
5620 'command.list': NoArgs;
5621 /**
5622 * The argument of `$.command.register(spec)`.
5623 */
5624 'command.register': CommandSpec;
5625 /**
5626 * The argument of `$.config.list()`.
5627 */
5628 'config.list': NoArgs;
5629 /**
5630 * The argument of `$.agent.list()`.
5631 */
5632 'agent.list': NoArgs;
5633 /**
5634 * The argument of `$.agent.register(spec)`: the agent type as the plugin
5635 * defined it. A hook above rewrites any of it; the type stays the caller's.
5636 */
5637 'agent.register': AgentSpec;
5638 /**
5639 * The argument of `$.ui.toast(text, { timeoutMs })`.
5640 */
5641 'ui.toast': {
5642 text: string;
5643 timeoutMs?: number;
5644 };
5645 /**
5646 * The argument of `$.ui.status(text)`; `text` undefined clears the line.
5647 */
5648 'ui.status': {
5649 text: string | undefined;
5650 };
5651 /**
5652 * The argument of `$.ui.log(text, { to })`; `to` is always present
5653 * (UiLogSink), and `next({ ...e, to: "debug" })` keeps a line off screen.
5654 */
5655 'ui.log': {
5656 text: string;
5657 to: UiLogSink;
5658 };
5659 /**
5660 * The argument of `$.ui.notice(tool_use_id, text)`.
5661 */
5662 'ui.notice': {
5663 tool_use_id: string;
5664 text: string | undefined;
5665 };
5666 /**
5667 * The argument of `$.ui.invalidate(event)`.
5668 */
5669 'ui.invalidate': {
5670 event: InvalidatableEventName;
5671 };
5672 /**
5673 * The argument of `$.ui.open({ id, title, focus })`; a hook above the
5674 * opener may retitle it or refuse it with `{ deny }`, never rename it.
5675 */
5676 'ui.open': PaneOpenArgs;
5677 /**
5678 * The argument of `$.ui.close({ id })` with `origin` `plugin`; the engine
5679 * raises it too, for the person (`person`) and an unload (`unload`).
5680 */
5681 'ui.close': PaneCloseInput;
5682 /**
5683 * The argument of `$.ui.panes()`.
5684 */
5685 'ui.panes': NoArgs;
5686 /**
5687 * The argument of `$.ui.blit(...)`: a Raster's `cells` or a keyed Image's
5688 * `source`; a hook above may rewrite either with `next`, or `{ deny }`.
5689 */
5690 'ui.blit': UiBlitArgs;
5691 /**
5692 * The argument of `$.fs.read(path, { as })`: `as` is `text` unless the
5693 * caller asked for `bytes`.
5694 */
5695 'fs.read': {
5696 path: string;
5697 as: FsReadAs;
5698 };
5699 /**
5700 * The argument of `$.fs.write(path, text)`.
5701 */
5702 'fs.write': {
5703 path: string;
5704 text: string;
5705 };
5706 /**
5707 * The argument of `$.fs.list(path)`.
5708 */
5709 'fs.list': {
5710 path: string;
5711 };
5712 /**
5713 * The argument of `$.fs.exists(path)`.
5714 */
5715 'fs.exists': {
5716 path: string;
5717 };
5718 /**
5719 * The argument of `$.fs.stat(path, { resolve })`: `resolve` is false
5720 * unless the caller asked where the path lands.
5721 */
5722 'fs.stat': {
5723 path: string;
5724 resolve: boolean;
5725 };
5726 /**
5727 * The argument of `$.fs.ancestors({ names, of, below })`.
5728 */
5729 'fs.ancestors': FsAncestorsRequest;
5730 /**
5731 * The argument of `$.store.get(key)`.
5732 */
5733 'store.get': {
5734 key: string;
5735 };
5736 /**
5737 * The argument of `$.store.set(key, value)`.
5738 */
5739 'store.set': {
5740 key: string;
5741 value: unknown;
5742 };
5743 /**
5744 * The argument of `$.store.delete(key)`.
5745 */
5746 'store.delete': {
5747 key: string;
5748 };
5749 /**
5750 * The argument of `$.store.keys()`.
5751 */
5752 'store.keys': NoArgs;
5753 /**
5754 * The argument of `$.clock.now()`.
5755 */
5756 'clock.now': NoArgs;
5757 /**
5758 * The argument of `$.clock.sleep(ms, { signal })`; the signal does not
5759 * cross, it aborts the dispatch.
5760 */
5761 'clock.sleep': ClockWait;
5762 /**
5763 * The argument of `$.clock.after(ms, fn)`: the wait before `fn`, which
5764 * stays in the plugin's environment and runs once the dispatch resolves.
5765 */
5766 'clock.after': ClockWait;
5767 /**
5768 * The argument of `$.clock.every(ms, fn)`, dispatched once per period:
5769 * `fn` runs each time a dispatch resolves, and the next period is asked.
5770 */
5771 'clock.every': ClockWait;
5772 /**
5773 * The argument of `$.http.fetch(url, init)`.
5774 */
5775 'http.fetch': {
5776 url: string;
5777 init?: HttpInit;
5778 };
5779 /**
5780 * The argument of `$.process.run(argv, init)`.
5781 */
5782 'process.run': {
5783 argv: readonly string[];
5784 init?: ProcessRunInit;
5785 };
5786 /**
5787 * The argument of `$.settings.read({ source })`.
5788 */
5789 'settings.read': SettingsReadArgs;
5790 /**
5791 * The argument of `$.env.get(name)`; `name` is identity, pinned.
5792 */
5793 'env.get': {
5794 name: string;
5795 };
5796 /**
5797 * The argument of `$.env.set(name, value)`; `name` is identity, pinned,
5798 * and no `value` unsets.
5799 */
5800 'env.set': {
5801 name: string;
5802 value?: string;
5803 };
5804 };
5805
5806 /**
5807 * The result of a call on `$` as its event's hooks see it: `{ value }` (the
5808 * call's answer) or `{ deny }`.
5809 */
5810 export type OpEventResult<N extends OpEventName = OpEventName> = ValueOrDeny<OpValueOf[N]>;
5811
5812 /**
5813 * What each call on `$` answers (the `value` of its event's result), by event
5814 * name.
5815 */
5816 export type OpValueOf = {
5817 'model.complete': string;
5818 'model.classify': string | undefined;
5819 'model.fork': ModelForkResult | null;
5820 'audio.play': void;
5821 'audio.speak': SpeakResult;
5822 'mcp.call': McpToolResult;
5823 'session.cwd': string;
5824 'session.root': string;
5825 'session.model': string;
5826 'session.turns': number;
5827 'session.id': string;
5828 'session.messages': SessionMessage[];
5829 'session.repo': SessionRepo | null;
5830 'session.surface': RenderSurface | null;
5831 'session.surfaces': readonly RenderSurface[];
5832 /**
5833 * The credential handle, or null where the build or the provider has no
5834 * first-party credential to hold.
5835 */
5836 'session.authorize': SessionAuthorization;
5837 'session.usage': SessionUsage;
5838 /**
5839 * The engine's version, its release, and its build time when stamped.
5840 */
5841 'session.version': SessionVersion;
5842 'turn.abort': void;
5843 /**
5844 * The box as it stands; the empty box where the session draws none.
5845 */
5846 'prompt.read': PromptBox;
5847 'tool.list': ToolInfo[];
5848 'tool.register': {
5849 tool: string;
5850 };
5851 'command.list': CommandInfo[];
5852 'command.register': {
5853 command: string;
5854 };
5855 'config.list': ConfigRow[];
5856 'agent.list': AgentInfo[];
5857 'agent.register': {
5858 agent: string;
5859 };
5860 'ui.toast': void;
5861 'ui.status': void;
5862 'ui.log': void;
5863 'ui.notice': void;
5864 'ui.invalidate': void;
5865 'ui.open': void;
5866 'ui.close': void;
5867 /**
5868 * The calling plugin's open panes, placed then unplaced, in open order.
5869 */
5870 'ui.panes': readonly UiPane[];
5871 'ui.blit': UiBlitResult;
5872 /**
5873 * The text; `{ base64 }` when asked for bytes.
5874 */
5875 'fs.read': string | FsBytes;
5876 'fs.write': void;
5877 'fs.list': FsEntry[];
5878 'fs.exists': boolean;
5879 'fs.stat': FsStat;
5880 'fs.ancestors': readonly FsAncestor[];
5881 'store.get': unknown;
5882 'store.set': void;
5883 'store.delete': void;
5884 'store.keys': string[];
5885 /**
5886 * Milliseconds since the epoch.
5887 */
5888 'clock.now': number;
5889 'clock.sleep': void;
5890 'clock.after': void;
5891 'clock.every': void;
5892 'http.fetch': HttpResponse;
5893 'process.run': ProcessRunResult;
5894 'settings.read': Settings;
5895 'env.get': string | undefined;
5896 'env.set': void;
5897 };
5898
5899 /**
5900 * One call signature per event in `Names`, intersected, the ambiguous ones
5901 * (LateOverload) after the rest: `next` for a hook covering several events.
5902 *
5903 * An empty group contributes nothing (Overloads<never> is unknown).
5904 */
5905 type OrderedOverloads<Names extends EventName> = Overloads<Exclude<Names, LateOverload>> & Overloads<Extract<Names, 'classic.PreToolUse'>> & Overloads<Extract<Names, 'turn.abort'>> & Overloads<Extract<Names, NoArgsEvent>>;
5906
5907 /**
5908 * Who raised a dispatch, as `next.origin` holds it: the calling plugin's
5909 * name and the tier it sits in; the engine reads `engine` in `core`.
5910 *
5911 * The same pair a `next.trace` entry names its link by, and an event's
5912 * `provider` its subject's definer by. Set by the host from where the call
5913 * came from and where that plugin was seated; nothing a plugin writes.
5914 */
5915 export type Origin = {
5916 /**
5917 * Whose hook made the `$` call, by name; `"engine"` for a call site,
5918 * `"client"` for a `Client` surface module's `ui.message` post.
5919 */
5920 readonly plugin: string;
5921 /**
5922 * Where that plugin sits among the chain's tiers (Tier); `"core"` for the
5923 * engine, the owning plugin's for a `client` post.
5924 */
5925 readonly tier: Tier;
5926 };
5927
5928 /**
5929 * One call signature per event in `Names`, intersected into an overload set.
5930 */
5931 type Overloads<Names extends EventName> = UnionToIntersection<{
5932 [N in Names]: (e: Args<N>) => Promise<NextResult<N>>;
5933 }[Names]>;
5934
5935 /**
5936 * The argument of `$.ui.close`: the pane to close (`{ id }`). `origin` is
5937 * the engine's to set: a plugin's call reads `plugin` at the hooks.
5938 */
5939 export type PaneCloseArgs = Omit<PaneCloseInput, 'origin'>;
5940
5941 /**
5942 * The input of `ui.close`: the pane closing and why (PaneCloseOrigin).
5943 * Closing an id that is not open does nothing.
5944 */
5945 export type PaneCloseInput = {
5946 /**
5947 * What `$.ui.open` named the pane; pinned: `next(e)` passes it on.
5948 */
5949 id: string;
5950 /**
5951 * Who closes it, set by the engine: a hook that answers without `next`
5952 * keeps the pane open on `plugin` and `person`, never on `unload`.
5953 */
5954 origin: PaneCloseOrigin;
5955 };
5956
5957 /**
5958 * Why a pane closes, as the engine stamped it at `ui.close`.
5959 *
5960 * `unload` drops a pane nothing draws any more (its plugin unloaded, or its
5961 * drawing threw): it is gone before the hooks hear of it, and its opener's
5962 * hooks do not run. `next(e)` passes the origin on as received; none sets it.
5963 */
5964 export type PaneCloseOrigin = {
5965 /**
5966 * `plugin`, a plugin's `$.ui.close`; `person`, the person's close mark or
5967 * close key; `unload`, the engine's own.
5968 */
5969 kind: 'plugin' | 'person' | 'unload';
5970 };
5971
5972 /**
5973 * The argument of `$.ui.open`: which pane, its title, whether it asks the
5974 * person's keyboard, its dialog manners, its size: rows inline, columns docked.
5975 *
5976 * An open answering the person's input (a command or prompt they entered, a
5977 * press) is placed at any width; one the plugin makes on its own waits
5978 * undrawn below 144 terminal columns, 110 once they asked for that id.
5979 */
5980 export type PaneOpenArgs = {
5981 /**
5982 * Names the pane: 1-64 of letters, digits, `_` and `-`. One pane per id:
5983 * opening an open id delivers the new title, never a second instance.
5984 *
5985 * Pinned at the hooks: `next(e)` passes it on; the title and focus rewrite.
5986 */
5987 id: string;
5988 /**
5989 * The pane's tab while more than one pane is open (with one, no title is
5990 * drawn), and the `title` its hook sees; the id when omitted.
5991 *
5992 * An unpaired surrogate half (a `.slice()` through an emoji) is drawn as
5993 * U+FFFD; a control character is refused.
5994 */
5995 title?: string;
5996 /**
5997 * A request, not a grant: the surface focuses (and raises) the pane only
5998 * while the prompt has the keys over an empty composer.
5999 *
6000 * An element of the band or a pane the person holds, text in the
6001 * composer, a dialog or a survey each refuse it: the pane opens without
6002 * the keyboard.
6003 */
6004 focus?: true;
6005 /**
6006 * While the pane holds the keyboard, the key that hands it back (Escape)
6007 * also closes it as the person's close does: `ui.close`, origin `person`.
6008 *
6009 * So does Escape at an idle, empty prompt once the prompt has the keys
6010 * again (the person typed, or `focus` was refused); over text, a running
6011 * turn, a dialog, a footer selection, a viewed agent's transcript or a
6012 * prompt mode of its own the key stays theirs.
6013 *
6014 * A hook may refuse that close and keep it open. Left out, Escape returns
6015 * the keys to the prompt and the pane stays. Each open sets it anew, as it
6016 * sets the title.
6017 */
6018 closeOnEscape?: true;
6019 /**
6020 * While the pane is on screen the surface holds its transient toasts (the
6021 * notification line under the prompt) and shows them once it closes.
6022 *
6023 * As it does behind the engine's own side panel; pinned warnings still
6024 * show. Left out, toasts show as they come. Each open sets it anew.
6025 */
6026 holdToasts?: true;
6027 /**
6028 * The body rows the pane's content wants while seated inline above the
6029 * prompt: it opens that tall, up to what the layout spares, not a third.
6030 *
6031 * A request, not a grant: a size the person dragged or keyed the block
6032 * to wins, this session's or a kept one, and the dock ignores it. A
6033 * positive whole number; left out, a third. Each open sets it anew.
6034 */
6035 rows?: number;
6036 /**
6037 * The body columns the pane's content wants while docked beside a
6038 * fullscreen transcript: the dock opens that wide, floor to ceiling.
6039 *
6040 * A request, not a grant: a width the person dragged or keyed the dock
6041 * to wins, this session's or a kept one, and the inline block ignores
6042 * it. A positive whole number; left out, the share. Each open sets it anew.
6043 *
6044 * @example
6045 * await $.ui.open({ id: "browser", focus: true, rows: 24, columns: 100 })
6046 */
6047 columns?: number;
6048 };
6049
6050 /**
6051 * What `on(pattern, hook)` and `next.is(pattern, e)` take: an event's name,
6052 * a glob (`*`, `classic.*`), or a negation of either (`!tool.describe`).
6053 */
6054 export type Pattern = EventName | Glob | Negation;
6055
6056 /**
6057 * The patterns `next.is` takes in a hook covering the events `N`: their
6058 * names, `*`, a glob over one of their namespaces, or a negation.
6059 *
6060 * A name none of them has is a compile error, as is a glob over a namespace
6061 * none is under; a negation that selects none of them narrows `e` to never.
6062 */
6063 type PatternOver<N extends EventName> = N | '*' | `${Namespace<N>}.*` | Negation;
6064
6065 type PermissionBehavior = 'allow' | 'deny' | 'ask';
6066
6067 type PermissionDeniedHookInput = BaseHookInput & {
6068 hook_event_name: 'PermissionDenied';
6069 tool_name: string;
6070 tool_input: unknown;
6071 tool_use_id: string;
6072 reason: string;
6073 mcp_server?: McpServerProvenance;
6074 };
6075
6076 /**
6077 * 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.
6078 */
6079 type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';
6080
6081 /**
6082 * A `classic.PermissionRequest` answer's `decision`, as the classic hook's
6083 * `hookSpecificOutput.decision`: allow (with a rewrite or rules) or deny.
6084 */
6085 export type PermissionRequestDecision = {
6086 behavior: 'allow';
6087 updatedInput?: Record<string, unknown>;
6088 updatedPermissions?: PermissionUpdates;
6089 } | {
6090 behavior: 'deny';
6091 message?: string;
6092 interrupt?: true;
6093 };
6094
6095 type PermissionRequestHookInput = BaseHookInput & {
6096 hook_event_name: 'PermissionRequest';
6097 tool_name: string;
6098 tool_input: unknown;
6099 permission_suggestions?: PermissionUpdate[];
6100 mcp_server?: McpServerProvenance;
6101 };
6102
6103 type PermissionRuleValue = {
6104 toolName: string;
6105 ruleContent?: string;
6106 };
6107
6108 type PermissionUpdate = {
6109 type: 'addRules';
6110 rules: PermissionRuleValue[];
6111 behavior: PermissionBehavior;
6112 destination: PermissionUpdateDestination;
6113 } | {
6114 type: 'replaceRules';
6115 rules: PermissionRuleValue[];
6116 behavior: PermissionBehavior;
6117 destination: PermissionUpdateDestination;
6118 } | {
6119 type: 'removeRules';
6120 rules: PermissionRuleValue[];
6121 behavior: PermissionBehavior;
6122 destination: PermissionUpdateDestination;
6123 } | {
6124 type: 'setMode';
6125 mode: PermissionMode;
6126 destination: PermissionUpdateDestination;
6127 } | {
6128 type: 'addDirectories';
6129 directories: string[];
6130 destination: PermissionUpdateDestination;
6131 } | {
6132 type: 'removeDirectories';
6133 directories: string[];
6134 destination: PermissionUpdateDestination;
6135 };
6136
6137 type PermissionUpdateDestination = 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg';
6138
6139 /**
6140 * The permission rules a PermissionRequest allow may add: the shape of the
6141 * request's own `permission_suggestions` (the SDK's PermissionUpdate list).
6142 */
6143 type PermissionUpdates = NonNullable<ClassicHookInputs['PermissionRequest']['permission_suggestions']>;
6144
6145 /**
6146 * How `$.audio.play` plays a clip: looped until `signal` aborts, or once.
6147 *
6148 * A loop needs the signal that ends it; a single play takes one as an option.
6149 */
6150 export type PlayOptions = {
6151 /**
6152 * Repeat the clip until `signal` aborts (the promise then resolves).
6153 */
6154 shouldLoop: true;
6155 /**
6156 * Linear gain, from 0 to 4; default 1.
6157 */
6158 gain?: number;
6159 /**
6160 * Stops the clip: playback ends at once and the promise resolves.
6161 */
6162 signal: AbortSignal;
6163 } | {
6164 /**
6165 * Play once.
6166 */
6167 shouldLoop?: false;
6168 /**
6169 * Linear gain, from 0 to 4; default 1.
6170 */
6171 gain?: number;
6172 /**
6173 * Stops the clip early, as above.
6174 */
6175 signal?: AbortSignal;
6176 };
6177
6178 /**
6179 * The nouns a plugin declared on `$` by merging into EngineInterface; never
6180 * one the engine's own events are under (`tool`, `session`, `ui`).
6181 */
6182 type PluginNoun = Exclude<keyof EngineInterface & string, keyof CoreEngineInterface | Namespace<CoreEventName>>;
6183
6184 /**
6185 * A plugin's options as `register(on, options)` receives them: the values of
6186 * the fields its manifest's `userConfig` declares, defaults filled in.
6187 *
6188 * Stored in settings.json `pluginConfigs[<plugin>].options` (sensitive ones
6189 * in secure storage), validated against the declared `type` before the module
6190 * loads; a required field with no value fails the load, naming the field. A
6191 * string field that declares `options` holds one of them: `/config` draws it
6192 * as a picker over them, and a stored value outside them counts as unset, so
6193 * its default applies. A `--plugin-dir` plugin's key is its plugin.json
6194 * `<name>` (or `<name>@inline`).
6195 */
6196 export type PluginOptions = Readonly<Record<string, string | number | boolean | readonly string[]>>;
6197
6198 /**
6199 * The input of `plugin.register`: one hooks module the engine is about to
6200 * load, read off its manifest and its scanned source. Every field is pinned.
6201 *
6202 * `tier` and `uses` are the host's reading of the module, what a gate holds
6203 * it to; `name`, `root`, `version` and `provenance` are its own word (its
6204 * manifest, its place), so a rule keyed on them is one a rename walks past.
6205 */
6206 export type PluginRegisterInput = {
6207 /**
6208 * The plugin's name, as its own plugin.json declares it.
6209 */
6210 name: string;
6211 /**
6212 * Where its hooks would stand among the chain's tiers (Tier); never
6213 * `core`, the engine's own.
6214 */
6215 tier: Exclude<Tier, 'core'>;
6216 /**
6217 * The plugin's directory (the one holding plugin.json), absolute.
6218 */
6219 root: string;
6220 /**
6221 * Its manifest's `version`, when it states one.
6222 */
6223 version?: string;
6224 /**
6225 * Where the plugin came from, as the loader keys it: `<name>@<marketplace>`
6226 * installed, `<name>@inline` by `--plugin-dir`, `<name>@builtin` bundled.
6227 */
6228 provenance: string;
6229 /**
6230 * What the module hooks and calls, as scanned (PluginRegisterUses).
6231 */
6232 uses: PluginRegisterUses;
6233 };
6234
6235 /**
6236 * What a `plugin.register` hook returns and what `next(e)` resolves to:
6237 * `{ allow: true }` from core, or `{ refuse: reason }`.
6238 */
6239 export type PluginRegisterResult = {
6240 /**
6241 * The module loads: its `engine.create` step runs and its hooks join.
6242 */
6243 allow: true;
6244 refuse?: undefined;
6245 } | {
6246 /**
6247 * The module does not load: no step, no hooks, no tools or commands;
6248 * the transcript names the plugin that refused and this reason.
6249 */
6250 refuse: string;
6251 allow?: undefined;
6252 };
6253
6254 /**
6255 * What a hooks module uses, as the host scanned its source before loading it:
6256 * the same lists `claude plugin validate` prints and the host's rule reads.
6257 *
6258 * Exact, since a module that spells `on`, `$` or `$.env` other than literally
6259 * does not load.
6260 */
6261 export type PluginRegisterUses = {
6262 /**
6263 * The patterns its `on(...)` registrations name, as written (`tool.call`,
6264 * `*`, `classic.*`, `!tool.describe`), in registration order, each once.
6265 */
6266 events: readonly string[];
6267 /**
6268 * What it calls on `$`, spelled `noun.method` (`fs.write`, `http.fetch`),
6269 * sorted, each once.
6270 */
6271 calls: readonly string[];
6272 /**
6273 * The environment variables its `$.env.get` and `$.env.set` calls name;
6274 * absent when it calls neither.
6275 */
6276 env?: {
6277 /**
6278 * The names its `$.env.get` calls spell, sorted, each once.
6279 */
6280 reads: readonly string[];
6281 /**
6282 * The names its `$.env.set` calls spell, sorted, each once.
6283 */
6284 writes: readonly string[];
6285 };
6286 };
6287
6288 /**
6289 * Whose element: the plugin whose hook drew it, stamped by the runtime as the
6290 * tree leaves it; a Box's or Text's `group`, a Client's or Raster's own.
6291 *
6292 * A Button's `press` names its plugin the same way, beside its handle. Two
6293 * plugins under one `hover.scope` string never share a group.
6294 */
6295 type PluginStamp = {
6296 plugin: string;
6297 };
6298
6299 type PostCompactHookInput = BaseHookInput & {
6300 hook_event_name: 'PostCompact';
6301 trigger: 'manual' | 'auto';
6302 /**
6303 * The conversation summary produced by compaction
6304 */
6305 compact_summary: string;
6306 };
6307
6308 type PostModelSwitchHookInput = (BaseHookInput & {
6309 hook_event_name: 'PostModelSwitch';
6310 }) & {
6311 /**
6312 * Resolved model id the session was running before the switch
6313 */
6314 from_model: string;
6315 /**
6316 * Resolved model id the session runs after the switch
6317 */
6318 to_model: string;
6319 /**
6320 * What was asked for (alias such as "opus", a full id, or null for "default")
6321 */
6322 requested_model: string | null;
6323 /**
6324 * 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
6325 */
6326 source: 'command' | 'picker' | 'sdk' | 'auto' | 'resume';
6327 /**
6328 * 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)
6329 */
6330 context_tokens: number;
6331 /**
6332 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
6333 */
6334 prompt_cache_warm: boolean;
6335 cache_ttl: '5m' | '1h';
6336 /**
6337 * 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
6338 */
6339 estimated_cache_write_usd: number;
6340 /**
6341 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
6342 */
6343 pricing: 'configured' | 'catalog' | 'default';
6344 };
6345
6346 /**
6347 * 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.
6348 */
6349 type PostToolBatchHookInput = BaseHookInput & {
6350 hook_event_name: 'PostToolBatch';
6351 tool_calls: PostToolBatchToolCall[];
6352 };
6353
6354 type PostToolBatchToolCall = {
6355 tool_name: string;
6356 tool_input: unknown;
6357 tool_use_id: string;
6358 tool_response?: unknown;
6359 };
6360
6361 type PostToolUseFailureHookInput = BaseHookInput & {
6362 hook_event_name: 'PostToolUseFailure';
6363 tool_name: string;
6364 tool_input: unknown;
6365 tool_use_id: string;
6366 error: string;
6367 is_interrupt?: boolean;
6368 /**
6369 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
6370 */
6371 duration_ms?: number;
6372 mcp_server?: McpServerProvenance;
6373 };
6374
6375 type PostToolUseHookInput = BaseHookInput & {
6376 hook_event_name: 'PostToolUse';
6377 tool_name: string;
6378 tool_input: unknown;
6379 tool_response: unknown;
6380 tool_use_id: string;
6381 /**
6382 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
6383 */
6384 duration_ms?: number;
6385 mcp_server?: McpServerProvenance;
6386 };
6387
6388 type PreCompactHookInput = BaseHookInput & {
6389 hook_event_name: 'PreCompact';
6390 trigger: 'manual' | 'auto';
6391 custom_instructions: string | null;
6392 };
6393
6394 type PreModelSwitchHookInput = (BaseHookInput & {
6395 hook_event_name: 'PreModelSwitch';
6396 }) & {
6397 /**
6398 * Resolved model id the session was running before the switch
6399 */
6400 from_model: string;
6401 /**
6402 * Resolved model id the session runs after the switch
6403 */
6404 to_model: string;
6405 /**
6406 * What was asked for (alias such as "opus", a full id, or null for "default")
6407 */
6408 requested_model: string | null;
6409 /**
6410 * 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)
6411 */
6412 source: 'command' | 'picker' | 'sdk';
6413 /**
6414 * 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)
6415 */
6416 context_tokens: number;
6417 /**
6418 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
6419 */
6420 prompt_cache_warm: boolean;
6421 cache_ttl: '5m' | '1h';
6422 /**
6423 * 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
6424 */
6425 estimated_cache_write_usd: number;
6426 /**
6427 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
6428 */
6429 pricing: 'configured' | 'catalog' | 'default';
6430 };
6431
6432 /**
6433 * The link a press landed on: one a `Markdown` drew, pressed where the
6434 * surface reports presses (a plain click in the fullscreen terminal).
6435 *
6436 * What the surface knows of the cell pressed, not which occurrence: two
6437 * links written with one target read the same here.
6438 */
6439 export type PressedLink = {
6440 /**
6441 * The link's target as the surface drew it: for an `https:` link, the
6442 * href as the markdown wrote it.
6443 */
6444 href: string;
6445 };
6446
6447 /**
6448 * The decision of a `classic.PreToolUse` result: `allow`, `ask`, `deny`, or
6449 * none.
6450 */
6451 export type PreToolUseDecision = {
6452 /**
6453 * Lets the call run without a permission prompt (the managed-settings
6454 * hooks ran first; a deny from them ended the chain above).
6455 */
6456 allow: true;
6457 ask?: undefined;
6458 deny?: undefined;
6459 } | {
6460 /**
6461 * Asks the user before the call runs; the text is shown as the reason.
6462 */
6463 ask: string;
6464 allow?: undefined;
6465 deny?: undefined;
6466 } | {
6467 /**
6468 * Refuses the call; the model receives the text as the reason.
6469 */
6470 deny: string;
6471 allow?: undefined;
6472 ask?: undefined;
6473 } | {
6474 allow?: undefined;
6475 ask?: undefined;
6476 deny?: undefined;
6477 };
6478
6479 type PreToolUseHookInput = BaseHookInput & {
6480 hook_event_name: 'PreToolUse';
6481 tool_name: string;
6482 tool_input: unknown;
6483 tool_use_id: string;
6484 mcp_server?: McpServerProvenance;
6485 };
6486
6487 /**
6488 * What a `classic.PreToolUse` hook returns: one of `allow`, `ask`, `deny`,
6489 * or none of them, which passes the call on to the normal permission flow.
6490 */
6491 export type PreToolUseResult = PreToolUseDecision & {
6492 /**
6493 * Replaces the tool's arguments; validated against the tool's schema before
6494 * the tool runs.
6495 */
6496 updatedInput?: Record<string, unknown>;
6497 /**
6498 * Extra context handed to the model with the call, one entry per note.
6499 */
6500 additionalContext?: string[];
6501 };
6502
6503 /**
6504 * Options of `$.process.run`.
6505 */
6506 export type ProcessRunInit = {
6507 /**
6508 * The child's working directory, relative to the session's or absolute;
6509 * absent, the session's working directory.
6510 */
6511 cwd?: string;
6512 /**
6513 * Variables set over the host process's own environment.
6514 */
6515 env?: Record<string, string>;
6516 /**
6517 * Text written to the child's standard input, then closed.
6518 */
6519 stdin?: string;
6520 /**
6521 * How long the child may run before it is killed and the call rejects,
6522 * in milliseconds; 30 seconds when absent, ten minutes at most.
6523 */
6524 timeoutMs?: number;
6525 };
6526
6527 /**
6528 * What `$.process.run` resolves with once the child has exited.
6529 */
6530 export type ProcessRunResult = {
6531 /**
6532 * The child's exit status; a child ended by a signal reads as 1.
6533 */
6534 exitCode: number;
6535 /**
6536 * What the child wrote to standard output, as text, cut at the output
6537 * limit.
6538 */
6539 stdout: string;
6540 /**
6541 * What the child wrote to standard error, as text, cut at the output
6542 * limit.
6543 */
6544 stderr: string;
6545 };
6546
6547 /**
6548 * The input of `prompt.attachment`: one message the engine injects into the
6549 * conversation for the model on its own, as a request is about to carry it.
6550 *
6551 * A reminder, a mode transition, a listing, a mentioned file, a hook's
6552 * context: the person never typed it and mostly never sees it. Only an
6553 * attachment that carries text for the model is raised.
6554 */
6555 export type PromptAttachmentInput = {
6556 /**
6557 * As the engine names the attachment's kind; the key a matcher narrows on.
6558 * Pinned. Builds add and retire kinds: match by name.
6559 *
6560 * Among them `todo_reminder`, `plan_mode`, `plan_mode_exit`, `auto_mode`,
6561 * `auto_mode_exit`, `instructions`, `nested_memory`, `skill_listing`,
6562 * `deferred_tools_delta`, `edited_text_file`, `file`, `queued_command`.
6563 */
6564 type: string;
6565 /**
6566 * What the model reads for this attachment, inside the engine's framing;
6567 * rewritable with `next({ ...e, text })`.
6568 *
6569 * The `<system-reminder>` wrapper (or the system channel that replaces it)
6570 * goes around what the chain answers, never inside it. An attachment
6571 * rendered as several text blocks hands them joined by newlines.
6572 */
6573 text: string;
6574 /**
6575 * Who authored the text (PromptAttachmentOrigin): the engine, a settings
6576 * hook, or a plugin's chain context.
6577 *
6578 * Pinned: a different value is refused, one left out is kept.
6579 */
6580 origin: PromptAttachmentOrigin;
6581 /**
6582 * The loop whose request carries the attachment: a subagent's id, the `id`
6583 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
6584 *
6585 * Pinned: a different value is refused, one left out is kept. A subagent
6586 * a hook spawned through `$.agent.spawn` is resolved past that hook.
6587 */
6588 agentId?: string;
6589 };
6590
6591 /**
6592 * Who authored the text an injected attachment carries, as the engine knows
6593 * it from the attachment itself; a closed set, pinned on the event.
6594 *
6595 * A hooks module reads `e.origin.kind` to tell the engine's own prose from a
6596 * settings hook's output or another plugin's context. `next(e)` passes it on
6597 * as received; one left out is put back; no hook sets one.
6598 */
6599 export type PromptAttachmentOrigin = {
6600 /**
6601 * The engine's own prose or framing: a reminder, a mode transition, a
6602 * listing, a notice, an announced context block.
6603 *
6604 * A file the person mentioned, as the engine presents it, and a prompt
6605 * or notification delivered into a running turn are the engine's too.
6606 */
6607 kind: 'engine';
6608 } | {
6609 /**
6610 * A settings hook's output the engine injects for the model: its
6611 * additional context, a blocking error's note, a stopped continuation.
6612 */
6613 kind: 'hook';
6614 /**
6615 * The settings hook event that produced it (`SessionStart`,
6616 * `UserPromptSubmit`, `PostToolUse`, ...).
6617 */
6618 event: string;
6619 } | {
6620 /**
6621 * Text a plugin's hook attached through a chain's `context`
6622 * (`prompt.submit`, `tool.call`), as the model reads it.
6623 */
6624 kind: 'plugin';
6625 /**
6626 * The chain's event that attached it.
6627 */
6628 event: string;
6629 };
6630
6631 /**
6632 * What a `prompt.attachment` hook returns: the text the model reads for that
6633 * attachment, or null to leave the attachment out of the request.
6634 */
6635 export type PromptAttachmentResult = {
6636 text: string | null;
6637 };
6638
6639 /**
6640 * The person's prompt box as it stands: the draft and where the cursor is in
6641 * it; what `$.prompt.read()` resolves and `$.prompt.fill` hands back.
6642 *
6643 * No selection: the terminal's box has none of its own, and a surface that
6644 * binds one adds it here.
6645 */
6646 export type PromptBox = {
6647 /**
6648 * The draft as typed so far; `''` where the session draws no box.
6649 */
6650 text: string;
6651 /**
6652 * Where the next typed character lands: an offset into `text` in UTF-16
6653 * code units, 0 at the start, `text.length` at the end.
6654 */
6655 cursor: number;
6656 };
6657
6658 /**
6659 * One block of the context the first user message carries: a name the
6660 * engine keys it by and the text under it.
6661 */
6662 export type PromptContextBlock = {
6663 /**
6664 * The key the block renders under (`# name`): `claudeMd`, `userEmail`,
6665 * `attachedProject`, `currentDate`, or a plugin's own.
6666 *
6667 * The field a matcher narrows on; unique among one context's blocks.
6668 */
6669 name: string;
6670 /**
6671 * The block's text; `claudeMd`'s is the instruction files framed as the
6672 * engine frames them, empty when it announces none.
6673 */
6674 text: string;
6675 };
6676
6677 /**
6678 * The context blocks of a conversation's first user message, in the order
6679 * the engine renders them: what `prompt.context` takes and answers alike.
6680 */
6681 export type PromptContextBlocks = {
6682 /**
6683 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
6684 * `attachedProject`, `currentDate`, each only when present.
6685 */
6686 blocks: readonly PromptContextBlock[];
6687 };
6688
6689 /**
6690 * The input of `prompt.context`: the context blocks the engine prepends to a
6691 * conversation's first user message, and the files behind `claudeMd`.
6692 */
6693 export type PromptContextInput = {
6694 /**
6695 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
6696 * `attachedProject`, `currentDate`, each only when present.
6697 */
6698 blocks: readonly PromptContextBlock[];
6699 /**
6700 * The files behind `claudeMd`, in the order it renders them, `@` imports
6701 * included; empty when it renders none.
6702 *
6703 * Undefined when a hook above rewrote the `claudeMd` text: the files
6704 * behind that text are then unknown, and a hook adds none of its own.
6705 */
6706 instructionFiles?: readonly InstructionFile[];
6707 };
6708
6709 /**
6710 * What a `prompt.context` hook returns: the blocks the conversation
6711 * carries, in order; one left out is not sent.
6712 */
6713 export type PromptContextResult = {
6714 /**
6715 * What the conversation carries, in order.
6716 */
6717 blocks: readonly PromptContextBlock[];
6718 /**
6719 * The files now behind `claudeMd`; left out, the ones from below stand.
6720 *
6721 * Kept in step with the `claudeMd` text at every link: a changed list
6722 * renders the text the next reader gets, a rewritten text makes the files
6723 * unknown from there on. Every kind is the hook's to add, drop or rewrite.
6724 */
6725 instructionFiles?: readonly InstructionFile[];
6726 };
6727
6728 /**
6729 * The input of `prompt.edit` (prompt-edit/): one edit the person makes in the
6730 * prompt box, as the draft before it and the splice the editor made of it.
6731 */
6732 export type PromptEditInput = {
6733 /**
6734 * Who edits (PromptEditOrigin): the person at the composer. Pinned:
6735 * `next(e)` passes it on as received.
6736 */
6737 origin: PromptEditOrigin;
6738 /**
6739 * The one key that made the edit, in `Client` `onKey`'s shape, when one
6740 * did; absent for a paste and for a burst of keys folded into one edit.
6741 *
6742 * Pinned: which key the person pressed is a fact, not the hook's to change.
6743 */
6744 key?: ClientKeyEvent;
6745 /**
6746 * The draft before the edit. `next({ ...e, text })` applies the edit to
6747 * another draft instead.
6748 */
6749 text: string;
6750 /**
6751 * Where the person's caret stood in `text` before the edit, 0 to
6752 * `text.length`.
6753 */
6754 cursor: number;
6755 /**
6756 * Where in `text` the edit begins: the start of the span it replaces, or
6757 * where what was typed goes in; a bare cursor move begins where it lands.
6758 */
6759 start: number;
6760 /**
6761 * Where the replaced span of `text` ends: `start` for an insertion or a
6762 * move, past it for a deletion (Backspace, a kill).
6763 */
6764 end: number;
6765 /**
6766 * What goes in between `start` and `end`: the typed or pasted text, `''` for
6767 * a deletion or a move.
6768 *
6769 * `next({ ...e, inputText })` puts in another; the cursor lands after it.
6770 */
6771 inputText: string;
6772 };
6773
6774 /**
6775 * Who edits the prompt box at `prompt.edit`, as the engine stamps it where
6776 * the edit starts; a closed set a matcher narrows on.
6777 *
6778 * `next(e)` passes it on as received; no hook sets one.
6779 */
6780 export type PromptEditOrigin = {
6781 /**
6782 * The person, typing or pasting into the main prompt box.
6783 */
6784 kind: 'composer';
6785 };
6786
6787 /**
6788 * What a `prompt.edit` hook returns and what `next(e)` resolves to: the box
6789 * after the edit (PromptBox), which the editor then shows.
6790 *
6791 * From core, `e.text` with the splice applied and the cursor after what went
6792 * in. Rewrite it (`{ ...r, text, cursor }`) to change what lands; answer
6793 * `{ text: e.text, cursor: e.cursor }` without `next` to consume the key.
6794 */
6795 export type PromptEditResult = PromptBox;
6796
6797 /**
6798 * `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it: no
6799 * `origin` (the engine sets the calling plugin's), `mode` optional.
6800 */
6801 export type PromptFillArgs = {
6802 /**
6803 * What the box is to take (PromptFillInput `text`).
6804 */
6805 text: string;
6806 /**
6807 * Where it goes (PromptFillMode); `replace` when left out.
6808 */
6809 mode?: PromptFillMode;
6810 };
6811
6812 /**
6813 * What `$.prompt.fill` resolves to: whether the box took the text, and the
6814 * box afterwards (PromptBox) as the caller's own `$.prompt.read()` reads it.
6815 *
6816 * The box goes to a plugin whose module calls `$.prompt.read`, through the
6817 * hooks on it; one that never does, or is refused there, gets the empty box.
6818 */
6819 export type PromptFilled = {
6820 /**
6821 * True once the box holds the text; false where no box could take it or a
6822 * hook kept it out (PromptFillResult).
6823 */
6824 isFilled: boolean;
6825 /**
6826 * The draft after the fill; unchanged when `isFilled` is false; `''` where
6827 * no box is drawn or the caller may not read it (see above).
6828 */
6829 text: string;
6830 /**
6831 * Where the person types next: an offset into `text`, past the fill's text
6832 * for `insert`, at the end for `replace` and `append`.
6833 */
6834 cursor: number;
6835 };
6836
6837 /**
6838 * The input of `prompt.fill` (prompt-fill/): a text about to be put in the
6839 * prompt box as the person's draft, over it, after it, or at the cursor.
6840 */
6841 export type PromptFillInput = {
6842 /**
6843 * What the box takes; the person edits it or presses Enter.
6844 * `next({ ...e, text })` writes another.
6845 */
6846 text: string;
6847 /**
6848 * Where the text goes (PromptFillMode): over the draft, after it, or in at
6849 * the cursor. `next({ ...e, mode })` moves it; left out of a rewrite, kept.
6850 */
6851 mode: PromptFillMode;
6852 /**
6853 * Who writes (PromptFillOrigin), set by the engine where the write
6854 * starts. Pinned: `next(e)` passes it on as received.
6855 */
6856 origin: PromptFillOrigin;
6857 };
6858
6859 /**
6860 * Where a `prompt.fill` puts its text: over the whole draft, after it, or
6861 * into it at the cursor.
6862 *
6863 * `replace` empties the box first and leaves the cursor at the text's end;
6864 * `append` keeps the draft and adds the text after it, cursor at the end;
6865 * `insert` splices the text in at the cursor and moves the cursor past it,
6866 * so what the person had typed stays on either side.
6867 */
6868 export type PromptFillMode = 'replace' | 'append' | 'insert';
6869
6870 /**
6871 * Who writes the prompt box at `prompt.fill`, as the engine stamps it where
6872 * the write starts; a closed set a matcher narrows on.
6873 *
6874 * `next(e)` passes it on as received; no hook sets one.
6875 */
6876 export type PromptFillOrigin = {
6877 /**
6878 * The engine writing the box on its own account; reserved for its own
6879 * sites, none of which raises `prompt.fill` as shipped.
6880 */
6881 kind: 'engine';
6882 } | {
6883 /**
6884 * A plugin's `$.prompt.fill`.
6885 */
6886 kind: 'plugin';
6887 /**
6888 * The filling plugin's name.
6889 */
6890 name: string;
6891 };
6892
6893 /**
6894 * What a `prompt.fill` hook returns and what `next(e)` resolves to: whether
6895 * the text went into the prompt box.
6896 */
6897 export type PromptFillResult = {
6898 /**
6899 * True once the box holds the text; false where no box can take it (a
6900 * dialog holds the keys, a headless session has none).
6901 *
6902 * A hook answering `{ isFilled: false }` without `next` keeps the text
6903 * out.
6904 */
6905 isFilled: boolean;
6906 };
6907
6908 /**
6909 * Where a `prompt.submit` submission came from, as the engine knows it at
6910 * the site it was queued from; a closed set, never a text prefix.
6911 *
6912 * A hooks module reads `e.origin.kind` to tell the user's own Enter from a
6913 * notification, a peer session, a schedule or another plugin. `next(e)`
6914 * passes it on as received; an answer may leave it out; no hook sets one.
6915 */
6916 export type PromptOrigin = {
6917 /**
6918 * The user's own gesture at the terminal, as the engine stamped it
6919 * (never presumed from an unstamped command).
6920 *
6921 * Enter at the prompt, typed or queued, or a click on a transcript
6922 * link; a channel the engine cannot attest (a same-user socket) is
6923 * never stamped, and arrives as `unclassified`.
6924 */
6925 kind: 'composer';
6926 } | {
6927 /**
6928 * The user's message through the Remote Control bridge (a phone or
6929 * web client).
6930 */
6931 kind: 'bridge';
6932 } | {
6933 /**
6934 * The SDK host's own turn (`claude -p`, the Agent SDK), not typed at
6935 * a terminal.
6936 */
6937 kind: 'sdk';
6938 } | {
6939 /**
6940 * A background task's notification, dequeued when the session went
6941 * idle or delivered into a running turn (`turnId` set).
6942 */
6943 kind: 'task-notification';
6944 } | {
6945 /**
6946 * A scheduled task, routine or /loop firing its stored prompt.
6947 */
6948 kind: 'scheduled-trigger';
6949 } | {
6950 /**
6951 * Another Claude session's message ("Another Claude session sent a
6952 * message"), as a turn of its own or delivered into a running one.
6953 */
6954 kind: 'peer';
6955 } | {
6956 /**
6957 * Another session's SendMessage delivery, model-authored and framed
6958 * as a notification.
6959 */
6960 kind: 'peer-send-message';
6961 } | {
6962 /**
6963 * A delivery a coordinating session composed for one of its threads.
6964 */
6965 kind: 'projects-relay';
6966 } | {
6967 /**
6968 * A message from a channel an MCP server relays (Slack, Telegram).
6969 */
6970 kind: 'channel';
6971 /**
6972 * The channel server's name.
6973 */
6974 server: string;
6975 } | {
6976 /**
6977 * A coordinating session's hand-off to a worker session.
6978 */
6979 kind: 'coordinator';
6980 } | {
6981 /**
6982 * A background observer agent's report to the agent it observes.
6983 */
6984 kind: 'observer';
6985 } | {
6986 /**
6987 * An activity digest delivered to an observer agent.
6988 */
6989 kind: 'observer-activity';
6990 } | {
6991 /**
6992 * A programmatic follow-up to a user's UI action, user-initiated but
6993 * not typed this turn.
6994 */
6995 kind: 'auto-continuation';
6996 } | {
6997 /**
6998 * A turn with no provenance the engine can name: one the ingress
6999 * could not classify, or a command queued with no stamp at all.
7000 *
7001 * An idle notice or a delivery receipt the engine queued isMeta with
7002 * no stamp is one too; the engine frames that shape as a non-user
7003 * source.
7004 */
7005 kind: 'unclassified';
7006 } | {
7007 /**
7008 * The session's owner pinging it from Slack.
7009 */
7010 kind: 'slack-ping';
7011 } | {
7012 /**
7013 * A plugin's `$.prompt.submit`; the model reads the prompt under the
7014 * plugin's name unless a hook leaves the origin out of its answer.
7015 */
7016 kind: 'plugin';
7017 /**
7018 * The submitting plugin's name.
7019 */
7020 name: string;
7021 };
7022
7023 /**
7024 * The input of `prompt.section`: one named section of the system prompt, at
7025 * the moment the engine assembles it.
7026 */
7027 export type PromptSectionInput = {
7028 /**
7029 * As the engine names the section (`env_info_simple`, `memory`, ...); the
7030 * key a matcher narrows on.
7031 */
7032 name: string;
7033 /**
7034 * The section's text as core computed it, or null when core omits it.
7035 */
7036 text: string | null;
7037 };
7038
7039 /**
7040 * What a `prompt.section` hook returns: the text the prompt carries for that
7041 * section, or null to leave it out.
7042 */
7043 export type PromptSectionResult = {
7044 text: string | null;
7045 };
7046
7047 /**
7048 * `prompt.submit`'s input as a plugin's call takes it: `origin`, `turnId`
7049 * and `wait` are the engine's to set, `context` the hooks' to attach.
7050 *
7051 * `origin` is the calling plugin's name; `turnId` is the turn a prompt typed
7052 * mid-turn ran over; `wait` is false, as a plugin's prompt runs once idle.
7053 */
7054 export type PromptSubmitArgs = Omit<PromptSubmitInput, 'origin' | 'turnId' | 'wait' | 'context'>;
7055
7056 /**
7057 * A pasted or attached non-text item of a submitted prompt; its kind, never
7058 * its bytes.
7059 */
7060 export type PromptSubmitAttachment = {
7061 /**
7062 * The item's kind.
7063 */
7064 type: 'image' | 'audio' | 'document';
7065 /**
7066 * The item's MIME type (`image/png`), when known.
7067 */
7068 mediaType?: string;
7069 /**
7070 * The pasted file's name, when it had one.
7071 */
7072 filename?: string;
7073 };
7074
7075 /**
7076 * The input of `prompt.submit`: the prompt as typed, after the input became
7077 * a user message and before it enters the session.
7078 */
7079 export type PromptSubmitInput = {
7080 /**
7081 * The prompt's text as it will reach the model (pastes already expanded).
7082 */
7083 text: string;
7084 /**
7085 * Present only when the submission carried images or other non-text items.
7086 */
7087 attachments?: readonly PromptSubmitAttachment[];
7088 /**
7089 * What the model reads beside the prompt and the user never sees, each
7090 * entry one block after the prompt as typed; absent as the engine raises it.
7091 *
7092 * A hook attaches on the way down: `next({ ...e, context: [...(e.context
7093 * ?? []), mine] })`, keeping which it likes; none empty, any length: past
7094 * 100,000 characters (200,000 together) the model reads a head and path.
7095 */
7096 context?: readonly string[];
7097 /**
7098 * The id of the model turn that was running when the prompt was submitted
7099 * (`turn.start`'s `turnId`): typed over that turn, or delivered into it.
7100 *
7101 * A queued delivery (a peer session's message) reaches the model inside a
7102 * running turn. Absent for a prompt submitted while the session was idle,
7103 * and for a plugin's own (`$.prompt.submit`), which runs once it is idle.
7104 */
7105 turnId?: string;
7106 /**
7107 * Whether the user asked the prompt to wait its turn (`chat:queueSubmit`,
7108 * `ctrl+x enter` by default): true for that submission, false otherwise.
7109 *
7110 * The engine queues every prompt typed mid-turn either way; the flag is
7111 * for hooks, so one that cancels the running turn on a plain Enter can
7112 * leave a waiting prompt alone. False for a prompt a plugin submitted.
7113 */
7114 wait: boolean;
7115 /**
7116 * Where the submission came from (PromptOrigin), set by the engine where
7117 * it was queued: the user's Enter, a notification, a peer, a plugin.
7118 *
7119 * `next(e)` passes it on as received; no hook may set one.
7120 */
7121 origin: PromptOrigin;
7122 };
7123
7124 /**
7125 * What a `prompt.submit` hook returns and what `next(e)` resolves to: the
7126 * prompt that entered, `{ text, context?, origin? }`, or `{ drop: reason }`.
7127 *
7128 * `next(e)` resolves once the prompt entered the session and its turn
7129 * started, or it was queued behind the running one; not when the turn ends,
7130 * which is `turn.complete`. A hook answering without `next` enters nothing.
7131 */
7132 export type PromptSubmitResult = {
7133 /**
7134 * The prompt that entered; from core, the text that arrived at the
7135 * bottom. A rewrite passes it down, `next({ ...e, text })`.
7136 */
7137 text: string;
7138 /**
7139 * What entered beside the prompt for the model, never shown the user:
7140 * from core, the context that arrived (`e.context`).
7141 *
7142 * Each entry is one block after the prompt as typed. A hook attaches
7143 * context on the way down; one put here after `next` resolved is not
7144 * attached (the prompt had entered), and is logged.
7145 */
7146 context?: readonly string[];
7147 /**
7148 * Where the prompt entered from: from core, `e.origin` as received;
7149 * absent, the prompt is the user's own.
7150 *
7151 * A hook may put back the origin it received; it may not set another.
7152 */
7153 origin?: PromptOrigin;
7154 drop?: undefined;
7155 } | {
7156 /**
7157 * The prompt did not enter: a hook's refusal, answered without `next`,
7158 * or a settings hook's block beneath.
7159 *
7160 * The text is shown to the user as the reason.
7161 */
7162 drop: string;
7163 text?: undefined;
7164 context?: undefined;
7165 origin?: undefined;
7166 };
7167
7168 /**
7169 * `prompt.suggest`'s input as a plugin's `$.prompt.suggest(args)` takes it:
7170 * `origin` is the engine's to set (the calling plugin's name).
7171 */
7172 export type PromptSuggestArgs = Omit<PromptSuggestInput, 'origin'>;
7173
7174 /**
7175 * The input of `prompt.suggest` (prompt-suggest/): a text about to be shown
7176 * dim in the empty prompt box, for Tab (or the right arrow) to take.
7177 */
7178 export type PromptSuggestInput = {
7179 /**
7180 * The proposed prompt: shown, not written; taking it puts it in the box
7181 * for editing. `next({ ...e, text })` proposes another.
7182 */
7183 text: string;
7184 /**
7185 * Who proposes (PromptSuggestOrigin), set by the engine where the
7186 * proposal starts. Pinned: `next(e)` passes it on as received.
7187 */
7188 origin: PromptSuggestOrigin;
7189 };
7190
7191 /**
7192 * Who proposes the text at `prompt.suggest`, as the engine stamps it where
7193 * the proposal starts; a closed set a matcher narrows on.
7194 *
7195 * `next(e)` passes it on as received; no hook sets one.
7196 */
7197 export type PromptSuggestOrigin = {
7198 /**
7199 * The engine's own guess at the person's next prompt, generated after
7200 * a turn (the prompt-suggestion service).
7201 */
7202 kind: 'suggestion';
7203 } | {
7204 /**
7205 * A plugin's `$.prompt.suggest`.
7206 */
7207 kind: 'plugin';
7208 /**
7209 * The proposing plugin's name.
7210 */
7211 name: string;
7212 };
7213
7214 /**
7215 * What a `prompt.suggest` hook returns and what `next(e)` resolves to:
7216 * whether the text is now the box's dim suggestion.
7217 */
7218 export type PromptSuggestResult = {
7219 /**
7220 * True once the box has the suggestion to show, at once or as soon as a
7221 * dialog gives the box back; false where it cannot show.
7222 *
7223 * It cannot while the box holds text, a turn runs, the text is blank, or
7224 * the session is headless. A hook answering `{ isShown: false }` without
7225 * `next` keeps it from showing.
7226 */
7227 isShown: boolean;
7228 };
7229
7230 /**
7231 * A `$.ui.blit` argument repainting one of the caller's mounted Rasters.
7232 *
7233 * `columns` and `rows`, when given, must be the mounted size (a resize is a
7234 * redraw, `$.ui.invalidate("ui.render")`, not a blit).
7235 */
7236 export type RasterBlitArgs = {
7237 /**
7238 * The site the Raster is drawn in, by the `requestId` this plugin draws
7239 * it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
7240 */
7241 requestId: string;
7242 /**
7243 * The Raster's `key` in that drawing.
7244 */
7245 key: string;
7246 /**
7247 * The new cells, encoded as the element's `cells` are (RasterProps), for
7248 * the mounted `columns * rows`.
7249 */
7250 cells: string;
7251 /**
7252 * The width the cells are laid out for; refused unless it is the mounted
7253 * Raster's. Absent, the mounted width.
7254 */
7255 columns?: number;
7256 /**
7257 * The height the cells are laid out for; refused unless it is the mounted
7258 * Raster's. Absent, the mounted height.
7259 */
7260 rows?: number;
7261 };
7262
7263 /**
7264 * The props of `Raster`, the terminal surface's cell-grid leaf: a fixed box
7265 * of cells, each a glyph, a foreground and a background, packed in `cells`.
7266 *
7267 * A leaf: no children, `hover` or `onPress` yet; repainted in place by
7268 * `$.ui.blit`. Terminal only for now (elsewhere a fragment); its palette
7269 * paints 1024 distinct color pairs at once and the rest as their nearest.
7270 */
7271 export type RasterProps = {
7272 /**
7273 * The element's address within the drawing: what `$.ui.blit` names to
7274 * repaint it, unique among the Rasters of one tree.
7275 */
7276 key: string;
7277 /**
7278 * How many terminal columns wide, 1 to 512; the site clips what its body
7279 * cannot show.
7280 */
7281 columns: number;
7282 /**
7283 * How many terminal rows tall, 1 to 256.
7284 */
7285 rows: number;
7286 /**
7287 * Every cell, row-major: standard padded base64 of `columns * rows`
7288 * little-endian u32 triplets `[codePoint, foreground, background]`.
7289 *
7290 * A code point is one printable width-1 BMP character (blocks, box drawing,
7291 * braille too), or the tree is refused naming the cell's index; a color is
7292 * `0x00RRGGBB`, or `0x01000000` (bit 24 alone) for the terminal's default.
7293 *
7294 * @example const words = Uint32Array.of(0x2588, 0xff8800, 0x01000000)
7295 * const cells = new Uint8Array(words.buffer).toBase64() // one orange cell
7296 */
7297 cells: string;
7298 };
7299
7300 /**
7301 * The hooks module's entry: `export function register(on, options)`. `on`
7302 * registers hooks; `options` is the plugin's configuration (PluginOptions).
7303 *
7304 * The options are fixed for this activation: a change to them reloads the
7305 * plugin and `register` runs again with the new object. Hooks close over it.
7306 * Its return is dropped, a promise awaited: `on => on(...)` is a module.
7307 *
7308 * @example
7309 * on("tool.call", ($, e, next) => e.tool === "Bash" ? { deny: "no" } : next(e))
7310 */
7311 export type Register = (on: On, options: PluginOptions) => unknown;
7312
7313 /**
7314 * What `on(...)` returns for a hook of type `F`: the registration, which
7315 * takes one `.catch` (CatchHandler); without it a failed hook is absent.
7316 *
7317 * A second `.catch` on one registration throws, as does one after
7318 * register() returned and one on `engine.create`, whose hook has no budget
7319 * and whose failure is the load's.
7320 */
7321 export type Registration<F> = {
7322 /**
7323 * Sets the handler run when the hook throws or overruns its budget; its
7324 * answer within the grace stands as the hook's result for the dispatch.
7325 *
7326 * The budget is HookBudget's `ms` and the grace its `catchMs`, both on
7327 * the clock that stops while the code waits on `next` or `$`.
7328 */
7329 readonly catch: (handler: CatchHandler<F>) => void;
7330 };
7331
7332 /**
7333 * What an element takes as `children`, as JSX passes them: a node, a number
7334 * (drawn as its string), a value the factory drops, or a list that may nest.
7335 *
7336 * `false`, `null` and `undefined` are dropped, so `{ok && <Text>hi</Text>}`
7337 * and `{n > 0 ? <Text>{n}</Text> : null}` type; a mapped list beside a
7338 * sibling nests. The element holds the flat, normalized list of RenderNode.
7339 */
7340 export type RenderChildren = RenderNode | number | boolean | null | undefined | readonly RenderChildren[];
7341
7342 /**
7343 * Everything `ui.render` can draw: one name per component that has a render
7344 * site; a matcher narrows on it.
7345 *
7346 * The permission dialog is drawn by the engine alone, since its answer
7347 * authorises an action; a plugin adds context with `$.ui.notice`. `Pane` is
7348 * the one component whose instances a plugin opens (`$.ui.open`).
7349 */
7350 export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'ToolProgress' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
7351
7352 /**
7353 * What a render hook returns, and what `next(e)` resolves to: a plain-data
7354 * tree of elements (a Box or Text is a StyledElement), strings as children.
7355 *
7356 * Props are an allowlisted subset of Ink's Box/Text props (the ones
7357 * ElementProps declares); a tree with any other prop fails validation as a
7358 * whole and the engine's own component is drawn with the original props.
7359 */
7360 export type RenderElement = StyledElement<'Box', BoxHoverProps> | StyledElement<'Text', TextHoverProps> | {
7361 /**
7362 * A button, on every surface: `[ label ]` on the terminal, a native
7363 * button on a desktop; a press raises `ui.press` (`e.element` the key).
7364 *
7365 * Built by `<Button>` or the table's `t.Button`. The `onPress` closure
7366 * stays in the plugin's own environment under `press.handle`; the host
7367 * holds the handle for the lifetime of the drawing. A leaf: no children.
7368 */
7369 type: 'Button';
7370 props: {
7371 /**
7372 * The element's address: what `e.element` carries and what a matcher
7373 * names (`{ element: "explain" }`).
7374 */
7375 key: string;
7376 /**
7377 * The text drawn on the button.
7378 */
7379 label: string;
7380 /**
7381 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it
7382 * while the plugin's site holds the focus; anything else is refused.
7383 *
7384 * The band after ctrl+x tab or a click, a focused `Pane`: on keydown,
7385 * lowercased; never from the composer, save a bare digit in an empty
7386 * one pressing a band Button. Two on one hotkey: the later wins.
7387 */
7388 hotkey?: string;
7389 /**
7390 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord
7391 * presses the Button from the prompt; an unknown name is refused.
7392 *
7393 * Chords, or a modified key Global or an active context binds, on
7394 * the terminal while mounted, no dialog up, no engine handler of it
7395 * mounted; a pane's over the band's over another's, the last drawn.
7396 */
7397 action?: string;
7398 /**
7399 * Drawn without chrome: the hotkey in the accent color, a colon,
7400 * then the label (`1: Yes`); without a `hotkey`, the label alone.
7401 *
7402 * The focus still inverts it. In JSX the label may be the one string
7403 * child (`<Button hotkey="1" plain onPress={...}>Yes</Button>`); the
7404 * key defaults to the label.
7405 */
7406 plain?: true;
7407 /**
7408 * The label dim at rest, as `Text`'s `dimColor`, and at full strength
7409 * under the pointer or the focus; absent draws as false.
7410 */
7411 dimColor?: TextProps['dimColor'];
7412 /**
7413 * The site's ring starts on this element when the site takes the
7414 * keyboard; the first drawn of several. Absent draws as before.
7415 */
7416 autoFocus?: true;
7417 };
7418 /**
7419 * Where the handler lives: the plugin whose hook drew the element, and
7420 * the handle its environment keeps the `onPress` closure under.
7421 *
7422 * The runtime stamps the plugin as the tree leaves that hook.
7423 */
7424 press: {
7425 plugin: string;
7426 handle: number;
7427 };
7428 /**
7429 * Label style overrides (the Text set) the surface applies while the
7430 * nearest keyed Box, or the group `scope` names, is hovered; plain data.
7431 */
7432 hover?: TextHoverProps;
7433 } | {
7434 /**
7435 * A one-line text field on every surface; a change and Enter raise
7436 * `ui.input` (`e.element` the key, `e.kind` which, `e.value` the text).
7437 *
7438 * Built by `<Input>` or the table's `t.Input`. The `onInput` and
7439 * `onSubmit` closures stay in the plugin's own environment under
7440 * `press.handle`, held as a Button's is. A leaf: no children.
7441 */
7442 type: 'Input';
7443 props: {
7444 /**
7445 * The element's address: what `e.element` carries and what a matcher
7446 * names (`{ element: "reply" }`).
7447 */
7448 key: string;
7449 /**
7450 * Text drawn before the field.
7451 */
7452 label?: string;
7453 /**
7454 * Text drawn dim in an empty field.
7455 */
7456 placeholder?: string;
7457 /**
7458 * The text the field holds when drawn.
7459 */
7460 value?: string;
7461 /**
7462 * What Enter does, drawn beside the field while it has focus.
7463 */
7464 submitLabel?: string;
7465 /**
7466 * The site's ring starts on this element when the site takes the
7467 * keyboard; the first drawn of several. Absent draws as before.
7468 */
7469 autoFocus?: true;
7470 };
7471 /**
7472 * Where the handlers live: the plugin whose hook drew the element, and
7473 * the handle its environment keeps the closures under.
7474 *
7475 * The runtime stamps the plugin as the tree leaves that hook.
7476 */
7477 press: {
7478 plugin: string;
7479 handle: number;
7480 };
7481 children?: undefined;
7482 } | {
7483 /**
7484 * A one-of-several picker on every surface; a pick raises `ui.select`
7485 * (`e.element` the key, `e.value` the option's value).
7486 *
7487 * Built by `<Select>` or the table's `t.Select`. The `onSelect` closure
7488 * stays in the plugin's own environment under `press.handle`, held as
7489 * a Button's is. A leaf: no children.
7490 */
7491 type: 'Select';
7492 props: {
7493 /**
7494 * The element's address: what `e.element` carries and what a matcher
7495 * names (`{ element: "peer" }`).
7496 */
7497 key: string;
7498 /**
7499 * Text drawn before the current value.
7500 */
7501 label?: string;
7502 /**
7503 * What can be picked, in the order drawn: each a value and the text
7504 * drawn for it.
7505 */
7506 options: readonly SelectOption[];
7507 /**
7508 * Which option is selected when drawn.
7509 */
7510 value?: string;
7511 /**
7512 * The site's ring starts on this element when the site takes the
7513 * keyboard; the first drawn of several. Absent draws as before.
7514 */
7515 autoFocus?: true;
7516 };
7517 /**
7518 * Where the handler lives: the plugin whose hook drew the element, and
7519 * the handle its environment keeps the closure under.
7520 *
7521 * The runtime stamps the plugin as the tree leaves that hook.
7522 */
7523 press: {
7524 plugin: string;
7525 handle: number;
7526 };
7527 children?: undefined;
7528 } | {
7529 /**
7530 * A hyperlink every surface draws: an OSC 8 span on the terminal (its
7531 * text then the URL in dim where unsupported), an anchor on desktop.
7532 *
7533 * Inline: its children are the text, strings and inline elements;
7534 * absent children the label, absent both the URL. `href` is `https:`
7535 * (or `http://localhost`) and bounded, or the tree is refused.
7536 */
7537 type: 'Link';
7538 props: LinkProps;
7539 children?: RenderNode[];
7540 } | {
7541 /**
7542 * Source code every surface draws with the engine's highlighter, tokens
7543 * coloured by language; under `format: 'diff'`, unified-diff hunks.
7544 *
7545 * A leaf: a dim gutter numbers the lines from `startLine`; a diff has
7546 * both gutters, markers, add and remove backgrounds. `source` is
7547 * bounded as a Text's string is, or the tree is refused.
7548 */
7549 type: 'Code';
7550 props: CodeProps;
7551 children?: undefined;
7552 } | {
7553 /**
7554 * A block of markdown every surface draws as it draws an assistant
7555 * reply's text: its own renderer, theme, hyperlinks and highlighting.
7556 *
7557 * Built by `<Markdown>` or the table's `t.Markdown`. A leaf: `text` is
7558 * bounded as a Text's string is, or the tree is refused. Without a
7559 * `press` its links are the surface's own, opened as it opens links.
7560 */
7561 type: 'Markdown';
7562 props: MarkdownLeafProps;
7563 children?: undefined;
7564 } | {
7565 /**
7566 * A `Markdown` whose plugin answers the links it drew (`onLinkPress`):
7567 * a press on one raises `ui.press` with `e.link`, the surface opens none.
7568 */
7569 type: 'Markdown';
7570 props: MarkdownLeafProps;
7571 /**
7572 * Where the `onLinkPress` handler lives: the plugin whose hook drew
7573 * the element, and the handle its environment keeps the closure under.
7574 *
7575 * The runtime stamps the plugin as the tree leaves that hook.
7576 */
7577 press: {
7578 plugin: string;
7579 handle: number;
7580 };
7581 children?: undefined;
7582 } | {
7583 /**
7584 * A region one of the plugin's SURFACE MODULES, named by path, draws and
7585 * handles input for on the drawing thread, without `$` (ClientModule).
7586 *
7587 * `Client` from the table. One instance per plugin, drawing and `key`
7588 * lives while the node stays in the tree, and talks to the plugin's
7589 * hooks through `ui.message`. The desktop carries it as data.
7590 */
7591 type: 'Client';
7592 props: ClientProps;
7593 /**
7594 * Whose surface module `props.module` names: the plugin whose hook
7595 * drew the element, stamped by the runtime as the tree leaves it.
7596 */
7597 client: {
7598 plugin: string;
7599 };
7600 children?: undefined;
7601 } | {
7602 /**
7603 * A vector drawing, the remote surfaces' alone: the SVG markup is the
7604 * element's data, drawn in an isolated box, off the page.
7605 *
7606 * A leaf: hooks above wrap or replace it whole, nothing reaches inside;
7607 * a press other plugins should see goes on an enclosing Button. On a
7608 * surface whose table lacks it the tree is refused.
7609 */
7610 type: 'Svg';
7611 props: SvgProps;
7612 children?: undefined;
7613 } | {
7614 /**
7615 * A grid of terminal cells, the terminal surface's alone: each cell a
7616 * glyph, a foreground and a background, packed in `props.cells`.
7617 *
7618 * A leaf, one node however many cells; hooks above wrap or replace it
7619 * whole. A mounted one is repainted in place by its plugin's
7620 * `$.ui.blit`. On a surface whose table lacks it the tree is refused.
7621 */
7622 type: 'Raster';
7623 props: RasterProps;
7624 /**
7625 * Whose Raster: the plugin whose hook drew the element, stamped by the
7626 * runtime as the tree leaves it; the one plugin whose blit reaches it.
7627 */
7628 raster: {
7629 plugin: string;
7630 };
7631 children?: undefined;
7632 } | {
7633 /**
7634 * A picture, the terminal surface's alone: `props.source` drawn over a
7635 * box of cells where the terminal can, `props.alt` where it cannot.
7636 *
7637 * A leaf: hooks above wrap or replace it whole; a press other plugins
7638 * should see goes on an enclosing Button; keyed, its plugin's
7639 * `$.ui.blit` swaps it. On a surface without it the tree is refused.
7640 */
7641 type: 'Image';
7642 props: ImageProps;
7643 /**
7644 * Whose Image: the plugin whose hook drew the element, stamped by the
7645 * runtime as the tree leaves it; the one plugin whose blit reaches it.
7646 */
7647 image: {
7648 plugin: string;
7649 };
7650 children?: undefined;
7651 } | {
7652 /**
7653 * The component core draws itself, with the props held under `ref`.
7654 */
7655 type: 'engine';
7656 /**
7657 * Which drawing: the number core answered from `next(e)`, under which
7658 * it holds the props it received; 0 draws the original props.
7659 */
7660 ref: number;
7661 };
7662
7663 /**
7664 * The render event: `ui.render`, one event for every component that has a
7665 * render site.
7666 */
7667 export type RenderEventName = 'ui.render';
7668
7669 /**
7670 * The input of `ui.render`: a union discriminated by `component`, one member
7671 * per RenderComponent and per RenderSurface.
7672 */
7673 export type RenderInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = C extends RenderComponent ? P extends RenderSurface ? RenderInputOf<C, P> : never : never;
7674
7675 /**
7676 * One `ui.render` input, for a component narrowed to one surface.
7677 */
7678 export type RenderInputOf<C extends RenderComponent, P extends RenderSurface> = {
7679 /**
7680 * Where the tree will be drawn; one literal per member, so
7681 * `if (e.surface === "terminal")` narrows `e` and `$.ui.resolve(e)`.
7682 *
7683 * Over the wire it is what the client declared, a rendering fact and not a
7684 * trust signal: do not key policy on it.
7685 */
7686 surface: P;
7687 /**
7688 * Which component this instance is; the key a matcher narrows on.
7689 */
7690 component: C;
7691 /**
7692 * The instance: the tool_use_id for a dialog or tool row, the message id
7693 * for a message, the agent id for a spinner.
7694 *
7695 * Two drawings of one component are two instances.
7696 */
7697 requestId: string;
7698 /**
7699 * The size of what the surface draws into, in character cells, and whether
7700 * its layout docks a pane; absent where no surface has measured.
7701 *
7702 * Part of the envelope: a rewrite keeps it. On the terminal, the interactive
7703 * screen's, where a change of width re-draws every hooked site once the
7704 * resize settles; on a remote surface, what it reported.
7705 */
7706 viewport?: RenderViewport;
7707 /**
7708 * The component's plain-data props.
7709 */
7710 props: RenderPropsOf[C];
7711 };
7712
7713 /**
7714 * A node of a render tree: an element, or a string (text).
7715 */
7716 export type RenderNode = RenderElement | string;
7717
7718 /**
7719 * The plain-data props of each renderable component, as `ui.render` sees
7720 * them under `e.props`; a hook rewrites them with `next({ ...e, props })`.
7721 *
7722 * A rewrite is validated by the component and an invalid one draws the
7723 * original. This table is the plugin-facing render contract; the author's
7724 * file notes which surfaces raise each member (RENDER_SURFACES_OF).
7725 */
7726 export type RenderPropsOf = {
7727 /**
7728 * The dialog the AskUserQuestion tool opens.
7729 *
7730 * Raised on every surface.
7731 */
7732 AskUserQuestion: {
7733 /**
7734 * The name of the tool whose call opened the dialog (`AskUserQuestion`).
7735 */
7736 tool: string;
7737 /**
7738 * The tool's `questions` input, as the dialog will draw them; a rewrite
7739 * must still fit the tool's schema or the original is drawn.
7740 */
7741 questions: unknown[];
7742 /**
7743 * The call's `metadata.source` (who asked) when the model gave one.
7744 * Analytics only; never drawn.
7745 */
7746 metadataSource?: string;
7747 };
7748 /**
7749 * A user-role transcript row: the person's prompt (`> ...`), a background
7750 * task's notification, or a message another agent, teammate or session sent.
7751 *
7752 * `origin`, `task` and `from` tell them apart and are read-only; a rewrite
7753 * of `text` draws in the row alone: the stored message, and the model's
7754 * framing of another party's words as that party's, stay as they were.
7755 *
7756 * Raised on every surface.
7757 */
7758 UserMessage: {
7759 /**
7760 * What the row shows: the prompt as typed, a notification's summary, or
7761 * a message's body less the engine's framing (summary line included).
7762 *
7763 * A rewrite is printable, bounded text and draws where the engine draws
7764 * the body; a teammate block of several frames or with a summary line
7765 * keeps the engine's drawing, one string not being those parts.
7766 */
7767 text: string;
7768 /**
7769 * Where the stored message came from, as `prompt.submit` named it: the
7770 * composer's, a task notification's, a peer's, a channel's, a plugin's.
7771 *
7772 * `unclassified` for a teammate's (its drain stamps none) and for a
7773 * message stored before stamps. Read-only.
7774 */
7775 origin: PromptOrigin;
7776 /**
7777 * Whether the view draws the row in full: the ctrl+o transcript,
7778 * `--verbose`, a surface with no ctrl+o (an export). Read-only.
7779 *
7780 * False, a message row is one dim line naming its sender; a hook that
7781 * draws a compact row of its own passes when true, so ctrl+o shows all.
7782 */
7783 isExpanded: boolean;
7784 /**
7785 * What a notification row (`origin.kind` `task-notification`) reports
7786 * on: its background task; absent on every other row. Read-only.
7787 */
7788 task?: UserMessageTask;
7789 /**
7790 * Who sent the message the row carries: another agent of this session, a
7791 * teammate, another session, a channel; absent otherwise. Read-only.
7792 */
7793 from?: UserMessageFrom;
7794 /**
7795 * Which of its rows the transcript's viewport shows now: `null` while
7796 * drawn outside it, absent where the surface does not say. Read-only.
7797 *
7798 * Reported once drawn and again when it changes: on a scroll, for the
7799 * messages at the viewport's edges only. A rewrite carries it on as
7800 * received; one that changes or drops it is refused.
7801 */
7802 onScreen?: OnScreen | null;
7803 };
7804 /**
7805 * One text block of an assistant reply in the transcript; a rewrite
7806 * changes the drawing and leaves the stored message alone (ctrl+o).
7807 *
7808 * Raised on every surface.
7809 */
7810 AssistantMessage: {
7811 /**
7812 * The block's text, markdown, as the transcript will draw it.
7813 */
7814 text: string;
7815 /**
7816 * True on the block that draws the bullet opening a reply.
7817 */
7818 isFirstOfReply: boolean;
7819 /**
7820 * Which of its rows the transcript's viewport shows now: `null` while
7821 * drawn outside it, absent where the surface does not say. Read-only.
7822 *
7823 * Reported once drawn and again when it changes: on a scroll, for the
7824 * messages at the viewport's edges only. A rewrite carries it on as
7825 * received; one that changes or drops it is refused.
7826 */
7827 onScreen?: OnScreen | null;
7828 };
7829 /**
7830 * A tool call's row in the transcript (`Bash(ls -la)` and its result); the
7831 * call was decided by `tool.call`, so a rewrite here changes the row alone.
7832 *
7833 * Raised on every surface.
7834 */
7835 ToolUse: {
7836 /**
7837 * The id `tool.call` carried for this call (`e.tool_use_id` there); the
7838 * same value as the row's `requestId`, where it is looked for. Read-only.
7839 */
7840 tool_use_id: string;
7841 /**
7842 * Which one the row draws (`Bash`, `Read`, a plugin's tool), as
7843 * `tool.call` named it.
7844 */
7845 tool: string;
7846 /**
7847 * The call's input, as the model sent it.
7848 */
7849 input: unknown;
7850 /**
7851 * True while the call is still running.
7852 */
7853 isRunning: boolean;
7854 /**
7855 * True when the call ended in an error (a refusal at the dialog is one).
7856 */
7857 isErrored: boolean;
7858 /**
7859 * True when an abort ended the call: the user's Esc or a plugin's
7860 * `$.turn.abort` cut it while it ran, or dropped it before it ran.
7861 *
7862 * The row draws `Interrupted` for it, as the transcript marker does.
7863 */
7864 isInterrupted: boolean;
7865 /**
7866 * The stored result once the call has resolved (`{ stdout, stderr, ... }`
7867 * for Bash: `BuiltinToolResults[tool]`); undefined while it runs.
7868 *
7869 * For a call that errored, was refused or an abort cut, it is the text
7870 * the model read (an `isInterrupted` call: the abort's own). An expanded
7871 * group's rows draw it inline; a standalone row's is its own `ToolResult`.
7872 */
7873 output?: unknown;
7874 /**
7875 * Which of its rows the transcript's viewport shows now: `null` while
7876 * drawn outside it, absent where the surface does not say. Read-only.
7877 *
7878 * Reported once drawn and again when it changes: on a scroll, for the
7879 * messages at the viewport's edges only. A rewrite carries it on as
7880 * received; one that changes or drops it is refused.
7881 */
7882 onScreen?: OnScreen | null;
7883 };
7884 /**
7885 * The result block drawn under a standalone tool row in the transcript,
7886 * which the tool's own result renderer draws from `output`.
7887 *
7888 * A rewrite of `output` is checked against the tool's output schema (one
7889 * that does not fit draws nothing; one the renderer cannot read hits the
7890 * row's error boundary). The stored result is untouched.
7891 *
7892 * Raised on every surface.
7893 */
7894 ToolResult: {
7895 /**
7896 * The id `tool.call` carried for the call this result belongs to
7897 * (`e.tool_use_id` there); the same value as `requestId`. Read-only.
7898 */
7899 tool_use_id: string;
7900 /**
7901 * Which one the result belongs to (`Bash`, `Read`, a plugin's tool).
7902 * Read-only.
7903 */
7904 tool: string;
7905 /**
7906 * The tool's own result object (`{ stdout, stderr, interrupted, ... }` for
7907 * Bash), the same one `ToolUse.output` carries; a rewrite is drawn.
7908 *
7909 * A built-in tool's is `BuiltinToolResults[tool]`, the record
7910 * `tool.call` resolved as `result`.
7911 */
7912 output: unknown;
7913 /**
7914 * True when the call ended in an error, which draws the error text and not
7915 * `output`. Read-only.
7916 */
7917 isErrored: boolean;
7918 /**
7919 * Which of its rows the transcript's viewport shows now: `null` while
7920 * drawn outside it, absent where the surface does not say. Read-only.
7921 *
7922 * Reported once drawn and again when it changes: on a scroll, for the
7923 * messages at the viewport's edges only. A rewrite carries it on as
7924 * received; one that changes or drops it is refused.
7925 */
7926 onScreen?: OnScreen | null;
7927 };
7928 /**
7929 * A run of tool calls the transcript folds into one count line (`Read 3
7930 * files, ran 2 shell commands`): reads, searches, listings.
7931 *
7932 * A hook that sets `isExpanded` unfolds the group where it is, and each row
7933 * it unfolds into is a `ToolUse` drawing a `ToolUse` hook then sees.
7934 *
7935 * Raised on every surface.
7936 */
7937 ToolGroup: {
7938 /**
7939 * In the order the model made them.
7940 */
7941 calls: ReadonlyArray<ToolGroupCall>;
7942 /**
7943 * True while the group is the live one: a call in it may still be
7944 * running and the model's next call may join it.
7945 */
7946 isActive: boolean;
7947 /**
7948 * Whether each call draws as its own `ToolUse` row (true under
7949 * `--verbose` and in the ctrl+o transcript) or the group draws one line.
7950 *
7951 * The one prop of the three a rewrite changes on the screen.
7952 */
7953 isExpanded: boolean;
7954 /**
7955 * Which of its rows the transcript's viewport shows now: `null` while
7956 * drawn outside it, absent where the surface does not say. Read-only.
7957 *
7958 * Reported once drawn and again when it changes: on a scroll, for the
7959 * messages at the viewport's edges only. A rewrite carries it on as
7960 * received; one that changes or drops it is refused.
7961 */
7962 onScreen?: OnScreen | null;
7963 };
7964 /**
7965 * The output row a slash command printed in the transcript, under its echo
7966 * (`/cost`'s lines, the `text` a `command.run` hook answered).
7967 *
7968 * What the run resolved as text, a `local` command's or a plugin's alike. A
7969 * rewrite of `text` draws there and the stored row keeps what the model
7970 * reads; a hook's own tree draws in the row's place, the transcript's width.
7971 *
7972 * Raised on every surface.
7973 */
7974 CommandOutput: {
7975 /**
7976 * Which one printed the row, as `command.run` named it (no slash); a
7977 * hook on its own command matches by it.
7978 *
7979 * Read-only: a rewrite carries it on as received; one that changes or
7980 * drops it is refused and the engine draws its own row.
7981 */
7982 command: string;
7983 /**
7984 * The arguments the run had, as the echo above the row shows them
7985 * (`***` for a command that marks its arguments sensitive). Read-only.
7986 */
7987 args: string;
7988 /**
7989 * The row's text: what the command printed, or the `text` a hook
7990 * answered under its plugin's name; markdown, as the row draws it.
7991 */
7992 text: string;
7993 /**
7994 * True when the row is the run's error line (a command that threw),
7995 * which draws in the error colour and not dim. Read-only.
7996 */
7997 isErrored: boolean;
7998 /**
7999 * Which of its rows the transcript's viewport shows now: `null` while
8000 * drawn outside it, absent where the surface does not say. Read-only.
8001 *
8002 * Reported once drawn and again when it changes: on a scroll, for the
8003 * messages at the viewport's edges only. A rewrite carries it on as
8004 * received; one that changes or drops it is refused.
8005 */
8006 onScreen?: OnScreen | null;
8007 };
8008 /**
8009 * One row of the live tool-progress region under a running tool call; today
8010 * the run-in-background pill. One instance per row.
8011 *
8012 * A union on `kind`: other progress kinds join as their props become plain
8013 * data, each with its own fields, so a hook matches `{ props: { kind:
8014 * "background_hint" } }` or branches on `e.props.kind` and stays right.
8015 *
8016 * Raised on the terminal surface only.
8017 */
8018 ToolProgress: {
8019 /**
8020 * The tool call the row belongs to, as `tool.call` and the `ToolUse` row
8021 * carry it. Read-only: a rewrite carries it on as received.
8022 *
8023 * While several foreground calls share one pill, the first of them.
8024 */
8025 tool_use_id: string;
8026 /**
8027 * Which progress row: the run-in-background pill. Read-only.
8028 */
8029 kind: 'background_hint';
8030 /**
8031 * The pill's text as the engine draws it, dim, under the tool call:
8032 * `(ctrl+b to run in background)`, or with the person's own binding.
8033 *
8034 * A rewrite is drawn in its place, dim; `""` draws nothing. A hook that
8035 * returns a tree draws that instead.
8036 */
8037 hint: string;
8038 };
8039 /**
8040 * The line that animates while a turn runs (`Sauteing... (12s, 300
8041 * tokens)`); a remote surface draws its own.
8042 *
8043 * The row reads `word` (or `message` while one overrides it), then
8044 * `suffix`, then the dim parenthetical the engine keeps (elapsed time,
8045 * tokens, effort); a hook rewrites the first three or draws its own tree.
8046 *
8047 * Raised on the terminal surface only.
8048 */
8049 Spinner: {
8050 /**
8051 * Animated by the line (`Sauteing`), as sampled for this turn.
8052 */
8053 word: string;
8054 /**
8055 * The text drawn instead of the word while a state overrides it, else null.
8056 */
8057 message: string | null;
8058 /**
8059 * What the engine draws right after the word or message to say the turn is
8060 * still going: one ellipsis character.
8061 *
8062 * Left off a text that already ends in an ellipsis, so a rewritten
8063 * `message` ending in one shows one. A rewrite is drawn as given (`""`
8064 * draws the text bare, `" ~"` draws `Sauteing ~`); left out, the engine's.
8065 */
8066 suffix: string;
8067 /**
8068 * What the turn is doing.
8069 */
8070 mode: 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use';
8071 };
8072 /**
8073 * The line that closes a turn in the transcript (`Baked for 3s`); a
8074 * remote surface draws its own footer.
8075 *
8076 * Raised on the terminal surface only.
8077 */
8078 TurnDuration: {
8079 /**
8080 * The past-tense word the line drew (`Baked`), as sampled for this line.
8081 */
8082 word: string;
8083 /**
8084 * The turn's duration in milliseconds, as the line formats it (`3s`,
8085 * `1m 4s`).
8086 */
8087 durationMs: number;
8088 /**
8089 * Which of its rows the transcript's viewport shows now: `null` while
8090 * drawn outside it, absent where the surface does not say. Read-only.
8091 *
8092 * Reported once drawn and again when it changes: on a scroll, for the
8093 * messages at the viewport's edges only. A rewrite carries it on as
8094 * received; one that changes or drops it is refused.
8095 */
8096 onScreen?: OnScreen | null;
8097 };
8098 /**
8099 * One dim status line under the logo (the model source, an experiment
8100 * enrollment, a settings hint), with a trailing `/command`.
8101 *
8102 * Raised on the terminal surface only.
8103 */
8104 InfoNotice: {
8105 /**
8106 * The notice's text, flattened to one string.
8107 */
8108 text: string;
8109 /**
8110 * The slash command appended after the text, or null when the notice has
8111 * none.
8112 */
8113 command: string | null;
8114 /**
8115 * Which of its rows the transcript's viewport shows now: `null` while
8116 * drawn outside it, absent where the surface does not say. Read-only.
8117 *
8118 * Reported once drawn and again when it changes: on a scroll, for the
8119 * messages at the viewport's edges only. A rewrite carries it on as
8120 * received; one that changes or drops it is refused.
8121 */
8122 onScreen?: OnScreen | null;
8123 };
8124 /**
8125 * The dim mode labels at the right of the prompt footer (`focus`, `memory
8126 * paused`), joined by ` & `. One instance.
8127 *
8128 * A hook adds a mode by rewriting `modes`, removes one by filtering, or
8129 * draws its own tree.
8130 *
8131 * Raised on the terminal and desktop surfaces only.
8132 */
8133 SessionMode: {
8134 /**
8135 * The labels the footer shows, in order; empty when there are none.
8136 */
8137 modes: readonly string[];
8138 };
8139 /**
8140 * The dim hint line under the prompt (`? for shortcuts`, `esc to
8141 * interrupt`, the pills beside them). One instance.
8142 *
8143 * A hook rewrites `hint` and the rewrite is drawn in the line's place, or
8144 * draws its own tree; `isDraft` and `isWorking` say what the line is for.
8145 *
8146 * Raised on the terminal surface only.
8147 */
8148 PromptHint: {
8149 /**
8150 * True while the prompt holds typed text. Read-only.
8151 */
8152 isDraft: boolean;
8153 /**
8154 * True while a model turn is running. Read-only.
8155 */
8156 isWorking: boolean;
8157 /**
8158 * The line's text as the engine draws it; one string, so a rewrite
8159 * replaces the line.
8160 *
8161 * Read from the drawn line the way the screen reader reads it, one space
8162 * between parts.
8163 */
8164 hint: string;
8165 };
8166 /**
8167 * The band directly above the prompt input, where the surveys draw; the
8168 * engine draws nothing of its own here.
8169 *
8170 * A hook draws a tree, or passes; one instance. The person collapses it
8171 * (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab): an Input
8172 * types, a Button arms the hotkeys, a tree taller than it scrolls.
8173 *
8174 * Raised on the terminal surface only.
8175 */
8176 AbovePrompt: {
8177 /**
8178 * True while a survey holds the band; a hook yields to it. Read-only.
8179 */
8180 hasSurvey: boolean;
8181 /**
8182 * True while a model turn is running. Read-only.
8183 */
8184 isWorking: boolean;
8185 /**
8186 * Rows the band may take: in fullscreen, what the bottom slot has left
8187 * above the prompt; otherwise the terminal's height. Read-only.
8188 *
8189 * That slot is capped at half the terminal's rows, the prompt's included.
8190 * A tree of at most `maxRows` rows shows whole; a taller one scrolls in a
8191 * window of `scroll.bodyRows`, and a bare digit arms no Button's hotkey.
8192 */
8193 maxRows: number;
8194 /**
8195 * Cells across the band: the terminal's width, or the transcript
8196 * column's while a `Pane` is docked beside it. Read-only.
8197 *
8198 * A tree wider than this wraps or truncates as its Text props say; size
8199 * a table or a rule to it rather than to `viewport.columns`.
8200 */
8201 bodyColumns: number;
8202 /**
8203 * The band's window over a tree taller than `maxRows`: engine-owned,
8204 * moved by the wheel, and by the person's keys while the band is focused.
8205 *
8206 * `bodyRows` is `maxRows` less the `n more` row. Read-only.
8207 */
8208 scroll: SiteScroll;
8209 /**
8210 * Which transcript is on screen above the band: the main conversation's
8211 * (no `agentId`) or one agent's, opened from the tasks list.
8212 *
8213 * The same band under either; a switch re-runs the hook with the new
8214 * view. Read-only: a rewrite carries it on as received; one that changes
8215 * or drops it is refused, the hook that passed it failing.
8216 */
8217 view: SiteView;
8218 };
8219 /**
8220 * The framed region a plugin opened with `$.ui.open({ id })`: one instance
8221 * per id (`requestId`), its body the hook's tree, one shown, the rest tabs.
8222 *
8223 * Placed by the surface (docked in fullscreen, else above the prompt) and
8224 * keyed by the person (ctrl+x tab, Esc), who closes it from the engine's mark
8225 * or ctrl+x x: `ui.close` with origin `person`, which a hook may refuse.
8226 *
8227 * Raised on every surface.
8228 */
8229 Pane: {
8230 /**
8231 * Its tab's label while more than one pane is open (with one, the engine
8232 * draws no title): the `title` it was opened with, or its id.
8233 *
8234 * A click on a tab, or Tab onto it and Enter, shows that pane. Read-only
8235 * here; another `$.ui.open` (or a hook on `ui.open`) retitles.
8236 */
8237 title: string;
8238 /**
8239 * True while the person has given the pane the keyboard: Tab walks its
8240 * elements, a Button's `hotkey` presses it, the arrows scroll. Read-only.
8241 */
8242 isFocused: boolean;
8243 /**
8244 * Cells across the body, inside the frame. Read-only.
8245 */
8246 bodyColumns: number;
8247 /**
8248 * Where the surface seated the pane: `dock` beside the transcript (the
8249 * terminal in fullscreen from 110 columns), or `inline` above the prompt.
8250 *
8251 * Read-only: a rewrite carries it on as received; one that changes or
8252 * drops it is refused, the hook that passed it failing.
8253 */
8254 placement: 'dock' | 'inline';
8255 /**
8256 * The body's window over the tree: engine-owned, moved by the person's
8257 * keys while the pane is focused. Read-only.
8258 */
8259 scroll: SiteScroll;
8260 /**
8261 * Which transcript is on screen beside the pane: the main conversation's
8262 * (no `agentId`) or one agent's, opened from the tasks list.
8263 *
8264 * The pane stays open across a switch, one instance re-rendered for the
8265 * view, so a hook draws for the agent in view. Read-only: a rewrite carries
8266 * it on as received; one that changes or drops it is refused.
8267 */
8268 view: SiteView;
8269 };
8270 };
8271
8272 /**
8273 * What a `ui.render` hook returns and what `next(e)` resolves to: a
8274 * RenderElement tree, the same for every component.
8275 */
8276 export type RenderResultOf = {
8277 [C in RenderComponent]: RenderElement;
8278 };
8279
8280 /**
8281 * Where a render event's component is drawn: `terminal` is Ink, which draws
8282 * the hook's whole tree; the rest are remote surfaces drawing it themselves.
8283 *
8284 * `desktop` is Claude Code Desktop, `mobile` the Claude mobile app, `vscode`
8285 * Claude Code for VS Code. A remote surface asks over the wire (ui_render),
8286 * draws with the props the hook handed core, and draws the tree where it has
8287 * a slot for it.
8288 *
8289 * Each surface's ask is its own evaluation, since a tree may hold an element
8290 * only some surfaces draw (Svg, Client).
8291 */
8292 export type RenderSurface = 'terminal' | 'desktop' | 'mobile' | 'vscode';
8293
8294 /**
8295 * The size of what a surface draws into, in character cells of the
8296 * surface's monospace metric, and whether its layout docks a pane.
8297 *
8298 * On the terminal, the conversation's columns and screen rows; on a remote
8299 * surface, the pane's width and height over the advance and line height of
8300 * its code font. Cell-based until the first element lays out in pixels.
8301 */
8302 export type RenderViewport = {
8303 /**
8304 * Cells across. A tree wider than this wraps or truncates, as its Text
8305 * props say.
8306 */
8307 columns: number;
8308 /**
8309 * Cells down the whole surface, not the room left for this component.
8310 *
8311 * Informational: a change of height alone re-draws nothing and keys no
8312 * new evaluation, so a hook reads it as of the last width or props change.
8313 */
8314 rows: number;
8315 /**
8316 * Whether this surface docks a pane beside the transcript, so a pane a
8317 * plugin opens unasked is a sidebar, not a takeover; absent is unknown.
8318 *
8319 * What `command.run`'s `presentation.isFullscreen` says. The terminal always
8320 * says: `true` fullscreen, `false` on the main screen, fixed per session; a
8321 * remote surface once its client reports it with the size, absent before.
8322 *
8323 * @remarks The desktop and VS Code report it once they place panes; the
8324 * mobile app, which has no dock, `false`. A change re-draws the sites.
8325 * @example if (e.viewport?.isFullscreen === true) void $.ui.open({ id })
8326 */
8327 isFullscreen?: boolean;
8328 };
8329
8330 /**
8331 * The input of `ui.resolve`: which surface's elements, for which component;
8332 * a union with one member per surface (ResolveInputOf).
8333 *
8334 * Resolved when the plugins load, ahead of any drawing, so it names the
8335 * surface and the component and not the props; a `ui.render` argument is
8336 * one (it carries both), which is what `$.ui.resolve(e)` takes.
8337 */
8338 export type ResolveInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = P extends RenderSurface ? ResolveInputOf<C, P> : never;
8339
8340 /**
8341 * One `ui.resolve` input, for a component on one surface.
8342 */
8343 export type ResolveInputOf<C extends RenderComponent, P extends RenderSurface> = {
8344 /**
8345 * Where the table draws; one literal per member, so a hook that narrows
8346 * it narrows the table `next(e)` resolves to.
8347 */
8348 surface: P;
8349 /**
8350 * Which drawing the table is resolved for; the key a matcher narrows on.
8351 */
8352 component: C;
8353 };
8354
8355 /**
8356 * What each event's hook returns, and what its `next(e)` resolves to, by event
8357 * name.
8358 */
8359 export type ResultOf = EngineResultOf & ClassicResultOf & {
8360 [N in OpEventName]: OpEventResult<N>;
8361 } & {
8362 [N in NounEventName]: NounEventResult<N>;
8363 };
8364
8365 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';
8366
8367 /**
8368 * The members of `T` assignable to `S`; all of `T` when none is.
8369 */
8370 type Select<T, S> = [Extract<T, S>] extends [never] ? T : Extract<T, S>;
8371
8372 /**
8373 * The events a pattern selects, as a union of names: the one named, every
8374 * one under a glob's namespace, or every one a negation does not exclude.
8375 */
8376 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>;
8377
8378 /**
8379 * The literal each tag key of `I` is held to by matcher `M`: one-of arrays
8380 * flattened, RegExps widened to `unknown`.
8381 */
8382 type Selection<I, M> = {
8383 [K in keyof M & TagKeys<I>]: Literal<M[K] extends readonly (infer One)[] ? One : M[K]>;
8384 };
8385
8386 /**
8387 * One option of a `Select`: the value `onSelect` and `ui.select` carry, and
8388 * the text drawn for it (the value when absent).
8389 */
8390 export type SelectOption = {
8391 value: string;
8392 label?: string;
8393 };
8394
8395 /**
8396 * The props of `Select`, every surface's one-of-several picker: an address,
8397 * a label, the options, the one selected, the closure a pick runs. A leaf.
8398 *
8399 * Focused through the same ring as `Button` (`abovePrompt:focus`); keys reach
8400 * it only while it has focus (arrows move, Enter picks) and Esc always
8401 * returns to the prompt; a pick raises `ui.select`, its bottom `onSelect`.
8402 */
8403 export type SelectProps = {
8404 /**
8405 * The element's address: `e.element` at `ui.select`, what a matcher names.
8406 */
8407 key: string;
8408 /**
8409 * Text drawn before the current value.
8410 */
8411 label?: string;
8412 /**
8413 * What can be picked, in the order drawn; at least one, values unique.
8414 */
8415 options: readonly SelectOption[];
8416 /**
8417 * Which option is selected when drawn; the person's pick replaces it
8418 * until the hook draws another.
8419 */
8420 value?: string;
8421 /**
8422 * The site's focus ring starts here when the site takes the keyboard,
8423 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
8424 *
8425 * A pane opened with `focus`, or the person's focus chord or click, is the
8426 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
8427 * origin this plugin. A ring the person has moved stays where it was put.
8428 */
8429 autoFocus?: true;
8430 /**
8431 * Runs on a pick with the option's value, in the plugin's own environment:
8432 * the bottom of a `ui.select` chain. No model turn unless it asks one.
8433 */
8434 onSelect: (value: string, e: UiSelectArgument) => void;
8435 };
8436
8437 /**
8438 * Which door a row came in by, decided from the row alone; a closed set,
8439 * pinned on the event and the key a matcher narrows on.
8440 */
8441 export type SessionAppendDoor = 'prompt' | 'command' | 'response' | 'tool-result' | 'tool-message' | 'delivery' | 'attachment' | 'hook-context' | 'note' | 'compaction' | 'notice';
8442
8443 /**
8444 * The input of `session.append`: one row a conversation of this session is
8445 * about to keep, raised once per row, before it is stored or sent again.
8446 *
8447 * Not on `e`, so stored as made: a tool result's structured record, the row's
8448 * timestamps, parent links and provenance stamps, an attachment's payload
8449 * (the model reads its recorded rendering, which `content` rewrites).
8450 */
8451 export type SessionAppendInput = {
8452 /**
8453 * The row as it will be kept (SessionAppendMessage). Its `content` is a
8454 * hook's to rewrite; the engine puts back what it pins.
8455 */
8456 message: SessionAppendMessage;
8457 /**
8458 * Which door the row came in by (SessionAppendDoor); the key a matcher
8459 * narrows on. Pinned.
8460 */
8461 door: SessionAppendDoor;
8462 /**
8463 * Who caused the row (SessionAppendOrigin): the person, the model, a tool,
8464 * the engine, a settings hook, a plugin. Pinned.
8465 */
8466 origin: SessionAppendOrigin;
8467 /**
8468 * The row's id, the same in the transcript file and on every later read,
8469 * so a hook can keep a table by row before calling `next`. Pinned.
8470 */
8471 uuid: string;
8472 /**
8473 * The loop whose conversation keeps the row: a subagent's id, as `turn.step`
8474 * and `tool.call` carry it; absent on main.
8475 *
8476 * Pinned: a different value is refused, one left out is kept.
8477 */
8478 agentId?: string;
8479 };
8480
8481 /**
8482 * One row of a conversation as `session.append` hands it: how the transcript
8483 * files it, under which role a request carries it, and its blocks.
8484 *
8485 * `{ role, content }` of a row a request carries reads as a message in
8486 * Messages API form.
8487 */
8488 export type SessionAppendMessage = {
8489 /**
8490 * How the transcript files the row: `user`, `assistant`, `attachment` (what
8491 * the engine injects beside the conversation), `system` (a notice). Pinned.
8492 */
8493 type: 'user' | 'assistant' | 'attachment' | 'system';
8494 /**
8495 * An attachment's type (`queued_command`, `nested_memory`, ...) or a
8496 * notice's subtype (`compact_boundary`, `local_command`, ...). Pinned.
8497 *
8498 * Absent on user and assistant rows. Builds add and retire names.
8499 */
8500 name?: string;
8501 /**
8502 * Under which role a request carries the row; absent when none does (a
8503 * notice, a record with no bytes on the wire, a virtual row). Pinned.
8504 */
8505 role?: 'user' | 'assistant';
8506 /**
8507 * True on a user-side row the person does not see as typed (a reminder, a
8508 * nudge, a delivery's text). Pinned.
8509 */
8510 isMeta?: true;
8511 /**
8512 * The row's blocks in order (ApiContentBlock): an attachment's as the
8513 * engine recorded its rendering, a notice's as one text block.
8514 *
8515 * Rewritable: text blocks, a tool_result's `content` and `is_error`, image
8516 * and document blocks. Thinking, tool_use and blocks the engine does not
8517 * author are put back, and so is every tool_result's `tool_use_id`.
8518 */
8519 content: ApiContentBlock[];
8520 };
8521
8522 /**
8523 * Who caused a row, as the engine knows it from the row itself: a submission's
8524 * sender, an injected row's author, the model, or the tool that was called.
8525 */
8526 export type SessionAppendOrigin = PromptOrigin | PromptAttachmentOrigin | {
8527 /**
8528 * A block of the model's response, or the engine's stand-in for one.
8529 */
8530 kind: 'model';
8531 /**
8532 * Whose response it is: the id the response names.
8533 */
8534 model: string;
8535 } | {
8536 /**
8537 * A tool call's result, or a row a tool handed over beside it.
8538 */
8539 kind: 'tool';
8540 /**
8541 * Which one was called, by name; `unknown` when no call of that id is
8542 * found.
8543 */
8544 tool: string;
8545 };
8546
8547 /**
8548 * What a `session.append` hook returns and what `next(e)` resolves to: the
8549 * row as the session stored it, and its id in the transcript.
8550 *
8551 * `next(e)` resolves once the row is kept in its stored form. A hook relays it;
8552 * one that answers without `next` is skipped and the row is kept as raised.
8553 */
8554 export type SessionAppendResult = {
8555 /**
8556 * The row as stored: what arrived at the bottom, the pinned parts put
8557 * back.
8558 */
8559 message: SessionAppendMessage;
8560 /**
8561 * The stored row's id: the same in the transcript file and on every
8562 * later read.
8563 */
8564 uuid: string;
8565 };
8566
8567 /**
8568 * The input of `session.attach`: a surface joined the session's roster of
8569 * attached clients (a phone opened the session; the desktop app connected).
8570 *
8571 * A remote client attaches by saying so (ui_attach) or by its first ask to
8572 * draw; the terminal's attachment is the REPL's binding and raises nothing.
8573 * Every field is the engine's: a hook observes, `next(e)` passes them on.
8574 */
8575 export type SessionAttachInput = {
8576 /**
8577 * Where the client draws: what it declared, a rendering fact.
8578 */
8579 surface: RenderSurface;
8580 /**
8581 * The client's own id, unique in the roster; two phones are two clients on
8582 * one surface. A client that never named itself is `<surface>:default`.
8583 */
8584 clientId: string;
8585 /**
8586 * The size the client draws into, in character cells, and whether its
8587 * layout docks a pane, when it said.
8588 */
8589 viewport?: RenderViewport;
8590 };
8591
8592 /**
8593 * What a `session.attach` hook returns and what `next(e)` resolves to:
8594 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
8595 */
8596 export type SessionAttachResult = {
8597 clientId: string;
8598 };
8599
8600 /**
8601 * What `$.session.authorize()` answers: an opaque handle for the session's
8602 * Anthropic credential and its kind, or null when there is none to hold.
8603 *
8604 * The secret itself stays with the engine; the handle is its plugin-side
8605 * face, spent through `$.http.fetch(url, { auth: handle })`.
8606 */
8607 export type SessionAuthorization = {
8608 handle: string;
8609 kind: 'bearer' | 'api-key';
8610 } | null;
8611
8612 /**
8613 * `session.compact`'s input as a plugin's `$.session.compact(args)` takes
8614 * it: `trigger` (`plugin`), `messages` and `agentId` are the engine's.
8615 */
8616 export type SessionCompactArgs = {
8617 /**
8618 * What the summary should keep or stress, as typed after `/compact`;
8619 * absent, the engine's own compaction prompt alone.
8620 */
8621 instructions?: string;
8622 };
8623
8624 /**
8625 * A compaction that stands: the conversation as it reads afterwards, and
8626 * the token counts the engine recorded when it was the one compacting.
8627 */
8628 export type SessionCompacted = {
8629 /**
8630 * The conversation after the compaction, oldest first: from core, its
8631 * summary and the messages it kept; from a hook, whatever it hands up.
8632 *
8633 * What the transcript becomes (kept, on `precompute`, for the compaction
8634 * that comes). A message with the engine's `handle` stands as the engine
8635 * has it; one without is built from its `role`, `text` and tool blocks.
8636 */
8637 messages: readonly SessionMessage[];
8638 /**
8639 * The conversation's size before, in tokens; absent when core did not
8640 * record it.
8641 */
8642 tokensBefore?: number;
8643 /**
8644 * Its size afterwards, in tokens; absent on `precompute` and when core
8645 * did not record it.
8646 */
8647 tokensAfter?: number;
8648 skip?: undefined;
8649 };
8650
8651 /**
8652 * The input of `session.compact`: one compaction of the conversation, about
8653 * to run; `messages` is the transcript it runs over.
8654 */
8655 export type SessionCompactInput = {
8656 /**
8657 * What is compacting (SessionCompactTrigger); the key a matcher narrows
8658 * on. Pinned: `next(e)` passes it on as received.
8659 */
8660 trigger: SessionCompactTrigger;
8661 /**
8662 * The id of the loop compacting, for a subagent's or a fork's own
8663 * transcript; absent for the main conversation (tool.call's `agentId`).
8664 *
8665 * Pinned: left out of a rewrite it is put back, changed it fails the hook.
8666 * `$.session.messages()` is the main conversation whatever this names.
8667 */
8668 agentId?: string;
8669 /**
8670 * What the summary should keep or stress: the text after `/compact`, a
8671 * plugin's, or absent.
8672 *
8673 * `next({ ...e, instructions })` changes what the summarizer is told.
8674 */
8675 instructions?: string;
8676 /**
8677 * The transcript being compacted, in `$.session.messages()`'s shape, each
8678 * message carrying the engine's `handle`; a subagent's own under `agentId`.
8679 *
8680 * `next({ ...e, messages })` changes what is summarized: a message kept
8681 * with its handle is the engine's own, whole; one without is read as built.
8682 */
8683 messages: readonly SessionMessage[];
8684 };
8685
8686 /**
8687 * What a `session.compact` hook returns and what `next(e)` resolves to: the
8688 * compaction (`{ messages, tokensBefore?, tokensAfter? }`) or `{ skip }`.
8689 *
8690 * There is no summary string: the summary is a message.
8691 */
8692 export type SessionCompactResult = SessionCompacted | SessionCompactSkipped;
8693
8694 /**
8695 * A compaction vetoed: on `precompute` nothing is computed or kept; on any
8696 * other trigger the conversation stays as it is and one line says why.
8697 *
8698 * Core answers it too, when a classic PreCompact hook blocks.
8699 */
8700 export type SessionCompactSkipped = {
8701 /**
8702 * Why, as the notice reads.
8703 */
8704 skip: string;
8705 messages?: undefined;
8706 };
8707
8708 /**
8709 * Who compacts: the person's `/compact` (`manual`), the engine at its
8710 * threshold or on a prompt too long (`auto`), a plugin, or a `precompute`.
8711 *
8712 * `precompute` is the one dispatch that installs nothing: its result is kept
8713 * for the compaction that comes, if the conversation it ran over still leads.
8714 */
8715 export type SessionCompactTrigger = 'manual' | 'auto' | 'plugin' | 'precompute';
8716
8717 /**
8718 * The context window broken down as /context breaks it down: the rows, the
8719 * grid and the lists beneath it, in the SDK's `get_context_usage` shape.
8720 *
8721 * Less that reply's internal-build sections. Token counts are the engine's
8722 * estimates as numbers, never formatted: a `full` breakdown counts with the
8723 * token-count API where it can, a `summary` one estimates throughout.
8724 */
8725 export type SessionContextBreakdown = {
8726 /**
8727 * One row per category, the free space and the compaction buffer among
8728 * them; `kind` says which is which.
8729 */
8730 categories: ContextCategory[];
8731 /**
8732 * Tokens in use, unclamped: past `rawMaxTokens` when over the window.
8733 */
8734 totalTokens: number;
8735 /**
8736 * The window measured against, the same figure as `rawMaxTokens`.
8737 */
8738 maxTokens: number;
8739 /**
8740 * The window measured against, in tokens: the model's limit, or a smaller
8741 * compaction window (`autocompactSource` says which).
8742 */
8743 rawMaxTokens: number;
8744 /**
8745 * How that window was settled (ContextWindowSource); the SDK's reply
8746 * carries it under this name too, outside its typed schema.
8747 */
8748 autocompactSource: ContextWindowSource;
8749 /**
8750 * `totalTokens` over `rawMaxTokens` as a whole percentage, 0 to 100 and
8751 * past it when over.
8752 */
8753 percentage: number;
8754 /**
8755 * The grid, row by row: 10 by 10, 20 by 10 for a window of a million or
8756 * more, 5 wide when asked for under 80 `columns`.
8757 */
8758 gridRows: ContextGridSquare[][];
8759 /**
8760 * Which model the breakdown was computed for, as `/model` shows it.
8761 */
8762 model: string;
8763 /**
8764 * Each memory file in the context, with its path and tokens.
8765 */
8766 memoryFiles: ContextMemoryFile[];
8767 /**
8768 * Each MCP tool's schema, with its server and tokens.
8769 */
8770 mcpTools: ContextMcpTool[];
8771 /**
8772 * The custom agents the Agent tool describes, each with its tokens.
8773 */
8774 agents: ContextAgent[];
8775 /**
8776 * The slash-command listing, counted; absent when the session lists none.
8777 */
8778 slashCommands?: ContextSlashCommands;
8779 /**
8780 * The skill listing, counted, with one entry per skill; absent when the
8781 * session lists none.
8782 */
8783 skills?: ContextSkills;
8784 /**
8785 * The token count at which auto-compaction runs; absent when it is off.
8786 */
8787 autoCompactThreshold?: number;
8788 /**
8789 * Whether auto-compaction is on for the session.
8790 */
8791 isAutoCompactEnabled: boolean;
8792 /**
8793 * The last response's own token counts, or null before one came back.
8794 */
8795 apiUsage: ContextApiUsage | null;
8796 };
8797
8798 /**
8799 * The live context window as the status line reads it, and by category as
8800 * /context breaks it down when the call asked (`{ breakdown }`).
8801 *
8802 * `tokens` and `percent` are the last API response's input side against the
8803 * model's window, absent until the first response of the live window: a
8804 * fresh session, or one just compacted, until its next response.
8805 */
8806 export type SessionContextUsage = {
8807 /**
8808 * Input tokens the last response was answered over: uncached, cache-written
8809 * and cache-read together (the status line's `total_input_tokens`).
8810 */
8811 tokens?: number;
8812 /**
8813 * The context window of the session's model, in tokens (the status line's
8814 * `context_window_size`).
8815 */
8816 window: number;
8817 /**
8818 * `tokens` over `window` as a whole percentage, 0 to 100 (the status
8819 * line's `used_percentage`).
8820 */
8821 percent?: number;
8822 /**
8823 * The window by category, as /context breaks it down: present only when
8824 * the call passed `breakdown`, and only with a session bound.
8825 *
8826 * It measures against the compaction window (`rawMaxTokens`), which may be
8827 * smaller than `window`, and estimates every category, so its
8828 * `totalTokens` need not equal `tokens`.
8829 */
8830 breakdown?: SessionContextBreakdown;
8831 };
8832
8833 /**
8834 * What the session has cost, as `/cost` and the status line total it.
8835 */
8836 export type SessionCost = {
8837 /**
8838 * US dollars, summed over every priced API response this session.
8839 */
8840 usd: number;
8841 };
8842
8843 type SessionCronSummary = {
8844 id: string;
8845 /**
8846 * Cron expression, e.g. "0 9 * * 1-5".
8847 */
8848 schedule: string;
8849 /**
8850 * False for one-shot wakeups whose cron field encodes a single fire time; true for tasks that re-fire on every match.
8851 */
8852 recurring: boolean;
8853 /**
8854 * Prompt text submitted when the cron fires. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
8855 */
8856 prompt: string;
8857 };
8858
8859 /**
8860 * The input of `session.detach`: a client left the session's roster. Every
8861 * field is the engine's: a hook observes, and `next(e)` passes them on.
8862 */
8863 export type SessionDetachInput = {
8864 /**
8865 * Where the client drew.
8866 */
8867 surface: RenderSurface;
8868 /**
8869 * The id it attached under.
8870 */
8871 clientId: string;
8872 /**
8873 * Why it left: it detached, or the session ended under it.
8874 */
8875 reason: SessionDetachReason;
8876 };
8877
8878 /**
8879 * Why a client left the roster: `detach`, it said so (ui_detach); `end`, the
8880 * session ended with it still attached.
8881 */
8882 export type SessionDetachReason = 'detach' | 'end';
8883
8884 /**
8885 * What a `session.detach` hook returns and what `next(e)` resolves to:
8886 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
8887 */
8888 export type SessionDetachResult = {
8889 clientId: string;
8890 };
8891
8892 type SessionEndHookInput = BaseHookInput & {
8893 hook_event_name: 'SessionEnd';
8894 reason: ExitReason;
8895 };
8896
8897 /**
8898 * The input of `session.end`: the session is ending, why, and how to come back
8899 * to it.
8900 *
8901 * Every field is the engine's: a hook observes, and `next(e)` passes them on.
8902 */
8903 export type SessionEndInput = {
8904 /**
8905 * Why it ends (SessionEndReason), the word the classic SessionEnd hook
8906 * receives as its `reason`.
8907 */
8908 reason: SessionEndReason;
8909 /**
8910 * The ending session's id (`$.session.id()` until now); after a `/clear`
8911 * or a resume the process goes on under another.
8912 */
8913 sessionId: string;
8914 /**
8915 * What `claude --resume` takes to return to it.
8916 */
8917 resume: SessionResume;
8918 };
8919
8920 /**
8921 * Why the session ended: the classic SessionEnd hook's own `reason`, word for
8922 * word.
8923 *
8924 * `prompt_input_exit`, the person left (/exit, ctrl+c, ctrl+d); `clear`, a
8925 * /clear started a fresh one; `resume`, another took its place; `logout`;
8926 * `other`, a `-p` run finished or the process got SIGINT, SIGTERM or SIGHUP.
8927 */
8928 export type SessionEndReason = ClassicHookInputs['SessionEnd']['reason'];
8929
8930 /**
8931 * What a `session.end` hook returns and what `next(e)` resolves to:
8932 * `{ sessionId }`, echoed by core; a hook's own value changes nothing.
8933 */
8934 export type SessionEndResult = {
8935 sessionId: string;
8936 };
8937
8938 /**
8939 * The input of `session.measure`: what `$.session.usage()` answers at this
8940 * moment, and which of its units moved since the last measurement a hook saw.
8941 *
8942 * The same figures the op reads, without `context.breakdown`: call
8943 * `$.session.usage({ breakdown })` from the hook when the categories matter.
8944 * Every field is the engine's: a hook observes, and `next(e)` passes them on.
8945 */
8946 export type SessionMeasureInput = {
8947 /**
8948 * The live context window (`$.session.usage()`'s `context`): the window,
8949 * and its fill once a response of the live window reported one.
8950 *
8951 * Never carries `breakdown` here.
8952 */
8953 context: SessionContextUsage;
8954 /**
8955 * The rate-limit windows the last response reported, each with its
8956 * `percentUsed`; empty off a subscription or before the first reading.
8957 */
8958 rateLimits: SessionRateLimit[];
8959 /**
8960 * What the session has cost so far; absent where the host keeps no ledger.
8961 */
8962 cost?: SessionCost;
8963 /**
8964 * Which units differ from the last measurement raised (UsageUnit), never
8965 * empty; the first measurement names every unit it has a figure for.
8966 *
8967 * `context`: the fill moved; `rateLimits`: a window moved a whole point,
8968 * appeared or left, or the account's limit status changed; `cost`: the
8969 * total grew.
8970 */
8971 changed: UsageUnit[];
8972 };
8973
8974 /**
8975 * What a `session.measure` hook returns and what `next(e)` resolves to:
8976 * `{ changed }`, echoed by core; a hook's own value changes nothing.
8977 */
8978 export type SessionMeasureResult = {
8979 changed: UsageUnit[];
8980 };
8981
8982 /**
8983 * One message of the transcript as `$.session.messages()` returns it.
8984 */
8985 export type SessionMessage = {
8986 /**
8987 * Who wrote it.
8988 */
8989 role: 'user' | 'assistant';
8990 /**
8991 * Its text blocks joined; '' when it has none.
8992 */
8993 text: string;
8994 /**
8995 * The tool_use blocks of an assistant message, each with its outcome
8996 * (`result`, `text`, `isError`) once the transcript holds it.
8997 */
8998 toolUses: ToolUseSummary[];
8999 /**
9000 * The tool_result blocks of a user message: `{ tool_use_id, text, isError,
9001 * result }`.
9002 */
9003 toolResults?: ToolResultSummary[];
9004 /**
9005 * An opaque token the engine stamps on a message it hands a
9006 * `session.compact` hook, so a list handed back maps to its own messages.
9007 *
9008 * Absent on `$.session.messages()` and on a message a hook built.
9009 */
9010 handle?: string;
9011 };
9012
9013 /**
9014 * One rate-limit window as the rate-limit notices read it.
9015 */
9016 export type SessionRateLimit = {
9017 /**
9018 * Which window: `five_hour`, `seven_day`, or a Claude gateway's
9019 * `spend_limit`.
9020 */
9021 kind: string;
9022 /**
9023 * How much of the window is used, 0 to 100 with at most one decimal:
9024 * 23.5, or 7, never 7.000000000000001; past 100 on an exceeded spend limit.
9025 */
9026 percentUsed: number;
9027 /**
9028 * When the window resets, as an ISO 8601 timestamp.
9029 */
9030 resetsAt?: string;
9031 };
9032
9033 /**
9034 * An external-event wake the delivery's text parsed as (a GitHub relay
9035 * event, a signal's notice): the envelope's attributes and its JSON body.
9036 */
9037 export type SessionReceiveEvent = {
9038 /**
9039 * The producing service (`github`).
9040 */
9041 source: string;
9042 /**
9043 * The event's discriminator (`pull_request.closed`, `check_suite`).
9044 */
9045 kind: string;
9046 /**
9047 * The envelope's JSON body (`{ pr: "acme/app#12", outcome: "merged" }`).
9048 */
9049 data: Record<string, unknown>;
9050 /**
9051 * The `data` keys whose values are free text a third party wrote (a
9052 * commenter's `author` and `comment`), as the producer marked them.
9053 *
9054 * Empty when none; the server asserts every other key's value, not these.
9055 */
9056 untrustedKeys: readonly string[];
9057 };
9058
9059 /**
9060 * The input of `session.receive`: one inbound delivery (a relay's event, a
9061 * peer's message, a Remote Control prompt), sanitized, before it is queued.
9062 */
9063 export type SessionReceiveInput = {
9064 /**
9065 * Where the delivery came from, as the bridge classified it; the key a
9066 * matcher narrows on. `next(e)` passes it on as received.
9067 */
9068 origin: SessionReceiveOrigin;
9069 /**
9070 * The delivery's body as the model would read it (a content-block
9071 * delivery's text blocks, joined).
9072 */
9073 text: string;
9074 /**
9075 * The external-event wake the text parsed as (`source` `github` for a
9076 * subscribed pull request's event); passed on as received.
9077 *
9078 * Present only for a delivery the server itself rendered as a wake (a
9079 * webhook relay, the session inbox), by its asserted origin; anyone else's
9080 * wake-shaped text stays `text`. Its `untrustedKeys` name third-party text.
9081 */
9082 event?: SessionReceiveEvent;
9083 };
9084
9085 /**
9086 * Where an inbound delivery came from, as the bridge classified it from the
9087 * server's stamps: `prompt.submit`'s `e.origin`, less what never arrives.
9088 */
9089 export type SessionReceiveOrigin = {
9090 /**
9091 * `bridge` the user's own from a Remote Control client; `peer` another
9092 * session; `unclassified` one the bridge could not place.
9093 *
9094 * `task-notification` a relay's event (a GitHub webhook) or a trigger;
9095 * `scheduled-trigger` a routine; `peer-send-message` another session's
9096 * SendMessage; `projects-relay` and `slack-ping` as at `prompt.submit`.
9097 */
9098 kind: 'bridge' | 'task-notification' | 'scheduled-trigger' | 'peer' | 'peer-send-message' | 'projects-relay' | 'slack-ping' | 'unclassified';
9099 };
9100
9101 /**
9102 * What a `session.receive` hook returns and what `next(e)` resolves to: the
9103 * delivery that was queued, `{ text }`, or `{ consumed: reason }`.
9104 *
9105 * `next(e)` resolves once the delivery is queued; a hook answering without
9106 * `next` queues nothing.
9107 */
9108 export type SessionReceiveResult = {
9109 /**
9110 * The body the delivery was queued with; from core, `e.text` as it
9111 * arrived at the bottom.
9112 *
9113 * A rewrite passes it down, `next({ ...e, text })`.
9114 */
9115 text: string;
9116 consumed?: undefined;
9117 } | {
9118 /**
9119 * Takes the delivery, answered without `next`: it is not queued, not
9120 * written to the transcript and never reaches the model.
9121 *
9122 * The reason is logged, the plugin named.
9123 */
9124 consumed: string;
9125 text?: undefined;
9126 };
9127
9128 /**
9129 * What `$.session.repo()` answers: the repository's root and its origin remote,
9130 * when the session is in one.
9131 */
9132 export type SessionRepo = {
9133 /**
9134 * The repository's root, absolute: the main working tree's for a worktree.
9135 */
9136 root: string;
9137 /**
9138 * The `origin` remote's URL as git has it (push URL preferred), or null when
9139 * the repository has none.
9140 */
9141 remote: string | null;
9142 /**
9143 * Whether the remote is one of the repositories this build treats as its
9144 * own; false in a build that has none or when the remote is unrecognized.
9145 *
9146 * The engine matches the build's own list of repositories with its
9147 * hardened remote parser. A plugin reads this to behave differently in a
9148 * public repository; which repositories are the build's is its to say.
9149 */
9150 internal: boolean;
9151 /**
9152 * The repository the allowlist matched, as `owner/name`; null when
9153 * `internal` is false.
9154 *
9155 * A working copy without a remote that the engine still recognises is
9156 * named by its own checkout configuration; a remote's name is its path.
9157 */
9158 name: string | null;
9159 };
9160
9161 /**
9162 * How to come back to the session that ended: what `claude --resume` takes.
9163 */
9164 export type SessionResume = {
9165 /**
9166 * What `claude --resume <id>` takes, the ending session's own.
9167 *
9168 * It resumes a session that wrote a transcript: one that never ran a
9169 * prompt, or ran with persistence off, left nothing under this id.
9170 */
9171 id: string;
9172 };
9173
9174 type SessionStartHookInput = BaseHookInput & {
9175 hook_event_name: 'SessionStart';
9176 source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork';
9177 agent_type?: string;
9178 model?: string;
9179 session_title?: string;
9180 /**
9181 * resume/fork: seconds since the resumed transcript's last assistant response
9182 */
9183 seconds_since_last_response?: number;
9184 /**
9185 * 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)
9186 */
9187 context_tokens?: number;
9188 /**
9189 * resume/fork: seconds_since_last_response exceeds the prompt-cache TTL, so the first request re-caches context_tokens
9190 */
9191 prompt_cache_likely_expired?: boolean;
9192 /**
9193 * resume/fork: estimated cost of re-caching context_tokens on the session model - the managed modelPricing when set, otherwise list price; excludes the response
9194 */
9195 estimated_cache_write_usd?: number;
9196 };
9197
9198 /**
9199 * The input of `session.start`: the session the process starts with, read the
9200 * way `$.session` reads it at that moment.
9201 */
9202 export type SessionStartInput = {
9203 /**
9204 * The directory the session runs in, absolute (`$.session.cwd()`).
9205 */
9206 cwd: string;
9207 /**
9208 * Where the session draws at start (`$.session.surfaces()[0]`): `terminal`
9209 * under the REPL; null for a `-p` run or the SDK, which draw nowhere yet.
9210 */
9211 surface: RenderSurface | null;
9212 /**
9213 * Whether a person is at the prompt: true under the REPL, false for a `-p`
9214 * run or the SDK.
9215 */
9216 isInteractive: boolean;
9217 };
9218
9219 /**
9220 * What a `session.start` hook returns and what `next(e)` resolves to:
9221 * `{ cwd }`, echoed by core; a hook's own value does not change the session.
9222 */
9223 export type SessionStartResult = {
9224 cwd: string;
9225 };
9226
9227 /**
9228 * What `$.session.usage()` answers: the context window's fill, the account's
9229 * rate-limit windows and the session's cost, as the status line has them.
9230 *
9231 * A figure the engine does not have is left out, never zeroed: `rateLimits`
9232 * is empty off a subscription, `cost` absent where the host keeps no ledger.
9233 */
9234 export type SessionUsage = {
9235 /**
9236 * The live context window: the status line's `context_window` figures.
9237 */
9238 context: SessionContextUsage;
9239 /**
9240 * The rate-limit windows the last API response reported (`five_hour`,
9241 * `seven_day`, a gateway's `spend_limit`); empty when none has a reading.
9242 */
9243 rateLimits: SessionRateLimit[];
9244 /**
9245 * What the session has cost so far, as /cost totals it; absent only where
9246 * the host keeps no cost ledger (the CLI always has one).
9247 */
9248 cost?: SessionCost;
9249 };
9250
9251 /**
9252 * What `$.session.usage(args)` takes: nothing for the status line's figures
9253 * alone; `breakdown` to have the window broken down as /context breaks it.
9254 */
9255 export type SessionUsageArgs = {
9256 /**
9257 * Asks for `context.breakdown` and says how it is counted
9258 * (ContextBreakdownDetail); absent, none is computed and the call is free.
9259 *
9260 * `full` sends one token-count request per tool and memory file, as
9261 * /context does; `summary` estimates locally and sends none.
9262 */
9263 breakdown?: ContextBreakdownDetail;
9264 /**
9265 * The width the breakdown's grid will be drawn in, in terminal columns;
9266 * absent, the full-width grid. Read only with `breakdown`.
9267 *
9268 * Under 80 the grid is the narrow one /context draws there, 5 wide. A thin
9269 * client's breakdown is the remote workspace's, whose grid ignores this.
9270 */
9271 columns?: number;
9272 };
9273
9274 /**
9275 * What `$.session.version()` answers: the version of the engine the session
9276 * runs on, the release that version is built from, and when it was built.
9277 *
9278 * The three are what the engine's own analytics rows carry as `version`,
9279 * `version_base` and `build_time`, so a row a plugin sends and a row the
9280 * engine sends from the same binary agree.
9281 */
9282 export type SessionVersion = {
9283 /**
9284 * The engine's full version, as `claude --version` prints it: a release's
9285 * (`2.1.280`) or a development build's, which adds the build's date, time
9286 * and commit (`2.1.280-dev.20260920.t101500.sha1a2b3c4`).
9287 */
9288 version: string;
9289 /**
9290 * The release the version is built from, its semantic core and channel:
9291 * `2.1.280` for that release, `2.1.280-dev` for a development build of it.
9292 * Absent when the version is not spelled as a release.
9293 */
9294 base?: string;
9295 /**
9296 * When the binary was built, an ISO 8601 timestamp
9297 * (`2026-09-20T10:15:00Z`). Absent in a run from source that stamps none.
9298 */
9299 builtAt?: string;
9300 };
9301
9302 /**
9303 * What `$.settings.read` answers: an object keyed as a settings.json is
9304 * (`permissions`, `env`, `hooks`, `model`, `enabledPlugins`, ...).
9305 *
9306 * Each key is as https://code.claude.com/docs/en/settings documents it and
9307 * https://json.schemastore.org/claude-code-settings.json types it. A
9308 * snapshot in plain data: a write to it changes nothing the engine reads.
9309 */
9310 export type Settings = Readonly<Record<string, unknown>>;
9311
9312 /**
9313 * What `$.settings.read(args)` takes.
9314 */
9315 export type SettingsReadArgs = {
9316 /**
9317 * The one source read, as loaded; absent, the settings merged over every
9318 * source, as the engine runs under them.
9319 */
9320 source?: SettingsSource;
9321 };
9322
9323 /**
9324 * One source of settings by the name a plugin gives it, lowest precedence
9325 * first; the engine's own name is the same word with `Settings` appended.
9326 *
9327 * `user` is ~/.claude/settings.json, `project` .claude/settings.json,
9328 * `local` .claude/settings.local.json, `flag` what `--settings` and the
9329 * SDK's inline settings carry, and `policy` the managed settings, every
9330 * managed tier merged.
9331 */
9332 export type SettingsSource = 'user' | 'project' | 'local' | 'flag' | 'policy';
9333
9334 type SetupHookInput = BaseHookInput & {
9335 hook_event_name: 'Setup';
9336 trigger: 'init' | 'maintenance';
9337 };
9338
9339 /**
9340 * Where a site's window sits over the tree a hook drew in it (a pane's body,
9341 * the band): the engine's to move (the person scrolls), the plugin's to read.
9342 */
9343 export type SiteScroll = {
9344 /**
9345 * The first row of the tree the window shows; 0 at the top. Read-only.
9346 */
9347 offset: number;
9348 /**
9349 * How many rows of the tree the window shows at once: the rows the
9350 * surface gave the body. Read-only.
9351 */
9352 bodyRows: number;
9353 };
9354
9355 /**
9356 * Which transcript the person has on screen where a site draws: the main
9357 * conversation's, or one agent's, opened from the tasks list.
9358 *
9359 * The person's to switch, the plugin's to read: a switch re-runs the site's
9360 * hooks with the new view, the site itself staying where it is.
9361 */
9362 export type SiteView = {
9363 /**
9364 * The agent whose transcript is in view: the `id` `$.agent.list()` gives
9365 * it, the `agentId` its `turn.step` and `tool.call` events carry.
9366 *
9367 * Absent while the main conversation is in view. Read-only.
9368 */
9369 agentId?: string;
9370 };
9371
9372 /**
9373 * The input of `skill.prompt`: one skill's prompt, at the moment the engine
9374 * expanded it for the model.
9375 *
9376 * Typed as `/name`, called through the Skill tool, or preloaded into a
9377 * subagent: the same event at each.
9378 */
9379 export type SkillPromptInput = {
9380 /**
9381 * Which skill (`commit`); the key a matcher narrows on.
9382 */
9383 skill: string;
9384 /**
9385 * The prompt's text as the skill computed it (its text blocks, joined).
9386 */
9387 text: string;
9388 };
9389
9390 /**
9391 * What a `skill.prompt` hook returns: the text the model reads for that
9392 * skill.
9393 */
9394 export type SkillPromptResult = {
9395 text: string;
9396 };
9397
9398 /**
9399 * Options of `$.clock.sleep`.
9400 */
9401 export type SleepOptions = {
9402 /**
9403 * Aborting it rejects the sleep at once.
9404 */
9405 signal?: AbortSignal;
9406 };
9407
9408 /**
9409 * Options of `$.audio.speak`.
9410 */
9411 export type SpeakOptions = {
9412 /**
9413 * The system voice's exact name as the platform lists it (`Samantha`, or the
9414 * name of a voice you installed). Absent: the synthesizer's default voice.
9415 */
9416 voice?: string;
9417 };
9418
9419 /**
9420 * The argument of `$.audio.speak(text, options)` as the event carries it.
9421 */
9422 type SpeakRequest = SpeakOptions & {
9423 /**
9424 * What to say, as plain text, of at most 4096 characters.
9425 */
9426 text: string;
9427 };
9428
9429 /**
9430 * What `$.audio.speak` resolves with once the utterance has ended.
9431 */
9432 export type SpeakResult = {
9433 /**
9434 * Which synthesizer spoke: `system`, the platform's own (`say` on macOS).
9435 */
9436 via: 'system';
9437 };
9438
9439 /**
9440 * `next` in a `*` hook: the set of events is open at runtime, so `e` is
9441 * `unknown` until `next.is(pattern, e)` narrows it to events it knows.
9442 *
9443 * The callable is an overload per known event (OrderedOverloads), then
9444 * `(e: unknown) => Promise<unknown>` last: `next(e)` with `e` still unknown
9445 * resolves to `unknown`.
9446 */
9447 export type StarNext = OrderedOverloads<EventName> & {
9448 (e: unknown): Promise<unknown>;
9449 /**
9450 * Continues this dispatch at a tier, as Next's `to` (a managed hook's):
9451 * `e` still unknown resolves to `unknown`.
9452 */
9453 readonly to: (e: unknown, tier: TargetTier) => Promise<unknown>;
9454 readonly signal: AbortSignal;
9455 readonly is: <M extends Pattern>(pattern: M, e: unknown) => e is Frozen<Args<Selected<M>>>;
9456 readonly event: EventName;
9457 readonly origin: Origin;
9458 readonly trace: readonly TraceEntry<EventName, unknown, unknown>[];
9459 readonly budget: NextBudget;
9460 };
9461
9462 type StopFailureHookInput = BaseHookInput & {
9463 hook_event_name: 'StopFailure';
9464 error: SDKAssistantMessageError;
9465 error_details?: string;
9466 last_assistant_message?: string;
9467 };
9468
9469 type StopHookInput = BaseHookInput & {
9470 hook_event_name: 'Stop';
9471 stop_hook_active: boolean;
9472 /**
9473 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
9474 */
9475 last_assistant_message?: string;
9476 /**
9477 * 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.
9478 */
9479 background_tasks?: BackgroundTaskSummary[];
9480 /**
9481 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
9482 */
9483 session_crons?: SessionCronSummary[];
9484 };
9485
9486 /**
9487 * The hook a streaming event takes: `async function* ($, e, next) {}`,
9488 * yielding the event's chunks and returning its result.
9489 *
9490 * `return yield* next(e)` passes; `for await (const c of next(e)) yield
9491 * f(c)` transforms; yielding without `next` answers alone. A chunk yielded
9492 * stays: a hook that fails mid-stream is left, the rest from beneath it.
9493 *
9494 * @example on('turn.step', async function* ($, e, next) {
9495 * const r = yield* next(e); return { ...r } })
9496 */
9497 export type StreamHook<N extends StreamingEventName> = ($: EngineInterface, e: Frozen<Args<N>>, next: StreamNext<N>) => StreamHookBody<Chunk<N>, EventResult<N>>;
9498
9499 /**
9500 * What a hook on a streaming event evaluates to: the async generator an
9501 * `async function*` makes, yielding `C` and returning `R` or nothing.
9502 *
9503 * Returning nothing lets its last `next(e)`'s result stand. A plain
9504 * function is a type error here even when it returns `next(e)`: the hook
9505 * is the generator, not a function that hands one back.
9506 */
9507 export type StreamHookBody<C, R> = AsyncGenerator<C, R | void> & {
9508 /**
9509 * Absent on a generator; present on `next(e)`, which is not a hook body.
9510 */
9511 readonly result?: never;
9512 };
9513
9514 /**
9515 * The events that stream: their hooks are async generators, `next(e)` is
9516 * the stream of everything beneath, and the result is what it returns.
9517 *
9518 * `turn.step` alone: the model's response arrives in pieces, and a hook
9519 * that saw it whole could not change what had already been shown.
9520 */
9521 export type StreamingEventName = 'turn.step';
9522
9523 /**
9524 * The rest of the chain as a hook on a streaming event receives it: Next,
9525 * except that `next(e)` is the stream beneath (HookStream), not a promise.
9526 *
9527 * Each call opens a fresh stream; for `turn.step` each is a model request,
9528 * so a hook that calls it twice makes two. Not calling it yields the hook's
9529 * own chunks and returns its own result, and nothing beneath runs.
9530 *
9531 * @template S what `next.is(pattern, e)` narrows `e` to, as Next's
9532 * @see HookBudget `ms`: the hook's budget counts its own code, never a wait
9533 * at a `yield` or on this stream, however long the response beneath takes
9534 */
9535 export type StreamNext<N extends StreamingEventName = StreamingEventName, E = Args<N>, O = NextResult<N>, S extends {
9536 [K in N]?: unknown;
9537 } = {
9538 [K in N]: Args<K>;
9539 }> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin' | 'budget'> & {
9540 (e: E): HookStream<Chunk<N>, O>;
9541 /**
9542 * Continues this dispatch at a tier, as Next's `to`: the stream beneath
9543 * with the links between this hook's tier and that one skipped.
9544 */
9545 readonly to: (e: E, tier: TargetTier) => HookStream<Chunk<N>, O>;
9546 /**
9547 * What settled beneath on the latest `next()` stream, as Next's; a
9548 * streaming link's entry counts the chunks it yielded up (`chunks`).
9549 */
9550 readonly trace: readonly TraceEntry<N, E, O>[];
9551 };
9552
9553 /**
9554 * The shape a `Box` and a `Text` share in a render tree: allowlisted props,
9555 * an optional `hover`, the group stamp a `hover.scope` earns, and children.
9556 *
9557 * `Tag` is which of the two; `Hover` is that element's hover props. Every
9558 * surface draws both: Ink's Box and Text on the terminal, a flex div and a
9559 * styled span on the desktop.
9560 */
9561 type StyledElement<Tag extends 'Box' | 'Text', Hover> = {
9562 type: Tag;
9563 /**
9564 * A Box's layout, position, spacing and border props and the `key` that
9565 * makes it a hover scope; a Text's colors and styles. Others are refused.
9566 */
9567 props?: Record<string, string | number | boolean>;
9568 /**
9569 * Style overrides the surface applies while the pointer is over the
9570 * nearest keyed Box, or over any member of the group `scope` names.
9571 *
9572 * Plain data, no hook. Nothing that moves a sibling: `borderStyle`
9573 * restyles a border the Box has, `display` only reveals a Box drawn
9574 * `"none"` (under a keyed Box or in a scope), an offset moves a placed Box.
9575 */
9576 hover?: Hover;
9577 /**
9578 * Whose group `hover.scope` names; absent without a `scope`.
9579 */
9580 group?: PluginStamp;
9581 /**
9582 * In order: a Box holds elements and strings (core wraps each string in
9583 * a Text); a Text holds strings and inline elements, never an engine node.
9584 */
9585 children?: RenderNode[];
9586 };
9587
9588 type SubagentStartHookInput = BaseHookInput & {
9589 hook_event_name: 'SubagentStart';
9590 agent_id: string;
9591 agent_type: string;
9592 };
9593
9594 type SubagentStopHookInput = BaseHookInput & {
9595 hook_event_name: 'SubagentStop';
9596 stop_hook_active: boolean;
9597 agent_id: string;
9598 agent_transcript_path: string;
9599 agent_type: string;
9600 /**
9601 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
9602 */
9603 last_assistant_message?: string;
9604 /**
9605 * 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.
9606 */
9607 background_tasks?: BackgroundTaskSummary[];
9608 /**
9609 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
9610 */
9611 session_crons?: SessionCronSummary[];
9612 };
9613
9614 /**
9615 * The props of `Svg`, the remote surfaces' vector leaf: the markup is the
9616 * element's data, as a string is a Text's, drawn isolated.
9617 *
9618 * A leaf: no children. The surface never lets the markup reach the page
9619 * (the engine bounds it; the desktop and the editor draw it as an image, or
9620 * in a sandboxed frame when `isInteractive`; the mobile app in a web view).
9621 */
9622 export type SvgProps = {
9623 /**
9624 * The SVG document, `<svg ...>...</svg>`, at most 131072 characters.
9625 */
9626 source: string;
9627 /**
9628 * What the drawing says, for a reader that cannot see it; required, since
9629 * a surface without the element draws nothing else of it.
9630 */
9631 alt: string;
9632 /**
9633 * CSS pixels; absent, the box takes the markup's own width up to the slot.
9634 */
9635 width?: number;
9636 /**
9637 * CSS pixels; absent, the markup's own height at the drawn width.
9638 */
9639 height?: number;
9640 /**
9641 * `true` draws the SVG in a script-less sandboxed frame so hover, CSS
9642 * `:hover`, SMIL animation and `<title>` tooltips work; absent, an image.
9643 *
9644 * It never enables script or event-handler attributes (the frame has no
9645 * allow-scripts and the scrub strips them); presses that other plugins
9646 * should observe go on an enclosing element.
9647 */
9648 isInteractive?: boolean;
9649 };
9650
9651 /**
9652 * The keys of `I` a matcher may select variants by: literal-valued in every
9653 * variant, and one literal per variant (IsDiscriminant).
9654 */
9655 type TagKeys<I> = {
9656 [K in MatcherKeys<I>]: IsLiteralValued<MatcherValueOf<I, K>> extends true ? IsDiscriminant<I, K> extends true ? K : never : never;
9657 }[MatcherKeys<I>];
9658
9659 /**
9660 * A tier `next.to(e, tier)` may name: one a floor can reach past a tier of
9661 * less authority to, so never `prepend` or `user`, which nothing skips to.
9662 */
9663 export type TargetTier = Exclude<Tier, 'prepend' | 'user'>;
9664
9665 type TaskCompletedHookInput = BaseHookInput & {
9666 hook_event_name: 'TaskCompleted';
9667 task_id: string;
9668 task_subject: string;
9669 task_description?: string;
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 type TaskCreatedHookInput = BaseHookInput & {
9678 hook_event_name: 'TaskCreated';
9679 task_id: string;
9680 task_subject: string;
9681 task_description?: string;
9682 teammate_name?: string;
9683 /**
9684 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9685 */
9686 team_name?: string;
9687 };
9688
9689 type TeammateIdleHookInput = BaseHookInput & {
9690 hook_event_name: 'TeammateIdle';
9691 teammate_name: string;
9692 /**
9693 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9694 */
9695 team_name: string;
9696 };
9697
9698 /**
9699 * The `Text` props a `hover` may override (its colors and styles, not its
9700 * wrapping) and `scope`, the hover group it joins; a `Button`'s label too.
9701 */
9702 export type TextHoverProps = {
9703 /**
9704 * Names a hover group of this plugin's: every element it draws with the
9705 * same `scope`, in any site on the surface, lights while any is hovered.
9706 *
9707 * Another plugin's elements under the same string are a different group.
9708 * One to 64 characters, no control characters; no keyed Box needed. On the
9709 * terminal a Text nested in a Text follows its group but cannot heat it.
9710 */
9711 scope?: string;
9712 color?: string;
9713 backgroundColor?: string;
9714 dimColor?: boolean;
9715 bold?: boolean;
9716 italic?: boolean;
9717 underline?: boolean;
9718 strikethrough?: boolean;
9719 inverse?: boolean;
9720 };
9721
9722 /**
9723 * The props of `Text`: the color and style props of Ink's Text a tree may
9724 * set. Colors are a theme key or a raw color.
9725 */
9726 export type TextProps = {
9727 /**
9728 * Style overrides applied by the surface while the pointer is over the
9729 * nearest enclosing keyed `Box`, or, given a `scope`, over its group.
9730 *
9731 * No hook runs and nothing crosses to the plugin. Refused outside a keyed
9732 * Box unless it names a `scope`.
9733 */
9734 hover?: TextHoverProps;
9735 color?: string;
9736 backgroundColor?: string;
9737 dimColor?: boolean;
9738 bold?: boolean;
9739 italic?: boolean;
9740 underline?: boolean;
9741 strikethrough?: boolean;
9742 inverse?: boolean;
9743 wrap?: 'wrap' | 'end' | 'middle' | 'truncate' | 'truncate-start' | 'truncate-middle' | 'truncate-end';
9744 };
9745
9746 /**
9747 * One of the chain's five tiers (TIERS), outermost first; on every
9748 * `next.trace` entry, and what `next.to(e, tier)` names.
9749 *
9750 * `prepend` and `append` are the managed plugins an administrator lists,
9751 * `user` everything a person installs, `builtin` the plugins bundled in the
9752 * binary, `core` the engine's innermost link.
9753 */
9754 export type Tier = (typeof TIERS)[number];
9755
9756 /**
9757 * The chain's five tiers, outermost first: earlier is outer is more
9758 * authority, and same-event hooks nest in this order and no other way.
9759 *
9760 * The managed plugins an administrator prepends, everything a person
9761 * installs, the managed plugins appended, the plugins bundled in the binary,
9762 * the engine's innermost link; a built-in's `$` calls still raise everywhere.
9763 */
9764 const TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
9765
9766 /**
9767 * A pending timer from `$.clock.after` / `$.clock.every`.
9768 */
9769 export type Timer = {
9770 /**
9771 * Stops it; a stopped timer never fires again.
9772 */
9773 cancel: () => void;
9774 };
9775
9776 /**
9777 * A timer on `$.clock` (`after`, `every`): `fn` runs after `ms` milliseconds,
9778 * once or until `cancel()`.
9779 */
9780 export type TimerCall = (ms: number, fn: () => void) => Timer;
9781
9782 /**
9783 * Options of `$.ui.toast`.
9784 */
9785 export type ToastOptions = {
9786 /**
9787 * How long the line stays, in milliseconds; default 4000.
9788 */
9789 timeoutMs?: number;
9790 };
9791
9792 /**
9793 * `tool.call`'s input as the call takes it: `tool_use_id` and `agentId` may
9794 * ride along (a hook passing its event's input on) and are dropped.
9795 *
9796 * The run gets its own id and runs in the session's loop.
9797 */
9798 export type ToolCallArgs = ToolCallEnvelope extends infer I ? I extends ToolCallEnvelope ? Omit<I, 'tool_use_id'> & ToolCallReserved<I['tool']> : never : never;
9799
9800 /**
9801 * The envelope the two tool events share: the tool, the id of this call, and
9802 * the tool's arguments spread beside them (`e.command` for Bash).
9803 *
9804 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
9805 * is a string and a rewrite is checked against Bash's schema. The `e` of
9806 * `classic.PreToolUse` exactly; `tool.call`'s adds the loop (ToolCallInput).
9807 */
9808 export type ToolCallEnvelope = BuiltinToolCallInput | McpToolCallInput;
9809
9810 /**
9811 * The input of `tool.call`: the tool, the id of this call, the tool's
9812 * arguments beside them (`e.command` for Bash), and `agentId` in a subagent.
9813 *
9814 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
9815 * is a string and a rewrite is checked against Bash's schema. `tool`,
9816 * `tool_use_id` and `agentId` are reserved: a rewrite of any is refused.
9817 */
9818 export type ToolCallInput = ToolCallEnvelope & AgentLoop;
9819
9820 /**
9821 * `$.tool.call(input)`: resolves with `result` typed for the tool `input`
9822 * names (ToolCallResult), or loosely for an input that names none literally.
9823 */
9824 type ToolCallOverloads = {
9825 <T extends string>(input: ToolCallArgs & ToolNamed<T>): Promise<ToolCallResult<T>>;
9826 (input: ToolCallArgs): Promise<ToolCallResult>;
9827 };
9828
9829 /**
9830 * The keys `tool.call`'s input carries beside the tool's own arguments, none
9831 * of which the tool sees (the engine strips them before the tool runs).
9832 *
9833 * `consent` is the person's own words for the press that raised the call
9834 * (`The user pressed "1: Yes" on ...`): the run's context carries it as a human
9835 * turn, which the permission path reads as the user's request.
9836 */
9837 export type ToolCallReserved<T> = {
9838 tool: T;
9839 tool_use_id?: string;
9840 consent?: string;
9841 };
9842
9843 /**
9844 * What a `tool.call` hook returns and what `next(e)` and `$.tool.call(input)`
9845 * resolve to: the tool's result (`{ result, context? }`) or `{ deny }`.
9846 *
9847 * From core the result is `{ ref, result, text }` or, when the tool reported
9848 * an error, `{ ref, result, text, isError }`; `ref` names core's messages.
9849 *
9850 * @template Name the tool the call went to, typing `result` per built-in
9851 * tool (BuiltinToolResults) once `e.tool` is narrowed; else `unknown`
9852 */
9853 export type ToolCallResult<Name extends string = string> = {
9854 /**
9855 * Refuses the call: the model receives the text as an error result.
9856 * Absent when the call was answered.
9857 */
9858 deny: string;
9859 result?: undefined;
9860 context?: undefined;
9861 ref?: undefined;
9862 text?: undefined;
9863 isError?: undefined;
9864 } | {
9865 /**
9866 * The tool's output: from core the tool's record, typed per built-in
9867 * tool once `e.tool` and `isError` are narrowed; from a hook, its own.
9868 *
9869 * Core validates a hook's answer against the tool's output schema when
9870 * it has one, maps it for the model with the tool's own mapper, and
9871 * records it in the transcript as the tool's result. Absent on a deny.
9872 */
9873 result: ToolResultOf<Name>;
9874 /**
9875 * What the model reads after the tool's result and the user never
9876 * sees. From core, none.
9877 *
9878 * One reminder, as a PostToolUse hook's is, after the managed tier's
9879 * review; none on a plugin's own `$.tool.call`. Kept whole from `next`,
9880 * none empty, any length: past 100,000 (200,000 together) head + path.
9881 */
9882 context?: readonly string[];
9883 /**
9884 * Set by core on what `next(e)` resolves to: names the messages core
9885 * produced for the call (they stay on the host side).
9886 *
9887 * A hook that returns the object it got makes core use them verbatim.
9888 * Absent on a hook's own `{ result }` and on a deny.
9889 */
9890 ref?: number;
9891 /**
9892 * Set by core: the result as the model reads it (text blocks joined),
9893 * present whatever the tool, where `result`'s shape varies per tool.
9894 *
9895 * Absent on a hook's own `{ result }`.
9896 */
9897 text?: string;
9898 isError?: undefined;
9899 deny?: undefined;
9900 } | {
9901 /**
9902 * Set by core, present only when the tool reported an error (it threw,
9903 * was interrupted, or answered an error): `text` is what the model read.
9904 */
9905 isError: true;
9906 /**
9907 * What the transcript stored for the errored call: the error text, or
9908 * undefined when nothing was stored; never the tool's typed record.
9909 */
9910 result: unknown;
9911 /**
9912 * The error as the model reads it.
9913 */
9914 text?: string;
9915 /**
9916 * As on an answered result: names the messages core produced.
9917 */
9918 ref?: number;
9919 /**
9920 * As on an answered result.
9921 */
9922 context?: readonly string[];
9923 deny?: undefined;
9924 };
9925
9926 /**
9927 * `tool.check`'s input as `$.tool.check` takes it: the tool and its
9928 * arguments; `tool_use_id` is the engine's to set, never a query's.
9929 */
9930 type ToolCheckArgs = Pick<ToolCheckInput, 'tool' | 'input'>;
9931
9932 /**
9933 * The verdict of `tool.check`: run the tool, put it to the mode's decider
9934 * (the dialog, the auto-mode classifier, a headless host), or refuse it.
9935 */
9936 type ToolCheckDecision = 'allow' | 'ask' | 'deny';
9937
9938 /**
9939 * The input of `tool.check`: the tool, its arguments, and the call's id when
9940 * the engine is deciding a real call.
9941 *
9942 * All three are the question's identity and are pinned: a hook decides
9943 * about this call, it does not change it (`tool.call` rewrites a call).
9944 */
9945 type ToolCheckInput = {
9946 /**
9947 * As the model names it (`Bash`, `mcp__server__tool`); the key a matcher
9948 * narrows on.
9949 */
9950 tool: string;
9951 /**
9952 * The tool's arguments as the permission decision reads them
9953 * (`{ command }` for Bash, `{ file_path, ... }` for the file tools).
9954 */
9955 input: unknown;
9956 /**
9957 * The call being decided, on a real call only; absent on a query.
9958 *
9959 * `next.origin` names who raised it: `{ plugin: 'engine', tier: 'core' }`
9960 * for the model's own call, the plugin for its `$.tool.call` or its query.
9961 */
9962 tool_use_id?: string;
9963 };
9964
9965 /**
9966 * What a `tool.check` hook returns and what `next(e)` resolves to: the
9967 * verdict, why, and the settings rule behind it when one decided.
9968 *
9969 * From core, the engine's declarative decision for the session's mode and
9970 * rules. A hook may answer any verdict in either direction; the last word up
9971 * the chain is the decision.
9972 */
9973 type ToolCheckResult = {
9974 /**
9975 * `allow` runs the tool; `ask` puts it to the mode's decider; `deny`
9976 * refuses it, the reason the model's error.
9977 */
9978 decision: ToolCheckDecision;
9979 /**
9980 * Why, in a sentence: from core the rule or check that decided; from a
9981 * hook, what the model reads on a deny and the dialog shows on an ask.
9982 */
9983 reason?: string;
9984 /**
9985 * The settings rule that decided, as written (`Bash(git push:*)`).
9986 *
9987 * Absent for a mode or a tool's own check.
9988 */
9989 rule?: string;
9990 };
9991
9992 /**
9993 * Where a `tool.describe` answer places the tool: `true` behind ToolSearch
9994 * (its schema loads when the model asks for it), `false` in the prompt's list.
9995 *
9996 * Left out of an answer, the placement beneath stands.
9997 */
9998 export type ToolDeferral = boolean;
9999
10000 /**
10001 * The input of `tool.describe`: one tool's description, at the moment the
10002 * engine first renders the tool's schema for the model.
10003 */
10004 export type ToolDescribeInput = {
10005 /**
10006 * As the model sees the name (`Bash`, `mcp__server__tool`); the key a
10007 * matcher narrows on.
10008 */
10009 tool: string;
10010 /**
10011 * The tool's description as it computed it.
10012 */
10013 description: string;
10014 /**
10015 * Present, and true, when the engine lists the tool behind ToolSearch (its
10016 * schema loads when the model asks for it by name); absent for one listed.
10017 *
10018 * By the engine's rule an MCP server's tool, or one that asks to be,
10019 * unless a rule keeps it in front.
10020 */
10021 isDeferred?: true;
10022 /**
10023 * Who provides this tool: the plugin and its tier; `{ plugin: "engine",
10024 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
10025 *
10026 * A configured MCP server's tool is `mcp:<server>`, in `prepend` when the
10027 * policy settings source configures the server, else `user`.
10028 */
10029 provider: Origin;
10030 };
10031
10032 /**
10033 * What a `tool.describe` hook returns: the description the model sees for that
10034 * tool and, when the hook moves it, where the tool waits (ToolDeferral).
10035 *
10036 * `{ description }` alone, or `{ ...(await next(e)), description }`, changes
10037 * the text and keeps the engine's placement; `isDeferred: true` puts the tool
10038 * behind ToolSearch, `isDeferred: false` puts its schema in the prompt's list.
10039 */
10040 export type ToolDescribeResult = {
10041 description: string;
10042 isDeferred?: ToolDeferral;
10043 };
10044
10045 /**
10046 * `{ tool, tool_use_id, ...args }` as one flat object type, generic over
10047 * the tool name and its parsed arguments.
10048 */
10049 type ToolEnvelope<Name, Arguments> = {
10050 /**
10051 * The name of the tool being called (`Bash`, `mcp__<server>__<tool>`);
10052 * comparing it narrows `e`. Reserved: a rewrite of it is ignored by core.
10053 */
10054 tool: Name;
10055 /**
10056 * The tool_use block's id: the same at every event of the call and in
10057 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
10058 */
10059 tool_use_id: string;
10060 } & Arguments;
10061
10062 /**
10063 * One tool call of a ToolGroup, as `ui.render` sees it under `calls`.
10064 */
10065 export type ToolGroupCall = {
10066 /**
10067 * The id `tool.call` carried for this call (`e.tool_use_id` there), so a
10068 * hook that saw the call finds its row in the group. Read-only.
10069 *
10070 * Absent on a desktop host that predates it.
10071 */
10072 tool_use_id?: string;
10073 /**
10074 * Which one the call ran (`Bash`, `Read`, `Grep`, ...).
10075 */
10076 tool: string;
10077 /**
10078 * The call's input, as the model sent it.
10079 */
10080 input: unknown;
10081 /**
10082 * True while the call is still running.
10083 */
10084 isRunning: boolean;
10085 /**
10086 * True when the call ended in an error.
10087 */
10088 isErrored: boolean;
10089 /**
10090 * True when an abort ended the call, as on `ToolUse`.
10091 */
10092 isInterrupted: boolean;
10093 /**
10094 * As on `ToolUse`; undefined while the call runs.
10095 */
10096 output?: unknown;
10097 };
10098
10099 /**
10100 * One tool as `$.tool.list()` returns it.
10101 */
10102 export type ToolInfo = {
10103 /**
10104 * What the model calls it by.
10105 */
10106 name: string;
10107 /**
10108 * What it does, in the tool's own words (its description; a first sentence at
10109 * most for MCP tools without one).
10110 */
10111 description: string;
10112 /**
10113 * True for an MCP server's tool.
10114 */
10115 mcp: boolean;
10116 };
10117
10118 /**
10119 * `{ tool, tool_use_id, ...args }` as one flat object type.
10120 *
10121 * The docs of `tool` and `tool_use_id` live on the `keyof` operand: a mapped
10122 * type takes its properties' docs from there.
10123 */
10124 export type ToolInputOf<Name extends string, Arguments> = {
10125 [K in keyof ToolEnvelope<Name, Arguments>]: ToolEnvelope<Name, Arguments>[K];
10126 };
10127
10128 /**
10129 * An input that names its tool as the literal `T`: what `next` and
10130 * `$.tool.call` read to type the call's result per tool (NextResultFor).
10131 */
10132 type ToolNamed<T extends string> = {
10133 /**
10134 * The name of the tool being called (`Bash`).
10135 */
10136 readonly tool: T;
10137 };
10138
10139 /**
10140 * The structured result of the tool named `Name`: its BuiltinToolResults
10141 * entry for a built-in tool, else `unknown`.
10142 *
10143 * Agent's is its entry or an AgentCallRecord (what a plugin-raised call
10144 * answers). `unknown` covers an MCP tool, a name the results table lacks
10145 * (one merged into the inputs table alone too), and `Name` left at `string`.
10146 */
10147 export type ToolResultOf<Name extends string> = string extends Name ? unknown : Name extends keyof BuiltinToolResults & string ? BuiltinToolResults[Name] | (Name extends 'Agent' ? AgentCallRecord : never) : unknown;
10148
10149 /**
10150 * One tool_result block of a user message.
10151 */
10152 export type ToolResultSummary = {
10153 /**
10154 * The id of the call this result answers (`tool.call`'s `e.tool_use_id`).
10155 */
10156 tool_use_id: string;
10157 /**
10158 * The result as the model read it (text blocks joined).
10159 */
10160 text: string;
10161 /**
10162 * True when the tool reported an error.
10163 */
10164 isError: boolean;
10165 /**
10166 * What the transcript stored for the call: the tool's record on an answered
10167 * one (`tool.call`'s `result`), the error text when `isError`.
10168 *
10169 * Absent when nothing was stored. Headless (`-p`), a tool may store the
10170 * record less its bulk (Bash blanks `stdout`); `text` is what the model
10171 * read either way.
10172 */
10173 result?: unknown;
10174 };
10175
10176 /**
10177 * What `$.tool.register` takes.
10178 */
10179 export type ToolSpec = {
10180 /**
10181 * The tool's short name (letters, digits, `_`, `-`; up to 64); the model
10182 * calls it as `mcp__<plugin>__<name>`.
10183 */
10184 name: string;
10185 /**
10186 * What the tool does, for the model (and the person where tools are
10187 * listed); an unpaired surrogate half in it is drawn as U+FFFD.
10188 */
10189 description: string;
10190 /**
10191 * A JSON schema object for the input (`{ type: "object", properties,
10192 * required }`); default `{ type: "object" }`.
10193 */
10194 inputSchema?: Record<string, unknown>;
10195 };
10196
10197 /**
10198 * One tool_use block of an assistant message, with its outcome once the
10199 * transcript holds the call's tool_result (paired by `tool_use_id`).
10200 */
10201 export type ToolUseSummary = {
10202 /**
10203 * The call's id, as `tool.call` carried it (`e.tool_use_id` there).
10204 */
10205 tool_use_id: string;
10206 /**
10207 * Which one was called (`Read`, `Bash`, `mcp__server__tool`), as
10208 * `tool.call` named it (`e.tool` there).
10209 */
10210 tool: string;
10211 /**
10212 * The arguments the model gave it.
10213 */
10214 input: Record<string, unknown>;
10215 /**
10216 * What the transcript stored for the call: the tool's record on an answered
10217 * one (`tool.call`'s `result`), the error text on a refused or errored one.
10218 *
10219 * Absent while the call is in flight or when nothing was stored. Headless
10220 * (`-p`), a tool may store the record less its bulk (Bash blanks `stdout`);
10221 * `text` holds either way.
10222 */
10223 result?: unknown;
10224 /**
10225 * The result as the model read it; absent while the call is in flight.
10226 */
10227 text?: string;
10228 /**
10229 * Present only when the tool reported an error, as on `tool.call`'s result.
10230 */
10231 isError?: true;
10232 };
10233
10234 /**
10235 * One settled run of a link beneath the caller, as `next.trace` lists it:
10236 * data, not a handle.
10237 *
10238 * `received` and `returned` are the live references where the hook runs
10239 * beside the chain; in a hooks module its own copies, as `e` is.
10240 */
10241 export type TraceEntry<N extends EventName = EventName, E = Args<N>, O = NextResult<N>> = {
10242 /**
10243 * The link's place in the chain, 0 the outermost.
10244 */
10245 readonly index: number;
10246 /**
10247 * The hook's plugin; `"engine"` for the engine's own core or bottom.
10248 */
10249 readonly plugin: string;
10250 /**
10251 * The link's tier (Tier); `"core"` for the engine's own core or bottom.
10252 */
10253 readonly tier: Tier;
10254 readonly event: N;
10255 readonly outcome: TraceOutcome;
10256 /**
10257 * Why the link was skipped without running, when it was: `bypassed by
10258 * <plugin>`, whose `next.to` went beneath this tier. Absent when it ran.
10259 */
10260 readonly reason?: string;
10261 /**
10262 * Its own wall time, its `next()` calls' time in flight taken out.
10263 *
10264 * The engine entry's is everything beneath the last hook: in a hooks
10265 * module, the host round trip.
10266 */
10267 readonly ms: number;
10268 /**
10269 * How many chunks the link yielded up, on a streaming event; absent on
10270 * every other. A link left mid-stream counts what it yielded before.
10271 */
10272 readonly chunks?: number;
10273 readonly received: E;
10274 /**
10275 * What the link settled on; undefined when it was skipped or rejected.
10276 */
10277 readonly returned: O | undefined;
10278 };
10279
10280 /**
10281 * What the chain decided for one link, as `next.trace` names it.
10282 *
10283 * `returned`: its result stood; `passed`: it returned, by reference, what its
10284 * last `next()` resolved to (a hooks module's hook answers with a copy of its
10285 * own, so it reads `returned`); `skipped`: it failed before `next`, or a
10286 * `next.to` above continued beneath its tier (`reason` says which), and
10287 * beneath ran in its place; `kept`: it failed after `next`, and that run's
10288 * result stands; `expired`: its budget ran out (what stands follows
10289 * skipped/kept); `caught`: it threw or its budget ran out, and its `.catch`
10290 * handler's result stands; `rejected`: the link rejected; the deepest such
10291 * entry is where the rejection came from, and the ones above it let it pass.
10292 */
10293 export type TraceOutcome = 'caught' | 'expired' | 'kept' | 'passed' | 'rejected' | 'returned' | 'skipped';
10294
10295 /**
10296 * What every `turn.complete` carries whatever its reason: the answer, the
10297 * duration, the interrupt flag, the turn's id, its loop and what it cost.
10298 */
10299 type TurnCompleteFields = {
10300 /**
10301 * The assistant's final visible text this turn ("" if none, e.g.
10302 * thinking-only).
10303 */
10304 answer: string;
10305 /**
10306 * Wall-clock length of the turn in milliseconds.
10307 */
10308 durationMs: number;
10309 /**
10310 * True when the turn ended by interruption (`reason === 'aborted'`).
10311 */
10312 isAborted: boolean;
10313 /**
10314 * The turn's id, the same one its `turn.start` and every `turn.step`
10315 * carried; a subagent's run raises no `turn.start`, its steps carry it.
10316 */
10317 turnId: string;
10318 /**
10319 * The loop the turn ran in: a subagent's id, as `$.agent.spawn` resolves
10320 * it, each run of its loop one turn; absent on the main loop.
10321 *
10322 * Pinned: a different value is refused, one left out is kept. Every hook
10323 * sees a subagent's turn, so a hook that spawns sees its children's turns
10324 * too and bounds itself.
10325 */
10326 agentId?: string;
10327 /**
10328 * What the turn cost: its responses' token counts summed and the model of
10329 * the last, read off the API responses the engine already holds.
10330 *
10331 * Absent when the turn got no response (interrupted before one, an API
10332 * error).
10333 */
10334 usage?: TurnUsage;
10335 };
10336
10337 /**
10338 * The input of `turn.complete`: the assistant's final message of a turn, at
10339 * the moment the turn ends (where the turn's duration is reported).
10340 *
10341 * `reason` says why it ended; `refusal` exists on a refusal alone.
10342 */
10343 export type TurnCompleteInput = TurnCompleteFields & (TurnCompleteRefused | TurnCompleteUnrefused);
10344
10345 /**
10346 * Why a turn ended: the model answered, the user interrupted it, the model
10347 * refused with no fallback model to retry on, or an API error ended it.
10348 */
10349 export type TurnCompleteReason = 'answer' | 'aborted' | 'refusal' | 'error';
10350
10351 /**
10352 * The end of a turn the model refused with no fallback model to retry on:
10353 * what the API said of the refusal rides along.
10354 */
10355 type TurnCompleteRefused = {
10356 reason: 'refusal';
10357 refusal: TurnRefusal;
10358 };
10359
10360 /**
10361 * What a `turn.complete` hook returns and what `next(e)` resolves to:
10362 * `{ text }`; a text other than a main-loop answer's is shown beneath it.
10363 *
10364 * Core fills `usage` from `e.usage` when the turn had one; a hook above reads
10365 * it, and one that answers its own may leave it out.
10366 */
10367 export type TurnCompleteResult = {
10368 text: string;
10369 usage?: TurnUsage;
10370 };
10371
10372 /**
10373 * The end of a turn that was not a refusal: answered, interrupted, or dead
10374 * on an API error (retries exhausted, the context limit), nothing more.
10375 */
10376 type TurnCompleteUnrefused = {
10377 reason: Exclude<TurnCompleteReason, 'refusal'>;
10378 };
10379
10380 /**
10381 * What the API said about a refusal that ended a turn: the classifier's
10382 * category and its explanation, each null when the API sent none.
10383 */
10384 export type TurnRefusal = {
10385 category: string | null;
10386 explanation: string | null;
10387 };
10388
10389 /**
10390 * The input of `turn.start`: the prompt a model turn begins with, after
10391 * `prompt.submit` settled the text and the UserPromptSubmit settings hooks ran.
10392 */
10393 export type TurnStartInput = {
10394 /**
10395 * The user's text as the turn proceeds with it ("" for a turn started without
10396 * a typed prompt, e.g. a continuation).
10397 */
10398 text: string;
10399 /**
10400 * The turn's id, minted here; the same one every `turn.step` and the
10401 * `turn.complete` of this turn carry.
10402 */
10403 turnId: string;
10404 };
10405
10406 /**
10407 * What a `turn.start` hook returns and what `next(e)` resolves to:
10408 * `{ turnId }`, echoed by core; a hook's own value does not change the turn.
10409 */
10410 export type TurnStartResult = {
10411 turnId: string;
10412 };
10413
10414 /**
10415 * One piece of a `turn.step` response as it streams through the chain:
10416 * what a hook's `next(e)` yields and what the hook yields up in turn.
10417 *
10418 * Text, thinking, a tool call's start and arguments, and the stop are
10419 * plain data a hook reads and rewrites; `engine` is the rest, passed on
10420 * unread. What leaves the outermost hook is what is shown and recorded.
10421 */
10422 export type TurnStepChunk = TurnStepTextChunk | TurnStepThinkingChunk | TurnStepToolChunk | TurnStepInputChunk | TurnStepStopChunk | TurnStepEngineChunk;
10423
10424 /**
10425 * An item of the engine's stream the other chunk kinds do not model (the
10426 * envelope, a block's start and end, a retry marker), opaque by `ref`.
10427 *
10428 * Pass it on where it came. A hook that yields its own response has none
10429 * to yield, and the engine supplies what the response needs around the
10430 * chunks it does yield.
10431 */
10432 export type TurnStepEngineChunk = {
10433 kind: 'engine';
10434 /**
10435 * The engine's handle on the item; opaque, this step's only.
10436 */
10437 ref: number;
10438 };
10439
10440 /**
10441 * The input of `turn.step`: one model request inside a turn, at the moment
10442 * the engine is about to send it; the bottom of the chain sends it.
10443 *
10444 * The transcript is not on it: `messageCount` says how many messages the
10445 * request carries, and `$.session.messages()` reads them. A hook rewrites
10446 * `model` or `effort` going down; the rest is pinned.
10447 */
10448 export type TurnStepInput = {
10449 /**
10450 * The turn this step belongs to (`turn.start`'s id; inside a subagent's
10451 * loop, the id the run's `turn.complete` will carry). Pinned.
10452 */
10453 turnId: string;
10454 /**
10455 * The step's position in the turn, from 0. Pinned.
10456 */
10457 index: number;
10458 /**
10459 * Which model the request names, as the engine resolved it for this step
10460 * (the session's, a fallback's). `next({ ...e, model })` names another.
10461 */
10462 model: string;
10463 /**
10464 * How hard the request asks the model to think: the session's setting or
10465 * the model's default, absent for a model without effort; rewritable.
10466 */
10467 effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number;
10468 /**
10469 * How many messages the request carries (the conversation so far, the
10470 * turn's tool results included). Pinned: the messages are the engine's.
10471 */
10472 messageCount: number;
10473 /**
10474 * The loop the request is made in: a subagent's id, the `id`
10475 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
10476 *
10477 * Pinned: a different value is refused, one left out is kept. A subagent
10478 * a hook spawned through `$.agent.spawn` steps past that hook, as its tool
10479 * calls do; every other hook sees its steps.
10480 */
10481 agentId?: string;
10482 };
10483
10484 /**
10485 * A piece of a tool call's arguments as they arrive: JSON text, partial,
10486 * for the `tool` chunk of the same `index`.
10487 *
10488 * The arguments the tool runs with are the pieces concatenated and parsed
10489 * once the block ends; pieces that do not parse leave the call without
10490 * arguments it can run on, as a model that wrote broken JSON would.
10491 */
10492 export type TurnStepInputChunk = ChunkRef & {
10493 kind: 'input';
10494 index: number;
10495 /**
10496 * The next piece of the arguments' JSON text.
10497 */
10498 json: string;
10499 };
10500
10501 /**
10502 * What a `turn.step` hook returns and what `next(e)` resolves to: the
10503 * model's response to the step's request, once its blocks are all in.
10504 *
10505 * From the bottom, the response the engine streamed; a hook's own value
10506 * changes what the hooks above it read, never what the engine streamed.
10507 */
10508 export type TurnStepResult = {
10509 /**
10510 * The turn this step belongs to, as received.
10511 */
10512 turnId: string;
10513 /**
10514 * The step's position in the turn, as received.
10515 */
10516 index: number;
10517 /**
10518 * The visible text of the response ("" when it only called tools, only
10519 * thought, or no request was made).
10520 */
10521 answer: string;
10522 /**
10523 * The tool calls the response made, in order; empty for a text-only step.
10524 */
10525 toolUses: readonly TurnStepToolUse[];
10526 /**
10527 * Why the model stopped; null when no response arrived (the request
10528 * failed or was interrupted before a message, or no request was made).
10529 */
10530 stopReason: TurnStopReason;
10531 /**
10532 * What the request cost as the API reported it, and the model that
10533 * answered; null when no response arrived or it carried no usage.
10534 */
10535 usage: TurnUsage | null;
10536 };
10537
10538 /**
10539 * The response is whole: why the model stopped and what the request cost,
10540 * as the step's result will carry them. The last chunk of one response.
10541 */
10542 export type TurnStepStopChunk = ChunkRef & {
10543 kind: 'stop';
10544 stopReason: TurnStopReason;
10545 usage: TurnUsage | null;
10546 };
10547
10548 /**
10549 * A piece of the response's visible text as it arrives, in block `index`.
10550 *
10551 * The text the person watches stream and the text the transcript records
10552 * are both the concatenation of these, in order, per block: a hook that
10553 * rewrites them rewrites both, one that drops them all drops the block.
10554 */
10555 export type TurnStepTextChunk = ChunkRef & {
10556 kind: 'text';
10557 /**
10558 * The content block the piece belongs to, from 0 within one response.
10559 */
10560 index: number;
10561 text: string;
10562 };
10563
10564 /**
10565 * A piece of the model's thinking as it arrives, in block `index`: what
10566 * the person sees of it live.
10567 *
10568 * The thinking block the transcript keeps is the one the model signed, as
10569 * the engine received it; thinking a hook streams without the engine's
10570 * block behind it is shown and not recorded.
10571 */
10572 export type TurnStepThinkingChunk = ChunkRef & {
10573 kind: 'thinking';
10574 index: number;
10575 text: string;
10576 };
10577
10578 /**
10579 * The model begins a tool call in block `index`: the tool's name and the
10580 * call's id; its arguments follow as `input` chunks of the same index.
10581 *
10582 * A block whose `tool` chunk never comes out of the chain is no tool call:
10583 * the engine records none and runs none.
10584 */
10585 export type TurnStepToolChunk = ChunkRef & {
10586 kind: 'tool';
10587 index: number;
10588 /**
10589 * The call's `tool_use_id`.
10590 */
10591 id: string;
10592 /**
10593 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
10594 */
10595 name: string;
10596 };
10597
10598 /**
10599 * One tool call the model asked for in a step: the tool's name and its
10600 * arguments.
10601 */
10602 export type TurnStepToolUse = {
10603 /**
10604 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
10605 */
10606 name: string;
10607 /**
10608 * The arguments the model gave it, as the tool schema shapes them.
10609 */
10610 input: unknown;
10611 };
10612
10613 /**
10614 * Why the model stopped, as a `turn.step` result and its stop chunk carry
10615 * it: one of the API's stop reasons, or null when no response arrived.
10616 */
10617 type TurnStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'compaction' | 'refusal' | 'model_context_window_exceeded' | null;
10618
10619 /**
10620 * What a model turn, or one response inside it, cost as the API reported it:
10621 * the four token counts (`$.model.fork`'s usage shape) and the model's id.
10622 *
10623 * A turn's counts are its responses' summed; its model is the last response's.
10624 */
10625 export type TurnUsage = ModelForkUsage & {
10626 /**
10627 * Which model answered, by the id the API reports.
10628 */
10629 model: string;
10630 };
10631
10632 /**
10633 * What a plugin's `$.ui.blit(args)` takes: a Raster's next `cells`
10634 * (RasterBlitArgs) or a keyed Image's next `source` (ImageBlitArgs).
10635 *
10636 * Either names an element this plugin's own `ui.render` hook drew, still
10637 * mounted; a hook above may rewrite the cells or the source, never the
10638 * address or which kind it is.
10639 */
10640 export type UiBlitArgs = RasterBlitArgs | ImageBlitArgs;
10641
10642 /**
10643 * What `$.ui.blit` resolves to and what a `ui.blit` hook's `{ value }`
10644 * holds: `{}` once the cells or source are the next frame's, or why not.
10645 */
10646 export type UiBlitResult = {
10647 /**
10648 * Absent when the cells or source were taken; else why not.
10649 *
10650 * Nothing of this plugin's is mounted there (another plugin's reads so),
10651 * the size is not the mounted one, the cells or source are bad, or the
10652 * Image draws its `alt` there, the reason spelled out for a fallback.
10653 */
10654 deny?: string;
10655 };
10656
10657 /**
10658 * What a plugin's `$.ui.focus(args)` takes: one of its own elements, by the
10659 * `key` it drew it under, in one of its sites that holds the keyboard now.
10660 *
10661 * The engine resolves it to that site's ring and raises `ui.focus` under
10662 * the plugin's origin; the keyboard is the person's to give, so a site that
10663 * does not hold it, or holds it on another plugin's element, is `{ deny }`.
10664 */
10665 export type UiFocusArgs = {
10666 /**
10667 * The site, by the `requestId` this plugin draws it under: one of its
10668 * panes' ids, or the band's.
10669 */
10670 requestId: string;
10671 /**
10672 * The element's `key`: a `Button`, `Input` or `Select` this plugin drew in
10673 * that site; of several under one key, the first in document order.
10674 */
10675 key: string;
10676 };
10677
10678 /**
10679 * The render components whose site keeps a focus ring: a pane's body and
10680 * the band above the prompt, each a ring over the elements hooks drew there.
10681 */
10682 export type UiFocusComponent = 'Pane' | 'AbovePrompt';
10683
10684 /**
10685 * The input of `ui.focus`: a site's focus ring about to move onto one of the
10686 * elements a hook drew in it (a `Button`, `Input` or `Select`), or off them.
10687 *
10688 * Every key but `element` is the engine's word, pinned: `next(e)` passes
10689 * them on, a rewrite that leaves one out keeps it, one that changes it fails
10690 * the hook. `element` is the hook's to rewrite; the ring has not moved yet.
10691 */
10692 export type UiFocusInput = {
10693 /**
10694 * Which site: a `Pane` body or the `AbovePrompt` band.
10695 */
10696 component: UiFocusComponent;
10697 /**
10698 * The instance the `ui.render` hook drawing the site sees: the pane's id,
10699 * or the band's one id.
10700 */
10701 requestId: string;
10702 /**
10703 * Whose `ui.render` hook drew the element taking the ring; absent with
10704 * `element`. Read-only.
10705 */
10706 plugin?: string;
10707 /**
10708 * The `key` of the element taking the ring, as `ui.press` names it; absent
10709 * for one of the engine's own stops (a pane's close mark or another's tab).
10710 *
10711 * `next({ ...e, element })` lands it on another element `plugin` drew in
10712 * the site instead; one not drawn there is core's `{ deny }`.
10713 */
10714 element?: string;
10715 /**
10716 * Who moves it (UiFocusOrigin), set by the engine where the move starts.
10717 */
10718 origin: UiFocusOrigin;
10719 };
10720
10721 /**
10722 * Who moves the ring at `ui.focus`, as the engine stamps it where the move
10723 * starts; a closed set a matcher narrows on.
10724 *
10725 * `next(e)` passes it on as received; no hook sets one.
10726 */
10727 export type UiFocusOrigin = {
10728 /**
10729 * The person, by Tab, the arrows or a click while the site holds the
10730 * keyboard.
10731 */
10732 kind: 'person';
10733 } | {
10734 /**
10735 * A plugin's `$.ui.focus`, or its `autoFocus` element taking the ring
10736 * as the site takes the keyboard.
10737 */
10738 kind: 'plugin';
10739 /**
10740 * The focusing plugin's name.
10741 */
10742 name: string;
10743 };
10744
10745 /**
10746 * What a `ui.focus` hook returns, what `next(e)` resolves to, and what
10747 * `$.ui.focus` hands back: `{}` once the ring moved, or why it did not.
10748 *
10749 * As `ui.scroll` spells it.
10750 */
10751 export type UiFocusResult = {
10752 /**
10753 * Absent when the ring is where the chain left it; else why nothing
10754 * moved.
10755 *
10756 * A hook kept the ring (no `next`); the site is not this plugin's, does
10757 * not hold the keyboard, or another plugin's element holds it; no element
10758 * of `plugin` is drawn under `element`; another move landed first.
10759 */
10760 deny?: string;
10761 };
10762
10763 /**
10764 * The argument of `ui.input`: a change of, or a submit from, an `Input` a
10765 * render hook drew. Flat and frozen like every event's.
10766 *
10767 * Another plugin addresses one field by matcher:
10768 * `on("ui.input", { plugin: "roster", element: "reply" }, ...)`.
10769 */
10770 export type UiInputArgument = {
10771 /**
10772 * Whose `ui.render` hook drew the element.
10773 */
10774 plugin: string;
10775 /**
10776 * The `key` the hook gave its `Input`: its address, what a matcher names.
10777 */
10778 element: string;
10779 /**
10780 * The render component the element was drawn in (`AbovePrompt`,
10781 * `ToolUse`, ...).
10782 */
10783 component: RenderComponent;
10784 /**
10785 * The instance the element was drawn in: the `requestId` the `ui.render`
10786 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
10787 */
10788 requestId: string;
10789 /**
10790 * Where the typing came from, one literal per member, so
10791 * `if (e.surface === "terminal")` narrows `e`.
10792 */
10793 surface: RenderSurface;
10794 /**
10795 * `change` after every edit of the text; `submit` on Enter.
10796 */
10797 kind: 'change' | 'submit';
10798 /**
10799 * The field's whole text at that moment; a hook above may rewrite it for
10800 * the plugins beneath and the element's own handler.
10801 */
10802 value: string;
10803 };
10804
10805 /**
10806 * What a `ui.input` hook returns and what `next(e)` resolves to.
10807 *
10808 * Beneath every hook, core runs the element's `onInput` (kind `change`) or
10809 * `onSubmit` (kind `submit`) closure in its plugin's environment with the
10810 * value as the chain left it, and answers `{ element, value }`.
10811 */
10812 export type UiInputResult = {
10813 /**
10814 * Which handler the input reached, by its Input's `key`.
10815 */
10816 element: string;
10817 /**
10818 * The text the handler received.
10819 */
10820 value: string;
10821 };
10822
10823 /**
10824 * Options of `$.ui.log`.
10825 */
10826 export type UiLogOptions = {
10827 /**
10828 * Where the line goes (UiLogSink); `transcript` when left out. A hook on
10829 * `ui.log` reads it as `e.to` and may send the line elsewhere.
10830 */
10831 to?: UiLogSink;
10832 };
10833
10834 /**
10835 * Where a `$.ui.log` line goes: `transcript`, a dim row of its own (and the
10836 * debug log, as every line); `debug`, the debug log alone, nothing on screen.
10837 *
10838 * The debug log is `claude --debug` or the `--debug-file`; either way the
10839 * line is led by the plugin's name.
10840 */
10841 export type UiLogSink = 'transcript' | 'debug';
10842
10843 /**
10844 * The argument of `ui.message`: what a `Client` instance's surface module
10845 * posted (`surface.post(data)`), addressed by where the instance is drawn.
10846 *
10847 * The origin is `client`: code sent it, on nobody's behalf, so `data` is
10848 * input to validate, not a fact. Everything but `data` is the engine's word
10849 * and a hook may not rewrite it.
10850 */
10851 export type UiMessageArgument = {
10852 /**
10853 * Where the instance is drawn: `terminal`, or `desktop` once it has them.
10854 */
10855 surface: RenderSurface;
10856 /**
10857 * The render component the `Client` was drawn in (`AbovePrompt`, `Pane`,
10858 * ...).
10859 */
10860 component: RenderComponent;
10861 /**
10862 * The engine's id for the drawing the `Client` sits in: the `requestId` the
10863 * `ui.render` hook that drew it saw.
10864 */
10865 requestId: string;
10866 /**
10867 * The `Client`'s `key`: which instance posted.
10868 */
10869 element: string;
10870 /**
10871 * The `Client`'s `module`: which surface module runs there, as its path
10872 * under the plugin's folder.
10873 */
10874 module: string;
10875 /**
10876 * What the instance posted: plain data (JsonValue), bounded as a tree's
10877 * text is; typed `unknown` since it came from code. Rewritable.
10878 */
10879 data: unknown;
10880 };
10881
10882 /**
10883 * What a `ui.message` hook returns and what `next(e)` resolves to.
10884 *
10885 * Core answers `{}`: the message was heard and nothing changes. A hook that
10886 * answers `{ props }` hands the posting instance its next props directly, its
10887 * local state kept, with no `ui.render` run; the plugin's next redraw hands
10888 * props again as usual.
10889 */
10890 export type UiMessageResult = {
10891 /**
10892 * The instance's next props, plain data (JsonValue) bounded as a `Client`'s
10893 * props are; absent leaves the instance's props as they were.
10894 */
10895 props?: unknown;
10896 };
10897
10898 /**
10899 * One of this plugin's open panes as `$.ui.panes()` lists it: the pane's
10900 * id and title, and where it stands with the person right now.
10901 *
10902 * Where a surface seated it (`dock` or `inline`) is that surface's to say, on
10903 * the `Pane` render props (`placement`); a session may draw on several.
10904 */
10905 export type UiPane = {
10906 /**
10907 * What `$.ui.open({ id })` named it, which `$.ui.close` and its
10908 * `ui.render` `requestId` name too.
10909 */
10910 id: string;
10911 /**
10912 * Its tab's label: the `title` of its latest open, or the id.
10913 */
10914 title: string;
10915 /**
10916 * True for the one pane the surface shows; the rest are tabs behind it.
10917 */
10918 isShown: boolean;
10919 /**
10920 * True while the person has given it the keyboard.
10921 */
10922 isFocused: boolean;
10923 /**
10924 * False while it waits undrawn: opened unasked on a terminal too narrow
10925 * for an unrequested pane, until an open the width or the person admits.
10926 */
10927 isPlaced: boolean;
10928 };
10929
10930 /**
10931 * The argument of `ui.press`: a press on a `Button` a render hook drew, or
10932 * on an answered `Markdown` link. Flat and frozen like every event's.
10933 *
10934 * Another plugin addresses one button by matcher:
10935 * `on("ui.press", { plugin: "explainer", element: "explain" }, ...)`.
10936 */
10937 export type UiPressArgument = {
10938 /**
10939 * Whose `ui.render` hook drew the element.
10940 */
10941 plugin: string;
10942 /**
10943 * The `key` the hook gave its `Button` or `Markdown`: its address, what a
10944 * matcher names.
10945 */
10946 element: string;
10947 /**
10948 * The render component the element was drawn in (`ToolUse`,
10949 * `AssistantMessage`, ...).
10950 */
10951 component: RenderComponent;
10952 /**
10953 * The instance the element was drawn in: the `requestId` the `ui.render`
10954 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
10955 */
10956 requestId: string;
10957 /**
10958 * Where the press came from, one literal per member, so
10959 * `if (e.surface === "terminal")` narrows `e`.
10960 */
10961 surface: RenderSurface;
10962 /**
10963 * Where the press landed, when the element is a `Markdown` whose links
10964 * its plugin answers (`onLinkPress`); absent for a `Button`.
10965 *
10966 * A hook may rewrite its `href` for the hooks and the closure beneath; one
10967 * that adds or drops it fails, and the press goes on beneath it.
10968 */
10969 link?: PressedLink;
10970 };
10971
10972 /**
10973 * What a `ui.press` hook returns and what `next(e)` resolves to.
10974 *
10975 * Beneath every hook, core runs the element's `onPress` closure in its
10976 * plugin's environment with `e` as the chain left it, and answers
10977 * `{ element }`.
10978 */
10979 export type UiPressResult = {
10980 /**
10981 * Which handler the press reached, by its Button's `key`.
10982 */
10983 element: string;
10984 };
10985
10986 /**
10987 * What a plugin's `$.ui.scroll(args)` takes: what to bring into view, in
10988 * which of its sites, and where in the window it lands.
10989 *
10990 * The engine resolves it to a window and an offset and raises `ui.scroll`
10991 * under the plugin's origin; a transcript row is the person's to move, so
10992 * it is revealed only while the plugin answers the person's own input.
10993 */
10994 export type UiScrollArgs = {
10995 /**
10996 * What to reveal (UiScrollTarget): a render instance by `requestId`, one
10997 * of this plugin's elements by `key`, or the `start` or `end` of `in`.
10998 */
10999 to: UiScrollTarget;
11000 /**
11001 * The site to scroll, by the `requestId` this plugin draws it under: one
11002 * of its panes' ids, or the band's.
11003 *
11004 * Required with `start` and `end`; with `{ key }` it picks the site when
11005 * the key is drawn in several.
11006 */
11007 in?: string;
11008 /**
11009 * Where the target lands in the window (UiScrollBlock); `nearest` when
11010 * left out, so a row already showing does not move.
11011 */
11012 block?: UiScrollBlock;
11013 };
11014
11015 /**
11016 * Where in its scrollable a revealed row lands, as the DOM's
11017 * `scrollIntoView({ block })` names it.
11018 *
11019 * `nearest` moves the least that shows the row whole, and not at all when
11020 * it already shows; `start`, `center` and `end` put its top, middle or
11021 * bottom at that edge of the window. A row taller than the window shows
11022 * its top.
11023 */
11024 export type UiScrollBlock = 'start' | 'center' | 'end' | 'nearest';
11025
11026 /**
11027 * The render components whose site the engine scrolls: a pane's body and
11028 * the band above the prompt, each a window over the tree a hook drew there.
11029 */
11030 export type UiScrollComponent = 'Pane' | 'AbovePrompt';
11031
11032 /**
11033 * The input of `ui.scroll`: a site's window asked to move over the tree a
11034 * hook drew in it (a pane's body, the band above the prompt).
11035 *
11036 * Every key but `offset` is the engine's word, pinned: `next(e)` passes
11037 * them on, a rewrite that leaves one out keeps it, one that changes or adds
11038 * one fails the hook. `offset` is the hook's to rewrite; nothing moved yet.
11039 */
11040 export type UiScrollInput = {
11041 /**
11042 * Which site: a `Pane` body or the `AbovePrompt` band.
11043 */
11044 component: UiScrollComponent;
11045 /**
11046 * The instance the `ui.render` hook drawing the site sees: the pane's id,
11047 * or the band's one id.
11048 */
11049 requestId: string;
11050 /**
11051 * The first row the window is to show, 0 at the top: the row it shows
11052 * now plus `by`, clamped to the tree, or where `$.ui.scroll` resolved.
11053 *
11054 * `next({ ...e, offset })` moves it elsewhere (a clamp); one past the
11055 * tree's end lands at the end. Nothing has moved when a hook reads it.
11056 */
11057 offset: number;
11058 /**
11059 * The rows the move asks for, signed, negative toward the top; what the
11060 * DOM's `scrollBy` takes. Read-only.
11061 *
11062 * The person's: a wheel tick `-1` or `1` at rest, more as ticks crowd or
11063 * summed in flight; an arrow a row while the engine has rows to scroll, a
11064 * page key `bodyRows`, Home and End `contentRows`. A plugin's: its distance.
11065 */
11066 by: number;
11067 /**
11068 * How many rows of the tree the window shows at once, as drawn now.
11069 * Read-only.
11070 */
11071 bodyRows: number;
11072 /**
11073 * How many rows the tree has, as drawn now: the window's last offset is
11074 * `contentRows - bodyRows`, none when the tree fits. Read-only.
11075 */
11076 contentRows: number;
11077 /**
11078 * Who moves it (UiScrollOrigin), set by the engine where the move starts.
11079 */
11080 origin: UiScrollOrigin;
11081 /**
11082 * The body cell the person's wheel or trackpad was over (UiScrollPointer);
11083 * absent for the scroll keys and for `$.ui.scroll`. Read-only.
11084 *
11085 * Moves summed while a dispatch was in flight carry the latest one's. A
11086 * hook pinning a list over rows it scrolls itself tells a tick over the
11087 * list (`row` among its list's rows) from one over the body.
11088 */
11089 pointer?: UiScrollPointer;
11090 };
11091
11092 /**
11093 * Who moves the window at `ui.scroll`, as the engine stamps it where the
11094 * move starts; a closed set a matcher narrows on.
11095 *
11096 * `next(e)` passes it on as received; no hook sets one.
11097 */
11098 export type UiScrollOrigin = {
11099 /**
11100 * The person, by the wheel over the site or its scroll keys while
11101 * they hold it.
11102 */
11103 kind: 'person';
11104 } | {
11105 /**
11106 * A plugin's `$.ui.scroll`.
11107 */
11108 kind: 'plugin';
11109 /**
11110 * The scrolling plugin's name.
11111 */
11112 name: string;
11113 };
11114
11115 /**
11116 * The cell the pointer was over when the person's wheel raised `ui.scroll`,
11117 * in the site's body: the box its `ui.render` hook draws into, as painted.
11118 *
11119 * The DOM's `clientY - body.top` in cells, the window's offset not added: a
11120 * hook drawing its own window reads `row` as its tree's row, one the engine
11121 * scrolls adds the `scroll.offset` it drew with. The frame lies outside.
11122 */
11123 export type UiScrollPointer = {
11124 /**
11125 * 0 at the body's left edge, as `bodyColumns` counts them; negative, or
11126 * `bodyColumns` and past, over an inline pane's side borders.
11127 */
11128 column: number;
11129 /**
11130 * 0 at the body's first showing row, as `bodyRows` counts them.
11131 *
11132 * The tree's row is `scroll.offset + row` under the engine's window, and
11133 * `row` itself under a hook's own (offset 0); negative over a pane's top
11134 * border or tab row, `bodyRows` or more over its bottom border.
11135 */
11136 row: number;
11137 };
11138
11139 /**
11140 * What a `ui.scroll` hook returns, what `next(e)` resolves to, and what
11141 * `$.ui.scroll` hands back: `{}` once the window moved, or why it did not.
11142 */
11143 export type UiScrollResult = {
11144 /**
11145 * Absent when the window is where the chain left it; else why nothing
11146 * moved, as `tool.call` and `config.set` spell a refusal.
11147 *
11148 * A hook kept the window (no `next`); the target is not this plugin's;
11149 * another move landed first (`the window moved meanwhile`); a transcript
11150 * row is not the person's ask (`not person-initiated`) or none scrolls.
11151 */
11152 deny?: string;
11153 };
11154
11155 /**
11156 * What `$.ui.scroll` brings into view: never a row number, always a thing
11157 * drawn somewhere.
11158 *
11159 * `{ requestId }` names a render instance by the id its `ui.render` hook
11160 * saw (a transcript message's, a tool row's tool_use_id), scrolled into view
11161 * inside whatever scrolls it. `{ key }` names an element this plugin drew
11162 * with that `key`, inside the site it drew it in. `start` and `end` are the
11163 * top and bottom of the site `in` names; `end` keeps up with a tree that
11164 * grows (rows the plugin just added count) until anything next moves it.
11165 */
11166 export type UiScrollTarget = {
11167 requestId: string;
11168 } | {
11169 key: string;
11170 } | 'start' | 'end';
11171
11172 /**
11173 * The argument of `ui.select`: a pick from a `Select` a render hook drew.
11174 * Flat and frozen like every event's.
11175 *
11176 * Another plugin addresses one picker by matcher:
11177 * `on("ui.select", { plugin: "roster", element: "peer" }, ...)`.
11178 */
11179 export type UiSelectArgument = {
11180 /**
11181 * Whose `ui.render` hook drew the element.
11182 */
11183 plugin: string;
11184 /**
11185 * The `key` the hook gave its `Select`: its address, what a matcher names.
11186 */
11187 element: string;
11188 /**
11189 * The render component the element was drawn in (`AbovePrompt`,
11190 * `ToolUse`, ...).
11191 */
11192 component: RenderComponent;
11193 /**
11194 * The instance the element was drawn in: the `requestId` the `ui.render`
11195 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
11196 */
11197 requestId: string;
11198 /**
11199 * Where the pick came from, one literal per member, so
11200 * `if (e.surface === "terminal")` narrows `e`.
11201 */
11202 surface: RenderSurface;
11203 /**
11204 * The picked option's value; a hook above may rewrite it for the plugins
11205 * beneath and the element's own handler.
11206 */
11207 value: string;
11208 };
11209
11210 /**
11211 * What a `ui.select` hook returns and what `next(e)` resolves to.
11212 *
11213 * Beneath every hook, core runs the element's `onSelect` closure in its
11214 * plugin's environment with the value as the chain left it, and answers
11215 * `{ element, value }`.
11216 */
11217 export type UiSelectResult = {
11218 /**
11219 * Which handler the pick reached, by its Select's `key`.
11220 */
11221 element: string;
11222 /**
11223 * What the handler received: the option's value as the chain left it.
11224 */
11225 value: string;
11226 };
11227
11228 /**
11229 * The intersection of a union's members (`A | B` to `A & B`), by inferring
11230 * one parameter type from the contravariant positions.
11231 */
11232 type UnionToIntersection<U> = (U extends unknown ? (member: U) => void : never) extends (member: infer I) => void ? I : never;
11233
11234 /**
11235 * One unit of what `$.session.usage()` answers, by its key there: the
11236 * context window's fill, the rate-limit windows, the session's cost.
11237 */
11238 export type UsageUnit = 'context' | 'rateLimits' | 'cost';
11239
11240 /**
11241 * Who sent the message a `UserMessage` row carries, when someone other than
11242 * the person did: another agent, a teammate, another session, a channel.
11243 *
11244 * Read-only. The sender's words are not the person's: the model reads them
11245 * framed as that sender's whatever a hook draws for the row.
11246 */
11247 type UserMessageFrom = {
11248 /**
11249 * The sender's name as the row shows it: a subagent's name, else its type;
11250 * a teammate's; another session's title; a channel's sender, else server.
11251 *
11252 * One printable line: control and format characters stripped, whitespace
11253 * collapsed, length bounded. Absent (no `from`) for a teammate block whose
11254 * frames name different senders or none.
11255 */
11256 name: string;
11257 };
11258
11259 /**
11260 * The background task a `UserMessage` notification row reports on: a
11261 * subagent, a background shell, a workflow, a remote agent, a monitor.
11262 *
11263 * Every field is the notification's own, so the row names the same task on
11264 * every draw, a resumed session's included; the session's record of it
11265 * (name, type, description) is `$.agent.list()`'s, by `id`. Each string is
11266 * one printable line, bounded (a forged envelope's bytes capped). Read-only.
11267 */
11268 type UserMessageTask = {
11269 /**
11270 * The task's id as the notification names it; for a subagent, the
11271 * `agentId` its `turn.complete` carried and `$.agent.list()` keys.
11272 */
11273 id?: string;
11274 /**
11275 * How the task ended: `completed`, `failed` or `killed` (stopped, by the
11276 * person or by Claude), or another word its producer wrote.
11277 */
11278 status?: string;
11279 /**
11280 * What kind of task, when the notification says (`remote_agent`, an
11281 * artifact watch's kind); a subagent's and a shell's leave it out.
11282 */
11283 type?: string;
11284 /**
11285 * Which call started the task: its `tool_use_id`, when the notification
11286 * carries it.
11287 */
11288 toolUseId?: string;
11289 /**
11290 * How long the task ran, in milliseconds, when the notification says; the
11291 * row draws it after the summary (`2m 2s`).
11292 */
11293 durationMs?: number;
11294 };
11295
11296 type UserPromptExpansionHookInput = BaseHookInput & {
11297 hook_event_name: 'UserPromptExpansion';
11298 expansion_type: 'slash_command' | 'mcp_prompt';
11299 command_name: string;
11300 command_args: string;
11301 command_source?: string;
11302 prompt: string;
11303 };
11304
11305 type UserPromptSubmitHookInput = BaseHookInput & {
11306 hook_event_name: 'UserPromptSubmit';
11307 prompt: string;
11308 /**
11309 * 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.
11310 */
11311 source?: 'user' | 'sdk' | 'system' | 'loop_wakeup' | 'schedule_wakeup' | 'poll_event';
11312 session_title?: string;
11313 };
11314
11315 /**
11316 * The result of a call on `$` as the hooks on its event see it: `{ value }`,
11317 * the call's answer, or `{ deny }`, the reason the caller's promise rejects.
11318 */
11319 type ValueOrDeny<Value> = {
11320 value: Value;
11321 deny?: undefined;
11322 } | {
11323 deny: string;
11324 value?: undefined;
11325 };
11326
11327 type WorktreeCreateHookInput = BaseHookInput & {
11328 hook_event_name: 'WorktreeCreate';
11329 name: string;
11330 };
11331
11332 type WorktreeRemoveHookInput = BaseHookInput & {
11333 hook_event_name: 'WorktreeRemove';
11334 worktree_path: string;
11335 };
11336
11337 /**
11338 * The globals of a hooks module's environment: these and no others (no DOM,
11339 * no Node). No code generation either: `eval` and `new Function` over a
11340 * string throw, and there is no `WebAssembly` (deliberately; a module that
11341 * needs compiled code runs it in a process of its own through `$.process.run`).
11342 * A surface module's environment (Client) has the same globals and a
11343 * `console`; neither has timers (a hooks module waits on `$.clock`, a
11344 * surface module on `surface.every`).
11345 */
11346 global {
11347 /**
11348 * The JSX factory (classic runtime, `@jsx h`; the engine prepends the
11349 * pragma): a plain-data element from a string tag or a component.
11350 *
11351 * JSX compiles to bare `h(...)` calls resolved by name, so a module (hooks or
11352 * surface) never declares, imports or takes as a parameter anything named
11353 * `h` or `Fragment` where it writes JSX, and carries no `@jsx` pragma of its
11354 * own: either silently points its JSX away from this factory, and a
11355 * `<Client>` tag written under another factory is not found when the
11356 * module's surface modules are read off its source.
11357 */
11358 const h: (
11359 tag: string | ((props: never) => RenderNode | null | undefined),
11360 props: Record<string, unknown> | null | undefined,
11361 ...children: unknown[]
11362 ) => RenderNode | null | undefined
11363
11364 /**
11365 * `<>...</>`: a column Box around the children.
11366 */
11367 const Fragment: (props: { children?: RenderNode[] }) => RenderElement
11368
11369 /**
11370 * JSX over the element table: every tag is a constructor from
11371 * `$.ui.resolve(e)` (`const { Box, Text } = $.ui.resolve(e)`), typed by
11372 * its props; there are no intrinsic (string) tags.
11373 */
11374 namespace JSX {
11375 type Element = RenderElement
11376 type Children = RenderChildren
11377 type ElementType = (props: never) => RenderNode | null | undefined
11378 interface IntrinsicElements {}
11379 interface ElementChildrenAttribute {
11380 children: unknown
11381 }
11382 interface IntrinsicAttributes {
11383 key?: string
11384 }
11385 }
11386
11387 interface AbortSignal {
11388 readonly aborted: boolean
11389 readonly reason: unknown
11390 throwIfAborted(): void
11391 addEventListener(
11392 type: 'abort',
11393 listener: () => void,
11394 options?: { once?: boolean },
11395 ): void
11396 removeEventListener(type: 'abort', listener: () => void): void
11397 }
11398 var AbortSignal: {
11399 prototype: AbortSignal
11400 abort(reason?: unknown): AbortSignal
11401 timeout(milliseconds: number): AbortSignal
11402 any(signals: AbortSignal[]): AbortSignal
11403 }
11404 interface AbortController {
11405 readonly signal: AbortSignal
11406 abort(reason?: unknown): void
11407 }
11408 var AbortController: {
11409 prototype: AbortController
11410 new (): AbortController
11411 }
11412 interface TextEncoder {
11413 readonly encoding: string
11414 encode(input?: string): Uint8Array
11415 }
11416 var TextEncoder: { prototype: TextEncoder; new (): TextEncoder }
11417 interface TextDecoder {
11418 readonly encoding: string
11419 decode(input?: ArrayBufferView | ArrayBuffer): string
11420 }
11421 var TextDecoder: { prototype: TextDecoder; new (label?: string): TextDecoder }
11422 interface URLSearchParams {
11423 append(name: string, value: string): void
11424 delete(name: string): void
11425 get(name: string): string | null
11426 getAll(name: string): string[]
11427 has(name: string): boolean
11428 set(name: string, value: string): void
11429 toString(): string
11430 forEach(callback: (value: string, key: string) => void): void
11431 }
11432 var URLSearchParams: {
11433 prototype: URLSearchParams
11434 new (init?: string | Record<string, string> | string[][]): URLSearchParams
11435 }
11436 interface URL {
11437 hash: string
11438 host: string
11439 hostname: string
11440 href: string
11441 readonly origin: string
11442 password: string
11443 pathname: string
11444 port: string
11445 protocol: string
11446 search: string
11447 readonly searchParams: URLSearchParams
11448 username: string
11449 toString(): string
11450 toJSON(): string
11451 }
11452 var URL: {
11453 prototype: URL
11454 new (url: string, base?: string | URL): URL
11455 canParse(url: string, base?: string): boolean
11456 }
11457 function atob(data: string): string
11458 function btoa(data: string): string
11459 function structuredClone<T>(value: T): T
11460 var crypto: {
11461 readonly subtle: {
11462 digest(
11463 algorithm: string | { name: string },
11464 data: ArrayBufferView | ArrayBuffer,
11465 ): Promise<ArrayBuffer>
11466 }
11467 randomUUID(): string
11468 getRandomValues<T extends ArrayBufferView>(array: T): T
11469 }
11470 var performance: { now(): number }
11471 }
11472}
11473
11474declare module 'claude-code/testing' {
11475 import type { Args } from 'claude-code';
11476 import type { Chunk } from 'claude-code';
11477 import type { ClientKeyEvent } from 'claude-code';
11478 import type { ClientPointerEvent } from 'claude-code';
11479 import type { Elements } from 'claude-code';
11480 import type { EventCalls } from 'claude-code';
11481 import type { EventName } from 'claude-code';
11482 import type { HookStream } from 'claude-code';
11483 import type { JsonValue } from 'claude-code';
11484 import type { On } from 'claude-code';
11485 import type { PressedLink } from 'claude-code';
11486 import type { Register } from 'claude-code';
11487 import type { RenderComponent } from 'claude-code';
11488 import type { RenderElement } from 'claude-code';
11489 import type { RenderPropsOf } from 'claude-code';
11490 import type { RenderSurface } from 'claude-code';
11491 import type { RenderViewport } from 'claude-code';
11492 import type { ResultOf } from 'claude-code';
11493 import type { StreamingEventName } from 'claude-code';
11494 import type { Tier } from 'claude-code';
11495 import type { UiInputArgument } from 'claude-code';
11496 import type { UiInputResult } from 'claude-code';
11497 import type { UiPressResult } from 'claude-code';
11498 import type { UiSelectResult } from 'claude-code';
11499
11500 /**
11501 * A value that matches by a rule inside `toEqual` and its kin
11502 * (`expect.any`, `expect.objectContaining`), known by its text in a failure.
11503 */
11504 export type AsymmetricMatcher = {
11505 readonly text: string;
11506 };
11507
11508 /**
11509 * The same checks on what a promise received settles with, each resolving
11510 * once the promise has settled and the check passed.
11511 */
11512 export type AsyncMatchers = {
11513 [K in keyof Matchers]: (...args: Parameters<Matchers[K]>) => Promise<void>;
11514 };
11515
11516 /**
11517 * Which `Client` of a mounted drawing an act or a read means, by the `key`
11518 * its element carries; optional while the drawing holds exactly one.
11519 */
11520 export type ClientScope = {
11521 in?: string;
11522 };
11523
11524 /**
11525 * A class, as `toThrow`, `toBeInstanceOf` and `expect.any` take it.
11526 */
11527 export type Constructor = abstract new (...args: never[]) => unknown;
11528
11529 /**
11530 * A group of tests: its name leads the title of each test declared inside,
11531 * and its body runs at once, while the file loads.
11532 *
11533 * @param name the group's name
11534 * @param body declares the group's tests
11535 */
11536 export const describe: (name: string, body: () => void) => void;
11537
11538 /**
11539 * The element each surface-dependent act of a mounted drawing reaches: a
11540 * handle carries the act only where the surface's table has the element.
11541 *
11542 * `input` needs `Input` and `select` needs `Select` (every surface but
11543 * mobile today); `key`, `pointer`, `post`, `advance` and `resize` reach a
11544 * `Client` (terminal and desktop today). The rest need nothing but a tree.
11545 */
11546 export type ElementOfAct = {
11547 input: 'Input';
11548 select: 'Select';
11549 key: 'Client';
11550 pointer: 'Client';
11551 post: 'Client';
11552 advance: 'Client';
11553 resize: 'Client';
11554 };
11555
11556 /**
11557 * What a mounted drawing's `find` and `findAll` match an element on, every
11558 * field given at once: its tag, its `key`, and the text it shows.
11559 *
11560 * `text` matches the element's whole shown text (string children, a Button
11561 * or Link's label, a Markdown's text, a Code's source, an Input's value):
11562 * a string by inclusion, a RegExp by test.
11563 *
11564 * @example
11565 * await ui.findAll({ type: 'Text', text: /overdue/, in: 'board' })
11566 */
11567 export type ElementQuery = {
11568 type?: string;
11569 key?: string;
11570 text?: string | RegExp;
11571 /**
11572 * Searches what this `Client`'s surface module drew (by the `Client`'s
11573 * key) instead of the plugin's own tree.
11574 */
11575 in?: string;
11576 };
11577
11578 /**
11579 * What a test holds as `$`, the engine's own: every call on it is made as
11580 * the REPL, the query loop and the render sites make theirs, over every plugin.
11581 *
11582 * `next.origin` is the engine, and the whole chain runs over the plugins
11583 * loaded. A tool call's `tool_use_id` is minted when left out; `$.ui.mount`
11584 * is a surface the test names drawing an instance, `$.ui.press` a press on it.
11585 */
11586 export type Engine = {
11587 [N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress & EngineMount : EngineNoun<N>;
11588 };
11589
11590 /**
11591 * One call on the engine's `$`: the event's input whole, as an engine call
11592 * site passes it, to its result, or for a streaming event to its stream.
11593 */
11594 export type EngineCall<E extends EventName> = E extends StreamingEventName ? (e: Args<E>) => HookStream<Chunk<E>, ResultOf[E]> : (e: Args<E>) => Promise<ResultOf[E]>;
11595
11596 /**
11597 * A surface drawing a component instance through the plugins, then driven
11598 * by key through a handle typed by that surface (Mounted).
11599 *
11600 * `ui.render` raised there for those props, the tree validated by that
11601 * table, its `Client`s running; the reads and `press` on every surface,
11602 * `input` where the table has `Input`, the `Client` acts where `Client`.
11603 *
11604 * @example
11605 * for (const surface of SURFACES) run(await $.ui.mount({ ...HINT, surface }))
11606 */
11607 export type EngineMount = {
11608 /**
11609 * Raises the plugins' drawing of the component on the surface and holds
11610 * it, as that surface showing the instance does.
11611 *
11612 * Resolves once the tree validated and every `Client` in it drew once.
11613 *
11614 * @param target whose elements, the surface, the component, its props,
11615 * the instance's requestId, and what the surface measured
11616 * @returns the mounted drawing; rejects when no `surface` (or an unknown
11617 * one) is named, when the surface cannot draw the tree the chain
11618 * returned (with the reason: an element its table lacks, a prop not
11619 * allowed), or when a `Client`'s module failed or drew nothing
11620 */
11621 mount: <P extends RenderSurface, C extends RenderComponent>(target: MountTarget<P, C>) => Promise<Mounted<P, C>>;
11622 };
11623
11624 /**
11625 * One noun of the engine's `$`: each of its events as the engine calls it,
11626 * `tool.call` and `ui.render` typed per tool and component, `ui.resolve` out.
11627 */
11628 export type EngineNoun<N extends keyof EventCalls> = {
11629 [V in EngineNounEvent<N>]: `${N}.${V}` extends 'tool.call' | 'ui.render' ? EventCalls[N][V] : EngineCall<`${N}.${V}` & EventName>;
11630 };
11631
11632 /**
11633 * The events of one noun a test's `$` carries: every one but `ui.resolve`,
11634 * which a render hook calls on its own `$` and the engine never raises.
11635 */
11636 export type EngineNounEvent<N extends keyof EventCalls> = Exclude<keyof EventCalls[N] & string, `${N}.resolve` extends 'ui.resolve' ? 'resolve' : never>;
11637
11638 /**
11639 * A surface pressing a Button a test rendered, or a Markdown's link: the
11640 * `ui.press` chain over every plugin hooked on it, its own closure last.
11641 */
11642 export type EnginePress = {
11643 /**
11644 * Presses the Button, as a click or its hotkey does; with `link`, the
11645 * Markdown's link, as a click on it does.
11646 *
11647 * `e.surface` is the surface of the drawing that holds it.
11648 *
11649 * @param target whose element, its key, the instance and surface when
11650 * several hold it, and for a Markdown the link
11651 * @returns what the chain settled on; rejects when no such element is
11652 * drawn, or several are and neither instance nor surface tells them apart
11653 */
11654 press: (target: PressTarget) => Promise<UiPressResult | undefined>;
11655 };
11656
11657 /**
11658 * The checks on a value (`expect(received)`), and with them the matchers
11659 * that stand inside an expected value (`expect.any(Number)`).
11660 */
11661 export type Expect = Expecting & Matching;
11662
11663 /**
11664 * Checks a value: `expect(received).toEqual(expected)` throws an
11665 * AssertionError naming both sides when it fails, a message given leading.
11666 *
11667 * `.not` negates; `.resolves` and `.rejects` check what a promise settles
11668 * with; `expect.any(Number)` and its kin stand inside an expected value.
11669 */
11670 export const expect: Expect;
11671
11672 /**
11673 * What `expect(received)` answers: the checks, their negation, and the
11674 * checks on what a promise received resolves or rejects with.
11675 */
11676 export type Expectation = Negatable<Matchers> & {
11677 /**
11678 * The checks on what the promise received resolves with; a rejection
11679 * fails them.
11680 */
11681 resolves: Negatable<AsyncMatchers>;
11682 /**
11683 * The checks on what the promise received rejects with; a resolution
11684 * fails them.
11685 */
11686 rejects: Negatable<AsyncMatchers>;
11687 };
11688
11689 /**
11690 * `expect(received, message?)`: the checks on a value, a message of the
11691 * test's own leading a failure's.
11692 */
11693 export type Expecting = (received: unknown, message?: string) => Expectation;
11694
11695 /**
11696 * One element of a mounted drawing as `find` returns it: the description
11697 * the plugin's hook (or a `Client`'s module) built, read as plain data.
11698 *
11699 * What every surface is handed to draw, not what any surface painted: the
11700 * same on the terminal, the desktop, VS Code and mobile.
11701 */
11702 export type FoundElement = {
11703 /**
11704 * The element's tag: `Box`, `Text`, `Button`, `Input`, `Client`, ...
11705 */
11706 type: string;
11707 /**
11708 * What its props carry as `key`, when they do.
11709 */
11710 key: string | undefined;
11711 /**
11712 * Its props, plain data: a Button's `label`, a Text's `color`, ...;
11713 * handlers never cross (a Button's `onPress` is not here).
11714 */
11715 props: Record<string, unknown>;
11716 /**
11717 * What it shows: its string children in document order and, for the
11718 * leaves that draw a prop as text, that prop (ElementQuery `text`).
11719 */
11720 text: string;
11721 /**
11722 * Its children as drawn: strings and element descriptions.
11723 */
11724 children: unknown[];
11725 };
11726
11727 /**
11728 * The checks `expect(received)` offers; each throws an AssertionError when
11729 * it fails, naming what was expected and what was received.
11730 */
11731 export type Matchers = {
11732 /**
11733 * Passes when received is the value, by `Object.is`.
11734 *
11735 * @param expected the value
11736 */
11737 toBe: (expected: unknown) => void;
11738 /**
11739 * Passes when received equals the value in structure, properties holding
11740 * undefined ignored; `expect.any` and its kin match inside it.
11741 *
11742 * @param expected the value
11743 */
11744 toEqual: (expected: unknown) => void;
11745 /**
11746 * As `toEqual`, but undefined properties and prototypes count.
11747 *
11748 * @param expected the value
11749 */
11750 toStrictEqual: (expected: unknown) => void;
11751 /**
11752 * Passes when received holds at least the object's properties, equal.
11753 *
11754 * @param expected the object
11755 */
11756 toMatchObject: (expected: object) => void;
11757 /**
11758 * Passes when a string received includes the item, or an iterable
11759 * received has an element that is it.
11760 *
11761 * @param item the substring or element
11762 */
11763 toContain: (item: unknown) => void;
11764 /**
11765 * Passes when an iterable received has an element equal to the item.
11766 *
11767 * @param item the element
11768 */
11769 toContainEqual: (item: unknown) => void;
11770 /**
11771 * Passes when received's `length` is the number.
11772 *
11773 * @param length the number
11774 */
11775 toHaveLength: (length: number) => void;
11776 /**
11777 * Passes when received holds a property at the path (`a.b`, or the keys
11778 * in order), equal to the value when one is given.
11779 *
11780 * @param path the property's path
11781 * @param value what it must equal, when given
11782 */
11783 toHaveProperty: (path: string | readonly string[], value?: unknown) => void;
11784 /**
11785 * Passes when received is undefined.
11786 */
11787 toBeUndefined: () => void;
11788 /**
11789 * Passes when received is anything but undefined.
11790 */
11791 toBeDefined: () => void;
11792 /**
11793 * Passes when received is null.
11794 */
11795 toBeNull: () => void;
11796 /**
11797 * Passes when received is truthy.
11798 */
11799 toBeTruthy: () => void;
11800 /**
11801 * Passes when received is falsy.
11802 */
11803 toBeFalsy: () => void;
11804 /**
11805 * Passes when received is NaN.
11806 */
11807 toBeNaN: () => void;
11808 /**
11809 * Passes when received is greater than the bound.
11810 *
11811 * @param bound the bound
11812 */
11813 toBeGreaterThan: (bound: number | bigint) => void;
11814 /**
11815 * Passes when received is the bound or greater.
11816 *
11817 * @param bound the bound
11818 */
11819 toBeGreaterThanOrEqual: (bound: number | bigint) => void;
11820 /**
11821 * Passes when received is less than the bound.
11822 *
11823 * @param bound the bound
11824 */
11825 toBeLessThan: (bound: number | bigint) => void;
11826 /**
11827 * Passes when received is the bound or less.
11828 *
11829 * @param bound the bound
11830 */
11831 toBeLessThanOrEqual: (bound: number | bigint) => void;
11832 /**
11833 * Passes when a string received includes the text, or the pattern matches
11834 * it.
11835 *
11836 * @param pattern the text or pattern
11837 */
11838 toMatch: (pattern: string | RegExp) => void;
11839 /**
11840 * Passes when a string received starts with the prefix.
11841 *
11842 * @param prefix the prefix
11843 */
11844 toStartWith: (prefix: string) => void;
11845 /**
11846 * Passes when a string received ends with the suffix.
11847 *
11848 * @param suffix the suffix
11849 */
11850 toEndWith: (suffix: string) => void;
11851 /**
11852 * Passes when received is an instance of the class.
11853 *
11854 * @param expected the class
11855 */
11856 toBeInstanceOf: (expected: Constructor) => void;
11857 /**
11858 * Passes when calling received throws (or, under `rejects`, the rejection
11859 * is) an error as described: by substring, pattern, class or message.
11860 *
11861 * @param expected the description; any throw passes without one
11862 */
11863 toThrow: (expected?: ThrowExpectation) => void;
11864 };
11865
11866 /**
11867 * The matchers that stand inside an expected value, each matching received
11868 * there by a rule instead of by equality.
11869 */
11870 export type Matching = {
11871 /**
11872 * Matches any instance of the class, a primitive by its wrapper
11873 * (`expect.any(Number)`).
11874 *
11875 * @param expected the class
11876 * @returns the matcher
11877 */
11878 any: (expected: Constructor) => AsymmetricMatcher;
11879 /**
11880 * Matches anything but null and undefined.
11881 *
11882 * @returns the matcher
11883 */
11884 anything: () => AsymmetricMatcher;
11885 /**
11886 * Matches a string that includes the text.
11887 *
11888 * @param text the substring
11889 * @returns the matcher
11890 */
11891 stringContaining: (text: string) => AsymmetricMatcher;
11892 /**
11893 * Matches a string the pattern matches.
11894 *
11895 * @param pattern the pattern, or the source of one
11896 * @returns the matcher
11897 */
11898 stringMatching: (pattern: string | RegExp) => AsymmetricMatcher;
11899 /**
11900 * Matches an object holding at least the shape's properties, equal.
11901 *
11902 * @param shape the properties
11903 * @returns the matcher
11904 */
11905 objectContaining: (shape: object) => AsymmetricMatcher;
11906 /**
11907 * Matches an array holding an element equal to each of the items.
11908 *
11909 * @param items the elements
11910 * @returns the matcher
11911 */
11912 arrayContaining: (items: readonly unknown[]) => AsymmetricMatcher;
11913 };
11914
11915 /**
11916 * The world beneath the plugins, mocked noun by noun: each member registers
11917 * hooks of the test's on `on`, visible where the test calls it.
11918 */
11919 export type Mock = {
11920 /**
11921 * Answers `$.clock` from a clock in memory that moves only when the test
11922 * moves it: `clock.now` reads it, and each wait is held.
11923 *
11924 * A held wait resolves when an advance crosses the time it is due, and is
11925 * dropped when its dispatch aborts; one held past a hook's budget (ten
11926 * seconds of real time) is let go, as a hook that overran.
11927 *
11928 * @param on the test's `on`
11929 * @param options where the clock starts (`now`, 0 when not given)
11930 * @returns the clock: its time, and the calls that move it
11931 */
11932 clock: (on: On, options?: MockClockOptions) => MockClock;
11933 /**
11934 * Answers `$.store` from a store in memory: `get`, `set`, `delete` and
11935 * `keys` over it, as the engine keeps a plugin's own.
11936 *
11937 * @param on the test's `on`
11938 * @param entries what the store holds at the start (nothing when not given)
11939 */
11940 store: (on: On, entries?: Readonly<Record<string, unknown>>) => void;
11941 /**
11942 * Answers `$.env.get` from a set of variables; one not listed is unset.
11943 *
11944 * @param on the test's `on`
11945 * @param variables the environment the plugins read
11946 */
11947 env: (on: On, variables: Readonly<Record<string, string>>) => void;
11948 };
11949
11950 /**
11951 * The world beneath the plugins, mocked noun by noun: `mock.clock`,
11952 * `mock.store` and `mock.env`.
11953 *
11954 * Each registers hooks of the test's on the `on` it is handed, visible where
11955 * the test calls it, and answers its noun from memory.
11956 */
11957 export const mock: Mock;
11958
11959 /**
11960 * The clock `mock.clock` hands back: the time its hooks answer, and the only
11961 * ways it moves.
11962 */
11963 export type MockClock = {
11964 /**
11965 * The time now, in milliseconds: what `$.clock.now()` resolves beneath the
11966 * plugins.
11967 *
11968 * @returns the time
11969 */
11970 now: () => number;
11971 /**
11972 * Moves the clock on, resolving each wait due on the way (`$.clock.sleep`,
11973 * `after`, `every`, this clock's `sleep`) in the order it comes due.
11974 *
11975 * The clock reads each wait's time as it resolves, and what one started
11976 * runs before the next resolves.
11977 *
11978 * @param ms how far to move, in milliseconds
11979 * @returns resolves once the clock is there and the event loop settled
11980 */
11981 advance: (ms: number) => Promise<void>;
11982 /**
11983 * Moves the clock to a time at or past now, as `advance` would.
11984 *
11985 * @param ms the time, in milliseconds
11986 * @returns resolves once the clock is there and the event loop settled
11987 */
11988 set: (ms: number) => Promise<void>;
11989 /**
11990 * Lets what is already under way run as far as it can without the clock
11991 * moving: every wait due now resolves and the event loop settles.
11992 *
11993 * The same as `advance(0)`; the name for the step between starting a
11994 * dispatch unawaited and looking at what it did.
11995 *
11996 * @returns resolves once the event loop settled, the time where it was
11997 */
11998 settle: () => Promise<void>;
11999 /**
12000 * Resolves once the clock has moved this far past now: how a hook of the
12001 * test's answers late.
12002 *
12003 * @param ms how far, in milliseconds
12004 * @returns resolves when an advance crosses that time
12005 */
12006 sleep: (ms: number) => Promise<void>;
12007 };
12008
12009 /**
12010 * Where a mocked clock starts: `now`, in milliseconds (0 when not given).
12011 */
12012 export type MockClockOptions = {
12013 now?: number;
12014 };
12015
12016 /**
12017 * A drawing of component `C` the test mounted on surface `P`: reads over its
12018 * description, acts on its elements by key, `Client` acts where `P` has one.
12019 *
12020 * Narrowed by the `surface` the test passed, as `e.surface` narrows
12021 * `$.ui.resolve(e)`: no `input` on `mobile`, no `key` on `vscode`, whose
12022 * tables (Elements) lack `Input` and `Client`; over a union, their meet.
12023 */
12024 export type Mounted<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
12025 [K in keyof MountedMembers<P, C> as K extends keyof ElementOfAct ? ElementOfAct[K] extends keyof Elements[P] ? K : never : K]: MountedMembers<P, C>[K];
12026 };
12027
12028 /**
12029 * Every member a mounted drawing of component `C` can have; `Mounted<P, C>`
12030 * keeps the ones surface `P` has the element for (ElementOfAct).
12031 *
12032 * Each act resolves once the loop settled and what a plugin invalidated
12033 * was drawn again. The kit exercises the mod (its hooks, its description
12034 * under the surface's rules, its `Client` modules), never a surface's paint.
12035 */
12036 export type MountedMembers<P extends RenderSurface, C extends RenderComponent = RenderComponent> = {
12037 /**
12038 * Where this drawing is, as the test named it.
12039 */
12040 readonly surface: P;
12041 /**
12042 * The tree as last drawn: what the plugins' `ui.render` chain returned
12043 * for this instance, validated by the surface's table, as plain data.
12044 *
12045 * With `in`, what that `Client`'s surface module last drew instead.
12046 *
12047 * @param scope `{ in }`: a `Client`'s key, to read its module's tree
12048 * @returns the tree; rejects with the refusal when the surface could not
12049 * draw what the chain returned, or with a `Client`'s fault line
12050 * @example
12051 * expect(await ui.drawn()).toMatchObject({ type: 'Box' })
12052 */
12053 drawn: (scope?: ClientScope) => Promise<RenderElement>;
12054 /**
12055 * The first element matching the query, outermost first in document
12056 * order, or undefined.
12057 *
12058 * @param query tag, key and shown text to match; `in` to search a Client
12059 * @returns the element's description, or undefined when none matches
12060 * @example
12061 * expect((await ui.find({ key: 'count' }))?.text).toBe('3 notes')
12062 */
12063 find: (query: ElementQuery) => Promise<FoundElement | undefined>;
12064 /**
12065 * Every element matching the query, in document order.
12066 *
12067 * @param query tag, key and shown text to match; `in` to search a Client
12068 * @returns the matching elements' descriptions
12069 * @example
12070 * expect(await ui.findAll({ type: 'Button' })).toHaveLength(2)
12071 */
12072 findAll: (query: ElementQuery) => Promise<FoundElement[]>;
12073 /**
12074 * Presses the Button keyed `key`, as the person activating it on this
12075 * surface does: the `ui.press` chain, the Button's own `onPress` last.
12076 *
12077 * `e.surface` is this drawing's. With `link`, presses that link of the
12078 * Markdown keyed `key` instead. A Button a `Client`'s module drew is
12079 * pressed the same way, by its key.
12080 *
12081 * @param target the key; another plugin's name to press its Button; a link
12082 * @returns what the chain settled on
12083 * @example
12084 * await ui.press({ key: 'save' })
12085 */
12086 press: (target: MountPressTarget) => Promise<UiPressResult | undefined>;
12087 /**
12088 * Types into the Input keyed `key`: the `ui.input` chain with the text as
12089 * `e.value`, the Input's own handler last.
12090 *
12091 * `kind` `submit` (the default) is Enter with that text, `change` an edit
12092 * that leaves it in the field.
12093 *
12094 * @param target the key and the text; `kind`; another plugin's name
12095 * @returns what the chain settled on
12096 * @example
12097 * await ui.input({ key: 'title', text: 'groceries' })
12098 */
12099 input: (target: MountInputTarget) => Promise<UiInputResult | undefined>;
12100 /**
12101 * Picks `value` in the Select keyed `key`: the `ui.select` chain, the
12102 * Select's own `onSelect` last.
12103 *
12104 * @param target the key and the option's value; another plugin's name
12105 * @returns what the chain settled on
12106 * @example
12107 * await ui.select({ key: 'sort', value: 'date' })
12108 */
12109 select: (target: MountSelectTarget) => Promise<UiSelectResult | undefined>;
12110 /**
12111 * Hands a `Client`'s `onKey` listener one key, as a key pressed while
12112 * its region has the focus does.
12113 *
12114 * `in` names the `Client` by key; optional when the drawing holds one.
12115 *
12116 * @param event the key (`{ key: 'right' }`, `{ key: 'a', ctrl: true }`)
12117 * @example
12118 * await ui.key({ key: 'return', in: 'board' })
12119 */
12120 key: (event: MountKeyEvent) => Promise<void>;
12121 /**
12122 * Hands a `Client`'s `onPointer` listener one event, in the cells of its
12123 * region as every surface that draws a `Client` reports them.
12124 *
12125 * @param event the event (`{ type: 'down', x: 3, y: 0, button: 'left' }`)
12126 * @example
12127 * await ui.pointer({ type: 'down', x: 2, y: 0, button: 'left' })
12128 */
12129 pointer: (event: MountPointerEvent) => Promise<void>;
12130 /**
12131 * Posts as a `Client`'s own `surface.post(data)` does: the plugin's
12132 * `ui.message` hooks run with `e.data`, `e.surface` this drawing's.
12133 *
12134 * A `{ props }` they answer reaches the instance, which redraws with
12135 * its state kept.
12136 *
12137 * @param data plain data (JsonValue)
12138 * @param scope `{ in }`: which `Client`, when the drawing holds several
12139 * @example
12140 * await ui.post({ pick: 2 })
12141 */
12142 post: (data: JsonValue, scope?: ClientScope) => Promise<void>;
12143 /**
12144 * Moves the drawing's frame clock on: each `surface.every(ms, fn)` timer
12145 * of its `Client`s fires at every interval of its own the move crosses.
12146 *
12147 * @param ms how far, in milliseconds
12148 * @example
12149 * await ui.advance(250)
12150 */
12151 advance: (ms: number) => Promise<void>;
12152 /**
12153 * Lays a `Client`'s region out at a size, as the surface measuring it
12154 * does: what its module reads as `surface.columns` and `surface.rows`.
12155 *
12156 * @param size cells across and down; `in`: which `Client`
12157 * @example
12158 * await ui.resize({ columns: 40, rows: 3 })
12159 */
12160 resize: (size: MountResizeTarget) => Promise<void>;
12161 /**
12162 * Draws the instance again, as the engine does when its props change (a
12163 * tool row's output arrived): the `ui.render` chain with the next props.
12164 *
12165 * A plugin's own `$.ui.invalidate` needs no call: the drawing follows it
12166 * before the next read.
12167 *
12168 * @param props the component's next props; the current ones when absent
12169 * @example
12170 * await ui.redraw({ ...TOOL_ROW, isRunning: false, output: 'done' })
12171 */
12172 redraw: (props?: RenderPropsOf[C]) => Promise<void>;
12173 /**
12174 * Lets the drawing go, as the surface dropping the instance does: its
12175 * `Client`s and their timers end. Later acts on the handle reject.
12176 *
12177 * @example
12178 * await ui.unmount()
12179 */
12180 unmount: () => Promise<void>;
12181 };
12182
12183 /**
12184 * What a mounted drawing's `input` takes: the Input's key, the text, which
12185 * of the two inputs it is (`submit` when unsaid), another plugin's name.
12186 */
12187 export type MountInputTarget = {
12188 key: string;
12189 text: string;
12190 kind?: UiInputArgument['kind'];
12191 plugin?: string;
12192 };
12193
12194 /**
12195 * What a mounted drawing's `key` takes: the key as a `Client`'s `onKey`
12196 * listener receives it (ClientKeyEvent), and which `Client` when several.
12197 */
12198 export type MountKeyEvent = ClientKeyEvent & ClientScope;
12199
12200 /**
12201 * What a mounted drawing's `pointer` takes: the event as a `Client`'s
12202 * `onPointer` listener receives it, in its region's cells, and which one.
12203 */
12204 export type MountPointerEvent = ClientPointerEvent & ClientScope;
12205
12206 /**
12207 * What a mounted drawing's `press` takes: the Button's key, another
12208 * plugin's name when the Button is not the mounted plugin's, a link.
12209 */
12210 export type MountPressTarget = {
12211 key: string;
12212 plugin?: string;
12213 /**
12214 * Presses this link of the Markdown keyed `key` instead of a Button.
12215 */
12216 link?: PressedLink;
12217 };
12218
12219 /**
12220 * What a mounted drawing's `resize` takes: a `Client` region's size in
12221 * cells, as the surface measuring it hands it, and which `Client`.
12222 */
12223 export type MountResizeTarget = {
12224 columns: number;
12225 rows: number;
12226 in?: string;
12227 };
12228
12229 /**
12230 * What a mounted drawing's `select` takes: the Select's key, the picked
12231 * option's value, another plugin's name when the Select is not its own.
12232 */
12233 export type MountSelectTarget = {
12234 key: string;
12235 value: string;
12236 plugin?: string;
12237 };
12238
12239 /**
12240 * What `$.ui.mount` takes: whose elements the test will act on, the surface
12241 * that draws, and the component instance the engine asks the plugins for.
12242 *
12243 * The envelope a `ui.render` hook sees as `e` (`surface`, `component`,
12244 * `requestId`, `viewport`, `props`) plus `plugin`. `surface` is never
12245 * defaulted: one body run over several surfaces is what shows independence.
12246 *
12247 * @example
12248 * $.ui.mount({ plugin: 'notes', surface, component: 'Pane', props: PANE })
12249 */
12250 export type MountTarget<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
12251 /**
12252 * Whose elements the handle's acts address by bare `key`: the plugin
12253 * under test, usually. An act names another plugin to reach its element.
12254 */
12255 plugin: string;
12256 /**
12257 * What draws: its element table validates every tree the plugins
12258 * return, and every dispatch the handle raises carries it as `e.surface`.
12259 *
12260 * One of `terminal`, `desktop`, `vscode`, `mobile`.
12261 */
12262 surface: P;
12263 /**
12264 * Which component the engine asks the plugins to draw (`Pane`,
12265 * `AbovePrompt`, `ToolUse`, ...): what a `ui.render` matcher narrows on.
12266 */
12267 component: C;
12268 /**
12269 * The component's props, what the hook reads as `e.props`.
12270 */
12271 props: RenderPropsOf[C];
12272 /**
12273 * The instance drawn (a pane's id, a tool row's tool_use_id); one is
12274 * minted when absent. Two mounts of one component are two instances.
12275 */
12276 requestId?: string;
12277 /**
12278 * What the surface measured, as the hook reads it under `e.viewport`;
12279 * absent when the surface has not measured, as on `e`.
12280 *
12281 * Cells across and down in the surface's monospace metric and whether it
12282 * docks a pane. A `Client` in the drawing starts laid out at this size
12283 * (0 by 0 when absent) until the handle's `resize` lays its region out.
12284 */
12285 viewport?: RenderViewport;
12286 };
12287
12288 /**
12289 * A set of checks and, under `not`, the same set passing where they fail.
12290 */
12291 export type Negatable<M> = M & {
12292 /**
12293 * The checks negated.
12294 */
12295 not: M;
12296 };
12297
12298 /**
12299 * Written inline in a test and loaded as a plugin folder is: its name, the
12300 * tier it loads in (`user` when not given), and its hooks module's `register`.
12301 *
12302 * `register` is written `register(on) { ... }` and is self-contained, as a
12303 * module's is: it closes over nothing of the test file.
12304 */
12305 export type Plugin = {
12306 name: string;
12307 tier?: PluginTier;
12308 register: Register;
12309 };
12310
12311 /**
12312 * A tier a plugin loads in: every tier but the engine's own.
12313 */
12314 export type PluginTier = Exclude<Tier, 'core'>;
12315
12316 /**
12317 * What `$.ui.press` takes: the plugin whose `ui.render` hook drew the element,
12318 * the `key` it gave it, the instance and surface when several, a `link`.
12319 */
12320 export type PressTarget = {
12321 plugin: string;
12322 key: string;
12323 /**
12324 * Which instance holds it, when the plugin drew the key in several.
12325 */
12326 requestId?: string;
12327 /**
12328 * Which surface's drawing, when the key is drawn on more than one; the
12329 * press carries the surface of the drawing it lands in either way.
12330 */
12331 surface?: RenderSurface;
12332 /**
12333 * For a Markdown answering its links: which of them the press lands on.
12334 */
12335 link?: PressedLink;
12336 };
12337
12338 /**
12339 * One test: it passes when its body returns or resolves, and fails when it
12340 * throws, rejects or outlasts its time (5000 ms, or `timeoutMs`).
12341 *
12342 * The body gets the engine's `$` and an `on` whose hooks sit beneath every
12343 * plugin; `plugins` load inline plugins beside the one under test. A failure
12344 * carries what the engine reported meanwhile: each hook it skipped, and why.
12345 *
12346 * @param name the test's name, led in its title by the describes around it
12347 * @param rest the body, `($, on) => ...`, or the options then the body
12348 */
12349 export const test: (name: string, ...rest: TestRest) => void;
12350
12351 /**
12352 * A test: the engine's `$`, and `on`, a plugin's registrar, whose hooks sit
12353 * beneath every plugin; beneath them the bottom hook throws, naming its event.
12354 *
12355 * The plugins load at the test's first call on `$`, so a test registers its
12356 * hooks before it, as a module registers its own in `register()`.
12357 */
12358 export type TestBody = ($: Engine, on: On) => unknown;
12359
12360 /**
12361 * What `test` takes beside its name: the inline plugins it loads beside the
12362 * one under test, and how long it may run (5000 ms when not given).
12363 */
12364 export type TestOptions = {
12365 plugins?: readonly Plugin[];
12366 timeoutMs?: number;
12367 };
12368
12369 /**
12370 * What follows a test's name: its body, or its options then its body.
12371 */
12372 export type TestRest = readonly [body: TestBody] | readonly [options: TestOptions, body: TestBody];
12373
12374 /**
12375 * What `toThrow` compares the thrown error with: a substring or pattern of
12376 * its message, its class, a value carrying the whole message, or nothing.
12377 */
12378 export type ThrowExpectation = string | RegExp | Constructor | WithMessage;
12379
12380 /**
12381 * Says which tier the plugin under test loads in, once, at the top of the
12382 * file: `prepend`, `user` (when unsaid), `append` or `builtin`.
12383 *
12384 * @param tier the tier
12385 */
12386 export const tier: (tier: PluginTier) => void;
12387
12388 /**
12389 * An error-like value `toThrow` compares by its whole message.
12390 */
12391 export type WithMessage = {
12392 message: string;
12393 };
12394}
12395
12396// The inputs of the built-in tools this build has, from each tool's
12397// input schema. Merges into ToolCallInput (BuiltinToolInputs) so
12398// `e.tool === "Bash"` narrows to the tool's arguments.
12399declare module 'claude-code' {
12400 interface BuiltinToolInputs {
12401 Agent: {
12402 /** A short (3-5 word) description of the task */
12403 description: string
12404 /** The task for the agent to perform */
12405 prompt: string
12406 /** The type of specialized agent to use for this task */
12407 subagent_type?: string
12408 /** 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. */
12409 model?: "sonnet" | "opus" | "haiku" | "fable"
12410 /** 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. */
12411 run_in_background?: boolean
12412 /** Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running. */
12413 name?: string
12414 /** Deprecated; ignored. The session has a single implicit team. */
12415 team_name?: string
12416 /** Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it. */
12417 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"
12418 /** 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). */
12419 isolation?: "worktree" | "remote"
12420 }
12421 Bash: {
12422 /** The command to execute */
12423 command: string
12424 /** Optional timeout in milliseconds (max 600000) */
12425 timeout?: number
12426 /** 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" */
12427 description?: string
12428 /** Set to true to run this command in the background. */
12429 run_in_background?: boolean
12430 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
12431 dangerouslyDisableSandbox?: boolean
12432 }
12433 CronCreate: {
12434 /** 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). */
12435 cron: string
12436 /** The prompt to enqueue at each fire time. */
12437 prompt: string
12438 /** 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. */
12439 recurring?: boolean
12440 /** 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. */
12441 durable?: boolean
12442 }
12443 CronDelete: {
12444 /** Job ID returned by CronCreate. */
12445 id: string
12446 }
12447 CronList: {}
12448 Edit: {
12449 /** The absolute path to the file to modify */
12450 file_path: string
12451 /** The text to replace */
12452 old_string: string
12453 /** The text to replace it with (must be different from old_string) */
12454 new_string: string
12455 /** Replace all occurrences of old_string (default false) */
12456 replace_all?: boolean
12457 }
12458 EnterWorktree: {
12459 /** 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`. */
12460 name?: string
12461 /** 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`. */
12462 path?: string
12463 }
12464 ExitWorktree: {
12465 /** "keep" leaves the worktree and branch on disk; "remove" deletes both. */
12466 action: "keep" | "remove"
12467 /** Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise. */
12468 discard_changes?: boolean
12469 }
12470 ListAgents: {
12471 /** Not available in this build; leave unset. */
12472 channel?: string
12473 /** Not available in this build; leave unset. */
12474 q?: string
12475 }
12476 NotebookEdit: {
12477 /** The absolute path to the Jupyter notebook file to edit (must be absolute, not relative) */
12478 notebook_path: string
12479 /** 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. */
12480 cell_id?: string
12481 /** The new source for the cell */
12482 new_source: string
12483 /** 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. */
12484 cell_type?: "code" | "markdown"
12485 /** The type of edit to make (replace, insert, delete). Defaults to replace. */
12486 edit_mode?: "replace" | "insert" | "delete"
12487 }
12488 PowerShell: {
12489 /** The PowerShell command to execute */
12490 command: string
12491 /** Optional timeout in milliseconds (max 600000) */
12492 timeout?: number
12493 /** Clear, concise description of what this command does in active voice. */
12494 description?: string
12495 /** Set to true to run this command in the background. */
12496 run_in_background?: boolean
12497 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
12498 dangerouslyDisableSandbox?: boolean
12499 }
12500 Read: {
12501 /** The absolute path to the file to read */
12502 file_path: string
12503 /** The line number to start reading from. Only provide if the file is too large to read at once */
12504 offset?: number
12505 /** The number of lines to read. Only provide if the file is too large to read at once. */
12506 limit?: number
12507 /** Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum 20 pages per request. */
12508 pages?: string
12509 }
12510 ReportFindings: {
12511 /** Effort level the review ran at */
12512 level?: "low" | "medium" | "high" | "xhigh" | "max"
12513 /** Verified findings, most-severe first; empty if none survived */
12514 findings: Array<{
12515 /** Repo-relative path of the file the finding is in */
12516 file: string
12517 /** 1-indexed line the finding anchors to */
12518 line?: number
12519 /** One-sentence statement of the defect */
12520 summary: string
12521 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
12522 short_summary?: string
12523 /** Concrete inputs/state → wrong output/crash */
12524 failure_scenario: string
12525 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
12526 category?: string
12527 /** Set when a verify pass ran; absent on inline-only reviews */
12528 verdict?: "CONFIRMED" | "PLAUSIBLE"
12529 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
12530 outcome?: "fixed" | "skipped" | "no_change_needed"
12531 }>
12532 }
12533 ScheduleWakeup: {
12534 /** Seconds from now to wake up. Clamped to [60, 3600] by the runtime. Required unless `stop` is true. */
12535 delaySeconds?: number
12536 /** One short sentence explaining the chosen delay. Goes to telemetry and is shown to the user. Be specific. Required unless `stop` is true. */
12537 reason?: string
12538 /** 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. */
12539 prompt?: string
12540 /** 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. */
12541 stop?: boolean
12542 /** 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. */
12543 noop?: boolean
12544 }
12545 SendMessage: {
12546 /** 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 */
12547 to: unknown & unknown
12548 /** 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. */
12549 summary?: string
12550 /** 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. */
12551 message: string
12552 /** 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. */
12553 notify_when_idle?: boolean
12554 }
12555 Skill: {
12556 /** The name of a skill from the available-skills list. Do not guess names. */
12557 skill: string
12558 /** Optional arguments for the skill */
12559 args?: string
12560 }
12561 TaskOutput: {
12562 /** The task ID to get output from */
12563 task_id: string
12564 /** Whether to wait for completion */
12565 block: boolean
12566 /** Max wait time in ms */
12567 timeout: number
12568 }
12569 TaskStop: {
12570 /** The ID of the background task to stop. Agent-team teammates and named background agents are also accepted by agent ID or name. */
12571 task_id?: string
12572 /** Deprecated: use task_id instead */
12573 shell_id?: string
12574 }
12575 ToolSearch: {
12576 /** Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search. */
12577 query: string
12578 /** Maximum number of results to return (default: 5) */
12579 max_results: number
12580 }
12581 WebFetch: {
12582 /** The URL to fetch content from */
12583 url: string
12584 /** The prompt to run on the fetched content */
12585 prompt: string
12586 }
12587 WebSearch: {
12588 /** The search query to use */
12589 query: string
12590 /** Only include search results from these domains */
12591 allowed_domains?: string[]
12592 /** Never include search results from these domains */
12593 blocked_domains?: string[]
12594 }
12595 Workflow: {
12596 /** 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(). */
12597 script?: string
12598 /** Name of a predefined workflow (built-in or from .claude/workflows/). Resolves to a self-contained script. */
12599 name?: string
12600 /** Ignored — set the workflow description in the script's `meta` block. */
12601 description?: string
12602 /** Ignored — set the workflow title in the script's `meta` block. */
12603 title?: string
12604 /** 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). */
12605 args?: unknown
12606 /** 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`. */
12607 scriptPath?: string
12608 /** 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. */
12609 resumeFromRunId?: string
12610 }
12611 Write: {
12612 /** The absolute path to the file to write (must be absolute, not relative) */
12613 file_path: string
12614 /** The content to write to the file */
12615 content: string
12616 }
12617 }
12618}
12619
12620// The structured results of the same tools, from each tool's output
12621// schema. Merges into ToolCallResult (BuiltinToolResults) so after
12622// `e.tool === "Bash"` the `result` of `next(e)` is the tool's record.
12623declare module 'claude-code' {
12624 interface BuiltinToolResults {
12625 Agent: {
12626 agentId: string
12627 /** @internal Count of leading harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
12628 harnessNoteCount?: number
12629 /** @internal Count of trailing harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
12630 harnessTailCount?: number
12631 /** @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 */
12632 harnessSectionHash?: string
12633 agentType?: string
12634 /** @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) */
12635 handback?: "send" | "flagged" | "withheld"
12636 content: Array<{
12637 type: "text"
12638 text: string
12639 citations?: unknown[] | null
12640 }>
12641 resolvedModel?: string
12642 modelsUsed?: string[]
12643 totalToolUseCount: number
12644 totalDurationMs: number
12645 totalTokens: number
12646 usage: {
12647 input_tokens: number
12648 output_tokens: number
12649 cache_creation_input_tokens: number | null
12650 cache_read_input_tokens: number | null
12651 server_tool_use: {
12652 web_search_requests: number
12653 web_fetch_requests: number
12654 } | null
12655 service_tier: string | null
12656 cache_creation: {
12657 ephemeral_1h_input_tokens: number
12658 ephemeral_5m_input_tokens: number
12659 } | null
12660 inference_geo?: string | null
12661 speed?: string | null
12662 iterations?: unknown
12663 output_tokens_details?: {
12664 thinking_tokens?: number | null
12665 } | null
12666 }
12667 toolStats?: {
12668 readCount: number
12669 searchCount: number
12670 bashCount: number
12671 editFileCount: number
12672 linesAdded: number
12673 linesRemoved: number
12674 otherToolCount: number
12675 frameCount?: number
12676 }
12677 status: "completed"
12678 prompt: string
12679 worktreePath?: string
12680 worktreeBranch?: string
12681 } | {
12682 status: "async_launched"
12683 isAsync?: true
12684 /** The ID of the async agent */
12685 agentId: string
12686 /** The description of the task */
12687 description: string
12688 /** Model in use at the backgrounding transition (a pre-background swap is reflected here) */
12689 resolvedModel?: string
12690 /** Ordered distinct models used before backgrounding (length > 1 means a mid-run swap) */
12691 modelsUsed?: string[]
12692 /** The prompt for the agent */
12693 prompt: string
12694 /** Path to the output file for checking agent progress */
12695 outputFile: string
12696 /** Whether the calling agent has Read/Bash tools to check progress */
12697 canReadOutputFile?: boolean
12698 } | {
12699 status: "remote_launched"
12700 /** The ID of the remote agent task */
12701 taskId: string
12702 /** The URL of the cloud session */
12703 sessionUrl: string
12704 /** The description of the task */
12705 description: string
12706 /** The prompt for the agent */
12707 prompt: string
12708 /** Path to the output file for checking agent progress */
12709 outputFile: string
12710 }
12711 Bash: {
12712 /** The standard output of the command */
12713 stdout: string
12714 /** The standard error output of the command */
12715 stderr: string
12716 /** Path to raw output file for large MCP tool outputs */
12717 rawOutputPath?: string
12718 /** Whether the command was interrupted */
12719 interrupted: boolean
12720 /** Flag to indicate if stdout contains image data */
12721 isImage?: boolean
12722 /** ID of the background task if command is running in background */
12723 backgroundTaskId?: string
12724 /** True if the user manually backgrounded the command with Ctrl+B */
12725 backgroundedByUser?: boolean
12726 /** @internal True if a plugin's turn abort moved the running command to the background */
12727 backgroundedByTurnAbort?: boolean
12728 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
12729 backgroundedToDeliverMessage?: boolean
12730 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
12731 timedOutAfterMs?: number
12732 /** Model-facing note that the session cwd was not changed by a backgrounded command containing a directory-change builtin (cd/pushd/popd/chdir) */
12733 backgroundCwdHint?: string
12734 /** 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) */
12735 backgroundEndsWithFinalResponse?: true
12736 /** Flag to indicate if sandbox mode was overridden */
12737 dangerouslyDisableSandbox?: boolean
12738 /** Semantic interpretation for non-error exit codes with special meaning */
12739 returnCodeInterpretation?: string
12740 /** Whether the command is expected to produce no output on success */
12741 noOutputExpected?: boolean
12742 /** Structured content blocks */
12743 structuredContent?: unknown[]
12744 /** Path to the persisted full output in tool-results dir (set when output is too large for inline) */
12745 persistedOutputPath?: string
12746 /** Total size of the output in bytes (set when output is too large for inline) */
12747 persistedOutputSize?: number
12748 /** Model-facing note listing readFileState entries whose mtime bumped during this command (set when WRITE_COMMAND_MARKERS matches) */
12749 staleReadFileStateHint?: string
12750 /** Model-facing system-reminder appended when a gh command reports a GitHub API rate-limit error */
12751 ghRateLimitHint?: string
12752 /** 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. */
12753 gitOperation?: {
12754 commit?: {
12755 sha: string
12756 kind: "committed" | "amended" | "cherry-picked"
12757 branch?: string
12758 }
12759 push?: {
12760 branch: string
12761 }
12762 branch?: {
12763 ref: string
12764 action: "merged" | "rebased"
12765 }
12766 pr?: {
12767 number: number
12768 url?: string
12769 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
12770 }
12771 }
12772 /** @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. */
12773 bashEditDiff?: {
12774 files: {
12775 filePath: string
12776 hunks: {
12777 oldStart: number
12778 oldLines: number
12779 newStart: number
12780 newLines: number
12781 lines: string[]
12782 }[]
12783 created?: true
12784 deleted?: true
12785 }[]
12786 moreFiles: number
12787 changedFiles?: string[]
12788 unavailable?: true
12789 skipped?: true
12790 shared?: true
12791 }
12792 }
12793 CronCreate: {
12794 id: string
12795 humanSchedule: string
12796 recurring: boolean
12797 durable?: boolean
12798 }
12799 CronDelete: {
12800 id: string
12801 }
12802 CronList: {
12803 jobs: {
12804 id: string
12805 cron: string
12806 humanSchedule: string
12807 prompt: string
12808 recurring?: boolean
12809 durable?: boolean
12810 }[]
12811 }
12812 Edit: {
12813 /** The file path that was edited */
12814 filePath: string
12815 /** The original string that was replaced */
12816 oldString: string
12817 /** The new string that replaced it */
12818 newString: string
12819 /** The original file contents before editing */
12820 originalFile: string | null
12821 /** Diff patch showing the changes */
12822 structuredPatch: {
12823 oldStart: number
12824 oldLines: number
12825 newStart: number
12826 newLines: number
12827 lines: string[]
12828 }[]
12829 /** Whether the user modified the proposed changes */
12830 userModified: boolean
12831 /** Whether all occurrences were replaced */
12832 replaceAll: boolean
12833 gitDiff?: {
12834 filename: string
12835 status: "modified" | "added"
12836 additions: number
12837 deletions: number
12838 changes: number
12839 patch: string
12840 /** GitHub owner/repo when available */
12841 repository?: string | null
12842 }
12843 /** True when the edit was held for the machine owner to review instead of written; the file is unchanged */
12844 staged?: boolean
12845 }
12846 EnterWorktree: {
12847 worktreePath: string
12848 worktreeBranch?: string
12849 message: string
12850 }
12851 ExitWorktree: {
12852 action: "keep" | "remove"
12853 originalCwd: string
12854 worktreePath: string
12855 worktreeBranch?: string
12856 tmuxSessionName?: string
12857 discardedFiles?: number
12858 discardedCommits?: number
12859 message: string
12860 }
12861 ListAgents: {
12862 /** Formatted list of reachable agents */
12863 listing: string
12864 }
12865 NotebookEdit: {
12866 /** The new source code that was written to the cell */
12867 new_source: string
12868 /** The previous cell source (replace/delete only). Enables cell-relative diff rendering without re-reading the notebook. */
12869 old_source?: string
12870 /** The ID of the cell that was edited */
12871 cell_id?: string
12872 /** The type of the cell */
12873 cell_type: "code" | "markdown"
12874 /** The programming language of the notebook */
12875 language: string
12876 /** The edit mode that was used */
12877 edit_mode: string
12878 /** Error message if the operation failed */
12879 error?: string
12880 /** The path to the notebook file */
12881 notebook_path: string
12882 /** The original notebook content before modification */
12883 original_file: string
12884 /** The updated notebook content after modification */
12885 updated_file: string
12886 }
12887 PowerShell: {
12888 /** The standard output of the command */
12889 stdout: string
12890 /** The standard error output of the command */
12891 stderr: string
12892 /** Whether the command was interrupted */
12893 interrupted: boolean
12894 /** Semantic interpretation for non-error exit codes with special meaning */
12895 returnCodeInterpretation?: string
12896 /** Flag to indicate if stdout contains image data */
12897 isImage?: boolean
12898 /** Path to persisted full output when too large for inline */
12899 persistedOutputPath?: string
12900 /** Total output size in bytes when persisted */
12901 persistedOutputSize?: number
12902 /** ID of the background task if command is running in background */
12903 backgroundTaskId?: string
12904 /** True if the user manually backgrounded the command with Ctrl+B */
12905 backgroundedByUser?: boolean
12906 /** @internal True if a plugin's turn abort moved the running command to the background */
12907 backgroundedByTurnAbort?: boolean
12908 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
12909 backgroundedToDeliverMessage?: boolean
12910 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
12911 timedOutAfterMs?: number
12912 /** 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) */
12913 backgroundEndsWithFinalResponse?: true
12914 /** 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. */
12915 gitOperation?: {
12916 commit?: {
12917 sha: string
12918 kind: "committed" | "amended" | "cherry-picked"
12919 branch?: string
12920 }
12921 push?: {
12922 branch: string
12923 }
12924 branch?: {
12925 ref: string
12926 action: "merged" | "rebased"
12927 }
12928 pr?: {
12929 number: number
12930 url?: string
12931 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
12932 }
12933 }
12934 }
12935 Read: {
12936 type: "text"
12937 file: {
12938 /** The path to the file that was read */
12939 filePath: string
12940 /** The content of the file */
12941 content: string
12942 /** Number of lines in the returned content */
12943 numLines: number
12944 /** The starting line number */
12945 startLine: number
12946 /** Total number of lines in the file */
12947 totalLines: number
12948 /** 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). */
12949 truncatedByTokenCap?: boolean
12950 }
12951 /** Set when this Read completed a saved Artifact source file: the Artifact and the version of it that now counts as viewed. */
12952 artifactRead?: {
12953 slug: string
12954 ver: string
12955 }
12956 } | {
12957 type: "image"
12958 file: {
12959 /** Base64-encoded image data */
12960 base64: string
12961 /** The MIME type of the image */
12962 type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
12963 /** Original file size in bytes */
12964 originalSize: number
12965 /** Image dimension info for coordinate mapping */
12966 dimensions?: {
12967 /** Original image width in pixels */
12968 originalWidth?: number
12969 /** Original image height in pixels */
12970 originalHeight?: number
12971 /** Displayed image width in pixels (after resizing) */
12972 displayWidth?: number
12973 /** Displayed image height in pixels (after resizing) */
12974 displayHeight?: number
12975 }
12976 }
12977 } | {
12978 type: "notebook"
12979 file: {
12980 /** The path to the notebook file */
12981 filePath: string
12982 /** Array of notebook cells */
12983 cells: unknown[]
12984 }
12985 } | {
12986 type: "pdf"
12987 file: {
12988 /** The path to the PDF file */
12989 filePath: string
12990 /** Base64-encoded PDF data */
12991 base64: string
12992 /** Original file size in bytes */
12993 originalSize: number
12994 }
12995 } | {
12996 type: "parts"
12997 file: {
12998 /** The path to the PDF file */
12999 filePath: string
13000 /** Original file size in bytes */
13001 originalSize: number
13002 /** Number of pages extracted */
13003 count: number
13004 /** Directory containing extracted page images */
13005 outputDir: string
13006 }
13007 /** Document page number of the first extracted page (1 when no range was requested); labels the page images in the model-facing tool_result */
13008 firstPage?: number
13009 /** 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 */
13010 pages?: Array<{
13011 /** Base64-encoded page image; empty when the page could not be processed */
13012 base64: string
13013 /** The MIME type of the image */
13014 mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
13015 /** Why the page could not be processed as an image; set only when base64 is empty */
13016 error?: string
13017 }>
13018 } | {
13019 type: "file_unchanged"
13020 file: {
13021 /** The path to the file */
13022 filePath: string
13023 }
13024 /** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result */
13025 source?: "seeded"
13026 }
13027 ReportFindings: {
13028 /** Number of findings reported */
13029 count: number
13030 /** Effort level the review ran at */
13031 level?: "low" | "medium" | "high" | "xhigh" | "max"
13032 /** Echoed for the result body */
13033 findings: Array<{
13034 /** Repo-relative path of the file the finding is in */
13035 file: string
13036 /** 1-indexed line the finding anchors to */
13037 line?: number
13038 /** One-sentence statement of the defect */
13039 summary: string
13040 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
13041 short_summary?: string
13042 /** Concrete inputs/state → wrong output/crash */
13043 failure_scenario: string
13044 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
13045 category?: string
13046 /** Set when a verify pass ran; absent on inline-only reviews */
13047 verdict?: "CONFIRMED" | "PLAUSIBLE"
13048 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
13049 outcome?: "fixed" | "skipped" | "no_change_needed"
13050 }>
13051 }
13052 ScheduleWakeup: {
13053 /** Epoch ms timestamp when the next wakeup will fire */
13054 scheduledFor: number
13055 /** Actual delay used after clamping to runtime bounds */
13056 clampedDelaySeconds: number
13057 /** True if the requested delaySeconds was outside [60, 3600] */
13058 wasClamped: boolean
13059 /** True when the model ended the loop via `stop: true` */
13060 stopped?: boolean
13061 /** How many pending dynamic-loop wakeups stop:true cancelled. 0 means nothing was pending — a recurring /loop cron is not cancelled by stop:true. */
13062 cancelledWakeups?: number
13063 }
13064 SendMessage: unknown
13065 Skill: {
13066 /** Whether the skill is valid */
13067 success: boolean
13068 /** The name of the skill */
13069 commandName: string
13070 /** Tools allowed by this skill */
13071 allowedTools?: string[]
13072 /** Resolved model the skill turn runs on when a frontmatter model override took effect; omitted otherwise */
13073 model?: string
13074 /** Execution status */
13075 status?: "inline"
13076 /** True when the skill instructions were loaded read-only (nothing was executed) */
13077 readOnly?: boolean
13078 } | {
13079 /** Whether the skill completed successfully */
13080 success: boolean
13081 /** The name of the skill */
13082 commandName: string
13083 /** Execution status */
13084 status: "forked"
13085 /** The ID of the sub-agent that executed the skill */
13086 agentId: string
13087 /** The result from the forked skill execution */
13088 result: string
13089 /** True when the sub-agent was launched in the background: `result` describes the launch, and the skill outcome arrives later as a task notification. */
13090 background?: boolean
13091 }
13092 TaskOutput: unknown
13093 TaskStop: {
13094 /** Status message about the operation */
13095 message: string
13096 /** The ID of the task that was stopped */
13097 task_id: string
13098 /** The type of the task that was stopped */
13099 task_type: string
13100 /** The command or description of the stopped task */
13101 command?: string
13102 }
13103 ToolSearch: {
13104 matches: string[]
13105 query: string
13106 total_deferred_tools: number
13107 pending_mcp_servers?: string[]
13108 failed_mcp_servers?: {
13109 name: string
13110 errorCode?: string
13111 error?: string
13112 }[]
13113 }
13114 WebFetch: {
13115 /** Size of the fetched content in bytes */
13116 bytes: number
13117 /** HTTP response code */
13118 code: number
13119 /** HTTP response code text */
13120 codeText: string
13121 /** Processed result from applying the prompt to the content */
13122 result: string
13123 /** Time taken to fetch and process the content */
13124 durationMs: number
13125 /** The URL that was fetched */
13126 url: string
13127 artifactRead?: {
13128 slug: string
13129 ver?: string
13130 seeded?: false
13131 }
13132 }
13133 WebSearch: {
13134 /** The search query that was executed */
13135 query: string
13136 /** Search results and/or text commentary from the model */
13137 results: Array<{
13138 /** ID of the tool use */
13139 tool_use_id: string
13140 /** Array of search hits */
13141 content: Array<{
13142 /** The title of the search result */
13143 title: string
13144 /** The URL of the search result */
13145 url: string
13146 }>
13147 } | string>
13148 /** Time taken to complete the search operation */
13149 durationSeconds: number
13150 /** Number of web searches performed */
13151 searchCount?: number
13152 }
13153 Workflow: {
13154 status: "async_launched" | "remote_launched"
13155 taskId: string
13156 /** 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. */
13157 taskType?: "local_workflow" | "remote_agent"
13158 /** 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. */
13159 workflowName?: string
13160 /** 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. */
13161 runId?: string
13162 summary?: string
13163 /** Directory where subagent transcripts are written during execution */
13164 transcriptDir?: string
13165 /** Path to the persisted workflow script for this invocation. Editable via Write/Edit; pass back as `scriptPath` to re-run without resending the script. */
13166 scriptPath?: string
13167 /** CCR session URL when status is remote_launched */
13168 sessionUrl?: string
13169 /** Non-blocking heads-up (e.g. local git state diverges from the pushed branch the cloud session will clone) */
13170 warning?: string
13171 /** Set if syntax check failed */
13172 error?: string
13173 }
13174 Write: {
13175 /** Whether a new file was created or an existing file was updated */
13176 type: "create" | "update"
13177 /** The path to the file that was written */
13178 filePath: string
13179 /** The content that was written to the file */
13180 content: string
13181 /** 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) */
13182 structuredPatch: {
13183 oldStart: number
13184 oldLines: number
13185 newStart: number
13186 newLines: number
13187 lines: string[]
13188 }[]
13189 /** The original file content before the write (null for new files, or when the previous content was too large to include) */
13190 originalFile: string | null
13191 gitDiff?: {
13192 filename: string
13193 status: "modified" | "added"
13194 additions: number
13195 deletions: number
13196 changes: number
13197 patch: string
13198 /** GitHub owner/repo when available */
13199 repository?: string | null
13200 }
13201 /** True when the user edited the proposed content in the permission dialog before accepting */
13202 userModified?: boolean
13203 /** True when the write was held for the machine owner to review instead of written; the file is unchanged */
13204 staged?: boolean
13205 }
13206 }
13207}