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,552 lines · 389.1 KBRaw
1// Written by Claude Code 2.1.271.
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 ]` (or `1: label` when `plain`), a desktop a
638 * native button; a click, a `hotkey`, the chord for its `action`, or Enter
639 * while it has the focus raises `ui.press`, whose bottom is `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.
672 */
673 plain?: true;
674 /**
675 * The label drawn dim at rest, as `Text`'s `dimColor`, and at full strength
676 * under the pointer or the focus: a secondary control, a path in a list.
677 */
678 dimColor?: boolean;
679 /**
680 * Label style overrides (the `Text` set) applied by the surface while the
681 * nearest enclosing keyed `Box`, or given a `scope` its group, is hovered.
682 *
683 * No hook runs and nothing crosses to the plugin; under the pointer itself
684 * the button inverts as it always has. Refused outside a keyed Box unless
685 * it names a `scope`.
686 */
687 hover?: TextHoverProps;
688 /**
689 * What the press runs, in the plugin's own environment: the bottom of the
690 * `ui.press` chain. The host holds only a handle, for the drawing's life.
691 */
692 onPress: () => void;
693 };
694
695 /**
696 * The handler `on(...).catch(handler)` takes for a hook of type `F`: the
697 * hook's `($, e, next)`, run afresh when it throws, misreturns or overruns.
698 *
699 * `next` carries `error` and `called` (Caught) and is replay-safe; a return
700 * within the grace is the hook's result, `undefined` the hook absent. On a
701 * streaming event the handler is a generator too, continuing the stream.
702 */
703 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;
704
705 /**
706 * What `next` carries into a `.catch` handler and nowhere else: why the
707 * hook failed, and whether it had called `next` before it did.
708 *
709 * There `next` is replay-safe: when `called`, `next(e)` resolves to what the
710 * hook's last call settled to, nothing beneath running again, the argument
711 * unread; when not, it runs the hooks beneath once and a later call replays.
712 */
713 export type Caught = {
714 /**
715 * Why the hook failed (HookFailure); undefined on an ordinary hook's
716 * `next`, so its presence says a handler is running.
717 */
718 readonly error: HookFailure;
719 /**
720 * True when the failed hook had called `next()` or `next.to()` at least
721 * once, settled or in flight; the handler runs once that call settled.
722 */
723 readonly called: boolean;
724 };
725
726 /**
727 * What a hook on streaming event `N` yields, and what its `next(e)` yields
728 * to it (ChunkOf by name).
729 */
730 export type Chunk<N extends StreamingEventName = StreamingEventName> = ChunkOf[N];
731
732 /**
733 * The chunk type of each streaming event, by name: what its stream yields.
734 */
735 export type ChunkOf = {
736 /**
737 * One piece of the model's response (TurnStepChunk).
738 */
739 'turn.step': TurnStepChunk;
740 };
741
742 /**
743 * What every `turn.step` chunk may carry: the engine's handle on the item
744 * of its own stream the chunk was read off, absent on a chunk a hook made.
745 *
746 * A hook that passes a chunk on, or rewrites it by spreading it, keeps the
747 * handle, and whatever it left unchanged reaches the engine as the engine
748 * streamed it; a chunk built afresh has none and is taken at its word.
749 */
750 type ChunkRef = {
751 /**
752 * The engine's handle on its own streamed item; opaque, this step's only.
753 */
754 ref?: number;
755 };
756
757 /**
758 * The name of a classic hook event as a function-hooks event: the settings
759 * hook's own name under `classic` (`classic.Stop`, `classic.PreToolUse`).
760 */
761 export type ClassicEventName = `classic.${ClassicHookEvent}`;
762
763 /**
764 * The classic (settings) hook events, one per classic event name: `e` is
765 * what the classic hook receives on stdin for that event.
766 *
767 * The chain is [managed settings hooks, ...hooks modules, the other settings
768 * hooks as core], so a managed block ends it above every module. In shape
769 * `classic.PreToolUse` alone differs: its `e` is ToolCallEnvelope, no more.
770 */
771 export type ClassicEventOf = {
772 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? ToolCallEnvelope : ClassicHookInputs[E];
773 };
774
775 /**
776 * The name of a classic hook event: `PreToolUse`, `Stop`, and the rest.
777 */
778 export type ClassicHookEvent = HookInput['hook_event_name'];
779
780 /**
781 * What a classic hook receives on stdin for each event, by event name: the
782 * Agent SDK's `<Event>HookInput`.
783 */
784 export type ClassicHookInputs = {
785 [I in HookInput as I['hook_event_name']]: I;
786 };
787
788 /**
789 * Everything a classic hook event's answer can carry, named as the classic
790 * hook's JSON output names it; each event reads its subset (ClassicResultOf).
791 *
792 * The settings hooks below fold into one of these (last write wins, contexts
793 * concatenate); a hooks module returns `next(e)`, a copy with fields changed,
794 * or its own. A field of the wrong shape fails the hook, which is skipped.
795 */
796 export type ClassicResult = {
797 /**
798 * `decision: "block"` with this text as `reason` (a command hook's exit
799 * code 2): the event's block, veto or re-prompt.
800 */
801 block?: string;
802 /**
803 * `continue: false`: the session stops after this event.
804 */
805 preventContinuation?: true;
806 /**
807 * Shown when `preventContinuation` stops the session (`stopReason`).
808 */
809 stopReason?: string;
810 /**
811 * `hookSpecificOutput.additionalContext`, one entry per hook: text handed
812 * to the model with the event.
813 */
814 additionalContext?: string[];
815 /**
816 * `hookSpecificOutput.sessionTitle` (UserPromptSubmit, SessionStart).
817 */
818 sessionTitle?: string;
819 /**
820 * `hookSpecificOutput.suppressOriginalPrompt` (UserPromptSubmit,
821 * UserPromptExpansion).
822 */
823 suppressOriginalPrompt?: true;
824 /**
825 * `hookSpecificOutput.initialUserMessage` (SessionStart).
826 */
827 initialUserMessage?: string;
828 /**
829 * `hookSpecificOutput.watchPaths` (SessionStart).
830 */
831 watchPaths?: string[];
832 /**
833 * `hookSpecificOutput.reloadSkills` (SessionStart).
834 */
835 reloadSkills?: true;
836 /**
837 * `hookSpecificOutput.permissionDecision` (PreModelSwitch).
838 */
839 permissionDecision?: 'allow' | 'deny' | 'ask';
840 /**
841 * `hookSpecificOutput.permissionDecisionReason` (PreModelSwitch).
842 */
843 permissionDecisionReason?: string;
844 /**
845 * `hookSpecificOutput.decision` (PermissionRequest).
846 */
847 decision?: PermissionRequestDecision;
848 /**
849 * `hookSpecificOutput.updatedToolOutput` (PostToolUse): replaces what the
850 * model sees of the tool's result.
851 */
852 updatedToolOutput?: unknown;
853 /**
854 * `hookSpecificOutput.updatedMCPToolOutput` (PostToolUse, MCP tools only).
855 */
856 updatedMCPToolOutput?: unknown;
857 /**
858 * `hookSpecificOutput.retry` (PermissionDenied).
859 */
860 retry?: true;
861 /**
862 * `hookSpecificOutput.displayContent` (MessageDisplay).
863 */
864 displayContent?: string;
865 /**
866 * `hookSpecificOutput.worktreePath` (WorktreeCreate; a command hook prints
867 * it): the worktree the hook created, absolute or relative to its cwd.
868 *
869 * Left unset, the session creates its git worktree as it would unhooked.
870 */
871 worktreePath?: string;
872 };
873
874 /**
875 * The event-specific fields of ClassicResult each classic event reads (its
876 * `hookSpecificOutput`), by event; an event absent here reads none of them.
877 *
878 * `block`, `preventContinuation` and `stopReason` are every event's.
879 */
880 export type ClassicResultFields = {
881 UserPromptSubmit: 'additionalContext' | 'sessionTitle' | 'suppressOriginalPrompt';
882 UserPromptExpansion: 'additionalContext' | 'suppressOriginalPrompt';
883 SessionStart: 'additionalContext' | 'initialUserMessage' | 'sessionTitle' | 'watchPaths' | 'reloadSkills';
884 Setup: 'additionalContext';
885 PreModelSwitch: 'permissionDecision' | 'permissionDecisionReason';
886 PostModelSwitch: 'additionalContext';
887 SubagentStart: 'additionalContext';
888 PostToolUse: 'additionalContext' | 'updatedToolOutput' | 'updatedMCPToolOutput';
889 PostToolUseFailure: 'additionalContext';
890 PostToolBatch: 'additionalContext';
891 Stop: 'additionalContext';
892 SubagentStop: 'additionalContext';
893 PermissionDenied: 'retry';
894 PermissionRequest: 'decision';
895 MessageDisplay: 'displayContent';
896 WorktreeCreate: 'worktreePath';
897 };
898
899 /**
900 * What each classic hook event's hook returns and its `next(e)` resolves to:
901 * the event's own subset of ClassicResult.
902 *
903 * `classic.PreToolUse` keeps its `allow` / `ask` / `deny` result
904 * (PreToolUseResult).
905 */
906 export type ClassicResultOf = {
907 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? PreToolUseResult : Pick<ClassicResult, 'block' | 'preventContinuation' | 'stopReason' | (E extends keyof ClassicResultFields ? ClassicResultFields[E] : never)>;
908 };
909
910 /**
911 * Options of `$.model.classify`.
912 */
913 export type ClassifyOptions = {
914 /**
915 * An alias (`haiku`) or a full model id; default the engine's small fast
916 * model.
917 */
918 model?: string;
919 };
920
921 /**
922 * The element table a surface module draws with, `surface.elements`: the
923 * terminal's (Elements) less `Client` (none nests) and `Raster` (needs `$`).
924 *
925 * What `$.ui.resolve(e)` is to a hooks module, with no `$` and no hook
926 * between: `const { Box, Text } = surface.elements`, then `<Box>`. A Button,
927 * Input or Select keeps its handler here and still raises `ui.press` etc.
928 */
929 export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster'>;
930
931 /**
932 * One key the person pressed while a `Client` had the focus, as
933 * `surface.onKey` hands it. Escape never arrives: it returns the focus.
934 */
935 export type ClientKeyEvent = {
936 /**
937 * A special key's name (`up`, `down`, `left`, `right`, `return`, `tab`,
938 * `backspace`, `delete`, `pageup`, `home`, ...) or the character typed.
939 */
940 key: string;
941 /**
942 * Modifier keys held with it, each present only when true.
943 */
944 ctrl?: true;
945 shift?: true;
946 meta?: true;
947 };
948
949 /**
950 * The component a surface module exports (default, or its one PascalCase
951 * export): from props and surface to the tree drawn (no nested `Client`).
952 *
953 * Runs in the plugin's surface environment on the drawing thread, under a
954 * time budget per call; a throw or an overrun unmounts the instance and
955 * draws one line naming the plugin and the module in its place.
956 */
957 export type ClientModule<P extends JsonValue = JsonValue, S = unknown> = (props: P, surface: ClientSurface<S>) => RenderElement;
958
959 /**
960 * One pointer event over a `Client`'s region, as `surface.onPointer` hands
961 * it: cell coordinates relative to the region's top-left corner.
962 *
963 * After a `down` in the region the instance holds the pointer until the
964 * `up`: every `move` reaches it, past the edges too (negative, or beyond
965 * `columns`/`rows`), and the transcript neither selects nor scrolls.
966 */
967 export type ClientPointerEvent = {
968 type: ClientPointerType;
969 /**
970 * The column under the pointer, 0 at the region's left edge; on `enter`
971 * and `leave`, the last column a move reported.
972 */
973 x: number;
974 /**
975 * The row under the pointer, 0 at the region's top edge.
976 */
977 y: number;
978 /**
979 * Which button is down (`down`, `move` while held) or came up (`up`);
980 * absent on a hover `move`, `enter` and `leave`.
981 */
982 button?: 'left' | 'middle' | 'right';
983 /**
984 * Modifier keys the terminal reported held, each present only when true.
985 */
986 shift?: true;
987 alt?: true;
988 ctrl?: true;
989 };
990
991 /**
992 * What the pointer did over a `Client`'s region: a button went down, the
993 * pointer moved, the button came up, or the pointer crossed the region's edge.
994 */
995 export type ClientPointerType = 'down' | 'move' | 'up' | 'enter' | 'leave';
996
997 /**
998 * The props of `Client`: which of the plugin's surface modules draws here,
999 * under what key, with what data, in how much room.
1000 */
1001 export type ClientProps = {
1002 /**
1003 * The instance's address within the drawing: two `Client`s of one plugin in
1004 * one tree take two keys. What `e.element` carries at `ui.message`.
1005 *
1006 * The engine keeps the instance (its local state, its timers) across the
1007 * plugin's redraws while a `Client` under this key stays in the tree.
1008 */
1009 key: string;
1010 /**
1011 * The surface module's path, a string literal relative to this file:
1012 * `module: "./<name>.tsx"` (or `.jsx`, `.ts`, `.js`, `.mjs`).
1013 *
1014 * Read off the source: a variable there is refused at load, as is a path
1015 * outside the plugin or naming no file. Its default export draws, else
1016 * its one PascalCase export; loaded, the tree carries the plugin's path.
1017 */
1018 module: string;
1019 /**
1020 * Plain data (JsonValue) handed to the module function; a new value on a
1021 * redraw reaches the running instance, its state kept.
1022 *
1023 * Bounded as a tree's text is; not a channel for closures.
1024 * Typed `unknown` so a matcher over a tree stays shallow.
1025 */
1026 props?: unknown;
1027 /**
1028 * Columns the instance's region takes: a count, or a percentage of the
1029 * parent. Absent, the region is as wide as what the module draws.
1030 */
1031 width?: number | string;
1032 /**
1033 * Rows the instance's region takes: a count, or a percentage of the parent.
1034 * Absent, the region is as tall as what the module draws.
1035 */
1036 height?: number | string;
1037 /**
1038 * How the region grows into free room along the parent's direction, as a
1039 * Box's `flexGrow`.
1040 */
1041 flexGrow?: number;
1042 };
1043
1044 /**
1045 * What a surface module's function receives as its second argument: its
1046 * elements, the instance's local state, its region, input, clock and port.
1047 *
1048 * Called again (same `surface`, same `state`) on new props, after
1049 * `setState`, and on a resize; what it returns is drawn in the region. No
1050 * `$` here: the hooks module has it, and `post` is the way to reach it.
1051 */
1052 export type ClientSurface<S = unknown> = {
1053 /**
1054 * The surface's element table (ClientElements), the tags the module draws
1055 * with: `const { Box, Text } = surface.elements`. No `Client` in it.
1056 */
1057 readonly elements: ClientElements;
1058 /**
1059 * The instance's local state: `undefined` until the first `setState`.
1060 * Kept across the plugin's redraws; dropped with the instance.
1061 */
1062 readonly state: S | undefined;
1063 /**
1064 * Replaces the local state and schedules one more call of the function on
1065 * the next frame; several calls before it coalesce into one redraw.
1066 */
1067 setState: (next: S) => void;
1068 /**
1069 * The region's width in cells, as last laid out (0 before the first
1070 * layout).
1071 */
1072 readonly columns: number;
1073 /**
1074 * The region's height in cells, as last laid out (0 before the first
1075 * layout).
1076 */
1077 readonly rows: number;
1078 /**
1079 * Calls `fn` every `ms` milliseconds on the surface's frame clock until
1080 * the returned function is called or the instance unmounts.
1081 *
1082 * Start it once (while `state` is still undefined), not on every call.
1083 */
1084 every: (ms: number, fn: () => void) => () => void;
1085 /**
1086 * Sets the instance's pointer listener (one; a later call replaces it)
1087 * and returns what clears it. See ClientPointerEvent for capture.
1088 */
1089 onPointer: (fn: (event: ClientPointerEvent) => void) => () => void;
1090 /**
1091 * Sets the instance's key listener (one; a later call replaces it),
1092 * reached while a click has given it the focus; Escape returns that.
1093 */
1094 onKey: (fn: (event: ClientKeyEvent) => void) => () => void;
1095 /**
1096 * Sends plain data to the plugin's hooks module: `e.data` of a
1097 * `ui.message` only that plugin's hooks see, one per frame at most.
1098 *
1099 * A later post in the same frame replaces an undelivered one; a hook
1100 * answering `{ props }` hands this instance its next props.
1101 */
1102 post: (data: JsonValue) => void;
1103 };
1104
1105 /**
1106 * The argument of the `$.clock` waits (`sleep`, `after`, `every`): how long,
1107 * in milliseconds, before the dispatch resolves.
1108 */
1109 type ClockWait = {
1110 /**
1111 * The wait, a non-negative number of milliseconds.
1112 */
1113 ms: number;
1114 };
1115
1116 /**
1117 * The props of `Code`, source text every surface draws with the engine's own
1118 * highlighter: coloured tokens, a line gutter on request, or a unified diff.
1119 *
1120 * A leaf: no children. `source` is the element's data as a string is a
1121 * Text's, bounded and free of control characters the same way; the colour
1122 * on screen is the engine's, never the plugin's.
1123 */
1124 export type CodeProps = {
1125 /**
1126 * The text drawn: source code, or under `format: 'diff'` one or more
1127 * unified-diff hunks.
1128 *
1129 * At most 10000 characters; tab and newline are the only control
1130 * characters it may hold.
1131 */
1132 source: string;
1133 /**
1134 * A highlighter language id or alias (`typescript`, `ts`, `py`), a
1135 * plugin-contributed grammar's included.
1136 *
1137 * Absent, the language is inferred from `path`; when neither resolves,
1138 * the text is drawn plain.
1139 */
1140 language?: string;
1141 /**
1142 * A file path the language is inferred from when `language` is absent:
1143 * its extension or name, else a shebang on the first line.
1144 *
1145 * Drawn nowhere and never read: nothing touches the disk.
1146 */
1147 path?: string;
1148 /**
1149 * The 1-based number of the first line of `source`: present, a dim
1150 * right-aligned gutter numbers the lines from it; absent, no gutter.
1151 *
1152 * Ignored under `format: 'diff'`, whose hunks carry their own numbers.
1153 */
1154 startLine?: number;
1155 /**
1156 * `'source'` (the default) draws `source` as code; `'diff'` reads it as
1157 * unified-diff hunks and draws gutters, markers, add and remove colouring.
1158 *
1159 * A hunk is `@@ -a,b +c,d @@` then lines starting ` `, `+` or `-`; a
1160 * leading `---`/`+++` pair and `\ No newline at end of file` are read
1161 * past. A source that does not parse as hunks is refused.
1162 */
1163 format?: 'source' | 'diff';
1164 /**
1165 * What a line wider than the room does, in Text's `wrap` vocabulary:
1166 * `'wrap'` (the default) continues it on rows under the gutter.
1167 *
1168 * `'truncate-end'` cuts it at the edge with an ellipsis; Text's other
1169 * spellings are refused, since a gutter leaves them no sense here.
1170 */
1171 wrap?: 'wrap' | 'truncate-end';
1172 };
1173
1174 /**
1175 * The input of `command.describe`: how one slash command presents in the
1176 * typeahead and `/help`, at the moment the engine lists it.
1177 */
1178 export type CommandDescribeInput = {
1179 /**
1180 * Names the command without its slash; the key a matcher narrows on. A
1181 * rewrite is refused.
1182 */
1183 command: string;
1184 /**
1185 * The one-line description the menu shows, as the command declares it.
1186 */
1187 description: string;
1188 /**
1189 * The hint drawn dim after the name (`[name]`), when the command has one.
1190 */
1191 argumentHint?: string;
1192 /**
1193 * Whether the typeahead and `/help` leave the command out; a hidden
1194 * command still runs when typed in full.
1195 */
1196 isHidden: boolean;
1197 /**
1198 * Whether the command declares it runs at once when typed mid-turn,
1199 * instead of waiting for the turn to end.
1200 *
1201 * One that decides per invocation reads false. Read only: not part of
1202 * what a hook answers, and a rewrite is refused.
1203 */
1204 immediate: boolean;
1205 /**
1206 * Who provides this command: the plugin and its tier; `{ plugin: "engine",
1207 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
1208 */
1209 provider: Origin;
1210 };
1211
1212 /**
1213 * What a `command.describe` hook returns: the description, hint and hidden
1214 * flag the menu uses; the name, `immediate` and `provider` stay as they were.
1215 */
1216 export type CommandDescribeResult = Omit<CommandDescribeInput, 'command' | 'immediate' | 'provider'>;
1217
1218 /**
1219 * One slash command as `$.command.list()` returns it.
1220 */
1221 export type CommandInfo = {
1222 /**
1223 * What the person runs it by, without the slash.
1224 */
1225 name: string;
1226 /**
1227 * The one line the typeahead shows for it.
1228 */
1229 description: string;
1230 /**
1231 * Where it comes from (CommandSource).
1232 */
1233 source: CommandSource;
1234 /**
1235 * Which plugin added it, when `source` is `plugin` and the engine knows:
1236 * the one that registered it, or whose manifest carries it.
1237 */
1238 plugin?: string;
1239 };
1240
1241 /**
1242 * Where a command's answer will show: which of the terminal's two layouts
1243 * the surface renders, and how wide it is when the command runs.
1244 *
1245 * A fact the engine stamps on `command.run`, so a command that draws (opens
1246 * a pane, prints a wide table) can suit the room it has: the fullscreen
1247 * layout docks a pane beside the transcript from 110 columns, the main
1248 * screen places it inline above the prompt at any width.
1249 */
1250 export type CommandPresentation = {
1251 /**
1252 * True under the fullscreen (alternate-screen) layout; false on the main
1253 * screen (`CLAUDE_CODE_NO_FLICKER=0`, tmux by default) and headless.
1254 */
1255 isFullscreen: boolean;
1256 /**
1257 * The terminal's width in cells as the command runs; 80 where no terminal
1258 * has measured (headless with no tty).
1259 */
1260 columns: number;
1261 };
1262
1263 /**
1264 * `command.run`'s input as a plugin's `$.command.run` takes it: `args` may
1265 * be left out (`/command`, bare); `origin` and `presentation` the engine sets.
1266 */
1267 export type CommandRunArgs = Omit<CommandRunInput, 'origin' | 'args' | 'presentation'> & {
1268 /**
1269 * Everything after the name, as the person would type it; left out, `""`.
1270 */
1271 args?: string;
1272 };
1273
1274 /**
1275 * The input of `command.run`: one slash command about to run, the way the
1276 * person typed it (`/name args`), and where the run came from.
1277 */
1278 export type CommandRunInput = {
1279 /**
1280 * Names the command without its slash (`compact`, `hello`), aliases and
1281 * folds resolved; the key a matcher narrows on. A rewrite is refused.
1282 */
1283 command: string;
1284 /**
1285 * Everything after the name, as typed (`""` when nothing was); a hook
1286 * rewrites it with `next({ ...e, args })`.
1287 */
1288 args: string;
1289 /**
1290 * Where the run came from, in `prompt.submit`'s words (PromptOrigin):
1291 * the person's Enter (`composer`), the bridge, the SDK, or a plugin.
1292 *
1293 * A plugin's `$.command.run` reads `{ kind: 'plugin', name }`. `next(e)`
1294 * passes it on as received.
1295 */
1296 origin: PromptOrigin;
1297 /**
1298 * Where the command's answer will show (CommandPresentation): the
1299 * fullscreen layout or the main screen, and the terminal's width.
1300 *
1301 * Pinned: the engine stamps it, `next(e)` passes it on, a rewrite that
1302 * leaves it out keeps it and one that changes it is refused.
1303 */
1304 presentation: CommandPresentation;
1305 };
1306
1307 /**
1308 * What a `command.run` hook returns and what `next(e)` and `$.command.run`
1309 * resolve to: the command's output text, when it has one.
1310 *
1311 * From core, `text` is what the command printed (a `local` command's
1312 * returned text; a panel command may print nothing) and `ref` names the
1313 * run. A hook's own answer without `next` runs no command: its `text` is
1314 * shown as the command's output, under the names of the plugins hooking
1315 * the command unless each is bundled with Claude Code, whose answer reads
1316 * as the built-in command's own.
1317 */
1318 export type CommandRunResult = {
1319 /**
1320 * The command's output as a transcript line, or undefined when the
1321 * command showed nothing as text (a panel, a prompt for the model).
1322 */
1323 text?: string;
1324 /**
1325 * Set by core on what `next(e)` resolves to: names the engine's run of
1326 * the command (its result stays on the host side).
1327 *
1328 * A hook that returns the object it got makes the engine use that run
1329 * verbatim. Absent on a hook's own `{ text }` and on `$.command.run`'s.
1330 */
1331 ref?: number;
1332 };
1333
1334 /**
1335 * Where a slash command comes from, as `$.command.list()` tells them apart.
1336 *
1337 * `builtin` ships with Claude Code; `plugin` is a plugin's markdown command,
1338 * skill or `$.command.register`; `user` is the user's or project's own
1339 * file; `mcp` an MCP server's prompt.
1340 */
1341 export type CommandSource = 'builtin' | 'plugin' | 'user' | 'mcp';
1342
1343 /**
1344 * What `$.command.register` takes: the slash command this plugin serves.
1345 */
1346 export type CommandSpec = {
1347 /**
1348 * The command's name without the slash (letters, digits, `_`, `-`; up to
1349 * 64); the person runs it as `/<name>`.
1350 */
1351 name: string;
1352 /**
1353 * The one line the typeahead and `/help` show for it.
1354 */
1355 description: string;
1356 /**
1357 * The hint drawn dim after the name (`[name]`), when it takes arguments.
1358 */
1359 argumentHint?: string;
1360 /**
1361 * Set so that `/<name>` typed while a turn is in flight runs at once
1362 * instead of waiting for the turn to end, as it does when left out.
1363 *
1364 * Its `command.run` hook then runs while a turn may still be streaming and
1365 * must not assume the turn's state (what the transcript holds, whether a
1366 * tool is mid-call); its `{ text }` prints as an idle run's does.
1367 */
1368 immediate?: true;
1369 };
1370
1371 type ConfigChangeHookInput = BaseHookInput & {
1372 hook_event_name: 'ConfigChange';
1373 source: 'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills';
1374 file_path?: string;
1375 };
1376
1377 /**
1378 * The input of `config.describe`: how one `/config` row presents, at the
1379 * moment the menu lists it (and for `$.config.list`).
1380 */
1381 export type ConfigDescribeInput = {
1382 /**
1383 * Names the row, as `config.set`'s `key` does; the key a matcher narrows
1384 * on. Pinned: a rewrite is refused.
1385 */
1386 key: string;
1387 /**
1388 * What the menu draws for the row, before its value.
1389 */
1390 label: string;
1391 /**
1392 * The help text beneath the label, when the row has one (a plugin
1393 * field's `description`); absent for the panel's own rows.
1394 */
1395 description?: string;
1396 /**
1397 * Whether the menu leaves the row out; a hidden row still answers
1398 * `$.config.set` and `/config key=value`.
1399 */
1400 isHidden: boolean;
1401 /**
1402 * Who owns the row, as `config.set`'s `provider`. Pinned.
1403 */
1404 provider: Origin;
1405 };
1406
1407 /**
1408 * What a `config.describe` hook returns: the label, help text and hidden
1409 * flag the menu uses; the key and provider stay as they were.
1410 */
1411 export type ConfigDescribeResult = Omit<ConfigDescribeInput, 'key' | 'provider'>;
1412
1413 /**
1414 * How a `/config` row takes its value: `boolean` toggles, `choice` picks one
1415 * of its `options`, `text` takes a string, `number` a number.
1416 */
1417 export type ConfigKind = 'boolean' | 'choice' | 'text' | 'number';
1418
1419 /**
1420 * Where a `config.set` came from, in `prompt.submit`'s words: the person
1421 * in the `/config` menu (`composer`), the bridge, or a plugin, named.
1422 *
1423 * Set by the engine; `next(e)` passes it on as received and none sets it.
1424 */
1425 export type ConfigOrigin = {
1426 /**
1427 * The person's own change in the `/config` menu (a toggle, a pick, a
1428 * typed value), or their `/config key=value`.
1429 */
1430 kind: 'composer';
1431 } | {
1432 /**
1433 * A `/config key=value` that arrived over the Remote Control bridge (a
1434 * phone or web client, or a relay): not attestably the owner's hand.
1435 */
1436 kind: 'bridge';
1437 } | {
1438 /**
1439 * A plugin's `$.config.set`; that plugin's own hooks do not see it.
1440 */
1441 kind: 'plugin';
1442 /**
1443 * The calling plugin's name.
1444 */
1445 name: string;
1446 };
1447
1448 /**
1449 * One `/config` row as `$.config.list()` returns it: what the menu would
1450 * draw now, after every `config.describe` hook, a hidden row left out.
1451 */
1452 export type ConfigRow = {
1453 /**
1454 * Names the row: the panel's id for a built-in, `<plugin>.<field>` for a
1455 * plugin's `userConfig` field; what `$.config.set` takes.
1456 */
1457 key: string;
1458 /**
1459 * What the menu draws for the row, before its value.
1460 */
1461 label: string;
1462 /**
1463 * The help text under the label, when the row has one.
1464 */
1465 description?: string;
1466 /**
1467 * How the row takes its value (ConfigKind).
1468 */
1469 kind: ConfigKind;
1470 /**
1471 * What the row holds now.
1472 */
1473 value: ConfigValue;
1474 /**
1475 * The values a `choice` row takes, in order (a plugin string field's
1476 * declared `options` for its row); absent otherwise.
1477 */
1478 options?: readonly string[];
1479 /**
1480 * Who owns the row: the engine for the panel's own, else the plugin.
1481 */
1482 provider: Origin;
1483 /**
1484 * Whether a trusted source (managed settings, the organization's policy)
1485 * owns the value, so the menu shows it and refuses a change.
1486 */
1487 isLocked: boolean;
1488 };
1489
1490 /**
1491 * `config.set`'s input as a plugin's `$.config.set(args)` takes it: the
1492 * row's key and the value; the engine fills the rest.
1493 */
1494 export type ConfigSetArgs = Pick<ConfigSetInput, 'key' | 'value'>;
1495
1496 /**
1497 * The input of `config.set`: one `/config` row about to change, from the
1498 * menu or a plugin's `$.config.set`, with what it holds now and who owns it.
1499 */
1500 export type ConfigSetInput = {
1501 /**
1502 * Names the row: the panel's own id for a built-in (`theme`, `verbose`,
1503 * `autoCompact`), `<plugin>.<field>` for a plugin's `userConfig` field.
1504 *
1505 * The key a matcher narrows on; pinned: a rewrite is refused.
1506 */
1507 key: string;
1508 /**
1509 * What the row is being set to; `next({ ...e, value })` clamps or
1510 * replaces it, held to the row's kind (a toggle takes a boolean).
1511 */
1512 value: ConfigValue;
1513 /**
1514 * What the row holds before the change, as the menu shows it. Pinned.
1515 */
1516 previous: ConfigValue;
1517 /**
1518 * Who owns the row: `{ plugin: "engine", tier: "core" }` for the panel's
1519 * own, the plugin and its tier for a `userConfig` field. Pinned.
1520 */
1521 provider: Origin;
1522 /**
1523 * Where the change came from (ConfigOrigin): the person in the menu
1524 * (`composer`) or a plugin's `$.config.set`. Pinned.
1525 */
1526 origin: ConfigOrigin;
1527 };
1528
1529 /**
1530 * What a `config.set` hook returns and what `next(e)` resolves to:
1531 * `{ value }` once written, or `{ deny: reason }`, the row left as it was.
1532 *
1533 * The menu shows a deny's reason beside the row; a plugin's `$.config.set`
1534 * resolves with it.
1535 */
1536 export type ConfigSetResult = {
1537 value: ConfigValue;
1538 deny?: undefined;
1539 } | {
1540 deny: string;
1541 value?: undefined;
1542 };
1543
1544 /**
1545 * A `/config` row's value as a hook and `$.config` see it: a toggle's
1546 * boolean, a choice's or a text's string, a number, or a list of strings.
1547 */
1548 export type ConfigValue = boolean | string | number | readonly string[];
1549
1550 /**
1551 * One custom agent whose description the Agent tool's prompt carries;
1552 * built-in agents are left out.
1553 */
1554 export type ContextAgent = {
1555 /**
1556 * The agent's type, as the Agent tool names it.
1557 */
1558 agentType: string;
1559 /**
1560 * Where it was defined, by the engine's word (`projectSettings`,
1561 * `userSettings`, `plugin`); the display label is the renderer's.
1562 */
1563 source: string;
1564 /**
1565 * The description's estimated tokens.
1566 */
1567 tokens: number;
1568 };
1569
1570 /**
1571 * The token counts the last API response of the live window reported, as
1572 * the API spells them; the breakdown's `Messages` row is reconciled to it.
1573 */
1574 export type ContextApiUsage = {
1575 /**
1576 * Uncached input tokens the response was answered over.
1577 */
1578 input_tokens: number;
1579 /**
1580 * Tokens the response generated.
1581 */
1582 output_tokens: number;
1583 /**
1584 * Input tokens written to the prompt cache by the request.
1585 */
1586 cache_creation_input_tokens: number;
1587 /**
1588 * Input tokens read from the prompt cache by the request.
1589 */
1590 cache_read_input_tokens: number;
1591 };
1592
1593 /**
1594 * How a context breakdown is counted: `full` with the token-count API per
1595 * category, `summary` from the last response's usage and local estimates.
1596 *
1597 * The SDK's `get_context_usage` takes the same two words as its `detail`.
1598 */
1599 export type ContextBreakdownDetail = 'summary' | 'full';
1600
1601 /**
1602 * One row of the breakdown, as /context lists it beside the grid (`System
1603 * prompt`, `Messages`, `Free space`, `Autocompact buffer`).
1604 */
1605 export type ContextCategory = {
1606 /**
1607 * The row's label as /context prints it.
1608 */
1609 name: string;
1610 /**
1611 * The row's estimated tokens; a `deferred` row's do not count toward the
1612 * total.
1613 */
1614 tokens: number;
1615 /**
1616 * The theme colour /context draws the row and its squares in, by its key
1617 * in the theme (`promptBorder`, `inactive`, `permission`).
1618 */
1619 color: string;
1620 /**
1621 * Whether the row is tool schemas loaded on demand, which the grid leaves
1622 * out; the same fact as `kind` `deferred`.
1623 */
1624 isDeferred: boolean;
1625 /**
1626 * What the row is (ContextCategoryKind), stamped by the engine.
1627 */
1628 kind: ContextCategoryKind;
1629 };
1630
1631 /**
1632 * What a breakdown row is; branch on this, never on the row's `name`.
1633 *
1634 * `used` content occupies the window, `free` is the window left, `buffer`
1635 * the compaction reserve, `deferred` tool schemas loaded on demand and
1636 * outside the window.
1637 */
1638 export type ContextCategoryKind = 'used' | 'free' | 'buffer' | 'deferred';
1639
1640 /**
1641 * One square of the grid /context draws: which row it belongs to and how
1642 * full it is.
1643 */
1644 export type ContextGridSquare = {
1645 /**
1646 * The theme colour of the square's row, by its key in the theme.
1647 */
1648 color: string;
1649 /**
1650 * Whether the square holds any of its row's tokens.
1651 */
1652 isFilled: boolean;
1653 /**
1654 * The `name` of the row the square belongs to (`Free space` for the
1655 * window left).
1656 */
1657 categoryName: string;
1658 /**
1659 * The row's tokens, repeated on each of its squares.
1660 */
1661 tokens: number;
1662 /**
1663 * The row's share of the window as a whole percentage, repeated likewise.
1664 */
1665 percentage: number;
1666 /**
1667 * How full this one square is, 0 to 1: a row's last square is the partial
1668 * one (/context draws it hollow under 0.7).
1669 */
1670 squareFullness: number;
1671 };
1672
1673 /**
1674 * One MCP tool's schema as the context carries it.
1675 */
1676 export type ContextMcpTool = {
1677 /**
1678 * The tool's wire name (`mcp__linear__create_issue`).
1679 */
1680 name: string;
1681 /**
1682 * The server it belongs to, as /mcp lists it.
1683 */
1684 serverName: string;
1685 /**
1686 * The schema's estimated tokens.
1687 */
1688 tokens: number;
1689 /**
1690 * Whether the schema is inside the window now: always, unless tool
1691 * schemas load on demand and this one has not been searched for yet.
1692 */
1693 isLoaded: boolean;
1694 };
1695
1696 /**
1697 * One memory file the context carries (a CLAUDE.md, a rules file, an
1698 * auto-memory entry).
1699 */
1700 export type ContextMemoryFile = {
1701 /**
1702 * The file's path, absolute.
1703 */
1704 path: string;
1705 /**
1706 * The display label of where it was loaded from (`Project`, `User`,
1707 * `Local`, `Managed`, `AutoMem`).
1708 */
1709 type: string;
1710 /**
1711 * The file's estimated tokens.
1712 */
1713 tokens: number;
1714 };
1715
1716 /**
1717 * One skill whose listing the context carries.
1718 */
1719 export type ContextSkill = {
1720 /**
1721 * The skill's name as `/skills` lists it.
1722 */
1723 name: string;
1724 /**
1725 * Where it came from, by the engine's word (`userSettings`, `plugin`,
1726 * `built-in`, `mcp`, `syncedSkills`); the display label is the renderer's.
1727 */
1728 source: string;
1729 /**
1730 * The providing plugin's name, when the skill comes from one.
1731 */
1732 pluginName?: string;
1733 /**
1734 * The listing's estimated tokens.
1735 */
1736 tokens: number;
1737 };
1738
1739 /**
1740 * The skills the context lists for the model: how many there are, how many
1741 * fit the listing's budget, and each one's share.
1742 */
1743 export type ContextSkills = {
1744 /**
1745 * How many skills the session has.
1746 */
1747 totalSkills: number;
1748 /**
1749 * How many the listing included within its token budget.
1750 */
1751 includedSkills: number;
1752 /**
1753 * The listing's tokens in all.
1754 */
1755 tokens: number;
1756 /**
1757 * One entry per listed skill.
1758 */
1759 skillFrontmatter: ContextSkill[];
1760 };
1761
1762 /**
1763 * The slash commands the Skill tool's prompt lists, counted.
1764 */
1765 export type ContextSlashCommands = {
1766 /**
1767 * How many commands the session has.
1768 */
1769 totalCommands: number;
1770 /**
1771 * How many the listing included.
1772 */
1773 includedCommands: number;
1774 /**
1775 * The listing's tokens in all.
1776 */
1777 tokens: number;
1778 };
1779
1780 /**
1781 * How the window the breakdown measures against was settled; /context
1782 * prints its `Auto-compact window` line off this.
1783 *
1784 * `auto` is the model's own limit; the rest name a compaction window by who
1785 * set it: the `CLAUDE_CODE_AUTO_COMPACT_WINDOW` variable, the settings, the
1786 * account, an experiment, the model's default, or an unrecognised model's.
1787 */
1788 export type ContextWindowSource = 'env' | 'settings' | 'clientdata' | 'experiment' | 'model-default' | 'unknown-model' | 'auto';
1789
1790 /**
1791 * The plugin's identity (`plugin`) and the nouns core contributes to `$` as
1792 * the innermost step of the `engine.create` fold.
1793 *
1794 * A plugin's finished `$` (EngineInterface) has every core noun an outer
1795 * step did not withhold, and every noun the plugins' steps added.
1796 */
1797 export interface CoreEngineInterface {
1798 /**
1799 * This plugin, as loaded: its manifest name and its directory.
1800 */
1801 plugin: {
1802 /**
1803 * From plugin.json; debug-log and `$.ui.log` lines carry it.
1804 */
1805 name: string;
1806 /**
1807 * The plugin's directory (the one holding plugin.json), absolute.
1808 */
1809 root: string;
1810 };
1811 /**
1812 * Display: a line under an open dialog, a redraw or a repaint, a
1813 * transcript line, a pane the surface places, a window scrolled.
1814 */
1815 ui: {
1816 /**
1817 * Shows `text` as one line under the dialog open for `tool_use_id`, or
1818 * removes the line when `text` is undefined.
1819 *
1820 * Core removes the line when the call resolves. A call that is not open
1821 * is refused, as is another plugin's `$.tool.call` run.
1822 *
1823 * @param tool_use_id the call whose open dialog gets the line
1824 * @param text the line to show; undefined removes it
1825 * @example
1826 * $.ui.notice(e.tool_use_id, "checked by my-plugin"); return next(e)
1827 */
1828 notice: (tool_use_id: string, text: string | undefined) => void;
1829 /**
1830 * Re-runs an event whose results the engine caches: `ui.render` draws the
1831 * instances this plugin may draw again; the others drop the cached answers.
1832 *
1833 * A render hook whose state changed (a countdown) calls it for a redraw, at
1834 * most ten a second, thirty for the shown pane and the band (calls sooner
1835 * fold); a `prompt.section` or `prompt.context` hook: dropped next turn.
1836 *
1837 * @param event `ui.render`, `prompt.section`, `prompt.context`,
1838 * `tool.describe`, `command.describe` or `config.describe`
1839 */
1840 invalidate: (event: InvalidatableEventName) => void;
1841 /**
1842 * Repaints a `Raster` this plugin's own render hook drew, still mounted,
1843 * with new cells, without the redraw `invalidate` asks for.
1844 *
1845 * The surface keeps the cells for that Raster (by site and `key`) and
1846 * paints them at its next frame, so blits between frames fold into one:
1847 * an animation runs at the frame rate. A resize is a redraw instead.
1848 *
1849 * @param args `requestId` (the site), `key` (the Raster's), `cells`
1850 * (RasterProps), `columns` and `rows` (the mounted size)
1851 * @returns `{}` once the cells are its next frame, or `{ deny }` (not
1852 * mounted, not this plugin's, another size, cells that do not
1853 * decode)
1854 * @example
1855 * $.clock.every(33, () => $.ui.blit({ requestId, key, cells: frame() }))
1856 */
1857 blit: (args: UiBlitArgs) => Promise<UiBlitResult>;
1858 /**
1859 * The elements of the surface `e` is drawn on (Elements[e.surface]): a
1860 * frozen table of constructors, the JSX tags a render hook draws with.
1861 *
1862 * A read, not a dispatch: the engine ran `ui.resolve` (the other hooks,
1863 * then core) at load, per surface and component. Narrowed `e.surface`:
1864 * that table exactly; unnarrowed: the union, so shared names type-check.
1865 *
1866 * @param e this hook's own `ui.render` argument (its surface and
1867 * component pick the table)
1868 * @returns the surface's frozen element table (`Elements[e.surface]`)
1869 * @example
1870 * const { Box, Text } = $.ui.resolve(e)
1871 * return <Box>{await next(e)}<Text dimColor>done</Text></Box>
1872 */
1873 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
1874 /**
1875 * Appends one line to the transcript, drawn like a system notice (dim;
1876 * not sent to the model), and records it in the debug log.
1877 *
1878 * The line is a row of its own at the surface's next frame, wherever the
1879 * transcript is then; lines keep the order they were logged in. A `-p` or
1880 * SDK run has no transcript: its host receives the line as `ui_log`.
1881 *
1882 * @param text the line's text
1883 * @example
1884 * $.ui.log(`prompt from ${e.origin.kind}: ${e.text.length} chars`)
1885 */
1886 log: (text: string) => void;
1887 /**
1888 * Asks the user `question` in the engine's own AskUserQuestion dialog and
1889 * resolves to the label they chose, or the text typed under "Other".
1890 *
1891 * A `tool.call` of `AskUserQuestion` through every hook but the calling
1892 * one, drawn by `ui.render` on `AskUserQuestion`; a multi-select answer is
1893 * comma-joined. Rejects when dismissed, and in a `-p` run (no one to ask).
1894 *
1895 * @param question the question, ending in a question mark
1896 * @param options 2-4 option labels, or `{ options, header, multiSelect }`
1897 * @returns the label chosen, the chosen labels comma-joined, or free text
1898 * typed under "Other" (so compare it with the labels exactly)
1899 * @example
1900 * const mood = await $.ui.ask("How careful?", ["Bold", "Careful"])
1901 */
1902 ask: (question: string, options?: readonly string[] | AskOptions) => Promise<string>;
1903 /**
1904 * Shows `text` on the notification bar under the prompt for a few
1905 * seconds, the way the engine's own "context left" notice appears.
1906 *
1907 * It leaves the transcript and the model untouched.
1908 *
1909 * @param text the line to show
1910 * @param options `timeoutMs`: how long it stays (default 4000)
1911 * @example
1912 * $.ui.toast(`turn took ${Math.round(e.durationMs / 1000)} s`)
1913 */
1914 toast: (text: string, options?: ToastOptions) => void;
1915 /**
1916 * Pins `text` as this plugin's status line under the prompt, beside the
1917 * engine's own pinned notices, until the next call replaces it.
1918 *
1919 * One per plugin; `undefined` removes it.
1920 *
1921 * @param text the line to keep on screen; undefined clears it
1922 * @example
1923 * $.ui.status("thinking..."); return next(e)
1924 */
1925 status: (text: string | undefined) => void;
1926 /**
1927 * Opens a pane: a framed region the surface places, whose body this
1928 * plugin draws by hooking `ui.render` for `{ component: "Pane" }`.
1929 *
1930 * One instance per id (`requestId`): opening an open id retitles it; a hook
1931 * on `ui.open` may refuse it. The keyboard is the person's; unasked, it
1932 * waits undrawn below 144 columns (110 once asked), judged at each open.
1933 *
1934 * @param pane `id` (1-64 of letters, digits, `_`, `-`), `title`, `focus`,
1935 * `closeOnEscape` and `holdToasts` (a dialog), `rows` it wants inline
1936 * @returns settles once the pane is open (or retitled)
1937 * @example
1938 * await $.ui.open({ id: "clock", title: "Clock" })
1939 * @example
1940 * await $.ui.open({ id: "ask", focus: true, closeOnEscape: true, rows: 9 })
1941 */
1942 open: (pane: PaneOpenArgs) => Promise<void>;
1943 /**
1944 * Closes one of the open panes; an id that is not open is left alone.
1945 *
1946 * Every close raises `ui.close`, `e.origin` naming whose it is: this call
1947 * (`plugin`), the person's mark or key (`person`), an unload (`unload`).
1948 * A hook answering without `next` keeps the pane open, save on an unload.
1949 *
1950 * @param pane `id`: the id the pane was opened under
1951 * @returns settles once the pane is gone or a hook answered for it;
1952 * rejects on a hook's `{ deny }`
1953 * @example
1954 * onPress: () => $.ui.close({ id: "clock" })
1955 */
1956 close: (pane: PaneCloseArgs) => Promise<void>;
1957 /**
1958 * Scrolls something into view as the DOM's `scrollIntoView` would: a
1959 * render instance by `requestId`, an element by `key`, a site's edge.
1960 *
1961 * A site of this plugin's (its pane, the band it draws into) moves under
1962 * the event `ui.scroll`, origin `plugin`. A transcript row moves only
1963 * while this call answers the person's own input, where one scrolls.
1964 *
1965 * @param args `to` (what), `in` (which site, required for `start` and
1966 * `end`), `block` (where it lands; `nearest` by default)
1967 * @returns `{}` once it moved, or `{ deny }` saying why not
1968 * @example
1969 * onPress: () => $.ui.scroll({ in: "log", to: "end" })
1970 */
1971 scroll: (args: UiScrollArgs) => Promise<UiScrollResult>;
1972 };
1973 /**
1974 * Completions through the session's own client and credentials.
1975 */
1976 model: {
1977 /**
1978 * Runs one text completion through the session's own API client and
1979 * resolves to the reply's text.
1980 *
1981 * No tools, no history, no system prompt beyond the CLI's identity block
1982 * and `request.system`.
1983 *
1984 * @param request the model (an alias such as `haiku`, or a full id,
1985 * resolved like a `--model` value), the prompt, and a token cap
1986 * @returns the reply's text
1987 * @example
1988 * const reply = await $.model.complete({ model: "haiku", prompt: "Hi." })
1989 */
1990 complete: (request: ModelCompleteRequest) => Promise<string>;
1991 /**
1992 * Runs one tool-less completion over the session's OWN transcript, sharing
1993 * the main thread's prompt cache; the reply's text and the fork's usage.
1994 *
1995 * Not `complete`: sharing the cache prefix means the model and system
1996 * prompt are the session's, read from its last turn's cache-safe snapshot,
1997 * and tools are denied. Null on a cold snapshot or an API error.
1998 *
1999 * @param request the one user message the fork answers
2000 * @returns the reply's text with the fork's usage, or null on a cold
2001 * snapshot or an API error
2002 * @example
2003 * const reply = await $.model.fork({ prompt: "One line to learn?" })
2004 * if (reply !== null) $.ui.log(`${reply.usage.output_tokens} tokens`)
2005 */
2006 fork: (request: ModelForkRequest) => Promise<ModelForkResult | null>;
2007 /**
2008 * Picks one of `labels` for `text` with one completion over
2009 * `$.model.complete` and a fixed classifier prompt.
2010 *
2011 * `text` is data; the model answers with a label alone. It resolves
2012 * `undefined` when the answer named none of `labels`. A failed request,
2013 * an abort or a reply with no text rejects, naming the cause.
2014 *
2015 * @param text what to classify
2016 * @param labels the labels to choose from (2 or more)
2017 * @param options `model`: an alias or id; default the engine's small
2018 * fast model
2019 * @returns the label the model named, or undefined when it named none;
2020 * rejects when the request fails or the reply has no text
2021 * @example
2022 * const kind = await $.model.classify(e.text, ["bug", "feature"])
2023 * if (kind === undefined) return next(e)
2024 */
2025 classify: (text: string, labels: readonly string[], options?: ClassifyOptions) => Promise<string | undefined>;
2026 };
2027 /**
2028 * Sound: clip playback and platform speech.
2029 */
2030 audio: {
2031 /**
2032 * Plays one audio clip, starting now; clips are not queued, so two calls
2033 * play together (a bed under speech).
2034 *
2035 * `{ asset }` is the plugin's own file, loaded by the engine and played
2036 * through the platform's player (`afplay` on macOS). Resolves when
2037 * playback ends; rejects, naming the cause, when the clip cannot play.
2038 *
2039 * @param clip the plugin's own file (`{ asset }`), a URL the engine
2040 * fetches, or the bytes as base64 with their MIME type
2041 * @param options `shouldLoop`, `gain`, and an AbortSignal that stops the
2042 * clip
2043 */
2044 play: (clip: AudioClip, options?: PlayOptions) => Promise<void>;
2045 /**
2046 * Speaks `text` with the platform's own synthesizer (`say` on macOS).
2047 * Plain text.
2048 *
2049 * Utterances are queued among themselves; clips are not. Resolves when
2050 * the utterance has ended; rejects, naming the cause, when there is no
2051 * synthesizer, the voice is not installed, or the utterance failed.
2052 *
2053 * @param text what to say, as plain text
2054 * @param options `voice`: the system voice's exact name (`Samantha`);
2055 * absent, the synthesizer's default
2056 * @returns which synthesizer spoke, once the utterance has ended
2057 */
2058 speak: (text: string, options?: SpeakOptions) => Promise<SpeakResult>;
2059 };
2060 /**
2061 * The engine's connected MCP servers.
2062 */
2063 mcp: {
2064 /**
2065 * Calls `tool` on one of the engine's connected MCP servers with the
2066 * engine's own connection and credentials.
2067 *
2068 * A `cached` server is dialed on first use. Resolves to the tool's result
2069 * as MCP returns it: `content` blocks and `isError`. No permission prompt:
2070 * the plugin's call, seen by the hooks above it, is the grant.
2071 *
2072 * @param server the server's name as /mcp lists it (`claude.ai Gmail`;
2073 * the tool-name spelling `claude_ai_Gmail` is accepted too)
2074 * @param tool the tool's name on that server (`create_draft`)
2075 * @param args the tool's arguments; none when absent
2076 * @returns the tool's result as MCP returns it: `content` blocks and
2077 * `isError`
2078 * @example
2079 * const { content } = await $.mcp.call("claude.ai Gmail", "create_draft")
2080 */
2081 call: (server: string, tool: string, args?: Record<string, unknown>) => Promise<McpToolResult>;
2082 };
2083 /**
2084 * The running session, read as plain data, and compacting it.
2085 */
2086 session: {
2087 /**
2088 * Returns the transcript so far, one entry per user or assistant
2089 * message; progress rows, `$.ui.log` lines and notices are not messages.
2090 *
2091 * Each entry is a SessionMessage, `{ role, text, toolUses }` (a user
2092 * message may add `toolResults`; a `toolUses` entry adds its `result` and
2093 * `text` once answered). A long transcript answers its newest 4096.
2094 *
2095 * @example
2096 * const last = (await $.session.messages()).at(-1)
2097 */
2098 messages: () => Promise<SessionMessage[]>;
2099 /**
2100 * Returns the directory the session runs in, absolute.
2101 */
2102 cwd: () => Promise<string>;
2103 /**
2104 * Returns the main loop's model, as `/model` shows it.
2105 */
2106 model: () => Promise<string>;
2107 /**
2108 * Returns how many prompts the user has sent this session (user turns in
2109 * the transcript).
2110 */
2111 turns: () => Promise<number>;
2112 /**
2113 * Returns the session's id (the transcript file's name).
2114 */
2115 id: () => Promise<string>;
2116 /**
2117 * Returns the git repository the session runs in, read from the working
2118 * copy on each call; null when the directory is not inside one.
2119 *
2120 * @example
2121 * const repo = await $.session.repo(); const publicRepo = !repo?.internal
2122 */
2123 repo: () => Promise<SessionRepo | null>;
2124 /**
2125 * Returns every surface the session draws on, each once: `terminal` under
2126 * the REPL first, then `desktop` and `mobile` in the order they attached.
2127 *
2128 * A session may draw on several at once (a terminal and two phones):
2129 * clients attach (`session.attach`) and detach, and a render hook still
2130 * reads `e.surface` per ask. Empty in a plain -p run; never rejects.
2131 *
2132 * @example
2133 * const inApp = (await $.session.surfaces()).some(s => s !== "terminal")
2134 */
2135 surfaces: () => Promise<readonly RenderSurface[]>;
2136 /**
2137 * Returns the first of `$.session.surfaces()`, or null where nothing
2138 * draws.
2139 *
2140 * @deprecated use `surfaces()`; a session may draw on several surfaces at
2141 * once
2142 */
2143 surface: () => Promise<RenderSurface | null>;
2144 /**
2145 * Returns the context window's fill, the rate-limit windows and the
2146 * cost, as the status line has them; with `breakdown`, by category too.
2147 *
2148 * The plain call costs nothing; `"full"` counts each category with the
2149 * token-count API as /context does, `"summary"` estimates locally, and
2150 * `context.breakdown` comes back in the SDK's `get_context_usage` shape.
2151 *
2152 * @param args `{ breakdown, columns }`: how the breakdown is counted and
2153 * the width its grid is drawn in; nothing for the status line's figures
2154 * @returns `{ context, rateLimits, cost }` as the status line has them
2155 * @example
2156 * const { context } = await $.session.usage()
2157 * if ((context.percent ?? 0) >= 85) await $.session.compact()
2158 * @example
2159 * const usage = await $.session.usage({ breakdown: "full", columns })
2160 * for (const row of usage.context.breakdown?.gridRows ?? []) draw(row)
2161 */
2162 usage: (args?: SessionUsageArgs) => Promise<SessionUsage>;
2163 /**
2164 * Compacts the conversation: the event `session.compact` with `trigger`
2165 * `plugin`, the same call `/compact` makes, between turns.
2166 *
2167 * It runs through every hook but the calling one, then core: a summary
2168 * and the kept messages in the transcript's place. Resolves `{ skip }`
2169 * when a hook vetoed it; rejects while a turn runs.
2170 *
2171 * @example
2172 * const { skip } = await $.session.compact({ instructions: "the plan" })
2173 */
2174 compact: EventCalls['session']['compact'];
2175 /**
2176 * Holds the session's Anthropic credential on the host and answers an
2177 * opaque handle and its kind; the secret never reaches the plugin.
2178 *
2179 * The handle is spent through `$.http.fetch(url, { auth: handle })`,
2180 * which sets the credential header, only for a first-party host. Null
2181 * where the build or the provider has no first-party credential to hold.
2182 *
2183 * @example
2184 * await $.http.fetch(url, { auth: (await $.session.authorize())?.handle })
2185 */
2186 authorize: () => Promise<SessionAuthorization>;
2187 };
2188 /**
2189 * The running model turn: ending it.
2190 */
2191 turn: {
2192 /**
2193 * Cancels the running model turn: the one whose id `turn.start` handed
2194 * this plugin, its running tools stopped, no interruption marker.
2195 *
2196 * The event `turn.abort`, seen by the hooks above; the prompt this
2197 * plugin submits next is the context. Rejects, naming both ids, when
2198 * `turnId` is not the running turn's; a hook may end its own turn.
2199 *
2200 * @param input `turnId`: the id `turn.start` carried
2201 * @example
2202 * on("turn.start", ($, e, next) => { held = e.turnId; return next(e) })
2203 */
2204 abort: (input: OpEventOf['turn.abort']) => Promise<void>;
2205 };
2206 /**
2207 * Submitting a prompt the model reads as a user turn, and putting a text
2208 * in the person's prompt box, written or proposed.
2209 */
2210 prompt: {
2211 /**
2212 * Submits a prompt: the event `prompt.submit`, the same call the engine
2213 * makes for a typed prompt; `input.text` runs when the session is idle.
2214 *
2215 * It goes through every hook but the calling one (the plugin's others
2216 * see it) with `e.origin` `{ kind: 'plugin', name }`, the name the
2217 * model reads it under unless a hook leaves it out of its answer.
2218 *
2219 * @example
2220 * void $.prompt.submit({ text: "List the TODOs you just mentioned." })
2221 */
2222 submit: EventCalls['prompt']['submit'];
2223 /**
2224 * Writes `input.text` into the prompt box as the person's draft, cursor
2225 * at its end, replacing what it held: the event `prompt.fill`.
2226 *
2227 * It goes through every other plugin's hook with `e.origin` `{ kind:
2228 * 'plugin', name }`. Resolves `{ isFilled: false }` when a dialog holds
2229 * the keys or the session has no box (headless); nothing is submitted.
2230 *
2231 * @example
2232 * const { isFilled } = await $.prompt.fill({ text: "/review latest" })
2233 */
2234 fill: EventCalls['prompt']['fill'];
2235 /**
2236 * Proposes `input.text` as the prompt box's dim suggestion, Tab to take:
2237 * the event `prompt.suggest`, as the engine's own guess after a turn.
2238 *
2239 * It goes through every other plugin's hook with `e.origin` `{ kind:
2240 * 'plugin', name }`, the engine's own suggestions on or off; `{ isShown:
2241 * false }` while the box holds text, a turn runs, or headless (no box).
2242 *
2243 * @example
2244 * void $.prompt.suggest({ text: "run the tests you just wrote" })
2245 */
2246 suggest: EventCalls['prompt']['suggest'];
2247 };
2248 /**
2249 * The tools the model has in this session, and running one.
2250 */
2251 tool: {
2252 /**
2253 * Returns the tools the model can call now, built-in and MCP alike, in
2254 * the order the model sees them.
2255 *
2256 * @example
2257 * const names = (await $.tool.list()).map(t => t.name)
2258 */
2259 list: () => Promise<ToolInfo[]>;
2260 /**
2261 * Calls a tool: the event `tool.call`, the same call the engine makes for
2262 * the model's tool calls, under a `tool_use_id` of its own.
2263 *
2264 * It runs through every hook but the calling one (the plugin's others
2265 * see it), the permission check and its dialog, then the tool. Rejects
2266 * when no tool has that name or the call is aborted.
2267 *
2268 * @example
2269 * const { text } = await $.tool.call({ tool: "Read", file_path: "a.md" })
2270 */
2271 call: EventCalls['tool']['call'];
2272 /**
2273 * Asks the engine's permission decision for a tool call now: the event
2274 * `tool.check`, resolved to `{ decision, reason?, rule? }`.
2275 *
2276 * The hooks run (the calling hook's own frame skipped, `next.origin` this
2277 * plugin, no `tool_use_id`); nothing runs, no dialog opens, no PreToolUse
2278 * hook or classifier is asked.
2279 *
2280 * @example
2281 * const { decision } = await $.tool.check({ tool: "Read", input })
2282 */
2283 check: EventCalls['tool']['check'];
2284 /**
2285 * Declares a tool the model can call from the next prompt on: the name,
2286 * description and input schema of `mcp__<plugin>__<name>`.
2287 *
2288 * Serve it with a `tool.call` hook on `{ tool: "mcp__<plugin>__<name>" }`
2289 * that returns the result (a call no hook answers fails); a name registered
2290 * again is replaced. Rejects until the session binds, at `session.start`.
2291 *
2292 * @param tool `name`, `description` (what the model reads), `inputSchema`
2293 * (a JSON schema object; default `{ type: "object" }`)
2294 * @returns `{ tool }`, the registered tool's full name
2295 * `mcp__<plugin>__<name>`
2296 * @example
2297 * await $.tool.register({ name: "weather", description: "Weather." })
2298 */
2299 register: (tool: ToolSpec) => Promise<OpValueOf['tool.register']>;
2300 };
2301 /**
2302 * The slash commands the person can run in this session, and running one.
2303 */
2304 command: {
2305 /**
2306 * Returns the slash commands the person can run now, built-in, plugin
2307 * and MCP alike, in the order the typeahead lists them.
2308 *
2309 * @example
2310 * const names = (await $.command.list()).map(c => c.name)
2311 */
2312 list: () => Promise<CommandInfo[]>;
2313 /**
2314 * Runs a slash command as if the person typed `/command args`: the
2315 * event `command.run`, queued and run once the session is idle.
2316 *
2317 * It runs through every hook but the calling one with `e.origin`
2318 * `{ kind: 'plugin', name }`, its lines in the transcript. Rejects an
2319 * unknown name, and inside a hook the turn is waiting on.
2320 *
2321 * @example
2322 * const { text } = await $.command.run({ command: "status" })
2323 */
2324 run: EventCalls['command']['run'];
2325 /**
2326 * Declares the slash command `/<name>` for this session, listed in the
2327 * typeahead from the next keystroke on.
2328 *
2329 * Serve it with a `command.run` hook on `{ command: "<name>" }` that
2330 * returns `{ text }`; a run no hook answers says so as its output.
2331 * Registering a name again replaces it; a built-in's name is refused.
2332 *
2333 * @param command `name`, `description` (what the menu shows),
2334 * `argumentHint` (dim after the name), `immediate` (runs mid-turn)
2335 * @returns `{ command }`, the registered name
2336 * @example
2337 * await $.command.register({ name: "hello", description: "Says hi." })
2338 */
2339 register: (command: CommandSpec) => Promise<OpValueOf['command.register']>;
2340 };
2341 /**
2342 * Every row of the settings menu (`/config`), the panel's own and each
2343 * enabled plugin's `userConfig` fields alike: listing and changing them.
2344 */
2345 config: {
2346 /**
2347 * Returns the rows the `/config` menu would draw now, in its order,
2348 * each with its current value, its kind, its owner and its lock.
2349 *
2350 * After every `config.describe` hook: a hidden row is left out, a
2351 * relabelled one carries the new label.
2352 *
2353 * @example
2354 * const theme = (await $.config.list()).find(row => row.key === "theme")
2355 */
2356 list: () => Promise<ConfigRow[]>;
2357 /**
2358 * Changes one row as if the person did in the menu: the event
2359 * `config.set` with `origin` `{ kind: 'plugin', name }`, then the writer.
2360 *
2361 * Through the other plugins' hooks, this plugin's own skipped; `{ deny }`
2362 * when a hook refused, the value does not fit, a trusted source owns the
2363 * row or only its dialog changes it. Rejects a key no row has.
2364 *
2365 * @param args `key` (as `list` names it) and `value` (the row's kind)
2366 * @returns `{ value }` once written, or `{ deny }`
2367 * @example
2368 * const { deny } = await $.config.set({ key: "verbose", value: true })
2369 */
2370 set: EventCalls['config']['set'];
2371 };
2372 /**
2373 * Subagents.
2374 */
2375 agent: {
2376 /**
2377 * Spawns a subagent: the event `agent.spawn`, the same call the engine
2378 * makes when the Agent tool starts one; the engine fills the rest.
2379 *
2380 * It runs every hook but the calling one, then the Agent tool in the
2381 * background under this call's origin: `{ model, agentId }` once the
2382 * subagent started (its answer is its `turn.complete`), or `{ deny }`.
2383 *
2384 * @example
2385 * const { agentId } = await $.agent.spawn({ prompt: "Read README.md." })
2386 */
2387 spawn: EventCalls['agent']['spawn'];
2388 /**
2389 * Returns the session's subagents so far, the ones the model spawned and
2390 * the ones plugins did alike.
2391 */
2392 list: () => Promise<AgentInfo[]>;
2393 };
2394 /**
2395 * The file system as the engine's own process reaches it, text only
2396 * (UTF-8); a relative path is under the session's working directory.
2397 *
2398 * An absolute path is used as given. A read or a write over 4 MiB
2399 * rejects; what the operating system refuses rejects with its errno
2400 * (`ENOENT`, `EACCES`). Where a path may go is an `fs.*` hook's to say.
2401 */
2402 fs: {
2403 /**
2404 * Reads a file and returns its text. Rejects when missing.
2405 *
2406 * @param path relative to the working directory, or absolute
2407 * @returns the file's text
2408 * @example
2409 * const readme = await $.fs.read("README.md")
2410 */
2411 read: (path: string) => Promise<string>;
2412 /**
2413 * Writes `text` to a file, creating it and its directories as needed.
2414 *
2415 * @param path relative to the working directory, or absolute
2416 * @param text the whole new content
2417 */
2418 write: (path: string, text: string) => Promise<void>;
2419 /**
2420 * Lists a directory: `{ name, kind, size }` per entry, by name.
2421 *
2422 * @param path the directory's path; absent, the working directory
2423 * @returns the entries, `{ name, kind, size }` each
2424 */
2425 list: (path?: string) => Promise<FsEntry[]>;
2426 /**
2427 * Returns whether the path exists; never rejects.
2428 */
2429 exists: (path: string) => Promise<boolean>;
2430 /**
2431 * Returns `{ kind, size, mtimeMs }` of the path. Rejects when missing.
2432 */
2433 stat: (path: string) => Promise<FsStat>;
2434 /**
2435 * Reads the named instruction files in every directory above the
2436 * session's original working directory, the way the engine reads CLAUDE.md.
2437 *
2438 * Root first, each `{ dir, name, content }` that exists, the content
2439 * with its `@include`s after it; with `of`, on down to that file's
2440 * directory, as the engine reads a nested CLAUDE.md when a file is read.
2441 *
2442 * @param request `names`, relative `.md` file names (no `..`) looked for
2443 * in each directory; `of`, the file whose directory the walk goes down to
2444 * @returns the files found, root first
2445 * @example
2446 * const found = await $.fs.ancestors({ names: ["AGENTS.md"] })
2447 * const stack = await $.fs.ancestors({ names: ["AGENTS.md"], of: path })
2448 */
2449 ancestors: (request: FsAncestorsRequest) => Promise<readonly FsAncestor[]>;
2450 };
2451 /**
2452 * This plugin's own key-value store, kept between sessions and hot
2453 * reloads; values are JSON data.
2454 *
2455 * A JSON file of the plugin's own under the user's Claude Code
2456 * configuration directory.
2457 */
2458 store: {
2459 /**
2460 * Returns the value under `key`, or `undefined` when unset.
2461 *
2462 * @example
2463 * const count = Number((await $.store.get("count")) ?? 0) + 1
2464 */
2465 get: (key: string) => Promise<unknown>;
2466 /**
2467 * Sets `key` to `value`, which must be JSON data.
2468 *
2469 * `get` reads back `JSON.parse(JSON.stringify(value))`: a Date is its ISO
2470 * string, an `undefined` field is dropped, a Map or Set is `{}`. Rejects
2471 * a function, a cycle, or a store over 4 MiB of JSON text in all.
2472 */
2473 set: (key: string, value: unknown) => Promise<void>;
2474 /**
2475 * Removes `key` from the store.
2476 */
2477 delete: (key: string) => Promise<void>;
2478 /**
2479 * Returns every key set, in insertion order.
2480 */
2481 keys: () => Promise<string[]>;
2482 };
2483 /**
2484 * The time and timers, each an event through the host: `clock.now` reads
2485 * the time; `clock.sleep`, `after` and `every` wait until it has passed.
2486 *
2487 * A timer's callback is the plugin's own function, kept in its environment
2488 * and run there when the wait resolves; a hot reload of the plugin cancels
2489 * its pending waits with the old environment.
2490 */
2491 clock: {
2492 /**
2493 * Resolves milliseconds since the epoch, now.
2494 *
2495 * @example
2496 * const startedAt = await $.clock.now()
2497 */
2498 now: () => Promise<number>;
2499 /**
2500 * Resolves after `ms` milliseconds; rejects at once when `signal` aborts.
2501 *
2502 * @param ms how long, in milliseconds
2503 * @param options `signal`: ends the wait early with a rejection (pass
2504 * `next.signal` so a hook's wait ends with its dispatch)
2505 * @example
2506 * await $.clock.sleep(500, { signal: next.signal })
2507 */
2508 sleep: (ms: number, options?: SleepOptions) => Promise<void>;
2509 /**
2510 * Calls `fn` once after `ms` milliseconds; `cancel()` before then stops it.
2511 *
2512 * One `clock.after` dispatch: `fn` runs when it resolves, and never when
2513 * a hook refuses it.
2514 */
2515 after: TimerCall;
2516 /**
2517 * Calls `fn` every `ms` milliseconds (at least 1) until `cancel()`.
2518 *
2519 * One `clock.every` dispatch per period: `fn` runs when it resolves and
2520 * the next period is asked; a refused period ends the interval.
2521 *
2522 * @example
2523 * const tick = $.clock.every(1000, () => $.ui.status("polling"))
2524 */
2525 every: TimerCall;
2526 };
2527 /**
2528 * The network, through the host.
2529 */
2530 http: {
2531 /**
2532 * Fetches `url` through the host (never the plugin's own network) and
2533 * resolves `{ status, ok, headers, text }` once the body is read.
2534 *
2535 * http or https, to whatever the host process can reach, unless the
2536 * administrator's policy switches refuse it; an `auth` handle from
2537 * `$.session.authorize()` rides https only, to a first-party host.
2538 *
2539 * @param url the URL (http or https)
2540 * @param init `{ method, headers, body, auth }` (body a string)
2541 * @returns `{ status, ok, headers, text }` once the body is read
2542 * @example
2543 * const { ok, text } = await $.http.fetch("https://example.com/status")
2544 */
2545 fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>;
2546 };
2547 /**
2548 * Commands on the host, run as the user the session runs as. CLI only.
2549 *
2550 * Local execution, not a network path: what a command of its own reaches
2551 * is its own, as for the Bash tool and a settings `command` hook.
2552 */
2553 process: {
2554 /**
2555 * Runs a command on the host by its argument vector (no shell) and
2556 * resolves `{ exitCode, stdout, stderr }` once it exits, any exit code.
2557 *
2558 * One shot: the whole output is read, so a background process left
2559 * writing holds the call until the timeout. Rejects when the command
2560 * cannot start or is still running then. Git runs with repo hooks off.
2561 *
2562 * @param argv the command and its arguments, `argv[0]` the executable
2563 * @param init `{ cwd, env, stdin, timeoutMs }` (cwd the session's by
2564 * default; timeout 30 s by default, ten minutes at most)
2565 * @returns `{ exitCode, stdout, stderr }` once the child exits
2566 * @example
2567 * const { exitCode, stdout } = await $.process.run(["git", "status"])
2568 */
2569 run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>;
2570 };
2571 /**
2572 * What the settings files, `--settings` and managed policy hold, as the
2573 * engine runs under it; read only.
2574 *
2575 * Every key crosses as the source holds it, `env` and the helper commands
2576 * included: nothing is filtered. The OAuth session and the global config
2577 * (~/.claude.json) are not settings and are never read.
2578 */
2579 settings: {
2580 /**
2581 * Resolves with the settings merged over every source, as the engine
2582 * reads them, or with one source's settings as loaded (`{ source }`).
2583 *
2584 * A snapshot in plain data each call; a source with no file answers
2585 * `{}`. The sources (SettingsSource) rise in precedence from `user` to
2586 * `policy`: the merge takes a key from the last source that has it.
2587 *
2588 * @param args `{ source }` to read one source; nothing for the merge
2589 * @returns the settings object, keyed as a settings.json is
2590 * @example
2591 * const { permissions } = await $.settings.read()
2592 * const policy = await $.settings.read({ source: "policy" })
2593 */
2594 read: (args?: SettingsReadArgs) => Promise<Settings>;
2595 };
2596 /**
2597 * The environment of this process, the one every Bash child, MCP server
2598 * and `$.process.run` command started after inherits.
2599 *
2600 * `get` and `set` take the variable's name as a string literal, so what a
2601 * module reads and writes is read off its source: `claude plugin validate`
2602 * lists the names, and a name the module does not spell is refused.
2603 */
2604 env: {
2605 /**
2606 * Resolves with the variable's value, or `undefined` when it is unset.
2607 *
2608 * `name` must be a string literal; `claude plugin validate` lists the
2609 * names your module reads and writes.
2610 *
2611 * @example
2612 * const home = await $.env.get("HOME")
2613 */
2614 get: (name: string) => Promise<string | undefined>;
2615 /**
2616 * Sets the variable for this process and everything it starts after, or
2617 * unsets it when `value` is `undefined`.
2618 *
2619 * `name` must be a string literal; `claude plugin validate` lists the
2620 * names your module reads and writes.
2621 *
2622 * @example
2623 * await $.env.set("GIT_PAGER", "cat")
2624 */
2625 set: (name: string, value: string | undefined) => Promise<void>;
2626 };
2627 }
2628
2629 /**
2630 * The name of an event the engine defines itself (a key of CoreEventOf);
2631 * EventName adds the declared plugin nouns' events.
2632 */
2633 type CoreEventName = keyof CoreEventOf;
2634
2635 /**
2636 * The argument of each event the engine defines itself: its call sites'
2637 * (EngineEventOf), the classic hooks' (ClassicEventOf), the calls on `$`.
2638 */
2639 type CoreEventOf = EngineEventOf & ClassicEventOf & OpEventOf;
2640
2641 type CwdChangedHookInput = BaseHookInput & {
2642 hook_event_name: 'CwdChanged';
2643 old_cwd: string;
2644 new_cwd: string;
2645 };
2646
2647 type DirectoryAddedHookInput = BaseHookInput & {
2648 hook_event_name: 'DirectoryAdded';
2649 /**
2650 * Absolute path of the directory that was added.
2651 */
2652 directory: string;
2653 /**
2654 * How the directory was added: "slash_command" for /add-dir, "register_repo_root" for the SDK control_request.
2655 */
2656 source: 'slash_command' | 'register_repo_root';
2657 };
2658
2659 /**
2660 * The `children` field every element constructor's props carry, appended
2661 * beside its own props type: one child, or a list that may nest.
2662 *
2663 * JSX types a lone child as the child itself (`<Text dimColor>done</Text>`
2664 * passes the string, `<Text>{count}</Text>` the number), and a mapped list
2665 * beside a sibling as a nested list (`<Box>{rows.map(row)}<Text>ok</Text>`).
2666 */
2667 export type ElementChildren = {
2668 children?: RenderChildren;
2669 };
2670
2671 /**
2672 * An element as `$.ui.resolve(e)` hands it out: a constructor from props to
2673 * the frozen plain-data element, `children` among the props as JSX passes.
2674 *
2675 * `const { Box } = $.ui.resolve(e)` then `<Box gap={1}>...</Box>` compiles to
2676 * `h(Box, { gap: 1 }, ...children)`, and `h` calls a function tag with its
2677 * props, so the table's constructors are the JSX tags.
2678 */
2679 export type ElementConstructor<P> = (props: P & ElementChildren) => RenderElement;
2680
2681 /**
2682 * Every element name of every surface: what a table handed out is completed to
2683 * (an omitted one draws a fragment; see `ui.resolve`).
2684 */
2685 export type ElementName = {
2686 [P in RenderSurface]: keyof Elements[P];
2687 }[RenderSurface];
2688
2689 /**
2690 * The element constructors each surface draws, by `e.surface`: what
2691 * `$.ui.resolve(e)` returns and a `ui.resolve` hook passes on; no globals.
2692 *
2693 * All carry `Box`, `Text`, `Button`, `Link`, `Code`; terminal and desktop add
2694 * `Input`, `Select`, `Client`; desktop and mobile `Svg`; terminal `Raster`.
2695 * Narrowed on `e.surface`, that table; unnarrowed, the union; else fragments.
2696 */
2697 export type Elements = {
2698 terminal: {
2699 Box: ElementConstructor<BoxProps>;
2700 Text: ElementConstructor<TextProps>;
2701 Button: ElementConstructor<ButtonProps>;
2702 Input: ElementConstructor<InputProps>;
2703 Select: ElementConstructor<SelectProps>;
2704 Link: ElementConstructor<LinkProps>;
2705 Code: ElementConstructor<CodeProps>;
2706 Client: ElementConstructor<ClientProps>;
2707 Raster: ElementConstructor<RasterProps>;
2708 };
2709 desktop: {
2710 Box: ElementConstructor<BoxProps>;
2711 Text: ElementConstructor<TextProps>;
2712 Button: ElementConstructor<ButtonProps>;
2713 Input: ElementConstructor<InputProps>;
2714 Select: ElementConstructor<SelectProps>;
2715 Svg: ElementConstructor<SvgProps>;
2716 Link: ElementConstructor<LinkProps>;
2717 Code: ElementConstructor<CodeProps>;
2718 Client: ElementConstructor<ClientProps>;
2719 };
2720 /**
2721 * No `Input` or `Select`: the control protocol carries presses (ui_press)
2722 * but no ui_input or ui_select yet; not a limit of the device.
2723 *
2724 * The table grows when those messages exist.
2725 */
2726 mobile: {
2727 Box: ElementConstructor<BoxProps>;
2728 Text: ElementConstructor<TextProps>;
2729 Button: ElementConstructor<ButtonProps>;
2730 Svg: ElementConstructor<SvgProps>;
2731 Link: ElementConstructor<LinkProps>;
2732 Code: ElementConstructor<CodeProps>;
2733 };
2734 };
2735
2736 /**
2737 * The table `ui.resolve` answers for an argument of surface `P`.
2738 */
2739 export type ElementTable<P extends RenderSurface = RenderSurface> = Elements[P];
2740
2741 /**
2742 * 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.
2743 */
2744 type ElicitationHookInput = BaseHookInput & {
2745 hook_event_name: 'Elicitation';
2746 mcp_server_name: string;
2747 message: string;
2748 mode?: 'form' | 'url';
2749 url?: string;
2750 elicitation_id?: string;
2751 requested_schema?: Record<string, unknown>;
2752 };
2753
2754 /**
2755 * 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.
2756 */
2757 type ElicitationResultHookInput = BaseHookInput & {
2758 hook_event_name: 'ElicitationResult';
2759 mcp_server_name: string;
2760 elicitation_id?: string;
2761 mode?: 'form' | 'url';
2762 action: 'accept' | 'decline' | 'cancel';
2763 content?: Record<string, unknown>;
2764 };
2765
2766 /**
2767 * The input of `engine.create`: the fold that builds `$`, once per load,
2768 * core innermost.
2769 *
2770 * A hook is written in post-order: `const built = await next(e)` is `$` as
2771 * built so far; `return { ...built, voice: { say } }` adds this plugin's noun.
2772 * See EngineEventOf's `engine.create` for what a step may and may not do.
2773 */
2774 export type EngineCreateInput = {
2775 /**
2776 * In list order, first is outermost (managed plugins first, so an org
2777 * plugin's withholding wins).
2778 */
2779 plugins: readonly string[];
2780 };
2781
2782 /**
2783 * What an `engine.create` hook returns: `$` as built so far with this
2784 * plugin's nouns added, less any it withheld.
2785 *
2786 * Every declared noun is optional here. Between hooks it crosses the chain
2787 * as interface descriptors; a hook sees objects (EngineInterfaceBuilt).
2788 */
2789 export type EngineCreateResult = Partial<EngineInterface> & {
2790 readonly [noun: string]: unknown;
2791 };
2792
2793 /**
2794 * The events the engine raises at its call sites, and `engine.create`; the
2795 * classic settings hooks' events are ClassicEventOf.
2796 *
2797 * At every one, a hook that fails (throws, overruns its budget, answers a
2798 * wrong shape) is skipped: the hooks beneath and core run in its place, or
2799 * its last `next` result stands; the failure is reported, naming it.
2800 */
2801 export type EngineEventOf = {
2802 /**
2803 * Fires when the engine is about to run a tool. `next(e)` runs the hooks
2804 * beneath, then core (the permission prompt, the tool itself).
2805 *
2806 * Return `{ deny: reason }` to refuse or `{ result }` to answer yourself; a
2807 * hook that returns while its `next` is pending aborts what runs beneath.
2808 * The managed-settings hooks run first: their deny is the call's result.
2809 */
2810 'tool.call': ToolCallInput;
2811 /**
2812 * Fires when the engine decides whether a tool call may run, after the
2813 * `tool.call` and PreToolUse hooks and before the mode settles an ask.
2814 *
2815 * `next(e)` resolves to the engine's verdict (rules, mode, the tool's own
2816 * check, PreToolUse's decision); return any `{ decision }`. `$.tool.check`
2817 * runs the same chain and executes nothing.
2818 *
2819 * @example
2820 * on("tool.check", { tool: "Read" }, () => ({ decision: "allow" }))
2821 */
2822 'tool.check': ToolCheckInput;
2823 /**
2824 * Fires when the engine is about to draw a component: once per input value
2825 * (props, viewport width), plugin load or `$.ui.invalidate("ui.render")`.
2826 *
2827 * A repaint reuses the answer; a clock invalidates. `next(e)` resolves to the
2828 * drawing: return it, wrap it, draw your own, or rewrite `props`. A tree that
2829 * does not validate draws the engine's own; `--plugin-dir` is told why.
2830 */
2831 'ui.render': RenderInput;
2832 /**
2833 * Fires when the plugins load (not per draw), once per surface, component
2834 * and plugin: `e` names the surface and component, never the props.
2835 *
2836 * `next(e)` resolves to the surface's table, which `$.ui.resolve(e)` then
2837 * reads. Return it, one with an element restyled for every other plugin,
2838 * or one with a key left out (a fragment there); own table: hook skipped.
2839 */
2840 'ui.resolve': ResolveInput;
2841 /**
2842 * Fires when a `Button` a render hook drew is pressed on a surface; `e` is
2843 * `{ plugin, element, component, surface }`, `element` the button's `key`.
2844 *
2845 * `next(e)` runs the hooks beneath, then core: the element's own `onPress`
2846 * closure, in its plugin's environment, resolving to `{ element }`. Return
2847 * `next(e)` to let the press through, or `{ element }` to take it.
2848 */
2849 'ui.press': UiPressArgument;
2850 /**
2851 * Fires when an `Input` a render hook drew changes or is submitted; `e` is
2852 * `{ plugin, element, component, surface, kind, value }`.
2853 *
2854 * `next(e)` runs the hooks beneath, then the element's own `onInput` or
2855 * `onSubmit` with `e.value` as the chain left it, resolving to `{ element,
2856 * value }`; `next({ ...e, value })` rewrites the typing, an answer takes it.
2857 */
2858 'ui.input': UiInputArgument;
2859 /**
2860 * Fires when a `Select` a render hook drew is picked from; `e` is
2861 * `{ plugin, element, component, surface, value }`.
2862 *
2863 * `next(e)` runs the hooks beneath, then the element's own `onSelect` with
2864 * `e.value` as the chain left it, resolving to `{ element, value }`;
2865 * `next({ ...e, value })` rewrites the pick, an answer takes it.
2866 */
2867 'ui.select': UiSelectArgument;
2868 /**
2869 * Fires when a `Client` THIS plugin drew posts from its surface module
2870 * (`surface.post(data)`); only this plugin's hooks see it.
2871 *
2872 * `next.origin` names `client`: `data` came from code. Core answers `{}`;
2873 * `next({ ...e, data })` rewrites the data; `{ props }` hands the posting
2874 * instance its next props without a redraw. One per instance per frame.
2875 */
2876 'ui.message': UiMessageArgument;
2877 /**
2878 * Fires before a site's window moves: the person's wheel or scroll keys on
2879 * a `Pane` body or the `AbovePrompt` band, at its edges too; `$.ui.scroll`.
2880 *
2881 * `next(e)` moves it to `e.offset` and draws: `{}`; `next({ ...e, offset
2882 * })` elsewhere; no `next` (`{}` or `{ deny }`) leaves it undrawn, so a hook
2883 * drawing its own rows under a header moves them by `e.by` and invalidates.
2884 *
2885 * @example
2886 * on("ui.scroll", { requestId: "log" }, ($, e) => (scrollOwnRows(e.by), {}))
2887 */
2888 'ui.scroll': UiScrollInput;
2889 /**
2890 * Fires when the engine offers an agent type to the model, in the agent
2891 * listing and again at dispatch; `next(e)` resolves to `{ isOffered: true }`.
2892 *
2893 * Return `{ isOffered: false }` to keep the type out of the listing and
2894 * refuse its dispatch. A hook that fails passes it through.
2895 *
2896 * @example
2897 * on("agent.offer", { agent: "Plan" }, () => ({ isOffered: false }))
2898 */
2899 'agent.offer': AgentOfferInput;
2900 /**
2901 * Fires when the Agent tool is about to start a subagent, everything
2902 * decided and its model not yet resolved.
2903 *
2904 * `next(e)` resolves to `{ model }`. Return it, `next({ ...e, model })`,
2905 * `{ model }` of your own (an alias resolves like the tool's parameter), or
2906 * `{ deny: reason }`.
2907 */
2908 'agent.spawn': AgentSpawnInput;
2909 /**
2910 * Fires when a prompt is submitted, before the turn starts. `next(e)` runs
2911 * the hooks beneath and the UserPromptSubmit settings hooks.
2912 *
2913 * Rewrite with `next({ ...e, text })` (the user message on screen follows)
2914 * or stop it with `{ drop: reason }`; a broken plugin never blocks a prompt.
2915 * A prompt typed while a turn ran fires at Enter, with that turn's id.
2916 */
2917 'prompt.submit': PromptSubmitInput;
2918 /**
2919 * Fires when a text is about to be written into the prompt box as the
2920 * person's draft (a plugin's `$.prompt.fill`); `next(e)` writes it.
2921 *
2922 * Rewrite with `next({ ...e, text })`, or answer `{ isFilled: false }`
2923 * without `next` to keep it out; `origin` passes on as received. Core
2924 * answers `{ isFilled: false }` where no box can take it (a dialog is up).
2925 *
2926 * @example
2927 * on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
2928 */
2929 'prompt.fill': PromptFillInput;
2930 /**
2931 * Fires when a text is proposed as the prompt box's dim suggestion, Tab to
2932 * take: the engine's guess after a turn, or a plugin's `$.prompt.suggest`.
2933 *
2934 * `next(e)` shows it: `{ isShown }`. Rewrite with `next({ ...e, text })`,
2935 * or answer `{ isShown: false }` without `next` to drop it; core answers
2936 * that too while the box holds text or a turn runs.
2937 *
2938 * @example
2939 * on("prompt.suggest", { origin: { kind: "suggestion" } }, hide)
2940 */
2941 'prompt.suggest': PromptSuggestInput;
2942 /**
2943 * Fires once per named section of the system prompt, when the engine
2944 * assembles it; `next(e)` resolves to `{ text }` as core computed it.
2945 *
2946 * Sections are cached by name for the session until
2947 * `$.ui.invalidate("prompt.section")`: an unstable answer spends the
2948 * model's prompt cache on every call. A hook that fails passes it through.
2949 *
2950 * @example
2951 * on("prompt.section", { name: "memory" }, () => ({ text: null }))
2952 */
2953 'prompt.section': PromptSectionInput;
2954 /**
2955 * Fires once per conversation, when the engine computes the context blocks
2956 * its first user message carries; `next(e)` resolves to `{ blocks }`.
2957 *
2958 * Append, drop, reorder or rewrite with `next({ ...e, blocks })`; the
2959 * engine renders what comes back, in order, until
2960 * `$.ui.invalidate("prompt.context")` or a re-read (compaction, `/clear`).
2961 *
2962 * @example
2963 * on("prompt.context", () => ({ blocks: [] }))
2964 */
2965 'prompt.context': PromptContextInput;
2966 /**
2967 * Fires once per tool, when the engine first renders the tool's schema for
2968 * the model in a session; `next(e)` resolves to `{ description }`.
2969 *
2970 * Rendered schemas are cached for the session until
2971 * `$.ui.invalidate("tool.describe")`: an unstable answer spends the model's
2972 * prompt cache on every call. A hook that fails passes it through.
2973 *
2974 * @example
2975 * on("tool.describe", { tool: "Bash" }, () => ({ description: "Shell." }))
2976 */
2977 'tool.describe': ToolDescribeInput;
2978 /**
2979 * Fires when a slash command is about to run (`/name args` typed, or a
2980 * plugin's `$.command.run`); `next(e)` resolves to `{ text }`, its output.
2981 *
2982 * Core is the engine's command (a registered one has none). Rewrite `args`
2983 * with `next`, or return `{ text }` without it to answer in its place; one
2984 * after `next` replaces a printed output, not a panel or prompt it opened.
2985 *
2986 * @example
2987 * on("command.run", { command: "hello" }, () => ({ text: "hello" }))
2988 */
2989 'command.run': CommandRunInput;
2990 /**
2991 * Fires once per command, when the engine lists it for the typeahead and
2992 * `/help`; `next(e)` resolves to `{ description, argumentHint, isHidden }`.
2993 *
2994 * Listed answers are cached for the session until
2995 * `$.ui.invalidate("command.describe")`. A hook that fails passes it
2996 * through.
2997 *
2998 * @example
2999 * on("command.describe", ($, e, next) => next({ ...e, isHidden: true }))
3000 */
3001 'command.describe': CommandDescribeInput;
3002 /**
3003 * Fires when a `/config` row is about to change, from the menu or a
3004 * plugin's `$.config.set`; `next(e)` resolves to `{ value }` once written.
3005 *
3006 * Return `{ deny: reason }` to leave the row as it is (the menu says why),
3007 * or `next({ ...e, value })` to clamp it; a value of the wrong kind for
3008 * the row is refused. A row a trusted source owns is core's to refuse.
3009 *
3010 * @example
3011 * on("config.set", { key: "theme" }, () => ({ deny: "the theme stays" }))
3012 */
3013 'config.set': ConfigSetInput;
3014 /**
3015 * Fires once per `/config` row, when the menu lists it and for
3016 * `$.config.list`; `next(e)` resolves to `{ label, description, isHidden }`.
3017 *
3018 * Relabel, re-describe or hide with `next({ ...e, isHidden: true })`; the
3019 * answers are cached until `$.ui.invalidate("config.describe")` or the
3020 * loaded plugins change. A hook that fails passes the row through.
3021 *
3022 * @example
3023 * on("config.describe", { key: "tips" }, hide) // answers isHidden: true
3024 */
3025 'config.describe': ConfigDescribeInput;
3026 /**
3027 * Fires when the engine expands a skill's prompt for the model (`/name`,
3028 * the Skill tool, a preload); `next(e)` resolves to `{ text }` as computed.
3029 *
3030 * Return `{ text }` with the text the model reads instead. A hook that
3031 * fails passes it through.
3032 *
3033 * @example
3034 * on("skill.prompt", { skill: "commit" }, () => ({ text: "A haiku." }))
3035 */
3036 'skill.prompt': SkillPromptInput;
3037 /**
3038 * Fires when the engine composes a git text the model is to write (`kind`:
3039 * `commit`, `pr`, `exemption`, `remedy`); `next(e)` resolves to `{ text }`.
3040 *
3041 * Return `{ text }` with the text the model reads instead. A hook that
3042 * fails passes it through.
3043 *
3044 * @example
3045 * on("attribution.text", { kind: "commit" }, () => ({ text: "" }))
3046 */
3047 'attribution.text': AttributionTextInput;
3048 /**
3049 * Fires once per process for each loaded plugin, before the first prompt,
3050 * and again for one that loads or reloads later; `next(e)` is `{ cwd }`.
3051 *
3052 * Observe. The first is awaited, so a `$.tool.register` here is listed by
3053 * turn one. A later one (an edit, new options, `/reload-plugins`, an enable)
3054 * runs that plugin's hooks alone, so its timers start again. Not `/clear`.
3055 *
3056 * @example
3057 * on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
3058 */
3059 'session.start': SessionStartInput;
3060 /**
3061 * Fires when a delivery reaches the session (a relay's event, a peer's
3062 * message, a Remote Control prompt), before it is queued; `{ text }`.
3063 *
3064 * Rewrite with `next({ ...e, text })`, or return `{ consumed: reason }` to
3065 * take it: nothing is queued, shown or read by the model. `origin` and
3066 * `event` pass on as received; `session.send`, its dual, is reserved.
3067 *
3068 * @example
3069 * on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
3070 */
3071 'session.receive': SessionReceiveInput;
3072 /**
3073 * Fires when the conversation is about to be compacted (`/compact`, the
3074 * threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
3075 *
3076 * Rewrite `instructions` or `messages` on the way down, the messages on
3077 * the way up, or answer `{ messages }` of your own; `{ skip: reason }`
3078 * leaves the conversation as it is. `trigger` passes on as received.
3079 *
3080 * @example
3081 * on("session.compact", { trigger: "precompute" }, () => ({ skip: "off" }))
3082 */
3083 'session.compact': SessionCompactInput;
3084 /**
3085 * Fires when a remote client joins the session's roster of attached
3086 * surfaces: it said so (ui_attach), or it first asked to draw.
3087 *
3088 * Observe (a phone joined: draw the lobby); `next(e)` resolves to
3089 * `{ clientId }`, a different return changes nothing. `$.session.surfaces()`
3090 * reads the roster; a render hook still reads `e.surface` per ask.
3091 *
3092 * @example
3093 * on("session.attach", { surface: "mobile" }, ($, e, next) => next(e))
3094 */
3095 'session.attach': SessionAttachInput;
3096 /**
3097 * Fires when a client leaves the roster: it detached, or the session ended
3098 * with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
3099 */
3100 'session.detach': SessionDetachInput;
3101 /**
3102 * Fires once per hooks module about to join the chain, at load (the set
3103 * folded and built, nothing swapped in) and at reload; core allows.
3104 *
3105 * Return `{ refuse: reason }` and it never joins: no hook, no noun, no tool
3106 * of it; the transcript names who refused. Its judges, `$` whole, are the
3107 * plugins admitted before it and the binary's; judge by `tier` and `uses`.
3108 *
3109 * @example
3110 * on("plugin.register", { tier: "user" }, () => ({ refuse: "managed only" }))
3111 */
3112 'plugin.register': PluginRegisterInput;
3113 /**
3114 * Fires when a model turn begins, before its first model call; `next(e)`
3115 * resolves to `{ turnId }`. Observe: a different return changes nothing.
3116 */
3117 'turn.start': TurnStartInput;
3118 /**
3119 * Fires when the engine is about to send a model request of a turn, main's
3120 * or a subagent's (`e.agentId`); `next(e)` resolves to the whole response.
3121 *
3122 * `next({ ...e, model })` or `effort` sends another; the turn, the index and
3123 * the message count are pinned. An answer without `next` sends no request.
3124 * Every request of the turn passes here; `turn.complete` follows the last.
3125 */
3126 'turn.step': TurnStepInput;
3127 /**
3128 * Fires when a model turn has ended, at the point its duration is reported;
3129 * `next(e)` resolves to `{ text }`, the answer. `e.reason` says why.
3130 *
3131 * Return `{ text }` with a different text to show it beneath the answer (a
3132 * synopsis, a TL;DR line); the transcript's record is never rewritten. A
3133 * hook that fails leaves the answer as it was.
3134 */
3135 'turn.complete': TurnCompleteInput;
3136 /**
3137 * Runs while `$` is being built, once per load or reload of this plugin
3138 * and before any other hook of it; `next(e)` resolves to `$` built so far.
3139 *
3140 * A step may ADD nouns and WITHHOLD nouns (leave one out, or return without
3141 * `next`); it may NOT REPLACE one another step added: the step fails, named
3142 * with both plugins. A step that fails unloads its plugin; `$` is rebuilt.
3143 */
3144 'engine.create': EngineCreateInput;
3145 };
3146
3147 /**
3148 * `$`, the first parameter of every hook. Frozen; core's interface plus
3149 * every noun the plugins' `engine.create` steps added.
3150 *
3151 * Flat, `<noun>.<event>`; it does not carry `on`, since registration happens
3152 * before `$` exists. An interface so a plugin types the noun it provides by
3153 * declaration merging, the way a jQuery plugin types `$.fn`.
3154 *
3155 * @example
3156 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
3157 */
3158 export interface EngineInterface extends CoreEngineInterface {
3159 }
3160
3161 /**
3162 * What `next(e)` resolves to at `engine.create`: `$` as the steps beneath
3163 * built it, typed as `$` is, open to nouns no declaration names yet.
3164 *
3165 * A withheld noun is on it as a stub (a step inside withheld it, or the
3166 * last fold did and this is a reload), and the host refuses an op on one a
3167 * step outside withholds later; a typed module bootstraps at load on it.
3168 */
3169 export type EngineInterfaceBuilt = EngineInterface & {
3170 readonly [noun: string]: unknown;
3171 };
3172
3173 /**
3174 * The engine's events' results.
3175 */
3176 export type EngineResultOf = {
3177 /**
3178 * `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`.
3179 */
3180 'tool.call': ToolCallResult;
3181 /**
3182 * `{ decision, reason?, rule? }`.
3183 */
3184 'tool.check': ToolCheckResult;
3185 /**
3186 * The tree to draw; `{ type: "engine", ref }` is core's own drawing.
3187 */
3188 'ui.render': RenderElement;
3189 /**
3190 * The surface's element table (Elements[e.surface]): constructors from props
3191 * to a RenderElement.
3192 */
3193 'ui.resolve': ElementTable;
3194 /**
3195 * `{ element }`: the element whose handler the press reached.
3196 */
3197 'ui.press': UiPressResult;
3198 /**
3199 * `{ element, value }`: the field whose handler the input reached, and
3200 * the text it received.
3201 */
3202 'ui.input': UiInputResult;
3203 /**
3204 * `{ element, value }`: the picker whose handler the pick reached, and
3205 * the value it received.
3206 */
3207 'ui.select': UiSelectResult;
3208 /**
3209 * `{ props? }`: the posting instance's next props, when a hook hands some.
3210 */
3211 'ui.message': UiMessageResult;
3212 /**
3213 * `{}` once the window moved, or `{ deny }`.
3214 */
3215 'ui.scroll': UiScrollResult;
3216 /**
3217 * `{ isOffered }`.
3218 */
3219 'agent.offer': AgentOfferResult;
3220 /**
3221 * `{ model }` or `{ deny }`.
3222 */
3223 'agent.spawn': AgentSpawnResult;
3224 /**
3225 * `{ text, context? }` or `{ drop }`.
3226 */
3227 'prompt.submit': PromptSubmitResult;
3228 /**
3229 * `{ isFilled }`.
3230 */
3231 'prompt.fill': PromptFillResult;
3232 /**
3233 * `{ isShown }`.
3234 */
3235 'prompt.suggest': PromptSuggestResult;
3236 /**
3237 * `{ text }` (null leaves the section out).
3238 */
3239 'prompt.section': PromptSectionResult;
3240 /**
3241 * `{ blocks }` (a block left out is not sent).
3242 */
3243 'prompt.context': PromptContextResult;
3244 /**
3245 * `{ description }`.
3246 */
3247 'tool.describe': ToolDescribeResult;
3248 /**
3249 * `{ text }` (the command's output, when it printed one).
3250 */
3251 'command.run': CommandRunResult;
3252 /**
3253 * `{ description, argumentHint, isHidden }`.
3254 */
3255 'command.describe': CommandDescribeResult;
3256 /**
3257 * `{ value }` once written, or `{ deny }`.
3258 */
3259 'config.set': ConfigSetResult;
3260 /**
3261 * `{ label, description, isHidden }`.
3262 */
3263 'config.describe': ConfigDescribeResult;
3264 /**
3265 * `{ text }`.
3266 */
3267 'skill.prompt': SkillPromptResult;
3268 /**
3269 * `{ text }`.
3270 */
3271 'attribution.text': AttributionTextResult;
3272 /**
3273 * `{ cwd }`.
3274 */
3275 'session.start': SessionStartResult;
3276 /**
3277 * `{ text }`, or `{ consumed }`.
3278 */
3279 'session.receive': SessionReceiveResult;
3280 /**
3281 * `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
3282 */
3283 'session.compact': SessionCompactResult;
3284 /**
3285 * `{ clientId }`.
3286 */
3287 'session.attach': SessionAttachResult;
3288 /**
3289 * `{ clientId }`.
3290 */
3291 'session.detach': SessionDetachResult;
3292 /**
3293 * `{ allow: true }`, or `{ refuse }`.
3294 */
3295 'plugin.register': PluginRegisterResult;
3296 /**
3297 * `{ turnId }`.
3298 */
3299 'turn.start': TurnStartResult;
3300 /**
3301 * The response: `{ turnId, index, answer, toolUses, stopReason, usage }`.
3302 */
3303 'turn.step': TurnStepResult;
3304 /**
3305 * `{ text }`.
3306 */
3307 'turn.complete': TurnCompleteResult;
3308 /**
3309 * `$` as built so far, with this plugin's interface added and any it
3310 * withheld left out; `next(e)` resolves to EngineInterfaceBuilt.
3311 */
3312 'engine.create': EngineCreateResult;
3313 };
3314
3315 /**
3316 * The engine's own events as calls on `$`, one signature each:
3317 * `$.<noun>.<event>(input)` resolves to its result, or to its stream.
3318 *
3319 * The engine raises its events through these same calls; a plugin's call
3320 * runs the same chain with the calling hook alone skipped. `input` may leave
3321 * out what the engine fills (`tool_use_id`, the parent agent).
3322 */
3323 export type EventCalls = {
3324 tool: {
3325 call: ToolCallOverloads;
3326 check: (input: ToolCheckArgs) => Promise<ToolCheckResult>;
3327 describe: (input: ToolDescribeInput) => Promise<ToolDescribeResult>;
3328 };
3329 command: {
3330 run: (input: CommandRunArgs) => Promise<CommandRunResult>;
3331 describe: (input: CommandDescribeInput) => Promise<CommandDescribeResult>;
3332 };
3333 config: {
3334 set: (input: ConfigSetArgs) => Promise<ConfigSetResult>;
3335 describe: (input: ConfigDescribeInput) => Promise<ConfigDescribeResult>;
3336 };
3337 prompt: {
3338 submit: (input: PromptSubmitArgs) => Promise<PromptSubmitResult>;
3339 fill: (input: PromptFillArgs) => Promise<PromptFillResult>;
3340 suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
3341 section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
3342 context: (input: PromptContextInput) => Promise<PromptContextResult>;
3343 };
3344 skill: {
3345 prompt: (input: SkillPromptInput) => Promise<SkillPromptResult>;
3346 };
3347 attribution: {
3348 text: (input: AttributionTextInput) => Promise<AttributionTextResult>;
3349 };
3350 agent: {
3351 offer: (input: AgentOfferInput) => Promise<AgentOfferResult>;
3352 spawn: (input: AgentSpawnArgs) => Promise<AgentSpawnResult>;
3353 };
3354 session: {
3355 start: (input: SessionStartInput) => Promise<SessionStartResult>;
3356 receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
3357 compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
3358 attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
3359 detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
3360 };
3361 turn: {
3362 start: (input: TurnStartInput) => Promise<TurnStartResult>;
3363 step: (input: TurnStepInput) => HookStream<TurnStepChunk, TurnStepResult>;
3364 complete: (input: TurnCompleteInput) => Promise<TurnCompleteResult>;
3365 };
3366 ui: {
3367 render: <C extends RenderComponent>(input: RenderInput<C>) => Promise<RenderElement>;
3368 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
3369 scroll: (input: UiScrollArgs) => Promise<UiScrollResult>;
3370 };
3371 };
3372
3373 /**
3374 * The name of an event: a key of EventOf, the engine's own (CoreEventName)
3375 * and the declared plugin nouns' (NounEventName).
3376 */
3377 export type EventName = keyof EventOf;
3378
3379 /**
3380 * The argument of each event, by event name: what a hook receives as `e`
3381 * and what the call on `$` takes. Plain data, frozen to every depth.
3382 *
3383 * The engine's own events (CoreEventOf: a plugin's `$.fs.write(...)` is
3384 * a dispatch the hooks above it see) and the methods of the plugin nouns
3385 * declared on EngineInterface (NounEventOf).
3386 */
3387 export type EventOf = CoreEventOf & NounEventOf;
3388
3389 /**
3390 * The result of event `N`: what its hooks return and what their `next(e)`
3391 * resolves to.
3392 */
3393 export type EventResult<N extends EventName = EventName> = ResultOf[N];
3394
3395 /**
3396 * The hook signature of each event, `($, e, next)`, as one mapped type over
3397 * EventOf; a streaming event's is the generator form (StreamHook).
3398 *
3399 * With one handler type per event, `Events[E]` for a generic E would be a
3400 * union; as one mapped type it stays a single function type the engine
3401 * calls without a cast (TS 4.6 correlated unions).
3402 *
3403 * @param $ the engine interface, frozen, the same object at every invocation;
3404 * at `engine.create` the empty table, since `$` exists after the fold
3405 * @param e the event's argument, frozen to every depth (`e.command = "ls"`
3406 * is a type error and throws); a rewrite is a copy passed to `next`
3407 * @param next the rest of the chain; a chain a hook raises through `$` skips
3408 * this hook and runs every other, its plugin's others too
3409 */
3410 export type Events = {
3411 [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>>;
3412 };
3413
3414 type ExitReason = 'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other';
3415
3416 type FileChangedHookInput = BaseHookInput & {
3417 hook_event_name: 'FileChanged';
3418 file_path: string;
3419 event: 'change' | 'add' | 'unlink';
3420 };
3421
3422 /**
3423 * `T` with every property read-only to every depth, arrays and tuples kept
3424 * as declared: how a hook's `e` is typed.
3425 *
3426 * `e.command = 'x'` is a type error; `next({ ...e, command: 'x' })` compiles.
3427 */
3428 export type Frozen<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? {
3429 [K in keyof T]: Frozen<T[K]>;
3430 } : T extends object ? {
3431 readonly [K in keyof T]: Frozen<T[K]>;
3432 } : T;
3433
3434 /**
3435 * One file `$.fs.ancestors` found: the directory it stands in, the name it
3436 * was asked for by, and its text as the engine's memory loader reads it.
3437 */
3438 export type FsAncestor = {
3439 /**
3440 * The directory the file stands in, absolute.
3441 */
3442 dir: string;
3443 /**
3444 * The spelling the caller asked for it by.
3445 */
3446 name: string;
3447 /**
3448 * The file's text, with what its `@include`s bring after it.
3449 */
3450 content: string;
3451 };
3452
3453 /**
3454 * The argument of `$.fs.ancestors`: the file names to look for in each
3455 * directory, and the file to walk down to.
3456 */
3457 export type FsAncestorsRequest = {
3458 /**
3459 * Relative `.md` file names, each looked for in every directory.
3460 */
3461 names: readonly string[];
3462 /**
3463 * The file the walk goes on down to the directory of, relative to the
3464 * working directory or absolute; absent, it ends at the working directory.
3465 */
3466 of?: string;
3467 };
3468
3469 /**
3470 * One entry of `$.fs.list`.
3471 */
3472 export type FsEntry = {
3473 /**
3474 * The entry's name (no directory part).
3475 */
3476 name: string;
3477 /**
3478 * `file`, `dir`, or `other`.
3479 */
3480 kind: 'file' | 'dir' | 'other';
3481 /**
3482 * Bytes, for a file.
3483 */
3484 size: number;
3485 };
3486
3487 /**
3488 * What `$.fs.stat` resolves with.
3489 */
3490 export type FsStat = {
3491 /**
3492 * `file`, `dir`, or `other`.
3493 */
3494 kind: 'file' | 'dir' | 'other';
3495 /**
3496 * Bytes, for a file.
3497 */
3498 size: number;
3499 /**
3500 * Last modification, milliseconds since the epoch.
3501 */
3502 mtimeMs: number;
3503 };
3504
3505 /**
3506 * Every event (`*`), or every event under a namespace (`classic.*`: each
3507 * one whose name starts with `classic.`).
3508 */
3509 export type Glob = '*' | `${Namespace}.*`;
3510
3511 /**
3512 * The hook `on(pattern, hook)` takes for a glob or a negation: one function
3513 * placed on every selected event, `e` and the result typed as their union.
3514 *
3515 * `next.event` says which event a run is; `next.is(pattern, e)` narrows `e`
3516 * to one of them. At `engine.create` (a negation may select it) `$` is the
3517 * empty table and the hook observes the fold, as a `*` hook does.
3518 */
3519 export type GlobHook<P extends Pattern, N extends EventName = Selected<P>> = ($: EngineInterface, e: Frozen<Args<N>>, next: GlobNext<P>) => EventResult<N> | Promise<EventResult<N>>;
3520
3521 /**
3522 * `next` in a hook on a glob or a negation: an overload per selected event,
3523 * then one over their union for an `e` not yet narrowed.
3524 *
3525 * `is` narrows `e` to the selected events its pattern names; `event` is one
3526 * of the selected names.
3527 */
3528 export type GlobNext<P extends Pattern, N extends EventName = Selected<P>> = OrderedOverloads<N> & {
3529 (e: Args<N>): Promise<GlobNextResult<N>>;
3530 /**
3531 * Continues this dispatch at a tier, as Next's `to` (a managed hook's),
3532 * over the selected events' union for an `e` not yet narrowed.
3533 */
3534 readonly to: (e: Args<N>, tier: TargetTier) => Promise<GlobNextResult<N>>;
3535 readonly signal: AbortSignal;
3536 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<Args<Extract<N, Selected<M>>>>;
3537 readonly event: N;
3538 readonly origin: Origin;
3539 readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
3540 };
3541
3542 /**
3543 * What `next(e)` resolves to in a glob hook before `e` is narrowed: the
3544 * NextResult of each selected event, as a union.
3545 */
3546 type GlobNextResult<N extends EventName> = {
3547 [K in N]: NextResult<K>;
3548 }[N];
3549
3550 /**
3551 * One hook, `($, e, next)`, on event `E`.
3552 */
3553 export type Hook<E extends EventName = EventName> = Events[E];
3554
3555 /**
3556 * Why a hook failed, as its `.catch` handler reads it on `next.error`: plain
3557 * frozen data.
3558 *
3559 * `throw`: the hook threw, or returned what the site refuses, `message`
3560 * saying what; `timeout`: it outran its budget, `message` then what its last
3561 * `next()` rejected with, if it did. `budget` is the handler's own grace.
3562 */
3563 export type HookFailure = {
3564 readonly kind: 'throw' | 'timeout';
3565 /**
3566 * The thrown error's message, or for a timeout what the hook's last
3567 * `next()` rejected with; absent for a timeout with nothing rejected.
3568 */
3569 readonly message?: string;
3570 /**
3571 * The grace the handler runs under, in milliseconds; past it, the hook is
3572 * absent as if it had no handler.
3573 */
3574 readonly budget: number;
3575 };
3576
3577 /**
3578 * The hook type per pattern: an event's own (Events), `*`'s (AnyEventHook),
3579 * or a glob's over the events it selects (GlobHook), as one conditional type.
3580 *
3581 * One type, so the two-argument `on` stays ONE generic signature: as an
3582 * overload set the language service offers no tool-name completions inside
3583 * `e.tool === "`; as an index into a table TS intersects every argument.
3584 */
3585 export type HookFor<P extends Pattern> = P extends '*' ? AnyEventHook : P extends EventName ? Events[P] : GlobHook<P>;
3586
3587 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;
3588
3589 /**
3590 * The hook event `E` takes: an async generator over its chunks for a
3591 * streaming event (`turn.step`), `($, e, next) => result` for every other.
3592 */
3593 export type HookOf<E extends EventName> = Events[E];
3594
3595 /**
3596 * What a hooks module exports: `register`, and nothing the loader reads
3597 * besides.
3598 */
3599 export type HooksModule = {
3600 register: Register;
3601 };
3602
3603 /**
3604 * What `next(e)` returns on a streaming event: the stream of everything
3605 * beneath, chunk by chunk, whose return value is the result from beneath.
3606 *
3607 * `yield* next(e)` forwards the chunks and evaluates to that result; a
3608 * transforming hook reads `for await (const chunk of stream)` and then
3609 * `await stream.result`. Each call runs what is beneath afresh.
3610 */
3611 export type HookStream<C, R> = AsyncGenerator<C, R> & {
3612 /**
3613 * Settles with what beneath returned once the stream has been read to
3614 * its end; rejects if the stream is closed before that.
3615 */
3616 readonly result: Promise<R>;
3617 };
3618
3619 /**
3620 * Options of `$.http.fetch`.
3621 */
3622 export type HttpInit = {
3623 /**
3624 * `GET` (default), `POST`, ...
3625 */
3626 method?: string;
3627 /**
3628 * Request headers.
3629 */
3630 headers?: Record<string, string>;
3631 /**
3632 * The request body, as text.
3633 */
3634 body?: string;
3635 /**
3636 * The handle `$.session.authorize()` answered: the engine sets the
3637 * session's credential header itself, only for a first-party host.
3638 */
3639 auth?: string;
3640 };
3641
3642 /**
3643 * What `$.http.fetch` resolves with.
3644 */
3645 export type HttpResponse = {
3646 /**
3647 * The HTTP status code.
3648 */
3649 status: number;
3650 /**
3651 * True for a 2xx status.
3652 */
3653 ok: boolean;
3654 /**
3655 * Response headers, lower-cased names.
3656 */
3657 headers: Record<string, string>;
3658 /**
3659 * The body, as text.
3660 */
3661 text: string;
3662 };
3663
3664 /**
3665 * The keys of object pattern `P` that object member `E` cannot satisfy, `D`
3666 * levels down; `never` when there is none, which is what keeps the member.
3667 *
3668 * A key `E` does not have (an open record has every string key), or one
3669 * whose value `P` narrows to nothing.
3670 */
3671 type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
3672 [K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
3673 }[keyof P];
3674
3675 /**
3676 * The props of `Input`, every surface's one-line text field: an address,
3677 * optional texts, and the closures a change and a submit run. A leaf.
3678 *
3679 * Focused through the same ring as `Button` (`abovePrompt:focus`); while it
3680 * has focus every printable key reaches it alone and Esc returns them; a
3681 * change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
3682 */
3683 export type InputProps = {
3684 /**
3685 * The element's address: `e.element` at `ui.input`, what a matcher names.
3686 */
3687 key: string;
3688 /**
3689 * Text drawn before the field.
3690 */
3691 label?: string;
3692 /**
3693 * Text drawn dim in an empty field.
3694 */
3695 placeholder?: string;
3696 /**
3697 * The text the field holds when drawn; the person's typing replaces it
3698 * until the hook draws another.
3699 */
3700 value?: string;
3701 /**
3702 * What Enter does, in a word or two, drawn beside the field while it has
3703 * focus (`send`). Defaults to `submit`.
3704 */
3705 submitLabel?: string;
3706 /**
3707 * Runs on every change of the text, in the plugin's own environment: the
3708 * bottom of a `ui.input` chain of kind `change`.
3709 */
3710 onInput?: (value: string, e: UiInputArgument) => void;
3711 /**
3712 * Runs on Enter with the text, in the plugin's own environment: the bottom
3713 * of a `ui.input` chain of kind `submit`. No model turn unless it asks one.
3714 */
3715 onSubmit: (value: string, e: UiInputArgument) => void;
3716 };
3717
3718 type InstructionsLoadedHookInput = BaseHookInput & {
3719 hook_event_name: 'InstructionsLoaded';
3720 file_path: string;
3721 memory_type: 'User' | 'Project' | 'Local' | 'Managed';
3722 load_reason: 'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact';
3723 globs?: string[];
3724 trigger_file_path?: string;
3725 parent_file_path?: string;
3726 };
3727
3728 /**
3729 * What `$.ui.invalidate` takes: a render event, or one of the five events
3730 * whose answers the engine caches for the session.
3731 */
3732 export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'tool.describe' | 'command.describe' | 'config.describe';
3733
3734 /**
3735 * Whether tag key `K` selects members of `I`: it does when each member gives
3736 * it ONE literal (`component: "ToolUse"` on the ToolUse variant).
3737 *
3738 * A key that is the same union on every member is a filter at runtime; it
3739 * is left out of the selection so that it cannot defeat the narrowing the
3740 * other keys give.
3741 */
3742 type IsDiscriminant<I, K> = I extends unknown ? K extends KnownKeys<I> ? IsSingleLiteral<I[K]> : true : never;
3743
3744 /**
3745 * Whether `V` is made of literals only: `"a" | "b"` is, `string` is not.
3746 */
3747 type IsLiteralValued<V> = string extends V ? false : number extends V ? false : boolean extends V ? false : [V] extends [string | number | boolean] ? true : false;
3748
3749 /**
3750 * Whether `V` is exactly one string, number or boolean literal.
3751 */
3752 type IsSingleLiteral<V> = [V] extends [string | number | boolean] ? IsUnion<V> extends true ? false : true : false;
3753
3754 /**
3755 * Whether `T` is a union of two or more members.
3756 */
3757 type IsUnion<T, U = T> = T extends unknown ? [U] extends [T] ? false : true : never;
3758
3759 /**
3760 * Plain data: what JSON holds, and what crosses between a plugin's hooks
3761 * module and its surface module whole (a `Client`'s props, a post's data).
3762 *
3763 * A function, a class instance, `undefined` or a cycle is not plain data;
3764 * the engine refuses one where it checks, and drops it where it clones.
3765 */
3766 export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
3767 readonly [key: string]: JsonValue;
3768 };
3769
3770 /**
3771 * What `next` takes in a matched hook: the variants of `e` the matcher can
3772 * match (KeptMembers), as declared, so a rewrite of a pinned field passes.
3773 */
3774 type KeptEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? KeptMembers<Args<N>, M> : never : never;
3775
3776 /**
3777 * The members of the argument union `E` matcher `P` can match, as declared;
3778 * what `next` takes, so a rewrite may change a field the matcher pinned.
3779 *
3780 * A member is dropped when `P` names a key it lacks, or gives a key, at any
3781 * depth, a value none of that key's values can equal (ImpossibleKeys).
3782 */
3783 type KeptMembers<E, P> = E extends unknown ? [ImpossibleKeys<E, P, []>] extends [never] ? E : never : never;
3784
3785 /**
3786 * The declared keys of `T`, the string and number index signatures left out.
3787 */
3788 type KnownKeys<T> = keyof {
3789 [K in keyof T as string extends K ? never : number extends K ? never : K]: 0;
3790 };
3791
3792 /**
3793 * The events whose overload must come after the rest, lest it shadow them.
3794 *
3795 * `classic.PreToolUse` shares `tool.call`'s envelope, `turn.abort` every
3796 * turn event's `turnId`, and an object of any shape is assignable to NoArgs.
3797 */
3798 type LateOverload = 'classic.PreToolUse' | 'turn.abort' | NoArgsEvent;
3799
3800 /**
3801 * The props of `Link`, a hyperlink every surface draws: an OSC 8 span on the
3802 * terminal (else its text then the URL in dim), an anchor on desktop.
3803 *
3804 * An inline element: its children are the text, strings and inline
3805 * elements; absent children the `label`, absent both the URL. The engine
3806 * bounds `href` before the tree crosses.
3807 */
3808 export type LinkProps = {
3809 /**
3810 * Where the link goes: an `https:` URL (or `http://localhost`), at most
3811 * 2048 characters of printable ASCII, spelled as `new URL(href).href`.
3812 *
3813 * No `user@host` part, no raw `@`, space or non-ASCII letter (encode them);
3814 * anything else refuses the tree the Link is in.
3815 */
3816 href: string;
3817 /**
3818 * The text drawn when the element has no children; absent both, the URL
3819 * itself is the text.
3820 */
3821 label?: string;
3822 };
3823
3824 /**
3825 * What a matcher value selects by: itself, or `unknown` for a RegExp, which
3826 * selects nothing.
3827 */
3828 type Literal<X> = X extends RegExp ? unknown : X;
3829
3830 /**
3831 * The argument a matched hook receives: `e` narrowed by `M` (Narrowed), per
3832 * event the registration covers.
3833 */
3834 export type MatchedEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Narrowed<Args<N>, M> : never : never;
3835
3836 /**
3837 * The hook `on(pattern, matcher, hook)` takes: `($, e, next)` with `e`
3838 * narrowed by the matcher (MatchedEvent), and a tagged result the same way.
3839 *
3840 * On a streaming event it is the generator form (MatchedStreamHook). `next`
3841 * takes the variants the matcher keeps, as declared (KeptEvent); `next.is`
3842 * names the events the registration covers and narrows as the matcher does.
3843 */
3844 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>, {
3845 [K in MatchedNames<P, M>]: Narrowed<Args<K>, M>;
3846 }>) => MatchedResult<P, M> | Promise<MatchedResult<P, M>>;
3847
3848 /**
3849 * The events a matched registration on `P` covers: the event named, or for a
3850 * glob every selected event whose input has each key the matcher names.
3851 */
3852 type MatchedNames<P, M = never> = P extends EventName ? P : {
3853 [N in Selected<P & string>]: [M] extends [never] ? N : keyof M extends AnyKeyOf<Args<N>> ? N : never;
3854 }[Selected<P & string>];
3855
3856 /**
3857 * What a matched hook returns: the event's result, narrowed by `M` where the
3858 * result is a union tagged by the matcher's tag keys.
3859 */
3860 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;
3861
3862 /**
3863 * The hook `on(event, matcher, hook)` takes on a streaming event: the
3864 * generator form, `e` narrowed by the matcher, `next(e)` the stream beneath.
3865 */
3866 export type MatchedStreamHook<P extends StreamingEventName, M> = ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: MatchedStreamNext<P, M>) => StreamHookBody<Chunk<P>, MatchedResult<P, M>>;
3867
3868 /**
3869 * What a matched streaming hook's `next.is(pattern, e)` narrows `e` to:
3870 * the streaming event's argument narrowed by the matcher.
3871 */
3872 type MatchedStreamNarrowings<P extends StreamingEventName, M> = {
3873 [K in P]: Narrowed<Args<K>, M>;
3874 };
3875
3876 /**
3877 * A matched streaming hook's `next`: the variants the matcher keeps, the
3878 * result tagged the same way, `next.is` narrowing as the matcher does.
3879 */
3880 type MatchedStreamNext<P extends StreamingEventName, M> = StreamNext<P, KeptEvent<P, M>, MatchedResult<P, M>, MatchedStreamNarrowings<P, M>>;
3881
3882 /**
3883 * What `on(event, matcher, hook)` takes for an argument of type `I`: the
3884 * shape of the `e` the hook wants, a partial of it at any depth.
3885 *
3886 * A leaf is `===` or a RegExp (`{ command: /^p4 / }`); an array is any-of;
3887 * an object is a partial of an OBJECT, so `{ command: { startsWith } }` is
3888 * a type error where `e` is typed and free where it is `unknown`.
3889 */
3890 export type Matcher<I, All = I> = I extends unknown ? {
3891 readonly [K in KnownKeys<I>]?: MatcherValue<I[K], MatcherValueOf<All, K>>;
3892 } & (string extends keyof I ? OpenMatcher<I, All> : unknown) : never;
3893
3894 /**
3895 * Any matcher at all, for a field typed `unknown` (a tool's input, a
3896 * result's output): the kinds the engine accepts, unchecked there.
3897 *
3898 * The four kinds: a scalar is `===`; a RegExp tests the value as a string
3899 * (`{ command: /^p4 / }`); an array matches if any element does; an object
3900 * is a partial of an object. `{ startsWith: 'p4' }` never matches a string.
3901 */
3902 type MatcherData = string | number | boolean | null | RegExp | readonly MatcherData[] | {
3903 readonly [key: string]: MatcherData;
3904 };
3905
3906 /**
3907 * The declared keys of every variant of `I` (index signatures aside).
3908 */
3909 type MatcherKeys<I> = I extends unknown ? KnownKeys<I> : never;
3910
3911 /**
3912 * What matches one value of type `V`, by the runtime's kinds:
3913 * a scalar leaf takes the value or a RegExp; an object, a partial of it.
3914 *
3915 * For an array, what matches one ELEMENT of it, since a pattern against an
3916 * array value holds when some element matches; for `unknown`, any matcher.
3917 * A scalar matches by `===`, a RegExp tests the value as a string.
3918 */
3919 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;
3920
3921 /**
3922 * What a matcher gives a key whose value is `V` on this variant and `Across`
3923 * over every variant: one MatcherOne, or an array of them matched as one-of.
3924 *
3925 * The one-of is typed over every variant, so `{ tool: ['Bash', 'Read'] }`
3926 * types on the Bash variant; with a nested pattern beside it, the pattern is
3927 * checked against a variant the one-of names, not against each of them.
3928 */
3929 type MatcherValue<V, Across = V> = MatcherOne<V> | readonly MatcherOne<Across>[];
3930
3931 /**
3932 * The type of key `K` across the variants of `I` that declare it.
3933 */
3934 type MatcherValueOf<I, K> = I extends unknown ? K extends KnownKeys<I> ? I[K] : never : never;
3935
3936 /**
3937 * One block of an MCP result: `type` and the fields that kind of block carries.
3938 */
3939 export type McpContentBlock = {
3940 /**
3941 * The block's kind: `text`, `image`, `audio`, `resource`, `resource_link`.
3942 */
3943 type: string;
3944 /**
3945 * Set on a `text` block.
3946 */
3947 text?: string;
3948 /**
3949 * Set on a `resource_link` (or embedded `resource`) block.
3950 */
3951 uri?: string;
3952 /**
3953 * Declared by an image, audio or resource block.
3954 */
3955 mimeType?: string;
3956 [field: string]: unknown;
3957 };
3958
3959 /**
3960 * The MCP branch: one variant per declared tool when McpToolInputs has
3961 * entries, else one loose variant over every `mcp__*` name.
3962 */
3963 export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
3964 [N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
3965 }[keyof McpToolInputs & string];
3966
3967 /**
3968 * The MCP branch's answer when no MCP tool is declared: every `mcp__*`
3969 * name, its args unconstrained.
3970 */
3971 type McpToolCallInputFallback = {
3972 /**
3973 * The name of the tool being called (`mcp__<server>__<tool>`); comparing
3974 * it narrows `e`. Reserved: a rewrite of it is ignored by core.
3975 */
3976 tool: McpToolName;
3977 /**
3978 * The tool_use block's id: the same at every event of the call and in
3979 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
3980 */
3981 tool_use_id: string;
3982 [argument: string]: unknown;
3983 };
3984
3985 /**
3986 * The inputs of the MCP tools this project knows, keyed by full tool name,
3987 * for declaration merging; empty by default, then every MCP tool is loose.
3988 *
3989 * A `.d.ts` in the plugin author's project (written by `/plugin-types <dir>`
3990 * from the connected servers' JSON Schemas, or by hand) adds entries under
3991 * `declare module "claude-code"`; `e.tool === <name>` then narrows to them.
3992 *
3993 * @example
3994 * interface McpToolInputs { "mcp__my_server__send": { to: string } }
3995 */
3996 export interface McpToolInputs {
3997 }
3998
3999 /**
4000 * The name of an MCP tool as the engine spells it: `mcp__<server>__<tool>`.
4001 */
4002 export type McpToolName = `mcp__${string}__${string}`;
4003
4004 /**
4005 * An MCP tools/call result as the SDK returns it, plain data.
4006 */
4007 export type McpToolResult = {
4008 /**
4009 * The result's content blocks, in order (text, image, resource,
4010 * resource_link, ...).
4011 */
4012 content: McpContentBlock[];
4013 /**
4014 * True when the server reported the call as failed; the blocks then describe
4015 * the error.
4016 */
4017 isError: boolean;
4018 /**
4019 * The server's structured result, when its tool declares an output schema.
4020 */
4021 structuredContent?: unknown;
4022 };
4023
4024 /**
4025 * 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.
4026 */
4027 type MessageDisplayHookInput = BaseHookInput & {
4028 hook_event_name: 'MessageDisplay';
4029 /**
4030 * UUID of the current turn.
4031 */
4032 turn_id: string;
4033 /**
4034 * UUID of the assistant message being displayed. Stable across every flush of the same message. Not the API msg_... id.
4035 */
4036 message_id: string;
4037 /**
4038 * Zero-based index of this delta within the message. Increments by one per flush.
4039 */
4040 index: number;
4041 /**
4042 * True on the message's last flush. Exactly one flush per message has it.
4043 */
4044 final: boolean;
4045 /**
4046 * 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.
4047 */
4048 delta: string;
4049 };
4050
4051 /**
4052 * What `$.model.complete` takes.
4053 */
4054 export type ModelCompleteRequest = {
4055 /**
4056 * An alias (`haiku`) or a full model id; resolved and allowlist-checked like
4057 * a `--model` value.
4058 */
4059 model: string;
4060 /**
4061 * The one user message; the reply's text comes back.
4062 */
4063 prompt: string;
4064 /**
4065 * Precedes the completion as its system prompt, after the CLI's identity
4066 * block. Default none.
4067 */
4068 system?: string;
4069 /**
4070 * The reply's token cap. Default 256.
4071 */
4072 maxTokens?: number;
4073 };
4074
4075 /**
4076 * What `$.model.fork` takes.
4077 */
4078 export type ModelForkRequest = {
4079 /**
4080 * The one user message, appended to the session's own transcript.
4081 *
4082 * The reply's text and usage come back, or null on an API error or a cold
4083 * transcript.
4084 */
4085 prompt: string;
4086 };
4087
4088 /**
4089 * What `$.model.fork` resolves to when the fork answered: the reply's text
4090 * and what the fork cost.
4091 */
4092 export type ModelForkResult = {
4093 /**
4094 * The non-error replies' text, joined by newlines.
4095 */
4096 text: string;
4097 /**
4098 * The fork's token counts, so a plugin can account for what it spent.
4099 */
4100 usage: ModelForkUsage;
4101 };
4102
4103 /**
4104 * What one fork cost, as the API counted it: the four token counts of the
4105 * fork's completions summed.
4106 */
4107 export type ModelForkUsage = {
4108 input_tokens: number;
4109 output_tokens: number;
4110 cache_read_input_tokens: number;
4111 cache_creation_input_tokens: number;
4112 };
4113
4114 /**
4115 * The prefixes a glob may name: one or more whole leading segments of an
4116 * event name (`tool` of `tool.call`), derived, plugin nouns included.
4117 */
4118 export type Namespace<N extends string = EventName> = N extends `${infer Head}.${infer Rest}` ? Head | `${Head}.${Namespace<Rest>}` : never;
4119
4120 /**
4121 * How many object or array levels a matcher narrows `e` through, counted as
4122 * a tuple's length: the runtime's own limit, which refuses a deeper matcher.
4123 *
4124 * Past it a field keeps its declared type; nothing becomes `any`.
4125 */
4126 type NarrowDepth = 8;
4127
4128 /**
4129 * `e` in a matched hook: the members of the argument union `E` matcher `P`
4130 * can match, each with the keys `P` names narrowed to what a match implies.
4131 *
4132 * A scalar narrows to the literal, a one-of to what its alternatives give,
4133 * an object key recursively, an array some element of which must match to
4134 * a non-empty tuple; other keys, `unknown` and RegExp-matched fields keep.
4135 */
4136 export type Narrowed<E, P> = E extends unknown ? NarrowedMember<E, P, []> : never;
4137
4138 /**
4139 * A value of declared type `V` under a one-of, folded over the tuple into
4140 * `Found`: the union of what each alternative narrows `V` to (NarrowedByOne).
4141 *
4142 * An alternative that cannot match adds nothing, so a one-of none of whose
4143 * alternatives can is `never`; a one-of typed as a plain array rather than
4144 * a tuple narrows by the union of its elements at once.
4145 */
4146 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>;
4147
4148 /**
4149 * A value of declared type `V` under one matcher node `Q` that is not a
4150 * one-of, member of `V` by member; a member that cannot match is `never`.
4151 *
4152 * An array some element of which must match becomes NonEmpty; a RegExp
4153 * keeps the member; an object pattern recurses into an object member, one
4154 * level down; a scalar keeps a member as narrow, and replaces a wider one.
4155 */
4156 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;
4157
4158 /**
4159 * One object member `E` under object pattern `P`, `D` levels down: `never`
4160 * when a key of `P` is impossible on it (ImpossibleKeys), else `E` narrowed.
4161 *
4162 * Each key `P` names is narrowed (NarrowedValue); every other key, and each
4163 * key's optionality, stays as declared.
4164 */
4165 type NarrowedMember<E, P, D extends readonly unknown[]> = [
4166 ImpossibleKeys<E, P, D>
4167 ] extends [never] ? {
4168 [K in keyof E]: K extends keyof P ? NarrowedValue<E[K], P[K], D> : E[K];
4169 } : never;
4170
4171 /**
4172 * A value of declared type `V` where the matcher gives `Q`, `D` levels
4173 * down: NarrowedByAny under a one-of (an array), NarrowedByOne otherwise.
4174 *
4175 * As declared once `D` reaches NarrowDepth, or for a field typed `unknown`
4176 * (a tool's input), which no pattern narrows.
4177 */
4178 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>;
4179
4180 /**
4181 * `!` before a name or a glob: every event except the ones it selects. `!*`
4182 * would select none, so it is no pattern.
4183 */
4184 type Negation = `!${Exclude<EventName | Glob, '*'>}`;
4185
4186 /**
4187 * The rest of the chain, as one hook receives it: made once per dispatch per
4188 * hook, frozen; `next(e)` resolves to the downstream result.
4189 *
4190 * Each call runs the hooks below again; core is the last, and below it `next`
4191 * rejects. Called with no argument it rejects, naming the hook. A hook that
4192 * returns without calling it ends the chain; returning nothing is a failure.
4193 *
4194 * @template S what `next.is(pattern, e)` narrows `e` to, per event: the event's
4195 * argument, or, under a matcher, that argument narrowed by it (MatchedHook)
4196 * @template T the tool `e` names, when it names one: on `tool.call` it types
4197 * the result (NextResultFor); an `e` without `tool` takes the line beneath
4198 */
4199 export type Next<N extends EventName = EventName, E = Args<N>, O = NextResult<N>, S extends {
4200 [K in N]?: unknown;
4201 } = {
4202 [K in N]: Args<K>;
4203 }> = {
4204 <T extends string>(e: E & ToolNamed<T>): Promise<NextResultFor<N, O, T>>;
4205 (e: E): Promise<O>;
4206 /**
4207 * Continues this dispatch at a tier: `next(e)` with every link between
4208 * this hook's own tier and that one skipped, by tier and narrowing only.
4209 *
4210 * A managed hook's: prepend may name append, builtin or core, append core;
4211 * it never skips a tier with more authority, so no user hook skips the
4212 * org's. A literal on the hook's own `next`; skipped links are traced.
4213 */
4214 readonly to: {
4215 <T extends string>(e: E & ToolNamed<T>, tier: TargetTier): Promise<NextResultFor<N, O, T>>;
4216 (e: E, tier: TargetTier): Promise<O>;
4217 };
4218 /**
4219 * Aborts when the call this dispatch belongs to is abandoned: the user
4220 * interrupted, a hook above settled first, or this hook ran out of budget.
4221 *
4222 * Anything the hook started (timers, requests) should stop on it. It is an
4223 * AbortSignal of the plugin's own environment, driven by the chain's.
4224 */
4225 readonly signal: AbortSignal;
4226 /**
4227 * Whether this dispatch's event is selected by `pattern` (a name, a glob,
4228 * a negation), as a type predicate on `e`: `next.is("tool.call", e)`.
4229 *
4230 * Under a matcher the narrowing includes it. `pattern` names events this
4231 * hook covers (PatternOver); a name outside them is a compile error.
4232 */
4233 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<S[Extract<N, Selected<M>>]>;
4234 /**
4235 * The name of this dispatch's event, as a value, for a glob hook to log or
4236 * switch on.
4237 */
4238 readonly event: N;
4239 /**
4240 * Who raised this dispatch: the calling plugin's name and the tier it sits
4241 * in (Origin); the engine reads `{ plugin: "engine", tier: "core" }`.
4242 *
4243 * Set by the host alone, from the environment the call came from (its own
4244 * MessagePort) and that plugin's seat; nothing a plugin writes reaches it.
4245 * Every hook of one dispatch sees the same origin, and `next.to` keeps it.
4246 *
4247 * @example
4248 * return next.origin.tier === "prepend" ? next.to(e, "append") : next(e)
4249 */
4250 readonly origin: Origin;
4251 /**
4252 * What settled beneath this hook on its latest `next()` call, the one
4253 * started last: an entry per link beneath, nearest first, the engine's last.
4254 *
4255 * Empty before `next` is called; filled even when `next` rejected; a link
4256 * still running joins in place later, nothing listed leaves; it ends short
4257 * of the engine at a link that answered its last call itself. Data, frozen.
4258 */
4259 readonly trace: readonly TraceEntry<N, E, O>[];
4260 };
4261
4262 /**
4263 * What `next(e)` resolves to for event `N`: the event's result, except at
4264 * `engine.create`, where the steps beneath return `$` as built so far.
4265 *
4266 * A withheld noun is on that `$` as a stub, so the built table is typed
4267 * whole where what a hook returns (EngineCreateResult) is partial.
4268 */
4269 export type NextResult<N extends EventName> = N extends 'engine.create' ? EngineInterfaceBuilt : EventResult<N>;
4270
4271 /**
4272 * What `next(e)` resolves to once `e.tool` is the literal `T`: on `tool.call`
4273 * the result typed for that tool; on every other event, `O` as declared.
4274 *
4275 * `result` is Bash's record after `e.tool === "Bash"`; an un-narrowed `e`
4276 * names every tool, and `result` stays `unknown`.
4277 */
4278 export type NextResultFor<N extends EventName, O, T extends string> = [
4279 N
4280 ] extends ['tool.call'] ? ToolCallResult<T> : O;
4281
4282 /**
4283 * The argument of a call on `$` that takes nothing (`$.session.cwd()`): an
4284 * object with no keys.
4285 */
4286 type NoArgs = Record<never, never>;
4287
4288 /**
4289 * The events whose argument is exactly NoArgs (`session.cwd`, a declared
4290 * plugin noun's `() => ...`); their overloads come last (LateOverload).
4291 */
4292 type NoArgsEvent = {
4293 [N in EventName]: Args<N> extends NoArgs ? NoArgs extends Args<N> ? N : never : never;
4294 }[EventName];
4295
4296 /**
4297 * What an `engine.create` hook receives as `$`: nothing. Every property
4298 * reads as `never`, so `$.model` inside the hook is a compile error.
4299 */
4300 export type NoEngineInterface = {
4301 readonly [noun: string]: never;
4302 };
4303
4304 /**
4305 * Array type `V`, of element `Item`, once some element of it is known to
4306 * match: a tuple of at least one `Item`, readonly when `V` is.
4307 *
4308 * So `e` still passes wherever the declared array is taken; a `V` that is
4309 * already a non-empty tuple is kept as it is.
4310 */
4311 type NonEmpty<V, Item> = V extends readonly [unknown, ...unknown[]] ? V : V extends Item[] ? [Item, ...Item[]] : readonly [Item, ...Item[]];
4312
4313 type NotificationHookInput = BaseHookInput & {
4314 hook_event_name: 'Notification';
4315 message: string;
4316 title?: string;
4317 notification_type: string;
4318 };
4319
4320 /**
4321 * The declared plugin nouns' methods as event rows (NounEventRow), one per
4322 * `<noun>.<method>` that is a function; a member that is not is no event.
4323 */
4324 type NounEvent = {
4325 [K in PluginNoun]: {
4326 [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;
4327 }[keyof EngineInterface[K] & string];
4328 }[PluginNoun];
4329
4330 /**
4331 * The name of a declared plugin noun's event (`voice.speak`).
4332 */
4333 type NounEventName = keyof NounEventOf & string;
4334
4335 /**
4336 * The events of the plugin nouns declared on EngineInterface, by name: the
4337 * argument of each `<noun>.<method>`. Empty until a plugin declares a noun.
4338 *
4339 * @example
4340 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
4341 */
4342 export type NounEventOf = {
4343 [E in NounEvent as E['name']]: E['args'];
4344 };
4345
4346 /**
4347 * The result of a declared plugin noun's event as its hooks see it:
4348 * `{ value }` (the method's answer) or `{ deny }`.
4349 */
4350 type NounEventResult<N extends NounEventName> = ValueOrDeny<NounValueOf[N]>;
4351
4352 /**
4353 * One method of a declared plugin noun as an event row: its event's name,
4354 * argument (the method's first parameter) and value (its awaited result).
4355 */
4356 type NounEventRow<Name extends string, Args, Value> = {
4357 name: Name;
4358 args: Args;
4359 value: Value;
4360 };
4361
4362 /**
4363 * What each declared plugin noun's method answers (the `value` of its
4364 * event's result), by event name.
4365 */
4366 type NounValueOf = {
4367 [E in NounEvent as E['name']]: E['value'];
4368 };
4369
4370 /**
4371 * Registers `hook` on the events `pattern` selects: one by name, every one
4372 * under a namespace (`classic.*`), all (`*`), or all but some (`!tool.*`).
4373 *
4374 * One function stands on every selected event (`next.event` says which),
4375 * under a matcher for the inputs it matches; a plugin's registrations nest
4376 * in order, first outermost; a repeat throws. Returns the Registration.
4377 */
4378 export type On = {
4379 <P extends Pattern>(pattern: P, hook: NoInfer<HookFor<P>>): Registration<HookFor<P>>;
4380 <P extends Pattern, const M extends Matcher<Args<MatchedNames<P>>>>(pattern: P, matcher: M, hook: NoInfer<MatchedHook<P, M>>): Registration<MatchedHook<P, M>>;
4381 };
4382
4383 /**
4384 * The keys a variant with a string index signature (an MCP tool's input)
4385 * takes beyond its own: another variant's key as typed there; others free.
4386 *
4387 * So a misspelt value for a key some variant declares (`command: 5`) is
4388 * refused on every variant, not admitted by the open one.
4389 */
4390 type OpenMatcher<I, All> = {
4391 readonly [K in Exclude<MatcherKeys<All>, KnownKeys<I>>]?: MatcherValue<MatcherValueOf<All, K>>;
4392 } & Readonly<Record<string, unknown>>;
4393
4394 /**
4395 * The name of a call on `$` the host serves, as an event.
4396 */
4397 export type OpEventName = keyof OpEventOf;
4398
4399 /**
4400 * The calls on `$` the host serves, as events: `e` is the call's argument as
4401 * it crosses to the host, and every one is hookable by name and by `on("*")`.
4402 *
4403 * A hook above the caller passes it on, rewrites it, refuses it with
4404 * `{ deny }` or answers with `{ value }`; core is the host's implementation.
4405 * The calling hook alone is skipped, and `next.origin` names the caller.
4406 */
4407 export type OpEventOf = {
4408 /**
4409 * The argument of `$.model.complete(request)`.
4410 */
4411 'model.complete': ModelCompleteRequest;
4412 /**
4413 * The argument of `$.model.classify(text, labels, options)`.
4414 */
4415 'model.classify': {
4416 text: string;
4417 labels: readonly string[];
4418 options?: ClassifyOptions;
4419 };
4420 /**
4421 * The argument of `$.model.fork(request)`.
4422 */
4423 'model.fork': ModelForkRequest;
4424 /**
4425 * The clip and how to play it (`shouldLoop`, `gain`); the signal does not
4426 * cross.
4427 */
4428 'audio.play': {
4429 clip: AudioClip;
4430 shouldLoop: boolean;
4431 gain?: number;
4432 };
4433 /**
4434 * The argument of `$.audio.speak(text, { voice })`.
4435 */
4436 'audio.speak': SpeakRequest;
4437 /**
4438 * The argument of `$.mcp.call(server, tool, args)`.
4439 */
4440 'mcp.call': {
4441 server: string;
4442 tool: string;
4443 args: Record<string, unknown>;
4444 };
4445 /**
4446 * The argument of `$.session.cwd()`.
4447 */
4448 'session.cwd': NoArgs;
4449 /**
4450 * The argument of `$.session.model()`.
4451 */
4452 'session.model': NoArgs;
4453 /**
4454 * The argument of `$.session.turns()`.
4455 */
4456 'session.turns': NoArgs;
4457 /**
4458 * The argument of `$.session.id()`.
4459 */
4460 'session.id': NoArgs;
4461 /**
4462 * The argument of `$.session.messages()`.
4463 */
4464 'session.messages': NoArgs;
4465 /**
4466 * The argument of `$.session.repo()`.
4467 */
4468 'session.repo': NoArgs;
4469 /**
4470 * The argument of `$.session.surface()`.
4471 *
4472 * @deprecated with `$.session.surface()`; hook `session.surfaces`
4473 */
4474 'session.surface': NoArgs;
4475 /**
4476 * The argument of `$.session.surfaces()`.
4477 */
4478 'session.surfaces': NoArgs;
4479 /**
4480 * The argument of `$.session.authorize()`.
4481 */
4482 'session.authorize': NoArgs;
4483 /**
4484 * The argument of `$.session.usage({ breakdown, columns })`.
4485 */
4486 'session.usage': SessionUsageArgs;
4487 /**
4488 * The argument of `$.turn.abort({ turnId })`.
4489 */
4490 'turn.abort': {
4491 turnId: string;
4492 };
4493 /**
4494 * The argument of `$.tool.list()`.
4495 */
4496 'tool.list': NoArgs;
4497 /**
4498 * The argument of `$.tool.register(spec)`.
4499 */
4500 'tool.register': Required<ToolSpec>;
4501 /**
4502 * The argument of `$.command.list()`.
4503 */
4504 'command.list': NoArgs;
4505 /**
4506 * The argument of `$.command.register(spec)`.
4507 */
4508 'command.register': CommandSpec;
4509 /**
4510 * The argument of `$.config.list()`.
4511 */
4512 'config.list': NoArgs;
4513 /**
4514 * The argument of `$.agent.list()`.
4515 */
4516 'agent.list': NoArgs;
4517 /**
4518 * The argument of `$.ui.toast(text, { timeoutMs })`.
4519 */
4520 'ui.toast': {
4521 text: string;
4522 timeoutMs?: number;
4523 };
4524 /**
4525 * The argument of `$.ui.status(text)`; `text` undefined clears the line.
4526 */
4527 'ui.status': {
4528 text: string | undefined;
4529 };
4530 /**
4531 * The argument of `$.ui.log(text)`.
4532 */
4533 'ui.log': {
4534 text: string;
4535 };
4536 /**
4537 * The argument of `$.ui.notice(tool_use_id, text)`.
4538 */
4539 'ui.notice': {
4540 tool_use_id: string;
4541 text: string | undefined;
4542 };
4543 /**
4544 * The argument of `$.ui.invalidate(event)`.
4545 */
4546 'ui.invalidate': {
4547 event: InvalidatableEventName;
4548 };
4549 /**
4550 * The argument of `$.ui.open({ id, title, focus })`; a hook above the
4551 * opener may retitle it or refuse it with `{ deny }`, never rename it.
4552 */
4553 'ui.open': PaneOpenArgs;
4554 /**
4555 * The argument of `$.ui.close({ id })` with `origin` `plugin`; the engine
4556 * raises it too, for the person (`person`) and an unload (`unload`).
4557 */
4558 'ui.close': PaneCloseInput;
4559 /**
4560 * The argument of `$.ui.blit({ requestId, key, cells })`; a hook above
4561 * the painter may repaint the cells with `next`, or refuse with `{ deny }`.
4562 */
4563 'ui.blit': UiBlitArgs;
4564 /**
4565 * The argument of `$.fs.read(path)`.
4566 */
4567 'fs.read': {
4568 path: string;
4569 };
4570 /**
4571 * The argument of `$.fs.write(path, text)`.
4572 */
4573 'fs.write': {
4574 path: string;
4575 text: string;
4576 };
4577 /**
4578 * The argument of `$.fs.list(path)`.
4579 */
4580 'fs.list': {
4581 path: string;
4582 };
4583 /**
4584 * The argument of `$.fs.exists(path)`.
4585 */
4586 'fs.exists': {
4587 path: string;
4588 };
4589 /**
4590 * The argument of `$.fs.stat(path)`.
4591 */
4592 'fs.stat': {
4593 path: string;
4594 };
4595 /**
4596 * The argument of `$.fs.ancestors({ names, of })`.
4597 */
4598 'fs.ancestors': FsAncestorsRequest;
4599 /**
4600 * The argument of `$.store.get(key)`.
4601 */
4602 'store.get': {
4603 key: string;
4604 };
4605 /**
4606 * The argument of `$.store.set(key, value)`.
4607 */
4608 'store.set': {
4609 key: string;
4610 value: unknown;
4611 };
4612 /**
4613 * The argument of `$.store.delete(key)`.
4614 */
4615 'store.delete': {
4616 key: string;
4617 };
4618 /**
4619 * The argument of `$.store.keys()`.
4620 */
4621 'store.keys': NoArgs;
4622 /**
4623 * The argument of `$.clock.now()`.
4624 */
4625 'clock.now': NoArgs;
4626 /**
4627 * The argument of `$.clock.sleep(ms, { signal })`; the signal does not
4628 * cross, it aborts the dispatch.
4629 */
4630 'clock.sleep': ClockWait;
4631 /**
4632 * The argument of `$.clock.after(ms, fn)`: the wait before `fn`, which
4633 * stays in the plugin's environment and runs once the dispatch resolves.
4634 */
4635 'clock.after': ClockWait;
4636 /**
4637 * The argument of `$.clock.every(ms, fn)`, dispatched once per period:
4638 * `fn` runs each time a dispatch resolves, and the next period is asked.
4639 */
4640 'clock.every': ClockWait;
4641 /**
4642 * The argument of `$.http.fetch(url, init)`.
4643 */
4644 'http.fetch': {
4645 url: string;
4646 init?: HttpInit;
4647 };
4648 /**
4649 * The argument of `$.process.run(argv, init)`.
4650 */
4651 'process.run': {
4652 argv: readonly string[];
4653 init?: ProcessRunInit;
4654 };
4655 /**
4656 * The argument of `$.settings.read({ source })`.
4657 */
4658 'settings.read': SettingsReadArgs;
4659 /**
4660 * The argument of `$.env.get(name)`; `name` is identity, pinned.
4661 */
4662 'env.get': {
4663 name: string;
4664 };
4665 /**
4666 * The argument of `$.env.set(name, value)`; `name` is identity, pinned,
4667 * and no `value` unsets.
4668 */
4669 'env.set': {
4670 name: string;
4671 value?: string;
4672 };
4673 };
4674
4675 /**
4676 * The result of a call on `$` as its event's hooks see it: `{ value }` (the
4677 * call's answer) or `{ deny }`.
4678 */
4679 export type OpEventResult<N extends OpEventName = OpEventName> = ValueOrDeny<OpValueOf[N]>;
4680
4681 /**
4682 * What each call on `$` answers (the `value` of its event's result), by event
4683 * name.
4684 */
4685 export type OpValueOf = {
4686 'model.complete': string;
4687 'model.classify': string | undefined;
4688 'model.fork': ModelForkResult | null;
4689 'audio.play': void;
4690 'audio.speak': SpeakResult;
4691 'mcp.call': McpToolResult;
4692 'session.cwd': string;
4693 'session.model': string;
4694 'session.turns': number;
4695 'session.id': string;
4696 'session.messages': SessionMessage[];
4697 'session.repo': SessionRepo | null;
4698 'session.surface': RenderSurface | null;
4699 'session.surfaces': readonly RenderSurface[];
4700 /**
4701 * The credential handle, or null where the build or the provider has no
4702 * first-party credential to hold.
4703 */
4704 'session.authorize': SessionAuthorization;
4705 'session.usage': SessionUsage;
4706 'turn.abort': void;
4707 'tool.list': ToolInfo[];
4708 'tool.register': {
4709 tool: string;
4710 };
4711 'command.list': CommandInfo[];
4712 'command.register': {
4713 command: string;
4714 };
4715 'config.list': ConfigRow[];
4716 'agent.list': AgentInfo[];
4717 'ui.toast': void;
4718 'ui.status': void;
4719 'ui.log': void;
4720 'ui.notice': void;
4721 'ui.invalidate': void;
4722 'ui.open': void;
4723 'ui.close': void;
4724 'ui.blit': UiBlitResult;
4725 'fs.read': string;
4726 'fs.write': void;
4727 'fs.list': FsEntry[];
4728 'fs.exists': boolean;
4729 'fs.stat': FsStat;
4730 'fs.ancestors': readonly FsAncestor[];
4731 'store.get': unknown;
4732 'store.set': void;
4733 'store.delete': void;
4734 'store.keys': string[];
4735 /**
4736 * Milliseconds since the epoch.
4737 */
4738 'clock.now': number;
4739 'clock.sleep': void;
4740 'clock.after': void;
4741 'clock.every': void;
4742 'http.fetch': HttpResponse;
4743 'process.run': ProcessRunResult;
4744 'settings.read': Settings;
4745 'env.get': string | undefined;
4746 'env.set': void;
4747 };
4748
4749 /**
4750 * One call signature per event in `Names`, intersected, the ambiguous ones
4751 * (LateOverload) after the rest: `next` for a hook covering several events.
4752 *
4753 * An empty group contributes nothing (Overloads<never> is unknown).
4754 */
4755 type OrderedOverloads<Names extends EventName> = Overloads<Exclude<Names, LateOverload>> & Overloads<Extract<Names, 'classic.PreToolUse'>> & Overloads<Extract<Names, 'turn.abort'>> & Overloads<Extract<Names, NoArgsEvent>>;
4756
4757 /**
4758 * Who raised a dispatch, as `next.origin` holds it: the calling plugin's
4759 * name and the tier it sits in; the engine reads `engine` in `core`.
4760 *
4761 * The same pair a `next.trace` entry names its link by, and an event's
4762 * `provider` its subject's definer by. Set by the host from where the call
4763 * came from and where that plugin was seated; nothing a plugin writes.
4764 */
4765 export type Origin = {
4766 /**
4767 * Whose hook made the `$` call, by name; `"engine"` for a call site,
4768 * `"client"` for a `Client` surface module's `ui.message` post.
4769 */
4770 readonly plugin: string;
4771 /**
4772 * Where that plugin sits among the chain's tiers (Tier); `"core"` for the
4773 * engine, the owning plugin's for a `client` post.
4774 */
4775 readonly tier: Tier;
4776 };
4777
4778 /**
4779 * One call signature per event in `Names`, intersected into an overload set.
4780 */
4781 type Overloads<Names extends EventName> = UnionToIntersection<{
4782 [N in Names]: (e: Args<N>) => Promise<NextResult<N>>;
4783 }[Names]>;
4784
4785 /**
4786 * The argument of `$.ui.close`: the pane to close (`{ id }`). `origin` is
4787 * the engine's to set: a plugin's call reads `plugin` at the hooks.
4788 */
4789 export type PaneCloseArgs = Omit<PaneCloseInput, 'origin'>;
4790
4791 /**
4792 * The input of `ui.close`: the pane closing and why (PaneCloseOrigin).
4793 * Closing an id that is not open does nothing.
4794 */
4795 export type PaneCloseInput = {
4796 /**
4797 * What `$.ui.open` named the pane; pinned: `next(e)` passes it on.
4798 */
4799 id: string;
4800 /**
4801 * Who closes it, set by the engine: a hook that answers without `next`
4802 * keeps the pane open on `plugin` and `person`, never on `unload`.
4803 */
4804 origin: PaneCloseOrigin;
4805 };
4806
4807 /**
4808 * Why a pane closes, as the engine stamped it at `ui.close`.
4809 *
4810 * `unload` drops a pane nothing draws any more (its plugin unloaded, or its
4811 * drawing threw): it is gone before the hooks hear of it, and its opener's
4812 * hooks do not run. `next(e)` passes the origin on as received; none sets it.
4813 */
4814 export type PaneCloseOrigin = {
4815 /**
4816 * `plugin`, a plugin's `$.ui.close`; `person`, the person's close mark or
4817 * close key; `unload`, the engine's own.
4818 */
4819 kind: 'plugin' | 'person' | 'unload';
4820 };
4821
4822 /**
4823 * The argument of `$.ui.open`: which pane, its title, whether it asks the
4824 * person's keyboard, its dialog manners, and the rows it wants inline.
4825 */
4826 export type PaneOpenArgs = {
4827 /**
4828 * Names the pane: 1-64 of letters, digits, `_` and `-`. One pane per id:
4829 * opening an open id delivers the new title, never a second instance.
4830 *
4831 * Pinned at the hooks: `next(e)` passes it on; the title and focus rewrite.
4832 */
4833 id: string;
4834 /**
4835 * The pane's tab while more than one pane is open (with one, no title is
4836 * drawn), and the `title` its hook sees; the id when omitted.
4837 */
4838 title?: string;
4839 /**
4840 * A request, not a grant: the surface focuses (and raises) the pane only
4841 * while the prompt has the keys over an empty composer.
4842 *
4843 * An element of the band or a pane the person holds, text in the
4844 * composer, a dialog or a survey each refuse it: the pane opens without
4845 * the keyboard.
4846 */
4847 focus?: true;
4848 /**
4849 * While the pane holds the keyboard, the key that hands it back (Escape)
4850 * also closes it as the person's close does: `ui.close`, origin `person`.
4851 *
4852 * A hook may refuse that close and keep it open. Left out, Escape returns
4853 * the keys to the prompt and the pane stays. Each open sets it anew, as it
4854 * sets the title.
4855 */
4856 closeOnEscape?: true;
4857 /**
4858 * While the pane is on screen the surface holds its transient toasts (the
4859 * notification line under the prompt) and shows them once it closes.
4860 *
4861 * As it does behind the engine's own side panel; pinned warnings still
4862 * show. Left out, toasts show as they come. Each open sets it anew.
4863 */
4864 holdToasts?: true;
4865 /**
4866 * The body rows the pane's content wants while seated inline above the
4867 * prompt: it opens that tall, up to what the layout spares, not a third.
4868 *
4869 * A request, not a grant: a size the person dragged or keyed the block
4870 * to wins, this session's or a kept one, and the dock ignores it. A
4871 * positive whole number; left out, a third. Each open sets it anew.
4872 */
4873 rows?: number;
4874 };
4875
4876 /**
4877 * What `on(pattern, hook)` and `next.is(pattern, e)` take: an event's name,
4878 * a glob (`*`, `classic.*`), or a negation of either (`!tool.describe`).
4879 */
4880 export type Pattern = EventName | Glob | Negation;
4881
4882 /**
4883 * The patterns `next.is` takes in a hook covering the events `N`: their
4884 * names, `*`, a glob over one of their namespaces, or a negation.
4885 *
4886 * A name none of them has is a compile error, as is a glob over a namespace
4887 * none is under; a negation that selects none of them narrows `e` to never.
4888 */
4889 type PatternOver<N extends EventName> = N | '*' | `${Namespace<N>}.*` | Negation;
4890
4891 type PermissionBehavior = 'allow' | 'deny' | 'ask';
4892
4893 type PermissionDeniedHookInput = BaseHookInput & {
4894 hook_event_name: 'PermissionDenied';
4895 tool_name: string;
4896 tool_input: unknown;
4897 tool_use_id: string;
4898 reason: string;
4899 };
4900
4901 /**
4902 * 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.
4903 */
4904 type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';
4905
4906 /**
4907 * A `classic.PermissionRequest` answer's `decision`, as the classic hook's
4908 * `hookSpecificOutput.decision`: allow (with a rewrite or rules) or deny.
4909 */
4910 export type PermissionRequestDecision = {
4911 behavior: 'allow';
4912 updatedInput?: Record<string, unknown>;
4913 updatedPermissions?: PermissionUpdates;
4914 } | {
4915 behavior: 'deny';
4916 message?: string;
4917 interrupt?: true;
4918 };
4919
4920 type PermissionRequestHookInput = BaseHookInput & {
4921 hook_event_name: 'PermissionRequest';
4922 tool_name: string;
4923 tool_input: unknown;
4924 permission_suggestions?: PermissionUpdate[];
4925 };
4926
4927 type PermissionRuleValue = {
4928 toolName: string;
4929 ruleContent?: string;
4930 };
4931
4932 type PermissionUpdate = {
4933 type: 'addRules';
4934 rules: PermissionRuleValue[];
4935 behavior: PermissionBehavior;
4936 destination: PermissionUpdateDestination;
4937 } | {
4938 type: 'replaceRules';
4939 rules: PermissionRuleValue[];
4940 behavior: PermissionBehavior;
4941 destination: PermissionUpdateDestination;
4942 } | {
4943 type: 'removeRules';
4944 rules: PermissionRuleValue[];
4945 behavior: PermissionBehavior;
4946 destination: PermissionUpdateDestination;
4947 } | {
4948 type: 'setMode';
4949 mode: PermissionMode;
4950 destination: PermissionUpdateDestination;
4951 } | {
4952 type: 'addDirectories';
4953 directories: string[];
4954 destination: PermissionUpdateDestination;
4955 } | {
4956 type: 'removeDirectories';
4957 directories: string[];
4958 destination: PermissionUpdateDestination;
4959 };
4960
4961 type PermissionUpdateDestination = 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg';
4962
4963 /**
4964 * The permission rules a PermissionRequest allow may add: the shape of the
4965 * request's own `permission_suggestions` (the SDK's PermissionUpdate list).
4966 */
4967 type PermissionUpdates = NonNullable<ClassicHookInputs['PermissionRequest']['permission_suggestions']>;
4968
4969 /**
4970 * How `$.audio.play` plays a clip: looped until `signal` aborts, or once.
4971 *
4972 * A loop needs the signal that ends it; a single play takes one as an option.
4973 */
4974 export type PlayOptions = {
4975 /**
4976 * Repeat the clip until `signal` aborts (the promise then resolves).
4977 */
4978 shouldLoop: true;
4979 /**
4980 * Linear gain, from 0 to 4; default 1.
4981 */
4982 gain?: number;
4983 /**
4984 * Stops the clip: playback ends at once and the promise resolves.
4985 */
4986 signal: AbortSignal;
4987 } | {
4988 /**
4989 * Play once.
4990 */
4991 shouldLoop?: false;
4992 /**
4993 * Linear gain, from 0 to 4; default 1.
4994 */
4995 gain?: number;
4996 /**
4997 * Stops the clip early, as above.
4998 */
4999 signal?: AbortSignal;
5000 };
5001
5002 /**
5003 * The nouns a plugin declared on `$` by merging into EngineInterface; never
5004 * one the engine's own events are under (`tool`, `session`, `ui`).
5005 */
5006 type PluginNoun = Exclude<keyof EngineInterface & string, keyof CoreEngineInterface | Namespace<CoreEventName>>;
5007
5008 /**
5009 * A plugin's options as `register(on, options)` receives them: the values of
5010 * the fields its manifest's `userConfig` declares, defaults filled in.
5011 *
5012 * Stored in settings.json `pluginConfigs[<plugin>].options` (sensitive ones
5013 * in secure storage), validated against the declared `type` before the module
5014 * loads; a required field with no value fails the load, naming the field. A
5015 * string field that declares `options` holds one of them: `/config` draws it
5016 * as a picker over them, and a stored value outside them counts as unset, so
5017 * its default applies. A `--plugin-dir` plugin's key is its plugin.json
5018 * `<name>` (or `<name>@inline`).
5019 */
5020 export type PluginOptions = Readonly<Record<string, string | number | boolean | readonly string[]>>;
5021
5022 /**
5023 * The input of `plugin.register`: one hooks module the engine is about to
5024 * load, read off its manifest and its scanned source. Every field is pinned.
5025 *
5026 * `tier` and `uses` are the host's reading of the module, what a gate holds
5027 * it to; `name`, `root`, `version` and `provenance` are its own word (its
5028 * manifest, its place), so a rule keyed on them is one a rename walks past.
5029 */
5030 export type PluginRegisterInput = {
5031 /**
5032 * The plugin's name, as its own plugin.json declares it.
5033 */
5034 name: string;
5035 /**
5036 * Where its hooks would stand among the chain's tiers (Tier); never
5037 * `core`, the engine's own.
5038 */
5039 tier: Exclude<Tier, 'core'>;
5040 /**
5041 * The plugin's directory (the one holding plugin.json), absolute.
5042 */
5043 root: string;
5044 /**
5045 * Its manifest's `version`, when it states one.
5046 */
5047 version?: string;
5048 /**
5049 * Where the plugin came from, as the loader keys it: `<name>@<marketplace>`
5050 * installed, `<name>@inline` by `--plugin-dir`, `<name>@builtin` bundled.
5051 */
5052 provenance: string;
5053 /**
5054 * What the module hooks and calls, as scanned (PluginRegisterUses).
5055 */
5056 uses: PluginRegisterUses;
5057 };
5058
5059 /**
5060 * What a `plugin.register` hook returns and what `next(e)` resolves to:
5061 * `{ allow: true }` from core, or `{ refuse: reason }`.
5062 */
5063 export type PluginRegisterResult = {
5064 /**
5065 * The module loads: its `engine.create` step runs and its hooks join.
5066 */
5067 allow: true;
5068 refuse?: undefined;
5069 } | {
5070 /**
5071 * The module does not load: no step, no hooks, no tools or commands;
5072 * the transcript names the plugin that refused and this reason.
5073 */
5074 refuse: string;
5075 allow?: undefined;
5076 };
5077
5078 /**
5079 * What a hooks module uses, as the host scanned its source before loading it:
5080 * the same lists `claude plugin validate` prints and the host's rule reads.
5081 *
5082 * Exact, since a module that spells `on`, `$` or `$.env` other than literally
5083 * does not load.
5084 */
5085 export type PluginRegisterUses = {
5086 /**
5087 * The patterns its `on(...)` registrations name, as written (`tool.call`,
5088 * `*`, `classic.*`, `!tool.describe`), in registration order, each once.
5089 */
5090 events: readonly string[];
5091 /**
5092 * What it calls on `$`, spelled `noun.method` (`fs.write`, `http.fetch`),
5093 * sorted, each once.
5094 */
5095 calls: readonly string[];
5096 /**
5097 * The environment variables its `$.env.get` and `$.env.set` calls name;
5098 * absent when it calls neither.
5099 */
5100 env?: {
5101 /**
5102 * The names its `$.env.get` calls spell, sorted, each once.
5103 */
5104 reads: readonly string[];
5105 /**
5106 * The names its `$.env.set` calls spell, sorted, each once.
5107 */
5108 writes: readonly string[];
5109 };
5110 };
5111
5112 /**
5113 * Whose element: the plugin whose hook drew it, stamped by the runtime as the
5114 * tree leaves it; a Box's or Text's `group`, a Client's or Raster's own.
5115 *
5116 * A Button's `press` names its plugin the same way, beside its handle. Two
5117 * plugins under one `hover.scope` string never share a group.
5118 */
5119 type PluginStamp = {
5120 plugin: string;
5121 };
5122
5123 type PostCompactHookInput = BaseHookInput & {
5124 hook_event_name: 'PostCompact';
5125 trigger: 'manual' | 'auto';
5126 /**
5127 * The conversation summary produced by compaction
5128 */
5129 compact_summary: string;
5130 };
5131
5132 type PostModelSwitchHookInput = (BaseHookInput & {
5133 hook_event_name: 'PostModelSwitch';
5134 }) & {
5135 /**
5136 * Resolved model id the session was running before the switch
5137 */
5138 from_model: string;
5139 /**
5140 * Resolved model id the session runs after the switch
5141 */
5142 to_model: string;
5143 /**
5144 * What was asked for (alias such as "opus", a full id, or null for "default")
5145 */
5146 requested_model: string | null;
5147 /**
5148 * 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
5149 */
5150 source: 'command' | 'picker' | 'sdk' | 'auto' | 'resume';
5151 /**
5152 * 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)
5153 */
5154 context_tokens: number;
5155 /**
5156 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
5157 */
5158 prompt_cache_warm: boolean;
5159 cache_ttl: '5m' | '1h';
5160 /**
5161 * 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
5162 */
5163 estimated_cache_write_usd: number;
5164 /**
5165 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
5166 */
5167 pricing: 'configured' | 'catalog' | 'default';
5168 };
5169
5170 /**
5171 * 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.
5172 */
5173 type PostToolBatchHookInput = BaseHookInput & {
5174 hook_event_name: 'PostToolBatch';
5175 tool_calls: PostToolBatchToolCall[];
5176 };
5177
5178 type PostToolBatchToolCall = {
5179 tool_name: string;
5180 tool_input: unknown;
5181 tool_use_id: string;
5182 tool_response?: unknown;
5183 };
5184
5185 type PostToolUseFailureHookInput = BaseHookInput & {
5186 hook_event_name: 'PostToolUseFailure';
5187 tool_name: string;
5188 tool_input: unknown;
5189 tool_use_id: string;
5190 error: string;
5191 is_interrupt?: boolean;
5192 /**
5193 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
5194 */
5195 duration_ms?: number;
5196 };
5197
5198 type PostToolUseHookInput = BaseHookInput & {
5199 hook_event_name: 'PostToolUse';
5200 tool_name: string;
5201 tool_input: unknown;
5202 tool_response: unknown;
5203 tool_use_id: string;
5204 /**
5205 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
5206 */
5207 duration_ms?: number;
5208 };
5209
5210 type PreCompactHookInput = BaseHookInput & {
5211 hook_event_name: 'PreCompact';
5212 trigger: 'manual' | 'auto';
5213 custom_instructions: string | null;
5214 };
5215
5216 type PreModelSwitchHookInput = (BaseHookInput & {
5217 hook_event_name: 'PreModelSwitch';
5218 }) & {
5219 /**
5220 * Resolved model id the session was running before the switch
5221 */
5222 from_model: string;
5223 /**
5224 * Resolved model id the session runs after the switch
5225 */
5226 to_model: string;
5227 /**
5228 * What was asked for (alias such as "opus", a full id, or null for "default")
5229 */
5230 requested_model: string | null;
5231 /**
5232 * 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)
5233 */
5234 source: 'command' | 'picker' | 'sdk';
5235 /**
5236 * 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)
5237 */
5238 context_tokens: number;
5239 /**
5240 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
5241 */
5242 prompt_cache_warm: boolean;
5243 cache_ttl: '5m' | '1h';
5244 /**
5245 * 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
5246 */
5247 estimated_cache_write_usd: number;
5248 /**
5249 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
5250 */
5251 pricing: 'configured' | 'catalog' | 'default';
5252 };
5253
5254 /**
5255 * The decision of a `classic.PreToolUse` result: `allow`, `ask`, `deny`, or
5256 * none.
5257 */
5258 export type PreToolUseDecision = {
5259 /**
5260 * Lets the call run without a permission prompt (the managed-settings
5261 * hooks ran first; a deny from them ended the chain above).
5262 */
5263 allow: true;
5264 ask?: undefined;
5265 deny?: undefined;
5266 } | {
5267 /**
5268 * Asks the user before the call runs; the text is shown as the reason.
5269 */
5270 ask: string;
5271 allow?: undefined;
5272 deny?: undefined;
5273 } | {
5274 /**
5275 * Refuses the call; the model receives the text as the reason.
5276 */
5277 deny: string;
5278 allow?: undefined;
5279 ask?: undefined;
5280 } | {
5281 allow?: undefined;
5282 ask?: undefined;
5283 deny?: undefined;
5284 };
5285
5286 type PreToolUseHookInput = BaseHookInput & {
5287 hook_event_name: 'PreToolUse';
5288 tool_name: string;
5289 tool_input: unknown;
5290 tool_use_id: string;
5291 };
5292
5293 /**
5294 * What a `classic.PreToolUse` hook returns: one of `allow`, `ask`, `deny`,
5295 * or none of them, which passes the call on to the normal permission flow.
5296 */
5297 export type PreToolUseResult = PreToolUseDecision & {
5298 /**
5299 * Replaces the tool's arguments; validated against the tool's schema before
5300 * the tool runs.
5301 */
5302 updatedInput?: Record<string, unknown>;
5303 /**
5304 * Extra context handed to the model with the call, one entry per note.
5305 */
5306 additionalContext?: string[];
5307 };
5308
5309 /**
5310 * Options of `$.process.run`.
5311 */
5312 export type ProcessRunInit = {
5313 /**
5314 * The child's working directory, relative to the session's or absolute;
5315 * absent, the session's working directory.
5316 */
5317 cwd?: string;
5318 /**
5319 * Variables set over the host process's own environment.
5320 */
5321 env?: Record<string, string>;
5322 /**
5323 * Text written to the child's standard input, then closed.
5324 */
5325 stdin?: string;
5326 /**
5327 * How long the child may run before it is killed and the call rejects,
5328 * in milliseconds; 30 seconds when absent, ten minutes at most.
5329 */
5330 timeoutMs?: number;
5331 };
5332
5333 /**
5334 * What `$.process.run` resolves with once the child has exited.
5335 */
5336 export type ProcessRunResult = {
5337 /**
5338 * The child's exit status; a child ended by a signal reads as 1.
5339 */
5340 exitCode: number;
5341 /**
5342 * What the child wrote to standard output, as text, cut at the output
5343 * limit.
5344 */
5345 stdout: string;
5346 /**
5347 * What the child wrote to standard error, as text, cut at the output
5348 * limit.
5349 */
5350 stderr: string;
5351 };
5352
5353 /**
5354 * A pasted or attached non-text item of a prompt; its kind, never its bytes.
5355 */
5356 export type PromptAttachment = {
5357 /**
5358 * The item's kind.
5359 */
5360 type: 'image' | 'audio' | 'document';
5361 /**
5362 * The item's MIME type (`image/png`), when known.
5363 */
5364 mediaType?: string;
5365 /**
5366 * The pasted file's name, when it had one.
5367 */
5368 filename?: string;
5369 };
5370
5371 /**
5372 * One block of the context the first user message carries: a name the
5373 * engine keys it by and the text under it.
5374 */
5375 export type PromptContextBlock = {
5376 /**
5377 * The key the block renders under (`# name`): `claudeMd`, `userEmail`,
5378 * `attachedProject`, `currentDate`, or a plugin's own.
5379 *
5380 * The field a matcher narrows on; unique among one context's blocks.
5381 */
5382 name: string;
5383 /**
5384 * The block's text; `claudeMd`'s is the instruction files framed as the
5385 * engine frames them, empty when it announces none.
5386 */
5387 text: string;
5388 };
5389
5390 /**
5391 * The context blocks of a conversation's first user message, in the order
5392 * the engine renders them: what `prompt.context` takes and answers alike.
5393 */
5394 export type PromptContextBlocks = {
5395 /**
5396 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
5397 * `attachedProject`, `currentDate`, each only when present.
5398 */
5399 blocks: readonly PromptContextBlock[];
5400 };
5401
5402 /**
5403 * The input of `prompt.context`: the context blocks the engine prepends to
5404 * a conversation's first user message, at the moment it computes them.
5405 */
5406 export type PromptContextInput = PromptContextBlocks;
5407
5408 /**
5409 * What a `prompt.context` hook returns: the blocks the conversation
5410 * carries, in order; one left out is not sent.
5411 */
5412 export type PromptContextResult = PromptContextBlocks;
5413
5414 /**
5415 * `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it:
5416 * `origin` is the engine's to set (the calling plugin's name).
5417 */
5418 export type PromptFillArgs = Omit<PromptFillInput, 'origin'>;
5419
5420 /**
5421 * The input of `prompt.fill` (prompt-fill/): a text about to be written into
5422 * the prompt box as the person's draft, replacing what the box holds.
5423 */
5424 export type PromptFillInput = {
5425 /**
5426 * What the box is to hold, cursor at its end; the person edits it or
5427 * presses Enter. `next({ ...e, text })` writes another.
5428 */
5429 text: string;
5430 /**
5431 * Who writes (PromptFillOrigin), set by the engine where the write
5432 * starts. Pinned: `next(e)` passes it on as received.
5433 */
5434 origin: PromptFillOrigin;
5435 };
5436
5437 /**
5438 * Who writes the prompt box at `prompt.fill`, as the engine stamps it where
5439 * the write starts; a closed set a matcher narrows on.
5440 *
5441 * `next(e)` passes it on as received; no hook sets one.
5442 */
5443 export type PromptFillOrigin = {
5444 /**
5445 * The engine writing the box on its own account; reserved for its own
5446 * sites, none of which raises `prompt.fill` as shipped.
5447 */
5448 kind: 'engine';
5449 } | {
5450 /**
5451 * A plugin's `$.prompt.fill`.
5452 */
5453 kind: 'plugin';
5454 /**
5455 * The filling plugin's name.
5456 */
5457 name: string;
5458 };
5459
5460 /**
5461 * What a `prompt.fill` hook returns and what `next(e)` resolves to: whether
5462 * the text went into the prompt box.
5463 */
5464 export type PromptFillResult = {
5465 /**
5466 * True once the box holds the text; false where no box can take it (a
5467 * dialog holds the keys, a headless session has none).
5468 *
5469 * A hook answering `{ isFilled: false }` without `next` keeps the text
5470 * out.
5471 */
5472 isFilled: boolean;
5473 };
5474
5475 /**
5476 * Where a `prompt.submit` submission came from, as the engine knows it at
5477 * the site it was queued from; a closed set, never a text prefix.
5478 *
5479 * A hooks module reads `e.origin.kind` to tell the user's own Enter from a
5480 * notification, a peer session, a schedule or another plugin. `next(e)`
5481 * passes it on as received; an answer may leave it out; no hook sets one.
5482 */
5483 export type PromptOrigin = {
5484 /**
5485 * The user's own gesture at the terminal, as the engine stamped it
5486 * (never presumed from an unstamped command).
5487 *
5488 * Enter at the prompt, typed or queued, or a click on a transcript
5489 * link; a channel the engine cannot attest (a same-user socket) is
5490 * never stamped, and arrives as `unclassified`.
5491 */
5492 kind: 'composer';
5493 } | {
5494 /**
5495 * The user's message through the Remote Control bridge (a phone or
5496 * web client).
5497 */
5498 kind: 'bridge';
5499 } | {
5500 /**
5501 * The SDK host's own turn (`claude -p`, the Agent SDK), not typed at
5502 * a terminal.
5503 */
5504 kind: 'sdk';
5505 } | {
5506 /**
5507 * A background task's notification, dequeued when the session went
5508 * idle or delivered into a running turn (`turnId` set).
5509 */
5510 kind: 'task-notification';
5511 } | {
5512 /**
5513 * A scheduled task, routine or /loop firing its stored prompt.
5514 */
5515 kind: 'scheduled-trigger';
5516 } | {
5517 /**
5518 * Another Claude session's message ("Another Claude session sent a
5519 * message"), as a turn of its own or delivered into a running one.
5520 */
5521 kind: 'peer';
5522 } | {
5523 /**
5524 * Another session's SendMessage delivery, model-authored and framed
5525 * as a notification.
5526 */
5527 kind: 'peer-send-message';
5528 } | {
5529 /**
5530 * A delivery a coordinating session composed for one of its threads.
5531 */
5532 kind: 'projects-relay';
5533 } | {
5534 /**
5535 * A message from a channel an MCP server relays (Slack, Telegram).
5536 */
5537 kind: 'channel';
5538 /**
5539 * The channel server's name.
5540 */
5541 server: string;
5542 } | {
5543 /**
5544 * A coordinating session's hand-off to a worker session.
5545 */
5546 kind: 'coordinator';
5547 } | {
5548 /**
5549 * A background observer agent's report to the agent it observes.
5550 */
5551 kind: 'observer';
5552 } | {
5553 /**
5554 * An activity digest delivered to an observer agent.
5555 */
5556 kind: 'observer-activity';
5557 } | {
5558 /**
5559 * A programmatic follow-up to a user's UI action, user-initiated but
5560 * not typed this turn.
5561 */
5562 kind: 'auto-continuation';
5563 } | {
5564 /**
5565 * A turn with no provenance the engine can name: one the ingress
5566 * could not classify, or a command queued with no stamp at all.
5567 *
5568 * An idle notice or a delivery receipt the engine queued isMeta with
5569 * no stamp is one too; the engine frames that shape as a non-user
5570 * source.
5571 */
5572 kind: 'unclassified';
5573 } | {
5574 /**
5575 * The session's owner pinging it from Slack.
5576 */
5577 kind: 'slack-ping';
5578 } | {
5579 /**
5580 * A plugin's `$.prompt.submit`; the model reads the prompt under the
5581 * plugin's name unless a hook leaves the origin out of its answer.
5582 */
5583 kind: 'plugin';
5584 /**
5585 * The submitting plugin's name.
5586 */
5587 name: string;
5588 };
5589
5590 /**
5591 * The input of `prompt.section`: one named section of the system prompt, at
5592 * the moment the engine assembles it.
5593 */
5594 export type PromptSectionInput = {
5595 /**
5596 * As the engine names the section (`env_info_simple`, `memory`, ...); the
5597 * key a matcher narrows on.
5598 */
5599 name: string;
5600 /**
5601 * The section's text as core computed it, or null when core omits it.
5602 */
5603 text: string | null;
5604 };
5605
5606 /**
5607 * What a `prompt.section` hook returns: the text the prompt carries for that
5608 * section, or null to leave it out.
5609 */
5610 export type PromptSectionResult = {
5611 text: string | null;
5612 };
5613
5614 /**
5615 * `prompt.submit`'s input as a plugin's call takes it: `origin`, `turnId`
5616 * and `wait` are the engine's to set, `context` the hooks' to attach.
5617 *
5618 * `origin` is the calling plugin's name; `turnId` is the turn a prompt typed
5619 * mid-turn ran over; `wait` is false, as a plugin's prompt runs once idle.
5620 */
5621 export type PromptSubmitArgs = Omit<PromptSubmitInput, 'origin' | 'turnId' | 'wait' | 'context'>;
5622
5623 /**
5624 * The input of `prompt.submit`: the prompt as typed, after the input became
5625 * a user message and before it enters the session.
5626 */
5627 export type PromptSubmitInput = {
5628 /**
5629 * The prompt's text as it will reach the model (pastes already expanded).
5630 */
5631 text: string;
5632 /**
5633 * Present only when the submission carried images or other non-text items.
5634 */
5635 attachments?: readonly PromptAttachment[];
5636 /**
5637 * What the model reads beside the prompt and the user never sees, each
5638 * entry one block after the prompt as typed; absent as the engine raises it.
5639 *
5640 * A hook attaches on the way down: `next({ ...e, context: [...(e.context
5641 * ?? []), mine] })`. It may not leave out an entry it received; the whole
5642 * is capped at 32000 characters, no entry empty.
5643 */
5644 context?: readonly string[];
5645 /**
5646 * The id of the model turn that was running when the prompt was submitted
5647 * (`turn.start`'s `turnId`): typed over that turn, or delivered into it.
5648 *
5649 * A queued delivery (a peer session's message) reaches the model inside a
5650 * running turn. Absent for a prompt submitted while the session was idle,
5651 * and for a plugin's own (`$.prompt.submit`), which runs once it is idle.
5652 */
5653 turnId?: string;
5654 /**
5655 * Whether the user asked the prompt to wait its turn (`chat:queueSubmit`,
5656 * `ctrl+x enter` by default): true for that submission, false otherwise.
5657 *
5658 * The engine queues every prompt typed mid-turn either way; the flag is
5659 * for hooks, so one that cancels the running turn on a plain Enter can
5660 * leave a waiting prompt alone. False for a prompt a plugin submitted.
5661 */
5662 wait: boolean;
5663 /**
5664 * Where the submission came from (PromptOrigin), set by the engine where
5665 * it was queued: the user's Enter, a notification, a peer, a plugin.
5666 *
5667 * `next(e)` passes it on as received; no hook may set one.
5668 */
5669 origin: PromptOrigin;
5670 };
5671
5672 /**
5673 * What a `prompt.submit` hook returns and what `next(e)` resolves to: the
5674 * prompt that entered, `{ text, context?, origin? }`, or `{ drop: reason }`.
5675 *
5676 * `next(e)` resolves once the prompt entered the session and its turn
5677 * started, or it was queued behind the running one; not when the turn ends,
5678 * which is `turn.complete`. A hook answering without `next` enters nothing.
5679 */
5680 export type PromptSubmitResult = {
5681 /**
5682 * The prompt that entered; from core, the text that arrived at the
5683 * bottom. A rewrite passes it down, `next({ ...e, text })`.
5684 */
5685 text: string;
5686 /**
5687 * What entered beside the prompt for the model, never shown the user:
5688 * from core, the context that arrived (`e.context`).
5689 *
5690 * Each entry is one block after the prompt as typed. A hook attaches
5691 * context on the way down; one put here after `next` resolved is not
5692 * attached (the prompt had entered), and is logged.
5693 */
5694 context?: readonly string[];
5695 /**
5696 * Where the prompt entered from: from core, `e.origin` as received;
5697 * absent, the prompt is the user's own.
5698 *
5699 * A hook may put back the origin it received; it may not set another.
5700 */
5701 origin?: PromptOrigin;
5702 drop?: undefined;
5703 } | {
5704 /**
5705 * The prompt did not enter: a hook's refusal, answered without `next`,
5706 * or a settings hook's block beneath.
5707 *
5708 * The text is shown to the user as the reason.
5709 */
5710 drop: string;
5711 text?: undefined;
5712 context?: undefined;
5713 origin?: undefined;
5714 };
5715
5716 /**
5717 * `prompt.suggest`'s input as a plugin's `$.prompt.suggest(args)` takes it:
5718 * `origin` is the engine's to set (the calling plugin's name).
5719 */
5720 export type PromptSuggestArgs = Omit<PromptSuggestInput, 'origin'>;
5721
5722 /**
5723 * The input of `prompt.suggest` (prompt-suggest/): a text about to be shown
5724 * dim in the empty prompt box, for Tab (or the right arrow) to take.
5725 */
5726 export type PromptSuggestInput = {
5727 /**
5728 * The proposed prompt: shown, not written; taking it puts it in the box
5729 * for editing. `next({ ...e, text })` proposes another.
5730 */
5731 text: string;
5732 /**
5733 * Who proposes (PromptSuggestOrigin), set by the engine where the
5734 * proposal starts. Pinned: `next(e)` passes it on as received.
5735 */
5736 origin: PromptSuggestOrigin;
5737 };
5738
5739 /**
5740 * Who proposes the text at `prompt.suggest`, as the engine stamps it where
5741 * the proposal starts; a closed set a matcher narrows on.
5742 *
5743 * `next(e)` passes it on as received; no hook sets one.
5744 */
5745 export type PromptSuggestOrigin = {
5746 /**
5747 * The engine's own guess at the person's next prompt, generated after
5748 * a turn (the prompt-suggestion service).
5749 */
5750 kind: 'suggestion';
5751 } | {
5752 /**
5753 * A plugin's `$.prompt.suggest`.
5754 */
5755 kind: 'plugin';
5756 /**
5757 * The proposing plugin's name.
5758 */
5759 name: string;
5760 };
5761
5762 /**
5763 * What a `prompt.suggest` hook returns and what `next(e)` resolves to:
5764 * whether the text is now the box's dim suggestion.
5765 */
5766 export type PromptSuggestResult = {
5767 /**
5768 * True once the box has the suggestion to show, at once or as soon as a
5769 * dialog gives the box back; false where it cannot show.
5770 *
5771 * It cannot while the box holds text, a turn runs, the text is blank, or
5772 * the session is headless. A hook answering `{ isShown: false }` without
5773 * `next` keeps it from showing.
5774 */
5775 isShown: boolean;
5776 };
5777
5778 /**
5779 * The props of `Raster`, the terminal surface's cell-grid leaf: a fixed box
5780 * of cells, each a glyph, a foreground and a background, packed in `cells`.
5781 *
5782 * A leaf: no children, `hover` or `onPress` yet; repainted in place by
5783 * `$.ui.blit`. Terminal only for now (elsewhere a fragment); its palette
5784 * paints 1024 distinct color pairs at once and the rest as their nearest.
5785 */
5786 export type RasterProps = {
5787 /**
5788 * The element's address within the drawing: what `$.ui.blit` names to
5789 * repaint it, unique among the Rasters of one tree.
5790 */
5791 key: string;
5792 /**
5793 * How many terminal columns wide, 1 to 512; the site clips what its body
5794 * cannot show.
5795 */
5796 columns: number;
5797 /**
5798 * How many terminal rows tall, 1 to 256.
5799 */
5800 rows: number;
5801 /**
5802 * Every cell, row-major: standard padded base64 of `columns * rows`
5803 * little-endian u32 triplets `[codePoint, foreground, background]`.
5804 *
5805 * A code point is one printable width-1 BMP character (blocks, box drawing,
5806 * braille too), or the tree is refused naming the cell's index; a color is
5807 * `0x00RRGGBB`, or `0x01000000` (bit 24 alone) for the terminal's default.
5808 *
5809 * @example const words = Uint32Array.of(0x2588, 0xff8800, 0x01000000)
5810 * const cells = new Uint8Array(words.buffer).toBase64() // one orange cell
5811 */
5812 cells: string;
5813 };
5814
5815 /**
5816 * The hooks module's entry: `export function register(on, options)`. `on`
5817 * registers hooks; `options` is the plugin's configuration (PluginOptions).
5818 *
5819 * The options are fixed for this activation: a change to them reloads the
5820 * plugin and `register` runs again with the new object. Hooks close over it.
5821 * Its return is dropped, a promise awaited: `on => on(...)` is a module.
5822 *
5823 * @example
5824 * on("tool.call", ($, e, next) => e.tool === "Bash" ? { deny: "no" } : next(e))
5825 */
5826 export type Register = (on: On, options: PluginOptions) => unknown;
5827
5828 /**
5829 * What `on(...)` returns for a hook of type `F`: the registration, which
5830 * takes one `.catch` (CatchHandler); without it a failed hook is absent.
5831 *
5832 * A second `.catch` on one registration throws, as does one after
5833 * register() returned and one on `engine.create`, whose hook has no budget
5834 * and whose failure is the load's.
5835 */
5836 export type Registration<F> = {
5837 /**
5838 * Sets the handler run when the hook throws or overruns its budget; its
5839 * answer within the grace stands as the hook's result for the dispatch.
5840 */
5841 readonly catch: (handler: CatchHandler<F>) => void;
5842 };
5843
5844 /**
5845 * What an element takes as `children`, as JSX passes them: a node, a number
5846 * (drawn as its string), a value the factory drops, or a list that may nest.
5847 *
5848 * `false`, `null` and `undefined` are dropped, so `{ok && <Text>hi</Text>}`
5849 * and `{n > 0 ? <Text>{n}</Text> : null}` type; a mapped list beside a
5850 * sibling nests. The element holds the flat, normalized list of RenderNode.
5851 */
5852 export type RenderChildren = RenderNode | number | boolean | null | undefined | readonly RenderChildren[];
5853
5854 /**
5855 * Everything `ui.render` can draw: one name per component that has a render
5856 * site; a matcher narrows on it.
5857 *
5858 * The permission dialog is drawn by the engine alone, since its answer
5859 * authorises an action; a plugin adds context with `$.ui.notice`. `Pane` is
5860 * the one component whose instances a plugin opens (`$.ui.open`).
5861 */
5862 export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
5863
5864 /**
5865 * What a render hook returns, and what `next(e)` resolves to: a plain-data
5866 * tree of elements (a Box or Text is a StyledElement), strings as children.
5867 *
5868 * Props are an allowlisted subset of Ink's Box/Text props (the ones
5869 * ElementProps declares); a tree with any other prop fails validation as a
5870 * whole and the engine's own component is drawn with the original props.
5871 */
5872 export type RenderElement = StyledElement<'Box', BoxHoverProps> | StyledElement<'Text', TextHoverProps> | {
5873 /**
5874 * A button, on every surface: `[ label ]` on the terminal, a native
5875 * button on a desktop; a press raises `ui.press` (`e.element` the key).
5876 *
5877 * Built by `<Button>` or the table's `t.Button`. The `onPress` closure
5878 * stays in the plugin's own environment under `press.handle`; the host
5879 * holds the handle for the lifetime of the drawing. A leaf: no children.
5880 */
5881 type: 'Button';
5882 props: {
5883 /**
5884 * The element's address: what `e.element` carries and what a matcher
5885 * names (`{ element: "explain" }`).
5886 */
5887 key: string;
5888 /**
5889 * The text drawn on the button.
5890 */
5891 label: string;
5892 /**
5893 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it
5894 * where the site honours one; anything else is refused.
5895 *
5896 * A bare digit in an empty composer presses, as a survey is answered;
5897 * while one of the band's Buttons has the focus a digit or a letter
5898 * presses on keydown, lowercased. Two on one hotkey: the later wins.
5899 */
5900 hotkey?: string;
5901 /**
5902 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord
5903 * presses the Button from the prompt; an unknown name is refused.
5904 *
5905 * Chords, or a modified key Global or an active context binds, on
5906 * the terminal while mounted, no dialog up, no engine handler of it
5907 * mounted; a pane's over the band's over another's, the last drawn.
5908 */
5909 action?: string;
5910 /**
5911 * Drawn without chrome: the hotkey in the accent color, a colon,
5912 * then the label (`1: Yes`), as a survey's row reads.
5913 *
5914 * In JSX the label may be the one string child
5915 * (`<Button hotkey="1" plain onPress={...}>Yes</Button>`); the key
5916 * defaults to the label.
5917 */
5918 plain?: true;
5919 /**
5920 * The label dim at rest, as `Text`'s `dimColor`, and at full strength
5921 * under the pointer or the focus; absent draws as false.
5922 */
5923 dimColor?: TextProps['dimColor'];
5924 };
5925 /**
5926 * Where the handler lives: the plugin whose hook drew the element, and
5927 * the handle its environment keeps the `onPress` closure under.
5928 *
5929 * The runtime stamps the plugin as the tree leaves that hook.
5930 */
5931 press: {
5932 plugin: string;
5933 handle: number;
5934 };
5935 /**
5936 * Label style overrides (the Text set) the surface applies while the
5937 * nearest keyed Box, or the group `scope` names, is hovered; plain data.
5938 */
5939 hover?: TextHoverProps;
5940 } | {
5941 /**
5942 * A one-line text field on every surface; a change and Enter raise
5943 * `ui.input` (`e.element` the key, `e.kind` which, `e.value` the text).
5944 *
5945 * Built by `<Input>` or the table's `t.Input`. The `onInput` and
5946 * `onSubmit` closures stay in the plugin's own environment under
5947 * `press.handle`, held as a Button's is. A leaf: no children.
5948 */
5949 type: 'Input';
5950 props: {
5951 /**
5952 * The element's address: what `e.element` carries and what a matcher
5953 * names (`{ element: "reply" }`).
5954 */
5955 key: string;
5956 /**
5957 * Text drawn before the field.
5958 */
5959 label?: string;
5960 /**
5961 * Text drawn dim in an empty field.
5962 */
5963 placeholder?: string;
5964 /**
5965 * The text the field holds when drawn.
5966 */
5967 value?: string;
5968 /**
5969 * What Enter does, drawn beside the field while it has focus.
5970 */
5971 submitLabel?: string;
5972 };
5973 /**
5974 * Where the handlers live: the plugin whose hook drew the element, and
5975 * the handle its environment keeps the closures under.
5976 *
5977 * The runtime stamps the plugin as the tree leaves that hook.
5978 */
5979 press: {
5980 plugin: string;
5981 handle: number;
5982 };
5983 children?: undefined;
5984 } | {
5985 /**
5986 * A one-of-several picker on every surface; a pick raises `ui.select`
5987 * (`e.element` the key, `e.value` the option's value).
5988 *
5989 * Built by `<Select>` or the table's `t.Select`. The `onSelect` closure
5990 * stays in the plugin's own environment under `press.handle`, held as
5991 * a Button's is. A leaf: no children.
5992 */
5993 type: 'Select';
5994 props: {
5995 /**
5996 * The element's address: what `e.element` carries and what a matcher
5997 * names (`{ element: "peer" }`).
5998 */
5999 key: string;
6000 /**
6001 * Text drawn before the current value.
6002 */
6003 label?: string;
6004 /**
6005 * What can be picked, in the order drawn: each a value and the text
6006 * drawn for it.
6007 */
6008 options: readonly SelectOption[];
6009 /**
6010 * Which option is selected when drawn.
6011 */
6012 value?: string;
6013 };
6014 /**
6015 * Where the handler lives: the plugin whose hook drew the element, and
6016 * the handle its environment keeps the closure under.
6017 *
6018 * The runtime stamps the plugin as the tree leaves that hook.
6019 */
6020 press: {
6021 plugin: string;
6022 handle: number;
6023 };
6024 children?: undefined;
6025 } | {
6026 /**
6027 * A hyperlink every surface draws: an OSC 8 span on the terminal (its
6028 * text then the URL in dim where unsupported), an anchor on desktop.
6029 *
6030 * Inline: its children are the text, strings and inline elements;
6031 * absent children the label, absent both the URL. `href` is `https:`
6032 * (or `http://localhost`) and bounded, or the tree is refused.
6033 */
6034 type: 'Link';
6035 props: LinkProps;
6036 children?: RenderNode[];
6037 } | {
6038 /**
6039 * Source code every surface draws with the engine's highlighter, tokens
6040 * coloured by language; under `format: 'diff'`, unified-diff hunks.
6041 *
6042 * A leaf: a dim gutter numbers the lines from `startLine`; a diff has
6043 * both gutters, markers, add and remove backgrounds. `source` is
6044 * bounded as a Text's string is, or the tree is refused.
6045 */
6046 type: 'Code';
6047 props: CodeProps;
6048 children?: undefined;
6049 } | {
6050 /**
6051 * A region one of the plugin's SURFACE MODULES, named by path, draws and
6052 * handles input for on the drawing thread, without `$` (ClientModule).
6053 *
6054 * `Client` from the table. One instance per plugin, drawing and `key`
6055 * lives while the node stays in the tree, and talks to the plugin's
6056 * hooks through `ui.message`. The desktop carries it as data.
6057 */
6058 type: 'Client';
6059 props: ClientProps;
6060 /**
6061 * Whose surface module `props.module` names: the plugin whose hook
6062 * drew the element, stamped by the runtime as the tree leaves it.
6063 */
6064 client: {
6065 plugin: string;
6066 };
6067 children?: undefined;
6068 } | {
6069 /**
6070 * A vector drawing, the desktop and mobile surfaces' alone: the SVG
6071 * markup is the element's data, drawn in an isolated box, off the page.
6072 *
6073 * A leaf: hooks above wrap or replace it whole, nothing reaches inside;
6074 * a press other plugins should see goes on an enclosing Button. On a
6075 * surface whose table lacks it the tree is refused.
6076 */
6077 type: 'Svg';
6078 props: SvgProps;
6079 children?: undefined;
6080 } | {
6081 /**
6082 * A grid of terminal cells, the terminal surface's alone: each cell a
6083 * glyph, a foreground and a background, packed in `props.cells`.
6084 *
6085 * A leaf, one node however many cells; hooks above wrap or replace it
6086 * whole. A mounted one is repainted in place by its plugin's
6087 * `$.ui.blit`. On a surface whose table lacks it the tree is refused.
6088 */
6089 type: 'Raster';
6090 props: RasterProps;
6091 /**
6092 * Whose Raster: the plugin whose hook drew the element, stamped by the
6093 * runtime as the tree leaves it; the one plugin whose blit reaches it.
6094 */
6095 raster: {
6096 plugin: string;
6097 };
6098 children?: undefined;
6099 } | {
6100 /**
6101 * The component core draws itself, with the props held under `ref`.
6102 */
6103 type: 'engine';
6104 /**
6105 * Which drawing: the number core answered from `next(e)`, under which
6106 * it holds the props it received; 0 draws the original props.
6107 */
6108 ref: number;
6109 };
6110
6111 /**
6112 * The render event: `ui.render`, one event for every component that has a
6113 * render site.
6114 */
6115 export type RenderEventName = 'ui.render';
6116
6117 /**
6118 * The input of `ui.render`: a union discriminated by `component`, one member
6119 * per RenderComponent and per RenderSurface.
6120 */
6121 export type RenderInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = C extends RenderComponent ? P extends RenderSurface ? RenderInputOf<C, P> : never : never;
6122
6123 /**
6124 * One `ui.render` input, for a component narrowed to one surface.
6125 */
6126 export type RenderInputOf<C extends RenderComponent, P extends RenderSurface> = {
6127 /**
6128 * Where the tree will be drawn; one literal per member, so
6129 * `if (e.surface === "terminal")` narrows `e` and `$.ui.resolve(e)`.
6130 *
6131 * Over the wire it is what the client declared, a rendering fact and not a
6132 * trust signal: do not key policy on it.
6133 */
6134 surface: P;
6135 /**
6136 * Which component this instance is; the key a matcher narrows on.
6137 */
6138 component: C;
6139 /**
6140 * The instance: the tool_use_id for a dialog or tool row, the message id
6141 * for a message, the agent id for a spinner.
6142 *
6143 * Two drawings of one component are two instances.
6144 */
6145 requestId: string;
6146 /**
6147 * The size of what the surface draws into, in character cells; absent where
6148 * no surface has measured. Part of the envelope: a rewrite keeps it.
6149 *
6150 * On the terminal, the interactive screen's size, where a change of width
6151 * re-draws every hooked site once the resize settles (a hook that sized its
6152 * tree to `columns` runs again); on a remote surface, what it reported.
6153 */
6154 viewport?: RenderViewport;
6155 /**
6156 * The component's plain-data props.
6157 */
6158 props: RenderPropsOf[C];
6159 };
6160
6161 /**
6162 * A node of a render tree: an element, or a string (text).
6163 */
6164 export type RenderNode = RenderElement | string;
6165
6166 /**
6167 * The plain-data props of each renderable component, as `ui.render` sees
6168 * them under `e.props`; a hook rewrites them with `next({ ...e, props })`.
6169 *
6170 * A rewrite is validated by the component and an invalid one draws the
6171 * original. This table is the plugin-facing render contract: the terminal
6172 * and the Code session renderer draw these components from these props.
6173 */
6174 export type RenderPropsOf = {
6175 /**
6176 * The dialog the AskUserQuestion tool opens.
6177 */
6178 AskUserQuestion: {
6179 /**
6180 * The name of the tool whose call opened the dialog (`AskUserQuestion`).
6181 */
6182 tool: string;
6183 /**
6184 * The tool's `questions` input, as the dialog will draw them; a rewrite
6185 * must still fit the tool's schema or the original is drawn.
6186 */
6187 questions: unknown[];
6188 /**
6189 * The call's `metadata.source` (who asked) when the model gave one.
6190 * Analytics only; never drawn.
6191 */
6192 metadataSource?: string;
6193 };
6194 /**
6195 * The user's own prompt in the transcript (the `> ...` row); a rewrite is
6196 * drawn there and nowhere else (the stored message is untouched).
6197 */
6198 UserMessage: {
6199 /**
6200 * The prompt's text, as the row draws it.
6201 */
6202 text: string;
6203 /**
6204 * Where the stored message came from, as `prompt.submit` named it
6205 * (PromptOrigin): the composer's, a peer's, a notification's, a plugin's.
6206 *
6207 * Read-only: a rewrite carries it on as received; one that changes or
6208 * drops it is refused and the engine draws its own row.
6209 */
6210 origin: PromptOrigin;
6211 };
6212 /**
6213 * One text block of an assistant reply in the transcript; a rewrite
6214 * changes the drawing and leaves the stored message alone (ctrl+o).
6215 */
6216 AssistantMessage: {
6217 /**
6218 * The block's text, markdown, as the transcript will draw it.
6219 */
6220 text: string;
6221 /**
6222 * True on the block that draws the bullet opening a reply.
6223 */
6224 isFirstOfReply: boolean;
6225 };
6226 /**
6227 * A tool call's row in the transcript (`Bash(ls -la)` and its result); the
6228 * call was decided by `tool.call`, so a rewrite here changes the row alone.
6229 */
6230 ToolUse: {
6231 /**
6232 * The id `tool.call` carried for this call (`e.tool_use_id` there); the
6233 * same value as the row's `requestId`, where it is looked for. Read-only.
6234 */
6235 tool_use_id: string;
6236 /**
6237 * Which one the row draws (`Bash`, `Read`, a plugin's tool), as
6238 * `tool.call` named it.
6239 */
6240 tool: string;
6241 /**
6242 * The call's input, as the model sent it.
6243 */
6244 input: unknown;
6245 /**
6246 * True while the call is still running.
6247 */
6248 isRunning: boolean;
6249 /**
6250 * True when the call ended in an error (a refusal at the dialog is one).
6251 */
6252 isErrored: boolean;
6253 /**
6254 * True when an abort ended the call: the user's Esc or a plugin's
6255 * `$.turn.abort` cut it while it ran, or dropped it before it ran.
6256 *
6257 * The row draws `Interrupted` for it, as the transcript marker does.
6258 */
6259 isInterrupted: boolean;
6260 /**
6261 * The stored result once the call has resolved (`{ stdout, stderr, ... }`
6262 * for Bash: `BuiltinToolResults[tool]`); undefined while it runs.
6263 *
6264 * For a call that errored, was refused or an abort cut, it is the text
6265 * the model read (an `isInterrupted` call: the abort's own). An expanded
6266 * group's rows draw it inline; a standalone row's is its own `ToolResult`.
6267 */
6268 output?: unknown;
6269 };
6270 /**
6271 * The result block drawn under a standalone tool row in the transcript,
6272 * which the tool's own result renderer draws from `output`.
6273 *
6274 * A rewrite of `output` is checked against the tool's output schema (one
6275 * that does not fit draws nothing; one the renderer cannot read hits the
6276 * row's error boundary). The stored result is untouched.
6277 */
6278 ToolResult: {
6279 /**
6280 * The id `tool.call` carried for the call this result belongs to
6281 * (`e.tool_use_id` there); the same value as `requestId`. Read-only.
6282 */
6283 tool_use_id: string;
6284 /**
6285 * Which one the result belongs to (`Bash`, `Read`, a plugin's tool).
6286 * Read-only.
6287 */
6288 tool: string;
6289 /**
6290 * The tool's own result object (`{ stdout, stderr, interrupted, ... }` for
6291 * Bash), the same one `ToolUse.output` carries; a rewrite is drawn.
6292 *
6293 * A built-in tool's is `BuiltinToolResults[tool]`, the record
6294 * `tool.call` resolved as `result`.
6295 */
6296 output: unknown;
6297 /**
6298 * True when the call ended in an error, which draws the error text and not
6299 * `output`. Read-only.
6300 */
6301 isErrored: boolean;
6302 };
6303 /**
6304 * A run of tool calls the transcript folds into one count line (`Read 3
6305 * files, ran 2 shell commands`): reads, searches, listings.
6306 *
6307 * A hook that sets `isExpanded` unfolds the group where it is, and each row
6308 * it unfolds into is a `ToolUse` drawing a `ToolUse` hook then sees.
6309 */
6310 ToolGroup: {
6311 /**
6312 * In the order the model made them.
6313 */
6314 calls: ReadonlyArray<ToolGroupCall>;
6315 /**
6316 * True while the group is the live one: a call in it may still be
6317 * running and the model's next call may join it.
6318 */
6319 isActive: boolean;
6320 /**
6321 * Whether each call draws as its own `ToolUse` row (true under
6322 * `--verbose` and in the ctrl+o transcript) or the group draws one line.
6323 *
6324 * The one prop of the three a rewrite changes on the screen.
6325 */
6326 isExpanded: boolean;
6327 };
6328 /**
6329 * The output row a slash command printed in the transcript, under its echo
6330 * (`/cost`'s lines, the `text` a `command.run` hook answered).
6331 *
6332 * What the run resolved as text, a `local` command's or a plugin's alike. A
6333 * rewrite of `text` draws there and the stored row keeps what the model
6334 * reads; a hook's own tree draws in the row's place, the transcript's width.
6335 */
6336 CommandOutput: {
6337 /**
6338 * Which one printed the row, as `command.run` named it (no slash); a
6339 * hook on its own command matches by it.
6340 *
6341 * Read-only: a rewrite carries it on as received; one that changes or
6342 * drops it is refused and the engine draws its own row.
6343 */
6344 command: string;
6345 /**
6346 * The arguments the run had, as the echo above the row shows them
6347 * (`***` for a command that marks its arguments sensitive). Read-only.
6348 */
6349 args: string;
6350 /**
6351 * The row's text: what the command printed, or the `text` a hook
6352 * answered under its plugin's name; markdown, as the row draws it.
6353 */
6354 text: string;
6355 /**
6356 * True when the row is the run's error line (a command that threw),
6357 * which draws in the error colour and not dim. Read-only.
6358 */
6359 isErrored: boolean;
6360 };
6361 /**
6362 * The line that animates while a turn runs (`Sauteing... (12s, 300
6363 * tokens)`). Terminal only: the Code session renderer draws its own.
6364 */
6365 Spinner: {
6366 /**
6367 * Animated by the line (`Sauteing`), as sampled for this turn.
6368 */
6369 word: string;
6370 /**
6371 * The text drawn instead of the word while a state overrides it, else null.
6372 */
6373 message: string | null;
6374 /**
6375 * What the turn is doing.
6376 */
6377 mode: 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use';
6378 };
6379 /**
6380 * The line that closes a turn in the transcript (`Baked for 3s`).
6381 * Terminal only: the Code session renderer draws its own footer.
6382 */
6383 TurnDuration: {
6384 /**
6385 * The past-tense word the line drew (`Baked`), as sampled for this line.
6386 */
6387 word: string;
6388 /**
6389 * The turn's duration in milliseconds, as the line formats it (`3s`,
6390 * `1m 4s`).
6391 */
6392 durationMs: number;
6393 };
6394 /**
6395 * One dim status line under the logo (the model source, an experiment
6396 * enrollment, a settings hint), with a trailing `/command`. Terminal only.
6397 */
6398 InfoNotice: {
6399 /**
6400 * The notice's text, flattened to one string.
6401 */
6402 text: string;
6403 /**
6404 * The slash command appended after the text, or null when the notice has
6405 * none.
6406 */
6407 command: string | null;
6408 };
6409 /**
6410 * The dim mode labels at the right of the prompt footer (`focus`, `memory
6411 * paused`), joined by ` & `. One instance; terminal only.
6412 *
6413 * A hook adds a mode by rewriting `modes`, removes one by filtering, or
6414 * draws its own tree.
6415 */
6416 SessionMode: {
6417 /**
6418 * The labels the footer shows, in order; empty when there are none.
6419 */
6420 modes: readonly string[];
6421 };
6422 /**
6423 * The dim hint line under the prompt (`? for shortcuts`, `esc to
6424 * interrupt`, the pills beside them). One instance; terminal only.
6425 *
6426 * A hook rewrites `hint` and the rewrite is drawn in the line's place, or
6427 * draws its own tree; `isDraft` and `isWorking` say what the line is for.
6428 */
6429 PromptHint: {
6430 /**
6431 * True while the prompt holds typed text. Read-only.
6432 */
6433 isDraft: boolean;
6434 /**
6435 * True while a model turn is running. Read-only.
6436 */
6437 isWorking: boolean;
6438 /**
6439 * The line's text as the engine draws it; one string, so a rewrite
6440 * replaces the line.
6441 *
6442 * Read from the drawn line the way the screen reader reads it, one space
6443 * between parts.
6444 */
6445 hint: string;
6446 };
6447 /**
6448 * The band directly above the prompt input, where the surveys draw; the
6449 * engine draws nothing of its own here.
6450 *
6451 * A hook draws a tree, or passes; one instance, terminal only. The person
6452 * collapses it (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab):
6453 * an Input types, a Button arms the hotkeys, a tree taller than it scrolls.
6454 */
6455 AbovePrompt: {
6456 /**
6457 * True while a survey holds the band; a hook yields to it. Read-only.
6458 */
6459 hasSurvey: boolean;
6460 /**
6461 * True while a model turn is running. Read-only.
6462 */
6463 isWorking: boolean;
6464 /**
6465 * Rows the band may take: in fullscreen, what the bottom slot has left
6466 * above the prompt; otherwise the terminal's height. Read-only.
6467 *
6468 * A tree of at most `maxRows` rows shows whole; a taller one scrolls in a
6469 * window of `scroll.bodyRows` (one fewer, over a dim `n more` row), and a
6470 * bare digit arms none of its Buttons' hotkeys.
6471 */
6472 maxRows: number;
6473 /**
6474 * Cells across the band: the terminal's width, or the transcript
6475 * column's while a `Pane` is docked beside it. Read-only.
6476 *
6477 * A tree wider than this wraps or truncates as its Text props say; size
6478 * a table or a rule to it rather than to `viewport.columns`.
6479 */
6480 bodyColumns: number;
6481 /**
6482 * The band's window over a tree taller than `maxRows`: engine-owned,
6483 * moved by the wheel, and by the person's keys while the band is focused.
6484 *
6485 * `bodyRows` is `maxRows` less the `n more` row. Read-only.
6486 */
6487 scroll: SiteScroll;
6488 /**
6489 * Which transcript is on screen above the band: the main conversation's
6490 * (no `agentId`) or one agent's, opened from the tasks list.
6491 *
6492 * The same band under either; a switch re-runs the hook with the new
6493 * view. Read-only: a rewrite carries it on as received; one that changes
6494 * or drops it is refused, the hook that passed it failing.
6495 */
6496 view: SiteView;
6497 };
6498 /**
6499 * The framed region a plugin opened with `$.ui.open({ id })`: one instance
6500 * per id (`requestId`), its body the hook's tree, one shown, the rest tabs.
6501 *
6502 * Placed by the surface (docked in fullscreen, else above the prompt) and
6503 * keyed by the person (ctrl+x tab, Esc), who closes it from the engine's mark
6504 * or ctrl+x x: `ui.close` with origin `person`, which a hook may refuse.
6505 */
6506 Pane: {
6507 /**
6508 * Its tab's label while more than one pane is open (with one, the engine
6509 * draws no title): the `title` it was opened with, or its id.
6510 *
6511 * A click on a tab, or Tab onto it and Enter, shows that pane. Read-only
6512 * here; another `$.ui.open` (or a hook on `ui.open`) retitles.
6513 */
6514 title: string;
6515 /**
6516 * True while the person has given the pane the keyboard. Read-only.
6517 */
6518 isFocused: boolean;
6519 /**
6520 * Cells across the body, inside the frame. Read-only.
6521 */
6522 bodyColumns: number;
6523 /**
6524 * Where the surface seated the pane: `dock` beside the transcript (the
6525 * terminal in fullscreen from 110 columns), or `inline` above the prompt.
6526 *
6527 * Read-only: a rewrite carries it on as received; one that changes or
6528 * drops it is refused, the hook that passed it failing.
6529 */
6530 placement: 'dock' | 'inline';
6531 /**
6532 * The body's window over the tree: engine-owned, moved by the person's
6533 * keys while the pane is focused. Read-only.
6534 */
6535 scroll: SiteScroll;
6536 /**
6537 * Which transcript is on screen beside the pane: the main conversation's
6538 * (no `agentId`) or one agent's, opened from the tasks list.
6539 *
6540 * The pane stays open across a switch, one instance re-rendered for the
6541 * view, so a hook draws for the agent in view. Read-only: a rewrite carries
6542 * it on as received; one that changes or drops it is refused.
6543 */
6544 view: SiteView;
6545 };
6546 };
6547
6548 /**
6549 * What a `ui.render` hook returns and what `next(e)` resolves to: a
6550 * RenderElement tree, the same for every component.
6551 */
6552 export type RenderResultOf = {
6553 [C in RenderComponent]: RenderElement;
6554 };
6555
6556 /**
6557 * Where a render event's component is drawn: `terminal` is Ink, which draws
6558 * the hook's whole tree; `desktop` (Claude Code Desktop) and `mobile` (the
6559 * Claude mobile app) are remote surfaces that draw the tree themselves.
6560 *
6561 * A remote surface asks over the wire (ui_render), draws with the props the
6562 * hook handed core and draws the tree where it has a slot for it. Each
6563 * surface's ask is its own evaluation, since a tree may hold an element only
6564 * some surfaces draw (Svg, Client).
6565 */
6566 export type RenderSurface = 'terminal' | 'desktop' | 'mobile';
6567
6568 /**
6569 * The size of what a surface draws into, in character cells of the
6570 * surface's monospace metric: on the terminal, the conversation's columns and
6571 * screen rows; on a remote surface, the pane's width and height divided by the
6572 * advance and line height of its code font. A pixel-sized companion
6573 * arrives with the first element that lays out in pixels; until then
6574 * every element on every surface is cell-based, and so is this.
6575 */
6576 export type RenderViewport = {
6577 /**
6578 * Cells across. A tree wider than this wraps or truncates, as its Text
6579 * props say.
6580 */
6581 columns: number;
6582 /**
6583 * Cells down the whole surface, not the room left for this component.
6584 * Informational: a change of height alone re-draws nothing and keys no
6585 * new evaluation, so a hook reads it as of the last width or props change.
6586 */
6587 rows: number;
6588 };
6589
6590 /**
6591 * The input of `ui.resolve`: which surface's elements, for which component;
6592 * a union with one member per surface (ResolveInputOf).
6593 *
6594 * Resolved when the plugins load, ahead of any drawing, so it names the
6595 * surface and the component and not the props; a `ui.render` argument is
6596 * one (it carries both), which is what `$.ui.resolve(e)` takes.
6597 */
6598 export type ResolveInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = P extends RenderSurface ? ResolveInputOf<C, P> : never;
6599
6600 /**
6601 * One `ui.resolve` input, for a component on one surface.
6602 */
6603 export type ResolveInputOf<C extends RenderComponent, P extends RenderSurface> = {
6604 /**
6605 * Where the table draws; one literal per member, so a hook that narrows
6606 * it narrows the table `next(e)` resolves to.
6607 */
6608 surface: P;
6609 /**
6610 * Which drawing the table is resolved for; the key a matcher narrows on.
6611 */
6612 component: C;
6613 };
6614
6615 /**
6616 * What each event's hook returns, and what its `next(e)` resolves to, by event
6617 * name.
6618 */
6619 export type ResultOf = EngineResultOf & ClassicResultOf & {
6620 [N in OpEventName]: OpEventResult<N>;
6621 } & {
6622 [N in NounEventName]: NounEventResult<N>;
6623 };
6624
6625 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';
6626
6627 /**
6628 * The members of `T` assignable to `S`; all of `T` when none is.
6629 */
6630 type Select<T, S> = [Extract<T, S>] extends [never] ? T : Extract<T, S>;
6631
6632 /**
6633 * The events a pattern selects, as a union of names: the one named, every
6634 * one under a glob's namespace, or every one a negation does not exclude.
6635 */
6636 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>;
6637
6638 /**
6639 * The literal each tag key of `I` is held to by matcher `M`: one-of arrays
6640 * flattened, RegExps widened to `unknown`.
6641 */
6642 type Selection<I, M> = {
6643 [K in keyof M & TagKeys<I>]: Literal<M[K] extends readonly (infer One)[] ? One : M[K]>;
6644 };
6645
6646 /**
6647 * One option of a `Select`: the value `onSelect` and `ui.select` carry, and
6648 * the text drawn for it (the value when absent).
6649 */
6650 export type SelectOption = {
6651 value: string;
6652 label?: string;
6653 };
6654
6655 /**
6656 * The props of `Select`, every surface's one-of-several picker: an address,
6657 * a label, the options, the one selected, the closure a pick runs. A leaf.
6658 *
6659 * Focused through the same ring as `Button` (`abovePrompt:focus`); keys reach
6660 * it only while it has focus (arrows move, Enter picks) and Esc always
6661 * returns to the prompt; a pick raises `ui.select`, its bottom `onSelect`.
6662 */
6663 export type SelectProps = {
6664 /**
6665 * The element's address: `e.element` at `ui.select`, what a matcher names.
6666 */
6667 key: string;
6668 /**
6669 * Text drawn before the current value.
6670 */
6671 label?: string;
6672 /**
6673 * What can be picked, in the order drawn; at least one, values unique.
6674 */
6675 options: readonly SelectOption[];
6676 /**
6677 * Which option is selected when drawn; the person's pick replaces it
6678 * until the hook draws another.
6679 */
6680 value?: string;
6681 /**
6682 * Runs on a pick with the option's value, in the plugin's own environment:
6683 * the bottom of a `ui.select` chain. No model turn unless it asks one.
6684 */
6685 onSelect: (value: string, e: UiSelectArgument) => void;
6686 };
6687
6688 /**
6689 * The input of `session.attach`: a surface joined the session's roster of
6690 * attached clients (a phone opened the session; the desktop app connected).
6691 *
6692 * A remote client attaches by saying so (ui_attach) or by its first ask to
6693 * draw; the terminal's attachment is the REPL's binding and raises nothing.
6694 * Every field is the engine's: a hook observes, `next(e)` passes them on.
6695 */
6696 export type SessionAttachInput = {
6697 /**
6698 * Where the client draws: what it declared, a rendering fact.
6699 */
6700 surface: RenderSurface;
6701 /**
6702 * The client's own id, unique in the roster; two phones are two clients on
6703 * one surface. A client that never named itself is `<surface>:default`.
6704 */
6705 clientId: string;
6706 /**
6707 * The size the client draws into, in character cells, when it said.
6708 */
6709 viewport?: RenderViewport;
6710 };
6711
6712 /**
6713 * What a `session.attach` hook returns and what `next(e)` resolves to:
6714 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
6715 */
6716 export type SessionAttachResult = {
6717 clientId: string;
6718 };
6719
6720 /**
6721 * What `$.session.authorize()` answers: an opaque handle for the session's
6722 * Anthropic credential and its kind, or null when there is none to hold.
6723 *
6724 * The secret itself stays with the engine; the handle is its plugin-side
6725 * face, spent through `$.http.fetch(url, { auth: handle })`.
6726 */
6727 export type SessionAuthorization = {
6728 handle: string;
6729 kind: 'bearer' | 'api-key';
6730 } | null;
6731
6732 /**
6733 * `session.compact`'s input as a plugin's `$.session.compact(args)` takes
6734 * it: `trigger` (`plugin`), `messages` and `agentId` are the engine's.
6735 */
6736 export type SessionCompactArgs = {
6737 /**
6738 * What the summary should keep or stress, as typed after `/compact`;
6739 * absent, the engine's own compaction prompt alone.
6740 */
6741 instructions?: string;
6742 };
6743
6744 /**
6745 * A compaction that stands: the conversation as it reads afterwards, and
6746 * the token counts the engine recorded when it was the one compacting.
6747 */
6748 export type SessionCompacted = {
6749 /**
6750 * The conversation after the compaction, oldest first: from core, its
6751 * summary and the messages it kept; from a hook, whatever it hands up.
6752 *
6753 * What the transcript becomes (kept, on `precompute`, for the compaction
6754 * that comes). A message with the engine's `handle` stands as the engine
6755 * has it; one without is built from its `role`, `text` and tool blocks.
6756 */
6757 messages: readonly SessionMessage[];
6758 /**
6759 * The conversation's size before, in tokens; absent when core did not
6760 * record it.
6761 */
6762 tokensBefore?: number;
6763 /**
6764 * Its size afterwards, in tokens; absent on `precompute` and when core
6765 * did not record it.
6766 */
6767 tokensAfter?: number;
6768 skip?: undefined;
6769 };
6770
6771 /**
6772 * The input of `session.compact`: one compaction of the conversation, about
6773 * to run; `messages` is the transcript it runs over.
6774 */
6775 export type SessionCompactInput = {
6776 /**
6777 * What is compacting (SessionCompactTrigger); the key a matcher narrows
6778 * on. Pinned: `next(e)` passes it on as received.
6779 */
6780 trigger: SessionCompactTrigger;
6781 /**
6782 * The id of the loop compacting, for a subagent's or a fork's own
6783 * transcript; absent for the main conversation (tool.call's `agentId`).
6784 *
6785 * Pinned: left out of a rewrite it is put back, changed it fails the hook.
6786 * `$.session.messages()` is the main conversation whatever this names.
6787 */
6788 agentId?: string;
6789 /**
6790 * What the summary should keep or stress: the text after `/compact`, a
6791 * plugin's, or absent.
6792 *
6793 * `next({ ...e, instructions })` changes what the summarizer is told.
6794 */
6795 instructions?: string;
6796 /**
6797 * The transcript being compacted, in `$.session.messages()`'s shape, each
6798 * message carrying the engine's `handle`; a subagent's own under `agentId`.
6799 *
6800 * `next({ ...e, messages })` changes what is summarized: a message kept
6801 * with its handle is the engine's own, whole; one without is read as built.
6802 */
6803 messages: readonly SessionMessage[];
6804 };
6805
6806 /**
6807 * What a `session.compact` hook returns and what `next(e)` resolves to: the
6808 * compaction (`{ messages, tokensBefore?, tokensAfter? }`) or `{ skip }`.
6809 *
6810 * There is no summary string: the summary is a message.
6811 */
6812 export type SessionCompactResult = SessionCompacted | SessionCompactSkipped;
6813
6814 /**
6815 * A compaction vetoed: on `precompute` nothing is computed or kept; on any
6816 * other trigger the conversation stays as it is and one line says why.
6817 *
6818 * Core answers it too, when a classic PreCompact hook blocks.
6819 */
6820 export type SessionCompactSkipped = {
6821 /**
6822 * Why, as the notice reads.
6823 */
6824 skip: string;
6825 messages?: undefined;
6826 };
6827
6828 /**
6829 * Who compacts: the person's `/compact` (`manual`), the engine at its
6830 * threshold or on a prompt too long (`auto`), a plugin, or a `precompute`.
6831 *
6832 * `precompute` is the one dispatch that installs nothing: its result is kept
6833 * for the compaction that comes, if the conversation it ran over still leads.
6834 */
6835 export type SessionCompactTrigger = 'manual' | 'auto' | 'plugin' | 'precompute';
6836
6837 /**
6838 * The context window broken down as /context breaks it down: the rows, the
6839 * grid and the lists beneath it, in the SDK's `get_context_usage` shape.
6840 *
6841 * Less that reply's internal-build sections. Token counts are the engine's
6842 * estimates as numbers, never formatted: a `full` breakdown counts with the
6843 * token-count API where it can, a `summary` one estimates throughout.
6844 */
6845 export type SessionContextBreakdown = {
6846 /**
6847 * One row per category, the free space and the compaction buffer among
6848 * them; `kind` says which is which.
6849 */
6850 categories: ContextCategory[];
6851 /**
6852 * Tokens in use, unclamped: past `rawMaxTokens` when over the window.
6853 */
6854 totalTokens: number;
6855 /**
6856 * The window measured against, the same figure as `rawMaxTokens`.
6857 */
6858 maxTokens: number;
6859 /**
6860 * The window measured against, in tokens: the model's limit, or a smaller
6861 * compaction window (`autocompactSource` says which).
6862 */
6863 rawMaxTokens: number;
6864 /**
6865 * How that window was settled (ContextWindowSource); the SDK's reply
6866 * carries it under this name too, outside its typed schema.
6867 */
6868 autocompactSource: ContextWindowSource;
6869 /**
6870 * `totalTokens` over `rawMaxTokens` as a whole percentage, 0 to 100 and
6871 * past it when over.
6872 */
6873 percentage: number;
6874 /**
6875 * The grid, row by row: 10 by 10, 20 by 10 for a window of a million or
6876 * more, 5 wide when asked for under 80 `columns`.
6877 */
6878 gridRows: ContextGridSquare[][];
6879 /**
6880 * Which model the breakdown was computed for, as `/model` shows it.
6881 */
6882 model: string;
6883 /**
6884 * Each memory file in the context, with its path and tokens.
6885 */
6886 memoryFiles: ContextMemoryFile[];
6887 /**
6888 * Each MCP tool's schema, with its server and tokens.
6889 */
6890 mcpTools: ContextMcpTool[];
6891 /**
6892 * The custom agents the Agent tool describes, each with its tokens.
6893 */
6894 agents: ContextAgent[];
6895 /**
6896 * The slash-command listing, counted; absent when the session lists none.
6897 */
6898 slashCommands?: ContextSlashCommands;
6899 /**
6900 * The skill listing, counted, with one entry per skill; absent when the
6901 * session lists none.
6902 */
6903 skills?: ContextSkills;
6904 /**
6905 * The token count at which auto-compaction runs; absent when it is off.
6906 */
6907 autoCompactThreshold?: number;
6908 /**
6909 * Whether auto-compaction is on for the session.
6910 */
6911 isAutoCompactEnabled: boolean;
6912 /**
6913 * The last response's own token counts, or null before one came back.
6914 */
6915 apiUsage: ContextApiUsage | null;
6916 };
6917
6918 /**
6919 * The live context window as the status line reads it, and by category as
6920 * /context breaks it down when the call asked (`{ breakdown }`).
6921 *
6922 * `tokens` and `percent` are the last API response's input side against the
6923 * model's window, absent until the first response of the live window: a
6924 * fresh session, or one just compacted, until its next response.
6925 */
6926 export type SessionContextUsage = {
6927 /**
6928 * Input tokens the last response was answered over: uncached, cache-written
6929 * and cache-read together (the status line's `total_input_tokens`).
6930 */
6931 tokens?: number;
6932 /**
6933 * The context window of the session's model, in tokens (the status line's
6934 * `context_window_size`).
6935 */
6936 window: number;
6937 /**
6938 * `tokens` over `window` as a whole percentage, 0 to 100 (the status
6939 * line's `used_percentage`).
6940 */
6941 percent?: number;
6942 /**
6943 * The window by category, as /context breaks it down: present only when
6944 * the call passed `breakdown`, and only with a session bound.
6945 *
6946 * It measures against the compaction window (`rawMaxTokens`), which may be
6947 * smaller than `window`, and estimates every category, so its
6948 * `totalTokens` need not equal `tokens`.
6949 */
6950 breakdown?: SessionContextBreakdown;
6951 };
6952
6953 /**
6954 * What the session has cost, as `/cost` and the status line total it.
6955 */
6956 export type SessionCost = {
6957 /**
6958 * US dollars, summed over every priced API response this session.
6959 */
6960 usd: number;
6961 };
6962
6963 type SessionCronSummary = {
6964 id: string;
6965 /**
6966 * Cron expression, e.g. "0 9 * * 1-5".
6967 */
6968 schedule: string;
6969 /**
6970 * False for one-shot wakeups whose cron field encodes a single fire time; true for tasks that re-fire on every match.
6971 */
6972 recurring: boolean;
6973 /**
6974 * Prompt text submitted when the cron fires. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
6975 */
6976 prompt: string;
6977 };
6978
6979 /**
6980 * The input of `session.detach`: a client left the session's roster. Every
6981 * field is the engine's: a hook observes, and `next(e)` passes them on.
6982 */
6983 export type SessionDetachInput = {
6984 /**
6985 * Where the client drew.
6986 */
6987 surface: RenderSurface;
6988 /**
6989 * The id it attached under.
6990 */
6991 clientId: string;
6992 /**
6993 * Why it left: it detached, or the session ended under it.
6994 */
6995 reason: SessionDetachReason;
6996 };
6997
6998 /**
6999 * Why a client left the roster: `detach`, it said so (ui_detach); `end`, the
7000 * session ended with it still attached.
7001 */
7002 export type SessionDetachReason = 'detach' | 'end';
7003
7004 /**
7005 * What a `session.detach` hook returns and what `next(e)` resolves to:
7006 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
7007 */
7008 export type SessionDetachResult = {
7009 clientId: string;
7010 };
7011
7012 type SessionEndHookInput = BaseHookInput & {
7013 hook_event_name: 'SessionEnd';
7014 reason: ExitReason;
7015 };
7016
7017 /**
7018 * One message of the transcript as `$.session.messages()` returns it.
7019 */
7020 export type SessionMessage = {
7021 /**
7022 * Who wrote it.
7023 */
7024 role: 'user' | 'assistant';
7025 /**
7026 * Its text blocks joined; '' when it has none.
7027 */
7028 text: string;
7029 /**
7030 * The tool_use blocks of an assistant message, each with its outcome
7031 * (`result`, `text`, `isError`) once the transcript holds it.
7032 */
7033 toolUses: ToolUseSummary[];
7034 /**
7035 * The tool_result blocks of a user message: `{ tool_use_id, text, isError,
7036 * result }`.
7037 */
7038 toolResults?: ToolResultSummary[];
7039 /**
7040 * An opaque token the engine stamps on a message it hands a
7041 * `session.compact` hook, so a list handed back maps to its own messages.
7042 *
7043 * Absent on `$.session.messages()` and on a message a hook built.
7044 */
7045 handle?: string;
7046 };
7047
7048 /**
7049 * One rate-limit window as the rate-limit notices read it.
7050 */
7051 export type SessionRateLimit = {
7052 /**
7053 * Which window: `five_hour`, `seven_day`, or a Claude gateway's
7054 * `spend_limit`.
7055 */
7056 kind: string;
7057 /**
7058 * How much of the window is used, 0 to 100 (above 100 once a spend limit
7059 * is exceeded).
7060 */
7061 percentUsed: number;
7062 /**
7063 * When the window resets, as an ISO 8601 timestamp.
7064 */
7065 resetsAt?: string;
7066 };
7067
7068 /**
7069 * An external-event wake the delivery's text parsed as (a GitHub relay
7070 * event, a signal's notice): the envelope's attributes and its JSON body.
7071 */
7072 export type SessionReceiveEvent = {
7073 /**
7074 * The producing service (`github`).
7075 */
7076 source: string;
7077 /**
7078 * The event's discriminator (`pull_request.closed`, `check_suite`).
7079 */
7080 kind: string;
7081 /**
7082 * The envelope's JSON body (`{ pr: "acme/app#12", outcome: "merged" }`).
7083 */
7084 data: Record<string, unknown>;
7085 /**
7086 * The `data` keys whose values are free text a third party wrote (a
7087 * commenter's `author` and `comment`), as the producer marked them.
7088 *
7089 * Empty when none; the server asserts every other key's value, not these.
7090 */
7091 untrustedKeys: readonly string[];
7092 };
7093
7094 /**
7095 * The input of `session.receive`: one inbound delivery (a relay's event, a
7096 * peer's message, a Remote Control prompt), sanitized, before it is queued.
7097 */
7098 export type SessionReceiveInput = {
7099 /**
7100 * Where the delivery came from, as the bridge classified it; the key a
7101 * matcher narrows on. `next(e)` passes it on as received.
7102 */
7103 origin: SessionReceiveOrigin;
7104 /**
7105 * The delivery's body as the model would read it (a content-block
7106 * delivery's text blocks, joined).
7107 */
7108 text: string;
7109 /**
7110 * The external-event wake the text parsed as (`source` `github` for a
7111 * subscribed pull request's event); passed on as received.
7112 *
7113 * Present only for a delivery the server itself rendered as a wake (a
7114 * webhook relay, the session inbox), by its asserted origin; anyone else's
7115 * wake-shaped text stays `text`. Its `untrustedKeys` name third-party text.
7116 */
7117 event?: SessionReceiveEvent;
7118 };
7119
7120 /**
7121 * Where an inbound delivery came from, as the bridge classified it from the
7122 * server's stamps: `prompt.submit`'s `e.origin`, less what never arrives.
7123 */
7124 export type SessionReceiveOrigin = {
7125 /**
7126 * `bridge` the user's own from a Remote Control client; `peer` another
7127 * session; `unclassified` one the bridge could not place.
7128 *
7129 * `task-notification` a relay's event (a GitHub webhook) or a trigger;
7130 * `scheduled-trigger` a routine; `peer-send-message` another session's
7131 * SendMessage; `projects-relay` and `slack-ping` as at `prompt.submit`.
7132 */
7133 kind: 'bridge' | 'task-notification' | 'scheduled-trigger' | 'peer' | 'peer-send-message' | 'projects-relay' | 'slack-ping' | 'unclassified';
7134 };
7135
7136 /**
7137 * What a `session.receive` hook returns and what `next(e)` resolves to: the
7138 * delivery that was queued, `{ text }`, or `{ consumed: reason }`.
7139 *
7140 * `next(e)` resolves once the delivery is queued; a hook answering without
7141 * `next` queues nothing.
7142 */
7143 export type SessionReceiveResult = {
7144 /**
7145 * The body the delivery was queued with; from core, `e.text` as it
7146 * arrived at the bottom.
7147 *
7148 * A rewrite passes it down, `next({ ...e, text })`.
7149 */
7150 text: string;
7151 consumed?: undefined;
7152 } | {
7153 /**
7154 * Takes the delivery, answered without `next`: it is not queued, not
7155 * written to the transcript and never reaches the model.
7156 *
7157 * The reason is logged, the plugin named.
7158 */
7159 consumed: string;
7160 text?: undefined;
7161 };
7162
7163 /**
7164 * What `$.session.repo()` answers: the repository's root and its origin remote,
7165 * when the session is in one.
7166 */
7167 export type SessionRepo = {
7168 /**
7169 * The repository's root, absolute: the main working tree's for a worktree.
7170 */
7171 root: string;
7172 /**
7173 * The `origin` remote's URL as git has it (push URL preferred), or null when
7174 * the repository has none.
7175 */
7176 remote: string | null;
7177 /**
7178 * Whether the remote is one of the repositories this build treats as its
7179 * own; false in a build that has none or when the remote is unrecognized.
7180 *
7181 * The engine matches the build's own list of repositories with its
7182 * hardened remote parser. A plugin reads this to behave differently in a
7183 * public repository; which repositories are the build's is its to say.
7184 */
7185 internal: boolean;
7186 /**
7187 * The repository the allowlist matched, as `owner/name`; null when
7188 * `internal` is false.
7189 *
7190 * A working copy without a remote that the engine still recognises is
7191 * named by its own checkout configuration; a remote's name is its path.
7192 */
7193 name: string | null;
7194 };
7195
7196 type SessionStartHookInput = BaseHookInput & {
7197 hook_event_name: 'SessionStart';
7198 source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork';
7199 agent_type?: string;
7200 model?: string;
7201 session_title?: string;
7202 /**
7203 * resume/fork: seconds since the resumed transcript's last assistant response
7204 */
7205 seconds_since_last_response?: number;
7206 /**
7207 * 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)
7208 */
7209 context_tokens?: number;
7210 /**
7211 * resume/fork: seconds_since_last_response exceeds the prompt-cache TTL, so the first request re-caches context_tokens
7212 */
7213 prompt_cache_likely_expired?: boolean;
7214 /**
7215 * resume/fork: estimated cost of re-caching context_tokens on the session model - the managed modelPricing when set, otherwise list price; excludes the response
7216 */
7217 estimated_cache_write_usd?: number;
7218 };
7219
7220 /**
7221 * The input of `session.start`: the session the process starts with, read the
7222 * way `$.session` reads it at that moment.
7223 */
7224 export type SessionStartInput = {
7225 /**
7226 * The directory the session runs in, absolute (`$.session.cwd()`).
7227 */
7228 cwd: string;
7229 /**
7230 * Where the session draws at start (`$.session.surfaces()[0]`): `terminal`
7231 * under the REPL; null for a `-p` run or the SDK, which draw nowhere yet.
7232 */
7233 surface: RenderSurface | null;
7234 /**
7235 * Whether a person is at the prompt: true under the REPL, false for a `-p`
7236 * run or the SDK.
7237 */
7238 isInteractive: boolean;
7239 };
7240
7241 /**
7242 * What a `session.start` hook returns and what `next(e)` resolves to:
7243 * `{ cwd }`, echoed by core; a hook's own value does not change the session.
7244 */
7245 export type SessionStartResult = {
7246 cwd: string;
7247 };
7248
7249 /**
7250 * What `$.session.usage()` answers: the context window's fill, the account's
7251 * rate-limit windows and the session's cost, as the status line has them.
7252 *
7253 * A figure the engine does not have is left out, never zeroed: `rateLimits`
7254 * is empty off a subscription, `cost` absent where the host keeps no ledger.
7255 */
7256 export type SessionUsage = {
7257 /**
7258 * The live context window: the status line's `context_window` figures.
7259 */
7260 context: SessionContextUsage;
7261 /**
7262 * The rate-limit windows the last API response reported (`five_hour`,
7263 * `seven_day`, a gateway's `spend_limit`); empty when none has a reading.
7264 */
7265 rateLimits: SessionRateLimit[];
7266 /**
7267 * What the session has cost so far, as /cost totals it; absent only where
7268 * the host keeps no cost ledger (the CLI always has one).
7269 */
7270 cost?: SessionCost;
7271 };
7272
7273 /**
7274 * What `$.session.usage(args)` takes: nothing for the status line's figures
7275 * alone; `breakdown` to have the window broken down as /context breaks it.
7276 */
7277 export type SessionUsageArgs = {
7278 /**
7279 * Asks for `context.breakdown` and says how it is counted
7280 * (ContextBreakdownDetail); absent, none is computed and the call is free.
7281 *
7282 * `full` sends one token-count request per tool and memory file, as
7283 * /context does; `summary` estimates locally and sends none.
7284 */
7285 breakdown?: ContextBreakdownDetail;
7286 /**
7287 * The width the breakdown's grid will be drawn in, in terminal columns;
7288 * absent, the full-width grid. Read only with `breakdown`.
7289 *
7290 * Under 80 the grid is the narrow one /context draws there, 5 wide. A thin
7291 * client's breakdown is the remote workspace's, whose grid ignores this.
7292 */
7293 columns?: number;
7294 };
7295
7296 /**
7297 * What `$.settings.read` answers: an object keyed as a settings.json is
7298 * (`permissions`, `env`, `hooks`, `model`, `enabledPlugins`, ...).
7299 *
7300 * Each key is as https://code.claude.com/docs/en/settings documents it and
7301 * https://json.schemastore.org/claude-code-settings.json types it. A
7302 * snapshot in plain data: a write to it changes nothing the engine reads.
7303 */
7304 export type Settings = Readonly<Record<string, unknown>>;
7305
7306 /**
7307 * What `$.settings.read(args)` takes.
7308 */
7309 export type SettingsReadArgs = {
7310 /**
7311 * The one source read, as loaded; absent, the settings merged over every
7312 * source, as the engine runs under them.
7313 */
7314 source?: SettingsSource;
7315 };
7316
7317 /**
7318 * One source of settings by the name a plugin gives it, lowest precedence
7319 * first; the engine's own name is the same word with `Settings` appended.
7320 *
7321 * `user` is ~/.claude/settings.json, `project` .claude/settings.json,
7322 * `local` .claude/settings.local.json, `flag` what `--settings` and the
7323 * SDK's inline settings carry, and `policy` the managed settings, every
7324 * managed tier merged.
7325 */
7326 export type SettingsSource = 'user' | 'project' | 'local' | 'flag' | 'policy';
7327
7328 type SetupHookInput = BaseHookInput & {
7329 hook_event_name: 'Setup';
7330 trigger: 'init' | 'maintenance';
7331 };
7332
7333 /**
7334 * Where a site's window sits over the tree a hook drew in it (a pane's body,
7335 * the band): the engine's to move (the person scrolls), the plugin's to read.
7336 */
7337 export type SiteScroll = {
7338 /**
7339 * The first row of the tree the window shows; 0 at the top. Read-only.
7340 */
7341 offset: number;
7342 /**
7343 * How many rows of the tree the window shows at once: the rows the
7344 * surface gave the body. Read-only.
7345 */
7346 bodyRows: number;
7347 };
7348
7349 /**
7350 * Which transcript the person has on screen where a site draws: the main
7351 * conversation's, or one agent's, opened from the tasks list.
7352 *
7353 * The person's to switch, the plugin's to read: a switch re-runs the site's
7354 * hooks with the new view, the site itself staying where it is.
7355 */
7356 export type SiteView = {
7357 /**
7358 * The agent whose transcript is in view: the `id` `$.agent.list()` gives
7359 * it, the `agentId` its `turn.step` and `tool.call` events carry.
7360 *
7361 * Absent while the main conversation is in view. Read-only.
7362 */
7363 agentId?: string;
7364 };
7365
7366 /**
7367 * The input of `skill.prompt`: one skill's prompt, at the moment the engine
7368 * expanded it for the model.
7369 *
7370 * Typed as `/name`, called through the Skill tool, or preloaded into a
7371 * subagent: the same event at each.
7372 */
7373 export type SkillPromptInput = {
7374 /**
7375 * Which skill (`commit`); the key a matcher narrows on.
7376 */
7377 skill: string;
7378 /**
7379 * The prompt's text as the skill computed it (its text blocks, joined).
7380 */
7381 text: string;
7382 };
7383
7384 /**
7385 * What a `skill.prompt` hook returns: the text the model reads for that
7386 * skill.
7387 */
7388 export type SkillPromptResult = {
7389 text: string;
7390 };
7391
7392 /**
7393 * Options of `$.clock.sleep`.
7394 */
7395 export type SleepOptions = {
7396 /**
7397 * Aborting it rejects the sleep at once.
7398 */
7399 signal?: AbortSignal;
7400 };
7401
7402 /**
7403 * Options of `$.audio.speak`.
7404 */
7405 export type SpeakOptions = {
7406 /**
7407 * The system voice's exact name as the platform lists it (`Samantha`, or the
7408 * name of a voice you installed). Absent: the synthesizer's default voice.
7409 */
7410 voice?: string;
7411 };
7412
7413 /**
7414 * The argument of `$.audio.speak(text, options)` as the event carries it.
7415 */
7416 type SpeakRequest = SpeakOptions & {
7417 /**
7418 * What to say, as plain text, of at most 4096 characters.
7419 */
7420 text: string;
7421 };
7422
7423 /**
7424 * What `$.audio.speak` resolves with once the utterance has ended.
7425 */
7426 export type SpeakResult = {
7427 /**
7428 * Which synthesizer spoke: `system`, the platform's own (`say` on macOS).
7429 */
7430 via: 'system';
7431 };
7432
7433 /**
7434 * `next` in a `*` hook: the set of events is open at runtime, so `e` is
7435 * `unknown` until `next.is(pattern, e)` narrows it to events it knows.
7436 *
7437 * The callable is an overload per known event (OrderedOverloads), then
7438 * `(e: unknown) => Promise<unknown>` last: `next(e)` with `e` still unknown
7439 * resolves to `unknown`.
7440 */
7441 export type StarNext = OrderedOverloads<EventName> & {
7442 (e: unknown): Promise<unknown>;
7443 /**
7444 * Continues this dispatch at a tier, as Next's `to` (a managed hook's):
7445 * `e` still unknown resolves to `unknown`.
7446 */
7447 readonly to: (e: unknown, tier: TargetTier) => Promise<unknown>;
7448 readonly signal: AbortSignal;
7449 readonly is: <M extends Pattern>(pattern: M, e: unknown) => e is Frozen<Args<Selected<M>>>;
7450 readonly event: EventName;
7451 readonly origin: Origin;
7452 readonly trace: readonly TraceEntry<EventName, unknown, unknown>[];
7453 };
7454
7455 type StopFailureHookInput = BaseHookInput & {
7456 hook_event_name: 'StopFailure';
7457 error: SDKAssistantMessageError;
7458 error_details?: string;
7459 last_assistant_message?: string;
7460 };
7461
7462 type StopHookInput = BaseHookInput & {
7463 hook_event_name: 'Stop';
7464 stop_hook_active: boolean;
7465 /**
7466 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
7467 */
7468 last_assistant_message?: string;
7469 /**
7470 * 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.
7471 */
7472 background_tasks?: BackgroundTaskSummary[];
7473 /**
7474 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
7475 */
7476 session_crons?: SessionCronSummary[];
7477 };
7478
7479 /**
7480 * The hook a streaming event takes: `async function* ($, e, next) {}`,
7481 * yielding the event's chunks and returning its result.
7482 *
7483 * `return yield* next(e)` passes; `for await (const c of next(e)) yield
7484 * f(c)` transforms; yielding without `next` answers alone. A chunk yielded
7485 * stays: a hook that fails mid-stream is left, the rest from beneath it.
7486 *
7487 * @example on('turn.step', async function* ($, e, next) {
7488 * const r = yield* next(e); return { ...r } })
7489 */
7490 export type StreamHook<N extends StreamingEventName> = ($: EngineInterface, e: Frozen<Args<N>>, next: StreamNext<N>) => StreamHookBody<Chunk<N>, EventResult<N>>;
7491
7492 /**
7493 * What a hook on a streaming event evaluates to: the async generator an
7494 * `async function*` makes, yielding `C` and returning `R` or nothing.
7495 *
7496 * Returning nothing lets its last `next(e)`'s result stand. A plain
7497 * function is a type error here even when it returns `next(e)`: the hook
7498 * is the generator, not a function that hands one back.
7499 */
7500 export type StreamHookBody<C, R> = AsyncGenerator<C, R | void> & {
7501 /**
7502 * Absent on a generator; present on `next(e)`, which is not a hook body.
7503 */
7504 readonly result?: never;
7505 };
7506
7507 /**
7508 * The events that stream: their hooks are async generators, `next(e)` is
7509 * the stream of everything beneath, and the result is what it returns.
7510 *
7511 * `turn.step` alone: the model's response arrives in pieces, and a hook
7512 * that saw it whole could not change what had already been shown.
7513 */
7514 export type StreamingEventName = 'turn.step';
7515
7516 /**
7517 * The rest of the chain as a hook on a streaming event receives it: Next,
7518 * except that `next(e)` is the stream beneath (HookStream), not a promise.
7519 *
7520 * Each call opens a fresh stream; for `turn.step` each is a model request,
7521 * so a hook that calls it twice makes two. Not calling it yields the hook's
7522 * own chunks and returns its own result, and nothing beneath runs.
7523 *
7524 * @template S what `next.is(pattern, e)` narrows `e` to, as Next's
7525 */
7526 export type StreamNext<N extends StreamingEventName = StreamingEventName, E = Args<N>, O = NextResult<N>, S extends {
7527 [K in N]?: unknown;
7528 } = {
7529 [K in N]: Args<K>;
7530 }> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin'> & {
7531 (e: E): HookStream<Chunk<N>, O>;
7532 /**
7533 * Continues this dispatch at a tier, as Next's `to`: the stream beneath
7534 * with the links between this hook's tier and that one skipped.
7535 */
7536 readonly to: (e: E, tier: TargetTier) => HookStream<Chunk<N>, O>;
7537 /**
7538 * What settled beneath on the latest `next()` stream, as Next's; a
7539 * streaming link's entry counts the chunks it yielded up (`chunks`).
7540 */
7541 readonly trace: readonly TraceEntry<N, E, O>[];
7542 };
7543
7544 /**
7545 * The shape a `Box` and a `Text` share in a render tree: allowlisted props,
7546 * an optional `hover`, the group stamp a `hover.scope` earns, and children.
7547 *
7548 * `Tag` is which of the two; `Hover` is that element's hover props. Every
7549 * surface draws both: Ink's Box and Text on the terminal, a flex div and a
7550 * styled span on the desktop.
7551 */
7552 type StyledElement<Tag extends 'Box' | 'Text', Hover> = {
7553 type: Tag;
7554 /**
7555 * A Box's layout, margin, padding and border props and the `key` that
7556 * makes it a hover scope; a Text's colors and styles. Others are refused.
7557 */
7558 props?: Record<string, string | number | boolean>;
7559 /**
7560 * Style overrides the surface applies while the pointer is over the
7561 * nearest keyed Box, or over any member of the group `scope` names.
7562 *
7563 * Plain data, no hook. Never a layout change: `borderStyle` restyles a
7564 * border the Box has, `display` only reveals a Box drawn `"none"` inside
7565 * a keyed Box, and never in a scope.
7566 */
7567 hover?: Hover;
7568 /**
7569 * Whose group `hover.scope` names; absent without a `scope`.
7570 */
7571 group?: PluginStamp;
7572 /**
7573 * In order: a Box holds elements and strings (core wraps each string in
7574 * a Text); a Text holds strings and inline elements, never an engine node.
7575 */
7576 children?: RenderNode[];
7577 };
7578
7579 type SubagentStartHookInput = BaseHookInput & {
7580 hook_event_name: 'SubagentStart';
7581 agent_id: string;
7582 agent_type: string;
7583 };
7584
7585 type SubagentStopHookInput = BaseHookInput & {
7586 hook_event_name: 'SubagentStop';
7587 stop_hook_active: boolean;
7588 agent_id: string;
7589 agent_transcript_path: string;
7590 agent_type: string;
7591 /**
7592 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
7593 */
7594 last_assistant_message?: string;
7595 /**
7596 * 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.
7597 */
7598 background_tasks?: BackgroundTaskSummary[];
7599 /**
7600 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
7601 */
7602 session_crons?: SessionCronSummary[];
7603 };
7604
7605 /**
7606 * The props of `Svg`, the desktop and mobile surfaces' vector leaf: the
7607 * markup is the element's data, as a string is a Text's, drawn isolated.
7608 *
7609 * A leaf: no children. The surface never lets the markup reach the page
7610 * (the engine bounds it; the desktop draws it as an image, or in a
7611 * sandboxed frame when `isInteractive`; the mobile app in a sandboxed web
7612 * view).
7613 */
7614 export type SvgProps = {
7615 /**
7616 * The SVG document, `<svg ...>...</svg>`, at most 131072 characters.
7617 */
7618 source: string;
7619 /**
7620 * What the drawing says, for a reader that cannot see it; required, since
7621 * a surface without the element draws nothing else of it.
7622 */
7623 alt: string;
7624 /**
7625 * CSS pixels; absent, the box takes the markup's own width up to the slot.
7626 */
7627 width?: number;
7628 /**
7629 * CSS pixels; absent, the markup's own height at the drawn width.
7630 */
7631 height?: number;
7632 /**
7633 * `true` draws the SVG in a script-less sandboxed frame so hover, CSS
7634 * `:hover`, SMIL animation and `<title>` tooltips work; absent, an image.
7635 *
7636 * It never enables script or event-handler attributes (the frame has no
7637 * allow-scripts and the scrub strips them); presses that other plugins
7638 * should observe go on an enclosing element.
7639 */
7640 isInteractive?: boolean;
7641 };
7642
7643 /**
7644 * The keys of `I` a matcher may select variants by: literal-valued in every
7645 * variant, and one literal per variant (IsDiscriminant).
7646 */
7647 type TagKeys<I> = {
7648 [K in MatcherKeys<I>]: IsLiteralValued<MatcherValueOf<I, K>> extends true ? IsDiscriminant<I, K> extends true ? K : never : never;
7649 }[MatcherKeys<I>];
7650
7651 /**
7652 * A tier `next.to(e, tier)` may name: one a floor can reach past a tier of
7653 * less authority to, so never `prepend` or `user`, which nothing skips to.
7654 */
7655 export type TargetTier = Exclude<Tier, 'prepend' | 'user'>;
7656
7657 type TaskCompletedHookInput = BaseHookInput & {
7658 hook_event_name: 'TaskCompleted';
7659 task_id: string;
7660 task_subject: string;
7661 task_description?: string;
7662 teammate_name?: string;
7663 /**
7664 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
7665 */
7666 team_name?: string;
7667 };
7668
7669 type TaskCreatedHookInput = BaseHookInput & {
7670 hook_event_name: 'TaskCreated';
7671 task_id: string;
7672 task_subject: string;
7673 task_description?: string;
7674 teammate_name?: string;
7675 /**
7676 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
7677 */
7678 team_name?: string;
7679 };
7680
7681 type TeammateIdleHookInput = BaseHookInput & {
7682 hook_event_name: 'TeammateIdle';
7683 teammate_name: string;
7684 /**
7685 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
7686 */
7687 team_name: string;
7688 };
7689
7690 /**
7691 * The `Text` props a `hover` may override (its colors and styles, not its
7692 * wrapping) and `scope`, the hover group it joins; a `Button`'s label too.
7693 */
7694 export type TextHoverProps = {
7695 /**
7696 * Names a hover group of this plugin's: every element it draws with the
7697 * same `scope`, in any site on the surface, lights while any is hovered.
7698 *
7699 * Another plugin's elements under the same string are a different group.
7700 * One to 64 characters, no control characters; no keyed Box needed. On the
7701 * terminal a Text nested in a Text follows its group but cannot heat it.
7702 */
7703 scope?: string;
7704 color?: string;
7705 backgroundColor?: string;
7706 dimColor?: boolean;
7707 bold?: boolean;
7708 italic?: boolean;
7709 underline?: boolean;
7710 strikethrough?: boolean;
7711 inverse?: boolean;
7712 };
7713
7714 /**
7715 * The props of `Text`: the color and style props of Ink's Text a tree may
7716 * set. Colors are a theme key or a raw color.
7717 */
7718 export type TextProps = {
7719 /**
7720 * Style overrides applied by the surface while the pointer is over the
7721 * nearest enclosing keyed `Box`, or, given a `scope`, over its group.
7722 *
7723 * No hook runs and nothing crosses to the plugin. Refused outside a keyed
7724 * Box unless it names a `scope`.
7725 */
7726 hover?: TextHoverProps;
7727 color?: string;
7728 backgroundColor?: string;
7729 dimColor?: boolean;
7730 bold?: boolean;
7731 italic?: boolean;
7732 underline?: boolean;
7733 strikethrough?: boolean;
7734 inverse?: boolean;
7735 wrap?: 'wrap' | 'end' | 'middle' | 'truncate' | 'truncate-start' | 'truncate-middle' | 'truncate-end';
7736 };
7737
7738 /**
7739 * One of the chain's five tiers (TIERS), outermost first; on every
7740 * `next.trace` entry, and what `next.to(e, tier)` names.
7741 *
7742 * `prepend` and `append` are the managed plugins an administrator lists,
7743 * `user` everything a person installs, `builtin` the plugins bundled in the
7744 * binary, `core` the engine's innermost link.
7745 */
7746 export type Tier = (typeof TIERS)[number];
7747
7748 /**
7749 * The chain's five tiers, outermost first: earlier is outer is more
7750 * authority, and same-event hooks nest in this order and no other way.
7751 *
7752 * The managed plugins an administrator prepends, everything a person
7753 * installs, the managed plugins appended, the plugins bundled in the binary,
7754 * the engine's innermost link; a built-in's `$` calls still raise everywhere.
7755 */
7756 const TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
7757
7758 /**
7759 * A pending timer from `$.clock.after` / `$.clock.every`.
7760 */
7761 export type Timer = {
7762 /**
7763 * Stops it; a stopped timer never fires again.
7764 */
7765 cancel: () => void;
7766 };
7767
7768 /**
7769 * A timer on `$.clock` (`after`, `every`): `fn` runs after `ms` milliseconds,
7770 * once or until `cancel()`.
7771 */
7772 export type TimerCall = (ms: number, fn: () => void) => Timer;
7773
7774 /**
7775 * Options of `$.ui.toast`.
7776 */
7777 export type ToastOptions = {
7778 /**
7779 * How long the line stays, in milliseconds; default 4000.
7780 */
7781 timeoutMs?: number;
7782 };
7783
7784 /**
7785 * `tool.call`'s input as the call takes it: `tool_use_id` and `agentId` may
7786 * ride along (a hook passing its event's input on) and are dropped.
7787 *
7788 * The run gets its own id and runs in the session's loop.
7789 */
7790 export type ToolCallArgs = ToolCallEnvelope extends infer I ? I extends ToolCallEnvelope ? Omit<I, 'tool_use_id'> & ToolCallReserved<I['tool']> : never : never;
7791
7792 /**
7793 * The envelope the two tool events share: the tool, the id of this call, and
7794 * the tool's arguments spread beside them (`e.command` for Bash).
7795 *
7796 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
7797 * is a string and a rewrite is checked against Bash's schema. The `e` of
7798 * `classic.PreToolUse` exactly; `tool.call`'s adds the loop (ToolCallInput).
7799 */
7800 export type ToolCallEnvelope = BuiltinToolCallInput | McpToolCallInput;
7801
7802 /**
7803 * The input of `tool.call`: the tool, the id of this call, the tool's
7804 * arguments beside them (`e.command` for Bash), and `agentId` in a subagent.
7805 *
7806 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
7807 * is a string and a rewrite is checked against Bash's schema. `tool`,
7808 * `tool_use_id` and `agentId` are reserved: a rewrite of any is refused.
7809 */
7810 export type ToolCallInput = ToolCallEnvelope & AgentLoop;
7811
7812 /**
7813 * `$.tool.call(input)`: resolves with `result` typed for the tool `input`
7814 * names (ToolCallResult), or loosely for an input that names none literally.
7815 */
7816 type ToolCallOverloads = {
7817 <T extends string>(input: ToolCallArgs & ToolNamed<T>): Promise<ToolCallResult<T>>;
7818 (input: ToolCallArgs): Promise<ToolCallResult>;
7819 };
7820
7821 /**
7822 * The keys `tool.call`'s input carries beside the tool's own arguments, none
7823 * of which the tool sees (the engine strips them before the tool runs).
7824 *
7825 * `consent` is the person's own words for the press that raised the call
7826 * (`The user pressed "1: Yes" on ...`): the run's context carries it as a human
7827 * turn, which the permission path reads as the user's request.
7828 */
7829 export type ToolCallReserved<T> = {
7830 tool: T;
7831 tool_use_id?: string;
7832 consent?: string;
7833 };
7834
7835 /**
7836 * What a `tool.call` hook returns and what `next(e)` and `$.tool.call(input)`
7837 * resolve to: the tool's result (`{ result, context? }`) or `{ deny }`.
7838 *
7839 * From core the result is `{ ref, result, text }` or, when the tool reported
7840 * an error, `{ ref, result, text, isError }`; `ref` names core's messages.
7841 *
7842 * @template Name the tool the call went to, typing `result` per built-in
7843 * tool (BuiltinToolResults) once `e.tool` is narrowed; else `unknown`
7844 */
7845 export type ToolCallResult<Name extends string = string> = {
7846 /**
7847 * Refuses the call: the model receives the text as an error result.
7848 * Absent when the call was answered.
7849 */
7850 deny: string;
7851 result?: undefined;
7852 context?: undefined;
7853 ref?: undefined;
7854 text?: undefined;
7855 isError?: undefined;
7856 } | {
7857 /**
7858 * The tool's output: from core the tool's record, typed per built-in
7859 * tool once `e.tool` and `isError` are narrowed; from a hook, its own.
7860 *
7861 * Core validates a hook's answer against the tool's output schema when
7862 * it has one, maps it for the model with the tool's own mapper, and
7863 * records it in the transcript as the tool's result. Absent on a deny.
7864 */
7865 result: ToolResultOf<Name>;
7866 /**
7867 * What the model reads after the tool's result and the user never
7868 * sees. From core, none.
7869 *
7870 * One newline-joined reminder, as a PostToolUse hook's additional
7871 * context is, after the managed tier's review of it; none on a plugin's
7872 * own `$.tool.call`. Kept whole from `next`; capped at 32000 characters.
7873 */
7874 context?: readonly string[];
7875 /**
7876 * Set by core on what `next(e)` resolves to: names the messages core
7877 * produced for the call (they stay on the host side).
7878 *
7879 * A hook that returns the object it got makes core use them verbatim.
7880 * Absent on a hook's own `{ result }` and on a deny.
7881 */
7882 ref?: number;
7883 /**
7884 * Set by core: the result as the model reads it (text blocks joined),
7885 * present whatever the tool, where `result`'s shape varies per tool.
7886 *
7887 * Absent on a hook's own `{ result }`.
7888 */
7889 text?: string;
7890 isError?: undefined;
7891 deny?: undefined;
7892 } | {
7893 /**
7894 * Set by core, present only when the tool reported an error (it threw,
7895 * was interrupted, or answered an error): `text` is what the model read.
7896 */
7897 isError: true;
7898 /**
7899 * What the transcript stored for the errored call: the error text, or
7900 * undefined when nothing was stored; never the tool's typed record.
7901 */
7902 result: unknown;
7903 /**
7904 * The error as the model reads it.
7905 */
7906 text?: string;
7907 /**
7908 * As on an answered result: names the messages core produced.
7909 */
7910 ref?: number;
7911 /**
7912 * As on an answered result.
7913 */
7914 context?: readonly string[];
7915 deny?: undefined;
7916 };
7917
7918 /**
7919 * `tool.check`'s input as `$.tool.check` takes it: the tool and its
7920 * arguments; `tool_use_id` is the engine's to set, never a query's.
7921 */
7922 type ToolCheckArgs = Pick<ToolCheckInput, 'tool' | 'input'>;
7923
7924 /**
7925 * The verdict of `tool.check`: run the tool, put it to the mode's decider
7926 * (the dialog, the auto-mode classifier, a headless host), or refuse it.
7927 */
7928 type ToolCheckDecision = 'allow' | 'ask' | 'deny';
7929
7930 /**
7931 * The input of `tool.check`: the tool, its arguments, and the call's id when
7932 * the engine is deciding a real call.
7933 *
7934 * All three are the question's identity and are pinned: a hook decides
7935 * about this call, it does not change it (`tool.call` rewrites a call).
7936 */
7937 type ToolCheckInput = {
7938 /**
7939 * As the model names it (`Bash`, `mcp__server__tool`); the key a matcher
7940 * narrows on.
7941 */
7942 tool: string;
7943 /**
7944 * The tool's arguments as the permission decision reads them
7945 * (`{ command }` for Bash, `{ file_path, ... }` for the file tools).
7946 */
7947 input: unknown;
7948 /**
7949 * The call being decided, on a real call only; absent on a query.
7950 *
7951 * `next.origin` names who raised it: `{ plugin: 'engine', tier: 'core' }`
7952 * for the model's own call, the plugin for its `$.tool.call` or its query.
7953 */
7954 tool_use_id?: string;
7955 };
7956
7957 /**
7958 * What a `tool.check` hook returns and what `next(e)` resolves to: the
7959 * verdict, why, and the settings rule behind it when one decided.
7960 *
7961 * From core, the engine's declarative decision for the session's mode and
7962 * rules. A hook may answer any verdict in either direction; the last word up
7963 * the chain is the decision.
7964 */
7965 type ToolCheckResult = {
7966 /**
7967 * `allow` runs the tool; `ask` puts it to the mode's decider; `deny`
7968 * refuses it, the reason the model's error.
7969 */
7970 decision: ToolCheckDecision;
7971 /**
7972 * Why, in a sentence: from core the rule or check that decided; from a
7973 * hook, what the model reads on a deny and the dialog shows on an ask.
7974 */
7975 reason?: string;
7976 /**
7977 * The settings rule that decided, as written (`Bash(git push:*)`).
7978 *
7979 * Absent for a mode or a tool's own check.
7980 */
7981 rule?: string;
7982 };
7983
7984 /**
7985 * The input of `tool.describe`: one tool's description, at the moment the
7986 * engine first renders the tool's schema for the model.
7987 */
7988 export type ToolDescribeInput = {
7989 /**
7990 * As the model sees the name (`Bash`, `mcp__server__tool`); the key a
7991 * matcher narrows on.
7992 */
7993 tool: string;
7994 /**
7995 * The tool's description as it computed it.
7996 */
7997 description: string;
7998 /**
7999 * Who provides this tool: the plugin and its tier; `{ plugin: "engine",
8000 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
8001 *
8002 * A configured MCP server's tool is `mcp:<server>`, in `prepend` when the
8003 * policy settings source configures the server, else `user`.
8004 */
8005 provider: Origin;
8006 };
8007
8008 /**
8009 * What a `tool.describe` hook returns: the description the model sees for that
8010 * tool.
8011 */
8012 export type ToolDescribeResult = {
8013 description: string;
8014 };
8015
8016 /**
8017 * `{ tool, tool_use_id, ...args }` as one flat object type, generic over
8018 * the tool name and its parsed arguments.
8019 */
8020 type ToolEnvelope<Name, Arguments> = {
8021 /**
8022 * The name of the tool being called (`Bash`, `mcp__<server>__<tool>`);
8023 * comparing it narrows `e`. Reserved: a rewrite of it is ignored by core.
8024 */
8025 tool: Name;
8026 /**
8027 * The tool_use block's id: the same at every event of the call and in
8028 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
8029 */
8030 tool_use_id: string;
8031 } & Arguments;
8032
8033 /**
8034 * One tool call of a ToolGroup, as `ui.render` sees it under `calls`.
8035 */
8036 export type ToolGroupCall = {
8037 /**
8038 * The id `tool.call` carried for this call (`e.tool_use_id` there), so a
8039 * hook that saw the call finds its row in the group. Read-only.
8040 *
8041 * Absent on a desktop host that predates it.
8042 */
8043 tool_use_id?: string;
8044 /**
8045 * Which one the call ran (`Bash`, `Read`, `Grep`, ...).
8046 */
8047 tool: string;
8048 /**
8049 * The call's input, as the model sent it.
8050 */
8051 input: unknown;
8052 /**
8053 * True while the call is still running.
8054 */
8055 isRunning: boolean;
8056 /**
8057 * True when the call ended in an error.
8058 */
8059 isErrored: boolean;
8060 /**
8061 * True when an abort ended the call, as on `ToolUse`.
8062 */
8063 isInterrupted: boolean;
8064 /**
8065 * As on `ToolUse`; undefined while the call runs.
8066 */
8067 output?: unknown;
8068 };
8069
8070 /**
8071 * One tool as `$.tool.list()` returns it.
8072 */
8073 export type ToolInfo = {
8074 /**
8075 * What the model calls it by.
8076 */
8077 name: string;
8078 /**
8079 * What it does, in the tool's own words (its description; a first sentence at
8080 * most for MCP tools without one).
8081 */
8082 description: string;
8083 /**
8084 * True for an MCP server's tool.
8085 */
8086 mcp: boolean;
8087 };
8088
8089 /**
8090 * `{ tool, tool_use_id, ...args }` as one flat object type.
8091 *
8092 * The docs of `tool` and `tool_use_id` live on the `keyof` operand: a mapped
8093 * type takes its properties' docs from there.
8094 */
8095 export type ToolInputOf<Name extends string, Arguments> = {
8096 [K in keyof ToolEnvelope<Name, Arguments>]: ToolEnvelope<Name, Arguments>[K];
8097 };
8098
8099 /**
8100 * An input that names its tool as the literal `T`: what `next` and
8101 * `$.tool.call` read to type the call's result per tool (NextResultFor).
8102 */
8103 type ToolNamed<T extends string> = {
8104 /**
8105 * The name of the tool being called (`Bash`).
8106 */
8107 readonly tool: T;
8108 };
8109
8110 /**
8111 * The structured result of the tool named `Name`: its BuiltinToolResults
8112 * entry for a built-in tool, else `unknown`.
8113 *
8114 * Agent's is its entry or an AgentCallRecord (what a plugin-raised call
8115 * answers). `unknown` covers an MCP tool, a name the results table lacks
8116 * (one merged into the inputs table alone too), and `Name` left at `string`.
8117 */
8118 export type ToolResultOf<Name extends string> = string extends Name ? unknown : Name extends keyof BuiltinToolResults & string ? BuiltinToolResults[Name] | (Name extends 'Agent' ? AgentCallRecord : never) : unknown;
8119
8120 /**
8121 * One tool_result block of a user message.
8122 */
8123 export type ToolResultSummary = {
8124 /**
8125 * The id of the call this result answers (`tool.call`'s `e.tool_use_id`).
8126 */
8127 tool_use_id: string;
8128 /**
8129 * The result as the model read it (text blocks joined).
8130 */
8131 text: string;
8132 /**
8133 * True when the tool reported an error.
8134 */
8135 isError: boolean;
8136 /**
8137 * What the transcript stored for the call: the tool's record on an answered
8138 * one (`tool.call`'s `result`), the error text when `isError`.
8139 *
8140 * Absent when nothing was stored. Headless (`-p`), a tool may store the
8141 * record less its bulk (Bash blanks `stdout`); `text` is what the model
8142 * read either way.
8143 */
8144 result?: unknown;
8145 };
8146
8147 /**
8148 * What `$.tool.register` takes.
8149 */
8150 export type ToolSpec = {
8151 /**
8152 * The tool's short name (letters, digits, `_`, `-`; up to 64); the model
8153 * calls it as `mcp__<plugin>__<name>`.
8154 */
8155 name: string;
8156 /**
8157 * What the tool does, for the model.
8158 */
8159 description: string;
8160 /**
8161 * A JSON schema object for the input (`{ type: "object", properties,
8162 * required }`); default `{ type: "object" }`.
8163 */
8164 inputSchema?: Record<string, unknown>;
8165 };
8166
8167 /**
8168 * One tool_use block of an assistant message, with its outcome once the
8169 * transcript holds the call's tool_result (paired by `tool_use_id`).
8170 */
8171 export type ToolUseSummary = {
8172 /**
8173 * The call's id, as `tool.call` carried it (`e.tool_use_id` there).
8174 */
8175 tool_use_id: string;
8176 /**
8177 * Which one was called (`Read`, `Bash`, `mcp__server__tool`), as
8178 * `tool.call` named it (`e.tool` there).
8179 */
8180 tool: string;
8181 /**
8182 * The arguments the model gave it.
8183 */
8184 input: Record<string, unknown>;
8185 /**
8186 * What the transcript stored for the call: the tool's record on an answered
8187 * one (`tool.call`'s `result`), the error text on a refused or errored one.
8188 *
8189 * Absent while the call is in flight or when nothing was stored. Headless
8190 * (`-p`), a tool may store the record less its bulk (Bash blanks `stdout`);
8191 * `text` holds either way.
8192 */
8193 result?: unknown;
8194 /**
8195 * The result as the model read it; absent while the call is in flight.
8196 */
8197 text?: string;
8198 /**
8199 * Present only when the tool reported an error, as on `tool.call`'s result.
8200 */
8201 isError?: true;
8202 };
8203
8204 /**
8205 * One settled run of a link beneath the caller, as `next.trace` lists it:
8206 * data, not a handle.
8207 *
8208 * `received` and `returned` are the live references where the hook runs
8209 * beside the chain; in a hooks module its own copies, as `e` is.
8210 */
8211 export type TraceEntry<N extends EventName = EventName, E = Args<N>, O = NextResult<N>> = {
8212 /**
8213 * The link's place in the chain, 0 the outermost.
8214 */
8215 readonly index: number;
8216 /**
8217 * The hook's plugin; `"engine"` for the engine's own core or bottom.
8218 */
8219 readonly plugin: string;
8220 /**
8221 * The link's tier (Tier); `"core"` for the engine's own core or bottom.
8222 */
8223 readonly tier: Tier;
8224 readonly event: N;
8225 readonly outcome: TraceOutcome;
8226 /**
8227 * Why the link was skipped without running, when it was: `bypassed by
8228 * <plugin>`, whose `next.to` went beneath this tier. Absent when it ran.
8229 */
8230 readonly reason?: string;
8231 /**
8232 * Its own wall time, its `next()` calls' time in flight taken out.
8233 *
8234 * The engine entry's is everything beneath the last hook: in a hooks
8235 * module, the host round trip.
8236 */
8237 readonly ms: number;
8238 /**
8239 * How many chunks the link yielded up, on a streaming event; absent on
8240 * every other. A link left mid-stream counts what it yielded before.
8241 */
8242 readonly chunks?: number;
8243 readonly received: E;
8244 /**
8245 * What the link settled on; undefined when it was skipped or rejected.
8246 */
8247 readonly returned: O | undefined;
8248 };
8249
8250 /**
8251 * What the chain decided for one link, as `next.trace` names it.
8252 *
8253 * `returned`: its result stood; `passed`: it returned, by reference, what its
8254 * last `next()` resolved to (a hooks module's hook answers with a copy of its
8255 * own, so it reads `returned`); `skipped`: it failed before `next`, or a
8256 * `next.to` above continued beneath its tier (`reason` says which), and
8257 * beneath ran in its place; `kept`: it failed after `next`, and that run's
8258 * result stands; `expired`: its budget ran out (what stands follows
8259 * skipped/kept); `caught`: it threw or its budget ran out, and its `.catch`
8260 * handler's result stands; `rejected`: the link rejected; the deepest such
8261 * entry is where the rejection came from, and the ones above it let it pass.
8262 */
8263 export type TraceOutcome = 'caught' | 'expired' | 'kept' | 'passed' | 'rejected' | 'returned' | 'skipped';
8264
8265 /**
8266 * What every `turn.complete` carries whatever its reason: the answer, the
8267 * duration, the interrupt flag, the turn's id, its loop and what it cost.
8268 */
8269 type TurnCompleteFields = {
8270 /**
8271 * The assistant's final visible text this turn ("" if none, e.g.
8272 * thinking-only).
8273 */
8274 answer: string;
8275 /**
8276 * Wall-clock length of the turn in milliseconds.
8277 */
8278 durationMs: number;
8279 /**
8280 * True when the turn ended by interruption (`reason === 'aborted'`).
8281 */
8282 isAborted: boolean;
8283 /**
8284 * The turn's id, the same one its `turn.start` and every `turn.step`
8285 * carried; a subagent's run raises no `turn.start`, its steps carry it.
8286 */
8287 turnId: string;
8288 /**
8289 * The loop the turn ran in: a subagent's id, as `$.agent.spawn` resolves
8290 * it, each run of its loop one turn; absent on the main loop.
8291 *
8292 * Pinned: a different value is refused, one left out is kept. Every hook
8293 * sees a subagent's turn, so a hook that spawns sees its children's turns
8294 * too and bounds itself.
8295 */
8296 agentId?: string;
8297 /**
8298 * What the turn cost: its responses' token counts summed and the model of
8299 * the last, read off the API responses the engine already holds.
8300 *
8301 * Absent when the turn got no response (interrupted before one, an API
8302 * error).
8303 */
8304 usage?: TurnUsage;
8305 };
8306
8307 /**
8308 * The input of `turn.complete`: the assistant's final message of a turn, at
8309 * the moment the turn ends (where the turn's duration is reported).
8310 *
8311 * `reason` says why it ended; `refusal` exists on a refusal alone.
8312 */
8313 export type TurnCompleteInput = TurnCompleteFields & (TurnCompleteRefused | TurnCompleteUnrefused);
8314
8315 /**
8316 * Why a turn ended: the model answered, the user interrupted it, the model
8317 * refused with no fallback model to retry on, or an API error ended it.
8318 */
8319 export type TurnCompleteReason = 'answer' | 'aborted' | 'refusal' | 'error';
8320
8321 /**
8322 * The end of a turn the model refused with no fallback model to retry on:
8323 * what the API said of the refusal rides along.
8324 */
8325 type TurnCompleteRefused = {
8326 reason: 'refusal';
8327 refusal: TurnRefusal;
8328 };
8329
8330 /**
8331 * What a `turn.complete` hook returns and what `next(e)` resolves to:
8332 * `{ text }`; a text other than a main-loop answer's is shown beneath it.
8333 *
8334 * Core fills `usage` from `e.usage` when the turn had one; a hook above reads
8335 * it, and one that answers its own may leave it out.
8336 */
8337 export type TurnCompleteResult = {
8338 text: string;
8339 usage?: TurnUsage;
8340 };
8341
8342 /**
8343 * The end of a turn that was not a refusal: answered, interrupted, or dead
8344 * on an API error (retries exhausted, the context limit), nothing more.
8345 */
8346 type TurnCompleteUnrefused = {
8347 reason: Exclude<TurnCompleteReason, 'refusal'>;
8348 };
8349
8350 /**
8351 * What the API said about a refusal that ended a turn: the classifier's
8352 * category and its explanation, each null when the API sent none.
8353 */
8354 export type TurnRefusal = {
8355 category: string | null;
8356 explanation: string | null;
8357 };
8358
8359 /**
8360 * The input of `turn.start`: the prompt a model turn begins with, after
8361 * `prompt.submit` settled the text and the UserPromptSubmit settings hooks ran.
8362 */
8363 export type TurnStartInput = {
8364 /**
8365 * The user's text as the turn proceeds with it ("" for a turn started without
8366 * a typed prompt, e.g. a continuation).
8367 */
8368 text: string;
8369 /**
8370 * The turn's id, minted here; the same one every `turn.step` and the
8371 * `turn.complete` of this turn carry.
8372 */
8373 turnId: string;
8374 };
8375
8376 /**
8377 * What a `turn.start` hook returns and what `next(e)` resolves to:
8378 * `{ turnId }`, echoed by core; a hook's own value does not change the turn.
8379 */
8380 export type TurnStartResult = {
8381 turnId: string;
8382 };
8383
8384 /**
8385 * One piece of a `turn.step` response as it streams through the chain:
8386 * what a hook's `next(e)` yields and what the hook yields up in turn.
8387 *
8388 * Text, thinking, a tool call's start and arguments, and the stop are
8389 * plain data a hook reads and rewrites; `engine` is the rest, passed on
8390 * unread. What leaves the outermost hook is what is shown and recorded.
8391 */
8392 export type TurnStepChunk = TurnStepTextChunk | TurnStepThinkingChunk | TurnStepToolChunk | TurnStepInputChunk | TurnStepStopChunk | TurnStepEngineChunk;
8393
8394 /**
8395 * An item of the engine's stream the other chunk kinds do not model (the
8396 * envelope, a block's start and end, a retry marker), opaque by `ref`.
8397 *
8398 * Pass it on where it came. A hook that yields its own response has none
8399 * to yield, and the engine supplies what the response needs around the
8400 * chunks it does yield.
8401 */
8402 export type TurnStepEngineChunk = {
8403 kind: 'engine';
8404 /**
8405 * The engine's handle on the item; opaque, this step's only.
8406 */
8407 ref: number;
8408 };
8409
8410 /**
8411 * The input of `turn.step`: one model request inside a turn, at the moment
8412 * the engine is about to send it; the bottom of the chain sends it.
8413 *
8414 * The transcript is not on it: `messageCount` says how many messages the
8415 * request carries, and `$.session.messages()` reads them. A hook rewrites
8416 * `model` or `effort` going down; the rest is pinned.
8417 */
8418 export type TurnStepInput = {
8419 /**
8420 * The turn this step belongs to (`turn.start`'s id; inside a subagent's
8421 * loop, the id the run's `turn.complete` will carry). Pinned.
8422 */
8423 turnId: string;
8424 /**
8425 * The step's position in the turn, from 0. Pinned.
8426 */
8427 index: number;
8428 /**
8429 * Which model the request names, as the engine resolved it for this step
8430 * (the session's, a fallback's). `next({ ...e, model })` names another.
8431 */
8432 model: string;
8433 /**
8434 * How hard the request asks the model to think: the session's setting or
8435 * the model's default, absent for a model without effort; rewritable.
8436 */
8437 effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number;
8438 /**
8439 * How many messages the request carries (the conversation so far, the
8440 * turn's tool results included). Pinned: the messages are the engine's.
8441 */
8442 messageCount: number;
8443 /**
8444 * The loop the request is made in: a subagent's id, the `id`
8445 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
8446 *
8447 * Pinned: a different value is refused, one left out is kept. A subagent
8448 * a hook spawned through `$.agent.spawn` steps past that hook, as its tool
8449 * calls do; every other hook sees its steps.
8450 */
8451 agentId?: string;
8452 };
8453
8454 /**
8455 * A piece of a tool call's arguments as they arrive: JSON text, partial,
8456 * for the `tool` chunk of the same `index`.
8457 *
8458 * The arguments the tool runs with are the pieces concatenated and parsed
8459 * once the block ends; pieces that do not parse leave the call without
8460 * arguments it can run on, as a model that wrote broken JSON would.
8461 */
8462 export type TurnStepInputChunk = ChunkRef & {
8463 kind: 'input';
8464 index: number;
8465 /**
8466 * The next piece of the arguments' JSON text.
8467 */
8468 json: string;
8469 };
8470
8471 /**
8472 * What a `turn.step` hook returns and what `next(e)` resolves to: the
8473 * model's response to the step's request, once its blocks are all in.
8474 *
8475 * From the bottom, the response the engine streamed; a hook's own value
8476 * changes what the hooks above it read, never what the engine streamed.
8477 */
8478 export type TurnStepResult = {
8479 /**
8480 * The turn this step belongs to, as received.
8481 */
8482 turnId: string;
8483 /**
8484 * The step's position in the turn, as received.
8485 */
8486 index: number;
8487 /**
8488 * The visible text of the response ("" when it only called tools, only
8489 * thought, or no request was made).
8490 */
8491 answer: string;
8492 /**
8493 * The tool calls the response made, in order; empty for a text-only step.
8494 */
8495 toolUses: readonly TurnStepToolUse[];
8496 /**
8497 * Why the model stopped; null when no response arrived (the request
8498 * failed or was interrupted before a message, or no request was made).
8499 */
8500 stopReason: TurnStopReason;
8501 /**
8502 * What the request cost as the API reported it, and the model that
8503 * answered; null when no response arrived or it carried no usage.
8504 */
8505 usage: TurnUsage | null;
8506 };
8507
8508 /**
8509 * The response is whole: why the model stopped and what the request cost,
8510 * as the step's result will carry them. The last chunk of one response.
8511 */
8512 export type TurnStepStopChunk = ChunkRef & {
8513 kind: 'stop';
8514 stopReason: TurnStopReason;
8515 usage: TurnUsage | null;
8516 };
8517
8518 /**
8519 * A piece of the response's visible text as it arrives, in block `index`.
8520 *
8521 * The text the person watches stream and the text the transcript records
8522 * are both the concatenation of these, in order, per block: a hook that
8523 * rewrites them rewrites both, one that drops them all drops the block.
8524 */
8525 export type TurnStepTextChunk = ChunkRef & {
8526 kind: 'text';
8527 /**
8528 * The content block the piece belongs to, from 0 within one response.
8529 */
8530 index: number;
8531 text: string;
8532 };
8533
8534 /**
8535 * A piece of the model's thinking as it arrives, in block `index`: what
8536 * the person sees of it live.
8537 *
8538 * The thinking block the transcript keeps is the one the model signed, as
8539 * the engine received it; thinking a hook streams without the engine's
8540 * block behind it is shown and not recorded.
8541 */
8542 export type TurnStepThinkingChunk = ChunkRef & {
8543 kind: 'thinking';
8544 index: number;
8545 text: string;
8546 };
8547
8548 /**
8549 * The model begins a tool call in block `index`: the tool's name and the
8550 * call's id; its arguments follow as `input` chunks of the same index.
8551 *
8552 * A block whose `tool` chunk never comes out of the chain is no tool call:
8553 * the engine records none and runs none.
8554 */
8555 export type TurnStepToolChunk = ChunkRef & {
8556 kind: 'tool';
8557 index: number;
8558 /**
8559 * The call's `tool_use_id`.
8560 */
8561 id: string;
8562 /**
8563 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
8564 */
8565 name: string;
8566 };
8567
8568 /**
8569 * One tool call the model asked for in a step: the tool's name and its
8570 * arguments.
8571 */
8572 export type TurnStepToolUse = {
8573 /**
8574 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
8575 */
8576 name: string;
8577 /**
8578 * The arguments the model gave it, as the tool schema shapes them.
8579 */
8580 input: unknown;
8581 };
8582
8583 /**
8584 * Why the model stopped, as a `turn.step` result and its stop chunk carry
8585 * it: one of the API's stop reasons, or null when no response arrived.
8586 */
8587 type TurnStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'compaction' | 'refusal' | 'model_context_window_exceeded' | null;
8588
8589 /**
8590 * What a model turn, or one response inside it, cost as the API reported it:
8591 * the four token counts (`$.model.fork`'s usage shape) and the model's id.
8592 *
8593 * A turn's counts are its responses' summed; its model is the last response's.
8594 */
8595 export type TurnUsage = ModelForkUsage & {
8596 /**
8597 * Which model answered, by the id the API reports.
8598 */
8599 model: string;
8600 };
8601
8602 /**
8603 * What a plugin's `$.ui.blit(args)` takes: which of its mounted Rasters to
8604 * repaint, in which of its sites, and the cells to paint it with.
8605 *
8606 * The Raster is one this plugin's own `ui.render` hook drew, still mounted;
8607 * `columns` and `rows`, when given, must be the mounted size (a resize is a
8608 * redraw, `$.ui.invalidate("ui.render")`, not a blit).
8609 */
8610 export type UiBlitArgs = {
8611 /**
8612 * The site the Raster is drawn in, by the `requestId` this plugin draws
8613 * it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
8614 */
8615 requestId: string;
8616 /**
8617 * The Raster's `key` in that drawing.
8618 */
8619 key: string;
8620 /**
8621 * The new cells, encoded as the element's `cells` are (RasterProps), for
8622 * the mounted `columns * rows`.
8623 */
8624 cells: string;
8625 /**
8626 * The width the cells are laid out for; refused unless it is the mounted
8627 * Raster's. Absent, the mounted width.
8628 */
8629 columns?: number;
8630 /**
8631 * The height the cells are laid out for; refused unless it is the mounted
8632 * Raster's. Absent, the mounted height.
8633 */
8634 rows?: number;
8635 };
8636
8637 /**
8638 * What `$.ui.blit` resolves to and what a `ui.blit` hook's `{ value }`
8639 * holds: `{}` once the cells are the Raster's next frame, or why not.
8640 */
8641 export type UiBlitResult = {
8642 /**
8643 * Absent when the cells were taken; else why not: nothing of this plugin's
8644 * is mounted there, the size is not the mounted one, the cells are bad.
8645 *
8646 * Another plugin's Raster under the same site and key reads as not this
8647 * plugin's; a cell that does not decode is named by its index.
8648 */
8649 deny?: string;
8650 };
8651
8652 /**
8653 * The argument of `ui.input`: a change of, or a submit from, an `Input` a
8654 * render hook drew. Flat and frozen like every event's.
8655 *
8656 * Another plugin addresses one field by matcher:
8657 * `on("ui.input", { plugin: "roster", element: "reply" }, ...)`.
8658 */
8659 export type UiInputArgument = {
8660 /**
8661 * Whose `ui.render` hook drew the element.
8662 */
8663 plugin: string;
8664 /**
8665 * The `key` the hook gave its `Input`: its address, what a matcher names.
8666 */
8667 element: string;
8668 /**
8669 * The render component the element was drawn in (`AbovePrompt`,
8670 * `ToolUse`, ...).
8671 */
8672 component: RenderComponent;
8673 /**
8674 * The instance the element was drawn in: the `requestId` the `ui.render`
8675 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
8676 */
8677 requestId: string;
8678 /**
8679 * Where the typing came from, one literal per member, so
8680 * `if (e.surface === "terminal")` narrows `e`.
8681 */
8682 surface: RenderSurface;
8683 /**
8684 * `change` after every edit of the text; `submit` on Enter.
8685 */
8686 kind: 'change' | 'submit';
8687 /**
8688 * The field's whole text at that moment; a hook above may rewrite it for
8689 * the plugins beneath and the element's own handler.
8690 */
8691 value: string;
8692 };
8693
8694 /**
8695 * What a `ui.input` hook returns and what `next(e)` resolves to.
8696 *
8697 * Beneath every hook, core runs the element's `onInput` (kind `change`) or
8698 * `onSubmit` (kind `submit`) closure in its plugin's environment with the
8699 * value as the chain left it, and answers `{ element, value }`.
8700 */
8701 export type UiInputResult = {
8702 /**
8703 * Which handler the input reached, by its Input's `key`.
8704 */
8705 element: string;
8706 /**
8707 * The text the handler received.
8708 */
8709 value: string;
8710 };
8711
8712 /**
8713 * The argument of `ui.message`: what a `Client` instance's surface module
8714 * posted (`surface.post(data)`), addressed by where the instance is drawn.
8715 *
8716 * The origin is `client`: code sent it, on nobody's behalf, so `data` is
8717 * input to validate, not a fact. Everything but `data` is the engine's word
8718 * and a hook may not rewrite it.
8719 */
8720 export type UiMessageArgument = {
8721 /**
8722 * Where the instance is drawn: `terminal`, or `desktop` once it has them.
8723 */
8724 surface: RenderSurface;
8725 /**
8726 * The render component the `Client` was drawn in (`AbovePrompt`, `Pane`,
8727 * ...).
8728 */
8729 component: RenderComponent;
8730 /**
8731 * The engine's id for the drawing the `Client` sits in: the `requestId` the
8732 * `ui.render` hook that drew it saw.
8733 */
8734 requestId: string;
8735 /**
8736 * The `Client`'s `key`: which instance posted.
8737 */
8738 element: string;
8739 /**
8740 * The `Client`'s `module`: which surface module runs there, as its path
8741 * under the plugin's folder.
8742 */
8743 module: string;
8744 /**
8745 * What the instance posted: plain data (JsonValue), bounded as a tree's
8746 * text is; typed `unknown` since it came from code. Rewritable.
8747 */
8748 data: unknown;
8749 };
8750
8751 /**
8752 * What a `ui.message` hook returns and what `next(e)` resolves to.
8753 *
8754 * Core answers `{}`: the message was heard and nothing changes. A hook that
8755 * answers `{ props }` hands the posting instance its next props directly, its
8756 * local state kept, with no `ui.render` run; the plugin's next redraw hands
8757 * props again as usual.
8758 */
8759 export type UiMessageResult = {
8760 /**
8761 * The instance's next props, plain data (JsonValue) bounded as a `Client`'s
8762 * props are; absent leaves the instance's props as they were.
8763 */
8764 props?: unknown;
8765 };
8766
8767 /**
8768 * The argument of `ui.press`: a press on a `Button` a render hook drew.
8769 * Flat and frozen like every event's.
8770 *
8771 * Another plugin addresses one button by matcher:
8772 * `on("ui.press", { plugin: "explainer", element: "explain" }, ...)`.
8773 */
8774 export type UiPressArgument = {
8775 /**
8776 * Whose `ui.render` hook drew the element.
8777 */
8778 plugin: string;
8779 /**
8780 * The `key` the hook gave its `Button`: its address, what a matcher names.
8781 */
8782 element: string;
8783 /**
8784 * The render component the element was drawn in (`ToolUse`,
8785 * `AssistantMessage`, ...).
8786 */
8787 component: RenderComponent;
8788 /**
8789 * The instance the element was drawn in: the `requestId` the `ui.render`
8790 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
8791 */
8792 requestId: string;
8793 /**
8794 * Where the press came from, one literal per member, so
8795 * `if (e.surface === "terminal")` narrows `e`.
8796 */
8797 surface: RenderSurface;
8798 };
8799
8800 /**
8801 * What a `ui.press` hook returns and what `next(e)` resolves to.
8802 *
8803 * Beneath every hook, core runs the element's `onPress` closure in its
8804 * plugin's environment with `e` as the chain left it, and answers
8805 * `{ element }`.
8806 */
8807 export type UiPressResult = {
8808 /**
8809 * Which handler the press reached, by its Button's `key`.
8810 */
8811 element: string;
8812 };
8813
8814 /**
8815 * What a plugin's `$.ui.scroll(args)` takes: what to bring into view, in
8816 * which of its sites, and where in the window it lands.
8817 *
8818 * The engine resolves it to a window and an offset and raises `ui.scroll`
8819 * under the plugin's origin; a transcript row is the person's to move, so
8820 * it is revealed only while the plugin answers the person's own input.
8821 */
8822 export type UiScrollArgs = {
8823 /**
8824 * What to reveal (UiScrollTarget): a render instance by `requestId`, one
8825 * of this plugin's elements by `key`, or the `start` or `end` of `in`.
8826 */
8827 to: UiScrollTarget;
8828 /**
8829 * The site to scroll, by the `requestId` this plugin draws it under: one
8830 * of its panes' ids, or the band's.
8831 *
8832 * Required with `start` and `end`; with `{ key }` it picks the site when
8833 * the key is drawn in several.
8834 */
8835 in?: string;
8836 /**
8837 * Where the target lands in the window (UiScrollBlock); `nearest` when
8838 * left out, so a row already showing does not move.
8839 */
8840 block?: UiScrollBlock;
8841 };
8842
8843 /**
8844 * Where in its scrollable a revealed row lands, as the DOM's
8845 * `scrollIntoView({ block })` names it.
8846 *
8847 * `nearest` moves the least that shows the row whole, and not at all when
8848 * it already shows; `start`, `center` and `end` put its top, middle or
8849 * bottom at that edge of the window. A row taller than the window shows
8850 * its top.
8851 */
8852 export type UiScrollBlock = 'start' | 'center' | 'end' | 'nearest';
8853
8854 /**
8855 * The render components whose site the engine scrolls: a pane's body and
8856 * the band above the prompt, each a window over the tree a hook drew there.
8857 */
8858 export type UiScrollComponent = 'Pane' | 'AbovePrompt';
8859
8860 /**
8861 * The input of `ui.scroll`: a site's window asked to move over the tree a
8862 * hook drew in it (a pane's body, the band above the prompt).
8863 *
8864 * Every key but `offset` is the engine's word, pinned: `next(e)` passes
8865 * them on, a rewrite that leaves one out keeps it, one that changes or adds
8866 * one fails the hook. `offset` is the hook's to rewrite; nothing moved yet.
8867 */
8868 export type UiScrollInput = {
8869 /**
8870 * Which site: a `Pane` body or the `AbovePrompt` band.
8871 */
8872 component: UiScrollComponent;
8873 /**
8874 * The instance the `ui.render` hook drawing the site sees: the pane's id,
8875 * or the band's one id.
8876 */
8877 requestId: string;
8878 /**
8879 * The first row the window is to show, 0 at the top: the row it shows
8880 * now plus `by`, clamped to the tree, or where `$.ui.scroll` resolved.
8881 *
8882 * `next({ ...e, offset })` moves it elsewhere (a clamp); one past the
8883 * tree's end lands at the end. Nothing has moved when a hook reads it.
8884 */
8885 offset: number;
8886 /**
8887 * The rows the move asks for, signed, negative toward the top; what the
8888 * DOM's `scrollBy` takes. Read-only.
8889 *
8890 * The person's: a wheel tick `-1` or `1` at rest, more as ticks crowd or
8891 * summed in flight; an arrow a row while the engine has rows to scroll, a
8892 * page key `bodyRows`, Home and End `contentRows`. A plugin's: its distance.
8893 */
8894 by: number;
8895 /**
8896 * How many rows of the tree the window shows at once, as drawn now.
8897 * Read-only.
8898 */
8899 bodyRows: number;
8900 /**
8901 * How many rows the tree has, as drawn now: the window's last offset is
8902 * `contentRows - bodyRows`, none when the tree fits. Read-only.
8903 */
8904 contentRows: number;
8905 /**
8906 * Who moves it (UiScrollOrigin), set by the engine where the move starts.
8907 */
8908 origin: UiScrollOrigin;
8909 /**
8910 * The body cell the person's wheel or trackpad was over (UiScrollPointer);
8911 * absent for the scroll keys and for `$.ui.scroll`. Read-only.
8912 *
8913 * Moves summed while a dispatch was in flight carry the latest one's. A
8914 * hook pinning a list over rows it scrolls itself tells a tick over the
8915 * list (`row` among its list's rows) from one over the body.
8916 */
8917 pointer?: UiScrollPointer;
8918 };
8919
8920 /**
8921 * Who moves the window at `ui.scroll`, as the engine stamps it where the
8922 * move starts; a closed set a matcher narrows on.
8923 *
8924 * `next(e)` passes it on as received; no hook sets one.
8925 */
8926 export type UiScrollOrigin = {
8927 /**
8928 * The person, by the wheel over the site or its scroll keys while
8929 * they hold it.
8930 */
8931 kind: 'person';
8932 } | {
8933 /**
8934 * A plugin's `$.ui.scroll`.
8935 */
8936 kind: 'plugin';
8937 /**
8938 * The scrolling plugin's name.
8939 */
8940 name: string;
8941 };
8942
8943 /**
8944 * The cell the pointer was over when the person's wheel raised `ui.scroll`,
8945 * in the site's body: the box its `ui.render` hook draws into, as painted.
8946 *
8947 * The DOM's `clientY - body.top` in cells, the window's offset not added: a
8948 * hook drawing its own window reads `row` as its tree's row, one the engine
8949 * scrolls adds the `scroll.offset` it drew with. The frame lies outside.
8950 */
8951 export type UiScrollPointer = {
8952 /**
8953 * 0 at the body's left edge, as `bodyColumns` counts them; negative, or
8954 * `bodyColumns` and past, over an inline pane's side borders.
8955 */
8956 column: number;
8957 /**
8958 * 0 at the body's first showing row, as `bodyRows` counts them.
8959 *
8960 * The tree's row is `scroll.offset + row` under the engine's window, and
8961 * `row` itself under a hook's own (offset 0); negative over a pane's top
8962 * border or tab row, `bodyRows` or more over its bottom border.
8963 */
8964 row: number;
8965 };
8966
8967 /**
8968 * What a `ui.scroll` hook returns, what `next(e)` resolves to, and what
8969 * `$.ui.scroll` hands back: `{}` once the window moved, or why it did not.
8970 */
8971 export type UiScrollResult = {
8972 /**
8973 * Absent when the window is where the chain left it; else why nothing
8974 * moved, as `tool.call` and `config.set` spell a refusal.
8975 *
8976 * A hook kept the window (no `next`); the target is not this plugin's;
8977 * another move landed first (`the window moved meanwhile`); a transcript
8978 * row is not the person's ask (`not person-initiated`) or none scrolls.
8979 */
8980 deny?: string;
8981 };
8982
8983 /**
8984 * What `$.ui.scroll` brings into view: never a row number, always a thing
8985 * drawn somewhere.
8986 *
8987 * `{ requestId }` names a render instance by the id its `ui.render` hook
8988 * saw (a transcript message's, a tool row's tool_use_id), scrolled into view
8989 * inside whatever scrolls it. `{ key }` names an element this plugin drew
8990 * with that `key`, inside the site it drew it in. `start` and `end` are the
8991 * top and bottom of the site `in` names; `end` keeps up with a tree that
8992 * grows (rows the plugin just added count) until anything next moves it.
8993 */
8994 export type UiScrollTarget = {
8995 requestId: string;
8996 } | {
8997 key: string;
8998 } | 'start' | 'end';
8999
9000 /**
9001 * The argument of `ui.select`: a pick from a `Select` a render hook drew.
9002 * Flat and frozen like every event's.
9003 *
9004 * Another plugin addresses one picker by matcher:
9005 * `on("ui.select", { plugin: "roster", element: "peer" }, ...)`.
9006 */
9007 export type UiSelectArgument = {
9008 /**
9009 * Whose `ui.render` hook drew the element.
9010 */
9011 plugin: string;
9012 /**
9013 * The `key` the hook gave its `Select`: its address, what a matcher names.
9014 */
9015 element: string;
9016 /**
9017 * The render component the element was drawn in (`AbovePrompt`,
9018 * `ToolUse`, ...).
9019 */
9020 component: RenderComponent;
9021 /**
9022 * The instance the element was drawn in: the `requestId` the `ui.render`
9023 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
9024 */
9025 requestId: string;
9026 /**
9027 * Where the pick came from, one literal per member, so
9028 * `if (e.surface === "terminal")` narrows `e`.
9029 */
9030 surface: RenderSurface;
9031 /**
9032 * The picked option's value; a hook above may rewrite it for the plugins
9033 * beneath and the element's own handler.
9034 */
9035 value: string;
9036 };
9037
9038 /**
9039 * What a `ui.select` hook returns and what `next(e)` resolves to.
9040 *
9041 * Beneath every hook, core runs the element's `onSelect` closure in its
9042 * plugin's environment with the value as the chain left it, and answers
9043 * `{ element, value }`.
9044 */
9045 export type UiSelectResult = {
9046 /**
9047 * Which handler the pick reached, by its Select's `key`.
9048 */
9049 element: string;
9050 /**
9051 * What the handler received: the option's value as the chain left it.
9052 */
9053 value: string;
9054 };
9055
9056 /**
9057 * The intersection of a union's members (`A | B` to `A & B`), by inferring
9058 * one parameter type from the contravariant positions.
9059 */
9060 type UnionToIntersection<U> = (U extends unknown ? (member: U) => void : never) extends (member: infer I) => void ? I : never;
9061
9062 type UserPromptExpansionHookInput = BaseHookInput & {
9063 hook_event_name: 'UserPromptExpansion';
9064 expansion_type: 'slash_command' | 'mcp_prompt';
9065 command_name: string;
9066 command_args: string;
9067 command_source?: string;
9068 prompt: string;
9069 };
9070
9071 type UserPromptSubmitHookInput = BaseHookInput & {
9072 hook_event_name: 'UserPromptSubmit';
9073 prompt: string;
9074 /**
9075 * 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.
9076 */
9077 source?: 'user' | 'sdk' | 'system' | 'loop_wakeup' | 'schedule_wakeup' | 'poll_event';
9078 session_title?: string;
9079 };
9080
9081 /**
9082 * The result of a call on `$` as the hooks on its event see it: `{ value }`,
9083 * the call's answer, or `{ deny }`, the reason the caller's promise rejects.
9084 */
9085 type ValueOrDeny<Value> = {
9086 value: Value;
9087 deny?: undefined;
9088 } | {
9089 deny: string;
9090 value?: undefined;
9091 };
9092
9093 type WorktreeCreateHookInput = BaseHookInput & {
9094 hook_event_name: 'WorktreeCreate';
9095 name: string;
9096 };
9097
9098 type WorktreeRemoveHookInput = BaseHookInput & {
9099 hook_event_name: 'WorktreeRemove';
9100 worktree_path: string;
9101 };
9102
9103 /**
9104 * The globals of a hooks module's environment: these and no others (no DOM,
9105 * no Node).
9106 */
9107 global {
9108 /**
9109 * The JSX factory (classic runtime, `@jsx h`; the engine prepends the
9110 * pragma): a plain-data element from a string tag or a component.
9111 */
9112 const h: (
9113 tag: string | ((props: never) => RenderNode | null | undefined),
9114 props: Record<string, unknown> | null | undefined,
9115 ...children: unknown[]
9116 ) => RenderNode | null | undefined
9117
9118 /**
9119 * `<>...</>`: a column Box around the children.
9120 */
9121 const Fragment: (props: { children?: RenderNode[] }) => RenderElement
9122
9123 /**
9124 * JSX over the element table: every tag is a constructor from
9125 * `$.ui.resolve(e)` (`const { Box, Text } = $.ui.resolve(e)`), typed by
9126 * its props; there are no intrinsic (string) tags.
9127 */
9128 namespace JSX {
9129 type Element = RenderElement
9130 type Children = RenderChildren
9131 type ElementType = (props: never) => RenderNode | null | undefined
9132 interface IntrinsicElements {}
9133 interface ElementChildrenAttribute {
9134 children: unknown
9135 }
9136 interface IntrinsicAttributes {
9137 key?: string
9138 }
9139 }
9140
9141 interface AbortSignal {
9142 readonly aborted: boolean
9143 readonly reason: unknown
9144 throwIfAborted(): void
9145 addEventListener(
9146 type: 'abort',
9147 listener: () => void,
9148 options?: { once?: boolean },
9149 ): void
9150 removeEventListener(type: 'abort', listener: () => void): void
9151 }
9152 var AbortSignal: {
9153 prototype: AbortSignal
9154 abort(reason?: unknown): AbortSignal
9155 timeout(milliseconds: number): AbortSignal
9156 any(signals: AbortSignal[]): AbortSignal
9157 }
9158 interface AbortController {
9159 readonly signal: AbortSignal
9160 abort(reason?: unknown): void
9161 }
9162 var AbortController: {
9163 prototype: AbortController
9164 new (): AbortController
9165 }
9166 interface TextEncoder {
9167 readonly encoding: string
9168 encode(input?: string): Uint8Array
9169 }
9170 var TextEncoder: { prototype: TextEncoder; new (): TextEncoder }
9171 interface TextDecoder {
9172 readonly encoding: string
9173 decode(input?: ArrayBufferView | ArrayBuffer): string
9174 }
9175 var TextDecoder: { prototype: TextDecoder; new (label?: string): TextDecoder }
9176 interface URLSearchParams {
9177 append(name: string, value: string): void
9178 delete(name: string): void
9179 get(name: string): string | null
9180 getAll(name: string): string[]
9181 has(name: string): boolean
9182 set(name: string, value: string): void
9183 toString(): string
9184 forEach(callback: (value: string, key: string) => void): void
9185 }
9186 var URLSearchParams: {
9187 prototype: URLSearchParams
9188 new (init?: string | Record<string, string> | string[][]): URLSearchParams
9189 }
9190 interface URL {
9191 hash: string
9192 host: string
9193 hostname: string
9194 href: string
9195 readonly origin: string
9196 password: string
9197 pathname: string
9198 port: string
9199 protocol: string
9200 search: string
9201 readonly searchParams: URLSearchParams
9202 username: string
9203 toString(): string
9204 toJSON(): string
9205 }
9206 var URL: {
9207 prototype: URL
9208 new (url: string, base?: string | URL): URL
9209 canParse(url: string, base?: string): boolean
9210 }
9211 function atob(data: string): string
9212 function btoa(data: string): string
9213 function structuredClone<T>(value: T): T
9214 var crypto: {
9215 readonly subtle: {
9216 digest(
9217 algorithm: string | { name: string },
9218 data: ArrayBufferView | ArrayBuffer,
9219 ): Promise<ArrayBuffer>
9220 }
9221 randomUUID(): string
9222 getRandomValues<T extends ArrayBufferView>(array: T): T
9223 }
9224 var performance: { now(): number }
9225 }
9226}
9227
9228declare module 'claude-code/testing' {
9229 import type { Args } from 'claude-code';
9230 import type { Chunk } from 'claude-code';
9231 import type { EventCalls } from 'claude-code';
9232 import type { EventName } from 'claude-code';
9233 import type { HookStream } from 'claude-code';
9234 import type { On } from 'claude-code';
9235 import type { Register } from 'claude-code';
9236 import type { ResultOf } from 'claude-code';
9237 import type { StreamingEventName } from 'claude-code';
9238 import type { Tier } from 'claude-code';
9239 import type { UiPressResult } from 'claude-code';
9240
9241 /**
9242 * A value that matches by a rule inside `toEqual` and its kin
9243 * (`expect.any`, `expect.objectContaining`), known by its text in a failure.
9244 */
9245 export type AsymmetricMatcher = {
9246 readonly text: string;
9247 };
9248
9249 /**
9250 * The same checks on what a promise received settles with, each resolving
9251 * once the promise has settled and the check passed.
9252 */
9253 export type AsyncMatchers = {
9254 [K in keyof Matchers]: (...args: Parameters<Matchers[K]>) => Promise<void>;
9255 };
9256
9257 /**
9258 * A class, as `toThrow`, `toBeInstanceOf` and `expect.any` take it.
9259 */
9260 export type Constructor = abstract new (...args: never[]) => unknown;
9261
9262 /**
9263 * A group of tests: its name leads the title of each test declared inside,
9264 * and its body runs at once, while the file loads.
9265 *
9266 * @param name the group's name
9267 * @param body declares the group's tests
9268 */
9269 export const describe: (name: string, body: () => void) => void;
9270
9271 /**
9272 * What a test holds as `$`, the engine's own: every call on it is made as
9273 * the REPL, the query loop and the render sites make theirs, over every plugin.
9274 *
9275 * `next.origin` is the engine, and the whole chain runs over the plugins
9276 * loaded. A tool call's `tool_use_id` is minted when left out, as the engine
9277 * mints it; `$.ui.press` is the terminal pressing a Button a test rendered.
9278 */
9279 export type Engine = {
9280 [N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress : EngineNoun<N>;
9281 };
9282
9283 /**
9284 * One call on the engine's `$`: the event's input whole, as an engine call
9285 * site passes it, to its result, or for a streaming event to its stream.
9286 */
9287 export type EngineCall<E extends EventName> = E extends StreamingEventName ? (e: Args<E>) => HookStream<Chunk<E>, ResultOf[E]> : (e: Args<E>) => Promise<ResultOf[E]>;
9288
9289 /**
9290 * One noun of the engine's `$`: each of its events as the engine calls it,
9291 * `tool.call` and `ui.render` typed per tool and component, `ui.resolve` out.
9292 */
9293 export type EngineNoun<N extends keyof EventCalls> = {
9294 [V in EngineNounEvent<N>]: `${N}.${V}` extends 'tool.call' | 'ui.render' ? EventCalls[N][V] : EngineCall<`${N}.${V}` & EventName>;
9295 };
9296
9297 /**
9298 * The events of one noun a test's `$` carries: every one but `ui.resolve`,
9299 * which a render hook calls on its own `$` and the engine never raises.
9300 */
9301 export type EngineNounEvent<N extends keyof EventCalls> = Exclude<keyof EventCalls[N] & string, `${N}.resolve` extends 'ui.resolve' ? 'resolve' : never>;
9302
9303 /**
9304 * The terminal pressing a Button a test rendered: the `ui.press` chain over
9305 * every plugin hooked on it, the Button's own `onPress` at the bottom.
9306 */
9307 export type EnginePress = {
9308 /**
9309 * Presses the Button, as a click or its hotkey does.
9310 *
9311 * @param target whose Button, its key, and the instance when several
9312 * @returns what the chain settled on; rejects when no such Button is
9313 * drawn on the terminal, or several are and no instance is named
9314 */
9315 press: (target: PressTarget) => Promise<UiPressResult | undefined>;
9316 };
9317
9318 /**
9319 * The checks on a value (`expect(received)`), and with them the matchers
9320 * that stand inside an expected value (`expect.any(Number)`).
9321 */
9322 export type Expect = Expecting & Matching;
9323
9324 /**
9325 * Checks a value: `expect(received).toEqual(expected)` throws an
9326 * AssertionError naming both sides when it fails, a message given leading.
9327 *
9328 * `.not` negates; `.resolves` and `.rejects` check what a promise settles
9329 * with; `expect.any(Number)` and its kin stand inside an expected value.
9330 */
9331 export const expect: Expect;
9332
9333 /**
9334 * What `expect(received)` answers: the checks, their negation, and the
9335 * checks on what a promise received resolves or rejects with.
9336 */
9337 export type Expectation = Negatable<Matchers> & {
9338 /**
9339 * The checks on what the promise received resolves with; a rejection
9340 * fails them.
9341 */
9342 resolves: Negatable<AsyncMatchers>;
9343 /**
9344 * The checks on what the promise received rejects with; a resolution
9345 * fails them.
9346 */
9347 rejects: Negatable<AsyncMatchers>;
9348 };
9349
9350 /**
9351 * `expect(received, message?)`: the checks on a value, a message of the
9352 * test's own leading a failure's.
9353 */
9354 export type Expecting = (received: unknown, message?: string) => Expectation;
9355
9356 /**
9357 * The checks `expect(received)` offers; each throws an AssertionError when
9358 * it fails, naming what was expected and what was received.
9359 */
9360 export type Matchers = {
9361 /**
9362 * Passes when received is the value, by `Object.is`.
9363 *
9364 * @param expected the value
9365 */
9366 toBe: (expected: unknown) => void;
9367 /**
9368 * Passes when received equals the value in structure, properties holding
9369 * undefined ignored; `expect.any` and its kin match inside it.
9370 *
9371 * @param expected the value
9372 */
9373 toEqual: (expected: unknown) => void;
9374 /**
9375 * As `toEqual`, but undefined properties and prototypes count.
9376 *
9377 * @param expected the value
9378 */
9379 toStrictEqual: (expected: unknown) => void;
9380 /**
9381 * Passes when received holds at least the object's properties, equal.
9382 *
9383 * @param expected the object
9384 */
9385 toMatchObject: (expected: object) => void;
9386 /**
9387 * Passes when a string received includes the item, or an iterable
9388 * received has an element that is it.
9389 *
9390 * @param item the substring or element
9391 */
9392 toContain: (item: unknown) => void;
9393 /**
9394 * Passes when an iterable received has an element equal to the item.
9395 *
9396 * @param item the element
9397 */
9398 toContainEqual: (item: unknown) => void;
9399 /**
9400 * Passes when received's `length` is the number.
9401 *
9402 * @param length the number
9403 */
9404 toHaveLength: (length: number) => void;
9405 /**
9406 * Passes when received holds a property at the path (`a.b`, or the keys
9407 * in order), equal to the value when one is given.
9408 *
9409 * @param path the property's path
9410 * @param value what it must equal, when given
9411 */
9412 toHaveProperty: (path: string | readonly string[], value?: unknown) => void;
9413 /**
9414 * Passes when received is undefined.
9415 */
9416 toBeUndefined: () => void;
9417 /**
9418 * Passes when received is anything but undefined.
9419 */
9420 toBeDefined: () => void;
9421 /**
9422 * Passes when received is null.
9423 */
9424 toBeNull: () => void;
9425 /**
9426 * Passes when received is truthy.
9427 */
9428 toBeTruthy: () => void;
9429 /**
9430 * Passes when received is falsy.
9431 */
9432 toBeFalsy: () => void;
9433 /**
9434 * Passes when received is NaN.
9435 */
9436 toBeNaN: () => void;
9437 /**
9438 * Passes when received is greater than the bound.
9439 *
9440 * @param bound the bound
9441 */
9442 toBeGreaterThan: (bound: number | bigint) => void;
9443 /**
9444 * Passes when received is the bound or greater.
9445 *
9446 * @param bound the bound
9447 */
9448 toBeGreaterThanOrEqual: (bound: number | bigint) => void;
9449 /**
9450 * Passes when received is less than the bound.
9451 *
9452 * @param bound the bound
9453 */
9454 toBeLessThan: (bound: number | bigint) => void;
9455 /**
9456 * Passes when received is the bound or less.
9457 *
9458 * @param bound the bound
9459 */
9460 toBeLessThanOrEqual: (bound: number | bigint) => void;
9461 /**
9462 * Passes when a string received includes the text, or the pattern matches
9463 * it.
9464 *
9465 * @param pattern the text or pattern
9466 */
9467 toMatch: (pattern: string | RegExp) => void;
9468 /**
9469 * Passes when a string received starts with the prefix.
9470 *
9471 * @param prefix the prefix
9472 */
9473 toStartWith: (prefix: string) => void;
9474 /**
9475 * Passes when a string received ends with the suffix.
9476 *
9477 * @param suffix the suffix
9478 */
9479 toEndWith: (suffix: string) => void;
9480 /**
9481 * Passes when received is an instance of the class.
9482 *
9483 * @param expected the class
9484 */
9485 toBeInstanceOf: (expected: Constructor) => void;
9486 /**
9487 * Passes when calling received throws (or, under `rejects`, the rejection
9488 * is) an error as described: by substring, pattern, class or message.
9489 *
9490 * @param expected the description; any throw passes without one
9491 */
9492 toThrow: (expected?: ThrowExpectation) => void;
9493 };
9494
9495 /**
9496 * The matchers that stand inside an expected value, each matching received
9497 * there by a rule instead of by equality.
9498 */
9499 export type Matching = {
9500 /**
9501 * Matches any instance of the class, a primitive by its wrapper
9502 * (`expect.any(Number)`).
9503 *
9504 * @param expected the class
9505 * @returns the matcher
9506 */
9507 any: (expected: Constructor) => AsymmetricMatcher;
9508 /**
9509 * Matches anything but null and undefined.
9510 *
9511 * @returns the matcher
9512 */
9513 anything: () => AsymmetricMatcher;
9514 /**
9515 * Matches a string that includes the text.
9516 *
9517 * @param text the substring
9518 * @returns the matcher
9519 */
9520 stringContaining: (text: string) => AsymmetricMatcher;
9521 /**
9522 * Matches a string the pattern matches.
9523 *
9524 * @param pattern the pattern, or the source of one
9525 * @returns the matcher
9526 */
9527 stringMatching: (pattern: string | RegExp) => AsymmetricMatcher;
9528 /**
9529 * Matches an object holding at least the shape's properties, equal.
9530 *
9531 * @param shape the properties
9532 * @returns the matcher
9533 */
9534 objectContaining: (shape: object) => AsymmetricMatcher;
9535 /**
9536 * Matches an array holding an element equal to each of the items.
9537 *
9538 * @param items the elements
9539 * @returns the matcher
9540 */
9541 arrayContaining: (items: readonly unknown[]) => AsymmetricMatcher;
9542 };
9543
9544 /**
9545 * The world beneath the plugins, mocked noun by noun: each member registers
9546 * hooks of the test's on `on`, visible where the test calls it.
9547 */
9548 export type Mock = {
9549 /**
9550 * Answers `$.clock` from a clock in memory that moves only when the test
9551 * moves it: `clock.now` reads it, and each wait is held.
9552 *
9553 * A held wait resolves when an advance crosses the time it is due, and is
9554 * dropped when its dispatch aborts; one held past a hook's budget (ten
9555 * seconds of real time) is let go, as a hook that overran.
9556 *
9557 * @param on the test's `on`
9558 * @param options where the clock starts (`now`, 0 when not given)
9559 * @returns the clock: its time, and the calls that move it
9560 */
9561 clock: (on: On, options?: MockClockOptions) => MockClock;
9562 /**
9563 * Answers `$.store` from a store in memory: `get`, `set`, `delete` and
9564 * `keys` over it, as the engine keeps a plugin's own.
9565 *
9566 * @param on the test's `on`
9567 * @param entries what the store holds at the start (nothing when not given)
9568 */
9569 store: (on: On, entries?: Readonly<Record<string, unknown>>) => void;
9570 /**
9571 * Answers `$.env.get` from a set of variables; one not listed is unset.
9572 *
9573 * @param on the test's `on`
9574 * @param variables the environment the plugins read
9575 */
9576 env: (on: On, variables: Readonly<Record<string, string>>) => void;
9577 };
9578
9579 /**
9580 * The world beneath the plugins, mocked noun by noun: `mock.clock`,
9581 * `mock.store` and `mock.env`.
9582 *
9583 * Each registers hooks of the test's on the `on` it is handed, visible where
9584 * the test calls it, and answers its noun from memory.
9585 */
9586 export const mock: Mock;
9587
9588 /**
9589 * The clock `mock.clock` hands back: the time its hooks answer, and the only
9590 * ways it moves.
9591 */
9592 export type MockClock = {
9593 /**
9594 * The time now, in milliseconds: what `$.clock.now()` resolves beneath the
9595 * plugins.
9596 *
9597 * @returns the time
9598 */
9599 now: () => number;
9600 /**
9601 * Moves the clock on, resolving each wait due on the way (`$.clock.sleep`,
9602 * `after`, `every`, this clock's `sleep`) in the order it comes due.
9603 *
9604 * The clock reads each wait's time as it resolves, and what one started
9605 * runs before the next resolves.
9606 *
9607 * @param ms how far to move, in milliseconds
9608 * @returns resolves once the clock is there and the event loop settled
9609 */
9610 advance: (ms: number) => Promise<void>;
9611 /**
9612 * Moves the clock to a time at or past now, as `advance` would.
9613 *
9614 * @param ms the time, in milliseconds
9615 * @returns resolves once the clock is there and the event loop settled
9616 */
9617 set: (ms: number) => Promise<void>;
9618 /**
9619 * Lets what is already under way run as far as it can without the clock
9620 * moving: every wait due now resolves and the event loop settles.
9621 *
9622 * The same as `advance(0)`; the name for the step between starting a
9623 * dispatch unawaited and looking at what it did.
9624 *
9625 * @returns resolves once the event loop settled, the time where it was
9626 */
9627 settle: () => Promise<void>;
9628 /**
9629 * Resolves once the clock has moved this far past now: how a hook of the
9630 * test's answers late.
9631 *
9632 * @param ms how far, in milliseconds
9633 * @returns resolves when an advance crosses that time
9634 */
9635 sleep: (ms: number) => Promise<void>;
9636 };
9637
9638 /**
9639 * Where a mocked clock starts: `now`, in milliseconds (0 when not given).
9640 */
9641 export type MockClockOptions = {
9642 now?: number;
9643 };
9644
9645 /**
9646 * A set of checks and, under `not`, the same set passing where they fail.
9647 */
9648 export type Negatable<M> = M & {
9649 /**
9650 * The checks negated.
9651 */
9652 not: M;
9653 };
9654
9655 /**
9656 * Written inline in a test and loaded as a plugin folder is: its name, the
9657 * tier it loads in (`user` when not given), and its hooks module's `register`.
9658 *
9659 * `register` is written `register(on) { ... }` and is self-contained, as a
9660 * module's is: it closes over nothing of the test file.
9661 */
9662 export type Plugin = {
9663 name: string;
9664 tier?: PluginTier;
9665 register: Register;
9666 };
9667
9668 /**
9669 * A tier a plugin loads in: every tier but the engine's own.
9670 */
9671 export type PluginTier = Exclude<Tier, 'core'>;
9672
9673 /**
9674 * What `$.ui.press` takes: the plugin whose `ui.render` hook drew the Button,
9675 * the `key` it gave it, and the instance when it drew one in several.
9676 */
9677 export type PressTarget = {
9678 plugin: string;
9679 key: string;
9680 requestId?: string;
9681 };
9682
9683 /**
9684 * One test: it passes when its body returns or resolves, and fails when it
9685 * throws, rejects or outlasts its time (5000 ms, or `timeoutMs`).
9686 *
9687 * The body gets the engine's `$` and an `on` whose hooks sit beneath every
9688 * plugin; `plugins` load inline plugins beside the one under test. A failure
9689 * carries what the engine reported meanwhile: each hook it skipped, and why.
9690 *
9691 * @param name the test's name, led in its title by the describes around it
9692 * @param rest the body, `($, on) => ...`, or the options then the body
9693 */
9694 export const test: (name: string, ...rest: TestRest) => void;
9695
9696 /**
9697 * A test: the engine's `$`, and `on`, a plugin's registrar, whose hooks sit
9698 * beneath every plugin; beneath them the bottom hook throws, naming its event.
9699 *
9700 * The plugins load at the test's first call on `$`, so a test registers its
9701 * hooks before it, as a module registers its own in `register()`.
9702 */
9703 export type TestBody = ($: Engine, on: On) => unknown;
9704
9705 /**
9706 * What `test` takes beside its name: the inline plugins it loads beside the
9707 * one under test, and how long it may run (5000 ms when not given).
9708 */
9709 export type TestOptions = {
9710 plugins?: readonly Plugin[];
9711 timeoutMs?: number;
9712 };
9713
9714 /**
9715 * What follows a test's name: its body, or its options then its body.
9716 */
9717 export type TestRest = readonly [body: TestBody] | readonly [options: TestOptions, body: TestBody];
9718
9719 /**
9720 * What `toThrow` compares the thrown error with: a substring or pattern of
9721 * its message, its class, a value carrying the whole message, or nothing.
9722 */
9723 export type ThrowExpectation = string | RegExp | Constructor | WithMessage;
9724
9725 /**
9726 * Says which tier the plugin under test loads in, once, at the top of the
9727 * file: `prepend`, `user` (when unsaid), `append` or `builtin`.
9728 *
9729 * @param tier the tier
9730 */
9731 export const tier: (tier: PluginTier) => void;
9732
9733 /**
9734 * An error-like value `toThrow` compares by its whole message.
9735 */
9736 export type WithMessage = {
9737 message: string;
9738 };
9739}
9740
9741// The inputs of the built-in tools this build has, from each tool's
9742// input schema. Merges into ToolCallInput (BuiltinToolInputs) so
9743// `e.tool === "Bash"` narrows to the tool's arguments.
9744declare module 'claude-code' {
9745 interface BuiltinToolInputs {
9746 Agent: {
9747 /** A short (3-5 word) description of the task */
9748 description: string
9749 /** The task for the agent to perform */
9750 prompt: string
9751 /** The type of specialized agent to use for this task */
9752 subagent_type?: string
9753 /** 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. */
9754 model?: "sonnet" | "opus" | "haiku" | "fable"
9755 /** 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. */
9756 run_in_background?: boolean
9757 /** Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running. */
9758 name?: string
9759 /** Deprecated; ignored. The session has a single implicit team. */
9760 team_name?: string
9761 /** Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it. */
9762 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"
9763 /** 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). */
9764 isolation?: "worktree" | "remote"
9765 }
9766 Bash: {
9767 /** The command to execute */
9768 command: string
9769 /** Optional timeout in milliseconds (max 600000) */
9770 timeout?: number
9771 /** 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" */
9772 description?: string
9773 /** Set to true to run this command in the background. */
9774 run_in_background?: boolean
9775 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
9776 dangerouslyDisableSandbox?: boolean
9777 }
9778 CronCreate: {
9779 /** 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). */
9780 cron: string
9781 /** The prompt to enqueue at each fire time. */
9782 prompt: string
9783 /** 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. */
9784 recurring?: boolean
9785 /** 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. */
9786 durable?: boolean
9787 }
9788 CronDelete: {
9789 /** Job ID returned by CronCreate. */
9790 id: string
9791 }
9792 CronList: {}
9793 Edit: {
9794 /** The absolute path to the file to modify */
9795 file_path: string
9796 /** The text to replace */
9797 old_string: string
9798 /** The text to replace it with (must be different from old_string) */
9799 new_string: string
9800 /** Replace all occurrences of old_string (default false) */
9801 replace_all?: boolean
9802 }
9803 EnterWorktree: {
9804 /** 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`. */
9805 name?: string
9806 /** 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`. */
9807 path?: string
9808 }
9809 ExitWorktree: {
9810 /** "keep" leaves the worktree and branch on disk; "remove" deletes both. */
9811 action: "keep" | "remove"
9812 /** Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise. */
9813 discard_changes?: boolean
9814 }
9815 ListAgents: {
9816 /** Not available in this build; leave unset. */
9817 channel?: string
9818 /** Not available in this build; leave unset. */
9819 q?: string
9820 }
9821 NotebookEdit: {
9822 /** The absolute path to the Jupyter notebook file to edit (must be absolute, not relative) */
9823 notebook_path: string
9824 /** 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. */
9825 cell_id?: string
9826 /** The new source for the cell */
9827 new_source: string
9828 /** 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. */
9829 cell_type?: "code" | "markdown"
9830 /** The type of edit to make (replace, insert, delete). Defaults to replace. */
9831 edit_mode?: "replace" | "insert" | "delete"
9832 }
9833 PowerShell: {
9834 /** The PowerShell command to execute */
9835 command: string
9836 /** Optional timeout in milliseconds (max 600000) */
9837 timeout?: number
9838 /** Clear, concise description of what this command does in active voice. */
9839 description?: string
9840 /** Set to true to run this command in the background. */
9841 run_in_background?: boolean
9842 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
9843 dangerouslyDisableSandbox?: boolean
9844 }
9845 Read: {
9846 /** The absolute path to the file to read */
9847 file_path: string
9848 /** The line number to start reading from. Only provide if the file is too large to read at once */
9849 offset?: number
9850 /** The number of lines to read. Only provide if the file is too large to read at once. */
9851 limit?: number
9852 /** Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum 20 pages per request. */
9853 pages?: string
9854 }
9855 ReportFindings: {
9856 /** Effort level the review ran at */
9857 level?: "low" | "medium" | "high" | "xhigh" | "max"
9858 /** Verified findings, most-severe first; empty if none survived */
9859 findings: Array<{
9860 /** Repo-relative path of the file the finding is in */
9861 file: string
9862 /** 1-indexed line the finding anchors to */
9863 line?: number
9864 /** One-sentence statement of the defect */
9865 summary: string
9866 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
9867 short_summary?: string
9868 /** Concrete inputs/state → wrong output/crash */
9869 failure_scenario: string
9870 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
9871 category?: string
9872 /** Set when a verify pass ran; absent on inline-only reviews */
9873 verdict?: "CONFIRMED" | "PLAUSIBLE"
9874 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
9875 outcome?: "fixed" | "skipped" | "no_change_needed"
9876 }>
9877 }
9878 ScheduleWakeup: {
9879 /** Seconds from now to wake up. Clamped to [60, 3600] by the runtime. Required unless `stop` is true. */
9880 delaySeconds?: number
9881 /** One short sentence explaining the chosen delay. Goes to telemetry and is shown to the user. Be specific. Required unless `stop` is true. */
9882 reason?: string
9883 /** 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. */
9884 prompt?: string
9885 /** 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. */
9886 stop?: boolean
9887 /** 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. */
9888 noop?: boolean
9889 }
9890 SendMessage: {
9891 /** 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 */
9892 to: unknown & unknown
9893 /** 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. */
9894 summary?: string
9895 /** 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. */
9896 message: string
9897 /** 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. */
9898 notify_when_idle?: boolean
9899 }
9900 Skill: {
9901 /** The name of a skill from the available-skills list. Do not guess names. */
9902 skill: string
9903 /** Optional arguments for the skill */
9904 args?: string
9905 }
9906 TaskOutput: {
9907 /** The task ID to get output from */
9908 task_id: string
9909 /** Whether to wait for completion */
9910 block: boolean
9911 /** Max wait time in ms */
9912 timeout: number
9913 }
9914 TaskStop: {
9915 /** The ID of the background task to stop. Agent-team teammates and named background agents are also accepted by agent ID or name. */
9916 task_id?: string
9917 /** Deprecated: use task_id instead */
9918 shell_id?: string
9919 }
9920 ToolSearch: {
9921 /** Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search. */
9922 query: string
9923 /** Maximum number of results to return (default: 5) */
9924 max_results: number
9925 }
9926 WebFetch: {
9927 /** The URL to fetch content from */
9928 url: string
9929 /** The prompt to run on the fetched content */
9930 prompt: string
9931 }
9932 WebSearch: {
9933 /** The search query to use */
9934 query: string
9935 /** Only include search results from these domains */
9936 allowed_domains?: string[]
9937 /** Never include search results from these domains */
9938 blocked_domains?: string[]
9939 }
9940 Workflow: {
9941 /** 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(). */
9942 script?: string
9943 /** Name of a predefined workflow (built-in or from .claude/workflows/). Resolves to a self-contained script. */
9944 name?: string
9945 /** Ignored — set the workflow description in the script's `meta` block. */
9946 description?: string
9947 /** Ignored — set the workflow title in the script's `meta` block. */
9948 title?: string
9949 /** 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). */
9950 args?: unknown
9951 /** 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`. */
9952 scriptPath?: string
9953 /** 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. */
9954 resumeFromRunId?: string
9955 }
9956 Write: {
9957 /** The absolute path to the file to write (must be absolute, not relative) */
9958 file_path: string
9959 /** The content to write to the file */
9960 content: string
9961 }
9962 }
9963}
9964
9965// The structured results of the same tools, from each tool's output
9966// schema. Merges into ToolCallResult (BuiltinToolResults) so after
9967// `e.tool === "Bash"` the `result` of `next(e)` is the tool's record.
9968declare module 'claude-code' {
9969 interface BuiltinToolResults {
9970 Agent: {
9971 agentId: string
9972 /** @internal Count of leading harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
9973 harnessNoteCount?: number
9974 /** @internal Count of trailing harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
9975 harnessTailCount?: number
9976 /** @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 */
9977 harnessSectionHash?: string
9978 agentType?: string
9979 /** @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) */
9980 handback?: "send" | "flagged" | "withheld"
9981 content: Array<{
9982 type: "text"
9983 text: string
9984 citations?: unknown[] | null
9985 }>
9986 resolvedModel?: string
9987 modelsUsed?: string[]
9988 totalToolUseCount: number
9989 totalDurationMs: number
9990 totalTokens: number
9991 usage: {
9992 input_tokens: number
9993 output_tokens: number
9994 cache_creation_input_tokens: number | null
9995 cache_read_input_tokens: number | null
9996 server_tool_use: {
9997 web_search_requests: number
9998 web_fetch_requests: number
9999 } | null
10000 service_tier: string | null
10001 cache_creation: {
10002 ephemeral_1h_input_tokens: number
10003 ephemeral_5m_input_tokens: number
10004 } | null
10005 inference_geo?: string | null
10006 speed?: string | null
10007 iterations?: unknown
10008 output_tokens_details?: {
10009 thinking_tokens?: number | null
10010 } | null
10011 }
10012 toolStats?: {
10013 readCount: number
10014 searchCount: number
10015 bashCount: number
10016 editFileCount: number
10017 linesAdded: number
10018 linesRemoved: number
10019 otherToolCount: number
10020 frameCount?: number
10021 }
10022 status: "completed"
10023 prompt: string
10024 worktreePath?: string
10025 worktreeBranch?: string
10026 } | {
10027 status: "async_launched"
10028 isAsync?: true
10029 /** The ID of the async agent */
10030 agentId: string
10031 /** The description of the task */
10032 description: string
10033 /** Model in use at the backgrounding transition (a pre-background swap is reflected here) */
10034 resolvedModel?: string
10035 /** Ordered distinct models used before backgrounding (length > 1 means a mid-run swap) */
10036 modelsUsed?: string[]
10037 /** The prompt for the agent */
10038 prompt: string
10039 /** Path to the output file for checking agent progress */
10040 outputFile: string
10041 /** Whether the calling agent has Read/Bash tools to check progress */
10042 canReadOutputFile?: boolean
10043 } | {
10044 status: "remote_launched"
10045 /** The ID of the remote agent task */
10046 taskId: string
10047 /** The URL of the cloud session */
10048 sessionUrl: string
10049 /** The description of the task */
10050 description: string
10051 /** The prompt for the agent */
10052 prompt: string
10053 /** Path to the output file for checking agent progress */
10054 outputFile: string
10055 }
10056 Bash: {
10057 /** The standard output of the command */
10058 stdout: string
10059 /** The standard error output of the command */
10060 stderr: string
10061 /** Path to raw output file for large MCP tool outputs */
10062 rawOutputPath?: string
10063 /** Whether the command was interrupted */
10064 interrupted: boolean
10065 /** Flag to indicate if stdout contains image data */
10066 isImage?: boolean
10067 /** ID of the background task if command is running in background */
10068 backgroundTaskId?: string
10069 /** True if the user manually backgrounded the command with Ctrl+B */
10070 backgroundedByUser?: boolean
10071 /** @internal True if a plugin's turn abort moved the running command to the background */
10072 backgroundedByTurnAbort?: boolean
10073 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
10074 backgroundedToDeliverMessage?: boolean
10075 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
10076 timedOutAfterMs?: number
10077 /** Model-facing note that the session cwd was not changed by a backgrounded command containing a directory-change builtin (cd/pushd/popd/chdir) */
10078 backgroundCwdHint?: string
10079 /** 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) */
10080 backgroundEndsWithFinalResponse?: true
10081 /** Flag to indicate if sandbox mode was overridden */
10082 dangerouslyDisableSandbox?: boolean
10083 /** Semantic interpretation for non-error exit codes with special meaning */
10084 returnCodeInterpretation?: string
10085 /** Whether the command is expected to produce no output on success */
10086 noOutputExpected?: boolean
10087 /** Structured content blocks */
10088 structuredContent?: unknown[]
10089 /** Path to the persisted full output in tool-results dir (set when output is too large for inline) */
10090 persistedOutputPath?: string
10091 /** Total size of the output in bytes (set when output is too large for inline) */
10092 persistedOutputSize?: number
10093 /** Model-facing note listing readFileState entries whose mtime bumped during this command (set when WRITE_COMMAND_MARKERS matches) */
10094 staleReadFileStateHint?: string
10095 /** Model-facing system-reminder appended when a gh command reports a GitHub API rate-limit error */
10096 ghRateLimitHint?: string
10097 /** 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. */
10098 gitOperation?: {
10099 commit?: {
10100 sha: string
10101 kind: "committed" | "amended" | "cherry-picked"
10102 branch?: string
10103 }
10104 push?: {
10105 branch: string
10106 }
10107 branch?: {
10108 ref: string
10109 action: "merged" | "rebased"
10110 }
10111 pr?: {
10112 number: number
10113 url?: string
10114 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
10115 }
10116 }
10117 /** @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. */
10118 bashEditDiff?: {
10119 files: {
10120 filePath: string
10121 hunks: {
10122 oldStart: number
10123 oldLines: number
10124 newStart: number
10125 newLines: number
10126 lines: string[]
10127 }[]
10128 created?: true
10129 deleted?: true
10130 }[]
10131 moreFiles: number
10132 changedFiles?: string[]
10133 unavailable?: true
10134 skipped?: true
10135 shared?: true
10136 }
10137 }
10138 CronCreate: {
10139 id: string
10140 humanSchedule: string
10141 recurring: boolean
10142 durable?: boolean
10143 }
10144 CronDelete: {
10145 id: string
10146 }
10147 CronList: {
10148 jobs: {
10149 id: string
10150 cron: string
10151 humanSchedule: string
10152 prompt: string
10153 recurring?: boolean
10154 durable?: boolean
10155 }[]
10156 }
10157 Edit: {
10158 /** The file path that was edited */
10159 filePath: string
10160 /** The original string that was replaced */
10161 oldString: string
10162 /** The new string that replaced it */
10163 newString: string
10164 /** The original file contents before editing */
10165 originalFile: string | null
10166 /** Diff patch showing the changes */
10167 structuredPatch: {
10168 oldStart: number
10169 oldLines: number
10170 newStart: number
10171 newLines: number
10172 lines: string[]
10173 }[]
10174 /** Whether the user modified the proposed changes */
10175 userModified: boolean
10176 /** Whether all occurrences were replaced */
10177 replaceAll: boolean
10178 gitDiff?: {
10179 filename: string
10180 status: "modified" | "added"
10181 additions: number
10182 deletions: number
10183 changes: number
10184 patch: string
10185 /** GitHub owner/repo when available */
10186 repository?: string | null
10187 }
10188 /** True when the edit was held for the machine owner to review instead of written; the file is unchanged */
10189 staged?: boolean
10190 }
10191 EnterWorktree: {
10192 worktreePath: string
10193 worktreeBranch?: string
10194 message: string
10195 }
10196 ExitWorktree: {
10197 action: "keep" | "remove"
10198 originalCwd: string
10199 worktreePath: string
10200 worktreeBranch?: string
10201 tmuxSessionName?: string
10202 discardedFiles?: number
10203 discardedCommits?: number
10204 message: string
10205 }
10206 ListAgents: {
10207 /** Formatted list of reachable agents */
10208 listing: string
10209 }
10210 NotebookEdit: {
10211 /** The new source code that was written to the cell */
10212 new_source: string
10213 /** The previous cell source (replace/delete only). Enables cell-relative diff rendering without re-reading the notebook. */
10214 old_source?: string
10215 /** The ID of the cell that was edited */
10216 cell_id?: string
10217 /** The type of the cell */
10218 cell_type: "code" | "markdown"
10219 /** The programming language of the notebook */
10220 language: string
10221 /** The edit mode that was used */
10222 edit_mode: string
10223 /** Error message if the operation failed */
10224 error?: string
10225 /** The path to the notebook file */
10226 notebook_path: string
10227 /** The original notebook content before modification */
10228 original_file: string
10229 /** The updated notebook content after modification */
10230 updated_file: string
10231 }
10232 PowerShell: {
10233 /** The standard output of the command */
10234 stdout: string
10235 /** The standard error output of the command */
10236 stderr: string
10237 /** Whether the command was interrupted */
10238 interrupted: boolean
10239 /** Semantic interpretation for non-error exit codes with special meaning */
10240 returnCodeInterpretation?: string
10241 /** Flag to indicate if stdout contains image data */
10242 isImage?: boolean
10243 /** Path to persisted full output when too large for inline */
10244 persistedOutputPath?: string
10245 /** Total output size in bytes when persisted */
10246 persistedOutputSize?: number
10247 /** ID of the background task if command is running in background */
10248 backgroundTaskId?: string
10249 /** True if the user manually backgrounded the command with Ctrl+B */
10250 backgroundedByUser?: boolean
10251 /** @internal True if a plugin's turn abort moved the running command to the background */
10252 backgroundedByTurnAbort?: boolean
10253 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
10254 backgroundedToDeliverMessage?: boolean
10255 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
10256 timedOutAfterMs?: number
10257 /** 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) */
10258 backgroundEndsWithFinalResponse?: true
10259 /** 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. */
10260 gitOperation?: {
10261 commit?: {
10262 sha: string
10263 kind: "committed" | "amended" | "cherry-picked"
10264 branch?: string
10265 }
10266 push?: {
10267 branch: string
10268 }
10269 branch?: {
10270 ref: string
10271 action: "merged" | "rebased"
10272 }
10273 pr?: {
10274 number: number
10275 url?: string
10276 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
10277 }
10278 }
10279 }
10280 Read: {
10281 type: "text"
10282 file: {
10283 /** The path to the file that was read */
10284 filePath: string
10285 /** The content of the file */
10286 content: string
10287 /** Number of lines in the returned content */
10288 numLines: number
10289 /** The starting line number */
10290 startLine: number
10291 /** Total number of lines in the file */
10292 totalLines: number
10293 /** 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). */
10294 truncatedByTokenCap?: boolean
10295 }
10296 /** Set when this Read completed a saved Artifact source file: the Artifact and the version of it that now counts as viewed. */
10297 artifactRead?: {
10298 slug: string
10299 ver: string
10300 }
10301 } | {
10302 type: "image"
10303 file: {
10304 /** Base64-encoded image data */
10305 base64: string
10306 /** The MIME type of the image */
10307 type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
10308 /** Original file size in bytes */
10309 originalSize: number
10310 /** Image dimension info for coordinate mapping */
10311 dimensions?: {
10312 /** Original image width in pixels */
10313 originalWidth?: number
10314 /** Original image height in pixels */
10315 originalHeight?: number
10316 /** Displayed image width in pixels (after resizing) */
10317 displayWidth?: number
10318 /** Displayed image height in pixels (after resizing) */
10319 displayHeight?: number
10320 }
10321 }
10322 } | {
10323 type: "notebook"
10324 file: {
10325 /** The path to the notebook file */
10326 filePath: string
10327 /** Array of notebook cells */
10328 cells: unknown[]
10329 }
10330 } | {
10331 type: "pdf"
10332 file: {
10333 /** The path to the PDF file */
10334 filePath: string
10335 /** Base64-encoded PDF data */
10336 base64: string
10337 /** Original file size in bytes */
10338 originalSize: number
10339 }
10340 } | {
10341 type: "parts"
10342 file: {
10343 /** The path to the PDF file */
10344 filePath: string
10345 /** Original file size in bytes */
10346 originalSize: number
10347 /** Number of pages extracted */
10348 count: number
10349 /** Directory containing extracted page images */
10350 outputDir: string
10351 }
10352 /** Document page number of the first extracted page (1 when no range was requested); labels the page images in the model-facing tool_result */
10353 firstPage?: number
10354 /** 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 */
10355 pages?: Array<{
10356 /** Base64-encoded page image; empty when the page could not be processed */
10357 base64: string
10358 /** The MIME type of the image */
10359 mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
10360 /** Why the page could not be processed as an image; set only when base64 is empty */
10361 error?: string
10362 }>
10363 } | {
10364 type: "file_unchanged"
10365 file: {
10366 /** The path to the file */
10367 filePath: string
10368 }
10369 /** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result */
10370 source?: "seeded"
10371 }
10372 ReportFindings: {
10373 /** Number of findings reported */
10374 count: number
10375 /** Effort level the review ran at */
10376 level?: "low" | "medium" | "high" | "xhigh" | "max"
10377 /** Echoed for the result body */
10378 findings: Array<{
10379 /** Repo-relative path of the file the finding is in */
10380 file: string
10381 /** 1-indexed line the finding anchors to */
10382 line?: number
10383 /** One-sentence statement of the defect */
10384 summary: string
10385 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
10386 short_summary?: string
10387 /** Concrete inputs/state → wrong output/crash */
10388 failure_scenario: string
10389 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
10390 category?: string
10391 /** Set when a verify pass ran; absent on inline-only reviews */
10392 verdict?: "CONFIRMED" | "PLAUSIBLE"
10393 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
10394 outcome?: "fixed" | "skipped" | "no_change_needed"
10395 }>
10396 }
10397 ScheduleWakeup: {
10398 /** Epoch ms timestamp when the next wakeup will fire */
10399 scheduledFor: number
10400 /** Actual delay used after clamping to runtime bounds */
10401 clampedDelaySeconds: number
10402 /** True if the requested delaySeconds was outside [60, 3600] */
10403 wasClamped: boolean
10404 /** True when the model ended the loop via `stop: true` */
10405 stopped?: boolean
10406 /** How many pending dynamic-loop wakeups stop:true cancelled. 0 means nothing was pending — a recurring /loop cron is not cancelled by stop:true. */
10407 cancelledWakeups?: number
10408 }
10409 SendMessage: unknown
10410 Skill: {
10411 /** Whether the skill is valid */
10412 success: boolean
10413 /** The name of the skill */
10414 commandName: string
10415 /** Tools allowed by this skill */
10416 allowedTools?: string[]
10417 /** Resolved model the skill turn runs on when a frontmatter model override took effect; omitted otherwise */
10418 model?: string
10419 /** Execution status */
10420 status?: "inline"
10421 /** True when the skill instructions were loaded read-only (nothing was executed) */
10422 readOnly?: boolean
10423 } | {
10424 /** Whether the skill completed successfully */
10425 success: boolean
10426 /** The name of the skill */
10427 commandName: string
10428 /** Execution status */
10429 status: "forked"
10430 /** The ID of the sub-agent that executed the skill */
10431 agentId: string
10432 /** The result from the forked skill execution */
10433 result: string
10434 /** True when the sub-agent was launched in the background: `result` describes the launch, and the skill outcome arrives later as a task notification. */
10435 background?: boolean
10436 }
10437 TaskOutput: unknown
10438 TaskStop: {
10439 /** Status message about the operation */
10440 message: string
10441 /** The ID of the task that was stopped */
10442 task_id: string
10443 /** The type of the task that was stopped */
10444 task_type: string
10445 /** The command or description of the stopped task */
10446 command?: string
10447 }
10448 ToolSearch: {
10449 matches: string[]
10450 query: string
10451 total_deferred_tools: number
10452 pending_mcp_servers?: string[]
10453 failed_mcp_servers?: {
10454 name: string
10455 errorCode?: string
10456 error?: string
10457 }[]
10458 }
10459 WebFetch: {
10460 /** Size of the fetched content in bytes */
10461 bytes: number
10462 /** HTTP response code */
10463 code: number
10464 /** HTTP response code text */
10465 codeText: string
10466 /** Processed result from applying the prompt to the content */
10467 result: string
10468 /** Time taken to fetch and process the content */
10469 durationMs: number
10470 /** The URL that was fetched */
10471 url: string
10472 artifactRead?: {
10473 slug: string
10474 ver?: string
10475 seeded?: false
10476 }
10477 }
10478 WebSearch: {
10479 /** The search query that was executed */
10480 query: string
10481 /** Search results and/or text commentary from the model */
10482 results: Array<{
10483 /** ID of the tool use */
10484 tool_use_id: string
10485 /** Array of search hits */
10486 content: Array<{
10487 /** The title of the search result */
10488 title: string
10489 /** The URL of the search result */
10490 url: string
10491 }>
10492 } | string>
10493 /** Time taken to complete the search operation */
10494 durationSeconds: number
10495 /** Number of web searches performed */
10496 searchCount?: number
10497 }
10498 Workflow: {
10499 status: "async_launched" | "remote_launched"
10500 taskId: string
10501 /** 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. */
10502 taskType?: "local_workflow" | "remote_agent"
10503 /** 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. */
10504 workflowName?: string
10505 /** 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. */
10506 runId?: string
10507 summary?: string
10508 /** Directory where subagent transcripts are written during execution */
10509 transcriptDir?: string
10510 /** Path to the persisted workflow script for this invocation. Editable via Write/Edit; pass back as `scriptPath` to re-run without resending the script. */
10511 scriptPath?: string
10512 /** CCR session URL when status is remote_launched */
10513 sessionUrl?: string
10514 /** Non-blocking heads-up (e.g. local git state diverges from the pushed branch the cloud session will clone) */
10515 warning?: string
10516 /** Set if syntax check failed */
10517 error?: string
10518 }
10519 Write: {
10520 /** Whether a new file was created or an existing file was updated */
10521 type: "create" | "update"
10522 /** The path to the file that was written */
10523 filePath: string
10524 /** The content that was written to the file */
10525 content: string
10526 /** 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) */
10527 structuredPatch: {
10528 oldStart: number
10529 oldLines: number
10530 newStart: number
10531 newLines: number
10532 lines: string[]
10533 }[]
10534 /** The original file content before the write (null for new files, or when the previous content was too large to include) */
10535 originalFile: string | null
10536 gitDiff?: {
10537 filename: string
10538 status: "modified" | "added"
10539 additions: number
10540 deletions: number
10541 changes: number
10542 patch: string
10543 /** GitHub owner/repo when available */
10544 repository?: string | null
10545 }
10546 /** True when the user edited the proposed content in the permission dialog before accepting */
10547 userModified?: boolean
10548 /** True when the write was held for the machine owner to review instead of written; the file is unchanged */
10549 staged?: boolean
10550 }
10551 }
10552}