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