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