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
10,772 lines · 398.0 KBRaw
1// Written by Claude Code 2.1.273.
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.
8//
9// What is here: the module a hooks module may import types from,
10// import type { Register, On, EngineInterface } from 'claude-code'
11// (at run time the import is empty), and the globals a hooks module has:
12// `h` and `Fragment` (what JSX compiles against), the JSX namespace, and
13// the environment's web APIs (URL, TextEncoder, AbortController,
14// crypto.subtle, ...). A hooks module runs in an environment of its own:
15// no DOM, no Node. The elements a render hook draws with (`Box`, `Text`,
16// `Button`, ...) are not globals: they come from the surface's table,
17// const { Box, Text } = $.ui.resolve(e)
18//
19// Also here: 'claude-code/testing', the kit a plugin's *.test.ts and
20// *.test.tsx files import under `claude plugin test <dir>`, which runs each
21// in an environment like the one a plugin's hooks run in (no fs, network or
22// process), the plugin loaded from the folder by the engine's own host:
23// `test(name, async ($, on) => { ... })`, where `$` is the engine's own
24// and the hooks `on` registers sit beneath every plugin; with describe,
25// expect, tier, and `mock`, whose clock, store and env answer those nouns
26// beneath the plugins from memory.
27//
28// Typing a plugin against it:
29// export const register: Register = (on, options) => { ... }
30// or, in a .js module,
31// /** @type {import('claude-code').Register} */
32// export const register = (on, options) => { ... }
33//
34// A tsconfig.json (or jsconfig.json) that fits a hooks module:
35// {
36// "compilerOptions": {
37// "target": "es2023", "lib": ["es2023"], "types": [],
38// "module": "esnext", "moduleResolution": "bundler",
39// "strict": true, "noUncheckedIndexedAccess": true,
40// "noEmit": true, "skipLibCheck": true,
41// "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment"
42// },
43// "include": [".claude/types", "hooks", "tests"]
44// }
45// ".claude/types" is where /plugin-types writes this file and, beside it,
46// claude-code-mcp.d.ts and claude-code-plugins.d.ts, the index of the
47// enabled plugins' type contracts, each copied to claude-code-plugins/
48// <plugin>.d.ts: what a plugin adds to `$` in engine.create, so a plugin
49// you depend on is typed with nothing copied (the include above takes the
50// whole folder). "hooks" is the plugin's hooks/ folder and "tests" its test
51// files. `lib` names no DOM: the environment has none, and its `Text`
52// would shadow the element.
53//
54// A plugin that adds a noun to `$` ships its own contract: a .d.ts its
55// plugin.json names as "types", exporting the noun's types at its top level
56// and declaring the noun on the engine's interface,
57// export type Topo = { ... }
58// declare module 'claude-code' {
59// interface EngineInterface { topo: Topo }
60// }
61// with no import or reference, its exported names led by the noun's
62// PascalCase name; the plugin's own hooks module imports them from it.
63
64declare module 'claude-code' {
65 /**
66 * What an Agent call a plugin raised (`$.tool.call({ tool: "Agent", ... })`)
67 * answers as `result` once the agent settles; `text` is its final answer.
68 *
69 * A plugin's spawn always runs in the background, so the call resolves with
70 * this record and not the Agent tool's own (BuiltinToolResults), which is
71 * what a model's Agent call carries at `tool.call`.
72 */
73 export type AgentCallRecord = {
74 /**
75 * The spawned agent's id, as `$.agent.list()` names it.
76 */
77 agentId: string;
78 /**
79 * The model the agent resolved to, when one is known.
80 */
81 resolvedModel?: string;
82 };
83
84 /**
85 * One agent loop of this session as `$.agent.list()` returns it: a subagent
86 * or an in-process teammate.
87 */
88 export type AgentInfo = {
89 /**
90 * The agent's id: the same string its loop's `tool.call` events carry as
91 * `agentId`, and a spawn inside it as `parentAgentId`.
92 */
93 id: string;
94 /**
95 * Its row's label.
96 */
97 description: string;
98 /**
99 * The agent definition it runs as (`general-purpose`, `Explore`, ...), or
100 * `teammate` for an in-process teammate.
101 */
102 type: string;
103 /**
104 * `running`, `completed`, `failed`, `killed`, or another of the engine's task
105 * statuses.
106 */
107 status: string;
108 /**
109 * The id of the subagent whose loop spawned it; absent when the main loop
110 * did.
111 */
112 parentId?: string;
113 /**
114 * The plugin whose `$.agent.spawn` (or Agent `$.tool.call`) started it;
115 * absent when the model or the person did.
116 *
117 * The origin axis: which plugin caused it, whichever loop that hook ran in.
118 */
119 spawnedBy?: string;
120 /**
121 * What SendMessage addresses it by (`Agent({ name })`, or the engine's own
122 * for a background agent), when it has one; not `description` or `type`.
123 */
124 name?: string;
125 };
126
127 /**
128 * Which model loop an event happened in: the loop's agent id inside a
129 * subagent's or a teammate's loop, absent on the main loop.
130 *
131 * The agent axis, not the origin axis: `next.origin` names the plugin whose
132 * hook frame caused the dispatch (the recursion skip), whichever loop it ran
133 * in; `agentId` names the loop, whoever caused the call.
134 */
135 export type AgentLoop = {
136 /**
137 * The id of the loop this call runs in: for a subagent or a teammate, the
138 * `id` `$.agent.list()` gives it; absent on the main loop.
139 *
140 * A workflow's agents and the engine's own forks (compaction, memory) carry
141 * ids no list names. Pinned: a different value is refused, one left out is
142 * kept. Which loop, not which plugin caused it (that is `next.origin`).
143 */
144 agentId?: string;
145 };
146
147 /**
148 * The input of `agent.offer`: one agent type, at the moment the engine
149 * offers it to the model.
150 *
151 * Listed for the model (the agent listing) or named by it at dispatch
152 * (`subagent_type`): the same event at each.
153 */
154 export type AgentOfferInput = {
155 /**
156 * Which type (`Explore`, `Plan`, a plugin's agent); the key a matcher
157 * narrows on.
158 */
159 agent: string;
160 /**
161 * Its listing line's text as the definition states it (`whenToUse`).
162 */
163 description: string;
164 /**
165 * Where the definition came from (`built-in`, `plugin`, a settings
166 * source), so a matcher tells a built-in from a user's agent of its name.
167 */
168 source: string;
169 /**
170 * Who provides this agent: the plugin and its tier; `{ plugin: "engine",
171 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
172 */
173 provider: Origin;
174 };
175
176 /**
177 * What an `agent.offer` hook returns: whether the model is offered the agent
178 * type, in its listing and at dispatch.
179 */
180 export type AgentOfferResult = {
181 isOffered: boolean;
182 };
183
184 /**
185 * `agent.spawn`'s input as the call takes it: what the Agent tool's caller
186 * says; the engine fills the rest.
187 *
188 * A call's spawn runs in the background: it resolves once the subagent
189 * started, and nothing holds it in the foreground.
190 */
191 export type AgentSpawnArgs = Pick<AgentSpawnInput, 'prompt'> & Partial<Pick<AgentSpawnInput, 'description' | 'subagentType' | 'model' | 'name' | 'cwd'>>;
192
193 /**
194 * The input of `agent.spawn`: what the Agent tool decided about the
195 * subagent it is about to start, before its model is resolved.
196 *
197 * A hook rewrites content (prompt, description, subagentType, model,
198 * background, cwd), read back as the tool's parameters; tool_use_id, name,
199 * fork, parentModel, permissionMode, parentAgentId and provider are pinned.
200 */
201 export type AgentSpawnInput = {
202 /**
203 * The Agent tool call this spawn belongs to (for `$.ui.notice`). Pinned:
204 * the spawn's identity.
205 */
206 tool_use_id: string;
207 /**
208 * The task the subagent is given: the Agent tool's `prompt` parameter. A
209 * rewrite is the prompt the subagent runs with.
210 */
211 prompt: string;
212 /**
213 * The Agent tool's short `description` of the task (a few words). A rewrite
214 * is what the task shows as.
215 */
216 description: string;
217 /**
218 * The resolved agent type (`general-purpose`, `Explore`, a plugin's agent,
219 * `fork`). A rewrite names another agent this call can dispatch, exactly.
220 *
221 * That definition is the one spawned; a name matching none refuses the
222 * spawn, and a fork dispatches no other.
223 */
224 subagentType: string;
225 /**
226 * Who provides this agent: the plugin and its tier; `{ plugin: "engine",
227 * tier: "core" }` for a built-in. Pinned with the spawn's identity.
228 */
229 provider: Origin;
230 /**
231 * The Agent tool's `model` parameter as given, an alias (`haiku`) or a
232 * full id; undefined lets the agent's own model, then the parent's, decide.
233 *
234 * Ignored for forks, which always inherit. A hook sets this to pick the
235 * subagent's model.
236 */
237 model?: string;
238 /**
239 * The parent's effective model, what `inherit` resolves to. Pinned: a fact
240 * of the parent (set `model` to change what the subagent runs on).
241 */
242 parentModel: string;
243 /**
244 * The id of the loop the spawn happens in (its `tool.call` `agentId`; for a
245 * subagent or teammate its `$.agent.list()` id); absent from main.
246 *
247 * Pinned: a different value is refused, one left out is kept. The agent
248 * axis, not the origin: `next.origin` names the plugin whose hook frame
249 * caused the spawn, this names the model loop it happened in.
250 */
251 parentAgentId?: string;
252 /**
253 * The parent's permission mode (`default`, `acceptEdits`, `plan`, ...), which
254 * the subagent inherits. Pinned: a fact of the parent.
255 */
256 permissionMode?: string;
257 /**
258 * True when the subagent will run in the background (or remotely). A
259 * rewrite is read back as the call's `run_in_background`.
260 *
261 * The agent's own definition and remote isolation can still force it on,
262 * and disabled background tasks force it off.
263 */
264 background: boolean;
265 /**
266 * True for a fork of the parent: it inherits the parent's context and model,
267 * and `model` is ignored. Pinned: the spawn's identity.
268 */
269 fork: boolean;
270 /**
271 * Given by the call (`Agent({ name })`, addressable by SendMessage);
272 * undefined when unnamed. Pinned: the address the parent routes by.
273 */
274 name?: string;
275 /**
276 * The directory the subagent runs in when the call set one (`cwd`); undefined
277 * means the parent's. A rewrite is where the subagent runs.
278 */
279 cwd?: string;
280 };
281
282 /**
283 * What an `agent.spawn` hook returns and what `next(e)` resolves to: the
284 * started subagent's `{ model, agentId }`, or `{ deny: reason }`, refusing it.
285 *
286 * It and `$.agent.spawn(input)` resolve once the subagent started; its answer
287 * is its own `turn.complete`, carrying this `agentId`. Keep the id and set
288 * `got[agentId]` to what waits; a `turn.complete` hook resolves it:
289 *
290 * @example
291 * on("turn.complete", ($, e, next) => (got[e.agentId]?.(e.answer), next(e)))
292 */
293 export type AgentSpawnResult = {
294 /**
295 * What the subagent runs on: from core the resolved id; from a hook an
296 * alias (`haiku`) or an id.
297 */
298 model: string;
299 /**
300 * The started subagent's id: the same string its loop's `tool.call`
301 * events carry as `agentId` and `$.agent.list()` lists it by.
302 *
303 * Set by core; a hook that answers without `next` started none.
304 */
305 agentId?: string;
306 deny?: undefined;
307 } | {
308 /**
309 * Refuses the spawn, so nothing starts; the model sees the text as the
310 * Agent tool's error.
311 */
312 deny: string;
313 model?: undefined;
314 agentId?: undefined;
315 };
316
317 /**
318 * The hook `on("*", hook)` takes: it runs on every event, plugin nouns no
319 * declaration names included, so `e` is `unknown` and `next` is StarNext.
320 *
321 * Until `next.is(pattern, e)` narrows `e`, all a hook can do with it is pass
322 * it on, time it, log it, or fail it; once narrowed it is an ordinary hook on
323 * those events.
324 *
325 * @param $ the engine interface; at `engine.create` the empty table, so a hook
326 * that reads `$` tests `next.is("engine.create", e)` first
327 */
328 export type AnyEventHook = ($: EngineInterface, e: unknown, next: StarNext) => unknown;
329
330 /**
331 * Every key of every variant, index signatures included.
332 */
333 type AnyKeyOf<I> = I extends unknown ? keyof I : never;
334
335 /**
336 * The argument of event `N`: `e` in its hooks, and what its call takes. For a
337 * union of names, the union of their arguments.
338 */
339 export type Args<N extends EventName = EventName> = EventOf[N];
340
341 /**
342 * Options of `$.ui.ask`.
343 */
344 export type AskOptions = {
345 /**
346 * 2-4 option labels; fewer than two are padded with Yes/No; free text is the
347 * dialog's Other.
348 */
349 options?: readonly string[];
350 /**
351 * A short chip beside the question (`Approach`, 12 characters at most).
352 */
353 header?: string;
354 /**
355 * Allow several options; the answer comes back comma-joined.
356 */
357 multiSelect?: true;
358 };
359
360 /**
361 * The input of `attribution.text`: one text the engine asks the model to
362 * write into a commit or a pull request, at the moment it is composed.
363 *
364 * Composed for the Bash description, the commit skills, a PR's body, the
365 * pre-ship mandate and the commit gate's deny: the same event at each.
366 */
367 export type AttributionTextInput = {
368 /**
369 * Which text (`commit`, `pr`, `exemption`, `remedy`); the key a matcher
370 * narrows on.
371 */
372 kind: AttributionTextKind;
373 /**
374 * As the engine composed it, the settings applied.
375 */
376 text: string;
377 };
378
379 /**
380 * Which git text `attribution.text` carries: the commit trailer, the PR
381 * footer, the mandate's or the commit gate's sentence naming the exemption.
382 */
383 export type AttributionTextKind = 'commit' | 'pr' | 'exemption' | 'remedy';
384
385 /**
386 * What an `attribution.text` hook returns: the text the model reads in
387 * that place.
388 */
389 export type AttributionTextResult = {
390 text: string;
391 };
392
393 /**
394 * What `$.audio.play` plays: a URL the engine fetches, or the bytes.
395 */
396 export type AudioClip = {
397 /**
398 * A file of the calling plugin's own, relative to the plugin's
399 * directory (`fx/open.wav`); no `.`, no leading slash.
400 *
401 * The engine resolves it and loads the file from disk.
402 */
403 asset: string;
404 url?: undefined;
405 base64?: undefined;
406 mime?: undefined;
407 } | {
408 /**
409 * The clip's URL; the engine fetches it (never the plugin).
410 */
411 url: string;
412 asset?: undefined;
413 base64?: undefined;
414 mime?: undefined;
415 } | {
416 /**
417 * The clip's bytes, base64.
418 */
419 base64: string;
420 /**
421 * What the bytes are (`audio/mpeg`, `audio/wav`).
422 */
423 mime: string;
424 asset?: undefined;
425 url?: undefined;
426 };
427
428 type BackgroundTaskSummary = {
429 id: string;
430 /**
431 * Friendly task-type label (e.g. 'shell', 'subagent', 'monitor', 'workflow'). Falls back to the raw discriminant for unknown types.
432 */
433 type: string;
434 status: string;
435 /**
436 * Free-text description. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
437 */
438 description: string;
439 /**
440 * Shell command line. Only present for 'shell' tasks. Capped at 1000 chars with the same "... [+N chars]" marker.
441 */
442 command?: string;
443 /**
444 * Subagent type name. Only present for 'subagent' tasks.
445 */
446 agent_type?: string;
447 /**
448 * MCP server name. Only present for 'monitor' / 'MCP task' tasks.
449 */
450 server?: string;
451 /**
452 * MCP tool name. Only present for 'monitor' / 'MCP task' tasks.
453 */
454 tool?: string;
455 /**
456 * Workflow name. Only present for 'workflow' tasks.
457 */
458 name?: string;
459 };
460
461 type BaseHookInput = {
462 session_id: string;
463 transcript_path: string;
464 cwd: string;
465 /**
466 * 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.
467 */
468 prompt_id?: string;
469 permission_mode?: string;
470 /**
471 * 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.
472 */
473 agent_id?: string;
474 /**
475 * 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).
476 */
477 agent_type?: string;
478 /**
479 * 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.
480 */
481 effort?: {
482 /**
483 * 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.
484 */
485 level: string;
486 };
487 };
488
489 /**
490 * The `Box` props a `hover` may override, none of which moves layout, and
491 * `scope`, which names the hover group the Box joins instead of a style.
492 *
493 * `display` is `"flex"` alone, on a Box drawn `display: "none"` inside a
494 * visible keyed Box, and never beside a `scope` (a group lit from another
495 * site would move what the pointer is over); `borderStyle` only restyles.
496 */
497 export type BoxHoverProps = {
498 /**
499 * Names a hover group of this plugin's: every element it draws with the
500 * same `scope`, in any site on the surface, lights while any is hovered.
501 *
502 * A Pane row and a mark on a transcript message can share one. Another
503 * plugin's elements under the same string are a different group. One to
504 * 64 characters, no control characters; no keyed Box needed; no hook runs.
505 */
506 scope?: string;
507 borderStyle?: string;
508 borderColor?: string;
509 borderDimColor?: boolean;
510 backgroundColor?: string;
511 display?: 'flex';
512 };
513
514 /**
515 * The props of `Box`: the layout, margin, padding and border props of Ink's
516 * Box a tree may set, and the two of hover.
517 */
518 export type BoxProps = {
519 /**
520 * Makes the Box a hover scope: while the pointer is anywhere over it, its
521 * own `hover` and that of every element beneath it apply.
522 *
523 * A nested Box with a `key` of its own scopes what is beneath it. A key a
524 * sibling Box already took, or one that is no plain string, names no
525 * scope: the Box draws, and hovers beneath it stay inert.
526 */
527 key?: string;
528 /**
529 * Style overrides applied by the surface while the pointer is over the
530 * nearest keyed `Box`, this one included, or, given a `scope`, its group.
531 *
532 * Never a layout change; no hook runs and nothing crosses to the plugin.
533 * To reveal on hover, draw a Box `display: "none"` with `hover: { display:
534 * "flex" }` inside a visible keyed Box; a scoped hover never reveals.
535 */
536 hover?: BoxHoverProps;
537 flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';
538 flexGrow?: number;
539 flexShrink?: number;
540 flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse';
541 alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch';
542 alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto';
543 justifyContent?: 'flex-start' | 'center' | 'flex-end' | 'space-between' | 'space-around' | 'space-evenly';
544 gap?: number;
545 columnGap?: number;
546 rowGap?: number;
547 width?: number | string;
548 height?: number | string;
549 minWidth?: number | string;
550 minHeight?: number | string;
551 margin?: number;
552 marginX?: number;
553 marginY?: number;
554 marginTop?: number;
555 marginBottom?: number;
556 marginLeft?: number;
557 marginRight?: number;
558 padding?: number;
559 paddingX?: number;
560 paddingY?: number;
561 paddingTop?: number;
562 paddingBottom?: number;
563 paddingLeft?: number;
564 paddingRight?: number;
565 borderStyle?: string;
566 borderColor?: string;
567 borderDimColor?: boolean;
568 backgroundColor?: string;
569 overflow?: 'visible' | 'hidden';
570 display?: 'flex' | 'none';
571 };
572
573 /**
574 * One variant per built-in tool; with none in the table (a plugin author's
575 * project before `/plugin-types` ran), one loose variant over every name.
576 */
577 export type BuiltinToolCallInput = [BuiltinToolName] extends [never] ? BuiltinToolCallInputFallback : {
578 [N in BuiltinToolName]: ToolInputOf<N, BuiltinToolInputs[N]>;
579 }[BuiltinToolName];
580
581 /**
582 * The built-in branch's answer when no built-in tool is declared: every
583 * name, its args unconstrained.
584 */
585 type BuiltinToolCallInputFallback = {
586 /**
587 * The name of the tool being called (`Bash`); comparing it narrows `e` once
588 * the table has entries. Reserved: a rewrite of it is ignored by core.
589 */
590 tool: string;
591 /**
592 * The tool_use block's id: the same at every event of the call and in
593 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
594 */
595 tool_use_id: string;
596 [argument: string]: unknown;
597 };
598
599 /**
600 * The arguments of each built-in tool by name, for declaration merging;
601 * empty until a declaration file adds entries, then `e.tool === "Bash"`
602 * narrows `e` to Bash's arguments.
603 *
604 * `/plugin-types` writes this build's set beneath the engine's declarations
605 * (claude-code.d.ts), from each tool's input schema.
606 *
607 * @example
608 * interface BuiltinToolInputs { Bash: { command: string; timeout?: number } }
609 */
610 export interface BuiltinToolInputs {
611 }
612
613 /**
614 * The names of the built-in tools.
615 */
616 export type BuiltinToolName = keyof BuiltinToolInputs & string;
617
618 /**
619 * The structured result of each built-in tool by name, for declaration
620 * merging; empty until a declaration file adds entries, then after
621 * `e.tool === "Bash"` the `result` of `next(e)` is Bash's record.
622 *
623 * `/plugin-types` writes this build's set beneath the engine's declarations
624 * (claude-code.d.ts), from each tool's output schema; a tool without one is
625 * `unknown`.
626 *
627 * @example
628 * interface BuiltinToolResults { Bash: { stdout: string; stderr: string } }
629 */
630 export interface BuiltinToolResults {
631 }
632
633 /**
634 * The props of `Button`, every surface's pressable leaf: an address, a
635 * label, the closure a press runs, and the label styles a hover overrides.
636 *
637 * The terminal draws `[ label ]` (when `plain`, `1: label` or the label
638 * alone), a desktop a native button; a click, a `hotkey`, the chord for its
639 * `action`, or Enter under the focus raises `ui.press`, its bottom `onPress`.
640 */
641 export type ButtonProps = {
642 /**
643 * The element's address: `e.element` at `ui.press`, what a matcher names.
644 * Defaults to the label.
645 */
646 key?: string;
647 /**
648 * The text drawn on the button; or the one string child.
649 */
650 label?: string;
651 /**
652 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it where
653 * the site honours one (the `AbovePrompt` band); anything else is refused.
654 *
655 * A digit presses from an empty composer; a digit or letter presses on
656 * keydown while one of the band's Buttons has the focus (Shift+w matches
657 * `"w"`; held keys repeat). Of two Buttons on one hotkey the later wins.
658 */
659 hotkey?: string;
660 /**
661 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord, as the
662 * person bound it, presses this from the prompt; unknown names refused.
663 *
664 * Chords, or a modified key Global or an active context binds, on the
665 * terminal while mounted, no dialog up and no engine handler of the action
666 * mounted; a pane's over the band's over another's, then the last drawn.
667 */
668 action?: string;
669 /**
670 * Drawn without chrome: the hotkey in the accent color, a colon, the
671 * label (`1: Yes`), as a survey's row reads; no `hotkey`, the label alone.
672 *
673 * A one-glyph label (`'\u{1F50A}'`, a speaker) is then a control by
674 * itself: the focus and the pointer still invert it, `dimColor` and `hover`
675 * still apply. A desktop draws its native button either way.
676 */
677 plain?: true;
678 /**
679 * The label drawn dim at rest, as `Text`'s `dimColor`, and at full strength
680 * under the pointer or the focus: a secondary control, a path in a list.
681 */
682 dimColor?: boolean;
683 /**
684 * The site's focus ring starts here when the site takes the keyboard,
685 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
686 *
687 * A pane opened with `focus`, or the person's focus chord or click, is the
688 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
689 * origin this plugin. A ring the person has moved stays where it was put.
690 */
691 autoFocus?: true;
692 /**
693 * Label style overrides (the `Text` set) applied by the surface while the
694 * nearest enclosing keyed `Box`, or given a `scope` its group, is hovered.
695 *
696 * No hook runs and nothing crosses to the plugin; under the pointer itself
697 * the button inverts as it always has. Refused outside a keyed Box unless
698 * it names a `scope`.
699 */
700 hover?: TextHoverProps;
701 /**
702 * What the press runs, in the plugin's own environment: the bottom of the
703 * `ui.press` chain. The host holds only a handle, for the drawing's life.
704 */
705 onPress: () => void;
706 };
707
708 /**
709 * The handler `on(...).catch(handler)` takes for a hook of type `F`: the
710 * hook's `($, e, next)`, run afresh when it throws, misreturns or overruns.
711 *
712 * `next` carries `error` and `called` (Caught) and is replay-safe; a return
713 * within the grace is the hook's result, `undefined` the hook absent. On a
714 * streaming event the handler is a generator too, continuing the stream.
715 */
716 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;
717
718 /**
719 * What `next` carries into a `.catch` handler and nowhere else: why the
720 * hook failed, and whether it had called `next` before it did.
721 *
722 * There `next` is replay-safe: when `called`, `next(e)` resolves to what the
723 * hook's last call settled to, nothing beneath running again, the argument
724 * unread; when not, it runs the hooks beneath once and a later call replays.
725 */
726 export type Caught = {
727 /**
728 * Why the hook failed (HookFailure); undefined on an ordinary hook's
729 * `next`, so its presence says a handler is running.
730 */
731 readonly error: HookFailure;
732 /**
733 * True when the failed hook had called `next()` or `next.to()` at least
734 * once, settled or in flight; the handler runs once that call settled.
735 */
736 readonly called: boolean;
737 };
738
739 /**
740 * What a hook on streaming event `N` yields, and what its `next(e)` yields
741 * to it (ChunkOf by name).
742 */
743 export type Chunk<N extends StreamingEventName = StreamingEventName> = ChunkOf[N];
744
745 /**
746 * The chunk type of each streaming event, by name: what its stream yields.
747 */
748 export type ChunkOf = {
749 /**
750 * One piece of the model's response (TurnStepChunk).
751 */
752 'turn.step': TurnStepChunk;
753 };
754
755 /**
756 * What every `turn.step` chunk may carry: the engine's handle on the item
757 * of its own stream the chunk was read off, absent on a chunk a hook made.
758 *
759 * A hook that passes a chunk on, or rewrites it by spreading it, keeps the
760 * handle, and whatever it left unchanged reaches the engine as the engine
761 * streamed it; a chunk built afresh has none and is taken at its word.
762 */
763 type ChunkRef = {
764 /**
765 * The engine's handle on its own streamed item; opaque, this step's only.
766 */
767 ref?: number;
768 };
769
770 /**
771 * The name of a classic hook event as a function-hooks event: the settings
772 * hook's own name under `classic` (`classic.Stop`, `classic.PreToolUse`).
773 */
774 export type ClassicEventName = `classic.${ClassicHookEvent}`;
775
776 /**
777 * The classic (settings) hook events, one per classic event name: `e` is
778 * what the classic hook receives on stdin for that event.
779 *
780 * The chain is [managed settings hooks, ...hooks modules, the other settings
781 * hooks as core], so a managed block ends it above every module. In shape
782 * `classic.PreToolUse` alone differs: its `e` is ToolCallEnvelope, no more.
783 */
784 export type ClassicEventOf = {
785 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? ToolCallEnvelope : ClassicHookInputs[E];
786 };
787
788 /**
789 * The name of a classic hook event: `PreToolUse`, `Stop`, and the rest.
790 */
791 export type ClassicHookEvent = HookInput['hook_event_name'];
792
793 /**
794 * What a classic hook receives on stdin for each event, by event name: the
795 * Agent SDK's `<Event>HookInput`.
796 */
797 export type ClassicHookInputs = {
798 [I in HookInput as I['hook_event_name']]: I;
799 };
800
801 /**
802 * Everything a classic hook event's answer can carry, named as the classic
803 * hook's JSON output names it; each event reads its subset (ClassicResultOf).
804 *
805 * The settings hooks below fold into one of these (last write wins, contexts
806 * concatenate); a hooks module returns `next(e)`, a copy with fields changed,
807 * or its own. A field of the wrong shape fails the hook, which is skipped.
808 */
809 export type ClassicResult = {
810 /**
811 * `decision: "block"` with this text as `reason` (a command hook's exit
812 * code 2): the event's block, veto or re-prompt.
813 */
814 block?: string;
815 /**
816 * `continue: false`: the session stops after this event.
817 */
818 preventContinuation?: true;
819 /**
820 * Shown when `preventContinuation` stops the session (`stopReason`).
821 */
822 stopReason?: string;
823 /**
824 * `hookSpecificOutput.additionalContext`, one entry per hook: text handed
825 * to the model with the event.
826 */
827 additionalContext?: string[];
828 /**
829 * `hookSpecificOutput.sessionTitle` (UserPromptSubmit, SessionStart).
830 */
831 sessionTitle?: string;
832 /**
833 * `hookSpecificOutput.suppressOriginalPrompt` (UserPromptSubmit,
834 * UserPromptExpansion).
835 */
836 suppressOriginalPrompt?: true;
837 /**
838 * `hookSpecificOutput.initialUserMessage` (SessionStart).
839 */
840 initialUserMessage?: string;
841 /**
842 * `hookSpecificOutput.watchPaths` (SessionStart).
843 */
844 watchPaths?: string[];
845 /**
846 * `hookSpecificOutput.reloadSkills` (SessionStart).
847 */
848 reloadSkills?: true;
849 /**
850 * `hookSpecificOutput.permissionDecision` (PreModelSwitch).
851 */
852 permissionDecision?: 'allow' | 'deny' | 'ask';
853 /**
854 * `hookSpecificOutput.permissionDecisionReason` (PreModelSwitch).
855 */
856 permissionDecisionReason?: string;
857 /**
858 * `hookSpecificOutput.decision` (PermissionRequest).
859 */
860 decision?: PermissionRequestDecision;
861 /**
862 * `hookSpecificOutput.updatedToolOutput` (PostToolUse): replaces what the
863 * model sees of the tool's result.
864 */
865 updatedToolOutput?: unknown;
866 /**
867 * `hookSpecificOutput.updatedMCPToolOutput` (PostToolUse, MCP tools only).
868 */
869 updatedMCPToolOutput?: unknown;
870 /**
871 * `hookSpecificOutput.retry` (PermissionDenied).
872 */
873 retry?: true;
874 /**
875 * `hookSpecificOutput.displayContent` (MessageDisplay).
876 */
877 displayContent?: string;
878 /**
879 * `hookSpecificOutput.worktreePath` (WorktreeCreate; a command hook prints
880 * it): the worktree the hook created, absolute or relative to its cwd.
881 *
882 * Left unset, the session creates its git worktree as it would unhooked.
883 */
884 worktreePath?: string;
885 };
886
887 /**
888 * The event-specific fields of ClassicResult each classic event reads (its
889 * `hookSpecificOutput`), by event; an event absent here reads none of them.
890 *
891 * `block`, `preventContinuation` and `stopReason` are every event's.
892 */
893 export type ClassicResultFields = {
894 UserPromptSubmit: 'additionalContext' | 'sessionTitle' | 'suppressOriginalPrompt';
895 UserPromptExpansion: 'additionalContext' | 'suppressOriginalPrompt';
896 SessionStart: 'additionalContext' | 'initialUserMessage' | 'sessionTitle' | 'watchPaths' | 'reloadSkills';
897 Setup: 'additionalContext';
898 PreModelSwitch: 'permissionDecision' | 'permissionDecisionReason';
899 PostModelSwitch: 'additionalContext';
900 SubagentStart: 'additionalContext';
901 PostToolUse: 'additionalContext' | 'updatedToolOutput' | 'updatedMCPToolOutput';
902 PostToolUseFailure: 'additionalContext';
903 PostToolBatch: 'additionalContext';
904 Stop: 'additionalContext';
905 SubagentStop: 'additionalContext';
906 PermissionDenied: 'retry';
907 PermissionRequest: 'decision';
908 MessageDisplay: 'displayContent';
909 WorktreeCreate: 'worktreePath';
910 };
911
912 /**
913 * What each classic hook event's hook returns and its `next(e)` resolves to:
914 * the event's own subset of ClassicResult.
915 *
916 * `classic.PreToolUse` keeps its `allow` / `ask` / `deny` result
917 * (PreToolUseResult).
918 */
919 export type ClassicResultOf = {
920 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? PreToolUseResult : Pick<ClassicResult, 'block' | 'preventContinuation' | 'stopReason' | (E extends keyof ClassicResultFields ? ClassicResultFields[E] : never)>;
921 };
922
923 /**
924 * Options of `$.model.classify`.
925 */
926 export type ClassifyOptions = {
927 /**
928 * An alias (`haiku`) or a full model id; default the engine's small fast
929 * model.
930 */
931 model?: string;
932 };
933
934 /**
935 * The element table a surface module draws with, `surface.elements`: the
936 * terminal's (Elements) less `Client` (none nests) and `Raster` (needs `$`).
937 *
938 * What `$.ui.resolve(e)` is to a hooks module, with no `$` and no hook
939 * between: `const { Box, Text } = surface.elements`, then `<Box>`. A Button,
940 * Input or Select keeps its handler here and still raises `ui.press` etc.
941 */
942 export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster'>;
943
944 /**
945 * One key the person pressed while a `Client` had the focus, as
946 * `surface.onKey` hands it. Escape never arrives: it returns the focus.
947 */
948 export type ClientKeyEvent = {
949 /**
950 * A special key's name (`up`, `down`, `left`, `right`, `return`, `tab`,
951 * `backspace`, `delete`, `pageup`, `home`, ...) or the character typed.
952 */
953 key: string;
954 /**
955 * Modifier keys held with it, each present only when true.
956 */
957 ctrl?: true;
958 shift?: true;
959 meta?: true;
960 };
961
962 /**
963 * The component a surface module exports (default, or its one PascalCase
964 * export): from props and surface to the tree drawn (no nested `Client`).
965 *
966 * Runs in the plugin's surface environment on the drawing thread, under a
967 * time budget per call; a throw or an overrun unmounts the instance and
968 * draws one line naming the plugin and the module in its place.
969 */
970 export type ClientModule<P extends JsonValue = JsonValue, S = unknown> = (props: P, surface: ClientSurface<S>) => RenderElement;
971
972 /**
973 * One pointer event over a `Client`'s region, as `surface.onPointer` hands
974 * it: cell coordinates relative to the region's top-left corner.
975 *
976 * After a `down` in the region the instance holds the pointer until the
977 * `up`: every `move` reaches it, past the edges too (negative, or beyond
978 * `columns`/`rows`), and the transcript neither selects nor scrolls.
979 */
980 export type ClientPointerEvent = {
981 type: ClientPointerType;
982 /**
983 * The column under the pointer, 0 at the region's left edge; on `enter`
984 * and `leave`, the last column a move reported.
985 */
986 x: number;
987 /**
988 * The row under the pointer, 0 at the region's top edge.
989 */
990 y: number;
991 /**
992 * Which button is down (`down`, `move` while held) or came up (`up`);
993 * absent on a hover `move`, `enter` and `leave`.
994 */
995 button?: 'left' | 'middle' | 'right';
996 /**
997 * Modifier keys the terminal reported held, each present only when true.
998 */
999 shift?: true;
1000 alt?: true;
1001 ctrl?: true;
1002 };
1003
1004 /**
1005 * What the pointer did over a `Client`'s region: a button went down, the
1006 * pointer moved, the button came up, or the pointer crossed the region's edge.
1007 */
1008 export type ClientPointerType = 'down' | 'move' | 'up' | 'enter' | 'leave';
1009
1010 /**
1011 * The props of `Client`: which of the plugin's surface modules draws here,
1012 * under what key, with what data, in how much room.
1013 */
1014 export type ClientProps = {
1015 /**
1016 * The instance's address within the drawing: two `Client`s of one plugin in
1017 * one tree take two keys. What `e.element` carries at `ui.message`.
1018 *
1019 * The engine keeps the instance (its local state, its timers) across the
1020 * plugin's redraws while a `Client` under this key stays in the tree.
1021 */
1022 key: string;
1023 /**
1024 * The surface module's path, a string literal relative to this file:
1025 * `module: "./<name>.tsx"` (or `.jsx`, `.ts`, `.js`, `.mjs`).
1026 *
1027 * Read off the source: a variable there is refused at load, as is a path
1028 * outside the plugin or naming no file. Its default export draws, else
1029 * its one PascalCase export; loaded, the tree carries the plugin's path.
1030 */
1031 module: string;
1032 /**
1033 * Plain data (JsonValue) handed to the module function; a new value on a
1034 * redraw reaches the running instance, its state kept.
1035 *
1036 * Bounded as a tree's text is; not a channel for closures.
1037 * Typed `unknown` so a matcher over a tree stays shallow.
1038 */
1039 props?: unknown;
1040 /**
1041 * Columns the instance's region takes: a count, or a percentage of the
1042 * parent. Absent, the region is as wide as what the module draws.
1043 */
1044 width?: number | string;
1045 /**
1046 * Rows the instance's region takes: a count, or a percentage of the parent.
1047 * Absent, the region is as tall as what the module draws.
1048 */
1049 height?: number | string;
1050 /**
1051 * How the region grows into free room along the parent's direction, as a
1052 * Box's `flexGrow`.
1053 */
1054 flexGrow?: number;
1055 };
1056
1057 /**
1058 * What a surface module's function receives as its second argument: its
1059 * elements, the instance's local state, its region, input, clock and port.
1060 *
1061 * Called again (same `surface`, same `state`) on new props, after
1062 * `setState`, and on a resize; what it returns is drawn in the region. No
1063 * `$` here: the hooks module has it, and `post` is the way to reach it.
1064 */
1065 export type ClientSurface<S = unknown> = {
1066 /**
1067 * The surface's element table (ClientElements), the tags the module draws
1068 * with: `const { Box, Text } = surface.elements`. No `Client` in it.
1069 */
1070 readonly elements: ClientElements;
1071 /**
1072 * The instance's local state: `undefined` until the first `setState`.
1073 * Kept across the plugin's redraws; dropped with the instance.
1074 */
1075 readonly state: S | undefined;
1076 /**
1077 * Replaces the local state and schedules one more call of the function on
1078 * the next frame; several calls before it coalesce into one redraw.
1079 */
1080 setState: (next: S) => void;
1081 /**
1082 * The region's width in cells, as last laid out (0 before the first
1083 * layout).
1084 */
1085 readonly columns: number;
1086 /**
1087 * The region's height in cells, as last laid out (0 before the first
1088 * layout).
1089 */
1090 readonly rows: number;
1091 /**
1092 * Calls `fn` every `ms` milliseconds on the surface's frame clock until
1093 * the returned function is called or the instance unmounts.
1094 *
1095 * Start it once (while `state` is still undefined), not on every call.
1096 */
1097 every: (ms: number, fn: () => void) => () => void;
1098 /**
1099 * Sets the instance's pointer listener (one; a later call replaces it)
1100 * and returns what clears it. See ClientPointerEvent for capture.
1101 */
1102 onPointer: (fn: (event: ClientPointerEvent) => void) => () => void;
1103 /**
1104 * Sets the instance's key listener (one; a later call replaces it),
1105 * reached while a click has given it the focus; Escape returns that.
1106 */
1107 onKey: (fn: (event: ClientKeyEvent) => void) => () => void;
1108 /**
1109 * Sends plain data to the plugin's hooks module: `e.data` of a
1110 * `ui.message` only that plugin's hooks see, one per frame at most.
1111 *
1112 * A later post in the same frame replaces an undelivered one; a hook
1113 * answering `{ props }` hands this instance its next props.
1114 */
1115 post: (data: JsonValue) => void;
1116 };
1117
1118 /**
1119 * The argument of the `$.clock` waits (`sleep`, `after`, `every`): how long,
1120 * in milliseconds, before the dispatch resolves.
1121 */
1122 type ClockWait = {
1123 /**
1124 * The wait, a non-negative number of milliseconds.
1125 */
1126 ms: number;
1127 };
1128
1129 /**
1130 * The props of `Code`, source text every surface draws with the engine's own
1131 * highlighter: coloured tokens, a line gutter on request, or a unified diff.
1132 *
1133 * A leaf: no children. `source` is the element's data as a string is a
1134 * Text's, bounded and free of control characters the same way; the colour
1135 * on screen is the engine's, never the plugin's.
1136 */
1137 export type CodeProps = {
1138 /**
1139 * The text drawn: source code, or under `format: 'diff'` one or more
1140 * unified-diff hunks.
1141 *
1142 * At most 10000 characters; tab and newline are the only control
1143 * characters it may hold.
1144 */
1145 source: string;
1146 /**
1147 * A highlighter language id or alias (`typescript`, `ts`, `py`), a
1148 * plugin-contributed grammar's included.
1149 *
1150 * Absent, the language is inferred from `path`; when neither resolves,
1151 * the text is drawn plain.
1152 */
1153 language?: string;
1154 /**
1155 * A file path the language is inferred from when `language` is absent:
1156 * its extension or name, else a shebang on the first line.
1157 *
1158 * Drawn nowhere and never read: nothing touches the disk.
1159 */
1160 path?: string;
1161 /**
1162 * The 1-based number of the first line of `source`: present, a dim
1163 * right-aligned gutter numbers the lines from it; absent, no gutter.
1164 *
1165 * Ignored under `format: 'diff'`, whose hunks carry their own numbers.
1166 */
1167 startLine?: number;
1168 /**
1169 * `'source'` (the default) draws `source` as code; `'diff'` reads it as
1170 * unified-diff hunks and draws gutters, markers, add and remove colouring.
1171 *
1172 * A hunk is `@@ -a,b +c,d @@` then lines starting ` `, `+` or `-`; a
1173 * leading `---`/`+++` pair and `\ No newline at end of file` are read
1174 * past. A source that does not parse as hunks is refused.
1175 */
1176 format?: 'source' | 'diff';
1177 /**
1178 * What a line wider than the room does, in Text's `wrap` vocabulary:
1179 * `'wrap'` (the default) continues it on rows under the gutter.
1180 *
1181 * `'truncate-end'` cuts it at the edge with an ellipsis; Text's other
1182 * spellings are refused, since a gutter leaves them no sense here.
1183 */
1184 wrap?: 'wrap' | 'truncate-end';
1185 };
1186
1187 /**
1188 * The input of `command.describe`: how one slash command presents in the
1189 * typeahead and `/help`, at the moment the engine lists it.
1190 */
1191 export type CommandDescribeInput = {
1192 /**
1193 * Names the command without its slash; the key a matcher narrows on. A
1194 * rewrite is refused.
1195 */
1196 command: string;
1197 /**
1198 * The one-line description the menu shows, as the command declares it.
1199 */
1200 description: string;
1201 /**
1202 * The hint drawn dim after the name (`[name]`), when the command has one.
1203 */
1204 argumentHint?: string;
1205 /**
1206 * Whether the typeahead and `/help` leave the command out; a hidden
1207 * command still runs when typed in full.
1208 */
1209 isHidden: boolean;
1210 /**
1211 * Whether the command declares it runs at once when typed mid-turn,
1212 * instead of waiting for the turn to end.
1213 *
1214 * One that decides per invocation reads false. Read only: not part of
1215 * what a hook answers, and a rewrite is refused.
1216 */
1217 immediate: boolean;
1218 /**
1219 * Who provides this command: the plugin and its tier; `{ plugin: "engine",
1220 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
1221 */
1222 provider: Origin;
1223 };
1224
1225 /**
1226 * What a `command.describe` hook returns: the description, hint and hidden
1227 * flag the menu uses; the name, `immediate` and `provider` stay as they were.
1228 */
1229 export type CommandDescribeResult = Omit<CommandDescribeInput, 'command' | 'immediate' | 'provider'>;
1230
1231 /**
1232 * One slash command as `$.command.list()` returns it.
1233 */
1234 export type CommandInfo = {
1235 /**
1236 * What the person runs it by, without the slash.
1237 */
1238 name: string;
1239 /**
1240 * The one line the typeahead shows for it.
1241 */
1242 description: string;
1243 /**
1244 * Where it comes from (CommandSource).
1245 */
1246 source: CommandSource;
1247 /**
1248 * Which plugin added it, when `source` is `plugin` and the engine knows:
1249 * the one that registered it, or whose manifest carries it.
1250 */
1251 plugin?: string;
1252 };
1253
1254 /**
1255 * Where a command's answer will show: which of the terminal's two layouts
1256 * the surface renders, and how wide it is when the command runs.
1257 *
1258 * A fact the engine stamps on `command.run`, so a command that draws (opens
1259 * a pane, prints a wide table) can suit the room it has: the fullscreen
1260 * layout docks a pane beside the transcript from 110 columns, the main
1261 * screen places it inline above the prompt at any width.
1262 */
1263 export type CommandPresentation = {
1264 /**
1265 * True under the fullscreen (alternate-screen) layout; false on the main
1266 * screen (`CLAUDE_CODE_NO_FLICKER=0`, tmux by default) and headless.
1267 */
1268 isFullscreen: boolean;
1269 /**
1270 * The terminal's width in cells as the command runs; 80 where no terminal
1271 * has measured (headless with no tty).
1272 */
1273 columns: number;
1274 };
1275
1276 /**
1277 * `command.run`'s input as a plugin's `$.command.run` takes it: `args` may
1278 * be left out (`/command`, bare); `origin` and `presentation` the engine sets.
1279 */
1280 export type CommandRunArgs = Omit<CommandRunInput, 'origin' | 'args' | 'presentation'> & {
1281 /**
1282 * Everything after the name, as the person would type it; left out, `""`.
1283 */
1284 args?: string;
1285 };
1286
1287 /**
1288 * The input of `command.run`: one slash command about to run, the way the
1289 * person typed it (`/name args`), and where the run came from.
1290 */
1291 export type CommandRunInput = {
1292 /**
1293 * Names the command without its slash (`compact`, `hello`), aliases and
1294 * folds resolved; the key a matcher narrows on. A rewrite is refused.
1295 */
1296 command: string;
1297 /**
1298 * Everything after the name, as typed (`""` when nothing was); a hook
1299 * rewrites it with `next({ ...e, args })`.
1300 */
1301 args: string;
1302 /**
1303 * Where the run came from, in `prompt.submit`'s words (PromptOrigin):
1304 * the person's Enter (`composer`), the bridge, the SDK, or a plugin.
1305 *
1306 * A plugin's `$.command.run` reads `{ kind: 'plugin', name }`. `next(e)`
1307 * passes it on as received.
1308 */
1309 origin: PromptOrigin;
1310 /**
1311 * Where the command's answer will show (CommandPresentation): the
1312 * fullscreen layout or the main screen, and the terminal's width.
1313 *
1314 * Pinned: the engine stamps it, `next(e)` passes it on, a rewrite that
1315 * leaves it out keeps it and one that changes it is refused.
1316 */
1317 presentation: CommandPresentation;
1318 };
1319
1320 /**
1321 * What a `command.run` hook returns and what `next(e)` and `$.command.run`
1322 * resolve to: the command's output text, when it has one.
1323 *
1324 * From core, `text` is what the command printed (a `local` command's
1325 * returned text; a panel command may print nothing) and `ref` names the
1326 * run. A hook's own answer without `next` runs no command: its `text` is
1327 * shown as the command's output, under the names of the plugins hooking
1328 * the command unless each is bundled with Claude Code, whose answer reads
1329 * as the built-in command's own.
1330 */
1331 export type CommandRunResult = {
1332 /**
1333 * The command's output as a transcript line, or undefined when the
1334 * command showed nothing as text (a panel, a prompt for the model).
1335 */
1336 text?: string;
1337 /**
1338 * Set by core on what `next(e)` resolves to: names the engine's run of
1339 * the command (its result stays on the host side).
1340 *
1341 * A hook that returns the object it got makes the engine use that run
1342 * verbatim. Absent on a hook's own `{ text }` and on `$.command.run`'s.
1343 */
1344 ref?: number;
1345 };
1346
1347 /**
1348 * Where a slash command comes from, as `$.command.list()` tells them apart.
1349 *
1350 * `builtin` ships with Claude Code; `plugin` is a plugin's markdown command,
1351 * skill or `$.command.register`; `user` is the user's or project's own
1352 * file; `mcp` an MCP server's prompt.
1353 */
1354 export type CommandSource = 'builtin' | 'plugin' | 'user' | 'mcp';
1355
1356 /**
1357 * What `$.command.register` takes: the slash command this plugin serves.
1358 */
1359 export type CommandSpec = {
1360 /**
1361 * The command's name without the slash (letters, digits, `_`, `-`; up to
1362 * 64); the person runs it as `/<name>`.
1363 */
1364 name: string;
1365 /**
1366 * The one line the typeahead and `/help` show for it.
1367 */
1368 description: string;
1369 /**
1370 * The hint drawn dim after the name (`[name]`), when it takes arguments.
1371 */
1372 argumentHint?: string;
1373 /**
1374 * Set so that `/<name>` typed while a turn is in flight runs at once
1375 * instead of waiting for the turn to end, as it does when left out.
1376 *
1377 * Its `command.run` hook then runs while a turn may still be streaming and
1378 * must not assume the turn's state (what the transcript holds, whether a
1379 * tool is mid-call); its `{ text }` prints as an idle run's does.
1380 */
1381 immediate?: true;
1382 };
1383
1384 type ConfigChangeHookInput = BaseHookInput & {
1385 hook_event_name: 'ConfigChange';
1386 source: 'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills';
1387 file_path?: string;
1388 };
1389
1390 /**
1391 * The input of `config.describe`: how one `/config` row presents, at the
1392 * moment the menu lists it (and for `$.config.list`).
1393 */
1394 export type ConfigDescribeInput = {
1395 /**
1396 * Names the row, as `config.set`'s `key` does; the key a matcher narrows
1397 * on. Pinned: a rewrite is refused.
1398 */
1399 key: string;
1400 /**
1401 * What the menu draws for the row, before its value.
1402 */
1403 label: string;
1404 /**
1405 * The help text beneath the label, when the row has one (a plugin
1406 * field's `description`); absent for the panel's own rows.
1407 */
1408 description?: string;
1409 /**
1410 * Whether the menu leaves the row out; a hidden row still answers
1411 * `$.config.set` and `/config key=value`.
1412 */
1413 isHidden: boolean;
1414 /**
1415 * Who owns the row, as `config.set`'s `provider`. Pinned.
1416 */
1417 provider: Origin;
1418 };
1419
1420 /**
1421 * What a `config.describe` hook returns: the label, help text and hidden
1422 * flag the menu uses; the key and provider stay as they were.
1423 */
1424 export type ConfigDescribeResult = Omit<ConfigDescribeInput, 'key' | 'provider'>;
1425
1426 /**
1427 * How a `/config` row takes its value: `boolean` toggles, `choice` picks one
1428 * of its `options`, `text` takes a string, `number` a number.
1429 */
1430 export type ConfigKind = 'boolean' | 'choice' | 'text' | 'number';
1431
1432 /**
1433 * Where a `config.set` came from, in `prompt.submit`'s words: the person
1434 * in the `/config` menu (`composer`), the bridge, or a plugin, named.
1435 *
1436 * Set by the engine; `next(e)` passes it on as received and none sets it.
1437 */
1438 export type ConfigOrigin = {
1439 /**
1440 * The person's own change in the `/config` menu (a toggle, a pick, a
1441 * typed value), or their `/config key=value`.
1442 */
1443 kind: 'composer';
1444 } | {
1445 /**
1446 * A `/config key=value` that arrived over the Remote Control bridge (a
1447 * phone or web client, or a relay): not attestably the owner's hand.
1448 */
1449 kind: 'bridge';
1450 } | {
1451 /**
1452 * A plugin's `$.config.set`; that plugin's own hooks do not see it.
1453 */
1454 kind: 'plugin';
1455 /**
1456 * The calling plugin's name.
1457 */
1458 name: string;
1459 };
1460
1461 /**
1462 * One `/config` row as `$.config.list()` returns it: what the menu would
1463 * draw now, after every `config.describe` hook, a hidden row left out.
1464 */
1465 export type ConfigRow = {
1466 /**
1467 * Names the row: the panel's id for a built-in, `<plugin>.<field>` for a
1468 * plugin's `userConfig` field; what `$.config.set` takes.
1469 */
1470 key: string;
1471 /**
1472 * What the menu draws for the row, before its value.
1473 */
1474 label: string;
1475 /**
1476 * The help text under the label, when the row has one.
1477 */
1478 description?: string;
1479 /**
1480 * How the row takes its value (ConfigKind).
1481 */
1482 kind: ConfigKind;
1483 /**
1484 * What the row holds now.
1485 */
1486 value: ConfigValue;
1487 /**
1488 * The values a `choice` row takes, in order (a plugin string field's
1489 * declared `options` for its row); absent otherwise.
1490 */
1491 options?: readonly string[];
1492 /**
1493 * Who owns the row: the engine for the panel's own, else the plugin.
1494 */
1495 provider: Origin;
1496 /**
1497 * Whether a trusted source (managed settings, the organization's policy)
1498 * owns the value, so the menu shows it and refuses a change.
1499 */
1500 isLocked: boolean;
1501 };
1502
1503 /**
1504 * `config.set`'s input as a plugin's `$.config.set(args)` takes it: the
1505 * row's key and the value; the engine fills the rest.
1506 */
1507 export type ConfigSetArgs = Pick<ConfigSetInput, 'key' | 'value'>;
1508
1509 /**
1510 * The input of `config.set`: one `/config` row about to change, from the
1511 * menu or a plugin's `$.config.set`, with what it holds now and who owns it.
1512 */
1513 export type ConfigSetInput = {
1514 /**
1515 * Names the row: the panel's own id for a built-in (`theme`, `verbose`,
1516 * `autoCompact`), `<plugin>.<field>` for a plugin's `userConfig` field.
1517 *
1518 * The key a matcher narrows on; pinned: a rewrite is refused.
1519 */
1520 key: string;
1521 /**
1522 * What the row is being set to; `next({ ...e, value })` clamps or
1523 * replaces it, held to the row's kind (a toggle takes a boolean).
1524 */
1525 value: ConfigValue;
1526 /**
1527 * What the row holds before the change, as the menu shows it. Pinned.
1528 */
1529 previous: ConfigValue;
1530 /**
1531 * Who owns the row: `{ plugin: "engine", tier: "core" }` for the panel's
1532 * own, the plugin and its tier for a `userConfig` field. Pinned.
1533 */
1534 provider: Origin;
1535 /**
1536 * Where the change came from (ConfigOrigin): the person in the menu
1537 * (`composer`) or a plugin's `$.config.set`. Pinned.
1538 */
1539 origin: ConfigOrigin;
1540 };
1541
1542 /**
1543 * What a `config.set` hook returns and what `next(e)` resolves to:
1544 * `{ value }` once written, or `{ deny: reason }`, the row left as it was.
1545 *
1546 * The menu shows a deny's reason beside the row; a plugin's `$.config.set`
1547 * resolves with it.
1548 */
1549 export type ConfigSetResult = {
1550 value: ConfigValue;
1551 deny?: undefined;
1552 } | {
1553 deny: string;
1554 value?: undefined;
1555 };
1556
1557 /**
1558 * A `/config` row's value as a hook and `$.config` see it: a toggle's
1559 * boolean, a choice's or a text's string, a number, or a list of strings.
1560 */
1561 export type ConfigValue = boolean | string | number | readonly string[];
1562
1563 /**
1564 * One custom agent whose description the Agent tool's prompt carries;
1565 * built-in agents are left out.
1566 */
1567 export type ContextAgent = {
1568 /**
1569 * The agent's type, as the Agent tool names it.
1570 */
1571 agentType: string;
1572 /**
1573 * Where it was defined, by the engine's word (`projectSettings`,
1574 * `userSettings`, `plugin`); the display label is the renderer's.
1575 */
1576 source: string;
1577 /**
1578 * The description's estimated tokens.
1579 */
1580 tokens: number;
1581 };
1582
1583 /**
1584 * The token counts the last API response of the live window reported, as
1585 * the API spells them; the breakdown's `Messages` row is reconciled to it.
1586 */
1587 export type ContextApiUsage = {
1588 /**
1589 * Uncached input tokens the response was answered over.
1590 */
1591 input_tokens: number;
1592 /**
1593 * Tokens the response generated.
1594 */
1595 output_tokens: number;
1596 /**
1597 * Input tokens written to the prompt cache by the request.
1598 */
1599 cache_creation_input_tokens: number;
1600 /**
1601 * Input tokens read from the prompt cache by the request.
1602 */
1603 cache_read_input_tokens: number;
1604 };
1605
1606 /**
1607 * How a context breakdown is counted: `full` with the token-count API per
1608 * category, `summary` from the last response's usage and local estimates.
1609 *
1610 * The SDK's `get_context_usage` takes the same two words as its `detail`.
1611 */
1612 export type ContextBreakdownDetail = 'summary' | 'full';
1613
1614 /**
1615 * One row of the breakdown, as /context lists it beside the grid (`System
1616 * prompt`, `Messages`, `Free space`, `Autocompact buffer`).
1617 */
1618 export type ContextCategory = {
1619 /**
1620 * The row's label as /context prints it.
1621 */
1622 name: string;
1623 /**
1624 * The row's estimated tokens; a `deferred` row's do not count toward the
1625 * total.
1626 */
1627 tokens: number;
1628 /**
1629 * The theme colour /context draws the row and its squares in, by its key
1630 * in the theme (`promptBorder`, `inactive`, `permission`).
1631 */
1632 color: string;
1633 /**
1634 * Whether the row is tool schemas loaded on demand, which the grid leaves
1635 * out; the same fact as `kind` `deferred`.
1636 */
1637 isDeferred: boolean;
1638 /**
1639 * What the row is (ContextCategoryKind), stamped by the engine.
1640 */
1641 kind: ContextCategoryKind;
1642 };
1643
1644 /**
1645 * What a breakdown row is; branch on this, never on the row's `name`.
1646 *
1647 * `used` content occupies the window, `free` is the window left, `buffer`
1648 * the compaction reserve, `deferred` tool schemas loaded on demand and
1649 * outside the window.
1650 */
1651 export type ContextCategoryKind = 'used' | 'free' | 'buffer' | 'deferred';
1652
1653 /**
1654 * One square of the grid /context draws: which row it belongs to and how
1655 * full it is.
1656 */
1657 export type ContextGridSquare = {
1658 /**
1659 * The theme colour of the square's row, by its key in the theme.
1660 */
1661 color: string;
1662 /**
1663 * Whether the square holds any of its row's tokens.
1664 */
1665 isFilled: boolean;
1666 /**
1667 * The `name` of the row the square belongs to (`Free space` for the
1668 * window left).
1669 */
1670 categoryName: string;
1671 /**
1672 * The row's tokens, repeated on each of its squares.
1673 */
1674 tokens: number;
1675 /**
1676 * The row's share of the window as a whole percentage, repeated likewise.
1677 */
1678 percentage: number;
1679 /**
1680 * How full this one square is, 0 to 1: a row's last square is the partial
1681 * one (/context draws it hollow under 0.7).
1682 */
1683 squareFullness: number;
1684 };
1685
1686 /**
1687 * One MCP tool's schema as the context carries it.
1688 */
1689 export type ContextMcpTool = {
1690 /**
1691 * The tool's wire name (`mcp__linear__create_issue`).
1692 */
1693 name: string;
1694 /**
1695 * The server it belongs to, as /mcp lists it.
1696 */
1697 serverName: string;
1698 /**
1699 * The schema's estimated tokens.
1700 */
1701 tokens: number;
1702 /**
1703 * Whether the schema is inside the window now: always, unless tool
1704 * schemas load on demand and this one has not been searched for yet.
1705 */
1706 isLoaded: boolean;
1707 };
1708
1709 /**
1710 * One memory file the context carries (a CLAUDE.md, a rules file, an
1711 * auto-memory entry).
1712 */
1713 export type ContextMemoryFile = {
1714 /**
1715 * The file's path, absolute.
1716 */
1717 path: string;
1718 /**
1719 * The display label of where it was loaded from (`Project`, `User`,
1720 * `Local`, `Managed`, `AutoMem`).
1721 */
1722 type: string;
1723 /**
1724 * The file's estimated tokens.
1725 */
1726 tokens: number;
1727 };
1728
1729 /**
1730 * One skill whose listing the context carries.
1731 */
1732 export type ContextSkill = {
1733 /**
1734 * The skill's name as `/skills` lists it.
1735 */
1736 name: string;
1737 /**
1738 * Where it came from, by the engine's word (`userSettings`, `plugin`,
1739 * `built-in`, `mcp`, `syncedSkills`); the display label is the renderer's.
1740 */
1741 source: string;
1742 /**
1743 * The providing plugin's name, when the skill comes from one.
1744 */
1745 pluginName?: string;
1746 /**
1747 * The listing's estimated tokens.
1748 */
1749 tokens: number;
1750 };
1751
1752 /**
1753 * The skills the context lists for the model: how many there are, how many
1754 * fit the listing's budget, and each one's share.
1755 */
1756 export type ContextSkills = {
1757 /**
1758 * How many skills the session has.
1759 */
1760 totalSkills: number;
1761 /**
1762 * How many the listing included within its token budget.
1763 */
1764 includedSkills: number;
1765 /**
1766 * The listing's tokens in all.
1767 */
1768 tokens: number;
1769 /**
1770 * One entry per listed skill.
1771 */
1772 skillFrontmatter: ContextSkill[];
1773 };
1774
1775 /**
1776 * The slash commands the Skill tool's prompt lists, counted.
1777 */
1778 export type ContextSlashCommands = {
1779 /**
1780 * How many commands the session has.
1781 */
1782 totalCommands: number;
1783 /**
1784 * How many the listing included.
1785 */
1786 includedCommands: number;
1787 /**
1788 * The listing's tokens in all.
1789 */
1790 tokens: number;
1791 };
1792
1793 /**
1794 * How the window the breakdown measures against was settled; /context
1795 * prints its `Auto-compact window` line off this.
1796 *
1797 * `auto` is the model's own limit; the rest name a compaction window by who
1798 * set it: the `CLAUDE_CODE_AUTO_COMPACT_WINDOW` variable, the settings, the
1799 * account, an experiment, the model's default, or an unrecognised model's.
1800 */
1801 export type ContextWindowSource = 'env' | 'settings' | 'clientdata' | 'experiment' | 'model-default' | 'unknown-model' | 'auto';
1802
1803 /**
1804 * The plugin's identity (`plugin`) and the nouns core contributes to `$` as
1805 * the innermost step of the `engine.create` fold.
1806 *
1807 * A plugin's finished `$` (EngineInterface) has every core noun an outer
1808 * step did not withhold, and every noun the plugins' steps added.
1809 */
1810 export interface CoreEngineInterface {
1811 /**
1812 * This plugin, as loaded: its manifest name and its directory.
1813 */
1814 plugin: {
1815 /**
1816 * From plugin.json; debug-log and `$.ui.log` lines carry it.
1817 */
1818 name: string;
1819 /**
1820 * The plugin's directory (the one holding plugin.json), absolute.
1821 */
1822 root: string;
1823 };
1824 /**
1825 * Display: a line under an open dialog, a redraw or a repaint, a
1826 * transcript line, a pane the surface places, a window or a ring moved.
1827 */
1828 ui: {
1829 /**
1830 * Shows `text` as one line under the dialog open for `tool_use_id`, or
1831 * removes the line when `text` is undefined.
1832 *
1833 * Core removes the line when the call resolves. A call that is not open
1834 * is refused, as is another plugin's `$.tool.call` run.
1835 *
1836 * @param tool_use_id the call whose open dialog gets the line
1837 * @param text the line to show; undefined removes it
1838 * @example
1839 * $.ui.notice(e.tool_use_id, "checked by my-plugin"); return next(e)
1840 */
1841 notice: (tool_use_id: string, text: string | undefined) => void;
1842 /**
1843 * Re-runs an event whose results the engine caches: `ui.render` draws the
1844 * instances this plugin may draw again; the others drop the cached answers.
1845 *
1846 * A render hook whose state changed (a countdown) calls it for a redraw, at
1847 * most ten a second, thirty for the shown pane and the band (calls sooner
1848 * fold); a `prompt.section` or `prompt.context` hook: dropped next turn.
1849 *
1850 * @param event `ui.render`, `prompt.section`, `prompt.context`,
1851 * `tool.describe`, `command.describe` or `config.describe`
1852 */
1853 invalidate: (event: InvalidatableEventName) => void;
1854 /**
1855 * Repaints a `Raster` this plugin's own render hook drew, still mounted,
1856 * with new cells, without the redraw `invalidate` asks for.
1857 *
1858 * The surface keeps the cells for that Raster (by site and `key`) and
1859 * paints them at its next frame, so blits between frames fold into one:
1860 * an animation runs at the frame rate. A resize is a redraw instead.
1861 *
1862 * @param args `requestId` (the site), `key` (the Raster's), `cells`
1863 * (RasterProps), `columns` and `rows` (the mounted size)
1864 * @returns `{}` once the cells are its next frame, or `{ deny }` (not
1865 * mounted, not this plugin's, another size, cells that do not
1866 * decode)
1867 * @example
1868 * $.clock.every(33, () => $.ui.blit({ requestId, key, cells: frame() }))
1869 */
1870 blit: (args: UiBlitArgs) => Promise<UiBlitResult>;
1871 /**
1872 * The elements of the surface `e` is drawn on (Elements[e.surface]): a
1873 * frozen table of constructors, the JSX tags a render hook draws with.
1874 *
1875 * A read, not a dispatch: the engine ran `ui.resolve` (the other hooks,
1876 * then core) at load, per surface and component. Narrowed `e.surface`:
1877 * that table exactly; unnarrowed: the union, so shared names type-check.
1878 *
1879 * @param e this hook's own `ui.render` argument (its surface and
1880 * component pick the table)
1881 * @returns the surface's frozen element table (`Elements[e.surface]`)
1882 * @example
1883 * const { Box, Text } = $.ui.resolve(e)
1884 * return <Box>{await next(e)}<Text dimColor>done</Text></Box>
1885 */
1886 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
1887 /**
1888 * Appends one line to the transcript, drawn like a system notice (dim;
1889 * not sent to the model), and records it in the debug log.
1890 *
1891 * The line is a row of its own at the surface's next frame, wherever the
1892 * transcript is then; lines keep the order they were logged in. A `-p` or
1893 * SDK run has no transcript: its host receives the line as `ui_log`.
1894 *
1895 * @param text the line's text
1896 * @example
1897 * $.ui.log(`prompt from ${e.origin.kind}: ${e.text.length} chars`)
1898 */
1899 log: (text: string) => void;
1900 /**
1901 * Asks the user `question` in the engine's own AskUserQuestion dialog and
1902 * resolves to the label they chose, or the text typed under "Other".
1903 *
1904 * A `tool.call` of `AskUserQuestion` through every hook but the calling
1905 * one, drawn by `ui.render` on `AskUserQuestion`; a multi-select answer is
1906 * comma-joined. Rejects when dismissed, and in a `-p` run (no one to ask).
1907 *
1908 * @param question the question, ending in a question mark
1909 * @param options 2-4 option labels, or `{ options, header, multiSelect }`
1910 * @returns the label chosen, the chosen labels comma-joined, or free text
1911 * typed under "Other" (so compare it with the labels exactly)
1912 * @example
1913 * const mood = await $.ui.ask("How careful?", ["Bold", "Careful"])
1914 */
1915 ask: (question: string, options?: readonly string[] | AskOptions) => Promise<string>;
1916 /**
1917 * Shows `text` on the notification bar under the prompt for a few
1918 * seconds, the way the engine's own "context left" notice appears.
1919 *
1920 * It leaves the transcript and the model untouched.
1921 *
1922 * @param text the line to show
1923 * @param options `timeoutMs`: how long it stays (default 4000)
1924 * @example
1925 * $.ui.toast(`turn took ${Math.round(e.durationMs / 1000)} s`)
1926 */
1927 toast: (text: string, options?: ToastOptions) => void;
1928 /**
1929 * Pins `text` as this plugin's status line under the prompt, beside the
1930 * engine's own pinned notices, until the next call replaces it.
1931 *
1932 * One per plugin; `undefined` removes it.
1933 *
1934 * @param text the line to keep on screen; undefined clears it
1935 * @example
1936 * $.ui.status("thinking..."); return next(e)
1937 */
1938 status: (text: string | undefined) => void;
1939 /**
1940 * Opens a pane: a framed region the surface places, whose body this
1941 * plugin draws by hooking `ui.render` for `{ component: "Pane" }`.
1942 *
1943 * One instance per id (`requestId`): opening an open id retitles it; a hook
1944 * on `ui.open` may refuse it. The keyboard is the person's; unasked, it
1945 * waits undrawn below 144 columns (110 once asked), judged at each open.
1946 *
1947 * @param pane `id` (1-64 of letters, digits, `_`, `-`), `title`, `focus`,
1948 * `closeOnEscape` and `holdToasts` (a dialog), `rows` it wants inline
1949 * @returns settles once the pane is open (or retitled)
1950 * @example
1951 * await $.ui.open({ id: "clock", title: "Clock" })
1952 * @example
1953 * await $.ui.open({ id: "ask", focus: true, closeOnEscape: true, rows: 9 })
1954 */
1955 open: (pane: PaneOpenArgs) => Promise<void>;
1956 /**
1957 * Closes one of the open panes; an id that is not open is left alone.
1958 *
1959 * Every close raises `ui.close`, `e.origin` naming whose it is: this call
1960 * (`plugin`), the person's mark or key (`person`), an unload (`unload`).
1961 * A hook answering without `next` keeps the pane open, save on an unload.
1962 *
1963 * @param pane `id`: the id the pane was opened under
1964 * @returns settles once the pane is gone or a hook answered for it;
1965 * rejects on a hook's `{ deny }`
1966 * @example
1967 * onPress: () => $.ui.close({ id: "clock" })
1968 */
1969 close: (pane: PaneCloseArgs) => Promise<void>;
1970 /**
1971 * Scrolls something into view as the DOM's `scrollIntoView` would: a
1972 * render instance by `requestId`, an element by `key`, a site's edge.
1973 *
1974 * A site of this plugin's (its pane, the band it draws into) moves under
1975 * the event `ui.scroll`, origin `plugin`. A transcript row moves only
1976 * while this call answers the person's own input, where one scrolls.
1977 *
1978 * @param args `to` (what), `in` (which site, required for `start` and
1979 * `end`), `block` (where it lands; `nearest` by default)
1980 * @returns `{}` once it moved, or `{ deny }` saying why not
1981 * @example
1982 * onPress: () => $.ui.scroll({ in: "log", to: "end" })
1983 */
1984 scroll: (args: UiScrollArgs) => Promise<UiScrollResult>;
1985 /**
1986 * Moves the focus ring of one of this plugin's sites onto an element it
1987 * drew there, as the DOM's `element.focus()`, while it holds the keys.
1988 *
1989 * Raised as the event `ui.focus`, origin `plugin`; the engine's inverse
1990 * marks the element. The keyboard is the person's to give: a site not
1991 * holding it, or holding it on another plugin's element, is `{ deny }`.
1992 *
1993 * @param args `requestId` (which site: a pane's id, the band's) and `key`
1994 * (the element's, as drawn)
1995 * @returns `{}` once it moved, or `{ deny }` saying why not
1996 * @example
1997 * onPress: () => $.ui.focus({ requestId: "files", key: "row:0" })
1998 */
1999 focus: (args: UiFocusArgs) => Promise<UiFocusResult>;
2000 };
2001 /**
2002 * Completions through the session's own client and credentials.
2003 */
2004 model: {
2005 /**
2006 * Runs one text completion through the session's own API client and
2007 * resolves to the reply's text.
2008 *
2009 * No tools, no history, no system prompt beyond the CLI's identity block
2010 * and `request.system`.
2011 *
2012 * @param request the model (an alias such as `haiku`, or a full id,
2013 * resolved like a `--model` value), the prompt, and a token cap
2014 * @returns the reply's text
2015 * @example
2016 * const reply = await $.model.complete({ model: "haiku", prompt: "Hi." })
2017 */
2018 complete: (request: ModelCompleteRequest) => Promise<string>;
2019 /**
2020 * Runs one tool-less completion over the session's OWN transcript, sharing
2021 * the main thread's prompt cache; the reply's text and the fork's usage.
2022 *
2023 * Not `complete`: sharing the cache prefix means the model and system
2024 * prompt are the session's, read from its last turn's cache-safe snapshot,
2025 * and tools are denied. Null on a cold snapshot or an API error.
2026 *
2027 * @param request the one user message the fork answers
2028 * @returns the reply's text with the fork's usage, or null on a cold
2029 * snapshot or an API error
2030 * @example
2031 * const reply = await $.model.fork({ prompt: "One line to learn?" })
2032 * if (reply !== null) $.ui.log(`${reply.usage.output_tokens} tokens`)
2033 */
2034 fork: (request: ModelForkRequest) => Promise<ModelForkResult | null>;
2035 /**
2036 * Picks one of `labels` for `text` with one completion over
2037 * `$.model.complete` and a fixed classifier prompt.
2038 *
2039 * `text` is data; the model answers with a label alone. It resolves
2040 * `undefined` when the answer named none of `labels`. A failed request,
2041 * an abort or a reply with no text rejects, naming the cause.
2042 *
2043 * @param text what to classify
2044 * @param labels the labels to choose from (2 or more)
2045 * @param options `model`: an alias or id; default the engine's small
2046 * fast model
2047 * @returns the label the model named, or undefined when it named none;
2048 * rejects when the request fails or the reply has no text
2049 * @example
2050 * const kind = await $.model.classify(e.text, ["bug", "feature"])
2051 * if (kind === undefined) return next(e)
2052 */
2053 classify: (text: string, labels: readonly string[], options?: ClassifyOptions) => Promise<string | undefined>;
2054 };
2055 /**
2056 * Sound: clip playback and platform speech.
2057 */
2058 audio: {
2059 /**
2060 * Plays one audio clip, starting now; clips are not queued, so two calls
2061 * play together (a bed under speech).
2062 *
2063 * `{ asset }` is the plugin's own file, loaded by the engine and played
2064 * through the platform's player (`afplay` on macOS). Resolves when
2065 * playback ends; rejects, naming the cause, when the clip cannot play.
2066 *
2067 * @param clip the plugin's own file (`{ asset }`), a URL the engine
2068 * fetches, or the bytes as base64 with their MIME type
2069 * @param options `shouldLoop`, `gain`, and an AbortSignal that stops the
2070 * clip
2071 */
2072 play: (clip: AudioClip, options?: PlayOptions) => Promise<void>;
2073 /**
2074 * Speaks `text` with the platform's own synthesizer (`say` on macOS).
2075 * Plain text.
2076 *
2077 * Utterances are queued among themselves; clips are not. Resolves when
2078 * the utterance has ended; rejects, naming the cause, when there is no
2079 * synthesizer, the voice is not installed, or the utterance failed.
2080 *
2081 * @param text what to say, as plain text
2082 * @param options `voice`: the system voice's exact name (`Samantha`);
2083 * absent, the synthesizer's default
2084 * @returns which synthesizer spoke, once the utterance has ended
2085 */
2086 speak: (text: string, options?: SpeakOptions) => Promise<SpeakResult>;
2087 };
2088 /**
2089 * The engine's connected MCP servers.
2090 */
2091 mcp: {
2092 /**
2093 * Calls `tool` on one of the engine's connected MCP servers with the
2094 * engine's own connection and credentials.
2095 *
2096 * A `cached` server is dialed on first use. Resolves to the tool's result
2097 * as MCP returns it: `content` blocks and `isError`. No permission prompt:
2098 * the plugin's call, seen by the hooks above it, is the grant.
2099 *
2100 * @param server the server's name as /mcp lists it (`claude.ai Gmail`;
2101 * the tool-name spelling `claude_ai_Gmail` is accepted too)
2102 * @param tool the tool's name on that server (`create_draft`)
2103 * @param args the tool's arguments; none when absent
2104 * @returns the tool's result as MCP returns it: `content` blocks and
2105 * `isError`
2106 * @example
2107 * const { content } = await $.mcp.call("claude.ai Gmail", "create_draft")
2108 */
2109 call: (server: string, tool: string, args?: Record<string, unknown>) => Promise<McpToolResult>;
2110 };
2111 /**
2112 * The running session, read as plain data, and compacting it.
2113 */
2114 session: {
2115 /**
2116 * Returns the transcript so far, one entry per user or assistant
2117 * message; progress rows, `$.ui.log` lines and notices are not messages.
2118 *
2119 * Each entry is a SessionMessage, `{ role, text, toolUses }` (a user
2120 * message may add `toolResults`; a `toolUses` entry adds its `result` and
2121 * `text` once answered). A long transcript answers its newest 4096.
2122 *
2123 * @example
2124 * const last = (await $.session.messages()).at(-1)
2125 */
2126 messages: () => Promise<SessionMessage[]>;
2127 /**
2128 * Returns the directory the session runs in, absolute.
2129 */
2130 cwd: () => Promise<string>;
2131 /**
2132 * Returns the main loop's model, as `/model` shows it.
2133 */
2134 model: () => Promise<string>;
2135 /**
2136 * Returns how many prompts the user has sent this session (user turns in
2137 * the transcript).
2138 */
2139 turns: () => Promise<number>;
2140 /**
2141 * Returns the session's id (the transcript file's name).
2142 */
2143 id: () => Promise<string>;
2144 /**
2145 * Returns the git repository the session runs in, read from the working
2146 * copy on each call; null when the directory is not inside one.
2147 *
2148 * @example
2149 * const repo = await $.session.repo(); const publicRepo = !repo?.internal
2150 */
2151 repo: () => Promise<SessionRepo | null>;
2152 /**
2153 * Returns every surface the session draws on, each once: `terminal` under
2154 * the REPL first, then the remote ones in the order they attached.
2155 *
2156 * A session may draw on several at once (a terminal and two phones):
2157 * clients attach (`session.attach`) and detach, and a render hook still
2158 * reads `e.surface` per ask. Empty in a plain -p run; never rejects.
2159 *
2160 * @example
2161 * const inApp = (await $.session.surfaces()).some(s => s !== "terminal")
2162 */
2163 surfaces: () => Promise<readonly RenderSurface[]>;
2164 /**
2165 * Returns the first of `$.session.surfaces()`, or null where nothing
2166 * draws.
2167 *
2168 * @deprecated use `surfaces()`; a session may draw on several surfaces at
2169 * once
2170 */
2171 surface: () => Promise<RenderSurface | null>;
2172 /**
2173 * Returns the context window's fill, the rate-limit windows and the
2174 * cost, as the status line has them; with `breakdown`, by category too.
2175 *
2176 * The plain call costs nothing; `"full"` counts each category with the
2177 * token-count API as /context does, `"summary"` estimates locally, and
2178 * `context.breakdown` comes back in the SDK's `get_context_usage` shape.
2179 *
2180 * @param args `{ breakdown, columns }`: how the breakdown is counted and
2181 * the width its grid is drawn in; nothing for the status line's figures
2182 * @returns `{ context, rateLimits, cost }` as the status line has them
2183 * @example
2184 * const { context } = await $.session.usage()
2185 * if ((context.percent ?? 0) >= 85) await $.session.compact()
2186 * @example
2187 * const usage = await $.session.usage({ breakdown: "full", columns })
2188 * for (const row of usage.context.breakdown?.gridRows ?? []) draw(row)
2189 */
2190 usage: (args?: SessionUsageArgs) => Promise<SessionUsage>;
2191 /**
2192 * Compacts the conversation: the event `session.compact` with `trigger`
2193 * `plugin`, the same call `/compact` makes, between turns.
2194 *
2195 * It runs through every hook but the calling one, then core: a summary
2196 * and the kept messages in the transcript's place. Resolves `{ skip }`
2197 * when a hook vetoed it; rejects while a turn runs.
2198 *
2199 * @example
2200 * const { skip } = await $.session.compact({ instructions: "the plan" })
2201 */
2202 compact: EventCalls['session']['compact'];
2203 /**
2204 * Holds the session's Anthropic credential on the host and answers an
2205 * opaque handle and its kind; the secret never reaches the plugin.
2206 *
2207 * The handle is spent through `$.http.fetch(url, { auth: handle })`,
2208 * which sets the credential header, only for a first-party host. Null
2209 * where the build or the provider has no first-party credential to hold.
2210 *
2211 * @example
2212 * await $.http.fetch(url, { auth: (await $.session.authorize())?.handle })
2213 */
2214 authorize: () => Promise<SessionAuthorization>;
2215 };
2216 /**
2217 * The running model turn: ending it.
2218 */
2219 turn: {
2220 /**
2221 * Cancels the running model turn: the one whose id `turn.start` handed
2222 * this plugin, its running tools stopped, no interruption marker.
2223 *
2224 * The event `turn.abort`, seen by the hooks above; the prompt this
2225 * plugin submits next is the context. Rejects, naming both ids, when
2226 * `turnId` is not the running turn's; a hook may end its own turn.
2227 *
2228 * @param input `turnId`: the id `turn.start` carried
2229 * @example
2230 * on("turn.start", ($, e, next) => { held = e.turnId; return next(e) })
2231 */
2232 abort: (input: OpEventOf['turn.abort']) => Promise<void>;
2233 };
2234 /**
2235 * Submitting a prompt the model reads as a user turn, and putting a text
2236 * in the person's prompt box, written or proposed.
2237 */
2238 prompt: {
2239 /**
2240 * Submits a prompt: the event `prompt.submit`, the same call the engine
2241 * makes for a typed prompt; `input.text` runs when the session is idle.
2242 *
2243 * It goes through every hook but the calling one (the plugin's others
2244 * see it) with `e.origin` `{ kind: 'plugin', name }`, the name the
2245 * model reads it under unless a hook leaves it out of its answer.
2246 *
2247 * @example
2248 * void $.prompt.submit({ text: "List the TODOs you just mentioned." })
2249 */
2250 submit: EventCalls['prompt']['submit'];
2251 /**
2252 * Writes `input.text` into the prompt box as the person's draft, cursor
2253 * at its end, replacing what it held: the event `prompt.fill`.
2254 *
2255 * It goes through every other plugin's hook with `e.origin` `{ kind:
2256 * 'plugin', name }`. Resolves `{ isFilled: false }` when a dialog holds
2257 * the keys or the session has no box (headless); nothing is submitted.
2258 *
2259 * @example
2260 * const { isFilled } = await $.prompt.fill({ text: "/review latest" })
2261 */
2262 fill: EventCalls['prompt']['fill'];
2263 /**
2264 * Proposes `input.text` as the prompt box's dim suggestion, Tab to take:
2265 * the event `prompt.suggest`, as the engine's own guess after a turn.
2266 *
2267 * It goes through every other plugin's hook with `e.origin` `{ kind:
2268 * 'plugin', name }`, the engine's own suggestions on or off; `{ isShown:
2269 * false }` while the box holds text, a turn runs, or headless (no box).
2270 *
2271 * @example
2272 * void $.prompt.suggest({ text: "run the tests you just wrote" })
2273 */
2274 suggest: EventCalls['prompt']['suggest'];
2275 };
2276 /**
2277 * The tools the model has in this session, and running one.
2278 */
2279 tool: {
2280 /**
2281 * Returns the tools the model can call now, built-in and MCP alike, in
2282 * the order the model sees them.
2283 *
2284 * @example
2285 * const names = (await $.tool.list()).map(t => t.name)
2286 */
2287 list: () => Promise<ToolInfo[]>;
2288 /**
2289 * Calls a tool: the event `tool.call`, the same call the engine makes for
2290 * the model's tool calls, under a `tool_use_id` of its own.
2291 *
2292 * It runs through every hook but the calling one (the plugin's others
2293 * see it), the permission check and its dialog, then the tool. Rejects
2294 * when no tool has that name or the call is aborted.
2295 *
2296 * @example
2297 * const { text } = await $.tool.call({ tool: "Read", file_path: "a.md" })
2298 */
2299 call: EventCalls['tool']['call'];
2300 /**
2301 * Asks the engine's permission decision for a tool call now: the event
2302 * `tool.check`, resolved to `{ decision, reason?, rule? }`.
2303 *
2304 * The hooks run (the calling hook's own frame skipped, `next.origin` this
2305 * plugin, no `tool_use_id`); nothing runs, no dialog opens, no PreToolUse
2306 * hook or classifier is asked.
2307 *
2308 * @example
2309 * const { decision } = await $.tool.check({ tool: "Read", input })
2310 */
2311 check: EventCalls['tool']['check'];
2312 /**
2313 * Declares a tool the model can call from the next prompt on: the name,
2314 * description and input schema of `mcp__<plugin>__<name>`.
2315 *
2316 * Serve it with a `tool.call` hook on `{ tool: "mcp__<plugin>__<name>" }`
2317 * that returns the result (a call no hook answers fails); a name registered
2318 * again is replaced. Rejects until the session binds, at `session.start`.
2319 *
2320 * @param tool `name`, `description` (what the model reads), `inputSchema`
2321 * (a JSON schema object; default `{ type: "object" }`)
2322 * @returns `{ tool }`, the registered tool's full name
2323 * `mcp__<plugin>__<name>`
2324 * @example
2325 * await $.tool.register({ name: "weather", description: "Weather." })
2326 */
2327 register: (tool: ToolSpec) => Promise<OpValueOf['tool.register']>;
2328 };
2329 /**
2330 * The slash commands the person can run in this session, and running one.
2331 */
2332 command: {
2333 /**
2334 * Returns the slash commands the person can run now, built-in, plugin
2335 * and MCP alike, in the order the typeahead lists them.
2336 *
2337 * @example
2338 * const names = (await $.command.list()).map(c => c.name)
2339 */
2340 list: () => Promise<CommandInfo[]>;
2341 /**
2342 * Runs a slash command as if the person typed `/command args`: the
2343 * event `command.run`, queued and run once the session is idle.
2344 *
2345 * It runs through every hook but the calling one with `e.origin`
2346 * `{ kind: 'plugin', name }`, its lines in the transcript. Rejects an
2347 * unknown name, and inside a hook the turn is waiting on.
2348 *
2349 * @example
2350 * const { text } = await $.command.run({ command: "status" })
2351 */
2352 run: EventCalls['command']['run'];
2353 /**
2354 * Declares the slash command `/<name>` for this session, listed in the
2355 * typeahead from the next keystroke on.
2356 *
2357 * Serve it with a `command.run` hook on `{ command: "<name>" }` that
2358 * returns `{ text }`; a run no hook answers says so as its output.
2359 * Registering a name again replaces it; a built-in's name is refused.
2360 *
2361 * @param command `name`, `description` (what the menu shows),
2362 * `argumentHint` (dim after the name), `immediate` (runs mid-turn)
2363 * @returns `{ command }`, the registered name
2364 * @example
2365 * await $.command.register({ name: "hello", description: "Says hi." })
2366 */
2367 register: (command: CommandSpec) => Promise<OpValueOf['command.register']>;
2368 };
2369 /**
2370 * Every row of the settings menu (`/config`), the panel's own and each
2371 * enabled plugin's `userConfig` fields alike: listing and changing them.
2372 */
2373 config: {
2374 /**
2375 * Returns the rows the `/config` menu would draw now, in its order,
2376 * each with its current value, its kind, its owner and its lock.
2377 *
2378 * After every `config.describe` hook: a hidden row is left out, a
2379 * relabelled one carries the new label.
2380 *
2381 * @example
2382 * const theme = (await $.config.list()).find(row => row.key === "theme")
2383 */
2384 list: () => Promise<ConfigRow[]>;
2385 /**
2386 * Changes one row as if the person did in the menu: the event
2387 * `config.set` with `origin` `{ kind: 'plugin', name }`, then the writer.
2388 *
2389 * Through the other plugins' hooks, this plugin's own skipped; `{ deny }`
2390 * when a hook refused, the value does not fit, a trusted source owns the
2391 * row or only its dialog changes it. Rejects a key no row has.
2392 *
2393 * @param args `key` (as `list` names it) and `value` (the row's kind)
2394 * @returns `{ value }` once written, or `{ deny }`
2395 * @example
2396 * const { deny } = await $.config.set({ key: "verbose", value: true })
2397 */
2398 set: EventCalls['config']['set'];
2399 };
2400 /**
2401 * Subagents.
2402 */
2403 agent: {
2404 /**
2405 * Spawns a subagent: the event `agent.spawn`, the same call the engine
2406 * makes when the Agent tool starts one; the engine fills the rest.
2407 *
2408 * It runs every hook but the calling one, then the Agent tool in the
2409 * background under this call's origin: `{ model, agentId }` once the
2410 * subagent started (its answer is its `turn.complete`), or `{ deny }`.
2411 *
2412 * @example
2413 * const { agentId } = await $.agent.spawn({ prompt: "Read README.md." })
2414 */
2415 spawn: EventCalls['agent']['spawn'];
2416 /**
2417 * Returns the session's subagents so far, the ones the model spawned and
2418 * the ones plugins did alike.
2419 */
2420 list: () => Promise<AgentInfo[]>;
2421 };
2422 /**
2423 * The file system as the engine's own process reaches it, text only
2424 * (UTF-8); a relative path is under the session's working directory.
2425 *
2426 * An absolute path is used as given. A read or a write over 4 MiB
2427 * rejects; what the operating system refuses rejects with its errno
2428 * (`ENOENT`, `EACCES`). Where a path may go is an `fs.*` hook's to say.
2429 */
2430 fs: {
2431 /**
2432 * Reads a file and returns its text. Rejects when missing.
2433 *
2434 * @param path relative to the working directory, or absolute
2435 * @returns the file's text
2436 * @example
2437 * const readme = await $.fs.read("README.md")
2438 */
2439 read: (path: string) => Promise<string>;
2440 /**
2441 * Writes `text` to a file, creating it and its directories as needed.
2442 *
2443 * @param path relative to the working directory, or absolute
2444 * @param text the whole new content
2445 */
2446 write: (path: string, text: string) => Promise<void>;
2447 /**
2448 * Lists a directory: `{ name, kind, size }` per entry, by name.
2449 *
2450 * @param path the directory's path; absent, the working directory
2451 * @returns the entries, `{ name, kind, size }` each
2452 */
2453 list: (path?: string) => Promise<FsEntry[]>;
2454 /**
2455 * Returns whether the path exists; never rejects.
2456 */
2457 exists: (path: string) => Promise<boolean>;
2458 /**
2459 * Returns `{ kind, size, mtimeMs }` of the path. Rejects when missing.
2460 */
2461 stat: (path: string) => Promise<FsStat>;
2462 /**
2463 * Reads the named instruction files in every directory above the
2464 * session's original working directory, the way the engine reads CLAUDE.md.
2465 *
2466 * Root first, each `{ dir, name, content }` that exists, the content
2467 * with its `@include`s after it; with `of`, on down to that file's
2468 * directory, as the engine reads a nested CLAUDE.md when a file is read.
2469 *
2470 * @param request `names`, relative `.md` file names (no `..`) looked for
2471 * in each directory; `of`, the file whose directory the walk goes down to
2472 * @returns the files found, root first
2473 * @example
2474 * const found = await $.fs.ancestors({ names: ["AGENTS.md"] })
2475 * const stack = await $.fs.ancestors({ names: ["AGENTS.md"], of: path })
2476 */
2477 ancestors: (request: FsAncestorsRequest) => Promise<readonly FsAncestor[]>;
2478 };
2479 /**
2480 * This plugin's own key-value store, kept between sessions and hot
2481 * reloads; values are JSON data.
2482 *
2483 * A JSON file of the plugin's own under the user's Claude Code
2484 * configuration directory.
2485 */
2486 store: {
2487 /**
2488 * Returns the value under `key`, or `undefined` when unset.
2489 *
2490 * @example
2491 * const count = Number((await $.store.get("count")) ?? 0) + 1
2492 */
2493 get: (key: string) => Promise<unknown>;
2494 /**
2495 * Sets `key` to `value`, which must be JSON data.
2496 *
2497 * `get` reads back `JSON.parse(JSON.stringify(value))`: a Date is its ISO
2498 * string, an `undefined` field is dropped, a Map or Set is `{}`. Rejects
2499 * a function, a cycle, or a store over 4 MiB of JSON text in all.
2500 */
2501 set: (key: string, value: unknown) => Promise<void>;
2502 /**
2503 * Removes `key` from the store.
2504 */
2505 delete: (key: string) => Promise<void>;
2506 /**
2507 * Returns every key set, in insertion order.
2508 */
2509 keys: () => Promise<string[]>;
2510 };
2511 /**
2512 * The time and timers, each an event through the host: `clock.now` reads
2513 * the time; `clock.sleep`, `after` and `every` wait until it has passed.
2514 *
2515 * A timer's callback is the plugin's own function, kept in its environment
2516 * and run there when the wait resolves; a hot reload of the plugin cancels
2517 * its pending waits with the old environment.
2518 */
2519 clock: {
2520 /**
2521 * Resolves milliseconds since the epoch, now.
2522 *
2523 * @example
2524 * const startedAt = await $.clock.now()
2525 */
2526 now: () => Promise<number>;
2527 /**
2528 * Resolves after `ms` milliseconds; rejects at once when `signal` aborts.
2529 *
2530 * @param ms how long, in milliseconds
2531 * @param options `signal`: ends the wait early with a rejection (pass
2532 * `next.signal` so a hook's wait ends with its dispatch)
2533 * @example
2534 * await $.clock.sleep(500, { signal: next.signal })
2535 */
2536 sleep: (ms: number, options?: SleepOptions) => Promise<void>;
2537 /**
2538 * Calls `fn` once after `ms` milliseconds; `cancel()` before then stops it.
2539 *
2540 * One `clock.after` dispatch: `fn` runs when it resolves, and never when
2541 * a hook refuses it.
2542 */
2543 after: TimerCall;
2544 /**
2545 * Calls `fn` every `ms` milliseconds (at least 1) until `cancel()`.
2546 *
2547 * One `clock.every` dispatch per period: `fn` runs when it resolves and
2548 * the next period is asked; a refused period ends the interval.
2549 *
2550 * @example
2551 * const tick = $.clock.every(1000, () => $.ui.status("polling"))
2552 */
2553 every: TimerCall;
2554 };
2555 /**
2556 * The network, through the host.
2557 */
2558 http: {
2559 /**
2560 * Fetches `url` through the host (never the plugin's own network) and
2561 * resolves `{ status, ok, headers, text }` once the body is read.
2562 *
2563 * http or https, to whatever the host process can reach, unless the
2564 * administrator's policy switches refuse it; an `auth` handle from
2565 * `$.session.authorize()` rides https only, to a first-party host.
2566 *
2567 * @param url the URL (http or https)
2568 * @param init `{ method, headers, body, auth }` (body a string)
2569 * @returns `{ status, ok, headers, text }` once the body is read
2570 * @example
2571 * const { ok, text } = await $.http.fetch("https://example.com/status")
2572 */
2573 fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>;
2574 };
2575 /**
2576 * Commands on the host, run as the user the session runs as. CLI only.
2577 *
2578 * Local execution, not a network path: what a command of its own reaches
2579 * is its own, as for the Bash tool and a settings `command` hook.
2580 */
2581 process: {
2582 /**
2583 * Runs a command on the host by its argument vector (no shell) and
2584 * resolves `{ exitCode, stdout, stderr }` once it exits, any exit code.
2585 *
2586 * One shot: the whole output is read, so a background process left
2587 * writing holds the call until the timeout. Rejects when the command
2588 * cannot start or is still running then. Git runs with repo hooks off.
2589 *
2590 * @param argv the command and its arguments, `argv[0]` the executable
2591 * @param init `{ cwd, env, stdin, timeoutMs }` (cwd the session's by
2592 * default; timeout 30 s by default, ten minutes at most)
2593 * @returns `{ exitCode, stdout, stderr }` once the child exits
2594 * @example
2595 * const { exitCode, stdout } = await $.process.run(["git", "status"])
2596 */
2597 run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>;
2598 };
2599 /**
2600 * What the settings files, `--settings` and managed policy hold, as the
2601 * engine runs under it; read only.
2602 *
2603 * Every key crosses as the source holds it, `env` and the helper commands
2604 * included: nothing is filtered. The OAuth session and the global config
2605 * (~/.claude.json) are not settings and are never read.
2606 */
2607 settings: {
2608 /**
2609 * Resolves with the settings merged over every source, as the engine
2610 * reads them, or with one source's settings as loaded (`{ source }`).
2611 *
2612 * A snapshot in plain data each call; a source with no file answers
2613 * `{}`. The sources (SettingsSource) rise in precedence from `user` to
2614 * `policy`: the merge takes a key from the last source that has it.
2615 *
2616 * @param args `{ source }` to read one source; nothing for the merge
2617 * @returns the settings object, keyed as a settings.json is
2618 * @example
2619 * const { permissions } = await $.settings.read()
2620 * const policy = await $.settings.read({ source: "policy" })
2621 */
2622 read: (args?: SettingsReadArgs) => Promise<Settings>;
2623 };
2624 /**
2625 * The environment of this process, the one every Bash child, MCP server
2626 * and `$.process.run` command started after inherits.
2627 *
2628 * `get` and `set` take the variable's name as a string literal, so what a
2629 * module reads and writes is read off its source: `claude plugin validate`
2630 * lists the names, and a name the module does not spell is refused.
2631 */
2632 env: {
2633 /**
2634 * Resolves with the variable's value, or `undefined` when it is unset.
2635 *
2636 * `name` must be a string literal; `claude plugin validate` lists the
2637 * names your module reads and writes.
2638 *
2639 * @example
2640 * const home = await $.env.get("HOME")
2641 */
2642 get: (name: string) => Promise<string | undefined>;
2643 /**
2644 * Sets the variable for this process and everything it starts after, or
2645 * unsets it when `value` is `undefined`.
2646 *
2647 * `name` must be a string literal; `claude plugin validate` lists the
2648 * names your module reads and writes.
2649 *
2650 * @example
2651 * await $.env.set("GIT_PAGER", "cat")
2652 */
2653 set: (name: string, value: string | undefined) => Promise<void>;
2654 };
2655 }
2656
2657 /**
2658 * The name of an event the engine defines itself (a key of CoreEventOf);
2659 * EventName adds the declared plugin nouns' events.
2660 */
2661 type CoreEventName = keyof CoreEventOf;
2662
2663 /**
2664 * The argument of each event the engine defines itself: its call sites'
2665 * (EngineEventOf), the classic hooks' (ClassicEventOf), the calls on `$`.
2666 */
2667 type CoreEventOf = EngineEventOf & ClassicEventOf & OpEventOf;
2668
2669 type CwdChangedHookInput = BaseHookInput & {
2670 hook_event_name: 'CwdChanged';
2671 old_cwd: string;
2672 new_cwd: string;
2673 };
2674
2675 type DirectoryAddedHookInput = BaseHookInput & {
2676 hook_event_name: 'DirectoryAdded';
2677 /**
2678 * Absolute path of the directory that was added.
2679 */
2680 directory: string;
2681 /**
2682 * How the directory was added: "slash_command" for /add-dir, "register_repo_root" for the SDK control_request.
2683 */
2684 source: 'slash_command' | 'register_repo_root';
2685 };
2686
2687 /**
2688 * The `children` field every element constructor's props carry, appended
2689 * beside its own props type: one child, or a list that may nest.
2690 *
2691 * JSX types a lone child as the child itself (`<Text dimColor>done</Text>`
2692 * passes the string, `<Text>{count}</Text>` the number), and a mapped list
2693 * beside a sibling as a nested list (`<Box>{rows.map(row)}<Text>ok</Text>`).
2694 */
2695 export type ElementChildren = {
2696 children?: RenderChildren;
2697 };
2698
2699 /**
2700 * An element as `$.ui.resolve(e)` hands it out: a constructor from props to
2701 * the frozen plain-data element, `children` among the props as JSX passes.
2702 *
2703 * `const { Box } = $.ui.resolve(e)` then `<Box gap={1}>...</Box>` compiles to
2704 * `h(Box, { gap: 1 }, ...children)`, and `h` calls a function tag with its
2705 * props, so the table's constructors are the JSX tags.
2706 */
2707 export type ElementConstructor<P> = (props: P & ElementChildren) => RenderElement;
2708
2709 /**
2710 * Every element name of every surface: what a table handed out is completed to
2711 * (an omitted one draws a fragment; see `ui.resolve`).
2712 */
2713 export type ElementName = {
2714 [P in RenderSurface]: keyof Elements[P];
2715 }[RenderSurface];
2716
2717 /**
2718 * The element constructors each surface draws, by `e.surface`: what
2719 * `$.ui.resolve(e)` returns and a `ui.resolve` hook passes on; no globals.
2720 *
2721 * All carry `Box`, `Text`, `Button`, `Link`, `Code`; every remote surface
2722 * `Svg`; all but mobile `Input` and `Select`; terminal and desktop `Client`;
2723 * terminal `Raster`. Narrowed on `e.surface`, that table; else the union.
2724 */
2725 export type Elements = {
2726 terminal: {
2727 Box: ElementConstructor<BoxProps>;
2728 Text: ElementConstructor<TextProps>;
2729 Button: ElementConstructor<ButtonProps>;
2730 Input: ElementConstructor<InputProps>;
2731 Select: ElementConstructor<SelectProps>;
2732 Link: ElementConstructor<LinkProps>;
2733 Code: ElementConstructor<CodeProps>;
2734 Client: ElementConstructor<ClientProps>;
2735 Raster: ElementConstructor<RasterProps>;
2736 };
2737 desktop: {
2738 Box: ElementConstructor<BoxProps>;
2739 Text: ElementConstructor<TextProps>;
2740 Button: ElementConstructor<ButtonProps>;
2741 Input: ElementConstructor<InputProps>;
2742 Select: ElementConstructor<SelectProps>;
2743 Svg: ElementConstructor<SvgProps>;
2744 Link: ElementConstructor<LinkProps>;
2745 Code: ElementConstructor<CodeProps>;
2746 Client: ElementConstructor<ClientProps>;
2747 };
2748 /**
2749 * No `Input` or `Select`: the control protocol carries presses (ui_press)
2750 * but no ui_input or ui_select yet; not a limit of the device.
2751 *
2752 * The table grows when those messages exist.
2753 */
2754 mobile: {
2755 Box: ElementConstructor<BoxProps>;
2756 Text: ElementConstructor<TextProps>;
2757 Button: ElementConstructor<ButtonProps>;
2758 Svg: ElementConstructor<SvgProps>;
2759 Link: ElementConstructor<LinkProps>;
2760 Code: ElementConstructor<CodeProps>;
2761 };
2762 /**
2763 * The desktop's table without `Client`: a remote `Client`'s module, presses
2764 * and posts (ui_client_module, ui_client_press, ui_message) name no surface.
2765 *
2766 * They are the desktop's alone today, not a limit of the editor's webview:
2767 * the table gains `Client` when those asks name a surface.
2768 */
2769 vscode: {
2770 Box: ElementConstructor<BoxProps>;
2771 Text: ElementConstructor<TextProps>;
2772 Button: ElementConstructor<ButtonProps>;
2773 Input: ElementConstructor<InputProps>;
2774 Select: ElementConstructor<SelectProps>;
2775 Svg: ElementConstructor<SvgProps>;
2776 Link: ElementConstructor<LinkProps>;
2777 Code: ElementConstructor<CodeProps>;
2778 };
2779 };
2780
2781 /**
2782 * The table `ui.resolve` answers for an argument of surface `P`.
2783 */
2784 export type ElementTable<P extends RenderSurface = RenderSurface> = Elements[P];
2785
2786 /**
2787 * 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.
2788 */
2789 type ElicitationHookInput = BaseHookInput & {
2790 hook_event_name: 'Elicitation';
2791 mcp_server_name: string;
2792 message: string;
2793 mode?: 'form' | 'url';
2794 url?: string;
2795 elicitation_id?: string;
2796 requested_schema?: Record<string, unknown>;
2797 };
2798
2799 /**
2800 * 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.
2801 */
2802 type ElicitationResultHookInput = BaseHookInput & {
2803 hook_event_name: 'ElicitationResult';
2804 mcp_server_name: string;
2805 elicitation_id?: string;
2806 mode?: 'form' | 'url';
2807 action: 'accept' | 'decline' | 'cancel';
2808 content?: Record<string, unknown>;
2809 };
2810
2811 /**
2812 * The input of `engine.create`: the fold that builds `$`, once per load,
2813 * core innermost.
2814 *
2815 * A hook is written in post-order: `const built = await next(e)` is `$` as
2816 * built so far; `return { ...built, voice: { say } }` adds this plugin's noun.
2817 * See EngineEventOf's `engine.create` for what a step may and may not do.
2818 */
2819 export type EngineCreateInput = {
2820 /**
2821 * In list order, first is outermost (managed plugins first, so an org
2822 * plugin's withholding wins).
2823 */
2824 plugins: readonly string[];
2825 };
2826
2827 /**
2828 * What an `engine.create` hook returns: `$` as built so far with this
2829 * plugin's nouns added, less any it withheld.
2830 *
2831 * Every declared noun is optional here. Between hooks it crosses the chain
2832 * as interface descriptors; a hook sees objects (EngineInterfaceBuilt).
2833 */
2834 export type EngineCreateResult = Partial<EngineInterface> & {
2835 readonly [noun: string]: unknown;
2836 };
2837
2838 /**
2839 * The events the engine raises at its call sites, and `engine.create`; the
2840 * classic settings hooks' events are ClassicEventOf.
2841 *
2842 * At every one, a hook that fails (throws, overruns its budget, answers a
2843 * wrong shape) is skipped: the hooks beneath and core run in its place, or
2844 * its last `next` result stands; the failure is reported, naming it.
2845 */
2846 export type EngineEventOf = {
2847 /**
2848 * Fires when the engine is about to run a tool. `next(e)` runs the hooks
2849 * beneath, then core (the permission prompt, the tool itself).
2850 *
2851 * Return `{ deny: reason }` to refuse or `{ result }` to answer yourself; a
2852 * hook that returns while its `next` is pending aborts what runs beneath.
2853 * The managed-settings hooks run first: their deny is the call's result.
2854 */
2855 'tool.call': ToolCallInput;
2856 /**
2857 * Fires when the engine decides whether a tool call may run, after the
2858 * `tool.call` and PreToolUse hooks and before the mode settles an ask.
2859 *
2860 * `next(e)` resolves to the engine's verdict (rules, mode, the tool's own
2861 * check, PreToolUse's decision); return any `{ decision }`. `$.tool.check`
2862 * runs the same chain and executes nothing.
2863 *
2864 * @example
2865 * on("tool.check", { tool: "Read" }, () => ({ decision: "allow" }))
2866 */
2867 'tool.check': ToolCheckInput;
2868 /**
2869 * Fires when the engine is about to draw a component: once per input value
2870 * (props, viewport width), plugin load or `$.ui.invalidate("ui.render")`.
2871 *
2872 * A repaint reuses the answer; a clock invalidates. `next(e)` resolves to the
2873 * drawing: return it, wrap it, draw your own, or rewrite `props`. A tree that
2874 * does not validate draws the engine's own; `--plugin-dir` is told why.
2875 */
2876 'ui.render': RenderInput;
2877 /**
2878 * Fires when the plugins load (not per draw), once per surface, component
2879 * and plugin: `e` names the surface and component, never the props.
2880 *
2881 * `next(e)` resolves to the surface's table, which `$.ui.resolve(e)` then
2882 * reads. Return it, one with an element restyled for every other plugin,
2883 * or one with a key left out (a fragment there); own table: hook skipped.
2884 */
2885 'ui.resolve': ResolveInput;
2886 /**
2887 * Fires when a `Button` a render hook drew is pressed on a surface; `e` is
2888 * `{ plugin, element, component, surface }`, `element` the button's `key`.
2889 *
2890 * `next(e)` runs the hooks beneath, then core: the element's own `onPress`
2891 * closure, in its plugin's environment, resolving to `{ element }`. Return
2892 * `next(e)` to let the press through, or `{ element }` to take it.
2893 */
2894 'ui.press': UiPressArgument;
2895 /**
2896 * Fires when an `Input` a render hook drew changes or is submitted; `e` is
2897 * `{ plugin, element, component, surface, kind, value }`.
2898 *
2899 * `next(e)` runs the hooks beneath, then the element's own `onInput` or
2900 * `onSubmit` with `e.value` as the chain left it, resolving to `{ element,
2901 * value }`; `next({ ...e, value })` rewrites the typing, an answer takes it.
2902 */
2903 'ui.input': UiInputArgument;
2904 /**
2905 * Fires when a `Select` a render hook drew is picked from; `e` is
2906 * `{ plugin, element, component, surface, value }`.
2907 *
2908 * `next(e)` runs the hooks beneath, then the element's own `onSelect` with
2909 * `e.value` as the chain left it, resolving to `{ element, value }`;
2910 * `next({ ...e, value })` rewrites the pick, an answer takes it.
2911 */
2912 'ui.select': UiSelectArgument;
2913 /**
2914 * Fires when a `Client` THIS plugin drew posts from its surface module
2915 * (`surface.post(data)`); only this plugin's hooks see it.
2916 *
2917 * `next.origin` names `client`: `data` came from code. Core answers `{}`;
2918 * `next({ ...e, data })` rewrites the data; `{ props }` hands the posting
2919 * instance its next props without a redraw. One per instance per frame.
2920 */
2921 'ui.message': UiMessageArgument;
2922 /**
2923 * Fires before a site's window moves: the person's wheel or scroll keys on
2924 * a `Pane` body or the `AbovePrompt` band, at its edges too; `$.ui.scroll`.
2925 *
2926 * `next(e)` moves it to `e.offset` and draws: `{}`; `next({ ...e, offset
2927 * })` elsewhere; no `next` (`{}` or `{ deny }`) leaves it undrawn, so a hook
2928 * drawing its own rows under a header moves them by `e.by` and invalidates.
2929 *
2930 * @example
2931 * on("ui.scroll", { requestId: "log" }, ($, e) => (scrollOwnRows(e.by), {}))
2932 */
2933 'ui.scroll': UiScrollInput;
2934 /**
2935 * Fires before a site's focus ring moves: the person's Tab, arrows or click
2936 * in a `Pane` or the band; an `autoFocus` element taking it; `$.ui.focus`.
2937 *
2938 * `next(e)` lands it on `e.element` (absent: one of the engine's stops) and
2939 * draws: `{}`; `next({ ...e, element })` on another of `e.plugin`'s; no
2940 * `next` (`{}` or `{ deny }`) keeps it where it was, drawn as it was.
2941 *
2942 * @example
2943 * on("ui.focus", { requestId: "list" }, ($, e, next) => (mark(e), next(e)))
2944 */
2945 'ui.focus': UiFocusInput;
2946 /**
2947 * Fires when the engine offers an agent type to the model, in the agent
2948 * listing and again at dispatch; `next(e)` resolves to `{ isOffered: true }`.
2949 *
2950 * Return `{ isOffered: false }` to keep the type out of the listing and
2951 * refuse its dispatch. A hook that fails passes it through.
2952 *
2953 * @example
2954 * on("agent.offer", { agent: "Plan" }, () => ({ isOffered: false }))
2955 */
2956 'agent.offer': AgentOfferInput;
2957 /**
2958 * Fires when the Agent tool is about to start a subagent, everything
2959 * decided and its model not yet resolved.
2960 *
2961 * `next(e)` resolves to `{ model }`. Return it, `next({ ...e, model })`,
2962 * `{ model }` of your own (an alias resolves like the tool's parameter), or
2963 * `{ deny: reason }`.
2964 */
2965 'agent.spawn': AgentSpawnInput;
2966 /**
2967 * Fires when a prompt is submitted, before the turn starts. `next(e)` runs
2968 * the hooks beneath and the UserPromptSubmit settings hooks.
2969 *
2970 * Rewrite with `next({ ...e, text })` (the user message on screen follows)
2971 * or stop it with `{ drop: reason }`; a broken plugin never blocks a prompt.
2972 * A prompt typed while a turn ran fires at Enter, with that turn's id.
2973 */
2974 'prompt.submit': PromptSubmitInput;
2975 /**
2976 * Fires when a text is about to be written into the prompt box as the
2977 * person's draft (a plugin's `$.prompt.fill`); `next(e)` writes it.
2978 *
2979 * Rewrite with `next({ ...e, text })`, or answer `{ isFilled: false }`
2980 * without `next` to keep it out; `origin` passes on as received. Core
2981 * answers `{ isFilled: false }` where no box can take it (a dialog is up).
2982 *
2983 * @example
2984 * on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
2985 */
2986 'prompt.fill': PromptFillInput;
2987 /**
2988 * Fires when a text is proposed as the prompt box's dim suggestion, Tab to
2989 * take: the engine's guess after a turn, or a plugin's `$.prompt.suggest`.
2990 *
2991 * `next(e)` shows it: `{ isShown }`. Rewrite with `next({ ...e, text })`,
2992 * or answer `{ isShown: false }` without `next` to drop it; core answers
2993 * that too while the box holds text or a turn runs.
2994 *
2995 * @example
2996 * on("prompt.suggest", { origin: { kind: "suggestion" } }, hide)
2997 */
2998 'prompt.suggest': PromptSuggestInput;
2999 /**
3000 * Fires once per named section of the system prompt, when the engine
3001 * assembles it; `next(e)` resolves to `{ text }` as core computed it.
3002 *
3003 * Sections are cached by name for the session until
3004 * `$.ui.invalidate("prompt.section")`: an unstable answer spends the
3005 * model's prompt cache on every call. A hook that fails passes it through.
3006 *
3007 * @example
3008 * on("prompt.section", { name: "memory" }, () => ({ text: null }))
3009 */
3010 'prompt.section': PromptSectionInput;
3011 /**
3012 * Fires once per conversation, when the engine computes the context blocks
3013 * its first user message carries; `next(e)` resolves to `{ blocks }`.
3014 *
3015 * Append, drop, reorder or rewrite with `next({ ...e, blocks })`; the
3016 * engine renders what comes back, in order, until
3017 * `$.ui.invalidate("prompt.context")` or a re-read (compaction, `/clear`).
3018 *
3019 * @example
3020 * on("prompt.context", () => ({ blocks: [] }))
3021 */
3022 'prompt.context': PromptContextInput;
3023 /**
3024 * Fires once per tool, when the engine first renders the tool's schema for
3025 * the model in a session; `next(e)` resolves to `{ description }`.
3026 *
3027 * Rendered schemas are cached for the session until
3028 * `$.ui.invalidate("tool.describe")`: an unstable answer spends the model's
3029 * prompt cache on every call. A hook that fails passes it through.
3030 *
3031 * @example
3032 * on("tool.describe", { tool: "Bash" }, () => ({ description: "Shell." }))
3033 */
3034 'tool.describe': ToolDescribeInput;
3035 /**
3036 * Fires when a slash command is about to run (`/name args` typed, or a
3037 * plugin's `$.command.run`); `next(e)` resolves to `{ text }`, its output.
3038 *
3039 * Core is the engine's command (a registered one has none). Rewrite `args`
3040 * with `next`, or return `{ text }` without it to answer in its place; one
3041 * after `next` replaces a printed output, not a panel or prompt it opened.
3042 *
3043 * @example
3044 * on("command.run", { command: "hello" }, () => ({ text: "hello" }))
3045 */
3046 'command.run': CommandRunInput;
3047 /**
3048 * Fires once per command, when the engine lists it for the typeahead and
3049 * `/help`; `next(e)` resolves to `{ description, argumentHint, isHidden }`.
3050 *
3051 * Listed answers are cached for the session until
3052 * `$.ui.invalidate("command.describe")`. A hook that fails passes it
3053 * through.
3054 *
3055 * @example
3056 * on("command.describe", ($, e, next) => next({ ...e, isHidden: true }))
3057 */
3058 'command.describe': CommandDescribeInput;
3059 /**
3060 * Fires when a `/config` row is about to change, from the menu or a
3061 * plugin's `$.config.set`; `next(e)` resolves to `{ value }` once written.
3062 *
3063 * Return `{ deny: reason }` to leave the row as it is (the menu says why),
3064 * or `next({ ...e, value })` to clamp it; a value of the wrong kind for
3065 * the row is refused. A row a trusted source owns is core's to refuse.
3066 *
3067 * @example
3068 * on("config.set", { key: "theme" }, () => ({ deny: "the theme stays" }))
3069 */
3070 'config.set': ConfigSetInput;
3071 /**
3072 * Fires once per `/config` row, when the menu lists it and for
3073 * `$.config.list`; `next(e)` resolves to `{ label, description, isHidden }`.
3074 *
3075 * Relabel, re-describe or hide with `next({ ...e, isHidden: true })`; the
3076 * answers are cached until `$.ui.invalidate("config.describe")` or the
3077 * loaded plugins change. A hook that fails passes the row through.
3078 *
3079 * @example
3080 * on("config.describe", { key: "tips" }, hide) // answers isHidden: true
3081 */
3082 'config.describe': ConfigDescribeInput;
3083 /**
3084 * Fires when the engine expands a skill's prompt for the model (`/name`,
3085 * the Skill tool, a preload); `next(e)` resolves to `{ text }` as computed.
3086 *
3087 * Return `{ text }` with the text the model reads instead. A hook that
3088 * fails passes it through.
3089 *
3090 * @example
3091 * on("skill.prompt", { skill: "commit" }, () => ({ text: "A haiku." }))
3092 */
3093 'skill.prompt': SkillPromptInput;
3094 /**
3095 * Fires when the engine composes a git text the model is to write (`kind`:
3096 * `commit`, `pr`, `exemption`, `remedy`); `next(e)` resolves to `{ text }`.
3097 *
3098 * Return `{ text }` with the text the model reads instead. A hook that
3099 * fails passes it through.
3100 *
3101 * @example
3102 * on("attribution.text", { kind: "commit" }, () => ({ text: "" }))
3103 */
3104 'attribution.text': AttributionTextInput;
3105 /**
3106 * Fires once per process for each loaded plugin, before the first prompt,
3107 * and again for one that loads or reloads later; `next(e)` is `{ cwd }`.
3108 *
3109 * Observe. The first is awaited, so a `$.tool.register` here is listed by
3110 * turn one. A later one (an edit, new options, `/reload-plugins`, an enable)
3111 * runs that plugin's hooks alone, so its timers start again. Not `/clear`.
3112 *
3113 * @example
3114 * on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
3115 */
3116 'session.start': SessionStartInput;
3117 /**
3118 * Fires when a delivery reaches the session (a relay's event, a peer's
3119 * message, a Remote Control prompt), before it is queued; `{ text }`.
3120 *
3121 * Rewrite with `next({ ...e, text })`, or return `{ consumed: reason }` to
3122 * take it: nothing is queued, shown or read by the model. `origin` and
3123 * `event` pass on as received; `session.send`, its dual, is reserved.
3124 *
3125 * @example
3126 * on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
3127 */
3128 'session.receive': SessionReceiveInput;
3129 /**
3130 * Fires when the conversation is about to be compacted (`/compact`, the
3131 * threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
3132 *
3133 * Rewrite `instructions` or `messages` on the way down, the messages on
3134 * the way up, or answer `{ messages }` of your own; `{ skip: reason }`
3135 * leaves the conversation as it is. `trigger` passes on as received.
3136 *
3137 * @example
3138 * on("session.compact", { trigger: "precompute" }, () => ({ skip: "off" }))
3139 */
3140 'session.compact': SessionCompactInput;
3141 /**
3142 * Fires when a remote client joins the session's roster of attached
3143 * surfaces: it said so (ui_attach), or it first asked to draw.
3144 *
3145 * Observe (a phone joined: draw the lobby); `next(e)` resolves to
3146 * `{ clientId }`, a different return changes nothing. `$.session.surfaces()`
3147 * reads the roster; a render hook still reads `e.surface` per ask.
3148 *
3149 * @example
3150 * on("session.attach", { surface: "mobile" }, ($, e, next) => next(e))
3151 */
3152 'session.attach': SessionAttachInput;
3153 /**
3154 * Fires when a client leaves the roster: it detached, or the session ended
3155 * with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
3156 */
3157 'session.detach': SessionDetachInput;
3158 /**
3159 * Fires once per hooks module about to join the chain, at load (the set
3160 * folded and built, nothing swapped in) and at reload; core allows.
3161 *
3162 * Return `{ refuse: reason }` and it never joins: no hook, no noun, no tool
3163 * of it; the transcript names who refused. Its judges, `$` whole, are the
3164 * plugins admitted before it and the binary's; judge by `tier` and `uses`.
3165 *
3166 * @example
3167 * on("plugin.register", { tier: "user" }, () => ({ refuse: "managed only" }))
3168 */
3169 'plugin.register': PluginRegisterInput;
3170 /**
3171 * Fires when a model turn begins, before its first model call; `next(e)`
3172 * resolves to `{ turnId }`. Observe: a different return changes nothing.
3173 */
3174 'turn.start': TurnStartInput;
3175 /**
3176 * Fires when the engine is about to send a model request of a turn, main's
3177 * or a subagent's (`e.agentId`); `next(e)` resolves to the whole response.
3178 *
3179 * `next({ ...e, model })` or `effort` sends another; the turn, the index and
3180 * the message count are pinned. An answer without `next` sends no request.
3181 * Every request of the turn passes here; `turn.complete` follows the last.
3182 */
3183 'turn.step': TurnStepInput;
3184 /**
3185 * Fires when a model turn has ended, at the point its duration is reported;
3186 * `next(e)` resolves to `{ text }`, the answer. `e.reason` says why.
3187 *
3188 * Return `{ text }` with a different text to show it beneath the answer (a
3189 * synopsis, a TL;DR line); the transcript's record is never rewritten. A
3190 * hook that fails leaves the answer as it was.
3191 */
3192 'turn.complete': TurnCompleteInput;
3193 /**
3194 * Runs while `$` is being built, once per load or reload of this plugin
3195 * and before any other hook of it; `next(e)` resolves to `$` built so far.
3196 *
3197 * A step may ADD nouns and WITHHOLD nouns (leave one out, or return without
3198 * `next`); it may NOT REPLACE one another step added: the step fails, named
3199 * with both plugins. A step that fails unloads its plugin; `$` is rebuilt.
3200 */
3201 'engine.create': EngineCreateInput;
3202 };
3203
3204 /**
3205 * `$`, the first parameter of every hook. Frozen; core's interface plus
3206 * every noun the plugins' `engine.create` steps added.
3207 *
3208 * Flat, `<noun>.<event>`; it does not carry `on`, since registration happens
3209 * before `$` exists. An interface so a plugin types the noun it provides by
3210 * declaration merging, the way a jQuery plugin types `$.fn`.
3211 *
3212 * @example
3213 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
3214 */
3215 export interface EngineInterface extends CoreEngineInterface {
3216 }
3217
3218 /**
3219 * What `next(e)` resolves to at `engine.create`: `$` as the steps beneath
3220 * built it, typed as `$` is, open to nouns no declaration names yet.
3221 *
3222 * A withheld noun is on it as a stub (a step inside withheld it, or the
3223 * last fold did and this is a reload), and the host refuses an op on one a
3224 * step outside withholds later; a typed module bootstraps at load on it.
3225 */
3226 export type EngineInterfaceBuilt = EngineInterface & {
3227 readonly [noun: string]: unknown;
3228 };
3229
3230 /**
3231 * The engine's events' results.
3232 */
3233 export type EngineResultOf = {
3234 /**
3235 * `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`.
3236 */
3237 'tool.call': ToolCallResult;
3238 /**
3239 * `{ decision, reason?, rule? }`.
3240 */
3241 'tool.check': ToolCheckResult;
3242 /**
3243 * The tree to draw; `{ type: "engine", ref }` is core's own drawing.
3244 */
3245 'ui.render': RenderElement;
3246 /**
3247 * The surface's element table (Elements[e.surface]): constructors from props
3248 * to a RenderElement.
3249 */
3250 'ui.resolve': ElementTable;
3251 /**
3252 * `{ element }`: the element whose handler the press reached.
3253 */
3254 'ui.press': UiPressResult;
3255 /**
3256 * `{ element, value }`: the field whose handler the input reached, and
3257 * the text it received.
3258 */
3259 'ui.input': UiInputResult;
3260 /**
3261 * `{ element, value }`: the picker whose handler the pick reached, and
3262 * the value it received.
3263 */
3264 'ui.select': UiSelectResult;
3265 /**
3266 * `{ props? }`: the posting instance's next props, when a hook hands some.
3267 */
3268 'ui.message': UiMessageResult;
3269 /**
3270 * `{}` once the window moved, or `{ deny }`.
3271 */
3272 'ui.scroll': UiScrollResult;
3273 /**
3274 * `{}` once the ring moved, or `{ deny }`.
3275 */
3276 'ui.focus': UiFocusResult;
3277 /**
3278 * `{ isOffered }`.
3279 */
3280 'agent.offer': AgentOfferResult;
3281 /**
3282 * `{ model }` or `{ deny }`.
3283 */
3284 'agent.spawn': AgentSpawnResult;
3285 /**
3286 * `{ text, context? }` or `{ drop }`.
3287 */
3288 'prompt.submit': PromptSubmitResult;
3289 /**
3290 * `{ isFilled }`.
3291 */
3292 'prompt.fill': PromptFillResult;
3293 /**
3294 * `{ isShown }`.
3295 */
3296 'prompt.suggest': PromptSuggestResult;
3297 /**
3298 * `{ text }` (null leaves the section out).
3299 */
3300 'prompt.section': PromptSectionResult;
3301 /**
3302 * `{ blocks }` (a block left out is not sent).
3303 */
3304 'prompt.context': PromptContextResult;
3305 /**
3306 * `{ description }`.
3307 */
3308 'tool.describe': ToolDescribeResult;
3309 /**
3310 * `{ text }` (the command's output, when it printed one).
3311 */
3312 'command.run': CommandRunResult;
3313 /**
3314 * `{ description, argumentHint, isHidden }`.
3315 */
3316 'command.describe': CommandDescribeResult;
3317 /**
3318 * `{ value }` once written, or `{ deny }`.
3319 */
3320 'config.set': ConfigSetResult;
3321 /**
3322 * `{ label, description, isHidden }`.
3323 */
3324 'config.describe': ConfigDescribeResult;
3325 /**
3326 * `{ text }`.
3327 */
3328 'skill.prompt': SkillPromptResult;
3329 /**
3330 * `{ text }`.
3331 */
3332 'attribution.text': AttributionTextResult;
3333 /**
3334 * `{ cwd }`.
3335 */
3336 'session.start': SessionStartResult;
3337 /**
3338 * `{ text }`, or `{ consumed }`.
3339 */
3340 'session.receive': SessionReceiveResult;
3341 /**
3342 * `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
3343 */
3344 'session.compact': SessionCompactResult;
3345 /**
3346 * `{ clientId }`.
3347 */
3348 'session.attach': SessionAttachResult;
3349 /**
3350 * `{ clientId }`.
3351 */
3352 'session.detach': SessionDetachResult;
3353 /**
3354 * `{ allow: true }`, or `{ refuse }`.
3355 */
3356 'plugin.register': PluginRegisterResult;
3357 /**
3358 * `{ turnId }`.
3359 */
3360 'turn.start': TurnStartResult;
3361 /**
3362 * The response: `{ turnId, index, answer, toolUses, stopReason, usage }`.
3363 */
3364 'turn.step': TurnStepResult;
3365 /**
3366 * `{ text }`.
3367 */
3368 'turn.complete': TurnCompleteResult;
3369 /**
3370 * `$` as built so far, with this plugin's interface added and any it
3371 * withheld left out; `next(e)` resolves to EngineInterfaceBuilt.
3372 */
3373 'engine.create': EngineCreateResult;
3374 };
3375
3376 /**
3377 * The engine's own events as calls on `$`, one signature each:
3378 * `$.<noun>.<event>(input)` resolves to its result, or to its stream.
3379 *
3380 * The engine raises its events through these same calls; a plugin's call
3381 * runs the same chain with the calling hook alone skipped. `input` may leave
3382 * out what the engine fills (`tool_use_id`, the parent agent).
3383 */
3384 export type EventCalls = {
3385 tool: {
3386 call: ToolCallOverloads;
3387 check: (input: ToolCheckArgs) => Promise<ToolCheckResult>;
3388 describe: (input: ToolDescribeInput) => Promise<ToolDescribeResult>;
3389 };
3390 command: {
3391 run: (input: CommandRunArgs) => Promise<CommandRunResult>;
3392 describe: (input: CommandDescribeInput) => Promise<CommandDescribeResult>;
3393 };
3394 config: {
3395 set: (input: ConfigSetArgs) => Promise<ConfigSetResult>;
3396 describe: (input: ConfigDescribeInput) => Promise<ConfigDescribeResult>;
3397 };
3398 prompt: {
3399 submit: (input: PromptSubmitArgs) => Promise<PromptSubmitResult>;
3400 fill: (input: PromptFillArgs) => Promise<PromptFillResult>;
3401 suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
3402 section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
3403 context: (input: PromptContextInput) => Promise<PromptContextResult>;
3404 };
3405 skill: {
3406 prompt: (input: SkillPromptInput) => Promise<SkillPromptResult>;
3407 };
3408 attribution: {
3409 text: (input: AttributionTextInput) => Promise<AttributionTextResult>;
3410 };
3411 agent: {
3412 offer: (input: AgentOfferInput) => Promise<AgentOfferResult>;
3413 spawn: (input: AgentSpawnArgs) => Promise<AgentSpawnResult>;
3414 };
3415 session: {
3416 start: (input: SessionStartInput) => Promise<SessionStartResult>;
3417 receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
3418 compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
3419 attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
3420 detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
3421 };
3422 turn: {
3423 start: (input: TurnStartInput) => Promise<TurnStartResult>;
3424 step: (input: TurnStepInput) => HookStream<TurnStepChunk, TurnStepResult>;
3425 complete: (input: TurnCompleteInput) => Promise<TurnCompleteResult>;
3426 };
3427 ui: {
3428 render: <C extends RenderComponent>(input: RenderInput<C>) => Promise<RenderElement>;
3429 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
3430 scroll: (input: UiScrollArgs) => Promise<UiScrollResult>;
3431 focus: (input: UiFocusArgs) => Promise<UiFocusResult>;
3432 };
3433 };
3434
3435 /**
3436 * The name of an event: a key of EventOf, the engine's own (CoreEventName)
3437 * and the declared plugin nouns' (NounEventName).
3438 */
3439 export type EventName = keyof EventOf;
3440
3441 /**
3442 * The argument of each event, by event name: what a hook receives as `e`
3443 * and what the call on `$` takes. Plain data, frozen to every depth.
3444 *
3445 * The engine's own events (CoreEventOf: a plugin's `$.fs.write(...)` is
3446 * a dispatch the hooks above it see) and the methods of the plugin nouns
3447 * declared on EngineInterface (NounEventOf).
3448 */
3449 export type EventOf = CoreEventOf & NounEventOf;
3450
3451 /**
3452 * The result of event `N`: what its hooks return and what their `next(e)`
3453 * resolves to.
3454 */
3455 export type EventResult<N extends EventName = EventName> = ResultOf[N];
3456
3457 /**
3458 * The hook signature of each event, `($, e, next)`, as one mapped type over
3459 * EventOf; a streaming event's is the generator form (StreamHook).
3460 *
3461 * With one handler type per event, `Events[E]` for a generic E would be a
3462 * union; as one mapped type it stays a single function type the engine
3463 * calls without a cast (TS 4.6 correlated unions).
3464 *
3465 * @param $ the engine interface, frozen, the same object at every invocation;
3466 * at `engine.create` the empty table, since `$` exists after the fold
3467 * @param e the event's argument, frozen to every depth (`e.command = "ls"`
3468 * is a type error and throws); a rewrite is a copy passed to `next`
3469 * @param next the rest of the chain; a chain a hook raises through `$` skips
3470 * this hook and runs every other, its plugin's others too
3471 */
3472 export type Events = {
3473 [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>>;
3474 };
3475
3476 type ExitReason = 'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other';
3477
3478 type FileChangedHookInput = BaseHookInput & {
3479 hook_event_name: 'FileChanged';
3480 file_path: string;
3481 event: 'change' | 'add' | 'unlink';
3482 };
3483
3484 /**
3485 * `T` with every property read-only to every depth, arrays and tuples kept
3486 * as declared: how a hook's `e` is typed.
3487 *
3488 * `e.command = 'x'` is a type error; `next({ ...e, command: 'x' })` compiles.
3489 */
3490 export type Frozen<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? {
3491 [K in keyof T]: Frozen<T[K]>;
3492 } : T extends object ? {
3493 readonly [K in keyof T]: Frozen<T[K]>;
3494 } : T;
3495
3496 /**
3497 * One file `$.fs.ancestors` found: the directory it stands in, the name it
3498 * was asked for by, and its text as the engine's memory loader reads it.
3499 */
3500 export type FsAncestor = {
3501 /**
3502 * The directory the file stands in, absolute.
3503 */
3504 dir: string;
3505 /**
3506 * The spelling the caller asked for it by.
3507 */
3508 name: string;
3509 /**
3510 * The file's text, with what its `@include`s bring after it.
3511 */
3512 content: string;
3513 };
3514
3515 /**
3516 * The argument of `$.fs.ancestors`: the file names to look for in each
3517 * directory, and the file to walk down to.
3518 */
3519 export type FsAncestorsRequest = {
3520 /**
3521 * Relative `.md` file names, each looked for in every directory.
3522 */
3523 names: readonly string[];
3524 /**
3525 * The file the walk goes on down to the directory of, relative to the
3526 * working directory or absolute; absent, it ends at the working directory.
3527 */
3528 of?: string;
3529 };
3530
3531 /**
3532 * One entry of `$.fs.list`.
3533 */
3534 export type FsEntry = {
3535 /**
3536 * The entry's name (no directory part).
3537 */
3538 name: string;
3539 /**
3540 * `file`, `dir`, or `other`.
3541 */
3542 kind: 'file' | 'dir' | 'other';
3543 /**
3544 * Bytes, for a file.
3545 */
3546 size: number;
3547 };
3548
3549 /**
3550 * What `$.fs.stat` resolves with.
3551 */
3552 export type FsStat = {
3553 /**
3554 * `file`, `dir`, or `other`.
3555 */
3556 kind: 'file' | 'dir' | 'other';
3557 /**
3558 * Bytes, for a file.
3559 */
3560 size: number;
3561 /**
3562 * Last modification, milliseconds since the epoch.
3563 */
3564 mtimeMs: number;
3565 };
3566
3567 /**
3568 * Every event (`*`), or every event under a namespace (`classic.*`: each
3569 * one whose name starts with `classic.`).
3570 */
3571 export type Glob = '*' | `${Namespace}.*`;
3572
3573 /**
3574 * The hook `on(pattern, hook)` takes for a glob or a negation: one function
3575 * placed on every selected event, `e` and the result typed as their union.
3576 *
3577 * `next.event` says which event a run is; `next.is(pattern, e)` narrows `e`
3578 * to one of them. At `engine.create` (a negation may select it) `$` is the
3579 * empty table and the hook observes the fold, as a `*` hook does.
3580 */
3581 export type GlobHook<P extends Pattern, N extends EventName = Selected<P>> = ($: EngineInterface, e: Frozen<Args<N>>, next: GlobNext<P>) => EventResult<N> | Promise<EventResult<N>>;
3582
3583 /**
3584 * `next` in a hook on a glob or a negation: an overload per selected event,
3585 * then one over their union for an `e` not yet narrowed.
3586 *
3587 * `is` narrows `e` to the selected events its pattern names; `event` is one
3588 * of the selected names.
3589 */
3590 export type GlobNext<P extends Pattern, N extends EventName = Selected<P>> = OrderedOverloads<N> & {
3591 (e: Args<N>): Promise<GlobNextResult<N>>;
3592 /**
3593 * Continues this dispatch at a tier, as Next's `to` (a managed hook's),
3594 * over the selected events' union for an `e` not yet narrowed.
3595 */
3596 readonly to: (e: Args<N>, tier: TargetTier) => Promise<GlobNextResult<N>>;
3597 readonly signal: AbortSignal;
3598 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<Args<Extract<N, Selected<M>>>>;
3599 readonly event: N;
3600 readonly origin: Origin;
3601 readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
3602 };
3603
3604 /**
3605 * What `next(e)` resolves to in a glob hook before `e` is narrowed: the
3606 * NextResult of each selected event, as a union.
3607 */
3608 type GlobNextResult<N extends EventName> = {
3609 [K in N]: NextResult<K>;
3610 }[N];
3611
3612 /**
3613 * One hook, `($, e, next)`, on event `E`.
3614 */
3615 export type Hook<E extends EventName = EventName> = Events[E];
3616
3617 /**
3618 * Why a hook failed, as its `.catch` handler reads it on `next.error`: plain
3619 * frozen data.
3620 *
3621 * `throw`: the hook threw, or returned what the site refuses, `message`
3622 * saying what; `timeout`: it outran its budget, `message` then what its last
3623 * `next()` rejected with, if it did. `budget` is the handler's own grace.
3624 */
3625 export type HookFailure = {
3626 readonly kind: 'throw' | 'timeout';
3627 /**
3628 * The thrown error's message, or for a timeout what the hook's last
3629 * `next()` rejected with; absent for a timeout with nothing rejected.
3630 */
3631 readonly message?: string;
3632 /**
3633 * The grace the handler runs under, in milliseconds; past it, the hook is
3634 * absent as if it had no handler.
3635 */
3636 readonly budget: number;
3637 };
3638
3639 /**
3640 * The hook type per pattern: an event's own (Events), `*`'s (AnyEventHook),
3641 * or a glob's over the events it selects (GlobHook), as one conditional type.
3642 *
3643 * One type, so the two-argument `on` stays ONE generic signature: as an
3644 * overload set the language service offers no tool-name completions inside
3645 * `e.tool === "`; as an index into a table TS intersects every argument.
3646 */
3647 export type HookFor<P extends Pattern> = P extends '*' ? AnyEventHook : P extends EventName ? Events[P] : GlobHook<P>;
3648
3649 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;
3650
3651 /**
3652 * The hook event `E` takes: an async generator over its chunks for a
3653 * streaming event (`turn.step`), `($, e, next) => result` for every other.
3654 */
3655 export type HookOf<E extends EventName> = Events[E];
3656
3657 /**
3658 * What a hooks module exports: `register`, and nothing the loader reads
3659 * besides.
3660 */
3661 export type HooksModule = {
3662 register: Register;
3663 };
3664
3665 /**
3666 * What `next(e)` returns on a streaming event: the stream of everything
3667 * beneath, chunk by chunk, whose return value is the result from beneath.
3668 *
3669 * `yield* next(e)` forwards the chunks and evaluates to that result; a
3670 * transforming hook reads `for await (const chunk of stream)` and then
3671 * `await stream.result`. Each call runs what is beneath afresh.
3672 */
3673 export type HookStream<C, R> = AsyncGenerator<C, R> & {
3674 /**
3675 * Settles with what beneath returned once the stream has been read to
3676 * its end; rejects if the stream is closed before that.
3677 */
3678 readonly result: Promise<R>;
3679 };
3680
3681 /**
3682 * Options of `$.http.fetch`.
3683 */
3684 export type HttpInit = {
3685 /**
3686 * `GET` (default), `POST`, ...
3687 */
3688 method?: string;
3689 /**
3690 * Request headers.
3691 */
3692 headers?: Record<string, string>;
3693 /**
3694 * The request body, as text.
3695 */
3696 body?: string;
3697 /**
3698 * The handle `$.session.authorize()` answered: the engine sets the
3699 * session's credential header itself, only for a first-party host.
3700 */
3701 auth?: string;
3702 };
3703
3704 /**
3705 * What `$.http.fetch` resolves with.
3706 */
3707 export type HttpResponse = {
3708 /**
3709 * The HTTP status code.
3710 */
3711 status: number;
3712 /**
3713 * True for a 2xx status.
3714 */
3715 ok: boolean;
3716 /**
3717 * Response headers, lower-cased names.
3718 */
3719 headers: Record<string, string>;
3720 /**
3721 * The body, as text.
3722 */
3723 text: string;
3724 };
3725
3726 /**
3727 * The keys of object pattern `P` that object member `E` cannot satisfy, `D`
3728 * levels down; `never` when there is none, which is what keeps the member.
3729 *
3730 * A key `E` does not have (an open record has every string key), or one
3731 * whose value `P` narrows to nothing.
3732 */
3733 type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
3734 [K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
3735 }[keyof P];
3736
3737 /**
3738 * The props of `Input`, every surface's one-line text field: an address,
3739 * optional texts, and the closures a change and a submit run. A leaf.
3740 *
3741 * Focused through the same ring as `Button` (`abovePrompt:focus`); while it
3742 * has focus every printable key reaches it alone and Esc returns them; a
3743 * change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
3744 */
3745 export type InputProps = {
3746 /**
3747 * The element's address: `e.element` at `ui.input`, what a matcher names.
3748 */
3749 key: string;
3750 /**
3751 * Text drawn before the field.
3752 */
3753 label?: string;
3754 /**
3755 * Text drawn dim in an empty field.
3756 */
3757 placeholder?: string;
3758 /**
3759 * The text the field holds when drawn; the person's typing replaces it
3760 * until the hook draws another.
3761 */
3762 value?: string;
3763 /**
3764 * What Enter does, in a word or two, drawn beside the field while it has
3765 * focus (`send`). Defaults to `submit`.
3766 */
3767 submitLabel?: string;
3768 /**
3769 * The site's focus ring starts here when the site takes the keyboard,
3770 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
3771 *
3772 * A pane opened with `focus`, or the person's focus chord or click, is the
3773 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
3774 * origin this plugin. A ring the person has moved stays where it was put.
3775 */
3776 autoFocus?: true;
3777 /**
3778 * Runs on every change of the text, in the plugin's own environment: the
3779 * bottom of a `ui.input` chain of kind `change`.
3780 */
3781 onInput?: (value: string, e: UiInputArgument) => void;
3782 /**
3783 * Runs on Enter with the text, in the plugin's own environment: the bottom
3784 * of a `ui.input` chain of kind `submit`. No model turn unless it asks one.
3785 */
3786 onSubmit: (value: string, e: UiInputArgument) => void;
3787 };
3788
3789 type InstructionsLoadedHookInput = BaseHookInput & {
3790 hook_event_name: 'InstructionsLoaded';
3791 file_path: string;
3792 memory_type: 'User' | 'Project' | 'Local' | 'Managed';
3793 load_reason: 'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact';
3794 globs?: string[];
3795 trigger_file_path?: string;
3796 parent_file_path?: string;
3797 };
3798
3799 /**
3800 * What `$.ui.invalidate` takes: a render event, or one of the five events
3801 * whose answers the engine caches for the session.
3802 */
3803 export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'tool.describe' | 'command.describe' | 'config.describe';
3804
3805 /**
3806 * Whether tag key `K` selects members of `I`: it does when each member gives
3807 * it ONE literal (`component: "ToolUse"` on the ToolUse variant).
3808 *
3809 * A key that is the same union on every member is a filter at runtime; it
3810 * is left out of the selection so that it cannot defeat the narrowing the
3811 * other keys give.
3812 */
3813 type IsDiscriminant<I, K> = I extends unknown ? K extends KnownKeys<I> ? IsSingleLiteral<I[K]> : true : never;
3814
3815 /**
3816 * Whether `V` is made of literals only: `"a" | "b"` is, `string` is not.
3817 */
3818 type IsLiteralValued<V> = string extends V ? false : number extends V ? false : boolean extends V ? false : [V] extends [string | number | boolean] ? true : false;
3819
3820 /**
3821 * Whether `V` is exactly one string, number or boolean literal.
3822 */
3823 type IsSingleLiteral<V> = [V] extends [string | number | boolean] ? IsUnion<V> extends true ? false : true : false;
3824
3825 /**
3826 * Whether `T` is a union of two or more members.
3827 */
3828 type IsUnion<T, U = T> = T extends unknown ? [U] extends [T] ? false : true : never;
3829
3830 /**
3831 * Plain data: what JSON holds, and what crosses between a plugin's hooks
3832 * module and its surface module whole (a `Client`'s props, a post's data).
3833 *
3834 * A function, a class instance, `undefined` or a cycle is not plain data;
3835 * the engine refuses one where it checks, and drops it where it clones.
3836 */
3837 export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
3838 readonly [key: string]: JsonValue;
3839 };
3840
3841 /**
3842 * What `next` takes in a matched hook: the variants of `e` the matcher can
3843 * match (KeptMembers), as declared, so a rewrite of a pinned field passes.
3844 */
3845 type KeptEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? KeptMembers<Args<N>, M> : never : never;
3846
3847 /**
3848 * The members of the argument union `E` matcher `P` can match, as declared;
3849 * what `next` takes, so a rewrite may change a field the matcher pinned.
3850 *
3851 * A member is dropped when `P` names a key it lacks, or gives a key, at any
3852 * depth, a value none of that key's values can equal (ImpossibleKeys).
3853 */
3854 type KeptMembers<E, P> = E extends unknown ? [ImpossibleKeys<E, P, []>] extends [never] ? E : never : never;
3855
3856 /**
3857 * The declared keys of `T`, the string and number index signatures left out.
3858 */
3859 type KnownKeys<T> = keyof {
3860 [K in keyof T as string extends K ? never : number extends K ? never : K]: 0;
3861 };
3862
3863 /**
3864 * The events whose overload must come after the rest, lest it shadow them.
3865 *
3866 * `classic.PreToolUse` shares `tool.call`'s envelope, `turn.abort` every
3867 * turn event's `turnId`, and an object of any shape is assignable to NoArgs.
3868 */
3869 type LateOverload = 'classic.PreToolUse' | 'turn.abort' | NoArgsEvent;
3870
3871 /**
3872 * The props of `Link`, a hyperlink every surface draws: an OSC 8 span on the
3873 * terminal (else its text then the URL in dim), an anchor on desktop.
3874 *
3875 * An inline element: its children are the text, strings and inline
3876 * elements; absent children the `label`, absent both the URL. The engine
3877 * bounds `href` before the tree crosses.
3878 */
3879 export type LinkProps = {
3880 /**
3881 * Where the link goes: an `https:` URL (or `http://localhost`), at most
3882 * 2048 characters of printable ASCII, spelled as `new URL(href).href`.
3883 *
3884 * No `user@host` part, no raw `@`, space or non-ASCII letter (encode them);
3885 * anything else refuses the tree the Link is in.
3886 */
3887 href: string;
3888 /**
3889 * The text drawn when the element has no children; absent both, the URL
3890 * itself is the text.
3891 */
3892 label?: string;
3893 };
3894
3895 /**
3896 * What a matcher value selects by: itself, or `unknown` for a RegExp, which
3897 * selects nothing.
3898 */
3899 type Literal<X> = X extends RegExp ? unknown : X;
3900
3901 /**
3902 * The argument a matched hook receives: `e` narrowed by `M` (Narrowed), per
3903 * event the registration covers.
3904 */
3905 export type MatchedEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Narrowed<Args<N>, M> : never : never;
3906
3907 /**
3908 * The hook `on(pattern, matcher, hook)` takes: `($, e, next)` with `e`
3909 * narrowed by the matcher (MatchedEvent), and a tagged result the same way.
3910 *
3911 * On a streaming event it is the generator form (MatchedStreamHook). `next`
3912 * takes the variants the matcher keeps, as declared (KeptEvent); `next.is`
3913 * names the events the registration covers and narrows as the matcher does.
3914 */
3915 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>, {
3916 [K in MatchedNames<P, M>]: Narrowed<Args<K>, M>;
3917 }>) => MatchedResult<P, M> | Promise<MatchedResult<P, M>>;
3918
3919 /**
3920 * The events a matched registration on `P` covers: the event named, or for a
3921 * glob every selected event whose input has each key the matcher names.
3922 */
3923 type MatchedNames<P, M = never> = P extends EventName ? P : {
3924 [N in Selected<P & string>]: [M] extends [never] ? N : keyof M extends AnyKeyOf<Args<N>> ? N : never;
3925 }[Selected<P & string>];
3926
3927 /**
3928 * What a matched hook returns: the event's result, narrowed by `M` where the
3929 * result is a union tagged by the matcher's tag keys.
3930 */
3931 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;
3932
3933 /**
3934 * The hook `on(event, matcher, hook)` takes on a streaming event: the
3935 * generator form, `e` narrowed by the matcher, `next(e)` the stream beneath.
3936 */
3937 export type MatchedStreamHook<P extends StreamingEventName, M> = ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: MatchedStreamNext<P, M>) => StreamHookBody<Chunk<P>, MatchedResult<P, M>>;
3938
3939 /**
3940 * What a matched streaming hook's `next.is(pattern, e)` narrows `e` to:
3941 * the streaming event's argument narrowed by the matcher.
3942 */
3943 type MatchedStreamNarrowings<P extends StreamingEventName, M> = {
3944 [K in P]: Narrowed<Args<K>, M>;
3945 };
3946
3947 /**
3948 * A matched streaming hook's `next`: the variants the matcher keeps, the
3949 * result tagged the same way, `next.is` narrowing as the matcher does.
3950 */
3951 type MatchedStreamNext<P extends StreamingEventName, M> = StreamNext<P, KeptEvent<P, M>, MatchedResult<P, M>, MatchedStreamNarrowings<P, M>>;
3952
3953 /**
3954 * What `on(event, matcher, hook)` takes for an argument of type `I`: the
3955 * shape of the `e` the hook wants, a partial of it at any depth.
3956 *
3957 * A leaf is `===` or a RegExp (`{ command: /^p4 / }`); an array is any-of;
3958 * an object is a partial of an OBJECT, so `{ command: { startsWith } }` is
3959 * a type error where `e` is typed and free where it is `unknown`.
3960 */
3961 export type Matcher<I, All = I> = I extends unknown ? {
3962 readonly [K in KnownKeys<I>]?: MatcherValue<I[K], MatcherValueOf<All, K>>;
3963 } & (string extends keyof I ? OpenMatcher<I, All> : unknown) : never;
3964
3965 /**
3966 * Any matcher at all, for a field typed `unknown` (a tool's input, a
3967 * result's output): the kinds the engine accepts, unchecked there.
3968 *
3969 * The four kinds: a scalar is `===`; a RegExp tests the value as a string
3970 * (`{ command: /^p4 / }`); an array matches if any element does; an object
3971 * is a partial of an object. `{ startsWith: 'p4' }` never matches a string.
3972 */
3973 type MatcherData = string | number | boolean | null | RegExp | readonly MatcherData[] | {
3974 readonly [key: string]: MatcherData;
3975 };
3976
3977 /**
3978 * The declared keys of every variant of `I` (index signatures aside).
3979 */
3980 type MatcherKeys<I> = I extends unknown ? KnownKeys<I> : never;
3981
3982 /**
3983 * What matches one value of type `V`, by the runtime's kinds:
3984 * a scalar leaf takes the value or a RegExp; an object, a partial of it.
3985 *
3986 * For an array, what matches one ELEMENT of it, since a pattern against an
3987 * array value holds when some element matches; for `unknown`, any matcher.
3988 * A scalar matches by `===`, a RegExp tests the value as a string.
3989 */
3990 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;
3991
3992 /**
3993 * What a matcher gives a key whose value is `V` on this variant and `Across`
3994 * over every variant: one MatcherOne, or an array of them matched as one-of.
3995 *
3996 * The one-of is typed over every variant, so `{ tool: ['Bash', 'Read'] }`
3997 * types on the Bash variant; with a nested pattern beside it, the pattern is
3998 * checked against a variant the one-of names, not against each of them.
3999 */
4000 type MatcherValue<V, Across = V> = MatcherOne<V> | readonly MatcherOne<Across>[];
4001
4002 /**
4003 * The type of key `K` across the variants of `I` that declare it.
4004 */
4005 type MatcherValueOf<I, K> = I extends unknown ? K extends KnownKeys<I> ? I[K] : never : never;
4006
4007 /**
4008 * One block of an MCP result: `type` and the fields that kind of block carries.
4009 */
4010 export type McpContentBlock = {
4011 /**
4012 * The block's kind: `text`, `image`, `audio`, `resource`, `resource_link`.
4013 */
4014 type: string;
4015 /**
4016 * Set on a `text` block.
4017 */
4018 text?: string;
4019 /**
4020 * Set on a `resource_link` (or embedded `resource`) block.
4021 */
4022 uri?: string;
4023 /**
4024 * Declared by an image, audio or resource block.
4025 */
4026 mimeType?: string;
4027 [field: string]: unknown;
4028 };
4029
4030 /**
4031 * The MCP branch: one variant per declared tool when McpToolInputs has
4032 * entries, else one loose variant over every `mcp__*` name.
4033 */
4034 export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
4035 [N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
4036 }[keyof McpToolInputs & string];
4037
4038 /**
4039 * The MCP branch's answer when no MCP tool is declared: every `mcp__*`
4040 * name, its args unconstrained.
4041 */
4042 type McpToolCallInputFallback = {
4043 /**
4044 * The name of the tool being called (`mcp__<server>__<tool>`); comparing
4045 * it narrows `e`. Reserved: a rewrite of it is ignored by core.
4046 */
4047 tool: McpToolName;
4048 /**
4049 * The tool_use block's id: the same at every event of the call and in
4050 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
4051 */
4052 tool_use_id: string;
4053 [argument: string]: unknown;
4054 };
4055
4056 /**
4057 * The inputs of the MCP tools this project knows, keyed by full tool name,
4058 * for declaration merging; empty by default, then every MCP tool is loose.
4059 *
4060 * A `.d.ts` in the plugin author's project (written by `/plugin-types <dir>`
4061 * from the connected servers' JSON Schemas, or by hand) adds entries under
4062 * `declare module "claude-code"`; `e.tool === <name>` then narrows to them.
4063 *
4064 * @example
4065 * interface McpToolInputs { "mcp__my_server__send": { to: string } }
4066 */
4067 export interface McpToolInputs {
4068 }
4069
4070 /**
4071 * The name of an MCP tool as the engine spells it: `mcp__<server>__<tool>`.
4072 */
4073 export type McpToolName = `mcp__${string}__${string}`;
4074
4075 /**
4076 * An MCP tools/call result as the SDK returns it, plain data.
4077 */
4078 export type McpToolResult = {
4079 /**
4080 * The result's content blocks, in order (text, image, resource,
4081 * resource_link, ...).
4082 */
4083 content: McpContentBlock[];
4084 /**
4085 * True when the server reported the call as failed; the blocks then describe
4086 * the error.
4087 */
4088 isError: boolean;
4089 /**
4090 * The server's structured result, when its tool declares an output schema.
4091 */
4092 structuredContent?: unknown;
4093 };
4094
4095 /**
4096 * 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.
4097 */
4098 type MessageDisplayHookInput = BaseHookInput & {
4099 hook_event_name: 'MessageDisplay';
4100 /**
4101 * UUID of the current turn.
4102 */
4103 turn_id: string;
4104 /**
4105 * UUID of the assistant message being displayed. Stable across every flush of the same message. Not the API msg_... id.
4106 */
4107 message_id: string;
4108 /**
4109 * Zero-based index of this delta within the message. Increments by one per flush.
4110 */
4111 index: number;
4112 /**
4113 * True on the message's last flush. Exactly one flush per message has it.
4114 */
4115 final: boolean;
4116 /**
4117 * 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.
4118 */
4119 delta: string;
4120 };
4121
4122 /**
4123 * What `$.model.complete` takes.
4124 */
4125 export type ModelCompleteRequest = {
4126 /**
4127 * An alias (`haiku`) or a full model id; resolved and allowlist-checked like
4128 * a `--model` value.
4129 */
4130 model: string;
4131 /**
4132 * The one user message; the reply's text comes back.
4133 */
4134 prompt: string;
4135 /**
4136 * Precedes the completion as its system prompt, after the CLI's identity
4137 * block. Default none.
4138 */
4139 system?: string;
4140 /**
4141 * The reply's token cap. Default 256.
4142 */
4143 maxTokens?: number;
4144 };
4145
4146 /**
4147 * What `$.model.fork` takes.
4148 */
4149 export type ModelForkRequest = {
4150 /**
4151 * The one user message, appended to the session's own transcript.
4152 *
4153 * The reply's text and usage come back, or null on an API error or a cold
4154 * transcript.
4155 */
4156 prompt: string;
4157 };
4158
4159 /**
4160 * What `$.model.fork` resolves to when the fork answered: the reply's text
4161 * and what the fork cost.
4162 */
4163 export type ModelForkResult = {
4164 /**
4165 * The non-error replies' text, joined by newlines.
4166 */
4167 text: string;
4168 /**
4169 * The fork's token counts, so a plugin can account for what it spent.
4170 */
4171 usage: ModelForkUsage;
4172 };
4173
4174 /**
4175 * What one fork cost, as the API counted it: the four token counts of the
4176 * fork's completions summed.
4177 */
4178 export type ModelForkUsage = {
4179 input_tokens: number;
4180 output_tokens: number;
4181 cache_read_input_tokens: number;
4182 cache_creation_input_tokens: number;
4183 };
4184
4185 /**
4186 * The prefixes a glob may name: one or more whole leading segments of an
4187 * event name (`tool` of `tool.call`), derived, plugin nouns included.
4188 */
4189 export type Namespace<N extends string = EventName> = N extends `${infer Head}.${infer Rest}` ? Head | `${Head}.${Namespace<Rest>}` : never;
4190
4191 /**
4192 * How many object or array levels a matcher narrows `e` through, counted as
4193 * a tuple's length: the runtime's own limit, which refuses a deeper matcher.
4194 *
4195 * Past it a field keeps its declared type; nothing becomes `any`.
4196 */
4197 type NarrowDepth = 8;
4198
4199 /**
4200 * `e` in a matched hook: the members of the argument union `E` matcher `P`
4201 * can match, each with the keys `P` names narrowed to what a match implies.
4202 *
4203 * A scalar narrows to the literal, a one-of to what its alternatives give,
4204 * an object key recursively, an array some element of which must match to
4205 * a non-empty tuple; other keys, `unknown` and RegExp-matched fields keep.
4206 */
4207 export type Narrowed<E, P> = E extends unknown ? NarrowedMember<E, P, []> : never;
4208
4209 /**
4210 * A value of declared type `V` under a one-of, folded over the tuple into
4211 * `Found`: the union of what each alternative narrows `V` to (NarrowedByOne).
4212 *
4213 * An alternative that cannot match adds nothing, so a one-of none of whose
4214 * alternatives can is `never`; a one-of typed as a plain array rather than
4215 * a tuple narrows by the union of its elements at once.
4216 */
4217 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>;
4218
4219 /**
4220 * A value of declared type `V` under one matcher node `Q` that is not a
4221 * one-of, member of `V` by member; a member that cannot match is `never`.
4222 *
4223 * An array some element of which must match becomes NonEmpty; a RegExp
4224 * keeps the member; an object pattern recurses into an object member, one
4225 * level down; a scalar keeps a member as narrow, and replaces a wider one.
4226 */
4227 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;
4228
4229 /**
4230 * One object member `E` under object pattern `P`, `D` levels down: `never`
4231 * when a key of `P` is impossible on it (ImpossibleKeys), else `E` narrowed.
4232 *
4233 * Each key `P` names is narrowed (NarrowedValue); every other key, and each
4234 * key's optionality, stays as declared.
4235 */
4236 type NarrowedMember<E, P, D extends readonly unknown[]> = [
4237 ImpossibleKeys<E, P, D>
4238 ] extends [never] ? {
4239 [K in keyof E]: K extends keyof P ? NarrowedValue<E[K], P[K], D> : E[K];
4240 } : never;
4241
4242 /**
4243 * A value of declared type `V` where the matcher gives `Q`, `D` levels
4244 * down: NarrowedByAny under a one-of (an array), NarrowedByOne otherwise.
4245 *
4246 * As declared once `D` reaches NarrowDepth, or for a field typed `unknown`
4247 * (a tool's input), which no pattern narrows.
4248 */
4249 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>;
4250
4251 /**
4252 * `!` before a name or a glob: every event except the ones it selects. `!*`
4253 * would select none, so it is no pattern.
4254 */
4255 type Negation = `!${Exclude<EventName | Glob, '*'>}`;
4256
4257 /**
4258 * The rest of the chain, as one hook receives it: made once per dispatch per
4259 * hook, frozen; `next(e)` resolves to the downstream result.
4260 *
4261 * Each call runs the hooks below again; core is the last, and below it `next`
4262 * rejects. Called with no argument it rejects, naming the hook. A hook that
4263 * returns without calling it ends the chain; returning nothing is a failure.
4264 *
4265 * @template S what `next.is(pattern, e)` narrows `e` to, per event: the event's
4266 * argument, or, under a matcher, that argument narrowed by it (MatchedHook)
4267 * @template T the tool `e` names, when it names one: on `tool.call` it types
4268 * the result (NextResultFor); an `e` without `tool` takes the line beneath
4269 */
4270 export type Next<N extends EventName = EventName, E = Args<N>, O = NextResult<N>, S extends {
4271 [K in N]?: unknown;
4272 } = {
4273 [K in N]: Args<K>;
4274 }> = {
4275 <T extends string>(e: E & ToolNamed<T>): Promise<NextResultFor<N, O, T>>;
4276 (e: E): Promise<O>;
4277 /**
4278 * Continues this dispatch at a tier: `next(e)` with every link between
4279 * this hook's own tier and that one skipped, by tier and narrowing only.
4280 *
4281 * A managed hook's: prepend may name append, builtin or core, append core;
4282 * it never skips a tier with more authority, so no user hook skips the
4283 * org's. A literal on the hook's own `next`; skipped links are traced.
4284 */
4285 readonly to: {
4286 <T extends string>(e: E & ToolNamed<T>, tier: TargetTier): Promise<NextResultFor<N, O, T>>;
4287 (e: E, tier: TargetTier): Promise<O>;
4288 };
4289 /**
4290 * Aborts when the call this dispatch belongs to is abandoned: the user
4291 * interrupted, a hook above settled first, or this hook ran out of budget.
4292 *
4293 * Anything the hook started (timers, requests) should stop on it. It is an
4294 * AbortSignal of the plugin's own environment, driven by the chain's.
4295 */
4296 readonly signal: AbortSignal;
4297 /**
4298 * Whether this dispatch's event is selected by `pattern` (a name, a glob,
4299 * a negation), as a type predicate on `e`: `next.is("tool.call", e)`.
4300 *
4301 * Under a matcher the narrowing includes it. `pattern` names events this
4302 * hook covers (PatternOver); a name outside them is a compile error.
4303 */
4304 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<S[Extract<N, Selected<M>>]>;
4305 /**
4306 * The name of this dispatch's event, as a value, for a glob hook to log or
4307 * switch on.
4308 */
4309 readonly event: N;
4310 /**
4311 * Who raised this dispatch: the calling plugin's name and the tier it sits
4312 * in (Origin); the engine reads `{ plugin: "engine", tier: "core" }`.
4313 *
4314 * Set by the host alone, from the environment the call came from (its own
4315 * MessagePort) and that plugin's seat; nothing a plugin writes reaches it.
4316 * Every hook of one dispatch sees the same origin, and `next.to` keeps it.
4317 *
4318 * @example
4319 * return next.origin.tier === "prepend" ? next.to(e, "append") : next(e)
4320 */
4321 readonly origin: Origin;
4322 /**
4323 * What settled beneath this hook on its latest `next()` call, the one
4324 * started last: an entry per link beneath, nearest first, the engine's last.
4325 *
4326 * Empty before `next` is called; filled even when `next` rejected; a link
4327 * still running joins in place later, nothing listed leaves; it ends short
4328 * of the engine at a link that answered its last call itself. Data, frozen.
4329 */
4330 readonly trace: readonly TraceEntry<N, E, O>[];
4331 };
4332
4333 /**
4334 * What `next(e)` resolves to for event `N`: the event's result, except at
4335 * `engine.create`, where the steps beneath return `$` as built so far.
4336 *
4337 * A withheld noun is on that `$` as a stub, so the built table is typed
4338 * whole where what a hook returns (EngineCreateResult) is partial.
4339 */
4340 export type NextResult<N extends EventName> = N extends 'engine.create' ? EngineInterfaceBuilt : EventResult<N>;
4341
4342 /**
4343 * What `next(e)` resolves to once `e.tool` is the literal `T`: on `tool.call`
4344 * the result typed for that tool; on every other event, `O` as declared.
4345 *
4346 * `result` is Bash's record after `e.tool === "Bash"`; an un-narrowed `e`
4347 * names every tool, and `result` stays `unknown`.
4348 */
4349 export type NextResultFor<N extends EventName, O, T extends string> = [
4350 N
4351 ] extends ['tool.call'] ? ToolCallResult<T> : O;
4352
4353 /**
4354 * The argument of a call on `$` that takes nothing (`$.session.cwd()`): an
4355 * object with no keys.
4356 */
4357 type NoArgs = Record<never, never>;
4358
4359 /**
4360 * The events whose argument is exactly NoArgs (`session.cwd`, a declared
4361 * plugin noun's `() => ...`); their overloads come last (LateOverload).
4362 */
4363 type NoArgsEvent = {
4364 [N in EventName]: Args<N> extends NoArgs ? NoArgs extends Args<N> ? N : never : never;
4365 }[EventName];
4366
4367 /**
4368 * What an `engine.create` hook receives as `$`: nothing. Every property
4369 * reads as `never`, so `$.model` inside the hook is a compile error.
4370 */
4371 export type NoEngineInterface = {
4372 readonly [noun: string]: never;
4373 };
4374
4375 /**
4376 * Array type `V`, of element `Item`, once some element of it is known to
4377 * match: a tuple of at least one `Item`, readonly when `V` is.
4378 *
4379 * So `e` still passes wherever the declared array is taken; a `V` that is
4380 * already a non-empty tuple is kept as it is.
4381 */
4382 type NonEmpty<V, Item> = V extends readonly [unknown, ...unknown[]] ? V : V extends Item[] ? [Item, ...Item[]] : readonly [Item, ...Item[]];
4383
4384 type NotificationHookInput = BaseHookInput & {
4385 hook_event_name: 'Notification';
4386 message: string;
4387 title?: string;
4388 notification_type: string;
4389 };
4390
4391 /**
4392 * The declared plugin nouns' methods as event rows (NounEventRow), one per
4393 * `<noun>.<method>` that is a function; a member that is not is no event.
4394 */
4395 type NounEvent = {
4396 [K in PluginNoun]: {
4397 [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;
4398 }[keyof EngineInterface[K] & string];
4399 }[PluginNoun];
4400
4401 /**
4402 * The name of a declared plugin noun's event (`voice.speak`).
4403 */
4404 type NounEventName = keyof NounEventOf & string;
4405
4406 /**
4407 * The events of the plugin nouns declared on EngineInterface, by name: the
4408 * argument of each `<noun>.<method>`. Empty until a plugin declares a noun.
4409 *
4410 * @example
4411 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
4412 */
4413 export type NounEventOf = {
4414 [E in NounEvent as E['name']]: E['args'];
4415 };
4416
4417 /**
4418 * The result of a declared plugin noun's event as its hooks see it:
4419 * `{ value }` (the method's answer) or `{ deny }`.
4420 */
4421 type NounEventResult<N extends NounEventName> = ValueOrDeny<NounValueOf[N]>;
4422
4423 /**
4424 * One method of a declared plugin noun as an event row: its event's name,
4425 * argument (the method's first parameter) and value (its awaited result).
4426 */
4427 type NounEventRow<Name extends string, Args, Value> = {
4428 name: Name;
4429 args: Args;
4430 value: Value;
4431 };
4432
4433 /**
4434 * What each declared plugin noun's method answers (the `value` of its
4435 * event's result), by event name.
4436 */
4437 type NounValueOf = {
4438 [E in NounEvent as E['name']]: E['value'];
4439 };
4440
4441 /**
4442 * Registers `hook` on the events `pattern` selects: one by name, every one
4443 * under a namespace (`classic.*`), all (`*`), or all but some (`!tool.*`).
4444 *
4445 * One function stands on every selected event (`next.event` says which),
4446 * under a matcher for the inputs it matches; a plugin's registrations nest
4447 * in order, first outermost; a repeat throws. Returns the Registration.
4448 */
4449 export type On = {
4450 <P extends Pattern>(pattern: P, hook: NoInfer<HookFor<P>>): Registration<HookFor<P>>;
4451 <P extends Pattern, const M extends Matcher<Args<MatchedNames<P>>>>(pattern: P, matcher: M, hook: NoInfer<MatchedHook<P, M>>): Registration<MatchedHook<P, M>>;
4452 };
4453
4454 /**
4455 * The keys a variant with a string index signature (an MCP tool's input)
4456 * takes beyond its own: another variant's key as typed there; others free.
4457 *
4458 * So a misspelt value for a key some variant declares (`command: 5`) is
4459 * refused on every variant, not admitted by the open one.
4460 */
4461 type OpenMatcher<I, All> = {
4462 readonly [K in Exclude<MatcherKeys<All>, KnownKeys<I>>]?: MatcherValue<MatcherValueOf<All, K>>;
4463 } & Readonly<Record<string, unknown>>;
4464
4465 /**
4466 * The name of a call on `$` the host serves, as an event.
4467 */
4468 export type OpEventName = keyof OpEventOf;
4469
4470 /**
4471 * The calls on `$` the host serves, as events: `e` is the call's argument as
4472 * it crosses to the host, and every one is hookable by name and by `on("*")`.
4473 *
4474 * A hook above the caller passes it on, rewrites it, refuses it with
4475 * `{ deny }` or answers with `{ value }`; core is the host's implementation.
4476 * The calling hook alone is skipped, and `next.origin` names the caller.
4477 */
4478 export type OpEventOf = {
4479 /**
4480 * The argument of `$.model.complete(request)`.
4481 */
4482 'model.complete': ModelCompleteRequest;
4483 /**
4484 * The argument of `$.model.classify(text, labels, options)`.
4485 */
4486 'model.classify': {
4487 text: string;
4488 labels: readonly string[];
4489 options?: ClassifyOptions;
4490 };
4491 /**
4492 * The argument of `$.model.fork(request)`.
4493 */
4494 'model.fork': ModelForkRequest;
4495 /**
4496 * The clip and how to play it (`shouldLoop`, `gain`); the signal does not
4497 * cross.
4498 */
4499 'audio.play': {
4500 clip: AudioClip;
4501 shouldLoop: boolean;
4502 gain?: number;
4503 };
4504 /**
4505 * The argument of `$.audio.speak(text, { voice })`.
4506 */
4507 'audio.speak': SpeakRequest;
4508 /**
4509 * The argument of `$.mcp.call(server, tool, args)`.
4510 */
4511 'mcp.call': {
4512 server: string;
4513 tool: string;
4514 args: Record<string, unknown>;
4515 };
4516 /**
4517 * The argument of `$.session.cwd()`.
4518 */
4519 'session.cwd': NoArgs;
4520 /**
4521 * The argument of `$.session.model()`.
4522 */
4523 'session.model': NoArgs;
4524 /**
4525 * The argument of `$.session.turns()`.
4526 */
4527 'session.turns': NoArgs;
4528 /**
4529 * The argument of `$.session.id()`.
4530 */
4531 'session.id': NoArgs;
4532 /**
4533 * The argument of `$.session.messages()`.
4534 */
4535 'session.messages': NoArgs;
4536 /**
4537 * The argument of `$.session.repo()`.
4538 */
4539 'session.repo': NoArgs;
4540 /**
4541 * The argument of `$.session.surface()`.
4542 *
4543 * @deprecated with `$.session.surface()`; hook `session.surfaces`
4544 */
4545 'session.surface': NoArgs;
4546 /**
4547 * The argument of `$.session.surfaces()`.
4548 */
4549 'session.surfaces': NoArgs;
4550 /**
4551 * The argument of `$.session.authorize()`.
4552 */
4553 'session.authorize': NoArgs;
4554 /**
4555 * The argument of `$.session.usage({ breakdown, columns })`.
4556 */
4557 'session.usage': SessionUsageArgs;
4558 /**
4559 * The argument of `$.turn.abort({ turnId })`.
4560 */
4561 'turn.abort': {
4562 turnId: string;
4563 };
4564 /**
4565 * The argument of `$.tool.list()`.
4566 */
4567 'tool.list': NoArgs;
4568 /**
4569 * The argument of `$.tool.register(spec)`.
4570 */
4571 'tool.register': Required<ToolSpec>;
4572 /**
4573 * The argument of `$.command.list()`.
4574 */
4575 'command.list': NoArgs;
4576 /**
4577 * The argument of `$.command.register(spec)`.
4578 */
4579 'command.register': CommandSpec;
4580 /**
4581 * The argument of `$.config.list()`.
4582 */
4583 'config.list': NoArgs;
4584 /**
4585 * The argument of `$.agent.list()`.
4586 */
4587 'agent.list': NoArgs;
4588 /**
4589 * The argument of `$.ui.toast(text, { timeoutMs })`.
4590 */
4591 'ui.toast': {
4592 text: string;
4593 timeoutMs?: number;
4594 };
4595 /**
4596 * The argument of `$.ui.status(text)`; `text` undefined clears the line.
4597 */
4598 'ui.status': {
4599 text: string | undefined;
4600 };
4601 /**
4602 * The argument of `$.ui.log(text)`.
4603 */
4604 'ui.log': {
4605 text: string;
4606 };
4607 /**
4608 * The argument of `$.ui.notice(tool_use_id, text)`.
4609 */
4610 'ui.notice': {
4611 tool_use_id: string;
4612 text: string | undefined;
4613 };
4614 /**
4615 * The argument of `$.ui.invalidate(event)`.
4616 */
4617 'ui.invalidate': {
4618 event: InvalidatableEventName;
4619 };
4620 /**
4621 * The argument of `$.ui.open({ id, title, focus })`; a hook above the
4622 * opener may retitle it or refuse it with `{ deny }`, never rename it.
4623 */
4624 'ui.open': PaneOpenArgs;
4625 /**
4626 * The argument of `$.ui.close({ id })` with `origin` `plugin`; the engine
4627 * raises it too, for the person (`person`) and an unload (`unload`).
4628 */
4629 'ui.close': PaneCloseInput;
4630 /**
4631 * The argument of `$.ui.blit({ requestId, key, cells })`; a hook above
4632 * the painter may repaint the cells with `next`, or refuse with `{ deny }`.
4633 */
4634 'ui.blit': UiBlitArgs;
4635 /**
4636 * The argument of `$.fs.read(path)`.
4637 */
4638 'fs.read': {
4639 path: string;
4640 };
4641 /**
4642 * The argument of `$.fs.write(path, text)`.
4643 */
4644 'fs.write': {
4645 path: string;
4646 text: string;
4647 };
4648 /**
4649 * The argument of `$.fs.list(path)`.
4650 */
4651 'fs.list': {
4652 path: string;
4653 };
4654 /**
4655 * The argument of `$.fs.exists(path)`.
4656 */
4657 'fs.exists': {
4658 path: string;
4659 };
4660 /**
4661 * The argument of `$.fs.stat(path)`.
4662 */
4663 'fs.stat': {
4664 path: string;
4665 };
4666 /**
4667 * The argument of `$.fs.ancestors({ names, of })`.
4668 */
4669 'fs.ancestors': FsAncestorsRequest;
4670 /**
4671 * The argument of `$.store.get(key)`.
4672 */
4673 'store.get': {
4674 key: string;
4675 };
4676 /**
4677 * The argument of `$.store.set(key, value)`.
4678 */
4679 'store.set': {
4680 key: string;
4681 value: unknown;
4682 };
4683 /**
4684 * The argument of `$.store.delete(key)`.
4685 */
4686 'store.delete': {
4687 key: string;
4688 };
4689 /**
4690 * The argument of `$.store.keys()`.
4691 */
4692 'store.keys': NoArgs;
4693 /**
4694 * The argument of `$.clock.now()`.
4695 */
4696 'clock.now': NoArgs;
4697 /**
4698 * The argument of `$.clock.sleep(ms, { signal })`; the signal does not
4699 * cross, it aborts the dispatch.
4700 */
4701 'clock.sleep': ClockWait;
4702 /**
4703 * The argument of `$.clock.after(ms, fn)`: the wait before `fn`, which
4704 * stays in the plugin's environment and runs once the dispatch resolves.
4705 */
4706 'clock.after': ClockWait;
4707 /**
4708 * The argument of `$.clock.every(ms, fn)`, dispatched once per period:
4709 * `fn` runs each time a dispatch resolves, and the next period is asked.
4710 */
4711 'clock.every': ClockWait;
4712 /**
4713 * The argument of `$.http.fetch(url, init)`.
4714 */
4715 'http.fetch': {
4716 url: string;
4717 init?: HttpInit;
4718 };
4719 /**
4720 * The argument of `$.process.run(argv, init)`.
4721 */
4722 'process.run': {
4723 argv: readonly string[];
4724 init?: ProcessRunInit;
4725 };
4726 /**
4727 * The argument of `$.settings.read({ source })`.
4728 */
4729 'settings.read': SettingsReadArgs;
4730 /**
4731 * The argument of `$.env.get(name)`; `name` is identity, pinned.
4732 */
4733 'env.get': {
4734 name: string;
4735 };
4736 /**
4737 * The argument of `$.env.set(name, value)`; `name` is identity, pinned,
4738 * and no `value` unsets.
4739 */
4740 'env.set': {
4741 name: string;
4742 value?: string;
4743 };
4744 };
4745
4746 /**
4747 * The result of a call on `$` as its event's hooks see it: `{ value }` (the
4748 * call's answer) or `{ deny }`.
4749 */
4750 export type OpEventResult<N extends OpEventName = OpEventName> = ValueOrDeny<OpValueOf[N]>;
4751
4752 /**
4753 * What each call on `$` answers (the `value` of its event's result), by event
4754 * name.
4755 */
4756 export type OpValueOf = {
4757 'model.complete': string;
4758 'model.classify': string | undefined;
4759 'model.fork': ModelForkResult | null;
4760 'audio.play': void;
4761 'audio.speak': SpeakResult;
4762 'mcp.call': McpToolResult;
4763 'session.cwd': string;
4764 'session.model': string;
4765 'session.turns': number;
4766 'session.id': string;
4767 'session.messages': SessionMessage[];
4768 'session.repo': SessionRepo | null;
4769 'session.surface': RenderSurface | null;
4770 'session.surfaces': readonly RenderSurface[];
4771 /**
4772 * The credential handle, or null where the build or the provider has no
4773 * first-party credential to hold.
4774 */
4775 'session.authorize': SessionAuthorization;
4776 'session.usage': SessionUsage;
4777 'turn.abort': void;
4778 'tool.list': ToolInfo[];
4779 'tool.register': {
4780 tool: string;
4781 };
4782 'command.list': CommandInfo[];
4783 'command.register': {
4784 command: string;
4785 };
4786 'config.list': ConfigRow[];
4787 'agent.list': AgentInfo[];
4788 'ui.toast': void;
4789 'ui.status': void;
4790 'ui.log': void;
4791 'ui.notice': void;
4792 'ui.invalidate': void;
4793 'ui.open': void;
4794 'ui.close': void;
4795 'ui.blit': UiBlitResult;
4796 'fs.read': string;
4797 'fs.write': void;
4798 'fs.list': FsEntry[];
4799 'fs.exists': boolean;
4800 'fs.stat': FsStat;
4801 'fs.ancestors': readonly FsAncestor[];
4802 'store.get': unknown;
4803 'store.set': void;
4804 'store.delete': void;
4805 'store.keys': string[];
4806 /**
4807 * Milliseconds since the epoch.
4808 */
4809 'clock.now': number;
4810 'clock.sleep': void;
4811 'clock.after': void;
4812 'clock.every': void;
4813 'http.fetch': HttpResponse;
4814 'process.run': ProcessRunResult;
4815 'settings.read': Settings;
4816 'env.get': string | undefined;
4817 'env.set': void;
4818 };
4819
4820 /**
4821 * One call signature per event in `Names`, intersected, the ambiguous ones
4822 * (LateOverload) after the rest: `next` for a hook covering several events.
4823 *
4824 * An empty group contributes nothing (Overloads<never> is unknown).
4825 */
4826 type OrderedOverloads<Names extends EventName> = Overloads<Exclude<Names, LateOverload>> & Overloads<Extract<Names, 'classic.PreToolUse'>> & Overloads<Extract<Names, 'turn.abort'>> & Overloads<Extract<Names, NoArgsEvent>>;
4827
4828 /**
4829 * Who raised a dispatch, as `next.origin` holds it: the calling plugin's
4830 * name and the tier it sits in; the engine reads `engine` in `core`.
4831 *
4832 * The same pair a `next.trace` entry names its link by, and an event's
4833 * `provider` its subject's definer by. Set by the host from where the call
4834 * came from and where that plugin was seated; nothing a plugin writes.
4835 */
4836 export type Origin = {
4837 /**
4838 * Whose hook made the `$` call, by name; `"engine"` for a call site,
4839 * `"client"` for a `Client` surface module's `ui.message` post.
4840 */
4841 readonly plugin: string;
4842 /**
4843 * Where that plugin sits among the chain's tiers (Tier); `"core"` for the
4844 * engine, the owning plugin's for a `client` post.
4845 */
4846 readonly tier: Tier;
4847 };
4848
4849 /**
4850 * One call signature per event in `Names`, intersected into an overload set.
4851 */
4852 type Overloads<Names extends EventName> = UnionToIntersection<{
4853 [N in Names]: (e: Args<N>) => Promise<NextResult<N>>;
4854 }[Names]>;
4855
4856 /**
4857 * The argument of `$.ui.close`: the pane to close (`{ id }`). `origin` is
4858 * the engine's to set: a plugin's call reads `plugin` at the hooks.
4859 */
4860 export type PaneCloseArgs = Omit<PaneCloseInput, 'origin'>;
4861
4862 /**
4863 * The input of `ui.close`: the pane closing and why (PaneCloseOrigin).
4864 * Closing an id that is not open does nothing.
4865 */
4866 export type PaneCloseInput = {
4867 /**
4868 * What `$.ui.open` named the pane; pinned: `next(e)` passes it on.
4869 */
4870 id: string;
4871 /**
4872 * Who closes it, set by the engine: a hook that answers without `next`
4873 * keeps the pane open on `plugin` and `person`, never on `unload`.
4874 */
4875 origin: PaneCloseOrigin;
4876 };
4877
4878 /**
4879 * Why a pane closes, as the engine stamped it at `ui.close`.
4880 *
4881 * `unload` drops a pane nothing draws any more (its plugin unloaded, or its
4882 * drawing threw): it is gone before the hooks hear of it, and its opener's
4883 * hooks do not run. `next(e)` passes the origin on as received; none sets it.
4884 */
4885 export type PaneCloseOrigin = {
4886 /**
4887 * `plugin`, a plugin's `$.ui.close`; `person`, the person's close mark or
4888 * close key; `unload`, the engine's own.
4889 */
4890 kind: 'plugin' | 'person' | 'unload';
4891 };
4892
4893 /**
4894 * The argument of `$.ui.open`: which pane, its title, whether it asks the
4895 * person's keyboard, its dialog manners, and the rows it wants inline.
4896 *
4897 * An open answering the person's input (a command or prompt they entered, a
4898 * press) is placed at any width; one the plugin makes on its own waits
4899 * undrawn below 144 terminal columns, 110 once they asked for that id.
4900 */
4901 export type PaneOpenArgs = {
4902 /**
4903 * Names the pane: 1-64 of letters, digits, `_` and `-`. One pane per id:
4904 * opening an open id delivers the new title, never a second instance.
4905 *
4906 * Pinned at the hooks: `next(e)` passes it on; the title and focus rewrite.
4907 */
4908 id: string;
4909 /**
4910 * The pane's tab while more than one pane is open (with one, no title is
4911 * drawn), and the `title` its hook sees; the id when omitted.
4912 */
4913 title?: string;
4914 /**
4915 * A request, not a grant: the surface focuses (and raises) the pane only
4916 * while the prompt has the keys over an empty composer.
4917 *
4918 * An element of the band or a pane the person holds, text in the
4919 * composer, a dialog or a survey each refuse it: the pane opens without
4920 * the keyboard.
4921 */
4922 focus?: true;
4923 /**
4924 * While the pane holds the keyboard, the key that hands it back (Escape)
4925 * also closes it as the person's close does: `ui.close`, origin `person`.
4926 *
4927 * A hook may refuse that close and keep it open. Left out, Escape returns
4928 * the keys to the prompt and the pane stays. Each open sets it anew, as it
4929 * sets the title.
4930 */
4931 closeOnEscape?: true;
4932 /**
4933 * While the pane is on screen the surface holds its transient toasts (the
4934 * notification line under the prompt) and shows them once it closes.
4935 *
4936 * As it does behind the engine's own side panel; pinned warnings still
4937 * show. Left out, toasts show as they come. Each open sets it anew.
4938 */
4939 holdToasts?: true;
4940 /**
4941 * The body rows the pane's content wants while seated inline above the
4942 * prompt: it opens that tall, up to what the layout spares, not a third.
4943 *
4944 * A request, not a grant: a size the person dragged or keyed the block
4945 * to wins, this session's or a kept one, and the dock ignores it. A
4946 * positive whole number; left out, a third. Each open sets it anew.
4947 */
4948 rows?: number;
4949 };
4950
4951 /**
4952 * What `on(pattern, hook)` and `next.is(pattern, e)` take: an event's name,
4953 * a glob (`*`, `classic.*`), or a negation of either (`!tool.describe`).
4954 */
4955 export type Pattern = EventName | Glob | Negation;
4956
4957 /**
4958 * The patterns `next.is` takes in a hook covering the events `N`: their
4959 * names, `*`, a glob over one of their namespaces, or a negation.
4960 *
4961 * A name none of them has is a compile error, as is a glob over a namespace
4962 * none is under; a negation that selects none of them narrows `e` to never.
4963 */
4964 type PatternOver<N extends EventName> = N | '*' | `${Namespace<N>}.*` | Negation;
4965
4966 type PermissionBehavior = 'allow' | 'deny' | 'ask';
4967
4968 type PermissionDeniedHookInput = BaseHookInput & {
4969 hook_event_name: 'PermissionDenied';
4970 tool_name: string;
4971 tool_input: unknown;
4972 tool_use_id: string;
4973 reason: string;
4974 };
4975
4976 /**
4977 * 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.
4978 */
4979 type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';
4980
4981 /**
4982 * A `classic.PermissionRequest` answer's `decision`, as the classic hook's
4983 * `hookSpecificOutput.decision`: allow (with a rewrite or rules) or deny.
4984 */
4985 export type PermissionRequestDecision = {
4986 behavior: 'allow';
4987 updatedInput?: Record<string, unknown>;
4988 updatedPermissions?: PermissionUpdates;
4989 } | {
4990 behavior: 'deny';
4991 message?: string;
4992 interrupt?: true;
4993 };
4994
4995 type PermissionRequestHookInput = BaseHookInput & {
4996 hook_event_name: 'PermissionRequest';
4997 tool_name: string;
4998 tool_input: unknown;
4999 permission_suggestions?: PermissionUpdate[];
5000 };
5001
5002 type PermissionRuleValue = {
5003 toolName: string;
5004 ruleContent?: string;
5005 };
5006
5007 type PermissionUpdate = {
5008 type: 'addRules';
5009 rules: PermissionRuleValue[];
5010 behavior: PermissionBehavior;
5011 destination: PermissionUpdateDestination;
5012 } | {
5013 type: 'replaceRules';
5014 rules: PermissionRuleValue[];
5015 behavior: PermissionBehavior;
5016 destination: PermissionUpdateDestination;
5017 } | {
5018 type: 'removeRules';
5019 rules: PermissionRuleValue[];
5020 behavior: PermissionBehavior;
5021 destination: PermissionUpdateDestination;
5022 } | {
5023 type: 'setMode';
5024 mode: PermissionMode;
5025 destination: PermissionUpdateDestination;
5026 } | {
5027 type: 'addDirectories';
5028 directories: string[];
5029 destination: PermissionUpdateDestination;
5030 } | {
5031 type: 'removeDirectories';
5032 directories: string[];
5033 destination: PermissionUpdateDestination;
5034 };
5035
5036 type PermissionUpdateDestination = 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg';
5037
5038 /**
5039 * The permission rules a PermissionRequest allow may add: the shape of the
5040 * request's own `permission_suggestions` (the SDK's PermissionUpdate list).
5041 */
5042 type PermissionUpdates = NonNullable<ClassicHookInputs['PermissionRequest']['permission_suggestions']>;
5043
5044 /**
5045 * How `$.audio.play` plays a clip: looped until `signal` aborts, or once.
5046 *
5047 * A loop needs the signal that ends it; a single play takes one as an option.
5048 */
5049 export type PlayOptions = {
5050 /**
5051 * Repeat the clip until `signal` aborts (the promise then resolves).
5052 */
5053 shouldLoop: true;
5054 /**
5055 * Linear gain, from 0 to 4; default 1.
5056 */
5057 gain?: number;
5058 /**
5059 * Stops the clip: playback ends at once and the promise resolves.
5060 */
5061 signal: AbortSignal;
5062 } | {
5063 /**
5064 * Play once.
5065 */
5066 shouldLoop?: false;
5067 /**
5068 * Linear gain, from 0 to 4; default 1.
5069 */
5070 gain?: number;
5071 /**
5072 * Stops the clip early, as above.
5073 */
5074 signal?: AbortSignal;
5075 };
5076
5077 /**
5078 * The nouns a plugin declared on `$` by merging into EngineInterface; never
5079 * one the engine's own events are under (`tool`, `session`, `ui`).
5080 */
5081 type PluginNoun = Exclude<keyof EngineInterface & string, keyof CoreEngineInterface | Namespace<CoreEventName>>;
5082
5083 /**
5084 * A plugin's options as `register(on, options)` receives them: the values of
5085 * the fields its manifest's `userConfig` declares, defaults filled in.
5086 *
5087 * Stored in settings.json `pluginConfigs[<plugin>].options` (sensitive ones
5088 * in secure storage), validated against the declared `type` before the module
5089 * loads; a required field with no value fails the load, naming the field. A
5090 * string field that declares `options` holds one of them: `/config` draws it
5091 * as a picker over them, and a stored value outside them counts as unset, so
5092 * its default applies. A `--plugin-dir` plugin's key is its plugin.json
5093 * `<name>` (or `<name>@inline`).
5094 */
5095 export type PluginOptions = Readonly<Record<string, string | number | boolean | readonly string[]>>;
5096
5097 /**
5098 * The input of `plugin.register`: one hooks module the engine is about to
5099 * load, read off its manifest and its scanned source. Every field is pinned.
5100 *
5101 * `tier` and `uses` are the host's reading of the module, what a gate holds
5102 * it to; `name`, `root`, `version` and `provenance` are its own word (its
5103 * manifest, its place), so a rule keyed on them is one a rename walks past.
5104 */
5105 export type PluginRegisterInput = {
5106 /**
5107 * The plugin's name, as its own plugin.json declares it.
5108 */
5109 name: string;
5110 /**
5111 * Where its hooks would stand among the chain's tiers (Tier); never
5112 * `core`, the engine's own.
5113 */
5114 tier: Exclude<Tier, 'core'>;
5115 /**
5116 * The plugin's directory (the one holding plugin.json), absolute.
5117 */
5118 root: string;
5119 /**
5120 * Its manifest's `version`, when it states one.
5121 */
5122 version?: string;
5123 /**
5124 * Where the plugin came from, as the loader keys it: `<name>@<marketplace>`
5125 * installed, `<name>@inline` by `--plugin-dir`, `<name>@builtin` bundled.
5126 */
5127 provenance: string;
5128 /**
5129 * What the module hooks and calls, as scanned (PluginRegisterUses).
5130 */
5131 uses: PluginRegisterUses;
5132 };
5133
5134 /**
5135 * What a `plugin.register` hook returns and what `next(e)` resolves to:
5136 * `{ allow: true }` from core, or `{ refuse: reason }`.
5137 */
5138 export type PluginRegisterResult = {
5139 /**
5140 * The module loads: its `engine.create` step runs and its hooks join.
5141 */
5142 allow: true;
5143 refuse?: undefined;
5144 } | {
5145 /**
5146 * The module does not load: no step, no hooks, no tools or commands;
5147 * the transcript names the plugin that refused and this reason.
5148 */
5149 refuse: string;
5150 allow?: undefined;
5151 };
5152
5153 /**
5154 * What a hooks module uses, as the host scanned its source before loading it:
5155 * the same lists `claude plugin validate` prints and the host's rule reads.
5156 *
5157 * Exact, since a module that spells `on`, `$` or `$.env` other than literally
5158 * does not load.
5159 */
5160 export type PluginRegisterUses = {
5161 /**
5162 * The patterns its `on(...)` registrations name, as written (`tool.call`,
5163 * `*`, `classic.*`, `!tool.describe`), in registration order, each once.
5164 */
5165 events: readonly string[];
5166 /**
5167 * What it calls on `$`, spelled `noun.method` (`fs.write`, `http.fetch`),
5168 * sorted, each once.
5169 */
5170 calls: readonly string[];
5171 /**
5172 * The environment variables its `$.env.get` and `$.env.set` calls name;
5173 * absent when it calls neither.
5174 */
5175 env?: {
5176 /**
5177 * The names its `$.env.get` calls spell, sorted, each once.
5178 */
5179 reads: readonly string[];
5180 /**
5181 * The names its `$.env.set` calls spell, sorted, each once.
5182 */
5183 writes: readonly string[];
5184 };
5185 };
5186
5187 /**
5188 * Whose element: the plugin whose hook drew it, stamped by the runtime as the
5189 * tree leaves it; a Box's or Text's `group`, a Client's or Raster's own.
5190 *
5191 * A Button's `press` names its plugin the same way, beside its handle. Two
5192 * plugins under one `hover.scope` string never share a group.
5193 */
5194 type PluginStamp = {
5195 plugin: string;
5196 };
5197
5198 type PostCompactHookInput = BaseHookInput & {
5199 hook_event_name: 'PostCompact';
5200 trigger: 'manual' | 'auto';
5201 /**
5202 * The conversation summary produced by compaction
5203 */
5204 compact_summary: string;
5205 };
5206
5207 type PostModelSwitchHookInput = (BaseHookInput & {
5208 hook_event_name: 'PostModelSwitch';
5209 }) & {
5210 /**
5211 * Resolved model id the session was running before the switch
5212 */
5213 from_model: string;
5214 /**
5215 * Resolved model id the session runs after the switch
5216 */
5217 to_model: string;
5218 /**
5219 * What was asked for (alias such as "opus", a full id, or null for "default")
5220 */
5221 requested_model: string | null;
5222 /**
5223 * 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
5224 */
5225 source: 'command' | 'picker' | 'sdk' | 'auto' | 'resume';
5226 /**
5227 * 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)
5228 */
5229 context_tokens: number;
5230 /**
5231 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
5232 */
5233 prompt_cache_warm: boolean;
5234 cache_ttl: '5m' | '1h';
5235 /**
5236 * 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
5237 */
5238 estimated_cache_write_usd: number;
5239 /**
5240 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
5241 */
5242 pricing: 'configured' | 'catalog' | 'default';
5243 };
5244
5245 /**
5246 * 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.
5247 */
5248 type PostToolBatchHookInput = BaseHookInput & {
5249 hook_event_name: 'PostToolBatch';
5250 tool_calls: PostToolBatchToolCall[];
5251 };
5252
5253 type PostToolBatchToolCall = {
5254 tool_name: string;
5255 tool_input: unknown;
5256 tool_use_id: string;
5257 tool_response?: unknown;
5258 };
5259
5260 type PostToolUseFailureHookInput = BaseHookInput & {
5261 hook_event_name: 'PostToolUseFailure';
5262 tool_name: string;
5263 tool_input: unknown;
5264 tool_use_id: string;
5265 error: string;
5266 is_interrupt?: boolean;
5267 /**
5268 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
5269 */
5270 duration_ms?: number;
5271 };
5272
5273 type PostToolUseHookInput = BaseHookInput & {
5274 hook_event_name: 'PostToolUse';
5275 tool_name: string;
5276 tool_input: unknown;
5277 tool_response: unknown;
5278 tool_use_id: string;
5279 /**
5280 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
5281 */
5282 duration_ms?: number;
5283 };
5284
5285 type PreCompactHookInput = BaseHookInput & {
5286 hook_event_name: 'PreCompact';
5287 trigger: 'manual' | 'auto';
5288 custom_instructions: string | null;
5289 };
5290
5291 type PreModelSwitchHookInput = (BaseHookInput & {
5292 hook_event_name: 'PreModelSwitch';
5293 }) & {
5294 /**
5295 * Resolved model id the session was running before the switch
5296 */
5297 from_model: string;
5298 /**
5299 * Resolved model id the session runs after the switch
5300 */
5301 to_model: string;
5302 /**
5303 * What was asked for (alias such as "opus", a full id, or null for "default")
5304 */
5305 requested_model: string | null;
5306 /**
5307 * 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)
5308 */
5309 source: 'command' | 'picker' | 'sdk';
5310 /**
5311 * 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)
5312 */
5313 context_tokens: number;
5314 /**
5315 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
5316 */
5317 prompt_cache_warm: boolean;
5318 cache_ttl: '5m' | '1h';
5319 /**
5320 * 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
5321 */
5322 estimated_cache_write_usd: number;
5323 /**
5324 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
5325 */
5326 pricing: 'configured' | 'catalog' | 'default';
5327 };
5328
5329 /**
5330 * The decision of a `classic.PreToolUse` result: `allow`, `ask`, `deny`, or
5331 * none.
5332 */
5333 export type PreToolUseDecision = {
5334 /**
5335 * Lets the call run without a permission prompt (the managed-settings
5336 * hooks ran first; a deny from them ended the chain above).
5337 */
5338 allow: true;
5339 ask?: undefined;
5340 deny?: undefined;
5341 } | {
5342 /**
5343 * Asks the user before the call runs; the text is shown as the reason.
5344 */
5345 ask: string;
5346 allow?: undefined;
5347 deny?: undefined;
5348 } | {
5349 /**
5350 * Refuses the call; the model receives the text as the reason.
5351 */
5352 deny: string;
5353 allow?: undefined;
5354 ask?: undefined;
5355 } | {
5356 allow?: undefined;
5357 ask?: undefined;
5358 deny?: undefined;
5359 };
5360
5361 type PreToolUseHookInput = BaseHookInput & {
5362 hook_event_name: 'PreToolUse';
5363 tool_name: string;
5364 tool_input: unknown;
5365 tool_use_id: string;
5366 };
5367
5368 /**
5369 * What a `classic.PreToolUse` hook returns: one of `allow`, `ask`, `deny`,
5370 * or none of them, which passes the call on to the normal permission flow.
5371 */
5372 export type PreToolUseResult = PreToolUseDecision & {
5373 /**
5374 * Replaces the tool's arguments; validated against the tool's schema before
5375 * the tool runs.
5376 */
5377 updatedInput?: Record<string, unknown>;
5378 /**
5379 * Extra context handed to the model with the call, one entry per note.
5380 */
5381 additionalContext?: string[];
5382 };
5383
5384 /**
5385 * Options of `$.process.run`.
5386 */
5387 export type ProcessRunInit = {
5388 /**
5389 * The child's working directory, relative to the session's or absolute;
5390 * absent, the session's working directory.
5391 */
5392 cwd?: string;
5393 /**
5394 * Variables set over the host process's own environment.
5395 */
5396 env?: Record<string, string>;
5397 /**
5398 * Text written to the child's standard input, then closed.
5399 */
5400 stdin?: string;
5401 /**
5402 * How long the child may run before it is killed and the call rejects,
5403 * in milliseconds; 30 seconds when absent, ten minutes at most.
5404 */
5405 timeoutMs?: number;
5406 };
5407
5408 /**
5409 * What `$.process.run` resolves with once the child has exited.
5410 */
5411 export type ProcessRunResult = {
5412 /**
5413 * The child's exit status; a child ended by a signal reads as 1.
5414 */
5415 exitCode: number;
5416 /**
5417 * What the child wrote to standard output, as text, cut at the output
5418 * limit.
5419 */
5420 stdout: string;
5421 /**
5422 * What the child wrote to standard error, as text, cut at the output
5423 * limit.
5424 */
5425 stderr: string;
5426 };
5427
5428 /**
5429 * A pasted or attached non-text item of a prompt; its kind, never its bytes.
5430 */
5431 export type PromptAttachment = {
5432 /**
5433 * The item's kind.
5434 */
5435 type: 'image' | 'audio' | 'document';
5436 /**
5437 * The item's MIME type (`image/png`), when known.
5438 */
5439 mediaType?: string;
5440 /**
5441 * The pasted file's name, when it had one.
5442 */
5443 filename?: string;
5444 };
5445
5446 /**
5447 * One block of the context the first user message carries: a name the
5448 * engine keys it by and the text under it.
5449 */
5450 export type PromptContextBlock = {
5451 /**
5452 * The key the block renders under (`# name`): `claudeMd`, `userEmail`,
5453 * `attachedProject`, `currentDate`, or a plugin's own.
5454 *
5455 * The field a matcher narrows on; unique among one context's blocks.
5456 */
5457 name: string;
5458 /**
5459 * The block's text; `claudeMd`'s is the instruction files framed as the
5460 * engine frames them, empty when it announces none.
5461 */
5462 text: string;
5463 };
5464
5465 /**
5466 * The context blocks of a conversation's first user message, in the order
5467 * the engine renders them: what `prompt.context` takes and answers alike.
5468 */
5469 export type PromptContextBlocks = {
5470 /**
5471 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
5472 * `attachedProject`, `currentDate`, each only when present.
5473 */
5474 blocks: readonly PromptContextBlock[];
5475 };
5476
5477 /**
5478 * The input of `prompt.context`: the context blocks the engine prepends to
5479 * a conversation's first user message, at the moment it computes them.
5480 */
5481 export type PromptContextInput = PromptContextBlocks;
5482
5483 /**
5484 * What a `prompt.context` hook returns: the blocks the conversation
5485 * carries, in order; one left out is not sent.
5486 */
5487 export type PromptContextResult = PromptContextBlocks;
5488
5489 /**
5490 * `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it:
5491 * `origin` is the engine's to set (the calling plugin's name).
5492 */
5493 export type PromptFillArgs = Omit<PromptFillInput, 'origin'>;
5494
5495 /**
5496 * The input of `prompt.fill` (prompt-fill/): a text about to be written into
5497 * the prompt box as the person's draft, replacing what the box holds.
5498 */
5499 export type PromptFillInput = {
5500 /**
5501 * What the box is to hold, cursor at its end; the person edits it or
5502 * presses Enter. `next({ ...e, text })` writes another.
5503 */
5504 text: string;
5505 /**
5506 * Who writes (PromptFillOrigin), set by the engine where the write
5507 * starts. Pinned: `next(e)` passes it on as received.
5508 */
5509 origin: PromptFillOrigin;
5510 };
5511
5512 /**
5513 * Who writes the prompt box at `prompt.fill`, as the engine stamps it where
5514 * the write starts; a closed set a matcher narrows on.
5515 *
5516 * `next(e)` passes it on as received; no hook sets one.
5517 */
5518 export type PromptFillOrigin = {
5519 /**
5520 * The engine writing the box on its own account; reserved for its own
5521 * sites, none of which raises `prompt.fill` as shipped.
5522 */
5523 kind: 'engine';
5524 } | {
5525 /**
5526 * A plugin's `$.prompt.fill`.
5527 */
5528 kind: 'plugin';
5529 /**
5530 * The filling plugin's name.
5531 */
5532 name: string;
5533 };
5534
5535 /**
5536 * What a `prompt.fill` hook returns and what `next(e)` resolves to: whether
5537 * the text went into the prompt box.
5538 */
5539 export type PromptFillResult = {
5540 /**
5541 * True once the box holds the text; false where no box can take it (a
5542 * dialog holds the keys, a headless session has none).
5543 *
5544 * A hook answering `{ isFilled: false }` without `next` keeps the text
5545 * out.
5546 */
5547 isFilled: boolean;
5548 };
5549
5550 /**
5551 * Where a `prompt.submit` submission came from, as the engine knows it at
5552 * the site it was queued from; a closed set, never a text prefix.
5553 *
5554 * A hooks module reads `e.origin.kind` to tell the user's own Enter from a
5555 * notification, a peer session, a schedule or another plugin. `next(e)`
5556 * passes it on as received; an answer may leave it out; no hook sets one.
5557 */
5558 export type PromptOrigin = {
5559 /**
5560 * The user's own gesture at the terminal, as the engine stamped it
5561 * (never presumed from an unstamped command).
5562 *
5563 * Enter at the prompt, typed or queued, or a click on a transcript
5564 * link; a channel the engine cannot attest (a same-user socket) is
5565 * never stamped, and arrives as `unclassified`.
5566 */
5567 kind: 'composer';
5568 } | {
5569 /**
5570 * The user's message through the Remote Control bridge (a phone or
5571 * web client).
5572 */
5573 kind: 'bridge';
5574 } | {
5575 /**
5576 * The SDK host's own turn (`claude -p`, the Agent SDK), not typed at
5577 * a terminal.
5578 */
5579 kind: 'sdk';
5580 } | {
5581 /**
5582 * A background task's notification, dequeued when the session went
5583 * idle or delivered into a running turn (`turnId` set).
5584 */
5585 kind: 'task-notification';
5586 } | {
5587 /**
5588 * A scheduled task, routine or /loop firing its stored prompt.
5589 */
5590 kind: 'scheduled-trigger';
5591 } | {
5592 /**
5593 * Another Claude session's message ("Another Claude session sent a
5594 * message"), as a turn of its own or delivered into a running one.
5595 */
5596 kind: 'peer';
5597 } | {
5598 /**
5599 * Another session's SendMessage delivery, model-authored and framed
5600 * as a notification.
5601 */
5602 kind: 'peer-send-message';
5603 } | {
5604 /**
5605 * A delivery a coordinating session composed for one of its threads.
5606 */
5607 kind: 'projects-relay';
5608 } | {
5609 /**
5610 * A message from a channel an MCP server relays (Slack, Telegram).
5611 */
5612 kind: 'channel';
5613 /**
5614 * The channel server's name.
5615 */
5616 server: string;
5617 } | {
5618 /**
5619 * A coordinating session's hand-off to a worker session.
5620 */
5621 kind: 'coordinator';
5622 } | {
5623 /**
5624 * A background observer agent's report to the agent it observes.
5625 */
5626 kind: 'observer';
5627 } | {
5628 /**
5629 * An activity digest delivered to an observer agent.
5630 */
5631 kind: 'observer-activity';
5632 } | {
5633 /**
5634 * A programmatic follow-up to a user's UI action, user-initiated but
5635 * not typed this turn.
5636 */
5637 kind: 'auto-continuation';
5638 } | {
5639 /**
5640 * A turn with no provenance the engine can name: one the ingress
5641 * could not classify, or a command queued with no stamp at all.
5642 *
5643 * An idle notice or a delivery receipt the engine queued isMeta with
5644 * no stamp is one too; the engine frames that shape as a non-user
5645 * source.
5646 */
5647 kind: 'unclassified';
5648 } | {
5649 /**
5650 * The session's owner pinging it from Slack.
5651 */
5652 kind: 'slack-ping';
5653 } | {
5654 /**
5655 * A plugin's `$.prompt.submit`; the model reads the prompt under the
5656 * plugin's name unless a hook leaves the origin out of its answer.
5657 */
5658 kind: 'plugin';
5659 /**
5660 * The submitting plugin's name.
5661 */
5662 name: string;
5663 };
5664
5665 /**
5666 * The input of `prompt.section`: one named section of the system prompt, at
5667 * the moment the engine assembles it.
5668 */
5669 export type PromptSectionInput = {
5670 /**
5671 * As the engine names the section (`env_info_simple`, `memory`, ...); the
5672 * key a matcher narrows on.
5673 */
5674 name: string;
5675 /**
5676 * The section's text as core computed it, or null when core omits it.
5677 */
5678 text: string | null;
5679 };
5680
5681 /**
5682 * What a `prompt.section` hook returns: the text the prompt carries for that
5683 * section, or null to leave it out.
5684 */
5685 export type PromptSectionResult = {
5686 text: string | null;
5687 };
5688
5689 /**
5690 * `prompt.submit`'s input as a plugin's call takes it: `origin`, `turnId`
5691 * and `wait` are the engine's to set, `context` the hooks' to attach.
5692 *
5693 * `origin` is the calling plugin's name; `turnId` is the turn a prompt typed
5694 * mid-turn ran over; `wait` is false, as a plugin's prompt runs once idle.
5695 */
5696 export type PromptSubmitArgs = Omit<PromptSubmitInput, 'origin' | 'turnId' | 'wait' | 'context'>;
5697
5698 /**
5699 * The input of `prompt.submit`: the prompt as typed, after the input became
5700 * a user message and before it enters the session.
5701 */
5702 export type PromptSubmitInput = {
5703 /**
5704 * The prompt's text as it will reach the model (pastes already expanded).
5705 */
5706 text: string;
5707 /**
5708 * Present only when the submission carried images or other non-text items.
5709 */
5710 attachments?: readonly PromptAttachment[];
5711 /**
5712 * What the model reads beside the prompt and the user never sees, each
5713 * entry one block after the prompt as typed; absent as the engine raises it.
5714 *
5715 * A hook attaches on the way down: `next({ ...e, context: [...(e.context
5716 * ?? []), mine] })`. It may not leave out an entry it received; the whole
5717 * is capped at 32000 characters, no entry empty.
5718 */
5719 context?: readonly string[];
5720 /**
5721 * The id of the model turn that was running when the prompt was submitted
5722 * (`turn.start`'s `turnId`): typed over that turn, or delivered into it.
5723 *
5724 * A queued delivery (a peer session's message) reaches the model inside a
5725 * running turn. Absent for a prompt submitted while the session was idle,
5726 * and for a plugin's own (`$.prompt.submit`), which runs once it is idle.
5727 */
5728 turnId?: string;
5729 /**
5730 * Whether the user asked the prompt to wait its turn (`chat:queueSubmit`,
5731 * `ctrl+x enter` by default): true for that submission, false otherwise.
5732 *
5733 * The engine queues every prompt typed mid-turn either way; the flag is
5734 * for hooks, so one that cancels the running turn on a plain Enter can
5735 * leave a waiting prompt alone. False for a prompt a plugin submitted.
5736 */
5737 wait: boolean;
5738 /**
5739 * Where the submission came from (PromptOrigin), set by the engine where
5740 * it was queued: the user's Enter, a notification, a peer, a plugin.
5741 *
5742 * `next(e)` passes it on as received; no hook may set one.
5743 */
5744 origin: PromptOrigin;
5745 };
5746
5747 /**
5748 * What a `prompt.submit` hook returns and what `next(e)` resolves to: the
5749 * prompt that entered, `{ text, context?, origin? }`, or `{ drop: reason }`.
5750 *
5751 * `next(e)` resolves once the prompt entered the session and its turn
5752 * started, or it was queued behind the running one; not when the turn ends,
5753 * which is `turn.complete`. A hook answering without `next` enters nothing.
5754 */
5755 export type PromptSubmitResult = {
5756 /**
5757 * The prompt that entered; from core, the text that arrived at the
5758 * bottom. A rewrite passes it down, `next({ ...e, text })`.
5759 */
5760 text: string;
5761 /**
5762 * What entered beside the prompt for the model, never shown the user:
5763 * from core, the context that arrived (`e.context`).
5764 *
5765 * Each entry is one block after the prompt as typed. A hook attaches
5766 * context on the way down; one put here after `next` resolved is not
5767 * attached (the prompt had entered), and is logged.
5768 */
5769 context?: readonly string[];
5770 /**
5771 * Where the prompt entered from: from core, `e.origin` as received;
5772 * absent, the prompt is the user's own.
5773 *
5774 * A hook may put back the origin it received; it may not set another.
5775 */
5776 origin?: PromptOrigin;
5777 drop?: undefined;
5778 } | {
5779 /**
5780 * The prompt did not enter: a hook's refusal, answered without `next`,
5781 * or a settings hook's block beneath.
5782 *
5783 * The text is shown to the user as the reason.
5784 */
5785 drop: string;
5786 text?: undefined;
5787 context?: undefined;
5788 origin?: undefined;
5789 };
5790
5791 /**
5792 * `prompt.suggest`'s input as a plugin's `$.prompt.suggest(args)` takes it:
5793 * `origin` is the engine's to set (the calling plugin's name).
5794 */
5795 export type PromptSuggestArgs = Omit<PromptSuggestInput, 'origin'>;
5796
5797 /**
5798 * The input of `prompt.suggest` (prompt-suggest/): a text about to be shown
5799 * dim in the empty prompt box, for Tab (or the right arrow) to take.
5800 */
5801 export type PromptSuggestInput = {
5802 /**
5803 * The proposed prompt: shown, not written; taking it puts it in the box
5804 * for editing. `next({ ...e, text })` proposes another.
5805 */
5806 text: string;
5807 /**
5808 * Who proposes (PromptSuggestOrigin), set by the engine where the
5809 * proposal starts. Pinned: `next(e)` passes it on as received.
5810 */
5811 origin: PromptSuggestOrigin;
5812 };
5813
5814 /**
5815 * Who proposes the text at `prompt.suggest`, as the engine stamps it where
5816 * the proposal starts; a closed set a matcher narrows on.
5817 *
5818 * `next(e)` passes it on as received; no hook sets one.
5819 */
5820 export type PromptSuggestOrigin = {
5821 /**
5822 * The engine's own guess at the person's next prompt, generated after
5823 * a turn (the prompt-suggestion service).
5824 */
5825 kind: 'suggestion';
5826 } | {
5827 /**
5828 * A plugin's `$.prompt.suggest`.
5829 */
5830 kind: 'plugin';
5831 /**
5832 * The proposing plugin's name.
5833 */
5834 name: string;
5835 };
5836
5837 /**
5838 * What a `prompt.suggest` hook returns and what `next(e)` resolves to:
5839 * whether the text is now the box's dim suggestion.
5840 */
5841 export type PromptSuggestResult = {
5842 /**
5843 * True once the box has the suggestion to show, at once or as soon as a
5844 * dialog gives the box back; false where it cannot show.
5845 *
5846 * It cannot while the box holds text, a turn runs, the text is blank, or
5847 * the session is headless. A hook answering `{ isShown: false }` without
5848 * `next` keeps it from showing.
5849 */
5850 isShown: boolean;
5851 };
5852
5853 /**
5854 * The props of `Raster`, the terminal surface's cell-grid leaf: a fixed box
5855 * of cells, each a glyph, a foreground and a background, packed in `cells`.
5856 *
5857 * A leaf: no children, `hover` or `onPress` yet; repainted in place by
5858 * `$.ui.blit`. Terminal only for now (elsewhere a fragment); its palette
5859 * paints 1024 distinct color pairs at once and the rest as their nearest.
5860 */
5861 export type RasterProps = {
5862 /**
5863 * The element's address within the drawing: what `$.ui.blit` names to
5864 * repaint it, unique among the Rasters of one tree.
5865 */
5866 key: string;
5867 /**
5868 * How many terminal columns wide, 1 to 512; the site clips what its body
5869 * cannot show.
5870 */
5871 columns: number;
5872 /**
5873 * How many terminal rows tall, 1 to 256.
5874 */
5875 rows: number;
5876 /**
5877 * Every cell, row-major: standard padded base64 of `columns * rows`
5878 * little-endian u32 triplets `[codePoint, foreground, background]`.
5879 *
5880 * A code point is one printable width-1 BMP character (blocks, box drawing,
5881 * braille too), or the tree is refused naming the cell's index; a color is
5882 * `0x00RRGGBB`, or `0x01000000` (bit 24 alone) for the terminal's default.
5883 *
5884 * @example const words = Uint32Array.of(0x2588, 0xff8800, 0x01000000)
5885 * const cells = new Uint8Array(words.buffer).toBase64() // one orange cell
5886 */
5887 cells: string;
5888 };
5889
5890 /**
5891 * The hooks module's entry: `export function register(on, options)`. `on`
5892 * registers hooks; `options` is the plugin's configuration (PluginOptions).
5893 *
5894 * The options are fixed for this activation: a change to them reloads the
5895 * plugin and `register` runs again with the new object. Hooks close over it.
5896 * Its return is dropped, a promise awaited: `on => on(...)` is a module.
5897 *
5898 * @example
5899 * on("tool.call", ($, e, next) => e.tool === "Bash" ? { deny: "no" } : next(e))
5900 */
5901 export type Register = (on: On, options: PluginOptions) => unknown;
5902
5903 /**
5904 * What `on(...)` returns for a hook of type `F`: the registration, which
5905 * takes one `.catch` (CatchHandler); without it a failed hook is absent.
5906 *
5907 * A second `.catch` on one registration throws, as does one after
5908 * register() returned and one on `engine.create`, whose hook has no budget
5909 * and whose failure is the load's.
5910 */
5911 export type Registration<F> = {
5912 /**
5913 * Sets the handler run when the hook throws or overruns its budget; its
5914 * answer within the grace stands as the hook's result for the dispatch.
5915 */
5916 readonly catch: (handler: CatchHandler<F>) => void;
5917 };
5918
5919 /**
5920 * What an element takes as `children`, as JSX passes them: a node, a number
5921 * (drawn as its string), a value the factory drops, or a list that may nest.
5922 *
5923 * `false`, `null` and `undefined` are dropped, so `{ok && <Text>hi</Text>}`
5924 * and `{n > 0 ? <Text>{n}</Text> : null}` type; a mapped list beside a
5925 * sibling nests. The element holds the flat, normalized list of RenderNode.
5926 */
5927 export type RenderChildren = RenderNode | number | boolean | null | undefined | readonly RenderChildren[];
5928
5929 /**
5930 * Everything `ui.render` can draw: one name per component that has a render
5931 * site; a matcher narrows on it.
5932 *
5933 * The permission dialog is drawn by the engine alone, since its answer
5934 * authorises an action; a plugin adds context with `$.ui.notice`. `Pane` is
5935 * the one component whose instances a plugin opens (`$.ui.open`).
5936 */
5937 export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
5938
5939 /**
5940 * What a render hook returns, and what `next(e)` resolves to: a plain-data
5941 * tree of elements (a Box or Text is a StyledElement), strings as children.
5942 *
5943 * Props are an allowlisted subset of Ink's Box/Text props (the ones
5944 * ElementProps declares); a tree with any other prop fails validation as a
5945 * whole and the engine's own component is drawn with the original props.
5946 */
5947 export type RenderElement = StyledElement<'Box', BoxHoverProps> | StyledElement<'Text', TextHoverProps> | {
5948 /**
5949 * A button, on every surface: `[ label ]` on the terminal, a native
5950 * button on a desktop; a press raises `ui.press` (`e.element` the key).
5951 *
5952 * Built by `<Button>` or the table's `t.Button`. The `onPress` closure
5953 * stays in the plugin's own environment under `press.handle`; the host
5954 * holds the handle for the lifetime of the drawing. A leaf: no children.
5955 */
5956 type: 'Button';
5957 props: {
5958 /**
5959 * The element's address: what `e.element` carries and what a matcher
5960 * names (`{ element: "explain" }`).
5961 */
5962 key: string;
5963 /**
5964 * The text drawn on the button.
5965 */
5966 label: string;
5967 /**
5968 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it
5969 * where the site honours one; anything else is refused.
5970 *
5971 * A bare digit in an empty composer presses, as a survey is answered;
5972 * while one of the band's Buttons has the focus a digit or a letter
5973 * presses on keydown, lowercased. Two on one hotkey: the later wins.
5974 */
5975 hotkey?: string;
5976 /**
5977 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord
5978 * presses the Button from the prompt; an unknown name is refused.
5979 *
5980 * Chords, or a modified key Global or an active context binds, on
5981 * the terminal while mounted, no dialog up, no engine handler of it
5982 * mounted; a pane's over the band's over another's, the last drawn.
5983 */
5984 action?: string;
5985 /**
5986 * Drawn without chrome: the hotkey in the accent color, a colon,
5987 * then the label (`1: Yes`); without a `hotkey`, the label alone.
5988 *
5989 * The focus still inverts it. In JSX the label may be the one string
5990 * child (`<Button hotkey="1" plain onPress={...}>Yes</Button>`); the
5991 * key defaults to the label.
5992 */
5993 plain?: true;
5994 /**
5995 * The label dim at rest, as `Text`'s `dimColor`, and at full strength
5996 * under the pointer or the focus; absent draws as false.
5997 */
5998 dimColor?: TextProps['dimColor'];
5999 /**
6000 * The site's ring starts on this element when the site takes the
6001 * keyboard; the first drawn of several. Absent draws as before.
6002 */
6003 autoFocus?: true;
6004 };
6005 /**
6006 * Where the handler lives: the plugin whose hook drew the element, and
6007 * the handle its environment keeps the `onPress` closure under.
6008 *
6009 * The runtime stamps the plugin as the tree leaves that hook.
6010 */
6011 press: {
6012 plugin: string;
6013 handle: number;
6014 };
6015 /**
6016 * Label style overrides (the Text set) the surface applies while the
6017 * nearest keyed Box, or the group `scope` names, is hovered; plain data.
6018 */
6019 hover?: TextHoverProps;
6020 } | {
6021 /**
6022 * A one-line text field on every surface; a change and Enter raise
6023 * `ui.input` (`e.element` the key, `e.kind` which, `e.value` the text).
6024 *
6025 * Built by `<Input>` or the table's `t.Input`. The `onInput` and
6026 * `onSubmit` closures stay in the plugin's own environment under
6027 * `press.handle`, held as a Button's is. A leaf: no children.
6028 */
6029 type: 'Input';
6030 props: {
6031 /**
6032 * The element's address: what `e.element` carries and what a matcher
6033 * names (`{ element: "reply" }`).
6034 */
6035 key: string;
6036 /**
6037 * Text drawn before the field.
6038 */
6039 label?: string;
6040 /**
6041 * Text drawn dim in an empty field.
6042 */
6043 placeholder?: string;
6044 /**
6045 * The text the field holds when drawn.
6046 */
6047 value?: string;
6048 /**
6049 * What Enter does, drawn beside the field while it has focus.
6050 */
6051 submitLabel?: string;
6052 /**
6053 * The site's ring starts on this element when the site takes the
6054 * keyboard; the first drawn of several. Absent draws as before.
6055 */
6056 autoFocus?: true;
6057 };
6058 /**
6059 * Where the handlers live: the plugin whose hook drew the element, and
6060 * the handle its environment keeps the closures under.
6061 *
6062 * The runtime stamps the plugin as the tree leaves that hook.
6063 */
6064 press: {
6065 plugin: string;
6066 handle: number;
6067 };
6068 children?: undefined;
6069 } | {
6070 /**
6071 * A one-of-several picker on every surface; a pick raises `ui.select`
6072 * (`e.element` the key, `e.value` the option's value).
6073 *
6074 * Built by `<Select>` or the table's `t.Select`. The `onSelect` closure
6075 * stays in the plugin's own environment under `press.handle`, held as
6076 * a Button's is. A leaf: no children.
6077 */
6078 type: 'Select';
6079 props: {
6080 /**
6081 * The element's address: what `e.element` carries and what a matcher
6082 * names (`{ element: "peer" }`).
6083 */
6084 key: string;
6085 /**
6086 * Text drawn before the current value.
6087 */
6088 label?: string;
6089 /**
6090 * What can be picked, in the order drawn: each a value and the text
6091 * drawn for it.
6092 */
6093 options: readonly SelectOption[];
6094 /**
6095 * Which option is selected when drawn.
6096 */
6097 value?: string;
6098 /**
6099 * The site's ring starts on this element when the site takes the
6100 * keyboard; the first drawn of several. Absent draws as before.
6101 */
6102 autoFocus?: true;
6103 };
6104 /**
6105 * Where the handler lives: the plugin whose hook drew the element, and
6106 * the handle its environment keeps the closure under.
6107 *
6108 * The runtime stamps the plugin as the tree leaves that hook.
6109 */
6110 press: {
6111 plugin: string;
6112 handle: number;
6113 };
6114 children?: undefined;
6115 } | {
6116 /**
6117 * A hyperlink every surface draws: an OSC 8 span on the terminal (its
6118 * text then the URL in dim where unsupported), an anchor on desktop.
6119 *
6120 * Inline: its children are the text, strings and inline elements;
6121 * absent children the label, absent both the URL. `href` is `https:`
6122 * (or `http://localhost`) and bounded, or the tree is refused.
6123 */
6124 type: 'Link';
6125 props: LinkProps;
6126 children?: RenderNode[];
6127 } | {
6128 /**
6129 * Source code every surface draws with the engine's highlighter, tokens
6130 * coloured by language; under `format: 'diff'`, unified-diff hunks.
6131 *
6132 * A leaf: a dim gutter numbers the lines from `startLine`; a diff has
6133 * both gutters, markers, add and remove backgrounds. `source` is
6134 * bounded as a Text's string is, or the tree is refused.
6135 */
6136 type: 'Code';
6137 props: CodeProps;
6138 children?: undefined;
6139 } | {
6140 /**
6141 * A region one of the plugin's SURFACE MODULES, named by path, draws and
6142 * handles input for on the drawing thread, without `$` (ClientModule).
6143 *
6144 * `Client` from the table. One instance per plugin, drawing and `key`
6145 * lives while the node stays in the tree, and talks to the plugin's
6146 * hooks through `ui.message`. The desktop carries it as data.
6147 */
6148 type: 'Client';
6149 props: ClientProps;
6150 /**
6151 * Whose surface module `props.module` names: the plugin whose hook
6152 * drew the element, stamped by the runtime as the tree leaves it.
6153 */
6154 client: {
6155 plugin: string;
6156 };
6157 children?: undefined;
6158 } | {
6159 /**
6160 * A vector drawing, the remote surfaces' alone: the SVG markup is the
6161 * element's data, drawn in an isolated box, off the page.
6162 *
6163 * A leaf: hooks above wrap or replace it whole, nothing reaches inside;
6164 * a press other plugins should see goes on an enclosing Button. On a
6165 * surface whose table lacks it the tree is refused.
6166 */
6167 type: 'Svg';
6168 props: SvgProps;
6169 children?: undefined;
6170 } | {
6171 /**
6172 * A grid of terminal cells, the terminal surface's alone: each cell a
6173 * glyph, a foreground and a background, packed in `props.cells`.
6174 *
6175 * A leaf, one node however many cells; hooks above wrap or replace it
6176 * whole. A mounted one is repainted in place by its plugin's
6177 * `$.ui.blit`. On a surface whose table lacks it the tree is refused.
6178 */
6179 type: 'Raster';
6180 props: RasterProps;
6181 /**
6182 * Whose Raster: the plugin whose hook drew the element, stamped by the
6183 * runtime as the tree leaves it; the one plugin whose blit reaches it.
6184 */
6185 raster: {
6186 plugin: string;
6187 };
6188 children?: undefined;
6189 } | {
6190 /**
6191 * The component core draws itself, with the props held under `ref`.
6192 */
6193 type: 'engine';
6194 /**
6195 * Which drawing: the number core answered from `next(e)`, under which
6196 * it holds the props it received; 0 draws the original props.
6197 */
6198 ref: number;
6199 };
6200
6201 /**
6202 * The render event: `ui.render`, one event for every component that has a
6203 * render site.
6204 */
6205 export type RenderEventName = 'ui.render';
6206
6207 /**
6208 * The input of `ui.render`: a union discriminated by `component`, one member
6209 * per RenderComponent and per RenderSurface.
6210 */
6211 export type RenderInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = C extends RenderComponent ? P extends RenderSurface ? RenderInputOf<C, P> : never : never;
6212
6213 /**
6214 * One `ui.render` input, for a component narrowed to one surface.
6215 */
6216 export type RenderInputOf<C extends RenderComponent, P extends RenderSurface> = {
6217 /**
6218 * Where the tree will be drawn; one literal per member, so
6219 * `if (e.surface === "terminal")` narrows `e` and `$.ui.resolve(e)`.
6220 *
6221 * Over the wire it is what the client declared, a rendering fact and not a
6222 * trust signal: do not key policy on it.
6223 */
6224 surface: P;
6225 /**
6226 * Which component this instance is; the key a matcher narrows on.
6227 */
6228 component: C;
6229 /**
6230 * The instance: the tool_use_id for a dialog or tool row, the message id
6231 * for a message, the agent id for a spinner.
6232 *
6233 * Two drawings of one component are two instances.
6234 */
6235 requestId: string;
6236 /**
6237 * The size of what the surface draws into, in character cells; absent where
6238 * no surface has measured. Part of the envelope: a rewrite keeps it.
6239 *
6240 * On the terminal, the interactive screen's size, where a change of width
6241 * re-draws every hooked site once the resize settles (a hook that sized its
6242 * tree to `columns` runs again); on a remote surface, what it reported.
6243 */
6244 viewport?: RenderViewport;
6245 /**
6246 * The component's plain-data props.
6247 */
6248 props: RenderPropsOf[C];
6249 };
6250
6251 /**
6252 * A node of a render tree: an element, or a string (text).
6253 */
6254 export type RenderNode = RenderElement | string;
6255
6256 /**
6257 * The plain-data props of each renderable component, as `ui.render` sees
6258 * them under `e.props`; a hook rewrites them with `next({ ...e, props })`.
6259 *
6260 * A rewrite is validated by the component and an invalid one draws the
6261 * original. This table is the plugin-facing render contract: the terminal
6262 * and the Code session renderer draw these components from these props.
6263 */
6264 export type RenderPropsOf = {
6265 /**
6266 * The dialog the AskUserQuestion tool opens.
6267 */
6268 AskUserQuestion: {
6269 /**
6270 * The name of the tool whose call opened the dialog (`AskUserQuestion`).
6271 */
6272 tool: string;
6273 /**
6274 * The tool's `questions` input, as the dialog will draw them; a rewrite
6275 * must still fit the tool's schema or the original is drawn.
6276 */
6277 questions: unknown[];
6278 /**
6279 * The call's `metadata.source` (who asked) when the model gave one.
6280 * Analytics only; never drawn.
6281 */
6282 metadataSource?: string;
6283 };
6284 /**
6285 * The user's own prompt in the transcript (the `> ...` row); a rewrite is
6286 * drawn there and nowhere else (the stored message is untouched).
6287 */
6288 UserMessage: {
6289 /**
6290 * The prompt's text, as the row draws it.
6291 */
6292 text: string;
6293 /**
6294 * Where the stored message came from, as `prompt.submit` named it
6295 * (PromptOrigin): the composer's, a peer's, a notification's, a plugin's.
6296 *
6297 * Read-only: a rewrite carries it on as received; one that changes or
6298 * drops it is refused and the engine draws its own row.
6299 */
6300 origin: PromptOrigin;
6301 };
6302 /**
6303 * One text block of an assistant reply in the transcript; a rewrite
6304 * changes the drawing and leaves the stored message alone (ctrl+o).
6305 */
6306 AssistantMessage: {
6307 /**
6308 * The block's text, markdown, as the transcript will draw it.
6309 */
6310 text: string;
6311 /**
6312 * True on the block that draws the bullet opening a reply.
6313 */
6314 isFirstOfReply: boolean;
6315 };
6316 /**
6317 * A tool call's row in the transcript (`Bash(ls -la)` and its result); the
6318 * call was decided by `tool.call`, so a rewrite here changes the row alone.
6319 */
6320 ToolUse: {
6321 /**
6322 * The id `tool.call` carried for this call (`e.tool_use_id` there); the
6323 * same value as the row's `requestId`, where it is looked for. Read-only.
6324 */
6325 tool_use_id: string;
6326 /**
6327 * Which one the row draws (`Bash`, `Read`, a plugin's tool), as
6328 * `tool.call` named it.
6329 */
6330 tool: string;
6331 /**
6332 * The call's input, as the model sent it.
6333 */
6334 input: unknown;
6335 /**
6336 * True while the call is still running.
6337 */
6338 isRunning: boolean;
6339 /**
6340 * True when the call ended in an error (a refusal at the dialog is one).
6341 */
6342 isErrored: boolean;
6343 /**
6344 * True when an abort ended the call: the user's Esc or a plugin's
6345 * `$.turn.abort` cut it while it ran, or dropped it before it ran.
6346 *
6347 * The row draws `Interrupted` for it, as the transcript marker does.
6348 */
6349 isInterrupted: boolean;
6350 /**
6351 * The stored result once the call has resolved (`{ stdout, stderr, ... }`
6352 * for Bash: `BuiltinToolResults[tool]`); undefined while it runs.
6353 *
6354 * For a call that errored, was refused or an abort cut, it is the text
6355 * the model read (an `isInterrupted` call: the abort's own). An expanded
6356 * group's rows draw it inline; a standalone row's is its own `ToolResult`.
6357 */
6358 output?: unknown;
6359 };
6360 /**
6361 * The result block drawn under a standalone tool row in the transcript,
6362 * which the tool's own result renderer draws from `output`.
6363 *
6364 * A rewrite of `output` is checked against the tool's output schema (one
6365 * that does not fit draws nothing; one the renderer cannot read hits the
6366 * row's error boundary). The stored result is untouched.
6367 */
6368 ToolResult: {
6369 /**
6370 * The id `tool.call` carried for the call this result belongs to
6371 * (`e.tool_use_id` there); the same value as `requestId`. Read-only.
6372 */
6373 tool_use_id: string;
6374 /**
6375 * Which one the result belongs to (`Bash`, `Read`, a plugin's tool).
6376 * Read-only.
6377 */
6378 tool: string;
6379 /**
6380 * The tool's own result object (`{ stdout, stderr, interrupted, ... }` for
6381 * Bash), the same one `ToolUse.output` carries; a rewrite is drawn.
6382 *
6383 * A built-in tool's is `BuiltinToolResults[tool]`, the record
6384 * `tool.call` resolved as `result`.
6385 */
6386 output: unknown;
6387 /**
6388 * True when the call ended in an error, which draws the error text and not
6389 * `output`. Read-only.
6390 */
6391 isErrored: boolean;
6392 };
6393 /**
6394 * A run of tool calls the transcript folds into one count line (`Read 3
6395 * files, ran 2 shell commands`): reads, searches, listings.
6396 *
6397 * A hook that sets `isExpanded` unfolds the group where it is, and each row
6398 * it unfolds into is a `ToolUse` drawing a `ToolUse` hook then sees.
6399 */
6400 ToolGroup: {
6401 /**
6402 * In the order the model made them.
6403 */
6404 calls: ReadonlyArray<ToolGroupCall>;
6405 /**
6406 * True while the group is the live one: a call in it may still be
6407 * running and the model's next call may join it.
6408 */
6409 isActive: boolean;
6410 /**
6411 * Whether each call draws as its own `ToolUse` row (true under
6412 * `--verbose` and in the ctrl+o transcript) or the group draws one line.
6413 *
6414 * The one prop of the three a rewrite changes on the screen.
6415 */
6416 isExpanded: boolean;
6417 };
6418 /**
6419 * The output row a slash command printed in the transcript, under its echo
6420 * (`/cost`'s lines, the `text` a `command.run` hook answered).
6421 *
6422 * What the run resolved as text, a `local` command's or a plugin's alike. A
6423 * rewrite of `text` draws there and the stored row keeps what the model
6424 * reads; a hook's own tree draws in the row's place, the transcript's width.
6425 */
6426 CommandOutput: {
6427 /**
6428 * Which one printed the row, as `command.run` named it (no slash); a
6429 * hook on its own command matches by it.
6430 *
6431 * Read-only: a rewrite carries it on as received; one that changes or
6432 * drops it is refused and the engine draws its own row.
6433 */
6434 command: string;
6435 /**
6436 * The arguments the run had, as the echo above the row shows them
6437 * (`***` for a command that marks its arguments sensitive). Read-only.
6438 */
6439 args: string;
6440 /**
6441 * The row's text: what the command printed, or the `text` a hook
6442 * answered under its plugin's name; markdown, as the row draws it.
6443 */
6444 text: string;
6445 /**
6446 * True when the row is the run's error line (a command that threw),
6447 * which draws in the error colour and not dim. Read-only.
6448 */
6449 isErrored: boolean;
6450 };
6451 /**
6452 * The line that animates while a turn runs (`Sauteing... (12s, 300
6453 * tokens)`). Terminal only: the Code session renderer draws its own.
6454 */
6455 Spinner: {
6456 /**
6457 * Animated by the line (`Sauteing`), as sampled for this turn.
6458 */
6459 word: string;
6460 /**
6461 * The text drawn instead of the word while a state overrides it, else null.
6462 */
6463 message: string | null;
6464 /**
6465 * What the turn is doing.
6466 */
6467 mode: 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use';
6468 };
6469 /**
6470 * The line that closes a turn in the transcript (`Baked for 3s`).
6471 * Terminal only: the Code session renderer draws its own footer.
6472 */
6473 TurnDuration: {
6474 /**
6475 * The past-tense word the line drew (`Baked`), as sampled for this line.
6476 */
6477 word: string;
6478 /**
6479 * The turn's duration in milliseconds, as the line formats it (`3s`,
6480 * `1m 4s`).
6481 */
6482 durationMs: number;
6483 };
6484 /**
6485 * One dim status line under the logo (the model source, an experiment
6486 * enrollment, a settings hint), with a trailing `/command`. Terminal only.
6487 */
6488 InfoNotice: {
6489 /**
6490 * The notice's text, flattened to one string.
6491 */
6492 text: string;
6493 /**
6494 * The slash command appended after the text, or null when the notice has
6495 * none.
6496 */
6497 command: string | null;
6498 };
6499 /**
6500 * The dim mode labels at the right of the prompt footer (`focus`, `memory
6501 * paused`), joined by ` & `. One instance; terminal only.
6502 *
6503 * A hook adds a mode by rewriting `modes`, removes one by filtering, or
6504 * draws its own tree.
6505 */
6506 SessionMode: {
6507 /**
6508 * The labels the footer shows, in order; empty when there are none.
6509 */
6510 modes: readonly string[];
6511 };
6512 /**
6513 * The dim hint line under the prompt (`? for shortcuts`, `esc to
6514 * interrupt`, the pills beside them). One instance; terminal only.
6515 *
6516 * A hook rewrites `hint` and the rewrite is drawn in the line's place, or
6517 * draws its own tree; `isDraft` and `isWorking` say what the line is for.
6518 */
6519 PromptHint: {
6520 /**
6521 * True while the prompt holds typed text. Read-only.
6522 */
6523 isDraft: boolean;
6524 /**
6525 * True while a model turn is running. Read-only.
6526 */
6527 isWorking: boolean;
6528 /**
6529 * The line's text as the engine draws it; one string, so a rewrite
6530 * replaces the line.
6531 *
6532 * Read from the drawn line the way the screen reader reads it, one space
6533 * between parts.
6534 */
6535 hint: string;
6536 };
6537 /**
6538 * The band directly above the prompt input, where the surveys draw; the
6539 * engine draws nothing of its own here.
6540 *
6541 * A hook draws a tree, or passes; one instance, terminal only. The person
6542 * collapses it (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab):
6543 * an Input types, a Button arms the hotkeys, a tree taller than it scrolls.
6544 */
6545 AbovePrompt: {
6546 /**
6547 * True while a survey holds the band; a hook yields to it. Read-only.
6548 */
6549 hasSurvey: boolean;
6550 /**
6551 * True while a model turn is running. Read-only.
6552 */
6553 isWorking: boolean;
6554 /**
6555 * Rows the band may take: in fullscreen, what the bottom slot has left
6556 * above the prompt; otherwise the terminal's height. Read-only.
6557 *
6558 * A tree of at most `maxRows` rows shows whole; a taller one scrolls in a
6559 * window of `scroll.bodyRows` (one fewer, over a dim `n more` row), and a
6560 * bare digit arms none of its Buttons' hotkeys.
6561 */
6562 maxRows: number;
6563 /**
6564 * Cells across the band: the terminal's width, or the transcript
6565 * column's while a `Pane` is docked beside it. Read-only.
6566 *
6567 * A tree wider than this wraps or truncates as its Text props say; size
6568 * a table or a rule to it rather than to `viewport.columns`.
6569 */
6570 bodyColumns: number;
6571 /**
6572 * The band's window over a tree taller than `maxRows`: engine-owned,
6573 * moved by the wheel, and by the person's keys while the band is focused.
6574 *
6575 * `bodyRows` is `maxRows` less the `n more` row. Read-only.
6576 */
6577 scroll: SiteScroll;
6578 /**
6579 * Which transcript is on screen above the band: the main conversation's
6580 * (no `agentId`) or one agent's, opened from the tasks list.
6581 *
6582 * The same band under either; a switch re-runs the hook with the new
6583 * view. Read-only: a rewrite carries it on as received; one that changes
6584 * or drops it is refused, the hook that passed it failing.
6585 */
6586 view: SiteView;
6587 };
6588 /**
6589 * The framed region a plugin opened with `$.ui.open({ id })`: one instance
6590 * per id (`requestId`), its body the hook's tree, one shown, the rest tabs.
6591 *
6592 * Placed by the surface (docked in fullscreen, else above the prompt) and
6593 * keyed by the person (ctrl+x tab, Esc), who closes it from the engine's mark
6594 * or ctrl+x x: `ui.close` with origin `person`, which a hook may refuse.
6595 */
6596 Pane: {
6597 /**
6598 * Its tab's label while more than one pane is open (with one, the engine
6599 * draws no title): the `title` it was opened with, or its id.
6600 *
6601 * A click on a tab, or Tab onto it and Enter, shows that pane. Read-only
6602 * here; another `$.ui.open` (or a hook on `ui.open`) retitles.
6603 */
6604 title: string;
6605 /**
6606 * True while the person has given the pane the keyboard. Read-only.
6607 */
6608 isFocused: boolean;
6609 /**
6610 * Cells across the body, inside the frame. Read-only.
6611 */
6612 bodyColumns: number;
6613 /**
6614 * Where the surface seated the pane: `dock` beside the transcript (the
6615 * terminal in fullscreen from 110 columns), or `inline` above the prompt.
6616 *
6617 * Read-only: a rewrite carries it on as received; one that changes or
6618 * drops it is refused, the hook that passed it failing.
6619 */
6620 placement: 'dock' | 'inline';
6621 /**
6622 * The body's window over the tree: engine-owned, moved by the person's
6623 * keys while the pane is focused. Read-only.
6624 */
6625 scroll: SiteScroll;
6626 /**
6627 * Which transcript is on screen beside the pane: the main conversation's
6628 * (no `agentId`) or one agent's, opened from the tasks list.
6629 *
6630 * The pane stays open across a switch, one instance re-rendered for the
6631 * view, so a hook draws for the agent in view. Read-only: a rewrite carries
6632 * it on as received; one that changes or drops it is refused.
6633 */
6634 view: SiteView;
6635 };
6636 };
6637
6638 /**
6639 * What a `ui.render` hook returns and what `next(e)` resolves to: a
6640 * RenderElement tree, the same for every component.
6641 */
6642 export type RenderResultOf = {
6643 [C in RenderComponent]: RenderElement;
6644 };
6645
6646 /**
6647 * Where a render event's component is drawn: `terminal` is Ink, which draws
6648 * the hook's whole tree; the rest are remote surfaces drawing it themselves.
6649 *
6650 * `desktop` is Claude Code Desktop, `mobile` the Claude mobile app, `vscode`
6651 * Claude Code for VS Code. A remote surface asks over the wire (ui_render),
6652 * draws with the props the hook handed core, and draws the tree where it has
6653 * a slot for it.
6654 *
6655 * Each surface's ask is its own evaluation, since a tree may hold an element
6656 * only some surfaces draw (Svg, Client).
6657 */
6658 export type RenderSurface = 'terminal' | 'desktop' | 'mobile' | 'vscode';
6659
6660 /**
6661 * The size of what a surface draws into, in character cells of the
6662 * surface's monospace metric, and whether its layout docks a pane.
6663 *
6664 * On the terminal, the conversation's columns and screen rows; on a remote
6665 * surface, the pane's width and height over the advance and line height of
6666 * its code font. Cell-based until the first element lays out in pixels.
6667 */
6668 export type RenderViewport = {
6669 /**
6670 * Cells across. A tree wider than this wraps or truncates, as its Text
6671 * props say.
6672 */
6673 columns: number;
6674 /**
6675 * Cells down the whole surface, not the room left for this component.
6676 *
6677 * Informational: a change of height alone re-draws nothing and keys no
6678 * new evaluation, so a hook reads it as of the last width or props change.
6679 */
6680 rows: number;
6681 /**
6682 * Whether this surface docks a pane beside the transcript, so a pane a
6683 * plugin opens unasked is a sidebar, not a takeover; absent is unknown.
6684 *
6685 * What `command.run`'s `presentation.isFullscreen` says. The terminal always
6686 * says: `true` fullscreen, `false` on the main screen, fixed per session; a
6687 * remote surface once its client reports it with the size, absent before.
6688 *
6689 * @remarks The desktop and VS Code report it once they place panes; the
6690 * mobile app, which has no dock, `false`. A change re-draws the sites.
6691 * @example if (e.viewport?.isFullscreen === true) void $.ui.open({ id })
6692 */
6693 isFullscreen?: boolean;
6694 };
6695
6696 /**
6697 * The input of `ui.resolve`: which surface's elements, for which component;
6698 * a union with one member per surface (ResolveInputOf).
6699 *
6700 * Resolved when the plugins load, ahead of any drawing, so it names the
6701 * surface and the component and not the props; a `ui.render` argument is
6702 * one (it carries both), which is what `$.ui.resolve(e)` takes.
6703 */
6704 export type ResolveInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = P extends RenderSurface ? ResolveInputOf<C, P> : never;
6705
6706 /**
6707 * One `ui.resolve` input, for a component on one surface.
6708 */
6709 export type ResolveInputOf<C extends RenderComponent, P extends RenderSurface> = {
6710 /**
6711 * Where the table draws; one literal per member, so a hook that narrows
6712 * it narrows the table `next(e)` resolves to.
6713 */
6714 surface: P;
6715 /**
6716 * Which drawing the table is resolved for; the key a matcher narrows on.
6717 */
6718 component: C;
6719 };
6720
6721 /**
6722 * What each event's hook returns, and what its `next(e)` resolves to, by event
6723 * name.
6724 */
6725 export type ResultOf = EngineResultOf & ClassicResultOf & {
6726 [N in OpEventName]: OpEventResult<N>;
6727 } & {
6728 [N in NounEventName]: NounEventResult<N>;
6729 };
6730
6731 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';
6732
6733 /**
6734 * The members of `T` assignable to `S`; all of `T` when none is.
6735 */
6736 type Select<T, S> = [Extract<T, S>] extends [never] ? T : Extract<T, S>;
6737
6738 /**
6739 * The events a pattern selects, as a union of names: the one named, every
6740 * one under a glob's namespace, or every one a negation does not exclude.
6741 */
6742 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>;
6743
6744 /**
6745 * The literal each tag key of `I` is held to by matcher `M`: one-of arrays
6746 * flattened, RegExps widened to `unknown`.
6747 */
6748 type Selection<I, M> = {
6749 [K in keyof M & TagKeys<I>]: Literal<M[K] extends readonly (infer One)[] ? One : M[K]>;
6750 };
6751
6752 /**
6753 * One option of a `Select`: the value `onSelect` and `ui.select` carry, and
6754 * the text drawn for it (the value when absent).
6755 */
6756 export type SelectOption = {
6757 value: string;
6758 label?: string;
6759 };
6760
6761 /**
6762 * The props of `Select`, every surface's one-of-several picker: an address,
6763 * a label, the options, the one selected, the closure a pick runs. A leaf.
6764 *
6765 * Focused through the same ring as `Button` (`abovePrompt:focus`); keys reach
6766 * it only while it has focus (arrows move, Enter picks) and Esc always
6767 * returns to the prompt; a pick raises `ui.select`, its bottom `onSelect`.
6768 */
6769 export type SelectProps = {
6770 /**
6771 * The element's address: `e.element` at `ui.select`, what a matcher names.
6772 */
6773 key: string;
6774 /**
6775 * Text drawn before the current value.
6776 */
6777 label?: string;
6778 /**
6779 * What can be picked, in the order drawn; at least one, values unique.
6780 */
6781 options: readonly SelectOption[];
6782 /**
6783 * Which option is selected when drawn; the person's pick replaces it
6784 * until the hook draws another.
6785 */
6786 value?: string;
6787 /**
6788 * The site's focus ring starts here when the site takes the keyboard,
6789 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
6790 *
6791 * A pane opened with `focus`, or the person's focus chord or click, is the
6792 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
6793 * origin this plugin. A ring the person has moved stays where it was put.
6794 */
6795 autoFocus?: true;
6796 /**
6797 * Runs on a pick with the option's value, in the plugin's own environment:
6798 * the bottom of a `ui.select` chain. No model turn unless it asks one.
6799 */
6800 onSelect: (value: string, e: UiSelectArgument) => void;
6801 };
6802
6803 /**
6804 * The input of `session.attach`: a surface joined the session's roster of
6805 * attached clients (a phone opened the session; the desktop app connected).
6806 *
6807 * A remote client attaches by saying so (ui_attach) or by its first ask to
6808 * draw; the terminal's attachment is the REPL's binding and raises nothing.
6809 * Every field is the engine's: a hook observes, `next(e)` passes them on.
6810 */
6811 export type SessionAttachInput = {
6812 /**
6813 * Where the client draws: what it declared, a rendering fact.
6814 */
6815 surface: RenderSurface;
6816 /**
6817 * The client's own id, unique in the roster; two phones are two clients on
6818 * one surface. A client that never named itself is `<surface>:default`.
6819 */
6820 clientId: string;
6821 /**
6822 * The size the client draws into, in character cells, when it said.
6823 */
6824 viewport?: RenderViewport;
6825 };
6826
6827 /**
6828 * What a `session.attach` hook returns and what `next(e)` resolves to:
6829 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
6830 */
6831 export type SessionAttachResult = {
6832 clientId: string;
6833 };
6834
6835 /**
6836 * What `$.session.authorize()` answers: an opaque handle for the session's
6837 * Anthropic credential and its kind, or null when there is none to hold.
6838 *
6839 * The secret itself stays with the engine; the handle is its plugin-side
6840 * face, spent through `$.http.fetch(url, { auth: handle })`.
6841 */
6842 export type SessionAuthorization = {
6843 handle: string;
6844 kind: 'bearer' | 'api-key';
6845 } | null;
6846
6847 /**
6848 * `session.compact`'s input as a plugin's `$.session.compact(args)` takes
6849 * it: `trigger` (`plugin`), `messages` and `agentId` are the engine's.
6850 */
6851 export type SessionCompactArgs = {
6852 /**
6853 * What the summary should keep or stress, as typed after `/compact`;
6854 * absent, the engine's own compaction prompt alone.
6855 */
6856 instructions?: string;
6857 };
6858
6859 /**
6860 * A compaction that stands: the conversation as it reads afterwards, and
6861 * the token counts the engine recorded when it was the one compacting.
6862 */
6863 export type SessionCompacted = {
6864 /**
6865 * The conversation after the compaction, oldest first: from core, its
6866 * summary and the messages it kept; from a hook, whatever it hands up.
6867 *
6868 * What the transcript becomes (kept, on `precompute`, for the compaction
6869 * that comes). A message with the engine's `handle` stands as the engine
6870 * has it; one without is built from its `role`, `text` and tool blocks.
6871 */
6872 messages: readonly SessionMessage[];
6873 /**
6874 * The conversation's size before, in tokens; absent when core did not
6875 * record it.
6876 */
6877 tokensBefore?: number;
6878 /**
6879 * Its size afterwards, in tokens; absent on `precompute` and when core
6880 * did not record it.
6881 */
6882 tokensAfter?: number;
6883 skip?: undefined;
6884 };
6885
6886 /**
6887 * The input of `session.compact`: one compaction of the conversation, about
6888 * to run; `messages` is the transcript it runs over.
6889 */
6890 export type SessionCompactInput = {
6891 /**
6892 * What is compacting (SessionCompactTrigger); the key a matcher narrows
6893 * on. Pinned: `next(e)` passes it on as received.
6894 */
6895 trigger: SessionCompactTrigger;
6896 /**
6897 * The id of the loop compacting, for a subagent's or a fork's own
6898 * transcript; absent for the main conversation (tool.call's `agentId`).
6899 *
6900 * Pinned: left out of a rewrite it is put back, changed it fails the hook.
6901 * `$.session.messages()` is the main conversation whatever this names.
6902 */
6903 agentId?: string;
6904 /**
6905 * What the summary should keep or stress: the text after `/compact`, a
6906 * plugin's, or absent.
6907 *
6908 * `next({ ...e, instructions })` changes what the summarizer is told.
6909 */
6910 instructions?: string;
6911 /**
6912 * The transcript being compacted, in `$.session.messages()`'s shape, each
6913 * message carrying the engine's `handle`; a subagent's own under `agentId`.
6914 *
6915 * `next({ ...e, messages })` changes what is summarized: a message kept
6916 * with its handle is the engine's own, whole; one without is read as built.
6917 */
6918 messages: readonly SessionMessage[];
6919 };
6920
6921 /**
6922 * What a `session.compact` hook returns and what `next(e)` resolves to: the
6923 * compaction (`{ messages, tokensBefore?, tokensAfter? }`) or `{ skip }`.
6924 *
6925 * There is no summary string: the summary is a message.
6926 */
6927 export type SessionCompactResult = SessionCompacted | SessionCompactSkipped;
6928
6929 /**
6930 * A compaction vetoed: on `precompute` nothing is computed or kept; on any
6931 * other trigger the conversation stays as it is and one line says why.
6932 *
6933 * Core answers it too, when a classic PreCompact hook blocks.
6934 */
6935 export type SessionCompactSkipped = {
6936 /**
6937 * Why, as the notice reads.
6938 */
6939 skip: string;
6940 messages?: undefined;
6941 };
6942
6943 /**
6944 * Who compacts: the person's `/compact` (`manual`), the engine at its
6945 * threshold or on a prompt too long (`auto`), a plugin, or a `precompute`.
6946 *
6947 * `precompute` is the one dispatch that installs nothing: its result is kept
6948 * for the compaction that comes, if the conversation it ran over still leads.
6949 */
6950 export type SessionCompactTrigger = 'manual' | 'auto' | 'plugin' | 'precompute';
6951
6952 /**
6953 * The context window broken down as /context breaks it down: the rows, the
6954 * grid and the lists beneath it, in the SDK's `get_context_usage` shape.
6955 *
6956 * Less that reply's internal-build sections. Token counts are the engine's
6957 * estimates as numbers, never formatted: a `full` breakdown counts with the
6958 * token-count API where it can, a `summary` one estimates throughout.
6959 */
6960 export type SessionContextBreakdown = {
6961 /**
6962 * One row per category, the free space and the compaction buffer among
6963 * them; `kind` says which is which.
6964 */
6965 categories: ContextCategory[];
6966 /**
6967 * Tokens in use, unclamped: past `rawMaxTokens` when over the window.
6968 */
6969 totalTokens: number;
6970 /**
6971 * The window measured against, the same figure as `rawMaxTokens`.
6972 */
6973 maxTokens: number;
6974 /**
6975 * The window measured against, in tokens: the model's limit, or a smaller
6976 * compaction window (`autocompactSource` says which).
6977 */
6978 rawMaxTokens: number;
6979 /**
6980 * How that window was settled (ContextWindowSource); the SDK's reply
6981 * carries it under this name too, outside its typed schema.
6982 */
6983 autocompactSource: ContextWindowSource;
6984 /**
6985 * `totalTokens` over `rawMaxTokens` as a whole percentage, 0 to 100 and
6986 * past it when over.
6987 */
6988 percentage: number;
6989 /**
6990 * The grid, row by row: 10 by 10, 20 by 10 for a window of a million or
6991 * more, 5 wide when asked for under 80 `columns`.
6992 */
6993 gridRows: ContextGridSquare[][];
6994 /**
6995 * Which model the breakdown was computed for, as `/model` shows it.
6996 */
6997 model: string;
6998 /**
6999 * Each memory file in the context, with its path and tokens.
7000 */
7001 memoryFiles: ContextMemoryFile[];
7002 /**
7003 * Each MCP tool's schema, with its server and tokens.
7004 */
7005 mcpTools: ContextMcpTool[];
7006 /**
7007 * The custom agents the Agent tool describes, each with its tokens.
7008 */
7009 agents: ContextAgent[];
7010 /**
7011 * The slash-command listing, counted; absent when the session lists none.
7012 */
7013 slashCommands?: ContextSlashCommands;
7014 /**
7015 * The skill listing, counted, with one entry per skill; absent when the
7016 * session lists none.
7017 */
7018 skills?: ContextSkills;
7019 /**
7020 * The token count at which auto-compaction runs; absent when it is off.
7021 */
7022 autoCompactThreshold?: number;
7023 /**
7024 * Whether auto-compaction is on for the session.
7025 */
7026 isAutoCompactEnabled: boolean;
7027 /**
7028 * The last response's own token counts, or null before one came back.
7029 */
7030 apiUsage: ContextApiUsage | null;
7031 };
7032
7033 /**
7034 * The live context window as the status line reads it, and by category as
7035 * /context breaks it down when the call asked (`{ breakdown }`).
7036 *
7037 * `tokens` and `percent` are the last API response's input side against the
7038 * model's window, absent until the first response of the live window: a
7039 * fresh session, or one just compacted, until its next response.
7040 */
7041 export type SessionContextUsage = {
7042 /**
7043 * Input tokens the last response was answered over: uncached, cache-written
7044 * and cache-read together (the status line's `total_input_tokens`).
7045 */
7046 tokens?: number;
7047 /**
7048 * The context window of the session's model, in tokens (the status line's
7049 * `context_window_size`).
7050 */
7051 window: number;
7052 /**
7053 * `tokens` over `window` as a whole percentage, 0 to 100 (the status
7054 * line's `used_percentage`).
7055 */
7056 percent?: number;
7057 /**
7058 * The window by category, as /context breaks it down: present only when
7059 * the call passed `breakdown`, and only with a session bound.
7060 *
7061 * It measures against the compaction window (`rawMaxTokens`), which may be
7062 * smaller than `window`, and estimates every category, so its
7063 * `totalTokens` need not equal `tokens`.
7064 */
7065 breakdown?: SessionContextBreakdown;
7066 };
7067
7068 /**
7069 * What the session has cost, as `/cost` and the status line total it.
7070 */
7071 export type SessionCost = {
7072 /**
7073 * US dollars, summed over every priced API response this session.
7074 */
7075 usd: number;
7076 };
7077
7078 type SessionCronSummary = {
7079 id: string;
7080 /**
7081 * Cron expression, e.g. "0 9 * * 1-5".
7082 */
7083 schedule: string;
7084 /**
7085 * False for one-shot wakeups whose cron field encodes a single fire time; true for tasks that re-fire on every match.
7086 */
7087 recurring: boolean;
7088 /**
7089 * Prompt text submitted when the cron fires. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
7090 */
7091 prompt: string;
7092 };
7093
7094 /**
7095 * The input of `session.detach`: a client left the session's roster. Every
7096 * field is the engine's: a hook observes, and `next(e)` passes them on.
7097 */
7098 export type SessionDetachInput = {
7099 /**
7100 * Where the client drew.
7101 */
7102 surface: RenderSurface;
7103 /**
7104 * The id it attached under.
7105 */
7106 clientId: string;
7107 /**
7108 * Why it left: it detached, or the session ended under it.
7109 */
7110 reason: SessionDetachReason;
7111 };
7112
7113 /**
7114 * Why a client left the roster: `detach`, it said so (ui_detach); `end`, the
7115 * session ended with it still attached.
7116 */
7117 export type SessionDetachReason = 'detach' | 'end';
7118
7119 /**
7120 * What a `session.detach` hook returns and what `next(e)` resolves to:
7121 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
7122 */
7123 export type SessionDetachResult = {
7124 clientId: string;
7125 };
7126
7127 type SessionEndHookInput = BaseHookInput & {
7128 hook_event_name: 'SessionEnd';
7129 reason: ExitReason;
7130 };
7131
7132 /**
7133 * One message of the transcript as `$.session.messages()` returns it.
7134 */
7135 export type SessionMessage = {
7136 /**
7137 * Who wrote it.
7138 */
7139 role: 'user' | 'assistant';
7140 /**
7141 * Its text blocks joined; '' when it has none.
7142 */
7143 text: string;
7144 /**
7145 * The tool_use blocks of an assistant message, each with its outcome
7146 * (`result`, `text`, `isError`) once the transcript holds it.
7147 */
7148 toolUses: ToolUseSummary[];
7149 /**
7150 * The tool_result blocks of a user message: `{ tool_use_id, text, isError,
7151 * result }`.
7152 */
7153 toolResults?: ToolResultSummary[];
7154 /**
7155 * An opaque token the engine stamps on a message it hands a
7156 * `session.compact` hook, so a list handed back maps to its own messages.
7157 *
7158 * Absent on `$.session.messages()` and on a message a hook built.
7159 */
7160 handle?: string;
7161 };
7162
7163 /**
7164 * One rate-limit window as the rate-limit notices read it.
7165 */
7166 export type SessionRateLimit = {
7167 /**
7168 * Which window: `five_hour`, `seven_day`, or a Claude gateway's
7169 * `spend_limit`.
7170 */
7171 kind: string;
7172 /**
7173 * How much of the window is used, 0 to 100 (above 100 once a spend limit
7174 * is exceeded).
7175 */
7176 percentUsed: number;
7177 /**
7178 * When the window resets, as an ISO 8601 timestamp.
7179 */
7180 resetsAt?: string;
7181 };
7182
7183 /**
7184 * An external-event wake the delivery's text parsed as (a GitHub relay
7185 * event, a signal's notice): the envelope's attributes and its JSON body.
7186 */
7187 export type SessionReceiveEvent = {
7188 /**
7189 * The producing service (`github`).
7190 */
7191 source: string;
7192 /**
7193 * The event's discriminator (`pull_request.closed`, `check_suite`).
7194 */
7195 kind: string;
7196 /**
7197 * The envelope's JSON body (`{ pr: "acme/app#12", outcome: "merged" }`).
7198 */
7199 data: Record<string, unknown>;
7200 /**
7201 * The `data` keys whose values are free text a third party wrote (a
7202 * commenter's `author` and `comment`), as the producer marked them.
7203 *
7204 * Empty when none; the server asserts every other key's value, not these.
7205 */
7206 untrustedKeys: readonly string[];
7207 };
7208
7209 /**
7210 * The input of `session.receive`: one inbound delivery (a relay's event, a
7211 * peer's message, a Remote Control prompt), sanitized, before it is queued.
7212 */
7213 export type SessionReceiveInput = {
7214 /**
7215 * Where the delivery came from, as the bridge classified it; the key a
7216 * matcher narrows on. `next(e)` passes it on as received.
7217 */
7218 origin: SessionReceiveOrigin;
7219 /**
7220 * The delivery's body as the model would read it (a content-block
7221 * delivery's text blocks, joined).
7222 */
7223 text: string;
7224 /**
7225 * The external-event wake the text parsed as (`source` `github` for a
7226 * subscribed pull request's event); passed on as received.
7227 *
7228 * Present only for a delivery the server itself rendered as a wake (a
7229 * webhook relay, the session inbox), by its asserted origin; anyone else's
7230 * wake-shaped text stays `text`. Its `untrustedKeys` name third-party text.
7231 */
7232 event?: SessionReceiveEvent;
7233 };
7234
7235 /**
7236 * Where an inbound delivery came from, as the bridge classified it from the
7237 * server's stamps: `prompt.submit`'s `e.origin`, less what never arrives.
7238 */
7239 export type SessionReceiveOrigin = {
7240 /**
7241 * `bridge` the user's own from a Remote Control client; `peer` another
7242 * session; `unclassified` one the bridge could not place.
7243 *
7244 * `task-notification` a relay's event (a GitHub webhook) or a trigger;
7245 * `scheduled-trigger` a routine; `peer-send-message` another session's
7246 * SendMessage; `projects-relay` and `slack-ping` as at `prompt.submit`.
7247 */
7248 kind: 'bridge' | 'task-notification' | 'scheduled-trigger' | 'peer' | 'peer-send-message' | 'projects-relay' | 'slack-ping' | 'unclassified';
7249 };
7250
7251 /**
7252 * What a `session.receive` hook returns and what `next(e)` resolves to: the
7253 * delivery that was queued, `{ text }`, or `{ consumed: reason }`.
7254 *
7255 * `next(e)` resolves once the delivery is queued; a hook answering without
7256 * `next` queues nothing.
7257 */
7258 export type SessionReceiveResult = {
7259 /**
7260 * The body the delivery was queued with; from core, `e.text` as it
7261 * arrived at the bottom.
7262 *
7263 * A rewrite passes it down, `next({ ...e, text })`.
7264 */
7265 text: string;
7266 consumed?: undefined;
7267 } | {
7268 /**
7269 * Takes the delivery, answered without `next`: it is not queued, not
7270 * written to the transcript and never reaches the model.
7271 *
7272 * The reason is logged, the plugin named.
7273 */
7274 consumed: string;
7275 text?: undefined;
7276 };
7277
7278 /**
7279 * What `$.session.repo()` answers: the repository's root and its origin remote,
7280 * when the session is in one.
7281 */
7282 export type SessionRepo = {
7283 /**
7284 * The repository's root, absolute: the main working tree's for a worktree.
7285 */
7286 root: string;
7287 /**
7288 * The `origin` remote's URL as git has it (push URL preferred), or null when
7289 * the repository has none.
7290 */
7291 remote: string | null;
7292 /**
7293 * Whether the remote is one of the repositories this build treats as its
7294 * own; false in a build that has none or when the remote is unrecognized.
7295 *
7296 * The engine matches the build's own list of repositories with its
7297 * hardened remote parser. A plugin reads this to behave differently in a
7298 * public repository; which repositories are the build's is its to say.
7299 */
7300 internal: boolean;
7301 /**
7302 * The repository the allowlist matched, as `owner/name`; null when
7303 * `internal` is false.
7304 *
7305 * A working copy without a remote that the engine still recognises is
7306 * named by its own checkout configuration; a remote's name is its path.
7307 */
7308 name: string | null;
7309 };
7310
7311 type SessionStartHookInput = BaseHookInput & {
7312 hook_event_name: 'SessionStart';
7313 source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork';
7314 agent_type?: string;
7315 model?: string;
7316 session_title?: string;
7317 /**
7318 * resume/fork: seconds since the resumed transcript's last assistant response
7319 */
7320 seconds_since_last_response?: number;
7321 /**
7322 * 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)
7323 */
7324 context_tokens?: number;
7325 /**
7326 * resume/fork: seconds_since_last_response exceeds the prompt-cache TTL, so the first request re-caches context_tokens
7327 */
7328 prompt_cache_likely_expired?: boolean;
7329 /**
7330 * resume/fork: estimated cost of re-caching context_tokens on the session model - the managed modelPricing when set, otherwise list price; excludes the response
7331 */
7332 estimated_cache_write_usd?: number;
7333 };
7334
7335 /**
7336 * The input of `session.start`: the session the process starts with, read the
7337 * way `$.session` reads it at that moment.
7338 */
7339 export type SessionStartInput = {
7340 /**
7341 * The directory the session runs in, absolute (`$.session.cwd()`).
7342 */
7343 cwd: string;
7344 /**
7345 * Where the session draws at start (`$.session.surfaces()[0]`): `terminal`
7346 * under the REPL; null for a `-p` run or the SDK, which draw nowhere yet.
7347 */
7348 surface: RenderSurface | null;
7349 /**
7350 * Whether a person is at the prompt: true under the REPL, false for a `-p`
7351 * run or the SDK.
7352 */
7353 isInteractive: boolean;
7354 };
7355
7356 /**
7357 * What a `session.start` hook returns and what `next(e)` resolves to:
7358 * `{ cwd }`, echoed by core; a hook's own value does not change the session.
7359 */
7360 export type SessionStartResult = {
7361 cwd: string;
7362 };
7363
7364 /**
7365 * What `$.session.usage()` answers: the context window's fill, the account's
7366 * rate-limit windows and the session's cost, as the status line has them.
7367 *
7368 * A figure the engine does not have is left out, never zeroed: `rateLimits`
7369 * is empty off a subscription, `cost` absent where the host keeps no ledger.
7370 */
7371 export type SessionUsage = {
7372 /**
7373 * The live context window: the status line's `context_window` figures.
7374 */
7375 context: SessionContextUsage;
7376 /**
7377 * The rate-limit windows the last API response reported (`five_hour`,
7378 * `seven_day`, a gateway's `spend_limit`); empty when none has a reading.
7379 */
7380 rateLimits: SessionRateLimit[];
7381 /**
7382 * What the session has cost so far, as /cost totals it; absent only where
7383 * the host keeps no cost ledger (the CLI always has one).
7384 */
7385 cost?: SessionCost;
7386 };
7387
7388 /**
7389 * What `$.session.usage(args)` takes: nothing for the status line's figures
7390 * alone; `breakdown` to have the window broken down as /context breaks it.
7391 */
7392 export type SessionUsageArgs = {
7393 /**
7394 * Asks for `context.breakdown` and says how it is counted
7395 * (ContextBreakdownDetail); absent, none is computed and the call is free.
7396 *
7397 * `full` sends one token-count request per tool and memory file, as
7398 * /context does; `summary` estimates locally and sends none.
7399 */
7400 breakdown?: ContextBreakdownDetail;
7401 /**
7402 * The width the breakdown's grid will be drawn in, in terminal columns;
7403 * absent, the full-width grid. Read only with `breakdown`.
7404 *
7405 * Under 80 the grid is the narrow one /context draws there, 5 wide. A thin
7406 * client's breakdown is the remote workspace's, whose grid ignores this.
7407 */
7408 columns?: number;
7409 };
7410
7411 /**
7412 * What `$.settings.read` answers: an object keyed as a settings.json is
7413 * (`permissions`, `env`, `hooks`, `model`, `enabledPlugins`, ...).
7414 *
7415 * Each key is as https://code.claude.com/docs/en/settings documents it and
7416 * https://json.schemastore.org/claude-code-settings.json types it. A
7417 * snapshot in plain data: a write to it changes nothing the engine reads.
7418 */
7419 export type Settings = Readonly<Record<string, unknown>>;
7420
7421 /**
7422 * What `$.settings.read(args)` takes.
7423 */
7424 export type SettingsReadArgs = {
7425 /**
7426 * The one source read, as loaded; absent, the settings merged over every
7427 * source, as the engine runs under them.
7428 */
7429 source?: SettingsSource;
7430 };
7431
7432 /**
7433 * One source of settings by the name a plugin gives it, lowest precedence
7434 * first; the engine's own name is the same word with `Settings` appended.
7435 *
7436 * `user` is ~/.claude/settings.json, `project` .claude/settings.json,
7437 * `local` .claude/settings.local.json, `flag` what `--settings` and the
7438 * SDK's inline settings carry, and `policy` the managed settings, every
7439 * managed tier merged.
7440 */
7441 export type SettingsSource = 'user' | 'project' | 'local' | 'flag' | 'policy';
7442
7443 type SetupHookInput = BaseHookInput & {
7444 hook_event_name: 'Setup';
7445 trigger: 'init' | 'maintenance';
7446 };
7447
7448 /**
7449 * Where a site's window sits over the tree a hook drew in it (a pane's body,
7450 * the band): the engine's to move (the person scrolls), the plugin's to read.
7451 */
7452 export type SiteScroll = {
7453 /**
7454 * The first row of the tree the window shows; 0 at the top. Read-only.
7455 */
7456 offset: number;
7457 /**
7458 * How many rows of the tree the window shows at once: the rows the
7459 * surface gave the body. Read-only.
7460 */
7461 bodyRows: number;
7462 };
7463
7464 /**
7465 * Which transcript the person has on screen where a site draws: the main
7466 * conversation's, or one agent's, opened from the tasks list.
7467 *
7468 * The person's to switch, the plugin's to read: a switch re-runs the site's
7469 * hooks with the new view, the site itself staying where it is.
7470 */
7471 export type SiteView = {
7472 /**
7473 * The agent whose transcript is in view: the `id` `$.agent.list()` gives
7474 * it, the `agentId` its `turn.step` and `tool.call` events carry.
7475 *
7476 * Absent while the main conversation is in view. Read-only.
7477 */
7478 agentId?: string;
7479 };
7480
7481 /**
7482 * The input of `skill.prompt`: one skill's prompt, at the moment the engine
7483 * expanded it for the model.
7484 *
7485 * Typed as `/name`, called through the Skill tool, or preloaded into a
7486 * subagent: the same event at each.
7487 */
7488 export type SkillPromptInput = {
7489 /**
7490 * Which skill (`commit`); the key a matcher narrows on.
7491 */
7492 skill: string;
7493 /**
7494 * The prompt's text as the skill computed it (its text blocks, joined).
7495 */
7496 text: string;
7497 };
7498
7499 /**
7500 * What a `skill.prompt` hook returns: the text the model reads for that
7501 * skill.
7502 */
7503 export type SkillPromptResult = {
7504 text: string;
7505 };
7506
7507 /**
7508 * Options of `$.clock.sleep`.
7509 */
7510 export type SleepOptions = {
7511 /**
7512 * Aborting it rejects the sleep at once.
7513 */
7514 signal?: AbortSignal;
7515 };
7516
7517 /**
7518 * Options of `$.audio.speak`.
7519 */
7520 export type SpeakOptions = {
7521 /**
7522 * The system voice's exact name as the platform lists it (`Samantha`, or the
7523 * name of a voice you installed). Absent: the synthesizer's default voice.
7524 */
7525 voice?: string;
7526 };
7527
7528 /**
7529 * The argument of `$.audio.speak(text, options)` as the event carries it.
7530 */
7531 type SpeakRequest = SpeakOptions & {
7532 /**
7533 * What to say, as plain text, of at most 4096 characters.
7534 */
7535 text: string;
7536 };
7537
7538 /**
7539 * What `$.audio.speak` resolves with once the utterance has ended.
7540 */
7541 export type SpeakResult = {
7542 /**
7543 * Which synthesizer spoke: `system`, the platform's own (`say` on macOS).
7544 */
7545 via: 'system';
7546 };
7547
7548 /**
7549 * `next` in a `*` hook: the set of events is open at runtime, so `e` is
7550 * `unknown` until `next.is(pattern, e)` narrows it to events it knows.
7551 *
7552 * The callable is an overload per known event (OrderedOverloads), then
7553 * `(e: unknown) => Promise<unknown>` last: `next(e)` with `e` still unknown
7554 * resolves to `unknown`.
7555 */
7556 export type StarNext = OrderedOverloads<EventName> & {
7557 (e: unknown): Promise<unknown>;
7558 /**
7559 * Continues this dispatch at a tier, as Next's `to` (a managed hook's):
7560 * `e` still unknown resolves to `unknown`.
7561 */
7562 readonly to: (e: unknown, tier: TargetTier) => Promise<unknown>;
7563 readonly signal: AbortSignal;
7564 readonly is: <M extends Pattern>(pattern: M, e: unknown) => e is Frozen<Args<Selected<M>>>;
7565 readonly event: EventName;
7566 readonly origin: Origin;
7567 readonly trace: readonly TraceEntry<EventName, unknown, unknown>[];
7568 };
7569
7570 type StopFailureHookInput = BaseHookInput & {
7571 hook_event_name: 'StopFailure';
7572 error: SDKAssistantMessageError;
7573 error_details?: string;
7574 last_assistant_message?: string;
7575 };
7576
7577 type StopHookInput = BaseHookInput & {
7578 hook_event_name: 'Stop';
7579 stop_hook_active: boolean;
7580 /**
7581 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
7582 */
7583 last_assistant_message?: string;
7584 /**
7585 * 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.
7586 */
7587 background_tasks?: BackgroundTaskSummary[];
7588 /**
7589 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
7590 */
7591 session_crons?: SessionCronSummary[];
7592 };
7593
7594 /**
7595 * The hook a streaming event takes: `async function* ($, e, next) {}`,
7596 * yielding the event's chunks and returning its result.
7597 *
7598 * `return yield* next(e)` passes; `for await (const c of next(e)) yield
7599 * f(c)` transforms; yielding without `next` answers alone. A chunk yielded
7600 * stays: a hook that fails mid-stream is left, the rest from beneath it.
7601 *
7602 * @example on('turn.step', async function* ($, e, next) {
7603 * const r = yield* next(e); return { ...r } })
7604 */
7605 export type StreamHook<N extends StreamingEventName> = ($: EngineInterface, e: Frozen<Args<N>>, next: StreamNext<N>) => StreamHookBody<Chunk<N>, EventResult<N>>;
7606
7607 /**
7608 * What a hook on a streaming event evaluates to: the async generator an
7609 * `async function*` makes, yielding `C` and returning `R` or nothing.
7610 *
7611 * Returning nothing lets its last `next(e)`'s result stand. A plain
7612 * function is a type error here even when it returns `next(e)`: the hook
7613 * is the generator, not a function that hands one back.
7614 */
7615 export type StreamHookBody<C, R> = AsyncGenerator<C, R | void> & {
7616 /**
7617 * Absent on a generator; present on `next(e)`, which is not a hook body.
7618 */
7619 readonly result?: never;
7620 };
7621
7622 /**
7623 * The events that stream: their hooks are async generators, `next(e)` is
7624 * the stream of everything beneath, and the result is what it returns.
7625 *
7626 * `turn.step` alone: the model's response arrives in pieces, and a hook
7627 * that saw it whole could not change what had already been shown.
7628 */
7629 export type StreamingEventName = 'turn.step';
7630
7631 /**
7632 * The rest of the chain as a hook on a streaming event receives it: Next,
7633 * except that `next(e)` is the stream beneath (HookStream), not a promise.
7634 *
7635 * Each call opens a fresh stream; for `turn.step` each is a model request,
7636 * so a hook that calls it twice makes two. Not calling it yields the hook's
7637 * own chunks and returns its own result, and nothing beneath runs.
7638 *
7639 * @template S what `next.is(pattern, e)` narrows `e` to, as Next's
7640 */
7641 export type StreamNext<N extends StreamingEventName = StreamingEventName, E = Args<N>, O = NextResult<N>, S extends {
7642 [K in N]?: unknown;
7643 } = {
7644 [K in N]: Args<K>;
7645 }> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin'> & {
7646 (e: E): HookStream<Chunk<N>, O>;
7647 /**
7648 * Continues this dispatch at a tier, as Next's `to`: the stream beneath
7649 * with the links between this hook's tier and that one skipped.
7650 */
7651 readonly to: (e: E, tier: TargetTier) => HookStream<Chunk<N>, O>;
7652 /**
7653 * What settled beneath on the latest `next()` stream, as Next's; a
7654 * streaming link's entry counts the chunks it yielded up (`chunks`).
7655 */
7656 readonly trace: readonly TraceEntry<N, E, O>[];
7657 };
7658
7659 /**
7660 * The shape a `Box` and a `Text` share in a render tree: allowlisted props,
7661 * an optional `hover`, the group stamp a `hover.scope` earns, and children.
7662 *
7663 * `Tag` is which of the two; `Hover` is that element's hover props. Every
7664 * surface draws both: Ink's Box and Text on the terminal, a flex div and a
7665 * styled span on the desktop.
7666 */
7667 type StyledElement<Tag extends 'Box' | 'Text', Hover> = {
7668 type: Tag;
7669 /**
7670 * A Box's layout, margin, padding and border props and the `key` that
7671 * makes it a hover scope; a Text's colors and styles. Others are refused.
7672 */
7673 props?: Record<string, string | number | boolean>;
7674 /**
7675 * Style overrides the surface applies while the pointer is over the
7676 * nearest keyed Box, or over any member of the group `scope` names.
7677 *
7678 * Plain data, no hook. Never a layout change: `borderStyle` restyles a
7679 * border the Box has, `display` only reveals a Box drawn `"none"` inside
7680 * a keyed Box, and never in a scope.
7681 */
7682 hover?: Hover;
7683 /**
7684 * Whose group `hover.scope` names; absent without a `scope`.
7685 */
7686 group?: PluginStamp;
7687 /**
7688 * In order: a Box holds elements and strings (core wraps each string in
7689 * a Text); a Text holds strings and inline elements, never an engine node.
7690 */
7691 children?: RenderNode[];
7692 };
7693
7694 type SubagentStartHookInput = BaseHookInput & {
7695 hook_event_name: 'SubagentStart';
7696 agent_id: string;
7697 agent_type: string;
7698 };
7699
7700 type SubagentStopHookInput = BaseHookInput & {
7701 hook_event_name: 'SubagentStop';
7702 stop_hook_active: boolean;
7703 agent_id: string;
7704 agent_transcript_path: string;
7705 agent_type: string;
7706 /**
7707 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
7708 */
7709 last_assistant_message?: string;
7710 /**
7711 * 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.
7712 */
7713 background_tasks?: BackgroundTaskSummary[];
7714 /**
7715 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
7716 */
7717 session_crons?: SessionCronSummary[];
7718 };
7719
7720 /**
7721 * The props of `Svg`, the remote surfaces' vector leaf: the markup is the
7722 * element's data, as a string is a Text's, drawn isolated.
7723 *
7724 * A leaf: no children. The surface never lets the markup reach the page
7725 * (the engine bounds it; the desktop and the editor draw it as an image, or
7726 * in a sandboxed frame when `isInteractive`; the mobile app in a web view).
7727 */
7728 export type SvgProps = {
7729 /**
7730 * The SVG document, `<svg ...>...</svg>`, at most 131072 characters.
7731 */
7732 source: string;
7733 /**
7734 * What the drawing says, for a reader that cannot see it; required, since
7735 * a surface without the element draws nothing else of it.
7736 */
7737 alt: string;
7738 /**
7739 * CSS pixels; absent, the box takes the markup's own width up to the slot.
7740 */
7741 width?: number;
7742 /**
7743 * CSS pixels; absent, the markup's own height at the drawn width.
7744 */
7745 height?: number;
7746 /**
7747 * `true` draws the SVG in a script-less sandboxed frame so hover, CSS
7748 * `:hover`, SMIL animation and `<title>` tooltips work; absent, an image.
7749 *
7750 * It never enables script or event-handler attributes (the frame has no
7751 * allow-scripts and the scrub strips them); presses that other plugins
7752 * should observe go on an enclosing element.
7753 */
7754 isInteractive?: boolean;
7755 };
7756
7757 /**
7758 * The keys of `I` a matcher may select variants by: literal-valued in every
7759 * variant, and one literal per variant (IsDiscriminant).
7760 */
7761 type TagKeys<I> = {
7762 [K in MatcherKeys<I>]: IsLiteralValued<MatcherValueOf<I, K>> extends true ? IsDiscriminant<I, K> extends true ? K : never : never;
7763 }[MatcherKeys<I>];
7764
7765 /**
7766 * A tier `next.to(e, tier)` may name: one a floor can reach past a tier of
7767 * less authority to, so never `prepend` or `user`, which nothing skips to.
7768 */
7769 export type TargetTier = Exclude<Tier, 'prepend' | 'user'>;
7770
7771 type TaskCompletedHookInput = BaseHookInput & {
7772 hook_event_name: 'TaskCompleted';
7773 task_id: string;
7774 task_subject: string;
7775 task_description?: string;
7776 teammate_name?: string;
7777 /**
7778 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
7779 */
7780 team_name?: string;
7781 };
7782
7783 type TaskCreatedHookInput = BaseHookInput & {
7784 hook_event_name: 'TaskCreated';
7785 task_id: string;
7786 task_subject: string;
7787 task_description?: string;
7788 teammate_name?: string;
7789 /**
7790 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
7791 */
7792 team_name?: string;
7793 };
7794
7795 type TeammateIdleHookInput = BaseHookInput & {
7796 hook_event_name: 'TeammateIdle';
7797 teammate_name: string;
7798 /**
7799 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
7800 */
7801 team_name: string;
7802 };
7803
7804 /**
7805 * The `Text` props a `hover` may override (its colors and styles, not its
7806 * wrapping) and `scope`, the hover group it joins; a `Button`'s label too.
7807 */
7808 export type TextHoverProps = {
7809 /**
7810 * Names a hover group of this plugin's: every element it draws with the
7811 * same `scope`, in any site on the surface, lights while any is hovered.
7812 *
7813 * Another plugin's elements under the same string are a different group.
7814 * One to 64 characters, no control characters; no keyed Box needed. On the
7815 * terminal a Text nested in a Text follows its group but cannot heat it.
7816 */
7817 scope?: string;
7818 color?: string;
7819 backgroundColor?: string;
7820 dimColor?: boolean;
7821 bold?: boolean;
7822 italic?: boolean;
7823 underline?: boolean;
7824 strikethrough?: boolean;
7825 inverse?: boolean;
7826 };
7827
7828 /**
7829 * The props of `Text`: the color and style props of Ink's Text a tree may
7830 * set. Colors are a theme key or a raw color.
7831 */
7832 export type TextProps = {
7833 /**
7834 * Style overrides applied by the surface while the pointer is over the
7835 * nearest enclosing keyed `Box`, or, given a `scope`, over its group.
7836 *
7837 * No hook runs and nothing crosses to the plugin. Refused outside a keyed
7838 * Box unless it names a `scope`.
7839 */
7840 hover?: TextHoverProps;
7841 color?: string;
7842 backgroundColor?: string;
7843 dimColor?: boolean;
7844 bold?: boolean;
7845 italic?: boolean;
7846 underline?: boolean;
7847 strikethrough?: boolean;
7848 inverse?: boolean;
7849 wrap?: 'wrap' | 'end' | 'middle' | 'truncate' | 'truncate-start' | 'truncate-middle' | 'truncate-end';
7850 };
7851
7852 /**
7853 * One of the chain's five tiers (TIERS), outermost first; on every
7854 * `next.trace` entry, and what `next.to(e, tier)` names.
7855 *
7856 * `prepend` and `append` are the managed plugins an administrator lists,
7857 * `user` everything a person installs, `builtin` the plugins bundled in the
7858 * binary, `core` the engine's innermost link.
7859 */
7860 export type Tier = (typeof TIERS)[number];
7861
7862 /**
7863 * The chain's five tiers, outermost first: earlier is outer is more
7864 * authority, and same-event hooks nest in this order and no other way.
7865 *
7866 * The managed plugins an administrator prepends, everything a person
7867 * installs, the managed plugins appended, the plugins bundled in the binary,
7868 * the engine's innermost link; a built-in's `$` calls still raise everywhere.
7869 */
7870 const TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
7871
7872 /**
7873 * A pending timer from `$.clock.after` / `$.clock.every`.
7874 */
7875 export type Timer = {
7876 /**
7877 * Stops it; a stopped timer never fires again.
7878 */
7879 cancel: () => void;
7880 };
7881
7882 /**
7883 * A timer on `$.clock` (`after`, `every`): `fn` runs after `ms` milliseconds,
7884 * once or until `cancel()`.
7885 */
7886 export type TimerCall = (ms: number, fn: () => void) => Timer;
7887
7888 /**
7889 * Options of `$.ui.toast`.
7890 */
7891 export type ToastOptions = {
7892 /**
7893 * How long the line stays, in milliseconds; default 4000.
7894 */
7895 timeoutMs?: number;
7896 };
7897
7898 /**
7899 * `tool.call`'s input as the call takes it: `tool_use_id` and `agentId` may
7900 * ride along (a hook passing its event's input on) and are dropped.
7901 *
7902 * The run gets its own id and runs in the session's loop.
7903 */
7904 export type ToolCallArgs = ToolCallEnvelope extends infer I ? I extends ToolCallEnvelope ? Omit<I, 'tool_use_id'> & ToolCallReserved<I['tool']> : never : never;
7905
7906 /**
7907 * The envelope the two tool events share: the tool, the id of this call, and
7908 * the tool's arguments spread beside them (`e.command` for Bash).
7909 *
7910 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
7911 * is a string and a rewrite is checked against Bash's schema. The `e` of
7912 * `classic.PreToolUse` exactly; `tool.call`'s adds the loop (ToolCallInput).
7913 */
7914 export type ToolCallEnvelope = BuiltinToolCallInput | McpToolCallInput;
7915
7916 /**
7917 * The input of `tool.call`: the tool, the id of this call, the tool's
7918 * arguments beside them (`e.command` for Bash), and `agentId` in a subagent.
7919 *
7920 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
7921 * is a string and a rewrite is checked against Bash's schema. `tool`,
7922 * `tool_use_id` and `agentId` are reserved: a rewrite of any is refused.
7923 */
7924 export type ToolCallInput = ToolCallEnvelope & AgentLoop;
7925
7926 /**
7927 * `$.tool.call(input)`: resolves with `result` typed for the tool `input`
7928 * names (ToolCallResult), or loosely for an input that names none literally.
7929 */
7930 type ToolCallOverloads = {
7931 <T extends string>(input: ToolCallArgs & ToolNamed<T>): Promise<ToolCallResult<T>>;
7932 (input: ToolCallArgs): Promise<ToolCallResult>;
7933 };
7934
7935 /**
7936 * The keys `tool.call`'s input carries beside the tool's own arguments, none
7937 * of which the tool sees (the engine strips them before the tool runs).
7938 *
7939 * `consent` is the person's own words for the press that raised the call
7940 * (`The user pressed "1: Yes" on ...`): the run's context carries it as a human
7941 * turn, which the permission path reads as the user's request.
7942 */
7943 export type ToolCallReserved<T> = {
7944 tool: T;
7945 tool_use_id?: string;
7946 consent?: string;
7947 };
7948
7949 /**
7950 * What a `tool.call` hook returns and what `next(e)` and `$.tool.call(input)`
7951 * resolve to: the tool's result (`{ result, context? }`) or `{ deny }`.
7952 *
7953 * From core the result is `{ ref, result, text }` or, when the tool reported
7954 * an error, `{ ref, result, text, isError }`; `ref` names core's messages.
7955 *
7956 * @template Name the tool the call went to, typing `result` per built-in
7957 * tool (BuiltinToolResults) once `e.tool` is narrowed; else `unknown`
7958 */
7959 export type ToolCallResult<Name extends string = string> = {
7960 /**
7961 * Refuses the call: the model receives the text as an error result.
7962 * Absent when the call was answered.
7963 */
7964 deny: string;
7965 result?: undefined;
7966 context?: undefined;
7967 ref?: undefined;
7968 text?: undefined;
7969 isError?: undefined;
7970 } | {
7971 /**
7972 * The tool's output: from core the tool's record, typed per built-in
7973 * tool once `e.tool` and `isError` are narrowed; from a hook, its own.
7974 *
7975 * Core validates a hook's answer against the tool's output schema when
7976 * it has one, maps it for the model with the tool's own mapper, and
7977 * records it in the transcript as the tool's result. Absent on a deny.
7978 */
7979 result: ToolResultOf<Name>;
7980 /**
7981 * What the model reads after the tool's result and the user never
7982 * sees. From core, none.
7983 *
7984 * One newline-joined reminder, as a PostToolUse hook's additional
7985 * context is, after the managed tier's review of it; none on a plugin's
7986 * own `$.tool.call`. Kept whole from `next`; capped at 32000 characters.
7987 */
7988 context?: readonly string[];
7989 /**
7990 * Set by core on what `next(e)` resolves to: names the messages core
7991 * produced for the call (they stay on the host side).
7992 *
7993 * A hook that returns the object it got makes core use them verbatim.
7994 * Absent on a hook's own `{ result }` and on a deny.
7995 */
7996 ref?: number;
7997 /**
7998 * Set by core: the result as the model reads it (text blocks joined),
7999 * present whatever the tool, where `result`'s shape varies per tool.
8000 *
8001 * Absent on a hook's own `{ result }`.
8002 */
8003 text?: string;
8004 isError?: undefined;
8005 deny?: undefined;
8006 } | {
8007 /**
8008 * Set by core, present only when the tool reported an error (it threw,
8009 * was interrupted, or answered an error): `text` is what the model read.
8010 */
8011 isError: true;
8012 /**
8013 * What the transcript stored for the errored call: the error text, or
8014 * undefined when nothing was stored; never the tool's typed record.
8015 */
8016 result: unknown;
8017 /**
8018 * The error as the model reads it.
8019 */
8020 text?: string;
8021 /**
8022 * As on an answered result: names the messages core produced.
8023 */
8024 ref?: number;
8025 /**
8026 * As on an answered result.
8027 */
8028 context?: readonly string[];
8029 deny?: undefined;
8030 };
8031
8032 /**
8033 * `tool.check`'s input as `$.tool.check` takes it: the tool and its
8034 * arguments; `tool_use_id` is the engine's to set, never a query's.
8035 */
8036 type ToolCheckArgs = Pick<ToolCheckInput, 'tool' | 'input'>;
8037
8038 /**
8039 * The verdict of `tool.check`: run the tool, put it to the mode's decider
8040 * (the dialog, the auto-mode classifier, a headless host), or refuse it.
8041 */
8042 type ToolCheckDecision = 'allow' | 'ask' | 'deny';
8043
8044 /**
8045 * The input of `tool.check`: the tool, its arguments, and the call's id when
8046 * the engine is deciding a real call.
8047 *
8048 * All three are the question's identity and are pinned: a hook decides
8049 * about this call, it does not change it (`tool.call` rewrites a call).
8050 */
8051 type ToolCheckInput = {
8052 /**
8053 * As the model names it (`Bash`, `mcp__server__tool`); the key a matcher
8054 * narrows on.
8055 */
8056 tool: string;
8057 /**
8058 * The tool's arguments as the permission decision reads them
8059 * (`{ command }` for Bash, `{ file_path, ... }` for the file tools).
8060 */
8061 input: unknown;
8062 /**
8063 * The call being decided, on a real call only; absent on a query.
8064 *
8065 * `next.origin` names who raised it: `{ plugin: 'engine', tier: 'core' }`
8066 * for the model's own call, the plugin for its `$.tool.call` or its query.
8067 */
8068 tool_use_id?: string;
8069 };
8070
8071 /**
8072 * What a `tool.check` hook returns and what `next(e)` resolves to: the
8073 * verdict, why, and the settings rule behind it when one decided.
8074 *
8075 * From core, the engine's declarative decision for the session's mode and
8076 * rules. A hook may answer any verdict in either direction; the last word up
8077 * the chain is the decision.
8078 */
8079 type ToolCheckResult = {
8080 /**
8081 * `allow` runs the tool; `ask` puts it to the mode's decider; `deny`
8082 * refuses it, the reason the model's error.
8083 */
8084 decision: ToolCheckDecision;
8085 /**
8086 * Why, in a sentence: from core the rule or check that decided; from a
8087 * hook, what the model reads on a deny and the dialog shows on an ask.
8088 */
8089 reason?: string;
8090 /**
8091 * The settings rule that decided, as written (`Bash(git push:*)`).
8092 *
8093 * Absent for a mode or a tool's own check.
8094 */
8095 rule?: string;
8096 };
8097
8098 /**
8099 * The input of `tool.describe`: one tool's description, at the moment the
8100 * engine first renders the tool's schema for the model.
8101 */
8102 export type ToolDescribeInput = {
8103 /**
8104 * As the model sees the name (`Bash`, `mcp__server__tool`); the key a
8105 * matcher narrows on.
8106 */
8107 tool: string;
8108 /**
8109 * The tool's description as it computed it.
8110 */
8111 description: string;
8112 /**
8113 * Who provides this tool: the plugin and its tier; `{ plugin: "engine",
8114 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
8115 *
8116 * A configured MCP server's tool is `mcp:<server>`, in `prepend` when the
8117 * policy settings source configures the server, else `user`.
8118 */
8119 provider: Origin;
8120 };
8121
8122 /**
8123 * What a `tool.describe` hook returns: the description the model sees for that
8124 * tool.
8125 */
8126 export type ToolDescribeResult = {
8127 description: string;
8128 };
8129
8130 /**
8131 * `{ tool, tool_use_id, ...args }` as one flat object type, generic over
8132 * the tool name and its parsed arguments.
8133 */
8134 type ToolEnvelope<Name, Arguments> = {
8135 /**
8136 * The name of the tool being called (`Bash`, `mcp__<server>__<tool>`);
8137 * comparing it narrows `e`. Reserved: a rewrite of it is ignored by core.
8138 */
8139 tool: Name;
8140 /**
8141 * The tool_use block's id: the same at every event of the call and in
8142 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
8143 */
8144 tool_use_id: string;
8145 } & Arguments;
8146
8147 /**
8148 * One tool call of a ToolGroup, as `ui.render` sees it under `calls`.
8149 */
8150 export type ToolGroupCall = {
8151 /**
8152 * The id `tool.call` carried for this call (`e.tool_use_id` there), so a
8153 * hook that saw the call finds its row in the group. Read-only.
8154 *
8155 * Absent on a desktop host that predates it.
8156 */
8157 tool_use_id?: string;
8158 /**
8159 * Which one the call ran (`Bash`, `Read`, `Grep`, ...).
8160 */
8161 tool: string;
8162 /**
8163 * The call's input, as the model sent it.
8164 */
8165 input: unknown;
8166 /**
8167 * True while the call is still running.
8168 */
8169 isRunning: boolean;
8170 /**
8171 * True when the call ended in an error.
8172 */
8173 isErrored: boolean;
8174 /**
8175 * True when an abort ended the call, as on `ToolUse`.
8176 */
8177 isInterrupted: boolean;
8178 /**
8179 * As on `ToolUse`; undefined while the call runs.
8180 */
8181 output?: unknown;
8182 };
8183
8184 /**
8185 * One tool as `$.tool.list()` returns it.
8186 */
8187 export type ToolInfo = {
8188 /**
8189 * What the model calls it by.
8190 */
8191 name: string;
8192 /**
8193 * What it does, in the tool's own words (its description; a first sentence at
8194 * most for MCP tools without one).
8195 */
8196 description: string;
8197 /**
8198 * True for an MCP server's tool.
8199 */
8200 mcp: boolean;
8201 };
8202
8203 /**
8204 * `{ tool, tool_use_id, ...args }` as one flat object type.
8205 *
8206 * The docs of `tool` and `tool_use_id` live on the `keyof` operand: a mapped
8207 * type takes its properties' docs from there.
8208 */
8209 export type ToolInputOf<Name extends string, Arguments> = {
8210 [K in keyof ToolEnvelope<Name, Arguments>]: ToolEnvelope<Name, Arguments>[K];
8211 };
8212
8213 /**
8214 * An input that names its tool as the literal `T`: what `next` and
8215 * `$.tool.call` read to type the call's result per tool (NextResultFor).
8216 */
8217 type ToolNamed<T extends string> = {
8218 /**
8219 * The name of the tool being called (`Bash`).
8220 */
8221 readonly tool: T;
8222 };
8223
8224 /**
8225 * The structured result of the tool named `Name`: its BuiltinToolResults
8226 * entry for a built-in tool, else `unknown`.
8227 *
8228 * Agent's is its entry or an AgentCallRecord (what a plugin-raised call
8229 * answers). `unknown` covers an MCP tool, a name the results table lacks
8230 * (one merged into the inputs table alone too), and `Name` left at `string`.
8231 */
8232 export type ToolResultOf<Name extends string> = string extends Name ? unknown : Name extends keyof BuiltinToolResults & string ? BuiltinToolResults[Name] | (Name extends 'Agent' ? AgentCallRecord : never) : unknown;
8233
8234 /**
8235 * One tool_result block of a user message.
8236 */
8237 export type ToolResultSummary = {
8238 /**
8239 * The id of the call this result answers (`tool.call`'s `e.tool_use_id`).
8240 */
8241 tool_use_id: string;
8242 /**
8243 * The result as the model read it (text blocks joined).
8244 */
8245 text: string;
8246 /**
8247 * True when the tool reported an error.
8248 */
8249 isError: boolean;
8250 /**
8251 * What the transcript stored for the call: the tool's record on an answered
8252 * one (`tool.call`'s `result`), the error text when `isError`.
8253 *
8254 * Absent when nothing was stored. Headless (`-p`), a tool may store the
8255 * record less its bulk (Bash blanks `stdout`); `text` is what the model
8256 * read either way.
8257 */
8258 result?: unknown;
8259 };
8260
8261 /**
8262 * What `$.tool.register` takes.
8263 */
8264 export type ToolSpec = {
8265 /**
8266 * The tool's short name (letters, digits, `_`, `-`; up to 64); the model
8267 * calls it as `mcp__<plugin>__<name>`.
8268 */
8269 name: string;
8270 /**
8271 * What the tool does, for the model.
8272 */
8273 description: string;
8274 /**
8275 * A JSON schema object for the input (`{ type: "object", properties,
8276 * required }`); default `{ type: "object" }`.
8277 */
8278 inputSchema?: Record<string, unknown>;
8279 };
8280
8281 /**
8282 * One tool_use block of an assistant message, with its outcome once the
8283 * transcript holds the call's tool_result (paired by `tool_use_id`).
8284 */
8285 export type ToolUseSummary = {
8286 /**
8287 * The call's id, as `tool.call` carried it (`e.tool_use_id` there).
8288 */
8289 tool_use_id: string;
8290 /**
8291 * Which one was called (`Read`, `Bash`, `mcp__server__tool`), as
8292 * `tool.call` named it (`e.tool` there).
8293 */
8294 tool: string;
8295 /**
8296 * The arguments the model gave it.
8297 */
8298 input: Record<string, unknown>;
8299 /**
8300 * What the transcript stored for the call: the tool's record on an answered
8301 * one (`tool.call`'s `result`), the error text on a refused or errored one.
8302 *
8303 * Absent while the call is in flight or when nothing was stored. Headless
8304 * (`-p`), a tool may store the record less its bulk (Bash blanks `stdout`);
8305 * `text` holds either way.
8306 */
8307 result?: unknown;
8308 /**
8309 * The result as the model read it; absent while the call is in flight.
8310 */
8311 text?: string;
8312 /**
8313 * Present only when the tool reported an error, as on `tool.call`'s result.
8314 */
8315 isError?: true;
8316 };
8317
8318 /**
8319 * One settled run of a link beneath the caller, as `next.trace` lists it:
8320 * data, not a handle.
8321 *
8322 * `received` and `returned` are the live references where the hook runs
8323 * beside the chain; in a hooks module its own copies, as `e` is.
8324 */
8325 export type TraceEntry<N extends EventName = EventName, E = Args<N>, O = NextResult<N>> = {
8326 /**
8327 * The link's place in the chain, 0 the outermost.
8328 */
8329 readonly index: number;
8330 /**
8331 * The hook's plugin; `"engine"` for the engine's own core or bottom.
8332 */
8333 readonly plugin: string;
8334 /**
8335 * The link's tier (Tier); `"core"` for the engine's own core or bottom.
8336 */
8337 readonly tier: Tier;
8338 readonly event: N;
8339 readonly outcome: TraceOutcome;
8340 /**
8341 * Why the link was skipped without running, when it was: `bypassed by
8342 * <plugin>`, whose `next.to` went beneath this tier. Absent when it ran.
8343 */
8344 readonly reason?: string;
8345 /**
8346 * Its own wall time, its `next()` calls' time in flight taken out.
8347 *
8348 * The engine entry's is everything beneath the last hook: in a hooks
8349 * module, the host round trip.
8350 */
8351 readonly ms: number;
8352 /**
8353 * How many chunks the link yielded up, on a streaming event; absent on
8354 * every other. A link left mid-stream counts what it yielded before.
8355 */
8356 readonly chunks?: number;
8357 readonly received: E;
8358 /**
8359 * What the link settled on; undefined when it was skipped or rejected.
8360 */
8361 readonly returned: O | undefined;
8362 };
8363
8364 /**
8365 * What the chain decided for one link, as `next.trace` names it.
8366 *
8367 * `returned`: its result stood; `passed`: it returned, by reference, what its
8368 * last `next()` resolved to (a hooks module's hook answers with a copy of its
8369 * own, so it reads `returned`); `skipped`: it failed before `next`, or a
8370 * `next.to` above continued beneath its tier (`reason` says which), and
8371 * beneath ran in its place; `kept`: it failed after `next`, and that run's
8372 * result stands; `expired`: its budget ran out (what stands follows
8373 * skipped/kept); `caught`: it threw or its budget ran out, and its `.catch`
8374 * handler's result stands; `rejected`: the link rejected; the deepest such
8375 * entry is where the rejection came from, and the ones above it let it pass.
8376 */
8377 export type TraceOutcome = 'caught' | 'expired' | 'kept' | 'passed' | 'rejected' | 'returned' | 'skipped';
8378
8379 /**
8380 * What every `turn.complete` carries whatever its reason: the answer, the
8381 * duration, the interrupt flag, the turn's id, its loop and what it cost.
8382 */
8383 type TurnCompleteFields = {
8384 /**
8385 * The assistant's final visible text this turn ("" if none, e.g.
8386 * thinking-only).
8387 */
8388 answer: string;
8389 /**
8390 * Wall-clock length of the turn in milliseconds.
8391 */
8392 durationMs: number;
8393 /**
8394 * True when the turn ended by interruption (`reason === 'aborted'`).
8395 */
8396 isAborted: boolean;
8397 /**
8398 * The turn's id, the same one its `turn.start` and every `turn.step`
8399 * carried; a subagent's run raises no `turn.start`, its steps carry it.
8400 */
8401 turnId: string;
8402 /**
8403 * The loop the turn ran in: a subagent's id, as `$.agent.spawn` resolves
8404 * it, each run of its loop one turn; absent on the main loop.
8405 *
8406 * Pinned: a different value is refused, one left out is kept. Every hook
8407 * sees a subagent's turn, so a hook that spawns sees its children's turns
8408 * too and bounds itself.
8409 */
8410 agentId?: string;
8411 /**
8412 * What the turn cost: its responses' token counts summed and the model of
8413 * the last, read off the API responses the engine already holds.
8414 *
8415 * Absent when the turn got no response (interrupted before one, an API
8416 * error).
8417 */
8418 usage?: TurnUsage;
8419 };
8420
8421 /**
8422 * The input of `turn.complete`: the assistant's final message of a turn, at
8423 * the moment the turn ends (where the turn's duration is reported).
8424 *
8425 * `reason` says why it ended; `refusal` exists on a refusal alone.
8426 */
8427 export type TurnCompleteInput = TurnCompleteFields & (TurnCompleteRefused | TurnCompleteUnrefused);
8428
8429 /**
8430 * Why a turn ended: the model answered, the user interrupted it, the model
8431 * refused with no fallback model to retry on, or an API error ended it.
8432 */
8433 export type TurnCompleteReason = 'answer' | 'aborted' | 'refusal' | 'error';
8434
8435 /**
8436 * The end of a turn the model refused with no fallback model to retry on:
8437 * what the API said of the refusal rides along.
8438 */
8439 type TurnCompleteRefused = {
8440 reason: 'refusal';
8441 refusal: TurnRefusal;
8442 };
8443
8444 /**
8445 * What a `turn.complete` hook returns and what `next(e)` resolves to:
8446 * `{ text }`; a text other than a main-loop answer's is shown beneath it.
8447 *
8448 * Core fills `usage` from `e.usage` when the turn had one; a hook above reads
8449 * it, and one that answers its own may leave it out.
8450 */
8451 export type TurnCompleteResult = {
8452 text: string;
8453 usage?: TurnUsage;
8454 };
8455
8456 /**
8457 * The end of a turn that was not a refusal: answered, interrupted, or dead
8458 * on an API error (retries exhausted, the context limit), nothing more.
8459 */
8460 type TurnCompleteUnrefused = {
8461 reason: Exclude<TurnCompleteReason, 'refusal'>;
8462 };
8463
8464 /**
8465 * What the API said about a refusal that ended a turn: the classifier's
8466 * category and its explanation, each null when the API sent none.
8467 */
8468 export type TurnRefusal = {
8469 category: string | null;
8470 explanation: string | null;
8471 };
8472
8473 /**
8474 * The input of `turn.start`: the prompt a model turn begins with, after
8475 * `prompt.submit` settled the text and the UserPromptSubmit settings hooks ran.
8476 */
8477 export type TurnStartInput = {
8478 /**
8479 * The user's text as the turn proceeds with it ("" for a turn started without
8480 * a typed prompt, e.g. a continuation).
8481 */
8482 text: string;
8483 /**
8484 * The turn's id, minted here; the same one every `turn.step` and the
8485 * `turn.complete` of this turn carry.
8486 */
8487 turnId: string;
8488 };
8489
8490 /**
8491 * What a `turn.start` hook returns and what `next(e)` resolves to:
8492 * `{ turnId }`, echoed by core; a hook's own value does not change the turn.
8493 */
8494 export type TurnStartResult = {
8495 turnId: string;
8496 };
8497
8498 /**
8499 * One piece of a `turn.step` response as it streams through the chain:
8500 * what a hook's `next(e)` yields and what the hook yields up in turn.
8501 *
8502 * Text, thinking, a tool call's start and arguments, and the stop are
8503 * plain data a hook reads and rewrites; `engine` is the rest, passed on
8504 * unread. What leaves the outermost hook is what is shown and recorded.
8505 */
8506 export type TurnStepChunk = TurnStepTextChunk | TurnStepThinkingChunk | TurnStepToolChunk | TurnStepInputChunk | TurnStepStopChunk | TurnStepEngineChunk;
8507
8508 /**
8509 * An item of the engine's stream the other chunk kinds do not model (the
8510 * envelope, a block's start and end, a retry marker), opaque by `ref`.
8511 *
8512 * Pass it on where it came. A hook that yields its own response has none
8513 * to yield, and the engine supplies what the response needs around the
8514 * chunks it does yield.
8515 */
8516 export type TurnStepEngineChunk = {
8517 kind: 'engine';
8518 /**
8519 * The engine's handle on the item; opaque, this step's only.
8520 */
8521 ref: number;
8522 };
8523
8524 /**
8525 * The input of `turn.step`: one model request inside a turn, at the moment
8526 * the engine is about to send it; the bottom of the chain sends it.
8527 *
8528 * The transcript is not on it: `messageCount` says how many messages the
8529 * request carries, and `$.session.messages()` reads them. A hook rewrites
8530 * `model` or `effort` going down; the rest is pinned.
8531 */
8532 export type TurnStepInput = {
8533 /**
8534 * The turn this step belongs to (`turn.start`'s id; inside a subagent's
8535 * loop, the id the run's `turn.complete` will carry). Pinned.
8536 */
8537 turnId: string;
8538 /**
8539 * The step's position in the turn, from 0. Pinned.
8540 */
8541 index: number;
8542 /**
8543 * Which model the request names, as the engine resolved it for this step
8544 * (the session's, a fallback's). `next({ ...e, model })` names another.
8545 */
8546 model: string;
8547 /**
8548 * How hard the request asks the model to think: the session's setting or
8549 * the model's default, absent for a model without effort; rewritable.
8550 */
8551 effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number;
8552 /**
8553 * How many messages the request carries (the conversation so far, the
8554 * turn's tool results included). Pinned: the messages are the engine's.
8555 */
8556 messageCount: number;
8557 /**
8558 * The loop the request is made in: a subagent's id, the `id`
8559 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
8560 *
8561 * Pinned: a different value is refused, one left out is kept. A subagent
8562 * a hook spawned through `$.agent.spawn` steps past that hook, as its tool
8563 * calls do; every other hook sees its steps.
8564 */
8565 agentId?: string;
8566 };
8567
8568 /**
8569 * A piece of a tool call's arguments as they arrive: JSON text, partial,
8570 * for the `tool` chunk of the same `index`.
8571 *
8572 * The arguments the tool runs with are the pieces concatenated and parsed
8573 * once the block ends; pieces that do not parse leave the call without
8574 * arguments it can run on, as a model that wrote broken JSON would.
8575 */
8576 export type TurnStepInputChunk = ChunkRef & {
8577 kind: 'input';
8578 index: number;
8579 /**
8580 * The next piece of the arguments' JSON text.
8581 */
8582 json: string;
8583 };
8584
8585 /**
8586 * What a `turn.step` hook returns and what `next(e)` resolves to: the
8587 * model's response to the step's request, once its blocks are all in.
8588 *
8589 * From the bottom, the response the engine streamed; a hook's own value
8590 * changes what the hooks above it read, never what the engine streamed.
8591 */
8592 export type TurnStepResult = {
8593 /**
8594 * The turn this step belongs to, as received.
8595 */
8596 turnId: string;
8597 /**
8598 * The step's position in the turn, as received.
8599 */
8600 index: number;
8601 /**
8602 * The visible text of the response ("" when it only called tools, only
8603 * thought, or no request was made).
8604 */
8605 answer: string;
8606 /**
8607 * The tool calls the response made, in order; empty for a text-only step.
8608 */
8609 toolUses: readonly TurnStepToolUse[];
8610 /**
8611 * Why the model stopped; null when no response arrived (the request
8612 * failed or was interrupted before a message, or no request was made).
8613 */
8614 stopReason: TurnStopReason;
8615 /**
8616 * What the request cost as the API reported it, and the model that
8617 * answered; null when no response arrived or it carried no usage.
8618 */
8619 usage: TurnUsage | null;
8620 };
8621
8622 /**
8623 * The response is whole: why the model stopped and what the request cost,
8624 * as the step's result will carry them. The last chunk of one response.
8625 */
8626 export type TurnStepStopChunk = ChunkRef & {
8627 kind: 'stop';
8628 stopReason: TurnStopReason;
8629 usage: TurnUsage | null;
8630 };
8631
8632 /**
8633 * A piece of the response's visible text as it arrives, in block `index`.
8634 *
8635 * The text the person watches stream and the text the transcript records
8636 * are both the concatenation of these, in order, per block: a hook that
8637 * rewrites them rewrites both, one that drops them all drops the block.
8638 */
8639 export type TurnStepTextChunk = ChunkRef & {
8640 kind: 'text';
8641 /**
8642 * The content block the piece belongs to, from 0 within one response.
8643 */
8644 index: number;
8645 text: string;
8646 };
8647
8648 /**
8649 * A piece of the model's thinking as it arrives, in block `index`: what
8650 * the person sees of it live.
8651 *
8652 * The thinking block the transcript keeps is the one the model signed, as
8653 * the engine received it; thinking a hook streams without the engine's
8654 * block behind it is shown and not recorded.
8655 */
8656 export type TurnStepThinkingChunk = ChunkRef & {
8657 kind: 'thinking';
8658 index: number;
8659 text: string;
8660 };
8661
8662 /**
8663 * The model begins a tool call in block `index`: the tool's name and the
8664 * call's id; its arguments follow as `input` chunks of the same index.
8665 *
8666 * A block whose `tool` chunk never comes out of the chain is no tool call:
8667 * the engine records none and runs none.
8668 */
8669 export type TurnStepToolChunk = ChunkRef & {
8670 kind: 'tool';
8671 index: number;
8672 /**
8673 * The call's `tool_use_id`.
8674 */
8675 id: string;
8676 /**
8677 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
8678 */
8679 name: string;
8680 };
8681
8682 /**
8683 * One tool call the model asked for in a step: the tool's name and its
8684 * arguments.
8685 */
8686 export type TurnStepToolUse = {
8687 /**
8688 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
8689 */
8690 name: string;
8691 /**
8692 * The arguments the model gave it, as the tool schema shapes them.
8693 */
8694 input: unknown;
8695 };
8696
8697 /**
8698 * Why the model stopped, as a `turn.step` result and its stop chunk carry
8699 * it: one of the API's stop reasons, or null when no response arrived.
8700 */
8701 type TurnStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'compaction' | 'refusal' | 'model_context_window_exceeded' | null;
8702
8703 /**
8704 * What a model turn, or one response inside it, cost as the API reported it:
8705 * the four token counts (`$.model.fork`'s usage shape) and the model's id.
8706 *
8707 * A turn's counts are its responses' summed; its model is the last response's.
8708 */
8709 export type TurnUsage = ModelForkUsage & {
8710 /**
8711 * Which model answered, by the id the API reports.
8712 */
8713 model: string;
8714 };
8715
8716 /**
8717 * What a plugin's `$.ui.blit(args)` takes: which of its mounted Rasters to
8718 * repaint, in which of its sites, and the cells to paint it with.
8719 *
8720 * The Raster is one this plugin's own `ui.render` hook drew, still mounted;
8721 * `columns` and `rows`, when given, must be the mounted size (a resize is a
8722 * redraw, `$.ui.invalidate("ui.render")`, not a blit).
8723 */
8724 export type UiBlitArgs = {
8725 /**
8726 * The site the Raster is drawn in, by the `requestId` this plugin draws
8727 * it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
8728 */
8729 requestId: string;
8730 /**
8731 * The Raster's `key` in that drawing.
8732 */
8733 key: string;
8734 /**
8735 * The new cells, encoded as the element's `cells` are (RasterProps), for
8736 * the mounted `columns * rows`.
8737 */
8738 cells: string;
8739 /**
8740 * The width the cells are laid out for; refused unless it is the mounted
8741 * Raster's. Absent, the mounted width.
8742 */
8743 columns?: number;
8744 /**
8745 * The height the cells are laid out for; refused unless it is the mounted
8746 * Raster's. Absent, the mounted height.
8747 */
8748 rows?: number;
8749 };
8750
8751 /**
8752 * What `$.ui.blit` resolves to and what a `ui.blit` hook's `{ value }`
8753 * holds: `{}` once the cells are the Raster's next frame, or why not.
8754 */
8755 export type UiBlitResult = {
8756 /**
8757 * Absent when the cells were taken; else why not: nothing of this plugin's
8758 * is mounted there, the size is not the mounted one, the cells are bad.
8759 *
8760 * Another plugin's Raster under the same site and key reads as not this
8761 * plugin's; a cell that does not decode is named by its index.
8762 */
8763 deny?: string;
8764 };
8765
8766 /**
8767 * What a plugin's `$.ui.focus(args)` takes: one of its own elements, by the
8768 * `key` it drew it under, in one of its sites that holds the keyboard now.
8769 *
8770 * The engine resolves it to that site's ring and raises `ui.focus` under
8771 * the plugin's origin; the keyboard is the person's to give, so a site that
8772 * does not hold it, or holds it on another plugin's element, is `{ deny }`.
8773 */
8774 export type UiFocusArgs = {
8775 /**
8776 * The site, by the `requestId` this plugin draws it under: one of its
8777 * panes' ids, or the band's.
8778 */
8779 requestId: string;
8780 /**
8781 * The element's `key`: a `Button`, `Input` or `Select` this plugin drew in
8782 * that site; of several under one key, the first in document order.
8783 */
8784 key: string;
8785 };
8786
8787 /**
8788 * The render components whose site keeps a focus ring: a pane's body and
8789 * the band above the prompt, each a ring over the elements hooks drew there.
8790 */
8791 export type UiFocusComponent = 'Pane' | 'AbovePrompt';
8792
8793 /**
8794 * The input of `ui.focus`: a site's focus ring about to move onto one of the
8795 * elements a hook drew in it (a `Button`, `Input` or `Select`), or off them.
8796 *
8797 * Every key but `element` is the engine's word, pinned: `next(e)` passes
8798 * them on, a rewrite that leaves one out keeps it, one that changes it fails
8799 * the hook. `element` is the hook's to rewrite; the ring has not moved yet.
8800 */
8801 export type UiFocusInput = {
8802 /**
8803 * Which site: a `Pane` body or the `AbovePrompt` band.
8804 */
8805 component: UiFocusComponent;
8806 /**
8807 * The instance the `ui.render` hook drawing the site sees: the pane's id,
8808 * or the band's one id.
8809 */
8810 requestId: string;
8811 /**
8812 * Whose `ui.render` hook drew the element taking the ring; absent with
8813 * `element`. Read-only.
8814 */
8815 plugin?: string;
8816 /**
8817 * The `key` of the element taking the ring, as `ui.press` names it; absent
8818 * for one of the engine's own stops (a pane's close mark or another's tab).
8819 *
8820 * `next({ ...e, element })` lands it on another element `plugin` drew in
8821 * the site instead; one not drawn there is core's `{ deny }`.
8822 */
8823 element?: string;
8824 /**
8825 * Who moves it (UiFocusOrigin), set by the engine where the move starts.
8826 */
8827 origin: UiFocusOrigin;
8828 };
8829
8830 /**
8831 * Who moves the ring at `ui.focus`, as the engine stamps it where the move
8832 * starts; a closed set a matcher narrows on.
8833 *
8834 * `next(e)` passes it on as received; no hook sets one.
8835 */
8836 export type UiFocusOrigin = {
8837 /**
8838 * The person, by Tab, the arrows or a click while the site holds the
8839 * keyboard.
8840 */
8841 kind: 'person';
8842 } | {
8843 /**
8844 * A plugin's `$.ui.focus`, or its `autoFocus` element taking the ring
8845 * as the site takes the keyboard.
8846 */
8847 kind: 'plugin';
8848 /**
8849 * The focusing plugin's name.
8850 */
8851 name: string;
8852 };
8853
8854 /**
8855 * What a `ui.focus` hook returns, what `next(e)` resolves to, and what
8856 * `$.ui.focus` hands back: `{}` once the ring moved, or why it did not.
8857 *
8858 * As `ui.scroll` spells it.
8859 */
8860 export type UiFocusResult = {
8861 /**
8862 * Absent when the ring is where the chain left it; else why nothing
8863 * moved.
8864 *
8865 * A hook kept the ring (no `next`); the site is not this plugin's, does
8866 * not hold the keyboard, or another plugin's element holds it; no element
8867 * of `plugin` is drawn under `element`; another move landed first.
8868 */
8869 deny?: string;
8870 };
8871
8872 /**
8873 * The argument of `ui.input`: a change of, or a submit from, an `Input` a
8874 * render hook drew. Flat and frozen like every event's.
8875 *
8876 * Another plugin addresses one field by matcher:
8877 * `on("ui.input", { plugin: "roster", element: "reply" }, ...)`.
8878 */
8879 export type UiInputArgument = {
8880 /**
8881 * Whose `ui.render` hook drew the element.
8882 */
8883 plugin: string;
8884 /**
8885 * The `key` the hook gave its `Input`: its address, what a matcher names.
8886 */
8887 element: string;
8888 /**
8889 * The render component the element was drawn in (`AbovePrompt`,
8890 * `ToolUse`, ...).
8891 */
8892 component: RenderComponent;
8893 /**
8894 * The instance the element was drawn in: the `requestId` the `ui.render`
8895 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
8896 */
8897 requestId: string;
8898 /**
8899 * Where the typing came from, one literal per member, so
8900 * `if (e.surface === "terminal")` narrows `e`.
8901 */
8902 surface: RenderSurface;
8903 /**
8904 * `change` after every edit of the text; `submit` on Enter.
8905 */
8906 kind: 'change' | 'submit';
8907 /**
8908 * The field's whole text at that moment; a hook above may rewrite it for
8909 * the plugins beneath and the element's own handler.
8910 */
8911 value: string;
8912 };
8913
8914 /**
8915 * What a `ui.input` hook returns and what `next(e)` resolves to.
8916 *
8917 * Beneath every hook, core runs the element's `onInput` (kind `change`) or
8918 * `onSubmit` (kind `submit`) closure in its plugin's environment with the
8919 * value as the chain left it, and answers `{ element, value }`.
8920 */
8921 export type UiInputResult = {
8922 /**
8923 * Which handler the input reached, by its Input's `key`.
8924 */
8925 element: string;
8926 /**
8927 * The text the handler received.
8928 */
8929 value: string;
8930 };
8931
8932 /**
8933 * The argument of `ui.message`: what a `Client` instance's surface module
8934 * posted (`surface.post(data)`), addressed by where the instance is drawn.
8935 *
8936 * The origin is `client`: code sent it, on nobody's behalf, so `data` is
8937 * input to validate, not a fact. Everything but `data` is the engine's word
8938 * and a hook may not rewrite it.
8939 */
8940 export type UiMessageArgument = {
8941 /**
8942 * Where the instance is drawn: `terminal`, or `desktop` once it has them.
8943 */
8944 surface: RenderSurface;
8945 /**
8946 * The render component the `Client` was drawn in (`AbovePrompt`, `Pane`,
8947 * ...).
8948 */
8949 component: RenderComponent;
8950 /**
8951 * The engine's id for the drawing the `Client` sits in: the `requestId` the
8952 * `ui.render` hook that drew it saw.
8953 */
8954 requestId: string;
8955 /**
8956 * The `Client`'s `key`: which instance posted.
8957 */
8958 element: string;
8959 /**
8960 * The `Client`'s `module`: which surface module runs there, as its path
8961 * under the plugin's folder.
8962 */
8963 module: string;
8964 /**
8965 * What the instance posted: plain data (JsonValue), bounded as a tree's
8966 * text is; typed `unknown` since it came from code. Rewritable.
8967 */
8968 data: unknown;
8969 };
8970
8971 /**
8972 * What a `ui.message` hook returns and what `next(e)` resolves to.
8973 *
8974 * Core answers `{}`: the message was heard and nothing changes. A hook that
8975 * answers `{ props }` hands the posting instance its next props directly, its
8976 * local state kept, with no `ui.render` run; the plugin's next redraw hands
8977 * props again as usual.
8978 */
8979 export type UiMessageResult = {
8980 /**
8981 * The instance's next props, plain data (JsonValue) bounded as a `Client`'s
8982 * props are; absent leaves the instance's props as they were.
8983 */
8984 props?: unknown;
8985 };
8986
8987 /**
8988 * The argument of `ui.press`: a press on a `Button` a render hook drew.
8989 * Flat and frozen like every event's.
8990 *
8991 * Another plugin addresses one button by matcher:
8992 * `on("ui.press", { plugin: "explainer", element: "explain" }, ...)`.
8993 */
8994 export type UiPressArgument = {
8995 /**
8996 * Whose `ui.render` hook drew the element.
8997 */
8998 plugin: string;
8999 /**
9000 * The `key` the hook gave its `Button`: its address, what a matcher names.
9001 */
9002 element: string;
9003 /**
9004 * The render component the element was drawn in (`ToolUse`,
9005 * `AssistantMessage`, ...).
9006 */
9007 component: RenderComponent;
9008 /**
9009 * The instance the element was drawn in: the `requestId` the `ui.render`
9010 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
9011 */
9012 requestId: string;
9013 /**
9014 * Where the press came from, one literal per member, so
9015 * `if (e.surface === "terminal")` narrows `e`.
9016 */
9017 surface: RenderSurface;
9018 };
9019
9020 /**
9021 * What a `ui.press` hook returns and what `next(e)` resolves to.
9022 *
9023 * Beneath every hook, core runs the element's `onPress` closure in its
9024 * plugin's environment with `e` as the chain left it, and answers
9025 * `{ element }`.
9026 */
9027 export type UiPressResult = {
9028 /**
9029 * Which handler the press reached, by its Button's `key`.
9030 */
9031 element: string;
9032 };
9033
9034 /**
9035 * What a plugin's `$.ui.scroll(args)` takes: what to bring into view, in
9036 * which of its sites, and where in the window it lands.
9037 *
9038 * The engine resolves it to a window and an offset and raises `ui.scroll`
9039 * under the plugin's origin; a transcript row is the person's to move, so
9040 * it is revealed only while the plugin answers the person's own input.
9041 */
9042 export type UiScrollArgs = {
9043 /**
9044 * What to reveal (UiScrollTarget): a render instance by `requestId`, one
9045 * of this plugin's elements by `key`, or the `start` or `end` of `in`.
9046 */
9047 to: UiScrollTarget;
9048 /**
9049 * The site to scroll, by the `requestId` this plugin draws it under: one
9050 * of its panes' ids, or the band's.
9051 *
9052 * Required with `start` and `end`; with `{ key }` it picks the site when
9053 * the key is drawn in several.
9054 */
9055 in?: string;
9056 /**
9057 * Where the target lands in the window (UiScrollBlock); `nearest` when
9058 * left out, so a row already showing does not move.
9059 */
9060 block?: UiScrollBlock;
9061 };
9062
9063 /**
9064 * Where in its scrollable a revealed row lands, as the DOM's
9065 * `scrollIntoView({ block })` names it.
9066 *
9067 * `nearest` moves the least that shows the row whole, and not at all when
9068 * it already shows; `start`, `center` and `end` put its top, middle or
9069 * bottom at that edge of the window. A row taller than the window shows
9070 * its top.
9071 */
9072 export type UiScrollBlock = 'start' | 'center' | 'end' | 'nearest';
9073
9074 /**
9075 * The render components whose site the engine scrolls: a pane's body and
9076 * the band above the prompt, each a window over the tree a hook drew there.
9077 */
9078 export type UiScrollComponent = 'Pane' | 'AbovePrompt';
9079
9080 /**
9081 * The input of `ui.scroll`: a site's window asked to move over the tree a
9082 * hook drew in it (a pane's body, the band above the prompt).
9083 *
9084 * Every key but `offset` is the engine's word, pinned: `next(e)` passes
9085 * them on, a rewrite that leaves one out keeps it, one that changes or adds
9086 * one fails the hook. `offset` is the hook's to rewrite; nothing moved yet.
9087 */
9088 export type UiScrollInput = {
9089 /**
9090 * Which site: a `Pane` body or the `AbovePrompt` band.
9091 */
9092 component: UiScrollComponent;
9093 /**
9094 * The instance the `ui.render` hook drawing the site sees: the pane's id,
9095 * or the band's one id.
9096 */
9097 requestId: string;
9098 /**
9099 * The first row the window is to show, 0 at the top: the row it shows
9100 * now plus `by`, clamped to the tree, or where `$.ui.scroll` resolved.
9101 *
9102 * `next({ ...e, offset })` moves it elsewhere (a clamp); one past the
9103 * tree's end lands at the end. Nothing has moved when a hook reads it.
9104 */
9105 offset: number;
9106 /**
9107 * The rows the move asks for, signed, negative toward the top; what the
9108 * DOM's `scrollBy` takes. Read-only.
9109 *
9110 * The person's: a wheel tick `-1` or `1` at rest, more as ticks crowd or
9111 * summed in flight; an arrow a row while the engine has rows to scroll, a
9112 * page key `bodyRows`, Home and End `contentRows`. A plugin's: its distance.
9113 */
9114 by: number;
9115 /**
9116 * How many rows of the tree the window shows at once, as drawn now.
9117 * Read-only.
9118 */
9119 bodyRows: number;
9120 /**
9121 * How many rows the tree has, as drawn now: the window's last offset is
9122 * `contentRows - bodyRows`, none when the tree fits. Read-only.
9123 */
9124 contentRows: number;
9125 /**
9126 * Who moves it (UiScrollOrigin), set by the engine where the move starts.
9127 */
9128 origin: UiScrollOrigin;
9129 /**
9130 * The body cell the person's wheel or trackpad was over (UiScrollPointer);
9131 * absent for the scroll keys and for `$.ui.scroll`. Read-only.
9132 *
9133 * Moves summed while a dispatch was in flight carry the latest one's. A
9134 * hook pinning a list over rows it scrolls itself tells a tick over the
9135 * list (`row` among its list's rows) from one over the body.
9136 */
9137 pointer?: UiScrollPointer;
9138 };
9139
9140 /**
9141 * Who moves the window at `ui.scroll`, as the engine stamps it where the
9142 * move starts; a closed set a matcher narrows on.
9143 *
9144 * `next(e)` passes it on as received; no hook sets one.
9145 */
9146 export type UiScrollOrigin = {
9147 /**
9148 * The person, by the wheel over the site or its scroll keys while
9149 * they hold it.
9150 */
9151 kind: 'person';
9152 } | {
9153 /**
9154 * A plugin's `$.ui.scroll`.
9155 */
9156 kind: 'plugin';
9157 /**
9158 * The scrolling plugin's name.
9159 */
9160 name: string;
9161 };
9162
9163 /**
9164 * The cell the pointer was over when the person's wheel raised `ui.scroll`,
9165 * in the site's body: the box its `ui.render` hook draws into, as painted.
9166 *
9167 * The DOM's `clientY - body.top` in cells, the window's offset not added: a
9168 * hook drawing its own window reads `row` as its tree's row, one the engine
9169 * scrolls adds the `scroll.offset` it drew with. The frame lies outside.
9170 */
9171 export type UiScrollPointer = {
9172 /**
9173 * 0 at the body's left edge, as `bodyColumns` counts them; negative, or
9174 * `bodyColumns` and past, over an inline pane's side borders.
9175 */
9176 column: number;
9177 /**
9178 * 0 at the body's first showing row, as `bodyRows` counts them.
9179 *
9180 * The tree's row is `scroll.offset + row` under the engine's window, and
9181 * `row` itself under a hook's own (offset 0); negative over a pane's top
9182 * border or tab row, `bodyRows` or more over its bottom border.
9183 */
9184 row: number;
9185 };
9186
9187 /**
9188 * What a `ui.scroll` hook returns, what `next(e)` resolves to, and what
9189 * `$.ui.scroll` hands back: `{}` once the window moved, or why it did not.
9190 */
9191 export type UiScrollResult = {
9192 /**
9193 * Absent when the window is where the chain left it; else why nothing
9194 * moved, as `tool.call` and `config.set` spell a refusal.
9195 *
9196 * A hook kept the window (no `next`); the target is not this plugin's;
9197 * another move landed first (`the window moved meanwhile`); a transcript
9198 * row is not the person's ask (`not person-initiated`) or none scrolls.
9199 */
9200 deny?: string;
9201 };
9202
9203 /**
9204 * What `$.ui.scroll` brings into view: never a row number, always a thing
9205 * drawn somewhere.
9206 *
9207 * `{ requestId }` names a render instance by the id its `ui.render` hook
9208 * saw (a transcript message's, a tool row's tool_use_id), scrolled into view
9209 * inside whatever scrolls it. `{ key }` names an element this plugin drew
9210 * with that `key`, inside the site it drew it in. `start` and `end` are the
9211 * top and bottom of the site `in` names; `end` keeps up with a tree that
9212 * grows (rows the plugin just added count) until anything next moves it.
9213 */
9214 export type UiScrollTarget = {
9215 requestId: string;
9216 } | {
9217 key: string;
9218 } | 'start' | 'end';
9219
9220 /**
9221 * The argument of `ui.select`: a pick from a `Select` a render hook drew.
9222 * Flat and frozen like every event's.
9223 *
9224 * Another plugin addresses one picker by matcher:
9225 * `on("ui.select", { plugin: "roster", element: "peer" }, ...)`.
9226 */
9227 export type UiSelectArgument = {
9228 /**
9229 * Whose `ui.render` hook drew the element.
9230 */
9231 plugin: string;
9232 /**
9233 * The `key` the hook gave its `Select`: its address, what a matcher names.
9234 */
9235 element: string;
9236 /**
9237 * The render component the element was drawn in (`AbovePrompt`,
9238 * `ToolUse`, ...).
9239 */
9240 component: RenderComponent;
9241 /**
9242 * The instance the element was drawn in: the `requestId` the `ui.render`
9243 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
9244 */
9245 requestId: string;
9246 /**
9247 * Where the pick came from, one literal per member, so
9248 * `if (e.surface === "terminal")` narrows `e`.
9249 */
9250 surface: RenderSurface;
9251 /**
9252 * The picked option's value; a hook above may rewrite it for the plugins
9253 * beneath and the element's own handler.
9254 */
9255 value: string;
9256 };
9257
9258 /**
9259 * What a `ui.select` hook returns and what `next(e)` resolves to.
9260 *
9261 * Beneath every hook, core runs the element's `onSelect` closure in its
9262 * plugin's environment with the value as the chain left it, and answers
9263 * `{ element, value }`.
9264 */
9265 export type UiSelectResult = {
9266 /**
9267 * Which handler the pick reached, by its Select's `key`.
9268 */
9269 element: string;
9270 /**
9271 * What the handler received: the option's value as the chain left it.
9272 */
9273 value: string;
9274 };
9275
9276 /**
9277 * The intersection of a union's members (`A | B` to `A & B`), by inferring
9278 * one parameter type from the contravariant positions.
9279 */
9280 type UnionToIntersection<U> = (U extends unknown ? (member: U) => void : never) extends (member: infer I) => void ? I : never;
9281
9282 type UserPromptExpansionHookInput = BaseHookInput & {
9283 hook_event_name: 'UserPromptExpansion';
9284 expansion_type: 'slash_command' | 'mcp_prompt';
9285 command_name: string;
9286 command_args: string;
9287 command_source?: string;
9288 prompt: string;
9289 };
9290
9291 type UserPromptSubmitHookInput = BaseHookInput & {
9292 hook_event_name: 'UserPromptSubmit';
9293 prompt: string;
9294 /**
9295 * 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.
9296 */
9297 source?: 'user' | 'sdk' | 'system' | 'loop_wakeup' | 'schedule_wakeup' | 'poll_event';
9298 session_title?: string;
9299 };
9300
9301 /**
9302 * The result of a call on `$` as the hooks on its event see it: `{ value }`,
9303 * the call's answer, or `{ deny }`, the reason the caller's promise rejects.
9304 */
9305 type ValueOrDeny<Value> = {
9306 value: Value;
9307 deny?: undefined;
9308 } | {
9309 deny: string;
9310 value?: undefined;
9311 };
9312
9313 type WorktreeCreateHookInput = BaseHookInput & {
9314 hook_event_name: 'WorktreeCreate';
9315 name: string;
9316 };
9317
9318 type WorktreeRemoveHookInput = BaseHookInput & {
9319 hook_event_name: 'WorktreeRemove';
9320 worktree_path: string;
9321 };
9322
9323 /**
9324 * The globals of a hooks module's environment: these and no others (no DOM,
9325 * no Node).
9326 */
9327 global {
9328 /**
9329 * The JSX factory (classic runtime, `@jsx h`; the engine prepends the
9330 * pragma): a plain-data element from a string tag or a component.
9331 */
9332 const h: (
9333 tag: string | ((props: never) => RenderNode | null | undefined),
9334 props: Record<string, unknown> | null | undefined,
9335 ...children: unknown[]
9336 ) => RenderNode | null | undefined
9337
9338 /**
9339 * `<>...</>`: a column Box around the children.
9340 */
9341 const Fragment: (props: { children?: RenderNode[] }) => RenderElement
9342
9343 /**
9344 * JSX over the element table: every tag is a constructor from
9345 * `$.ui.resolve(e)` (`const { Box, Text } = $.ui.resolve(e)`), typed by
9346 * its props; there are no intrinsic (string) tags.
9347 */
9348 namespace JSX {
9349 type Element = RenderElement
9350 type Children = RenderChildren
9351 type ElementType = (props: never) => RenderNode | null | undefined
9352 interface IntrinsicElements {}
9353 interface ElementChildrenAttribute {
9354 children: unknown
9355 }
9356 interface IntrinsicAttributes {
9357 key?: string
9358 }
9359 }
9360
9361 interface AbortSignal {
9362 readonly aborted: boolean
9363 readonly reason: unknown
9364 throwIfAborted(): void
9365 addEventListener(
9366 type: 'abort',
9367 listener: () => void,
9368 options?: { once?: boolean },
9369 ): void
9370 removeEventListener(type: 'abort', listener: () => void): void
9371 }
9372 var AbortSignal: {
9373 prototype: AbortSignal
9374 abort(reason?: unknown): AbortSignal
9375 timeout(milliseconds: number): AbortSignal
9376 any(signals: AbortSignal[]): AbortSignal
9377 }
9378 interface AbortController {
9379 readonly signal: AbortSignal
9380 abort(reason?: unknown): void
9381 }
9382 var AbortController: {
9383 prototype: AbortController
9384 new (): AbortController
9385 }
9386 interface TextEncoder {
9387 readonly encoding: string
9388 encode(input?: string): Uint8Array
9389 }
9390 var TextEncoder: { prototype: TextEncoder; new (): TextEncoder }
9391 interface TextDecoder {
9392 readonly encoding: string
9393 decode(input?: ArrayBufferView | ArrayBuffer): string
9394 }
9395 var TextDecoder: { prototype: TextDecoder; new (label?: string): TextDecoder }
9396 interface URLSearchParams {
9397 append(name: string, value: string): void
9398 delete(name: string): void
9399 get(name: string): string | null
9400 getAll(name: string): string[]
9401 has(name: string): boolean
9402 set(name: string, value: string): void
9403 toString(): string
9404 forEach(callback: (value: string, key: string) => void): void
9405 }
9406 var URLSearchParams: {
9407 prototype: URLSearchParams
9408 new (init?: string | Record<string, string> | string[][]): URLSearchParams
9409 }
9410 interface URL {
9411 hash: string
9412 host: string
9413 hostname: string
9414 href: string
9415 readonly origin: string
9416 password: string
9417 pathname: string
9418 port: string
9419 protocol: string
9420 search: string
9421 readonly searchParams: URLSearchParams
9422 username: string
9423 toString(): string
9424 toJSON(): string
9425 }
9426 var URL: {
9427 prototype: URL
9428 new (url: string, base?: string | URL): URL
9429 canParse(url: string, base?: string): boolean
9430 }
9431 function atob(data: string): string
9432 function btoa(data: string): string
9433 function structuredClone<T>(value: T): T
9434 var crypto: {
9435 readonly subtle: {
9436 digest(
9437 algorithm: string | { name: string },
9438 data: ArrayBufferView | ArrayBuffer,
9439 ): Promise<ArrayBuffer>
9440 }
9441 randomUUID(): string
9442 getRandomValues<T extends ArrayBufferView>(array: T): T
9443 }
9444 var performance: { now(): number }
9445 }
9446}
9447
9448declare module 'claude-code/testing' {
9449 import type { Args } from 'claude-code';
9450 import type { Chunk } from 'claude-code';
9451 import type { EventCalls } from 'claude-code';
9452 import type { EventName } from 'claude-code';
9453 import type { HookStream } from 'claude-code';
9454 import type { On } from 'claude-code';
9455 import type { Register } from 'claude-code';
9456 import type { ResultOf } from 'claude-code';
9457 import type { StreamingEventName } from 'claude-code';
9458 import type { Tier } from 'claude-code';
9459 import type { UiPressResult } from 'claude-code';
9460
9461 /**
9462 * A value that matches by a rule inside `toEqual` and its kin
9463 * (`expect.any`, `expect.objectContaining`), known by its text in a failure.
9464 */
9465 export type AsymmetricMatcher = {
9466 readonly text: string;
9467 };
9468
9469 /**
9470 * The same checks on what a promise received settles with, each resolving
9471 * once the promise has settled and the check passed.
9472 */
9473 export type AsyncMatchers = {
9474 [K in keyof Matchers]: (...args: Parameters<Matchers[K]>) => Promise<void>;
9475 };
9476
9477 /**
9478 * A class, as `toThrow`, `toBeInstanceOf` and `expect.any` take it.
9479 */
9480 export type Constructor = abstract new (...args: never[]) => unknown;
9481
9482 /**
9483 * A group of tests: its name leads the title of each test declared inside,
9484 * and its body runs at once, while the file loads.
9485 *
9486 * @param name the group's name
9487 * @param body declares the group's tests
9488 */
9489 export const describe: (name: string, body: () => void) => void;
9490
9491 /**
9492 * What a test holds as `$`, the engine's own: every call on it is made as
9493 * the REPL, the query loop and the render sites make theirs, over every plugin.
9494 *
9495 * `next.origin` is the engine, and the whole chain runs over the plugins
9496 * loaded. A tool call's `tool_use_id` is minted when left out, as the engine
9497 * mints it; `$.ui.press` is the terminal pressing a Button a test rendered.
9498 */
9499 export type Engine = {
9500 [N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress : EngineNoun<N>;
9501 };
9502
9503 /**
9504 * One call on the engine's `$`: the event's input whole, as an engine call
9505 * site passes it, to its result, or for a streaming event to its stream.
9506 */
9507 export type EngineCall<E extends EventName> = E extends StreamingEventName ? (e: Args<E>) => HookStream<Chunk<E>, ResultOf[E]> : (e: Args<E>) => Promise<ResultOf[E]>;
9508
9509 /**
9510 * One noun of the engine's `$`: each of its events as the engine calls it,
9511 * `tool.call` and `ui.render` typed per tool and component, `ui.resolve` out.
9512 */
9513 export type EngineNoun<N extends keyof EventCalls> = {
9514 [V in EngineNounEvent<N>]: `${N}.${V}` extends 'tool.call' | 'ui.render' ? EventCalls[N][V] : EngineCall<`${N}.${V}` & EventName>;
9515 };
9516
9517 /**
9518 * The events of one noun a test's `$` carries: every one but `ui.resolve`,
9519 * which a render hook calls on its own `$` and the engine never raises.
9520 */
9521 export type EngineNounEvent<N extends keyof EventCalls> = Exclude<keyof EventCalls[N] & string, `${N}.resolve` extends 'ui.resolve' ? 'resolve' : never>;
9522
9523 /**
9524 * The terminal pressing a Button a test rendered: the `ui.press` chain over
9525 * every plugin hooked on it, the Button's own `onPress` at the bottom.
9526 */
9527 export type EnginePress = {
9528 /**
9529 * Presses the Button, as a click or its hotkey does.
9530 *
9531 * @param target whose Button, its key, and the instance when several
9532 * @returns what the chain settled on; rejects when no such Button is
9533 * drawn on the terminal, or several are and no instance is named
9534 */
9535 press: (target: PressTarget) => Promise<UiPressResult | undefined>;
9536 };
9537
9538 /**
9539 * The checks on a value (`expect(received)`), and with them the matchers
9540 * that stand inside an expected value (`expect.any(Number)`).
9541 */
9542 export type Expect = Expecting & Matching;
9543
9544 /**
9545 * Checks a value: `expect(received).toEqual(expected)` throws an
9546 * AssertionError naming both sides when it fails, a message given leading.
9547 *
9548 * `.not` negates; `.resolves` and `.rejects` check what a promise settles
9549 * with; `expect.any(Number)` and its kin stand inside an expected value.
9550 */
9551 export const expect: Expect;
9552
9553 /**
9554 * What `expect(received)` answers: the checks, their negation, and the
9555 * checks on what a promise received resolves or rejects with.
9556 */
9557 export type Expectation = Negatable<Matchers> & {
9558 /**
9559 * The checks on what the promise received resolves with; a rejection
9560 * fails them.
9561 */
9562 resolves: Negatable<AsyncMatchers>;
9563 /**
9564 * The checks on what the promise received rejects with; a resolution
9565 * fails them.
9566 */
9567 rejects: Negatable<AsyncMatchers>;
9568 };
9569
9570 /**
9571 * `expect(received, message?)`: the checks on a value, a message of the
9572 * test's own leading a failure's.
9573 */
9574 export type Expecting = (received: unknown, message?: string) => Expectation;
9575
9576 /**
9577 * The checks `expect(received)` offers; each throws an AssertionError when
9578 * it fails, naming what was expected and what was received.
9579 */
9580 export type Matchers = {
9581 /**
9582 * Passes when received is the value, by `Object.is`.
9583 *
9584 * @param expected the value
9585 */
9586 toBe: (expected: unknown) => void;
9587 /**
9588 * Passes when received equals the value in structure, properties holding
9589 * undefined ignored; `expect.any` and its kin match inside it.
9590 *
9591 * @param expected the value
9592 */
9593 toEqual: (expected: unknown) => void;
9594 /**
9595 * As `toEqual`, but undefined properties and prototypes count.
9596 *
9597 * @param expected the value
9598 */
9599 toStrictEqual: (expected: unknown) => void;
9600 /**
9601 * Passes when received holds at least the object's properties, equal.
9602 *
9603 * @param expected the object
9604 */
9605 toMatchObject: (expected: object) => void;
9606 /**
9607 * Passes when a string received includes the item, or an iterable
9608 * received has an element that is it.
9609 *
9610 * @param item the substring or element
9611 */
9612 toContain: (item: unknown) => void;
9613 /**
9614 * Passes when an iterable received has an element equal to the item.
9615 *
9616 * @param item the element
9617 */
9618 toContainEqual: (item: unknown) => void;
9619 /**
9620 * Passes when received's `length` is the number.
9621 *
9622 * @param length the number
9623 */
9624 toHaveLength: (length: number) => void;
9625 /**
9626 * Passes when received holds a property at the path (`a.b`, or the keys
9627 * in order), equal to the value when one is given.
9628 *
9629 * @param path the property's path
9630 * @param value what it must equal, when given
9631 */
9632 toHaveProperty: (path: string | readonly string[], value?: unknown) => void;
9633 /**
9634 * Passes when received is undefined.
9635 */
9636 toBeUndefined: () => void;
9637 /**
9638 * Passes when received is anything but undefined.
9639 */
9640 toBeDefined: () => void;
9641 /**
9642 * Passes when received is null.
9643 */
9644 toBeNull: () => void;
9645 /**
9646 * Passes when received is truthy.
9647 */
9648 toBeTruthy: () => void;
9649 /**
9650 * Passes when received is falsy.
9651 */
9652 toBeFalsy: () => void;
9653 /**
9654 * Passes when received is NaN.
9655 */
9656 toBeNaN: () => void;
9657 /**
9658 * Passes when received is greater than the bound.
9659 *
9660 * @param bound the bound
9661 */
9662 toBeGreaterThan: (bound: number | bigint) => void;
9663 /**
9664 * Passes when received is the bound or greater.
9665 *
9666 * @param bound the bound
9667 */
9668 toBeGreaterThanOrEqual: (bound: number | bigint) => void;
9669 /**
9670 * Passes when received is less than the bound.
9671 *
9672 * @param bound the bound
9673 */
9674 toBeLessThan: (bound: number | bigint) => void;
9675 /**
9676 * Passes when received is the bound or less.
9677 *
9678 * @param bound the bound
9679 */
9680 toBeLessThanOrEqual: (bound: number | bigint) => void;
9681 /**
9682 * Passes when a string received includes the text, or the pattern matches
9683 * it.
9684 *
9685 * @param pattern the text or pattern
9686 */
9687 toMatch: (pattern: string | RegExp) => void;
9688 /**
9689 * Passes when a string received starts with the prefix.
9690 *
9691 * @param prefix the prefix
9692 */
9693 toStartWith: (prefix: string) => void;
9694 /**
9695 * Passes when a string received ends with the suffix.
9696 *
9697 * @param suffix the suffix
9698 */
9699 toEndWith: (suffix: string) => void;
9700 /**
9701 * Passes when received is an instance of the class.
9702 *
9703 * @param expected the class
9704 */
9705 toBeInstanceOf: (expected: Constructor) => void;
9706 /**
9707 * Passes when calling received throws (or, under `rejects`, the rejection
9708 * is) an error as described: by substring, pattern, class or message.
9709 *
9710 * @param expected the description; any throw passes without one
9711 */
9712 toThrow: (expected?: ThrowExpectation) => void;
9713 };
9714
9715 /**
9716 * The matchers that stand inside an expected value, each matching received
9717 * there by a rule instead of by equality.
9718 */
9719 export type Matching = {
9720 /**
9721 * Matches any instance of the class, a primitive by its wrapper
9722 * (`expect.any(Number)`).
9723 *
9724 * @param expected the class
9725 * @returns the matcher
9726 */
9727 any: (expected: Constructor) => AsymmetricMatcher;
9728 /**
9729 * Matches anything but null and undefined.
9730 *
9731 * @returns the matcher
9732 */
9733 anything: () => AsymmetricMatcher;
9734 /**
9735 * Matches a string that includes the text.
9736 *
9737 * @param text the substring
9738 * @returns the matcher
9739 */
9740 stringContaining: (text: string) => AsymmetricMatcher;
9741 /**
9742 * Matches a string the pattern matches.
9743 *
9744 * @param pattern the pattern, or the source of one
9745 * @returns the matcher
9746 */
9747 stringMatching: (pattern: string | RegExp) => AsymmetricMatcher;
9748 /**
9749 * Matches an object holding at least the shape's properties, equal.
9750 *
9751 * @param shape the properties
9752 * @returns the matcher
9753 */
9754 objectContaining: (shape: object) => AsymmetricMatcher;
9755 /**
9756 * Matches an array holding an element equal to each of the items.
9757 *
9758 * @param items the elements
9759 * @returns the matcher
9760 */
9761 arrayContaining: (items: readonly unknown[]) => AsymmetricMatcher;
9762 };
9763
9764 /**
9765 * The world beneath the plugins, mocked noun by noun: each member registers
9766 * hooks of the test's on `on`, visible where the test calls it.
9767 */
9768 export type Mock = {
9769 /**
9770 * Answers `$.clock` from a clock in memory that moves only when the test
9771 * moves it: `clock.now` reads it, and each wait is held.
9772 *
9773 * A held wait resolves when an advance crosses the time it is due, and is
9774 * dropped when its dispatch aborts; one held past a hook's budget (ten
9775 * seconds of real time) is let go, as a hook that overran.
9776 *
9777 * @param on the test's `on`
9778 * @param options where the clock starts (`now`, 0 when not given)
9779 * @returns the clock: its time, and the calls that move it
9780 */
9781 clock: (on: On, options?: MockClockOptions) => MockClock;
9782 /**
9783 * Answers `$.store` from a store in memory: `get`, `set`, `delete` and
9784 * `keys` over it, as the engine keeps a plugin's own.
9785 *
9786 * @param on the test's `on`
9787 * @param entries what the store holds at the start (nothing when not given)
9788 */
9789 store: (on: On, entries?: Readonly<Record<string, unknown>>) => void;
9790 /**
9791 * Answers `$.env.get` from a set of variables; one not listed is unset.
9792 *
9793 * @param on the test's `on`
9794 * @param variables the environment the plugins read
9795 */
9796 env: (on: On, variables: Readonly<Record<string, string>>) => void;
9797 };
9798
9799 /**
9800 * The world beneath the plugins, mocked noun by noun: `mock.clock`,
9801 * `mock.store` and `mock.env`.
9802 *
9803 * Each registers hooks of the test's on the `on` it is handed, visible where
9804 * the test calls it, and answers its noun from memory.
9805 */
9806 export const mock: Mock;
9807
9808 /**
9809 * The clock `mock.clock` hands back: the time its hooks answer, and the only
9810 * ways it moves.
9811 */
9812 export type MockClock = {
9813 /**
9814 * The time now, in milliseconds: what `$.clock.now()` resolves beneath the
9815 * plugins.
9816 *
9817 * @returns the time
9818 */
9819 now: () => number;
9820 /**
9821 * Moves the clock on, resolving each wait due on the way (`$.clock.sleep`,
9822 * `after`, `every`, this clock's `sleep`) in the order it comes due.
9823 *
9824 * The clock reads each wait's time as it resolves, and what one started
9825 * runs before the next resolves.
9826 *
9827 * @param ms how far to move, in milliseconds
9828 * @returns resolves once the clock is there and the event loop settled
9829 */
9830 advance: (ms: number) => Promise<void>;
9831 /**
9832 * Moves the clock to a time at or past now, as `advance` would.
9833 *
9834 * @param ms the time, in milliseconds
9835 * @returns resolves once the clock is there and the event loop settled
9836 */
9837 set: (ms: number) => Promise<void>;
9838 /**
9839 * Lets what is already under way run as far as it can without the clock
9840 * moving: every wait due now resolves and the event loop settles.
9841 *
9842 * The same as `advance(0)`; the name for the step between starting a
9843 * dispatch unawaited and looking at what it did.
9844 *
9845 * @returns resolves once the event loop settled, the time where it was
9846 */
9847 settle: () => Promise<void>;
9848 /**
9849 * Resolves once the clock has moved this far past now: how a hook of the
9850 * test's answers late.
9851 *
9852 * @param ms how far, in milliseconds
9853 * @returns resolves when an advance crosses that time
9854 */
9855 sleep: (ms: number) => Promise<void>;
9856 };
9857
9858 /**
9859 * Where a mocked clock starts: `now`, in milliseconds (0 when not given).
9860 */
9861 export type MockClockOptions = {
9862 now?: number;
9863 };
9864
9865 /**
9866 * A set of checks and, under `not`, the same set passing where they fail.
9867 */
9868 export type Negatable<M> = M & {
9869 /**
9870 * The checks negated.
9871 */
9872 not: M;
9873 };
9874
9875 /**
9876 * Written inline in a test and loaded as a plugin folder is: its name, the
9877 * tier it loads in (`user` when not given), and its hooks module's `register`.
9878 *
9879 * `register` is written `register(on) { ... }` and is self-contained, as a
9880 * module's is: it closes over nothing of the test file.
9881 */
9882 export type Plugin = {
9883 name: string;
9884 tier?: PluginTier;
9885 register: Register;
9886 };
9887
9888 /**
9889 * A tier a plugin loads in: every tier but the engine's own.
9890 */
9891 export type PluginTier = Exclude<Tier, 'core'>;
9892
9893 /**
9894 * What `$.ui.press` takes: the plugin whose `ui.render` hook drew the Button,
9895 * the `key` it gave it, and the instance when it drew one in several.
9896 */
9897 export type PressTarget = {
9898 plugin: string;
9899 key: string;
9900 requestId?: string;
9901 };
9902
9903 /**
9904 * One test: it passes when its body returns or resolves, and fails when it
9905 * throws, rejects or outlasts its time (5000 ms, or `timeoutMs`).
9906 *
9907 * The body gets the engine's `$` and an `on` whose hooks sit beneath every
9908 * plugin; `plugins` load inline plugins beside the one under test. A failure
9909 * carries what the engine reported meanwhile: each hook it skipped, and why.
9910 *
9911 * @param name the test's name, led in its title by the describes around it
9912 * @param rest the body, `($, on) => ...`, or the options then the body
9913 */
9914 export const test: (name: string, ...rest: TestRest) => void;
9915
9916 /**
9917 * A test: the engine's `$`, and `on`, a plugin's registrar, whose hooks sit
9918 * beneath every plugin; beneath them the bottom hook throws, naming its event.
9919 *
9920 * The plugins load at the test's first call on `$`, so a test registers its
9921 * hooks before it, as a module registers its own in `register()`.
9922 */
9923 export type TestBody = ($: Engine, on: On) => unknown;
9924
9925 /**
9926 * What `test` takes beside its name: the inline plugins it loads beside the
9927 * one under test, and how long it may run (5000 ms when not given).
9928 */
9929 export type TestOptions = {
9930 plugins?: readonly Plugin[];
9931 timeoutMs?: number;
9932 };
9933
9934 /**
9935 * What follows a test's name: its body, or its options then its body.
9936 */
9937 export type TestRest = readonly [body: TestBody] | readonly [options: TestOptions, body: TestBody];
9938
9939 /**
9940 * What `toThrow` compares the thrown error with: a substring or pattern of
9941 * its message, its class, a value carrying the whole message, or nothing.
9942 */
9943 export type ThrowExpectation = string | RegExp | Constructor | WithMessage;
9944
9945 /**
9946 * Says which tier the plugin under test loads in, once, at the top of the
9947 * file: `prepend`, `user` (when unsaid), `append` or `builtin`.
9948 *
9949 * @param tier the tier
9950 */
9951 export const tier: (tier: PluginTier) => void;
9952
9953 /**
9954 * An error-like value `toThrow` compares by its whole message.
9955 */
9956 export type WithMessage = {
9957 message: string;
9958 };
9959}
9960
9961// The inputs of the built-in tools this build has, from each tool's
9962// input schema. Merges into ToolCallInput (BuiltinToolInputs) so
9963// `e.tool === "Bash"` narrows to the tool's arguments.
9964declare module 'claude-code' {
9965 interface BuiltinToolInputs {
9966 Agent: {
9967 /** A short (3-5 word) description of the task */
9968 description: string
9969 /** The task for the agent to perform */
9970 prompt: string
9971 /** The type of specialized agent to use for this task */
9972 subagent_type?: string
9973 /** 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. */
9974 model?: "sonnet" | "opus" | "haiku" | "fable"
9975 /** 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. */
9976 run_in_background?: boolean
9977 /** Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running. */
9978 name?: string
9979 /** Deprecated; ignored. The session has a single implicit team. */
9980 team_name?: string
9981 /** Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it. */
9982 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"
9983 /** 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). */
9984 isolation?: "worktree" | "remote"
9985 }
9986 Bash: {
9987 /** The command to execute */
9988 command: string
9989 /** Optional timeout in milliseconds (max 600000) */
9990 timeout?: number
9991 /** 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" */
9992 description?: string
9993 /** Set to true to run this command in the background. */
9994 run_in_background?: boolean
9995 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
9996 dangerouslyDisableSandbox?: boolean
9997 }
9998 CronCreate: {
9999 /** 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). */
10000 cron: string
10001 /** The prompt to enqueue at each fire time. */
10002 prompt: string
10003 /** 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. */
10004 recurring?: boolean
10005 /** 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. */
10006 durable?: boolean
10007 }
10008 CronDelete: {
10009 /** Job ID returned by CronCreate. */
10010 id: string
10011 }
10012 CronList: {}
10013 Edit: {
10014 /** The absolute path to the file to modify */
10015 file_path: string
10016 /** The text to replace */
10017 old_string: string
10018 /** The text to replace it with (must be different from old_string) */
10019 new_string: string
10020 /** Replace all occurrences of old_string (default false) */
10021 replace_all?: boolean
10022 }
10023 EnterWorktree: {
10024 /** 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`. */
10025 name?: string
10026 /** 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`. */
10027 path?: string
10028 }
10029 ExitWorktree: {
10030 /** "keep" leaves the worktree and branch on disk; "remove" deletes both. */
10031 action: "keep" | "remove"
10032 /** Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise. */
10033 discard_changes?: boolean
10034 }
10035 ListAgents: {
10036 /** Not available in this build; leave unset. */
10037 channel?: string
10038 /** Not available in this build; leave unset. */
10039 q?: string
10040 }
10041 NotebookEdit: {
10042 /** The absolute path to the Jupyter notebook file to edit (must be absolute, not relative) */
10043 notebook_path: string
10044 /** 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. */
10045 cell_id?: string
10046 /** The new source for the cell */
10047 new_source: string
10048 /** 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. */
10049 cell_type?: "code" | "markdown"
10050 /** The type of edit to make (replace, insert, delete). Defaults to replace. */
10051 edit_mode?: "replace" | "insert" | "delete"
10052 }
10053 PowerShell: {
10054 /** The PowerShell command to execute */
10055 command: string
10056 /** Optional timeout in milliseconds (max 600000) */
10057 timeout?: number
10058 /** Clear, concise description of what this command does in active voice. */
10059 description?: string
10060 /** Set to true to run this command in the background. */
10061 run_in_background?: boolean
10062 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
10063 dangerouslyDisableSandbox?: boolean
10064 }
10065 Read: {
10066 /** The absolute path to the file to read */
10067 file_path: string
10068 /** The line number to start reading from. Only provide if the file is too large to read at once */
10069 offset?: number
10070 /** The number of lines to read. Only provide if the file is too large to read at once. */
10071 limit?: number
10072 /** Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum 20 pages per request. */
10073 pages?: string
10074 }
10075 ReportFindings: {
10076 /** Effort level the review ran at */
10077 level?: "low" | "medium" | "high" | "xhigh" | "max"
10078 /** Verified findings, most-severe first; empty if none survived */
10079 findings: Array<{
10080 /** Repo-relative path of the file the finding is in */
10081 file: string
10082 /** 1-indexed line the finding anchors to */
10083 line?: number
10084 /** One-sentence statement of the defect */
10085 summary: string
10086 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
10087 short_summary?: string
10088 /** Concrete inputs/state → wrong output/crash */
10089 failure_scenario: string
10090 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
10091 category?: string
10092 /** Set when a verify pass ran; absent on inline-only reviews */
10093 verdict?: "CONFIRMED" | "PLAUSIBLE"
10094 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
10095 outcome?: "fixed" | "skipped" | "no_change_needed"
10096 }>
10097 }
10098 ScheduleWakeup: {
10099 /** Seconds from now to wake up. Clamped to [60, 3600] by the runtime. Required unless `stop` is true. */
10100 delaySeconds?: number
10101 /** One short sentence explaining the chosen delay. Goes to telemetry and is shown to the user. Be specific. Required unless `stop` is true. */
10102 reason?: string
10103 /** 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. */
10104 prompt?: string
10105 /** 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. */
10106 stop?: boolean
10107 /** 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. */
10108 noop?: boolean
10109 }
10110 SendMessage: {
10111 /** 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 */
10112 to: unknown & unknown
10113 /** 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. */
10114 summary?: string
10115 /** 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. */
10116 message: string
10117 /** 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. */
10118 notify_when_idle?: boolean
10119 }
10120 Skill: {
10121 /** The name of a skill from the available-skills list. Do not guess names. */
10122 skill: string
10123 /** Optional arguments for the skill */
10124 args?: string
10125 }
10126 TaskOutput: {
10127 /** The task ID to get output from */
10128 task_id: string
10129 /** Whether to wait for completion */
10130 block: boolean
10131 /** Max wait time in ms */
10132 timeout: number
10133 }
10134 TaskStop: {
10135 /** The ID of the background task to stop. Agent-team teammates and named background agents are also accepted by agent ID or name. */
10136 task_id?: string
10137 /** Deprecated: use task_id instead */
10138 shell_id?: string
10139 }
10140 ToolSearch: {
10141 /** Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search. */
10142 query: string
10143 /** Maximum number of results to return (default: 5) */
10144 max_results: number
10145 }
10146 WebFetch: {
10147 /** The URL to fetch content from */
10148 url: string
10149 /** The prompt to run on the fetched content */
10150 prompt: string
10151 }
10152 WebSearch: {
10153 /** The search query to use */
10154 query: string
10155 /** Only include search results from these domains */
10156 allowed_domains?: string[]
10157 /** Never include search results from these domains */
10158 blocked_domains?: string[]
10159 }
10160 Workflow: {
10161 /** 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(). */
10162 script?: string
10163 /** Name of a predefined workflow (built-in or from .claude/workflows/). Resolves to a self-contained script. */
10164 name?: string
10165 /** Ignored — set the workflow description in the script's `meta` block. */
10166 description?: string
10167 /** Ignored — set the workflow title in the script's `meta` block. */
10168 title?: string
10169 /** 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). */
10170 args?: unknown
10171 /** 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`. */
10172 scriptPath?: string
10173 /** 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. */
10174 resumeFromRunId?: string
10175 }
10176 Write: {
10177 /** The absolute path to the file to write (must be absolute, not relative) */
10178 file_path: string
10179 /** The content to write to the file */
10180 content: string
10181 }
10182 }
10183}
10184
10185// The structured results of the same tools, from each tool's output
10186// schema. Merges into ToolCallResult (BuiltinToolResults) so after
10187// `e.tool === "Bash"` the `result` of `next(e)` is the tool's record.
10188declare module 'claude-code' {
10189 interface BuiltinToolResults {
10190 Agent: {
10191 agentId: string
10192 /** @internal Count of leading harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
10193 harnessNoteCount?: number
10194 /** @internal Count of trailing harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
10195 harnessTailCount?: number
10196 /** @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 */
10197 harnessSectionHash?: string
10198 agentType?: string
10199 /** @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) */
10200 handback?: "send" | "flagged" | "withheld"
10201 content: Array<{
10202 type: "text"
10203 text: string
10204 citations?: unknown[] | null
10205 }>
10206 resolvedModel?: string
10207 modelsUsed?: string[]
10208 totalToolUseCount: number
10209 totalDurationMs: number
10210 totalTokens: number
10211 usage: {
10212 input_tokens: number
10213 output_tokens: number
10214 cache_creation_input_tokens: number | null
10215 cache_read_input_tokens: number | null
10216 server_tool_use: {
10217 web_search_requests: number
10218 web_fetch_requests: number
10219 } | null
10220 service_tier: string | null
10221 cache_creation: {
10222 ephemeral_1h_input_tokens: number
10223 ephemeral_5m_input_tokens: number
10224 } | null
10225 inference_geo?: string | null
10226 speed?: string | null
10227 iterations?: unknown
10228 output_tokens_details?: {
10229 thinking_tokens?: number | null
10230 } | null
10231 }
10232 toolStats?: {
10233 readCount: number
10234 searchCount: number
10235 bashCount: number
10236 editFileCount: number
10237 linesAdded: number
10238 linesRemoved: number
10239 otherToolCount: number
10240 frameCount?: number
10241 }
10242 status: "completed"
10243 prompt: string
10244 worktreePath?: string
10245 worktreeBranch?: string
10246 } | {
10247 status: "async_launched"
10248 isAsync?: true
10249 /** The ID of the async agent */
10250 agentId: string
10251 /** The description of the task */
10252 description: string
10253 /** Model in use at the backgrounding transition (a pre-background swap is reflected here) */
10254 resolvedModel?: string
10255 /** Ordered distinct models used before backgrounding (length > 1 means a mid-run swap) */
10256 modelsUsed?: string[]
10257 /** The prompt for the agent */
10258 prompt: string
10259 /** Path to the output file for checking agent progress */
10260 outputFile: string
10261 /** Whether the calling agent has Read/Bash tools to check progress */
10262 canReadOutputFile?: boolean
10263 } | {
10264 status: "remote_launched"
10265 /** The ID of the remote agent task */
10266 taskId: string
10267 /** The URL of the cloud session */
10268 sessionUrl: string
10269 /** The description of the task */
10270 description: string
10271 /** The prompt for the agent */
10272 prompt: string
10273 /** Path to the output file for checking agent progress */
10274 outputFile: string
10275 }
10276 Bash: {
10277 /** The standard output of the command */
10278 stdout: string
10279 /** The standard error output of the command */
10280 stderr: string
10281 /** Path to raw output file for large MCP tool outputs */
10282 rawOutputPath?: string
10283 /** Whether the command was interrupted */
10284 interrupted: boolean
10285 /** Flag to indicate if stdout contains image data */
10286 isImage?: boolean
10287 /** ID of the background task if command is running in background */
10288 backgroundTaskId?: string
10289 /** True if the user manually backgrounded the command with Ctrl+B */
10290 backgroundedByUser?: boolean
10291 /** @internal True if a plugin's turn abort moved the running command to the background */
10292 backgroundedByTurnAbort?: boolean
10293 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
10294 backgroundedToDeliverMessage?: boolean
10295 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
10296 timedOutAfterMs?: number
10297 /** Model-facing note that the session cwd was not changed by a backgrounded command containing a directory-change builtin (cd/pushd/popd/chdir) */
10298 backgroundCwdHint?: string
10299 /** 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) */
10300 backgroundEndsWithFinalResponse?: true
10301 /** Flag to indicate if sandbox mode was overridden */
10302 dangerouslyDisableSandbox?: boolean
10303 /** Semantic interpretation for non-error exit codes with special meaning */
10304 returnCodeInterpretation?: string
10305 /** Whether the command is expected to produce no output on success */
10306 noOutputExpected?: boolean
10307 /** Structured content blocks */
10308 structuredContent?: unknown[]
10309 /** Path to the persisted full output in tool-results dir (set when output is too large for inline) */
10310 persistedOutputPath?: string
10311 /** Total size of the output in bytes (set when output is too large for inline) */
10312 persistedOutputSize?: number
10313 /** Model-facing note listing readFileState entries whose mtime bumped during this command (set when WRITE_COMMAND_MARKERS matches) */
10314 staleReadFileStateHint?: string
10315 /** Model-facing system-reminder appended when a gh command reports a GitHub API rate-limit error */
10316 ghRateLimitHint?: string
10317 /** 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. */
10318 gitOperation?: {
10319 commit?: {
10320 sha: string
10321 kind: "committed" | "amended" | "cherry-picked"
10322 branch?: string
10323 }
10324 push?: {
10325 branch: string
10326 }
10327 branch?: {
10328 ref: string
10329 action: "merged" | "rebased"
10330 }
10331 pr?: {
10332 number: number
10333 url?: string
10334 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
10335 }
10336 }
10337 /** @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. */
10338 bashEditDiff?: {
10339 files: {
10340 filePath: string
10341 hunks: {
10342 oldStart: number
10343 oldLines: number
10344 newStart: number
10345 newLines: number
10346 lines: string[]
10347 }[]
10348 created?: true
10349 deleted?: true
10350 }[]
10351 moreFiles: number
10352 changedFiles?: string[]
10353 unavailable?: true
10354 skipped?: true
10355 shared?: true
10356 }
10357 }
10358 CronCreate: {
10359 id: string
10360 humanSchedule: string
10361 recurring: boolean
10362 durable?: boolean
10363 }
10364 CronDelete: {
10365 id: string
10366 }
10367 CronList: {
10368 jobs: {
10369 id: string
10370 cron: string
10371 humanSchedule: string
10372 prompt: string
10373 recurring?: boolean
10374 durable?: boolean
10375 }[]
10376 }
10377 Edit: {
10378 /** The file path that was edited */
10379 filePath: string
10380 /** The original string that was replaced */
10381 oldString: string
10382 /** The new string that replaced it */
10383 newString: string
10384 /** The original file contents before editing */
10385 originalFile: string | null
10386 /** Diff patch showing the changes */
10387 structuredPatch: {
10388 oldStart: number
10389 oldLines: number
10390 newStart: number
10391 newLines: number
10392 lines: string[]
10393 }[]
10394 /** Whether the user modified the proposed changes */
10395 userModified: boolean
10396 /** Whether all occurrences were replaced */
10397 replaceAll: boolean
10398 gitDiff?: {
10399 filename: string
10400 status: "modified" | "added"
10401 additions: number
10402 deletions: number
10403 changes: number
10404 patch: string
10405 /** GitHub owner/repo when available */
10406 repository?: string | null
10407 }
10408 /** True when the edit was held for the machine owner to review instead of written; the file is unchanged */
10409 staged?: boolean
10410 }
10411 EnterWorktree: {
10412 worktreePath: string
10413 worktreeBranch?: string
10414 message: string
10415 }
10416 ExitWorktree: {
10417 action: "keep" | "remove"
10418 originalCwd: string
10419 worktreePath: string
10420 worktreeBranch?: string
10421 tmuxSessionName?: string
10422 discardedFiles?: number
10423 discardedCommits?: number
10424 message: string
10425 }
10426 ListAgents: {
10427 /** Formatted list of reachable agents */
10428 listing: string
10429 }
10430 NotebookEdit: {
10431 /** The new source code that was written to the cell */
10432 new_source: string
10433 /** The previous cell source (replace/delete only). Enables cell-relative diff rendering without re-reading the notebook. */
10434 old_source?: string
10435 /** The ID of the cell that was edited */
10436 cell_id?: string
10437 /** The type of the cell */
10438 cell_type: "code" | "markdown"
10439 /** The programming language of the notebook */
10440 language: string
10441 /** The edit mode that was used */
10442 edit_mode: string
10443 /** Error message if the operation failed */
10444 error?: string
10445 /** The path to the notebook file */
10446 notebook_path: string
10447 /** The original notebook content before modification */
10448 original_file: string
10449 /** The updated notebook content after modification */
10450 updated_file: string
10451 }
10452 PowerShell: {
10453 /** The standard output of the command */
10454 stdout: string
10455 /** The standard error output of the command */
10456 stderr: string
10457 /** Whether the command was interrupted */
10458 interrupted: boolean
10459 /** Semantic interpretation for non-error exit codes with special meaning */
10460 returnCodeInterpretation?: string
10461 /** Flag to indicate if stdout contains image data */
10462 isImage?: boolean
10463 /** Path to persisted full output when too large for inline */
10464 persistedOutputPath?: string
10465 /** Total output size in bytes when persisted */
10466 persistedOutputSize?: number
10467 /** ID of the background task if command is running in background */
10468 backgroundTaskId?: string
10469 /** True if the user manually backgrounded the command with Ctrl+B */
10470 backgroundedByUser?: boolean
10471 /** @internal True if a plugin's turn abort moved the running command to the background */
10472 backgroundedByTurnAbort?: boolean
10473 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
10474 backgroundedToDeliverMessage?: boolean
10475 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
10476 timedOutAfterMs?: number
10477 /** 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) */
10478 backgroundEndsWithFinalResponse?: true
10479 /** 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. */
10480 gitOperation?: {
10481 commit?: {
10482 sha: string
10483 kind: "committed" | "amended" | "cherry-picked"
10484 branch?: string
10485 }
10486 push?: {
10487 branch: string
10488 }
10489 branch?: {
10490 ref: string
10491 action: "merged" | "rebased"
10492 }
10493 pr?: {
10494 number: number
10495 url?: string
10496 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
10497 }
10498 }
10499 }
10500 Read: {
10501 type: "text"
10502 file: {
10503 /** The path to the file that was read */
10504 filePath: string
10505 /** The content of the file */
10506 content: string
10507 /** Number of lines in the returned content */
10508 numLines: number
10509 /** The starting line number */
10510 startLine: number
10511 /** Total number of lines in the file */
10512 totalLines: number
10513 /** 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). */
10514 truncatedByTokenCap?: boolean
10515 }
10516 /** Set when this Read completed a saved Artifact source file: the Artifact and the version of it that now counts as viewed. */
10517 artifactRead?: {
10518 slug: string
10519 ver: string
10520 }
10521 } | {
10522 type: "image"
10523 file: {
10524 /** Base64-encoded image data */
10525 base64: string
10526 /** The MIME type of the image */
10527 type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
10528 /** Original file size in bytes */
10529 originalSize: number
10530 /** Image dimension info for coordinate mapping */
10531 dimensions?: {
10532 /** Original image width in pixels */
10533 originalWidth?: number
10534 /** Original image height in pixels */
10535 originalHeight?: number
10536 /** Displayed image width in pixels (after resizing) */
10537 displayWidth?: number
10538 /** Displayed image height in pixels (after resizing) */
10539 displayHeight?: number
10540 }
10541 }
10542 } | {
10543 type: "notebook"
10544 file: {
10545 /** The path to the notebook file */
10546 filePath: string
10547 /** Array of notebook cells */
10548 cells: unknown[]
10549 }
10550 } | {
10551 type: "pdf"
10552 file: {
10553 /** The path to the PDF file */
10554 filePath: string
10555 /** Base64-encoded PDF data */
10556 base64: string
10557 /** Original file size in bytes */
10558 originalSize: number
10559 }
10560 } | {
10561 type: "parts"
10562 file: {
10563 /** The path to the PDF file */
10564 filePath: string
10565 /** Original file size in bytes */
10566 originalSize: number
10567 /** Number of pages extracted */
10568 count: number
10569 /** Directory containing extracted page images */
10570 outputDir: string
10571 }
10572 /** Document page number of the first extracted page (1 when no range was requested); labels the page images in the model-facing tool_result */
10573 firstPage?: number
10574 /** 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 */
10575 pages?: Array<{
10576 /** Base64-encoded page image; empty when the page could not be processed */
10577 base64: string
10578 /** The MIME type of the image */
10579 mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
10580 /** Why the page could not be processed as an image; set only when base64 is empty */
10581 error?: string
10582 }>
10583 } | {
10584 type: "file_unchanged"
10585 file: {
10586 /** The path to the file */
10587 filePath: string
10588 }
10589 /** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result */
10590 source?: "seeded"
10591 }
10592 ReportFindings: {
10593 /** Number of findings reported */
10594 count: number
10595 /** Effort level the review ran at */
10596 level?: "low" | "medium" | "high" | "xhigh" | "max"
10597 /** Echoed for the result body */
10598 findings: Array<{
10599 /** Repo-relative path of the file the finding is in */
10600 file: string
10601 /** 1-indexed line the finding anchors to */
10602 line?: number
10603 /** One-sentence statement of the defect */
10604 summary: string
10605 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
10606 short_summary?: string
10607 /** Concrete inputs/state → wrong output/crash */
10608 failure_scenario: string
10609 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
10610 category?: string
10611 /** Set when a verify pass ran; absent on inline-only reviews */
10612 verdict?: "CONFIRMED" | "PLAUSIBLE"
10613 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
10614 outcome?: "fixed" | "skipped" | "no_change_needed"
10615 }>
10616 }
10617 ScheduleWakeup: {
10618 /** Epoch ms timestamp when the next wakeup will fire */
10619 scheduledFor: number
10620 /** Actual delay used after clamping to runtime bounds */
10621 clampedDelaySeconds: number
10622 /** True if the requested delaySeconds was outside [60, 3600] */
10623 wasClamped: boolean
10624 /** True when the model ended the loop via `stop: true` */
10625 stopped?: boolean
10626 /** How many pending dynamic-loop wakeups stop:true cancelled. 0 means nothing was pending — a recurring /loop cron is not cancelled by stop:true. */
10627 cancelledWakeups?: number
10628 }
10629 SendMessage: unknown
10630 Skill: {
10631 /** Whether the skill is valid */
10632 success: boolean
10633 /** The name of the skill */
10634 commandName: string
10635 /** Tools allowed by this skill */
10636 allowedTools?: string[]
10637 /** Resolved model the skill turn runs on when a frontmatter model override took effect; omitted otherwise */
10638 model?: string
10639 /** Execution status */
10640 status?: "inline"
10641 /** True when the skill instructions were loaded read-only (nothing was executed) */
10642 readOnly?: boolean
10643 } | {
10644 /** Whether the skill completed successfully */
10645 success: boolean
10646 /** The name of the skill */
10647 commandName: string
10648 /** Execution status */
10649 status: "forked"
10650 /** The ID of the sub-agent that executed the skill */
10651 agentId: string
10652 /** The result from the forked skill execution */
10653 result: string
10654 /** True when the sub-agent was launched in the background: `result` describes the launch, and the skill outcome arrives later as a task notification. */
10655 background?: boolean
10656 }
10657 TaskOutput: unknown
10658 TaskStop: {
10659 /** Status message about the operation */
10660 message: string
10661 /** The ID of the task that was stopped */
10662 task_id: string
10663 /** The type of the task that was stopped */
10664 task_type: string
10665 /** The command or description of the stopped task */
10666 command?: string
10667 }
10668 ToolSearch: {
10669 matches: string[]
10670 query: string
10671 total_deferred_tools: number
10672 pending_mcp_servers?: string[]
10673 failed_mcp_servers?: {
10674 name: string
10675 errorCode?: string
10676 error?: string
10677 }[]
10678 }
10679 WebFetch: {
10680 /** Size of the fetched content in bytes */
10681 bytes: number
10682 /** HTTP response code */
10683 code: number
10684 /** HTTP response code text */
10685 codeText: string
10686 /** Processed result from applying the prompt to the content */
10687 result: string
10688 /** Time taken to fetch and process the content */
10689 durationMs: number
10690 /** The URL that was fetched */
10691 url: string
10692 artifactRead?: {
10693 slug: string
10694 ver?: string
10695 seeded?: false
10696 }
10697 }
10698 WebSearch: {
10699 /** The search query that was executed */
10700 query: string
10701 /** Search results and/or text commentary from the model */
10702 results: Array<{
10703 /** ID of the tool use */
10704 tool_use_id: string
10705 /** Array of search hits */
10706 content: Array<{
10707 /** The title of the search result */
10708 title: string
10709 /** The URL of the search result */
10710 url: string
10711 }>
10712 } | string>
10713 /** Time taken to complete the search operation */
10714 durationSeconds: number
10715 /** Number of web searches performed */
10716 searchCount?: number
10717 }
10718 Workflow: {
10719 status: "async_launched" | "remote_launched"
10720 taskId: string
10721 /** 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. */
10722 taskType?: "local_workflow" | "remote_agent"
10723 /** 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. */
10724 workflowName?: string
10725 /** 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. */
10726 runId?: string
10727 summary?: string
10728 /** Directory where subagent transcripts are written during execution */
10729 transcriptDir?: string
10730 /** Path to the persisted workflow script for this invocation. Editable via Write/Edit; pass back as `scriptPath` to re-run without resending the script. */
10731 scriptPath?: string
10732 /** CCR session URL when status is remote_launched */
10733 sessionUrl?: string
10734 /** Non-blocking heads-up (e.g. local git state diverges from the pushed branch the cloud session will clone) */
10735 warning?: string
10736 /** Set if syntax check failed */
10737 error?: string
10738 }
10739 Write: {
10740 /** Whether a new file was created or an existing file was updated */
10741 type: "create" | "update"
10742 /** The path to the file that was written */
10743 filePath: string
10744 /** The content that was written to the file */
10745 content: string
10746 /** 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) */
10747 structuredPatch: {
10748 oldStart: number
10749 oldLines: number
10750 newStart: number
10751 newLines: number
10752 lines: string[]
10753 }[]
10754 /** The original file content before the write (null for new files, or when the previous content was too large to include) */
10755 originalFile: string | null
10756 gitDiff?: {
10757 filename: string
10758 status: "modified" | "added"
10759 additions: number
10760 deletions: number
10761 changes: number
10762 patch: string
10763 /** GitHub owner/repo when available */
10764 repository?: string | null
10765 }
10766 /** True when the user edited the proposed content in the permission dialog before accepting */
10767 userModified?: boolean
10768 /** True when the write was held for the machine owner to review instead of written; the file is unchanged */
10769 staged?: boolean
10770 }
10771 }
10772}