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