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
12,990 lines · 487.4 KBRaw
1// Written by Claude Code 2.1.277.
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. `claude plugin validate <dir>`
8// is the other half: it reads a plugin's manifest and its hooks module's
9// source the way the engine will and reports what the module hooks and
10// calls and everything the engine would refuse, before any session loads it.
11//
12// What is here: the module a hooks module may import types from,
13// import type { Register, On, EngineInterface } from 'claude-code'
14// (at run time the import is empty), and the globals a hooks module has:
15// `h` and `Fragment` (what JSX compiles against), the JSX namespace, and
16// the environment's web APIs (URL, TextEncoder, AbortController,
17// crypto.subtle, ...). A hooks module runs in an environment of its own:
18// no DOM, no Node. The module, and every file it imports from the plugin,
19// is named .ts, .tsx, .jsx, .js, .mjs, .cjs, .mts or .cts (a file named
20// otherwise is not loaded) and is an ES module whatever its suffix: there
21// is no `require`. The elements a render hook draws with (`Box`, `Text`,
22// `Button`, ...) are not globals: they come from the surface's table,
23// const { Box, Text } = $.ui.resolve(e)
24//
25// Also here: 'claude-code/testing', the kit a plugin's *.test.ts and
26// *.test.tsx files import under `claude plugin test <dir>`, which runs each
27// in an environment like the one a plugin's hooks run in (no fs, network or
28// process), the plugin loaded from the folder by the engine's own host:
29// `test(name, async ($, on) => { ... })`, where `$` is the engine's own
30// and the hooks `on` registers sit beneath every plugin; with describe,
31// expect, tier, and `mock`, whose clock, store and env answer those nouns
32// beneath the plugins from memory. `$.ui.mount` draws a component through
33// the plugin on the surface the test names (terminal, desktop, vscode or
34// mobile: never assumed) and hands back the drawing to read and act on by
35// key: find an element, press a Button, type into an Input, drive a
36// `Client`'s module (keys, pointer, posts, its frame clock), each act typed
37// by that surface's element table, so one test body run over several
38// surfaces covers the mod's hooks and description on each. It exercises
39// the mod (its hooks, the tree they return under each surface's rules, its
40// `Client` modules), never a surface's paint (Ink's, the desktop page's):
41//
42// test('notes add up on every surface that takes input', async $ => {
43// for (const surface of ['terminal', 'desktop'] as const) {
44// const ui = await $.ui.mount({ plugin: 'notes', surface, ...BAND })
45// await ui.input({ key: 'new', text: 'milk' })
46// expect((await ui.find({ key: 'count' }))?.text).toBe('1 note')
47// await ui.key({ key: 'down', in: 'list' })
48// await ui.unmount()
49// }
50// for (const surface of ['terminal', 'desktop', 'vscode', 'mobile'] as const) {
51// const ui = await $.ui.mount({ plugin: 'notes', surface, ...HINT })
52// expect(await ui.find({ type: 'Text', text: /notes/ })).toBeDefined()
53// await ui.press({ key: 'dismiss' })
54// }
55// })
56//
57// Typing a plugin against it:
58// export const register: Register = (on, options) => { ... }
59// or, in a .js module,
60// /** @type {import('claude-code').Register} */
61// export const register = (on, options) => { ... }
62//
63// A tsconfig.json (or jsconfig.json) that fits a hooks module:
64// {
65// "compilerOptions": {
66// "target": "es2023", "lib": ["es2023"], "types": [],
67// "module": "esnext", "moduleResolution": "bundler",
68// "strict": true, "noUncheckedIndexedAccess": true,
69// "noEmit": true, "skipLibCheck": true,
70// "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment"
71// },
72// "include": [".claude/types", "hooks", "tests"]
73// }
74// ".claude/types" is where /plugin-types writes this file and, beside it,
75// claude-code-mcp.d.ts and claude-code-plugins.d.ts, the index of the
76// enabled plugins' type contracts, each copied to claude-code-plugins/
77// <plugin>.d.ts: what a plugin adds to `$` in engine.create, so a plugin
78// you depend on is typed with nothing copied (the include above takes the
79// whole folder). "hooks" is the plugin's hooks/ folder and "tests" its test
80// files. `lib` names no DOM: the environment has none, and its `Text`
81// would shadow the element.
82//
83// A plugin that adds a noun to `$` ships its own contract: a .d.ts its
84// plugin.json names as "types", exporting the noun's types at its top level
85// and declaring the noun on the engine's interface,
86// export type Topo = { ... }
87// declare module 'claude-code' {
88// interface EngineInterface { topo: Topo }
89// }
90// with no import or reference, its exported names led by the noun's
91// PascalCase name; the plugin's own hooks module imports them from it.
92
93declare module 'claude-code' {
94 /**
95 * What an Agent call a plugin raised (`$.tool.call({ tool: "Agent", ... })`)
96 * answers as `result` once the agent settles; `text` is its final answer.
97 *
98 * A plugin's spawn always runs in the background, so the call resolves with
99 * this record and not the Agent tool's own (BuiltinToolResults), which is
100 * what a model's Agent call carries at `tool.call`.
101 */
102 export type AgentCallRecord = {
103 /**
104 * The spawned agent's id, as `$.agent.list()` names it.
105 */
106 agentId: string;
107 /**
108 * The model the agent resolved to, when one is known.
109 */
110 resolvedModel?: string;
111 };
112
113 /**
114 * One agent loop of this session as `$.agent.list()` returns it: a subagent
115 * or an in-process teammate.
116 */
117 export type AgentInfo = {
118 /**
119 * The agent's id: the same string its loop's `tool.call` events carry as
120 * `agentId`, and a spawn inside it as `parentAgentId`.
121 */
122 id: string;
123 /**
124 * Its row's label.
125 */
126 description: string;
127 /**
128 * The agent definition it runs as (`general-purpose`, `Explore`, ...), or
129 * `teammate` for an in-process teammate.
130 */
131 type: string;
132 /**
133 * `running`, `completed`, `failed`, `killed`, or another of the engine's task
134 * statuses.
135 */
136 status: string;
137 /**
138 * The id of the subagent whose loop spawned it; absent when the main loop
139 * did.
140 */
141 parentId?: string;
142 /**
143 * The plugin whose `$.agent.spawn` (or Agent `$.tool.call`) started it;
144 * absent when the model or the person did.
145 *
146 * The origin axis: which plugin caused it, whichever loop that hook ran in.
147 */
148 spawnedBy?: string;
149 /**
150 * What SendMessage addresses it by (`Agent({ name })`, or the engine's own
151 * for a background agent), when it has one; not `description` or `type`.
152 */
153 name?: string;
154 };
155
156 /**
157 * Which model loop an event happened in: the loop's agent id inside a
158 * subagent's or a teammate's loop, absent on the main loop.
159 *
160 * The agent axis, not the origin axis: `next.origin` names the plugin whose
161 * hook frame caused the dispatch (the recursion skip), whichever loop it ran
162 * in; `agentId` names the loop, whoever caused the call.
163 */
164 export type AgentLoop = {
165 /**
166 * The id of the loop this call runs in: for a subagent or a teammate, the
167 * `id` `$.agent.list()` gives it; absent on the main loop.
168 *
169 * A workflow's agents and the engine's own forks (compaction, memory) carry
170 * ids no list names. Pinned: a different value is refused, one left out is
171 * kept. Which loop, not which plugin caused it (that is `next.origin`).
172 */
173 agentId?: string;
174 };
175
176 /**
177 * The input of `agent.offer`: one agent type, at the moment the engine
178 * offers it to the model.
179 *
180 * Listed for the model (the agent listing) or named by it at dispatch
181 * (`subagent_type`): the same event at each. Model-facing only: a plugin's
182 * own `$.agent.spawn` of a type is no offer, and `agent.spawn` governs it.
183 */
184 export type AgentOfferInput = {
185 /**
186 * Which type (`Explore`, `Plan`, a plugin's agent); the key a matcher
187 * narrows on.
188 */
189 agent: string;
190 /**
191 * Its listing line's text as the definition states it (`whenToUse`).
192 */
193 description: string;
194 /**
195 * Where the definition came from (`built-in`, `plugin`, a settings
196 * source), so a matcher tells a built-in from a user's agent of its name.
197 */
198 source: string;
199 /**
200 * Who provides this agent: the plugin and its tier; `{ plugin: "engine",
201 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
202 */
203 provider: Origin;
204 };
205
206 /**
207 * What an `agent.offer` hook returns: whether the model is offered the agent
208 * type, in its listing and at dispatch.
209 */
210 export type AgentOfferResult = {
211 isOffered: boolean;
212 };
213
214 /**
215 * `agent.spawn`'s input as the call takes it: what the Agent tool's caller
216 * says; the engine fills the rest.
217 *
218 * A call's spawn runs in the background: it resolves once the subagent
219 * started, and nothing holds it in the foreground.
220 */
221 export type AgentSpawnArgs = Pick<AgentSpawnInput, 'prompt'> & Partial<Pick<AgentSpawnInput, 'description' | 'subagentType' | 'model' | 'name' | 'cwd'>>;
222
223 /**
224 * The input of `agent.spawn`: what the Agent tool decided about the
225 * subagent it is about to start, before its model is resolved.
226 *
227 * A hook rewrites content (prompt, description, subagentType, model,
228 * background, cwd), read back as the tool's parameters; tool_use_id, name,
229 * fork, parentModel, permissionMode, parentAgentId and provider are pinned.
230 */
231 export type AgentSpawnInput = {
232 /**
233 * The Agent tool call this spawn belongs to (for `$.ui.notice`). Pinned:
234 * the spawn's identity.
235 */
236 tool_use_id: string;
237 /**
238 * The task the subagent is given: the Agent tool's `prompt` parameter. A
239 * rewrite is the prompt the subagent runs with.
240 */
241 prompt: string;
242 /**
243 * The Agent tool's short `description` of the task (a few words). A rewrite
244 * is what the task shows as.
245 */
246 description: string;
247 /**
248 * The resolved agent type (`general-purpose`, `Explore`, a plugin's agent,
249 * `fork`). A rewrite names another agent this call can dispatch, exactly.
250 *
251 * That definition is the one spawned; a name matching none refuses the
252 * spawn, and a fork dispatches no other.
253 */
254 subagentType: string;
255 /**
256 * Who provides this agent: the plugin and its tier; `{ plugin: "engine",
257 * tier: "core" }` for a built-in. Pinned with the spawn's identity.
258 */
259 provider: Origin;
260 /**
261 * The Agent tool's `model` parameter as given, an alias (`haiku`) or a
262 * full id; undefined lets the agent's own model, then the parent's, decide.
263 *
264 * Ignored for forks, which always inherit. A hook sets this to pick the
265 * subagent's model.
266 */
267 model?: string;
268 /**
269 * The parent's effective model, what `inherit` resolves to. Pinned: a fact
270 * of the parent (set `model` to change what the subagent runs on).
271 */
272 parentModel: string;
273 /**
274 * The id of the loop the spawn happens in (its `tool.call` `agentId`; for a
275 * subagent or teammate its `$.agent.list()` id); absent from main.
276 *
277 * Pinned: a different value is refused, one left out is kept. The agent
278 * axis, not the origin: `next.origin` names the plugin whose hook frame
279 * caused the spawn, this names the model loop it happened in.
280 */
281 parentAgentId?: string;
282 /**
283 * The parent's permission mode (`default`, `acceptEdits`, `plan`, ...), which
284 * the subagent inherits. Pinned: a fact of the parent.
285 */
286 permissionMode?: string;
287 /**
288 * True when the subagent will run in the background (or remotely). A
289 * rewrite is read back as the call's `run_in_background`.
290 *
291 * The agent's own definition and remote isolation can still force it on,
292 * and disabled background tasks force it off.
293 */
294 background: boolean;
295 /**
296 * True for a fork of the parent: it inherits the parent's context and model,
297 * and `model` is ignored. Pinned: the spawn's identity.
298 */
299 fork: boolean;
300 /**
301 * Given by the call (`Agent({ name })`, addressable by SendMessage);
302 * undefined when unnamed. Pinned: the address the parent routes by.
303 */
304 name?: string;
305 /**
306 * The directory the subagent runs in when the call set one (`cwd`); undefined
307 * means the parent's. A rewrite is where the subagent runs.
308 */
309 cwd?: string;
310 };
311
312 /**
313 * What an `agent.spawn` hook returns and what `next(e)` resolves to: the
314 * started subagent's `{ model, agentId }`, or `{ deny: reason }`, refusing it.
315 *
316 * It and `$.agent.spawn(input)` resolve once the subagent started; its answer
317 * is its own `turn.complete`, carrying this `agentId`. Keep the id and set
318 * `got[agentId]` to what waits; a `turn.complete` hook resolves it:
319 *
320 * @example
321 * on("turn.complete", ($, e, next) => (got[e.agentId]?.(e.answer), next(e)))
322 */
323 export type AgentSpawnResult = {
324 /**
325 * What the subagent runs on: from core the resolved id; from a hook an
326 * alias (`haiku`) or an id.
327 */
328 model: string;
329 /**
330 * The started subagent's id: the same string its loop's `tool.call`
331 * events carry as `agentId` and `$.agent.list()` lists it by.
332 *
333 * Set by core; a hook that answers without `next` started none.
334 */
335 agentId?: string;
336 deny?: undefined;
337 } | {
338 /**
339 * Refuses the spawn, so nothing starts; the model sees the text as the
340 * Agent tool's error.
341 */
342 deny: string;
343 model?: undefined;
344 agentId?: undefined;
345 };
346
347 /**
348 * What `$.agent.register` takes: an agent type this plugin defines, spelled
349 * as an agent definition in settings JSON is, plus its `name`.
350 *
351 * Every field an agent file or `--agents` entry may carry is here and takes
352 * effect as it does there; the engine validates it with the same schema.
353 */
354 type AgentSpec = {
355 /**
356 * The type's short name (letters, digits, `_`, `-`; up to 64); the type is
357 * `<plugin>:<name>`, as a plugin's agent file `agents/<name>.md` names one.
358 */
359 name: string;
360 /**
361 * When to delegate to this agent: the line the model reads in its listing
362 * of agent types, and `agent.offer`'s `description`.
363 */
364 description: string;
365 /**
366 * The agent's system prompt, whole: it replaces the session's.
367 */
368 prompt: string;
369 /**
370 * What the agent may call, by tool name (`Read`, `Bash`, `mcp__x__y`); a
371 * call to any other is refused. Left out: every tool the parent has.
372 */
373 tools?: readonly string[];
374 /**
375 * Tools withheld from the agent, by name, out of whatever `tools` allows.
376 */
377 disallowedTools?: readonly string[];
378 /**
379 * The agent's model: an alias (`haiku`, `sonnet`, `opus`), a full id, or
380 * `inherit` for the parent's. Left out: the session's subagent default.
381 */
382 model?: string;
383 /**
384 * The agent's effort: a level (`low`, `medium`, `high`, `xhigh`, `max`)
385 * or an integer budget.
386 */
387 effort?: string | number;
388 /**
389 * How the agent's permission asks are decided, a mode: `default`,
390 * `acceptEdits`, `plan`, `auto`, `dontAsk` or `bypassPermissions`.
391 *
392 * Left out: the parent's.
393 */
394 permissionMode?: string;
395 /**
396 * Servers connected over MCP for the agent's run: a configured server's
397 * name, or `{ "<name>": { command, args } }`, one server's config inline.
398 */
399 mcpServers?: readonly (string | Record<string, unknown>)[];
400 /**
401 * Settings hooks in force while the agent runs, in settings.json's `hooks`
402 * shape (`{ PreToolUse: [{ matcher, hooks: [...] }] }`).
403 */
404 hooks?: Record<string, unknown>;
405 /**
406 * The most turns the agent takes before it stops.
407 */
408 maxTurns?: number;
409 /**
410 * Preloaded into the agent's context before its first turn: skill names.
411 */
412 skills?: readonly string[];
413 /**
414 * The agent's first user turn; `{{intent}}` in it takes the spawn's prompt.
415 * Left out: the spawn's prompt is the first turn.
416 */
417 initialPrompt?: string;
418 /**
419 * A persistent memory the agent keeps between runs, and where: `user`,
420 * `project` or `local`.
421 */
422 memory?: 'user' | 'project' | 'local';
423 /**
424 * Set so that every spawn of the agent runs in the background.
425 */
426 background?: true;
427 /**
428 * Set so that the agent's context carries no CLAUDE.md block (the person's,
429 * the project's, the rules): it takes what it needs from its prompt.
430 */
431 omitClaudeMd?: true;
432 /**
433 * Where the agent runs apart from the session: `worktree`, a git worktree
434 * of its own; `remote`, a cloud session where the build allows one.
435 */
436 isolation?: 'worktree' | 'remote';
437 };
438
439 /**
440 * The hook `on("*", hook)` takes: it runs on every event, plugin nouns no
441 * declaration names included, so `e` is `unknown` and `next` is StarNext.
442 *
443 * Until `next.is(pattern, e)` narrows `e`, all a hook can do with it is pass
444 * it on, time it, log it, or fail it; once narrowed it is an ordinary hook on
445 * those events.
446 *
447 * @param $ the engine interface; at `engine.create` the empty table, so a hook
448 * that reads `$` tests `next.is("engine.create", e)` first
449 */
450 export type AnyEventHook = ($: EngineInterface, e: unknown, next: StarNext) => unknown;
451
452 /**
453 * Every key of every variant, index signatures included.
454 */
455 type AnyKeyOf<I> = I extends unknown ? keyof I : never;
456
457 /**
458 * The argument of event `N`: `e` in its hooks, and what its call takes. For a
459 * union of names, the union of their arguments.
460 */
461 export type Args<N extends EventName = EventName> = EventOf[N];
462
463 /**
464 * Options of `$.ui.ask`.
465 */
466 export type AskOptions = {
467 /**
468 * 2-4 option labels; fewer than two are padded with Yes/No; free text is the
469 * dialog's Other.
470 */
471 options?: readonly string[];
472 /**
473 * A short chip beside the question (`Approach`, 12 characters at most).
474 */
475 header?: string;
476 /**
477 * Allow several options; the answer comes back comma-joined.
478 */
479 multiSelect?: true;
480 };
481
482 /**
483 * The input of `attribution.text`: one text the engine asks the model to
484 * write into a commit or a pull request, at the moment it is composed.
485 *
486 * Composed for the Bash description, the commit skills, a PR's body, the
487 * pre-ship mandate and the commit gate's deny: the same event at each.
488 */
489 export type AttributionTextInput = {
490 /**
491 * Which text (`commit`, `pr`, `exemption`, `remedy`); the key a matcher
492 * narrows on.
493 */
494 kind: AttributionTextKind;
495 /**
496 * As the engine composed it, the settings applied.
497 */
498 text: string;
499 };
500
501 /**
502 * Which git text `attribution.text` carries: the commit trailer, the PR
503 * footer, the mandate's or the commit gate's sentence naming the exemption.
504 */
505 export type AttributionTextKind = 'commit' | 'pr' | 'exemption' | 'remedy';
506
507 /**
508 * What an `attribution.text` hook returns: the text the model reads in
509 * that place.
510 */
511 export type AttributionTextResult = {
512 text: string;
513 };
514
515 /**
516 * What `$.audio.play` plays: a URL the engine fetches, or the bytes.
517 */
518 export type AudioClip = {
519 /**
520 * A file of the calling plugin's own, relative to the plugin's
521 * directory (`fx/open.wav`); no `.`, no leading slash.
522 *
523 * The engine resolves it and loads the file from disk.
524 */
525 asset: string;
526 url?: undefined;
527 base64?: undefined;
528 mime?: undefined;
529 } | {
530 /**
531 * The clip's URL; the engine fetches it (never the plugin).
532 */
533 url: string;
534 asset?: undefined;
535 base64?: undefined;
536 mime?: undefined;
537 } | {
538 /**
539 * The clip's bytes, base64.
540 */
541 base64: string;
542 /**
543 * What the bytes are (`audio/mpeg`, `audio/wav`).
544 */
545 mime: string;
546 asset?: undefined;
547 url?: undefined;
548 };
549
550 type BackgroundTaskSummary = {
551 id: string;
552 /**
553 * Friendly task-type label (e.g. 'shell', 'subagent', 'monitor', 'workflow'). Falls back to the raw discriminant for unknown types.
554 */
555 type: string;
556 status: string;
557 /**
558 * Free-text description. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
559 */
560 description: string;
561 /**
562 * Shell command line. Only present for 'shell' tasks. Capped at 1000 chars with the same "... [+N chars]" marker.
563 */
564 command?: string;
565 /**
566 * Subagent type name. Only present for 'subagent' tasks.
567 */
568 agent_type?: string;
569 /**
570 * MCP server name. Only present for 'monitor' / 'MCP task' tasks.
571 */
572 server?: string;
573 /**
574 * MCP tool name. Only present for 'monitor' / 'MCP task' tasks.
575 */
576 tool?: string;
577 /**
578 * Workflow name. Only present for 'workflow' tasks.
579 */
580 name?: string;
581 };
582
583 type BaseHookInput = {
584 session_id: string;
585 transcript_path: string;
586 cwd: string;
587 /**
588 * 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.
589 */
590 prompt_id?: string;
591 permission_mode?: string;
592 /**
593 * 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.
594 */
595 agent_id?: string;
596 /**
597 * 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).
598 */
599 agent_type?: string;
600 /**
601 * 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.
602 */
603 effort?: {
604 /**
605 * 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.
606 */
607 level: string;
608 };
609 };
610
611 /**
612 * The `Box` props a `hover` may override, none of which moves the Box's
613 * siblings, and `scope`, which names the hover group the Box joins.
614 *
615 * `display` is `"flex"` alone, on a Box drawn `display: "none"`: with a
616 * `scope`, every member of the lit group is revealed, in whichever site it
617 * sits, so a pointer on a glyph in the transcript can swap an entry into a
618 * fixed row of the band, or reveal an absolutely positioned card.
619 * `borderStyle` only restyles a border the Box has; the offsets move a Box
620 * drawn `position: "absolute"`, none in the flow. The surface applies a
621 * hover as the pointer moves, so a reveal that moves what the pointer rests
622 * on is drawn once, not in a loop.
623 */
624 export type BoxHoverProps = {
625 /**
626 * Names a hover group of this plugin's: every element it draws with the
627 * same `scope`, in any site, lights while any is hovered, reveals included.
628 *
629 * A Pane row and a mark on a transcript message can share one. Another
630 * plugin's elements under the same string are a different group. One to
631 * 64 characters, no control characters; no keyed Box needed; no hook runs.
632 */
633 scope?: string;
634 borderStyle?: string;
635 borderColor?: string;
636 borderDimColor?: boolean;
637 backgroundColor?: string;
638 display?: 'flex';
639 top?: number;
640 left?: number;
641 right?: number;
642 bottom?: number;
643 };
644
645 /**
646 * The props of `Box`: the layout, position, margin, padding and border props
647 * of Ink's Box a tree may set, and the two of hover.
648 */
649 export type BoxProps = {
650 /**
651 * Makes the Box a hover scope: while the pointer is anywhere over it, its
652 * own `hover` and that of every element beneath it apply.
653 *
654 * A nested Box with a `key` of its own scopes what is beneath it, a placed
655 * card outside its rows included. A key a sibling Box already took, or one
656 * that is no plain string, names no scope: hovers beneath it stay inert.
657 */
658 key?: string;
659 /**
660 * Style overrides applied by the surface while the pointer is over the
661 * nearest keyed `Box`, this one included, or, given a `scope`, its group.
662 *
663 * No hook runs and nothing crosses to the plugin. To reveal on hover, draw
664 * the Box `display: "none"` with `hover: { display: "flex" }` in a visible
665 * keyed Box or under a `scope`; on a `position: "absolute"` Box, no reflow.
666 */
667 hover?: BoxHoverProps;
668 /**
669 * `"absolute"` leaves the flow, as in CSS: placed against its parent by
670 * the offsets, no room among its siblings, painted over those before it.
671 *
672 * So showing or moving it (a hover may) moves nothing; the pointer on it is
673 * on its parent. Clipped, pointer and paint, by the region its site is in
674 * (viewport, pane, band), by the site itself on the main screen or export.
675 *
676 * @example <Box key="k"><Text>glyph</Text><Box position="absolute" top={-2}
677 * left={2} display="none" hover={{ display: 'flex' }}>the card</Box></Box>
678 */
679 position?: 'relative' | 'absolute';
680 /**
681 * Rows from the parent's top edge, in character cells: an integer,
682 * negative above the edge.
683 *
684 * With `bottom` and no `height` the Box spans the two.
685 */
686 top?: number;
687 /**
688 * Columns from the parent's left edge, in character cells: an integer,
689 * negative left of the edge.
690 *
691 * With `right` and no `width` the Box spans the two.
692 */
693 left?: number;
694 /**
695 * Columns from the parent's right edge, in character cells: an integer,
696 * negative right of the edge.
697 */
698 right?: number;
699 /**
700 * Rows from the parent's bottom edge, in character cells: an integer,
701 * negative below the edge.
702 */
703 bottom?: number;
704 flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';
705 flexGrow?: number;
706 flexShrink?: number;
707 flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse';
708 alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch';
709 alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto';
710 justifyContent?: 'flex-start' | 'center' | 'flex-end' | 'space-between' | 'space-around' | 'space-evenly';
711 gap?: number;
712 columnGap?: number;
713 rowGap?: number;
714 width?: number | string;
715 height?: number | string;
716 minWidth?: number | string;
717 minHeight?: number | string;
718 margin?: number;
719 marginX?: number;
720 marginY?: number;
721 marginTop?: number;
722 marginBottom?: number;
723 marginLeft?: number;
724 marginRight?: number;
725 padding?: number;
726 paddingX?: number;
727 paddingY?: number;
728 paddingTop?: number;
729 paddingBottom?: number;
730 paddingLeft?: number;
731 paddingRight?: number;
732 borderStyle?: string;
733 borderColor?: string;
734 borderDimColor?: boolean;
735 backgroundColor?: string;
736 overflow?: 'visible' | 'hidden';
737 display?: 'flex' | 'none';
738 };
739
740 /**
741 * One variant per built-in tool; with none in the table (a plugin author's
742 * project before `/plugin-types` ran), one loose variant over every name.
743 */
744 export type BuiltinToolCallInput = [BuiltinToolName] extends [never] ? BuiltinToolCallInputFallback : {
745 [N in BuiltinToolName]: ToolInputOf<N, BuiltinToolInputs[N]>;
746 }[BuiltinToolName];
747
748 /**
749 * The built-in branch's answer when no built-in tool is declared: every
750 * name, its args unconstrained.
751 */
752 type BuiltinToolCallInputFallback = {
753 /**
754 * The name of the tool being called (`Bash`); comparing it narrows `e` once
755 * the table has entries. Reserved: a rewrite of it is ignored by core.
756 */
757 tool: string;
758 /**
759 * The tool_use block's id: the same at every event of the call and in
760 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
761 */
762 tool_use_id: string;
763 [argument: string]: unknown;
764 };
765
766 /**
767 * The arguments of each built-in tool by name, for declaration merging;
768 * empty until a declaration file adds entries, then `e.tool === "Bash"`
769 * narrows `e` to Bash's arguments.
770 *
771 * `/plugin-types` writes this build's set beneath the engine's declarations
772 * (claude-code.d.ts), from each tool's input schema.
773 *
774 * @example
775 * interface BuiltinToolInputs { Bash: { command: string; timeout?: number } }
776 */
777 export interface BuiltinToolInputs {
778 }
779
780 /**
781 * The names of the built-in tools.
782 */
783 export type BuiltinToolName = keyof BuiltinToolInputs & string;
784
785 /**
786 * The structured result of each built-in tool by name, for declaration
787 * merging; empty until a declaration file adds entries, then after
788 * `e.tool === "Bash"` the `result` of `next(e)` is Bash's record.
789 *
790 * `/plugin-types` writes this build's set beneath the engine's declarations
791 * (claude-code.d.ts), from each tool's output schema; a tool without one is
792 * `unknown`.
793 *
794 * @example
795 * interface BuiltinToolResults { Bash: { stdout: string; stderr: string } }
796 */
797 export interface BuiltinToolResults {
798 }
799
800 /**
801 * The props of `Button`, every surface's pressable leaf: an address, a
802 * label, the closure a press runs, and the label styles a hover overrides.
803 *
804 * The terminal draws `[ label ]` (when `plain`, `1: label` or the label
805 * alone), a desktop a native button; a click, a `hotkey`, the chord for its
806 * `action`, or Enter under the focus raises `ui.press`, its bottom `onPress`.
807 */
808 export type ButtonProps = {
809 /**
810 * The element's address: `e.element` at `ui.press`, what a matcher names.
811 * Defaults to the label.
812 */
813 key?: string;
814 /**
815 * The text drawn on the button; or the one string child.
816 */
817 label?: string;
818 /**
819 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it while
820 * the plugin's site holds the focus; anything else is refused.
821 *
822 * The band after ctrl+x tab or a click, a focused `Pane`; never from the
823 * composer, save a bare digit in an empty one pressing a band Button, as a
824 * survey is answered. Shift+w matches `"w"`; two on one key, the later wins.
825 */
826 hotkey?: string;
827 /**
828 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord, as the
829 * person bound it, presses this from the prompt; unknown names refused.
830 *
831 * Chords, or a modified key Global or an active context binds, on the
832 * terminal while mounted, no dialog up and no engine handler of the action
833 * mounted; a pane's over the band's over another's, then the last drawn.
834 */
835 action?: string;
836 /**
837 * Drawn without chrome: the hotkey in the accent color, a colon, the
838 * label (`1: Yes`), as a survey's row reads; no `hotkey`, the label alone.
839 *
840 * A one-glyph label (`'\u{1F50A}'`, a speaker) is then a control by
841 * itself: the focus and the pointer still invert it, `dimColor` and `hover`
842 * still apply. A desktop draws its native button either way.
843 */
844 plain?: true;
845 /**
846 * The label drawn dim at rest, as `Text`'s `dimColor`, and at full strength
847 * under the pointer or the focus: a secondary control, a path in a list.
848 */
849 dimColor?: boolean;
850 /**
851 * The site's focus ring starts here when the site takes the keyboard,
852 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
853 *
854 * A pane opened with `focus`, or the person's focus chord or click, is the
855 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
856 * origin this plugin. A ring the person has moved stays where it was put.
857 */
858 autoFocus?: true;
859 /**
860 * Label style overrides (the `Text` set) applied by the surface while the
861 * nearest enclosing keyed `Box`, or given a `scope` its group, is hovered.
862 *
863 * No hook runs and nothing crosses to the plugin; under the pointer itself
864 * the button inverts as it always has. Refused outside a keyed Box unless
865 * it names a `scope`.
866 */
867 hover?: TextHoverProps;
868 /**
869 * What the press runs, in the plugin's own environment: the bottom of the
870 * `ui.press` chain. The host holds only a handle, for the drawing's life.
871 */
872 onPress: () => void;
873 };
874
875 /**
876 * The handler `on(...).catch(handler)` takes for a hook of type `F`: the
877 * hook's `($, e, next)`, run afresh when it throws, misreturns or overruns.
878 *
879 * `next` carries `error` and `called` (Caught) and is replay-safe; a return
880 * within the grace is the hook's result, `undefined` the hook absent. On a
881 * streaming event the handler is a generator too, continuing the stream.
882 */
883 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;
884
885 /**
886 * What `next` carries into a `.catch` handler and nowhere else: why the
887 * hook failed, and whether it had called `next` before it did.
888 *
889 * There `next` is replay-safe: when `called`, `next(e)` resolves to what the
890 * hook's last call settled to, nothing beneath running again, the argument
891 * unread; when not, it runs the hooks beneath once and a later call replays.
892 */
893 export type Caught = {
894 /**
895 * Why the hook failed (HookFailure); undefined on an ordinary hook's
896 * `next`, so its presence says a handler is running.
897 */
898 readonly error: HookFailure;
899 /**
900 * True when the failed hook had called `next()` or `next.to()` at least
901 * once, settled or in flight; the handler runs once that call settled.
902 */
903 readonly called: boolean;
904 };
905
906 /**
907 * What a hook on streaming event `N` yields, and what its `next(e)` yields
908 * to it (ChunkOf by name).
909 */
910 export type Chunk<N extends StreamingEventName = StreamingEventName> = ChunkOf[N];
911
912 /**
913 * The chunk type of each streaming event, by name: what its stream yields.
914 */
915 export type ChunkOf = {
916 /**
917 * One piece of the model's response (TurnStepChunk).
918 */
919 'turn.step': TurnStepChunk;
920 };
921
922 /**
923 * What every `turn.step` chunk may carry: the engine's handle on the item
924 * of its own stream the chunk was read off, absent on a chunk a hook made.
925 *
926 * A hook that passes a chunk on, or rewrites it by spreading it, keeps the
927 * handle, and whatever it left unchanged reaches the engine as the engine
928 * streamed it; a chunk built afresh has none and is taken at its word.
929 */
930 type ChunkRef = {
931 /**
932 * The engine's handle on its own streamed item; opaque, this step's only.
933 */
934 ref?: number;
935 };
936
937 /**
938 * The name of a classic hook event as a function-hooks event: the settings
939 * hook's own name under `classic` (`classic.Stop`, `classic.PreToolUse`).
940 */
941 export type ClassicEventName = `classic.${ClassicHookEvent}`;
942
943 /**
944 * The classic (settings) hook events, one per classic event name: `e` is
945 * what the classic hook receives on stdin for that event.
946 *
947 * The chain is [managed settings hooks, ...hooks modules, the other settings
948 * hooks as core], so a managed block ends it above every module. In shape
949 * `classic.PreToolUse` alone differs: its `e` is ToolCallEnvelope, no more.
950 */
951 export type ClassicEventOf = {
952 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? ToolCallEnvelope : ClassicHookInputs[E];
953 };
954
955 /**
956 * The name of a classic hook event: `PreToolUse`, `Stop`, and the rest.
957 */
958 export type ClassicHookEvent = HookInput['hook_event_name'];
959
960 /**
961 * What a classic hook receives on stdin for each event, by event name: the
962 * Agent SDK's `<Event>HookInput`.
963 */
964 export type ClassicHookInputs = {
965 [I in HookInput as I['hook_event_name']]: I;
966 };
967
968 /**
969 * Everything a classic hook event's answer can carry, named as the classic
970 * hook's JSON output names it; each event reads its subset (ClassicResultOf).
971 *
972 * The settings hooks below fold into one of these (last write wins, contexts
973 * concatenate); a hooks module returns `next(e)`, a copy with fields changed,
974 * or its own. A field of the wrong shape fails the hook, which is skipped.
975 */
976 export type ClassicResult = {
977 /**
978 * `decision: "block"` with this text as `reason` (a command hook's exit
979 * code 2): the event's block, veto or re-prompt.
980 */
981 block?: string;
982 /**
983 * `continue: false`: the session stops after this event.
984 */
985 preventContinuation?: true;
986 /**
987 * Shown when `preventContinuation` stops the session (`stopReason`).
988 */
989 stopReason?: string;
990 /**
991 * `hookSpecificOutput.additionalContext`, one entry per hook: text handed
992 * to the model with the event.
993 */
994 additionalContext?: string[];
995 /**
996 * `hookSpecificOutput.sessionTitle` (UserPromptSubmit, SessionStart).
997 */
998 sessionTitle?: string;
999 /**
1000 * `hookSpecificOutput.suppressOriginalPrompt` (UserPromptSubmit,
1001 * UserPromptExpansion).
1002 */
1003 suppressOriginalPrompt?: true;
1004 /**
1005 * `hookSpecificOutput.initialUserMessage` (SessionStart).
1006 */
1007 initialUserMessage?: string;
1008 /**
1009 * `hookSpecificOutput.watchPaths` (SessionStart).
1010 */
1011 watchPaths?: string[];
1012 /**
1013 * `hookSpecificOutput.reloadSkills` (SessionStart).
1014 */
1015 reloadSkills?: true;
1016 /**
1017 * `hookSpecificOutput.permissionDecision` (PreModelSwitch).
1018 */
1019 permissionDecision?: 'allow' | 'deny' | 'ask';
1020 /**
1021 * `hookSpecificOutput.permissionDecisionReason` (PreModelSwitch).
1022 */
1023 permissionDecisionReason?: string;
1024 /**
1025 * `hookSpecificOutput.decision` (PermissionRequest).
1026 */
1027 decision?: PermissionRequestDecision;
1028 /**
1029 * `hookSpecificOutput.updatedToolOutput` (PostToolUse): replaces what the
1030 * model sees of the tool's result.
1031 */
1032 updatedToolOutput?: unknown;
1033 /**
1034 * `hookSpecificOutput.updatedMCPToolOutput` (PostToolUse, MCP tools only).
1035 */
1036 updatedMCPToolOutput?: unknown;
1037 /**
1038 * `hookSpecificOutput.retry` (PermissionDenied).
1039 */
1040 retry?: true;
1041 /**
1042 * `hookSpecificOutput.displayContent` (MessageDisplay).
1043 */
1044 displayContent?: string;
1045 /**
1046 * `hookSpecificOutput.worktreePath` (WorktreeCreate; a command hook prints
1047 * it): the worktree the hook created, absolute or relative to its cwd.
1048 *
1049 * Left unset, the session creates its git worktree as it would unhooked.
1050 */
1051 worktreePath?: string;
1052 };
1053
1054 /**
1055 * The event-specific fields of ClassicResult each classic event reads (its
1056 * `hookSpecificOutput`), by event; an event absent here reads none of them.
1057 *
1058 * `block`, `preventContinuation` and `stopReason` are every event's.
1059 */
1060 export type ClassicResultFields = {
1061 UserPromptSubmit: 'additionalContext' | 'sessionTitle' | 'suppressOriginalPrompt';
1062 UserPromptExpansion: 'additionalContext' | 'suppressOriginalPrompt';
1063 SessionStart: 'additionalContext' | 'initialUserMessage' | 'sessionTitle' | 'watchPaths' | 'reloadSkills';
1064 Setup: 'additionalContext';
1065 PreModelSwitch: 'permissionDecision' | 'permissionDecisionReason';
1066 PostModelSwitch: 'additionalContext';
1067 SubagentStart: 'additionalContext';
1068 PostToolUse: 'additionalContext' | 'updatedToolOutput' | 'updatedMCPToolOutput';
1069 PostToolUseFailure: 'additionalContext';
1070 PostToolBatch: 'additionalContext';
1071 Stop: 'additionalContext';
1072 SubagentStop: 'additionalContext';
1073 PermissionDenied: 'retry';
1074 PermissionRequest: 'decision';
1075 MessageDisplay: 'displayContent';
1076 WorktreeCreate: 'worktreePath';
1077 };
1078
1079 /**
1080 * What each classic hook event's hook returns and its `next(e)` resolves to:
1081 * the event's own subset of ClassicResult.
1082 *
1083 * `classic.PreToolUse` keeps its `allow` / `ask` / `deny` result
1084 * (PreToolUseResult).
1085 */
1086 export type ClassicResultOf = {
1087 [E in ClassicHookEvent as `classic.${E}`]: E extends 'PreToolUse' ? PreToolUseResult : Pick<ClassicResult, 'block' | 'preventContinuation' | 'stopReason' | (E extends keyof ClassicResultFields ? ClassicResultFields[E] : never)>;
1088 };
1089
1090 /**
1091 * Options of `$.model.classify`.
1092 */
1093 export type ClassifyOptions = {
1094 /**
1095 * An alias (`haiku`) or a full model id; default the engine's small fast
1096 * model.
1097 */
1098 model?: string;
1099 };
1100
1101 /**
1102 * The element table a surface module draws with, `surface.elements`: the
1103 * terminal's (Elements) less `Client` (none nests), `Raster` and `Image`.
1104 *
1105 * What `$.ui.resolve(e)` is to a hooks module; a Button, Input or Select
1106 * keeps its handler here. A tree of them keeps every tree's bounds (20,000
1107 * nodes, 32 deep, 100,000 characters serialized) or the instance unmounts.
1108 */
1109 export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster' | 'Image'>;
1110
1111 /**
1112 * One key the person pressed while a `Client` had the focus, as
1113 * `surface.onKey` hands it. Escape never arrives: it returns the focus.
1114 */
1115 export type ClientKeyEvent = {
1116 /**
1117 * A special key's name (`up`, `down`, `left`, `right`, `return`, `tab`,
1118 * `backspace`, `delete`, `pageup`, `home`, ...) or the character typed.
1119 */
1120 key: string;
1121 /**
1122 * Modifier keys held with it, each present only when true.
1123 */
1124 ctrl?: true;
1125 shift?: true;
1126 meta?: true;
1127 };
1128
1129 /**
1130 * The component a surface module exports (default, or its one PascalCase
1131 * export): from props and surface to the tree drawn (no nested `Client`).
1132 *
1133 * Runs on the drawing thread, a second per call at most; `h` and `Fragment`
1134 * are the environment's, so nothing of the module's takes those names. A
1135 * throw, an overrun or a tree past the bounds (ClientElements) unmounts it.
1136 *
1137 * @example
1138 * const Tag: ClientModule<string> = (t, s) => s.elements.Text({ children: t })
1139 */
1140 export type ClientModule<P extends JsonValue = JsonValue, S = unknown> = (props: P, surface: ClientSurface<S>) => RenderElement;
1141
1142 /**
1143 * One pointer event over a `Client`'s region, as `surface.onPointer` hands
1144 * it: region-relative cells, and the sub-cell position where known.
1145 *
1146 * After a `down` in the region the instance holds the pointer until the
1147 * `up`: every `move` reaches it, past the edges too (negative, or beyond
1148 * `columns`/`rows`), and the transcript neither selects nor scrolls.
1149 */
1150 export type ClientPointerEvent = {
1151 type: ClientPointerType;
1152 /**
1153 * The column under the pointer, 0 at the region's left edge; on `enter`
1154 * and `leave`, the last column a move reported.
1155 */
1156 x: number;
1157 /**
1158 * The row under the pointer, 0 at the region's top edge.
1159 */
1160 y: number;
1161 /**
1162 * The same position with the fraction of a cell kept (`x: 12`, `fine.x:
1163 * 12.375`), where the surface knows it: a terminal that reports pixels.
1164 *
1165 * kitty, Ghostty, iTerm2, WezTerm and foot do; tmux passes none through.
1166 * Absent elsewhere and on `enter`/`leave`; present, a `move` comes within
1167 * a cell too. What a module showing another program's pixels forwards.
1168 *
1169 * @example
1170 * surface.onPointer(e => click((e.fine?.x ?? e.x + 0.5) * pixelsPerCell))
1171 */
1172 fine?: {
1173 x: number;
1174 y: number;
1175 };
1176 /**
1177 * Which button is down (`down`, `move` while held) or came up (`up`);
1178 * absent on a hover `move`, `enter` and `leave`.
1179 */
1180 button?: 'left' | 'middle' | 'right';
1181 /**
1182 * Modifier keys the terminal reported held, each present only when true.
1183 */
1184 shift?: true;
1185 alt?: true;
1186 ctrl?: true;
1187 };
1188
1189 /**
1190 * What the pointer did over a `Client`'s region: a button went down, the
1191 * pointer moved, the button came up, or the pointer crossed the region's edge.
1192 */
1193 export type ClientPointerType = 'down' | 'move' | 'up' | 'enter' | 'leave';
1194
1195 /**
1196 * The props of `Client`: which of the plugin's surface modules draws here,
1197 * under what key, with what data, in how much room.
1198 */
1199 export type ClientProps = {
1200 /**
1201 * The instance's address within the drawing: two `Client`s of one plugin in
1202 * one tree take two keys. What `e.element` carries at `ui.message`.
1203 *
1204 * The engine keeps the instance (its local state, its timers) across the
1205 * plugin's redraws while a `Client` under this key stays in the tree.
1206 */
1207 key: string;
1208 /**
1209 * The surface module's path, a string literal relative to this file:
1210 * `module: "./<name>.tsx"` (or `.jsx`, `.ts`, `.js`, `.mjs`).
1211 *
1212 * Read off the source: a variable there is refused at load, as is a path
1213 * outside the plugin or naming no file. Its default export draws, else
1214 * its one PascalCase export; loaded, the tree carries the plugin's path.
1215 */
1216 module: string;
1217 /**
1218 * Plain data (JsonValue) handed to the module function; a new value on a
1219 * redraw reaches the running instance, its state kept.
1220 *
1221 * Bounded as a tree's text is; not a channel for closures.
1222 * Typed `unknown` so a matcher over a tree stays shallow.
1223 */
1224 props?: unknown;
1225 /**
1226 * Columns the instance's region takes: a count, or a percentage of the
1227 * parent. Absent, the region is as wide as what the module draws.
1228 */
1229 width?: number | string;
1230 /**
1231 * Rows the instance's region takes: a count, or a percentage of the parent.
1232 * Absent, the region is as tall as what the module draws.
1233 */
1234 height?: number | string;
1235 /**
1236 * How the region grows into free room along the parent's direction, as a
1237 * Box's `flexGrow`.
1238 */
1239 flexGrow?: number;
1240 };
1241
1242 /**
1243 * What a surface module's function receives as its second argument: its
1244 * elements, the instance's local state, its region, input, clock and port.
1245 *
1246 * Called again (same `surface`, same `state`) on new props, after
1247 * `setState`, and on a resize; what it returns is drawn in the region. No
1248 * `$` here: the hooks module has it, and `post` is the way to reach it.
1249 */
1250 export type ClientSurface<S = unknown> = {
1251 /**
1252 * The surface's element table (ClientElements), the tags the module draws
1253 * with: `const { Box, Text } = surface.elements`. No `Client` in it.
1254 */
1255 readonly elements: ClientElements;
1256 /**
1257 * The instance's local state: `undefined` until the first `setState`.
1258 * Kept across the plugin's redraws; dropped with the instance.
1259 */
1260 readonly state: S | undefined;
1261 /**
1262 * Replaces the local state and schedules one more call of the function on
1263 * the next frame; several calls before it coalesce into one redraw.
1264 *
1265 * A `setState` on each of three renders in a row with no key, pointer,
1266 * tick, press or props between is a render loop: the instance unmounts.
1267 */
1268 setState: (next: S) => void;
1269 /**
1270 * The region's width in cells, as last laid out (0 before the first
1271 * layout).
1272 */
1273 readonly columns: number;
1274 /**
1275 * The region's height in cells, as last laid out (0 before the first
1276 * layout).
1277 */
1278 readonly rows: number;
1279 /**
1280 * Calls `fn` every `ms` milliseconds on the surface's frame clock until
1281 * the returned function is called or the instance unmounts.
1282 *
1283 * Start it once (while `state` is still undefined), not on every call.
1284 */
1285 every: (ms: number, fn: () => void) => () => void;
1286 /**
1287 * Sets the instance's pointer listener (one; a later call replaces it)
1288 * and returns what clears it. See ClientPointerEvent for capture.
1289 */
1290 onPointer: (fn: (event: ClientPointerEvent) => void) => () => void;
1291 /**
1292 * Sets the instance's key listener (one; a later call replaces it),
1293 * reached while a click has given it the focus; Escape returns that.
1294 */
1295 onKey: (fn: (event: ClientKeyEvent) => void) => () => void;
1296 /**
1297 * Sends plain data to the plugin's hooks module: `e.data` of a
1298 * `ui.message` only that plugin's hooks see, one per frame at most.
1299 *
1300 * A later post in the same frame replaces an undelivered one; a hook
1301 * answering `{ props }` hands this instance its next props. At most
1302 * 20,000 values, 32 deep, 100,000 characters, or the post is not sent.
1303 */
1304 post: (data: JsonValue) => void;
1305 };
1306
1307 /**
1308 * The argument of the `$.clock` waits (`sleep`, `after`, `every`): how long,
1309 * in milliseconds, before the dispatch resolves.
1310 */
1311 type ClockWait = {
1312 /**
1313 * The wait, a non-negative number of milliseconds.
1314 */
1315 ms: number;
1316 };
1317
1318 /**
1319 * The props of `Code`, source text every surface draws with the engine's own
1320 * highlighter: coloured tokens, a line gutter on request, or a unified diff.
1321 *
1322 * A leaf: no children. `source` is the element's data as a string is a
1323 * Text's, bounded and free of control characters the same way; the colour
1324 * on screen is the engine's, never the plugin's.
1325 */
1326 export type CodeProps = {
1327 /**
1328 * The text drawn: source code, or under `format: 'diff'` one or more
1329 * unified-diff hunks.
1330 *
1331 * At most 10000 characters; tab and newline are the only control
1332 * characters it may hold.
1333 */
1334 source: string;
1335 /**
1336 * A highlighter language id or alias (`typescript`, `ts`, `py`), a
1337 * plugin-contributed grammar's included.
1338 *
1339 * Absent, the language is inferred from `path`; when neither resolves,
1340 * the text is drawn plain.
1341 */
1342 language?: string;
1343 /**
1344 * A file path the language is inferred from when `language` is absent:
1345 * its extension or name, else a shebang on the first line.
1346 *
1347 * Drawn nowhere and never read: nothing touches the disk.
1348 */
1349 path?: string;
1350 /**
1351 * The 1-based number of the first line of `source`: present, a dim
1352 * right-aligned gutter numbers the lines from it; absent, no gutter.
1353 *
1354 * Ignored under `format: 'diff'`, whose hunks carry their own numbers.
1355 */
1356 startLine?: number;
1357 /**
1358 * `'source'` (the default) draws `source` as code; `'diff'` reads it as
1359 * unified-diff hunks and draws gutters, markers, add and remove colouring.
1360 *
1361 * A hunk is `@@ -a,b +c,d @@` then lines starting ` `, `+` or `-`; a
1362 * leading `---`/`+++` pair and `\ No newline at end of file` are read
1363 * past. A source that does not parse as hunks is refused.
1364 */
1365 format?: 'source' | 'diff';
1366 /**
1367 * What a line wider than the room does, in Text's `wrap` vocabulary:
1368 * `'wrap'` (the default) continues it on rows under the gutter.
1369 *
1370 * `'truncate-end'` cuts it at the edge with an ellipsis; Text's other
1371 * spellings are refused, since a gutter leaves them no sense here.
1372 */
1373 wrap?: 'wrap' | 'truncate-end';
1374 };
1375
1376 /**
1377 * The input of `command.describe`: how one slash command presents in the
1378 * typeahead and `/help`, at the moment the engine lists it.
1379 */
1380 export type CommandDescribeInput = {
1381 /**
1382 * Names the command without its slash; the key a matcher narrows on. A
1383 * rewrite is refused.
1384 */
1385 command: string;
1386 /**
1387 * The one-line description the menu shows, as the command declares it.
1388 */
1389 description: string;
1390 /**
1391 * The hint drawn dim after the name (`[name]`), when the command has one.
1392 */
1393 argumentHint?: string;
1394 /**
1395 * Whether the typeahead and `/help` leave the command out; a hidden
1396 * command still runs when typed in full.
1397 */
1398 isHidden: boolean;
1399 /**
1400 * Whether the command declares it runs at once when typed mid-turn,
1401 * instead of waiting for the turn to end.
1402 *
1403 * One that decides per invocation reads false. Read only: not part of
1404 * what a hook answers, and a rewrite is refused.
1405 */
1406 immediate: boolean;
1407 /**
1408 * Who provides this command: the plugin and its tier; `{ plugin: "engine",
1409 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
1410 */
1411 provider: Origin;
1412 };
1413
1414 /**
1415 * What a `command.describe` hook returns: the description, hint and hidden
1416 * flag the menu uses; the name, `immediate` and `provider` stay as they were.
1417 */
1418 export type CommandDescribeResult = Omit<CommandDescribeInput, 'command' | 'immediate' | 'provider'>;
1419
1420 /**
1421 * One slash command as `$.command.list()` returns it.
1422 */
1423 export type CommandInfo = {
1424 /**
1425 * What the person runs it by, without the slash.
1426 */
1427 name: string;
1428 /**
1429 * The one line the typeahead shows for it.
1430 */
1431 description: string;
1432 /**
1433 * Where it comes from (CommandSource).
1434 */
1435 source: CommandSource;
1436 /**
1437 * Which plugin added it, when `source` is `plugin` and the engine knows:
1438 * the one that registered it, or whose manifest carries it.
1439 */
1440 plugin?: string;
1441 };
1442
1443 /**
1444 * Where a command's answer will show: which of the terminal's two layouts
1445 * the surface renders, and how wide it is when the command runs.
1446 *
1447 * A fact the engine stamps on `command.run`, so a command that draws (opens
1448 * a pane, prints a wide table) can suit the room it has: the fullscreen
1449 * layout docks a pane beside the transcript from 110 columns, the main
1450 * screen places it inline above the prompt at any width.
1451 */
1452 export type CommandPresentation = {
1453 /**
1454 * True under the fullscreen (alternate-screen) layout; false on the main
1455 * screen (`CLAUDE_CODE_NO_FLICKER=0`, tmux by default) and headless.
1456 *
1457 * The fact `RenderViewport`'s `isFullscreen` carries on every terminal
1458 * drawing, from the same source: the two agree.
1459 */
1460 isFullscreen: boolean;
1461 /**
1462 * The terminal's width in cells as the command runs; 80 where no terminal
1463 * has measured (headless with no tty).
1464 */
1465 columns: number;
1466 };
1467
1468 /**
1469 * `command.run`'s input as a plugin's `$.command.run` takes it: `args` may
1470 * be left out (`/command`, bare); `origin` and `presentation` the engine sets.
1471 */
1472 export type CommandRunArgs = Omit<CommandRunInput, 'origin' | 'args' | 'presentation'> & {
1473 /**
1474 * Everything after the name, as the person would type it; left out, `""`.
1475 */
1476 args?: string;
1477 };
1478
1479 /**
1480 * The input of `command.run`: one slash command about to run, the way the
1481 * person typed it (`/name args`), and where the run came from.
1482 */
1483 export type CommandRunInput = {
1484 /**
1485 * Names the command without its slash (`compact`, `hello`), aliases and
1486 * folds resolved; the key a matcher narrows on. A rewrite is refused.
1487 */
1488 command: string;
1489 /**
1490 * Everything after the name, as typed (`""` when nothing was); a hook
1491 * rewrites it with `next({ ...e, args })`.
1492 */
1493 args: string;
1494 /**
1495 * Where the run came from, in `prompt.submit`'s words (PromptOrigin):
1496 * the person's Enter (`composer`), the bridge, the SDK, or a plugin.
1497 *
1498 * A plugin's `$.command.run` reads `{ kind: 'plugin', name }`. `next(e)`
1499 * passes it on as received.
1500 */
1501 origin: PromptOrigin;
1502 /**
1503 * Where the command's answer will show (CommandPresentation): the
1504 * fullscreen layout or the main screen, and the terminal's width.
1505 *
1506 * Pinned: the engine stamps it, `next(e)` passes it on, a rewrite that
1507 * leaves it out keeps it and one that changes it is refused.
1508 */
1509 presentation: CommandPresentation;
1510 };
1511
1512 /**
1513 * What a `command.run` hook returns and what `next(e)` and `$.command.run`
1514 * resolve to: the command's output text and the notes it leaves the model.
1515 *
1516 * From core, `text` is what the command printed (a `local` command's
1517 * returned text; a panel command may print nothing), `context` what it
1518 * recorded for the model beside that, and `ref` names the run.
1519 *
1520 * A hook's own answer without `next` runs no command: its `text` is shown
1521 * as the command's output, under the names of the plugins hooking the
1522 * command unless each is bundled with Claude Code, whose answer reads as
1523 * the built-in command's own, and its `context` is recorded after it.
1524 *
1525 * Both are the plugin's to size, as a core command's output is; what bounds
1526 * them is what bounds any transcript row where a surface draws it.
1527 */
1528 export type CommandRunResult = {
1529 /**
1530 * The command's output as a transcript line, or undefined when the
1531 * command showed nothing as text (a panel, a prompt for the model).
1532 */
1533 text?: string;
1534 /**
1535 * What the model reads after the command's output and the person never
1536 * sees, each entry one hidden user message recorded after the output row.
1537 *
1538 * From core, the notes the command left the model, absent when none. Kept
1539 * whole from `next`: left out after `next`, the last answer's notes ride
1540 * along; written, it keeps every entry that answer had (none empty).
1541 */
1542 context?: readonly string[];
1543 /**
1544 * Set by core on what `next(e)` resolves to: names the engine's run of
1545 * the command (its result stays on the host side).
1546 *
1547 * A hook that returns the object it got makes the engine use that run
1548 * verbatim. Absent on a hook's own `{ text }` and on `$.command.run`'s.
1549 */
1550 ref?: number;
1551 };
1552
1553 /**
1554 * Where a slash command comes from, as `$.command.list()` tells them apart.
1555 *
1556 * `builtin` ships with Claude Code; `plugin` is a plugin's markdown command,
1557 * skill or `$.command.register`; `user` is the user's or project's own
1558 * file; `mcp` an MCP server's prompt.
1559 */
1560 export type CommandSource = 'builtin' | 'plugin' | 'user' | 'mcp';
1561
1562 /**
1563 * What `$.command.register` takes: the slash command this plugin serves.
1564 */
1565 export type CommandSpec = {
1566 /**
1567 * The command's name without the slash (letters, digits, `_`, `-`; up to
1568 * 64); the person runs it as `/<name>`.
1569 */
1570 name: string;
1571 /**
1572 * The one line the typeahead and `/help` show for it.
1573 */
1574 description: string;
1575 /**
1576 * The hint drawn dim after the name (`[name]`), when it takes arguments.
1577 */
1578 argumentHint?: string;
1579 /**
1580 * Set so that `/<name>` typed while a turn is in flight runs at once
1581 * instead of waiting for the turn to end, as it does when left out.
1582 *
1583 * Its `command.run` hook then runs while a turn may still be streaming and
1584 * must not assume the turn's state (what the transcript holds, whether a
1585 * tool is mid-call); its `{ text }` prints as an idle run's does.
1586 */
1587 immediate?: true;
1588 };
1589
1590 type ConfigChangeHookInput = BaseHookInput & {
1591 hook_event_name: 'ConfigChange';
1592 source: 'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills';
1593 file_path?: string;
1594 };
1595
1596 /**
1597 * The input of `config.describe`: how one `/config` row presents, at the
1598 * moment the menu lists it (and for `$.config.list`).
1599 */
1600 export type ConfigDescribeInput = {
1601 /**
1602 * Names the row, as `config.set`'s `key` does; the key a matcher narrows
1603 * on. Pinned: a rewrite is refused.
1604 */
1605 key: string;
1606 /**
1607 * What the menu draws for the row, before its value.
1608 */
1609 label: string;
1610 /**
1611 * The help text beneath the label, when the row has one (a plugin
1612 * field's `description`); absent for the panel's own rows.
1613 */
1614 description?: string;
1615 /**
1616 * Whether the menu leaves the row out; a hidden row still answers
1617 * `$.config.set` and `/config key=value`.
1618 */
1619 isHidden: boolean;
1620 /**
1621 * Who owns the row, as `config.set`'s `provider`. Pinned.
1622 */
1623 provider: Origin;
1624 };
1625
1626 /**
1627 * What a `config.describe` hook returns: the label, help text and hidden
1628 * flag the menu uses; the key and provider stay as they were.
1629 */
1630 export type ConfigDescribeResult = Omit<ConfigDescribeInput, 'key' | 'provider'>;
1631
1632 /**
1633 * How a `/config` row takes its value: `boolean` toggles, `choice` picks one
1634 * of its `options`, `text` takes a string, `number` a number.
1635 */
1636 export type ConfigKind = 'boolean' | 'choice' | 'text' | 'number';
1637
1638 /**
1639 * Where a `config.set` came from, in `prompt.submit`'s words: the person
1640 * in the `/config` menu (`composer`), the bridge, or a plugin, named.
1641 *
1642 * Set by the engine; `next(e)` passes it on as received and none sets it.
1643 */
1644 export type ConfigOrigin = {
1645 /**
1646 * The person's own change in the `/config` menu (a toggle, a pick, a
1647 * typed value), or their `/config key=value`.
1648 */
1649 kind: 'composer';
1650 } | {
1651 /**
1652 * A `/config key=value` that arrived over the Remote Control bridge (a
1653 * phone or web client, or a relay): not attestably the owner's hand.
1654 */
1655 kind: 'bridge';
1656 } | {
1657 /**
1658 * A plugin's `$.config.set`; that plugin's own hooks do not see it.
1659 */
1660 kind: 'plugin';
1661 /**
1662 * The calling plugin's name.
1663 */
1664 name: string;
1665 };
1666
1667 /**
1668 * One `/config` row as `$.config.list()` returns it: what the menu would
1669 * draw now, after every `config.describe` hook, a hidden row left out.
1670 */
1671 export type ConfigRow = {
1672 /**
1673 * Names the row: the panel's id for a built-in, `<plugin>.<field>` for a
1674 * plugin's `userConfig` field; what `$.config.set` takes.
1675 */
1676 key: string;
1677 /**
1678 * What the menu draws for the row, before its value.
1679 */
1680 label: string;
1681 /**
1682 * The help text under the label, when the row has one.
1683 */
1684 description?: string;
1685 /**
1686 * How the row takes its value (ConfigKind).
1687 */
1688 kind: ConfigKind;
1689 /**
1690 * What the row holds now.
1691 */
1692 value: ConfigValue;
1693 /**
1694 * The values a `choice` row takes, in order (a plugin string field's
1695 * declared `options` for its row); absent otherwise.
1696 */
1697 options?: readonly string[];
1698 /**
1699 * Who owns the row: the engine for the panel's own, else the plugin.
1700 */
1701 provider: Origin;
1702 /**
1703 * Whether a trusted source (managed settings, the organization's policy)
1704 * owns the value, so the menu shows it and refuses a change.
1705 */
1706 isLocked: boolean;
1707 };
1708
1709 /**
1710 * `config.set`'s input as a plugin's `$.config.set(args)` takes it: the
1711 * row's key and the value; the engine fills the rest.
1712 */
1713 export type ConfigSetArgs = Pick<ConfigSetInput, 'key' | 'value'>;
1714
1715 /**
1716 * The input of `config.set`: one `/config` row about to change, from the
1717 * menu or a plugin's `$.config.set`, with what it holds now and who owns it.
1718 */
1719 export type ConfigSetInput = {
1720 /**
1721 * Names the row: the panel's own id for a built-in (`theme`, `verbose`,
1722 * `autoCompact`), `<plugin>.<field>` for a plugin's `userConfig` field.
1723 *
1724 * The key a matcher narrows on; pinned: a rewrite is refused.
1725 */
1726 key: string;
1727 /**
1728 * What the row is being set to; `next({ ...e, value })` clamps or
1729 * replaces it, held to the row's kind (a toggle takes a boolean).
1730 */
1731 value: ConfigValue;
1732 /**
1733 * What the row holds before the change, as the menu shows it. Pinned.
1734 */
1735 previous: ConfigValue;
1736 /**
1737 * Who owns the row: `{ plugin: "engine", tier: "core" }` for the panel's
1738 * own, the plugin and its tier for a `userConfig` field. Pinned.
1739 */
1740 provider: Origin;
1741 /**
1742 * Where the change came from (ConfigOrigin): the person in the menu
1743 * (`composer`) or a plugin's `$.config.set`. Pinned.
1744 */
1745 origin: ConfigOrigin;
1746 };
1747
1748 /**
1749 * What a `config.set` hook returns and what `next(e)` resolves to:
1750 * `{ value }` once written, or `{ deny: reason }`, the row left as it was.
1751 *
1752 * The menu shows a deny's reason beside the row; a plugin's `$.config.set`
1753 * resolves with it.
1754 */
1755 export type ConfigSetResult = {
1756 value: ConfigValue;
1757 deny?: undefined;
1758 } | {
1759 deny: string;
1760 value?: undefined;
1761 };
1762
1763 /**
1764 * A `/config` row's value as a hook and `$.config` see it: a toggle's
1765 * boolean, a choice's or a text's string, a number, or a list of strings.
1766 */
1767 export type ConfigValue = boolean | string | number | readonly string[];
1768
1769 /**
1770 * One custom agent whose description the Agent tool's prompt carries;
1771 * built-in agents are left out.
1772 */
1773 export type ContextAgent = {
1774 /**
1775 * The agent's type, as the Agent tool names it.
1776 */
1777 agentType: string;
1778 /**
1779 * Where it was defined, by the engine's word (`projectSettings`,
1780 * `userSettings`, `plugin`); the display label is the renderer's.
1781 */
1782 source: string;
1783 /**
1784 * The description's estimated tokens.
1785 */
1786 tokens: number;
1787 };
1788
1789 /**
1790 * The token counts the last API response of the live window reported, as
1791 * the API spells them; the breakdown's `Messages` row is reconciled to it.
1792 */
1793 export type ContextApiUsage = {
1794 /**
1795 * Uncached input tokens the response was answered over.
1796 */
1797 input_tokens: number;
1798 /**
1799 * Tokens the response generated.
1800 */
1801 output_tokens: number;
1802 /**
1803 * Input tokens written to the prompt cache by the request.
1804 */
1805 cache_creation_input_tokens: number;
1806 /**
1807 * Input tokens read from the prompt cache by the request.
1808 */
1809 cache_read_input_tokens: number;
1810 };
1811
1812 /**
1813 * How a context breakdown is counted: `full` with the token-count API per
1814 * category, `summary` from the last response's usage and local estimates.
1815 *
1816 * The SDK's `get_context_usage` takes the same two words as its `detail`.
1817 */
1818 export type ContextBreakdownDetail = 'summary' | 'full';
1819
1820 /**
1821 * One row of the breakdown, as /context lists it beside the grid (`System
1822 * prompt`, `Messages`, `Free space`, `Autocompact buffer`).
1823 */
1824 export type ContextCategory = {
1825 /**
1826 * The row's label as /context prints it.
1827 */
1828 name: string;
1829 /**
1830 * The row's estimated tokens; a `deferred` row's do not count toward the
1831 * total.
1832 */
1833 tokens: number;
1834 /**
1835 * The theme colour /context draws the row and its squares in, by its key
1836 * in the theme (`promptBorder`, `inactive`, `permission`).
1837 */
1838 color: string;
1839 /**
1840 * Whether the row is tool schemas loaded on demand, which the grid leaves
1841 * out; the same fact as `kind` `deferred`.
1842 */
1843 isDeferred: boolean;
1844 /**
1845 * What the row is (ContextCategoryKind), stamped by the engine.
1846 */
1847 kind: ContextCategoryKind;
1848 };
1849
1850 /**
1851 * What a breakdown row is; branch on this, never on the row's `name`.
1852 *
1853 * `used` content occupies the window, `free` is the window left, `buffer`
1854 * the compaction reserve, `deferred` tool schemas loaded on demand and
1855 * outside the window.
1856 */
1857 export type ContextCategoryKind = 'used' | 'free' | 'buffer' | 'deferred';
1858
1859 /**
1860 * One square of the grid /context draws: which row it belongs to and how
1861 * full it is.
1862 */
1863 export type ContextGridSquare = {
1864 /**
1865 * The theme colour of the square's row, by its key in the theme.
1866 */
1867 color: string;
1868 /**
1869 * Whether the square holds any of its row's tokens.
1870 */
1871 isFilled: boolean;
1872 /**
1873 * The `name` of the row the square belongs to (`Free space` for the
1874 * window left).
1875 */
1876 categoryName: string;
1877 /**
1878 * The row's tokens, repeated on each of its squares.
1879 */
1880 tokens: number;
1881 /**
1882 * The row's share of the window as a whole percentage, repeated likewise.
1883 */
1884 percentage: number;
1885 /**
1886 * How full this one square is, 0 to 1: a row's last square is the partial
1887 * one (/context draws it hollow under 0.7).
1888 */
1889 squareFullness: number;
1890 };
1891
1892 /**
1893 * One MCP tool's schema as the context carries it.
1894 */
1895 export type ContextMcpTool = {
1896 /**
1897 * The tool's wire name (`mcp__linear__create_issue`).
1898 */
1899 name: string;
1900 /**
1901 * The server it belongs to, as /mcp lists it.
1902 */
1903 serverName: string;
1904 /**
1905 * The schema's estimated tokens.
1906 */
1907 tokens: number;
1908 /**
1909 * Whether the schema is inside the window now: always, unless tool
1910 * schemas load on demand and this one has not been searched for yet.
1911 */
1912 isLoaded: boolean;
1913 };
1914
1915 /**
1916 * One memory file the context carries (a CLAUDE.md, a rules file, an
1917 * auto-memory entry).
1918 */
1919 export type ContextMemoryFile = {
1920 /**
1921 * The file's path, absolute.
1922 */
1923 path: string;
1924 /**
1925 * The display label of where it was loaded from (`Project`, `User`,
1926 * `Local`, `Managed`, `AutoMem`).
1927 */
1928 type: string;
1929 /**
1930 * The file's estimated tokens.
1931 */
1932 tokens: number;
1933 };
1934
1935 /**
1936 * One skill whose listing the context carries.
1937 */
1938 export type ContextSkill = {
1939 /**
1940 * The skill's name as `/skills` lists it.
1941 */
1942 name: string;
1943 /**
1944 * Where it came from, by the engine's word (`userSettings`, `plugin`,
1945 * `built-in`, `mcp`, `syncedSkills`); the display label is the renderer's.
1946 */
1947 source: string;
1948 /**
1949 * The providing plugin's name, when the skill comes from one.
1950 */
1951 pluginName?: string;
1952 /**
1953 * The listing's estimated tokens.
1954 */
1955 tokens: number;
1956 };
1957
1958 /**
1959 * The skills the context lists for the model: how many there are, how many
1960 * fit the listing's budget, and each one's share.
1961 */
1962 export type ContextSkills = {
1963 /**
1964 * How many skills the session has.
1965 */
1966 totalSkills: number;
1967 /**
1968 * How many the listing included within its token budget.
1969 */
1970 includedSkills: number;
1971 /**
1972 * The listing's tokens in all.
1973 */
1974 tokens: number;
1975 /**
1976 * One entry per listed skill.
1977 */
1978 skillFrontmatter: ContextSkill[];
1979 };
1980
1981 /**
1982 * The slash commands the Skill tool's prompt lists, counted.
1983 */
1984 export type ContextSlashCommands = {
1985 /**
1986 * How many commands the session has.
1987 */
1988 totalCommands: number;
1989 /**
1990 * How many the listing included.
1991 */
1992 includedCommands: number;
1993 /**
1994 * The listing's tokens in all.
1995 */
1996 tokens: number;
1997 };
1998
1999 /**
2000 * How the window the breakdown measures against was settled; /context
2001 * prints its `Auto-compact window` line off this.
2002 *
2003 * `auto` is the model's own limit; the rest name a compaction window by who
2004 * set it: the `CLAUDE_CODE_AUTO_COMPACT_WINDOW` variable, the settings, the
2005 * account, an experiment, the model's default, or an unrecognised model's.
2006 */
2007 export type ContextWindowSource = 'env' | 'settings' | 'clientdata' | 'experiment' | 'model-default' | 'unknown-model' | 'auto';
2008
2009 /**
2010 * The plugin's identity (`plugin`) and the nouns core contributes to `$` as
2011 * the innermost step of the `engine.create` fold.
2012 *
2013 * A plugin's finished `$` (EngineInterface) has every core noun an outer
2014 * step did not withhold, and every noun the plugins' steps added.
2015 */
2016 export interface CoreEngineInterface {
2017 /**
2018 * This plugin, as loaded: its manifest name and its directory.
2019 */
2020 plugin: {
2021 /**
2022 * From plugin.json; debug-log and `$.ui.log` lines carry it.
2023 */
2024 name: string;
2025 /**
2026 * The plugin's directory (the one holding plugin.json), absolute.
2027 */
2028 root: string;
2029 };
2030 /**
2031 * Display: a line under an open dialog, a redraw or a repaint, a
2032 * transcript or debug line, panes the surface places, a window or ring.
2033 */
2034 ui: {
2035 /**
2036 * Shows `text` as one line under the dialog open for `tool_use_id`, or
2037 * removes the line when `text` is undefined.
2038 *
2039 * Core removes the line when the call resolves. A call that is not open
2040 * is refused, as is another plugin's `$.tool.call` run.
2041 *
2042 * @param tool_use_id the call whose open dialog gets the line
2043 * @param text the line to show; undefined removes it
2044 * @example
2045 * $.ui.notice(e.tool_use_id, "checked by my-plugin"); return next(e)
2046 */
2047 notice: (tool_use_id: string, text: string | undefined) => void;
2048 /**
2049 * Re-runs an event whose results the engine caches: `ui.render` draws the
2050 * instances this plugin may draw again; the others drop the cached answers.
2051 *
2052 * A render hook whose state changed (a countdown) calls it for a redraw, at
2053 * most ten a second, thirty for the shown pane and the band (calls sooner
2054 * fold); a prompt section, context or attachment hook: dropped next turn.
2055 *
2056 * @param event `ui.render`, or a cached-answer event: `prompt.section`,
2057 * `prompt.context`, `prompt.attachment`, `tool/command/config.describe`
2058 */
2059 invalidate: (event: InvalidatableEventName) => void;
2060 /**
2061 * Repaints a mounted `Raster` this plugin's own render hook drew with new
2062 * cells, or swaps a keyed `Image` it drew to a new source; no redraw.
2063 *
2064 * The surface paints the cells or source at its next frame, so blits
2065 * between frames fold into one: up to 120 a second taken, some sixty
2066 * shown. An Image swap sends one small command; a resize is a redraw.
2067 *
2068 * @param args `requestId` (the site), `key`, and `cells` (RasterProps) or
2069 * `source` (ImageSource); `columns`, `rows` (the mounted size)
2070 * @returns `{}` once the cells or source are its next frame, or `{ deny }`
2071 * (not mounted, not this plugin's, another size, cells that do
2072 * not decode, a bad source, or an Image drawing its alt there:
2073 * no placeholder images, or a file this terminal cannot read)
2074 * @example
2075 * $.clock.every(33, () => $.ui.blit({ requestId, key, cells: frame() }))
2076 * @example
2077 * await $.ui.blit({ requestId: 'browser', key: 'view',
2078 * source: { shm: name, format: 'rgb', width, height } })
2079 */
2080 blit: (args: UiBlitArgs) => Promise<UiBlitResult>;
2081 /**
2082 * The elements of the surface `e` is drawn on (Elements[e.surface]): a
2083 * frozen table of constructors, the JSX tags a render hook draws with.
2084 *
2085 * A read, not a dispatch: the engine ran `ui.resolve` (the other hooks,
2086 * then core) at load, per surface and component. Narrowed `e.surface`:
2087 * that table exactly; unnarrowed: the union, so shared names type-check.
2088 *
2089 * @param e this hook's own `ui.render` argument (its surface and
2090 * component pick the table)
2091 * @returns the surface's frozen element table (`Elements[e.surface]`)
2092 * @example
2093 * const { Box, Text } = $.ui.resolve(e)
2094 * return <Box>{await next(e)}<Text dimColor>done</Text></Box>
2095 */
2096 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
2097 /**
2098 * Appends one line to the transcript, drawn like a system notice (dim;
2099 * not sent to the model), or with `{ to: "debug" }` to the debug log alone.
2100 *
2101 * A row of its own at the next frame, in logging order; a `-p` or SDK
2102 * host receives it as `ui_log`; the debug log has every line under this
2103 * plugin's name. Raised as `ui.log`: a hook above may rewrite `e.to`.
2104 *
2105 * @param text the line's text
2106 * @param options `to`: `transcript` (the default) or `debug`
2107 * @example
2108 * $.ui.log(`prompt from ${e.origin.kind}: ${e.text.length} chars`)
2109 * @example
2110 * $.ui.log(`cache miss for ${e.tool_use_id}`, { to: "debug" })
2111 */
2112 log: (text: string, options?: UiLogOptions) => void;
2113 /**
2114 * Asks the user `question` in the engine's own AskUserQuestion dialog and
2115 * resolves to the label they chose, or the text typed under "Other".
2116 *
2117 * A `tool.call` of `AskUserQuestion` through every hook but the calling
2118 * one, drawn by `ui.render` on `AskUserQuestion`; a multi-select answer is
2119 * comma-joined. Rejects when dismissed, and in a `-p` run (no one to ask).
2120 *
2121 * @param question the question, ending in a question mark
2122 * @param options 2-4 option labels, or `{ options, header, multiSelect }`
2123 * @returns the label chosen, the chosen labels comma-joined, or free text
2124 * typed under "Other" (so compare it with the labels exactly)
2125 * @example
2126 * const mood = await $.ui.ask("How careful?", ["Bold", "Careful"])
2127 */
2128 ask: (question: string, options?: readonly string[] | AskOptions) => Promise<string>;
2129 /**
2130 * Shows `text` on the notification bar under the prompt for a few
2131 * seconds, the way the engine's own "context left" notice appears.
2132 *
2133 * It leaves the transcript and the model untouched.
2134 *
2135 * @param text the line to show; an unpaired surrogate half in it is drawn
2136 * as U+FFFD
2137 * @param options `timeoutMs`: how long it stays (default 4000)
2138 * @example
2139 * $.ui.toast(`turn took ${Math.round(e.durationMs / 1000)} s`)
2140 */
2141 toast: (text: string, options?: ToastOptions) => void;
2142 /**
2143 * Pins `text` as this plugin's status line under the prompt, beside the
2144 * engine's own pinned notices, until the next call replaces it.
2145 *
2146 * One per plugin; `undefined` removes it.
2147 *
2148 * @param text the line to keep on screen (an unpaired surrogate half is
2149 * drawn as U+FFFD); undefined clears it
2150 * @example
2151 * $.ui.status("thinking..."); return next(e)
2152 */
2153 status: (text: string | undefined) => void;
2154 /**
2155 * Opens a pane: a framed region the surface places, whose body this
2156 * plugin draws by hooking `ui.render` for `{ component: "Pane" }`.
2157 *
2158 * One instance per id (`requestId`): opening an open id retitles it; a hook
2159 * on `ui.open` may refuse it. The keyboard is the person's; unasked, it
2160 * waits undrawn below 144 columns (110 once asked), judged at each open.
2161 *
2162 * @param pane `id` (1-64 of letters, digits, `_`, `-`), `title`, `focus`,
2163 * `closeOnEscape` and `holdToasts` (a dialog), `rows` / `columns` wanted
2164 * @returns settles once the pane is open (or retitled)
2165 * @example
2166 * await $.ui.open({ id: "clock", title: "Clock" })
2167 * @example
2168 * await $.ui.open({ id: "ask", focus: true, closeOnEscape: true, rows: 9 })
2169 */
2170 open: (pane: PaneOpenArgs) => Promise<void>;
2171 /**
2172 * Closes one of the open panes; an id that is not open is left alone.
2173 *
2174 * Every close raises `ui.close`, `e.origin` naming whose it is: this call
2175 * (`plugin`), the person's mark or key (`person`), an unload (`unload`).
2176 * A hook answering without `next` keeps the pane open, save on an unload.
2177 *
2178 * @param pane `id`: the id the pane was opened under
2179 * @returns settles once the pane is gone or a hook answered for it;
2180 * rejects on a hook's `{ deny }`
2181 * @example
2182 * onPress: () => $.ui.close({ id: "clock" })
2183 */
2184 close: (pane: PaneCloseArgs) => Promise<void>;
2185 /**
2186 * Lists this plugin's own open panes (UiPane): each one's id and title,
2187 * and whether it is shown, holds the keyboard, and is placed.
2188 *
2189 * The engine's record, not the module's: a module reloaded while its
2190 * pane stayed up finds it here. Another plugin's panes are not listed.
2191 *
2192 * @returns the panes in open order, placed ones first; empty with none
2193 * @example
2194 * const isUp = (await $.ui.panes()).some(pane => pane.id === "clock")
2195 * if (!isUp) await $.ui.open({ id: "clock", title: "Clock" })
2196 */
2197 panes: () => Promise<readonly UiPane[]>;
2198 /**
2199 * Scrolls something into view as the DOM's `scrollIntoView` would: a
2200 * render instance by `requestId`, an element by `key`, a site's edge.
2201 *
2202 * A site of this plugin's (its pane, the band it draws into) moves under
2203 * the event `ui.scroll`, origin `plugin`. A transcript row moves only
2204 * while this call answers the person's own input, where one scrolls.
2205 *
2206 * @param args `to` (what), `in` (which site, required for `start` and
2207 * `end`), `block` (where it lands; `nearest` by default)
2208 * @returns `{}` once it moved, or `{ deny }` saying why not
2209 * @example
2210 * onPress: () => $.ui.scroll({ in: "log", to: "end" })
2211 */
2212 scroll: (args: UiScrollArgs) => Promise<UiScrollResult>;
2213 /**
2214 * Moves the focus ring of one of this plugin's sites onto an element it
2215 * drew there, as the DOM's `element.focus()`, while it holds the keys.
2216 *
2217 * Raised as the event `ui.focus`, origin `plugin`; the engine's inverse
2218 * marks the element. The keyboard is the person's to give: a site not
2219 * holding it, or holding it on another plugin's element, is `{ deny }`.
2220 *
2221 * @param args `requestId` (which site: a pane's id, the band's) and `key`
2222 * (the element's, as drawn)
2223 * @returns `{}` once it moved, or `{ deny }` saying why not
2224 * @example
2225 * onPress: () => $.ui.focus({ requestId: "files", key: "row:0" })
2226 */
2227 focus: (args: UiFocusArgs) => Promise<UiFocusResult>;
2228 };
2229 /**
2230 * Completions through the session's own client and credentials.
2231 */
2232 model: {
2233 /**
2234 * Runs one text completion through the session's own API client and
2235 * resolves to the reply's text.
2236 *
2237 * No tools, no history, no system prompt beyond the CLI's identity block
2238 * and `request.system`.
2239 *
2240 * @param request the model (an alias such as `haiku`, or a full id,
2241 * resolved like a `--model` value), the prompt, and a token cap
2242 * @returns the reply's text
2243 * @example
2244 * const reply = await $.model.complete({ model: "haiku", prompt: "Hi." })
2245 */
2246 complete: (request: ModelCompleteRequest) => Promise<string>;
2247 /**
2248 * Runs one tool-less completion over the session's OWN transcript, sharing
2249 * the main thread's prompt cache; the reply's text and the fork's usage.
2250 *
2251 * Not `complete`: sharing the cache prefix means the model and system
2252 * prompt are the session's, read from its last turn's cache-safe snapshot,
2253 * and tools are denied. Null on a cold snapshot or an API error.
2254 *
2255 * @param request the one user message the fork answers
2256 * @returns the reply's text with the fork's usage, or null on a cold
2257 * snapshot or an API error
2258 * @example
2259 * const reply = await $.model.fork({ prompt: "One line to learn?" })
2260 * if (reply !== null) $.ui.log(`${reply.usage.output_tokens} tokens`)
2261 */
2262 fork: (request: ModelForkRequest) => Promise<ModelForkResult | null>;
2263 /**
2264 * Picks one of `labels` for `text` with one completion over
2265 * `$.model.complete` and a fixed classifier prompt.
2266 *
2267 * `text` is data; the model answers with a label alone. It resolves
2268 * `undefined` when the answer named none of `labels`. A failed request,
2269 * an abort or a reply with no text rejects, naming the cause.
2270 *
2271 * @param text what to classify
2272 * @param labels the labels to choose from (2 or more)
2273 * @param options `model`: an alias or id; default the engine's small
2274 * fast model
2275 * @returns the label the model named, or undefined when it named none;
2276 * rejects when the request fails or the reply has no text
2277 * @example
2278 * const kind = await $.model.classify(e.text, ["bug", "feature"])
2279 * if (kind === undefined) return next(e)
2280 */
2281 classify: (text: string, labels: readonly string[], options?: ClassifyOptions) => Promise<string | undefined>;
2282 };
2283 /**
2284 * Sound: clip playback and platform speech.
2285 */
2286 audio: {
2287 /**
2288 * Plays one audio clip, starting now; clips are not queued, so two calls
2289 * play together (a bed under speech).
2290 *
2291 * `{ asset }` is the plugin's own file, loaded by the engine and played
2292 * through the platform's player (`afplay` on macOS). Resolves when
2293 * playback ends; rejects, naming the cause, when the clip cannot play.
2294 *
2295 * @param clip the plugin's own file (`{ asset }`), a URL the engine
2296 * fetches, or the bytes as base64 with their MIME type
2297 * @param options `shouldLoop`, `gain`, and an AbortSignal that stops the
2298 * clip
2299 */
2300 play: (clip: AudioClip, options?: PlayOptions) => Promise<void>;
2301 /**
2302 * Speaks `text` with the platform's own synthesizer (`say` on macOS).
2303 * Plain text.
2304 *
2305 * Utterances are queued among themselves; clips are not. Resolves when
2306 * the utterance has ended; rejects, naming the cause, when there is no
2307 * synthesizer, the voice is not installed, or the utterance failed.
2308 *
2309 * @param text what to say, as plain text
2310 * @param options `voice`: the system voice's exact name (`Samantha`);
2311 * absent, the synthesizer's default
2312 * @returns which synthesizer spoke, once the utterance has ended
2313 */
2314 speak: (text: string, options?: SpeakOptions) => Promise<SpeakResult>;
2315 };
2316 /**
2317 * The engine's connected MCP servers.
2318 */
2319 mcp: {
2320 /**
2321 * Calls `tool` on one of the engine's connected MCP servers with the
2322 * engine's own connection and credentials.
2323 *
2324 * A `cached` server is dialed on first use. No permission prompt: the
2325 * plugin's call, seen by the hooks above it, is the grant. Positional, not
2326 * the `{ tool: "mcp__server__tool", ... }` shape a `tool.call` hook sees.
2327 *
2328 * @param server the server's name as /mcp lists it (`claude.ai Gmail`;
2329 * the tool-name spelling `claude_ai_Gmail` is accepted too)
2330 * @param tool the tool's name on that server (`create_draft`)
2331 * @param args the tool's arguments; none when absent
2332 * @returns the tool's result as MCP returns it: `content` blocks and
2333 * `isError`
2334 * @example
2335 * const { content } = await $.mcp.call("claude.ai Gmail", "create_draft", {
2336 * to: "team@example.com",
2337 * subject: "Release notes",
2338 * })
2339 */
2340 call: (server: string, tool: string, args?: Record<string, unknown>) => Promise<McpToolResult>;
2341 };
2342 /**
2343 * The running session, read as plain data, and compacting it.
2344 */
2345 session: {
2346 /**
2347 * Returns the transcript so far, one entry per user or assistant
2348 * message; progress rows, `$.ui.log` lines and notices are not messages.
2349 *
2350 * Each entry is a SessionMessage, `{ role, text, toolUses }` (a user
2351 * message may add `toolResults`; a `toolUses` entry adds its `result` and
2352 * `text` once answered). A long transcript answers its newest 4096.
2353 *
2354 * @example
2355 * const last = (await $.session.messages()).at(-1)
2356 */
2357 messages: () => Promise<SessionMessage[]>;
2358 /**
2359 * Returns the directory the session runs in, absolute.
2360 */
2361 cwd: () => Promise<string>;
2362 /**
2363 * Returns the session's project root, absolute: where it started, or
2364 * where `/cd`, a host's directory change or a worktree move took it.
2365 *
2366 * A shell `cd` during the session does not move it; nested instruction
2367 * files are read only beneath it.
2368 */
2369 root: () => Promise<string>;
2370 /**
2371 * Returns the main loop's model, as `/model` shows it.
2372 */
2373 model: () => Promise<string>;
2374 /**
2375 * Returns how many prompts the user has sent this session (user turns in
2376 * the transcript).
2377 */
2378 turns: () => Promise<number>;
2379 /**
2380 * Returns the session's id (the transcript file's name).
2381 */
2382 id: () => Promise<string>;
2383 /**
2384 * Returns the git repository the session runs in, read from the working
2385 * copy on each call; null when the directory is not inside one.
2386 *
2387 * @example
2388 * const repo = await $.session.repo(); const publicRepo = !repo?.internal
2389 */
2390 repo: () => Promise<SessionRepo | null>;
2391 /**
2392 * Returns every surface the session draws on, each once: `terminal` under
2393 * the REPL first, then the remote ones in the order they attached.
2394 *
2395 * A session may draw on several at once (a terminal and two phones):
2396 * clients attach (`session.attach`) and detach, and a render hook still
2397 * reads `e.surface` per ask. Empty in a plain -p run; never rejects.
2398 *
2399 * @example
2400 * const inApp = (await $.session.surfaces()).some(s => s !== "terminal")
2401 */
2402 surfaces: () => Promise<readonly RenderSurface[]>;
2403 /**
2404 * Returns the first of `$.session.surfaces()`, or null where nothing
2405 * draws.
2406 *
2407 * @deprecated use `surfaces()`; a session may draw on several surfaces at
2408 * once
2409 */
2410 surface: () => Promise<RenderSurface | null>;
2411 /**
2412 * Returns the context window's fill, the rate-limit windows and the
2413 * cost, as the status line has them; with `breakdown`, by category too.
2414 *
2415 * The plain call costs nothing; `"full"` counts each category with the
2416 * token-count API as /context does, `"summary"` estimates locally, and
2417 * `context.breakdown` comes back in the SDK's `get_context_usage` shape.
2418 *
2419 * @param args `{ breakdown, columns }`: how the breakdown is counted and
2420 * the width its grid is drawn in; nothing for the status line's figures
2421 * @returns `{ context, rateLimits, cost }` as the status line has them
2422 * @example
2423 * const { context } = await $.session.usage()
2424 * if ((context.percent ?? 0) >= 85) await $.session.compact()
2425 * @example
2426 * const usage = await $.session.usage({ breakdown: "full", columns })
2427 * for (const row of usage.context.breakdown?.gridRows ?? []) draw(row)
2428 */
2429 usage: (args?: SessionUsageArgs) => Promise<SessionUsage>;
2430 /**
2431 * Compacts the conversation: the event `session.compact` with `trigger`
2432 * `plugin`, the same call `/compact` makes, between turns.
2433 *
2434 * It runs through every hook but the calling one, then core: a summary
2435 * and the kept messages in the transcript's place. Resolves `{ skip }`
2436 * when a hook vetoed it; rejects while a turn runs.
2437 *
2438 * @example
2439 * const { skip } = await $.session.compact({ instructions: "the plan" })
2440 */
2441 compact: EventCalls['session']['compact'];
2442 /**
2443 * Holds the session's Anthropic credential on the host and answers an
2444 * opaque handle and its kind; the secret never reaches the plugin.
2445 *
2446 * The handle is spent through `$.http.fetch(url, { auth: handle })`,
2447 * which sets the credential header, only for a first-party host. Null
2448 * where the build or the provider has no first-party credential to hold.
2449 *
2450 * @example
2451 * await $.http.fetch(url, { auth: (await $.session.authorize())?.handle })
2452 */
2453 authorize: () => Promise<SessionAuthorization>;
2454 };
2455 /**
2456 * The running model turn: ending it.
2457 */
2458 turn: {
2459 /**
2460 * Cancels the running model turn: the one whose id `turn.start` handed
2461 * this plugin, its running tools stopped, no interruption marker.
2462 *
2463 * The event `turn.abort`, seen by the hooks above; the prompt this
2464 * plugin submits next is the context. Rejects, naming both ids, when
2465 * `turnId` is not the running turn's; a hook may end its own turn.
2466 *
2467 * @param input `turnId`: the id `turn.start` carried
2468 * @example
2469 * on("turn.start", ($, e, next) => { held = e.turnId; return next(e) })
2470 */
2471 abort: (input: OpEventOf['turn.abort']) => Promise<void>;
2472 };
2473 /**
2474 * Submitting a prompt the model reads as a user turn, and the person's
2475 * prompt box: read as it stands, written, or proposed into.
2476 */
2477 prompt: {
2478 /**
2479 * Submits a prompt: the event `prompt.submit`, the same call the engine
2480 * makes for a typed prompt; `input.text` runs when the session is idle.
2481 *
2482 * It goes through every hook but the calling one (the plugin's others
2483 * see it) with `e.origin` `{ kind: 'plugin', name }`, the name the
2484 * model reads it under unless a hook leaves it out of its answer.
2485 *
2486 * @example
2487 * void $.prompt.submit({ text: "List the TODOs you just mentioned." })
2488 */
2489 submit: EventCalls['prompt']['submit'];
2490 /**
2491 * Returns the prompt box as it stands, the draft typed so far and the
2492 * cursor's offset into it, so a `fill` can keep what the person typed.
2493 *
2494 * Never rejects: `{ text: '', cursor: 0 }` where the session draws no box
2495 * (a -p run, an SDK host) or none is mounted yet.
2496 *
2497 * @example
2498 * const { text, cursor } = await $.prompt.read()
2499 */
2500 read: () => Promise<PromptBox>;
2501 /**
2502 * Puts `input.text` in the prompt box as the draft, by `mode`: `replace`
2503 * (the default) over it, `append` after it, `insert` at the cursor.
2504 *
2505 * The event `prompt.fill` through the other plugins' hooks; `isFilled:
2506 * false` under a dialog or headless. To hand the model text WITH the next
2507 * prompt instead, a `prompt.submit` hook adds `context` (second example).
2508 *
2509 * @example
2510 * await $.prompt.fill({ text: `> ${quote}\n`, mode: "insert" })
2511 * @example
2512 * ($, e, next) => next({ ...e, context: [...(e.context ?? []), hunk] })
2513 */
2514 fill: (input: PromptFillArgs) => Promise<PromptFilled>;
2515 /**
2516 * Proposes `input.text` as the prompt box's dim suggestion, Tab to take:
2517 * the event `prompt.suggest`, as the engine's own guess after a turn.
2518 *
2519 * It goes through every other plugin's hook with `e.origin` `{ kind:
2520 * 'plugin', name }`, the engine's own suggestions on or off; `{ isShown:
2521 * false }` while the box holds text, a turn runs, or headless (no box).
2522 *
2523 * @example
2524 * void $.prompt.suggest({ text: "run the tests you just wrote" })
2525 */
2526 suggest: EventCalls['prompt']['suggest'];
2527 };
2528 /**
2529 * The tools the model has in this session, and running one.
2530 */
2531 tool: {
2532 /**
2533 * Returns the tools the model can call now, built-in and MCP alike, in
2534 * the order the model sees them.
2535 *
2536 * @example
2537 * const names = (await $.tool.list()).map(t => t.name)
2538 */
2539 list: () => Promise<ToolInfo[]>;
2540 /**
2541 * Calls a tool: the event `tool.call`, the same call the engine makes for
2542 * the model's tool calls, under a `tool_use_id` of its own.
2543 *
2544 * It runs through every hook but the calling one (the plugin's others
2545 * see it), the permission check and its dialog, then the tool. Rejects
2546 * when no tool has that name or the call is aborted.
2547 *
2548 * @example
2549 * const { text } = await $.tool.call({ tool: "Read", file_path: "a.md" })
2550 */
2551 call: EventCalls['tool']['call'];
2552 /**
2553 * Asks the engine's permission decision for a tool call now: the event
2554 * `tool.check`, resolved to `{ decision, reason?, rule? }`.
2555 *
2556 * The hooks run (the calling hook's own frame skipped, `next.origin` this
2557 * plugin, no `tool_use_id`); nothing runs, no dialog opens, no PreToolUse
2558 * hook or classifier is asked.
2559 *
2560 * @example
2561 * const { decision } = await $.tool.check({ tool: "Read", input })
2562 */
2563 check: EventCalls['tool']['check'];
2564 /**
2565 * Declares a tool the model can call from the next prompt on: the name,
2566 * description and input schema of `mcp__<plugin>__<name>`.
2567 *
2568 * Serve it with a `tool.call` hook on `{ tool: "mcp__<plugin>__<name>" }`
2569 * that returns the result (a call no hook answers fails); a name registered
2570 * again is replaced. Rejects until the session binds, at `session.start`.
2571 *
2572 * @param tool `name`, `description` (what the model reads), `inputSchema`
2573 * (a JSON schema object; default `{ type: "object" }`)
2574 * @returns `{ tool }`, the registered tool's full name
2575 * `mcp__<plugin>__<name>`
2576 * @example
2577 * await $.tool.register({ name: "weather", description: "Weather." })
2578 */
2579 register: (tool: ToolSpec) => Promise<OpValueOf['tool.register']>;
2580 };
2581 /**
2582 * The slash commands the person can run in this session, and running one.
2583 */
2584 command: {
2585 /**
2586 * Returns the slash commands the person can run now, built-in, plugin
2587 * and MCP alike, in the order the typeahead lists them.
2588 *
2589 * @example
2590 * const names = (await $.command.list()).map(c => c.name)
2591 */
2592 list: () => Promise<CommandInfo[]>;
2593 /**
2594 * Runs a slash command as if the person typed `/command args`: the
2595 * event `command.run`, queued and run once the session is idle.
2596 *
2597 * It runs through every hook but the calling one with `e.origin`
2598 * `{ kind: 'plugin', name }`, its lines in the transcript. Rejects an
2599 * unknown name, and inside a hook the turn is waiting on.
2600 *
2601 * @example
2602 * const { text } = await $.command.run({ command: "status" })
2603 */
2604 run: EventCalls['command']['run'];
2605 /**
2606 * Declares the slash command `/<name>` for this session, listed in the
2607 * typeahead from the next keystroke on.
2608 *
2609 * Serve it with a `command.run` hook on `{ command: "<name>" }` that
2610 * returns `{ text }`; a run no hook answers says so as its output.
2611 * Registering a name again replaces it; a built-in's name is refused.
2612 *
2613 * @param command `name`, `description` (what the menu shows),
2614 * `argumentHint` (dim after the name), `immediate` (runs mid-turn)
2615 * @returns `{ command }`, the registered name
2616 * @example
2617 * await $.command.register({ name: "hello", description: "Says hi." })
2618 */
2619 register: (command: CommandSpec) => Promise<OpValueOf['command.register']>;
2620 };
2621 /**
2622 * Every row of the settings menu (`/config`), the panel's own and each
2623 * enabled plugin's `userConfig` fields alike: listing and changing them.
2624 */
2625 config: {
2626 /**
2627 * Returns the rows the `/config` menu would draw now, in its order,
2628 * each with its current value, its kind, its owner and its lock.
2629 *
2630 * After every `config.describe` hook: a hidden row is left out, a
2631 * relabelled one carries the new label.
2632 *
2633 * @example
2634 * const theme = (await $.config.list()).find(row => row.key === "theme")
2635 */
2636 list: () => Promise<ConfigRow[]>;
2637 /**
2638 * Changes one row as if the person did in the menu: the event
2639 * `config.set` with `origin` `{ kind: 'plugin', name }`, then the writer.
2640 *
2641 * Through the other plugins' hooks, this plugin's own skipped; `{ deny }`
2642 * when a hook refused, the value does not fit, a trusted source owns the
2643 * row or only its dialog changes it. Rejects a key no row has.
2644 *
2645 * @param args `key` (as `list` names it) and `value` (the row's kind)
2646 * @returns `{ value }` once written, or `{ deny }`
2647 * @example
2648 * const { deny } = await $.config.set({ key: "verbose", value: true })
2649 */
2650 set: EventCalls['config']['set'];
2651 };
2652 /**
2653 * Subagents.
2654 */
2655 agent: {
2656 /**
2657 * Spawns a subagent: the event `agent.spawn`, the same call the engine
2658 * makes when the Agent tool starts one; the engine fills the rest.
2659 *
2660 * It runs every hook but the calling one, then the Agent tool in the
2661 * background under this call's origin: `{ model, agentId }` once the
2662 * subagent started (its answer is its `turn.complete`), or `{ deny }`.
2663 *
2664 * @example
2665 * const { agentId } = await $.agent.spawn({ prompt: "Read README.md." })
2666 */
2667 spawn: EventCalls['agent']['spawn'];
2668 /**
2669 * Returns the session's subagents so far, the ones the model spawned and
2670 * the ones plugins did alike.
2671 */
2672 list: () => Promise<AgentInfo[]>;
2673 /**
2674 * Defines an agent type the Agent tool dispatches from the next turn on,
2675 * named `<plugin>:<name>`: the event `agent.register`.
2676 *
2677 * Every field takes effect as in an agent file; re-registered, a name is
2678 * replaced; unloaded, a plugin's types go. `agent.offer` hides it from
2679 * the model alone; any plugin's `$.agent.spawn` answers to `agent.spawn`.
2680 *
2681 * @param spec `name`, `description` (when to delegate), `prompt` (its
2682 * system prompt), and any other field of an agent definition
2683 * @returns `{ agent }`, the full name; rejects until the session binds,
2684 * on a spec the schema refuses (its reason), on a hook's deny
2685 * @example
2686 * await $.agent.register({ name: "runner", description: "Runs a spec",
2687 * prompt: RUNNER_PROMPT, tools: ["Read", "Bash"], omitClaudeMd: true })
2688 * @example
2689 * // runner-only: hidden from the model, spawned by this plugin's tool,
2690 * // answered by the subagent's turn.complete (matched by agentId)
2691 * on("agent.offer", { agent: "lab:runner" }, () => ({ isOffered: false }))
2692 * on("tool.call", { tool: "mcp__lab__run" }, async ($, e) => {
2693 * const { agentId, deny } = await $.agent.spawn({
2694 * subagentType: "lab:runner", prompt: e.spec, description: "run" })
2695 * return { result: deny ?? (await answerOf(agentId)) }
2696 * })
2697 */
2698 register: (spec: AgentSpec) => Promise<OpValueOf['agent.register']>;
2699 };
2700 /**
2701 * The file system as the engine's own process reaches it; a relative path
2702 * is under the session's working directory, and text is UTF-8.
2703 *
2704 * An absolute path is used as given; where one may go is an `fs.*` hook's
2705 * to say. A read or write over 4 MiB rejects, a foreign network location
2706 * as spelled rejects untouched, and an OS refusal rejects with its errno.
2707 */
2708 fs: {
2709 /**
2710 * Reads a file and returns its text, or with `{ as: "bytes" }` its bytes
2711 * as `{ base64 }`.
2712 *
2713 * Rejects when missing, or over 4 MiB, which bounds what one read copies
2714 * into the plugin's environment. A file the plugin ships is under
2715 * `$.plugin.root`.
2716 *
2717 * @param path relative to the working directory, or absolute
2718 * @param options `as`: `"text"` (the default) or `"bytes"`
2719 * @returns the file's text, or `{ base64 }`
2720 * @example
2721 * const readme = await $.fs.read("README.md")
2722 * @example
2723 * const { base64 } = await $.fs.read(
2724 * `${$.plugin.root}/hooks/weights.bin`, { as: "bytes" })
2725 * const weights = Uint8Array.fromBase64(base64)
2726 */
2727 read: FsReadCall;
2728 /**
2729 * Writes `text` to a file, creating it and its directories as needed.
2730 *
2731 * @param path relative to the working directory, or absolute
2732 * @param text the whole new content
2733 */
2734 write: (path: string, text: string) => Promise<void>;
2735 /**
2736 * Lists a directory: `{ name, kind, size, isLink }` per entry, by name,
2737 * each entry as it stands (a symbolic link is `other` with `isLink`).
2738 *
2739 * @param path the directory's path; absent, the working directory
2740 * @returns the entries, `{ name, kind, size, isLink }` each
2741 */
2742 list: (path?: string) => Promise<FsEntry[]>;
2743 /**
2744 * Returns whether the path exists; rejects only a network location as
2745 * spelled, which no `fs` call reaches.
2746 */
2747 exists: (path: string) => Promise<boolean>;
2748 /**
2749 * Returns `{ kind, size, mtimeMs, isLink }` of the path: what it leads to,
2750 * and whether it is itself a symbolic link. Rejects when missing.
2751 *
2752 * With `{ resolve: true }` also `realPath`, where the path lands, absent
2753 * when it leads nowhere; a guard matches it and denies without it, since a
2754 * spelling it cannot resolve (`~`, a file not there yet) the tool may open.
2755 *
2756 * @param path relative to the working directory, or absolute
2757 * @param options `resolve`: also answer `realPath` (one more file system
2758 * call)
2759 * @returns the stat, `realPath` with it when asked and resolvable; rejects
2760 * `ENOENT` for a missing path
2761 * @example
2762 * // ROOT was resolved the same way and SEP is its separator; an
2763 * // allow-list under it is the robust guard, a deny-list on spellings
2764 * // only best effort (a hard link or a case alias keeps its own)
2765 * on("tool.call", { tool: "Read" }, async ($, e, next) => {
2766 * const stat = await $.fs.stat(e.file_path, { resolve: true })
2767 * .catch(() => undefined)
2768 * const real = stat?.realPath
2769 * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
2770 * return isInside ? next(e) : { deny: "outside the project" }
2771 * })
2772 * @example
2773 * // a Write may name a file not there yet: `placed` answers where the
2774 * // path lands or undefined, and the guard denies on undefined or
2775 * // outside ROOT. Unplaceable by spelling first, with no file system
2776 * // call (drive-relative `D:x`, a `\\` or `//` network or device path,
2777 * // a name that is empty, ".", ".." or itself `C:...`); then the file
2778 * // if it stats; else its folder, cut after the last separator and
2779 * // keeping it so a drive or share root stays that root, plus the name
2780 * const placed = async (path) => {
2781 * const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))
2782 * const name = path.slice(cut + 1)
2783 * const isPlaceable = !/^[A-Za-z]:(?![\\/])/.test(path) &&
2784 * !/^[\\/][\\/]/.test(path) && !/^[A-Za-z]:/.test(name) &&
2785 * name !== "" && name !== "." && name !== ".."
2786 * if (!isPlaceable) return undefined
2787 * const own = await $.fs.stat(path, { resolve: true })
2788 * .catch(() => undefined)
2789 * if (own) return own.realPath
2790 * const folder = cut < 0 ? "." : path.slice(0, cut + 1)
2791 * const dir = await $.fs.stat(folder, { resolve: true })
2792 * .catch(() => undefined)
2793 * return dir?.realPath === undefined ? undefined
2794 * : `${dir.realPath.replace(/[\\/]$/, "")}${SEP}${name}`
2795 * }
2796 * const real = await placed(e.file_path)
2797 * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
2798 * return isInside ? next(e) : { deny: "cannot place it, or outside" }
2799 */
2800 stat: (path: string, options?: FsStatOptions) => Promise<FsStat>;
2801 /**
2802 * Reads the named instruction files in every directory above the
2803 * session's original working directory, the way the engine reads CLAUDE.md.
2804 *
2805 * Root first, each `{ dir, name, content }` that exists, the content
2806 * with its `@include`s after it; `of` and `below` together are the
2807 * engine's own walk for a nested CLAUDE.md between root and read file.
2808 *
2809 * @param request `names`, relative `.md` file names (no `..`); `of`, the
2810 * file walked down to; `below`, the directory the walk stays inside
2811 * @returns the files found, root first
2812 * @example
2813 * const found = await $.fs.ancestors({ names: ["AGENTS.md"] })
2814 * const stack = await $.fs.ancestors({ names: ["AGENTS.md"], of: path })
2815 * const nested = await $.fs.ancestors({
2816 * names: ["AGENTS.md"],
2817 * of: e.file_path,
2818 * below: await $.session.root(),
2819 * })
2820 */
2821 ancestors: (request: FsAncestorsRequest) => Promise<readonly FsAncestor[]>;
2822 };
2823 /**
2824 * This plugin's own key-value store, kept between sessions and hot
2825 * reloads; values are JSON data.
2826 *
2827 * A JSON file of the plugin's own under the user's Claude Code
2828 * configuration directory.
2829 */
2830 store: {
2831 /**
2832 * Returns the value under `key`, or `undefined` when unset.
2833 *
2834 * @example
2835 * const count = Number((await $.store.get("count")) ?? 0) + 1
2836 */
2837 get: (key: string) => Promise<unknown>;
2838 /**
2839 * Sets `key` to `value`, which must be JSON data.
2840 *
2841 * `get` reads back `JSON.parse(JSON.stringify(value))`: a Date is its ISO
2842 * string, an `undefined` field is dropped, a Map or Set is `{}`. Rejects
2843 * a function, a cycle, or a store over 4 MiB of JSON text in all.
2844 */
2845 set: (key: string, value: unknown) => Promise<void>;
2846 /**
2847 * Removes `key` from the store.
2848 */
2849 delete: (key: string) => Promise<void>;
2850 /**
2851 * Returns every key set, in insertion order.
2852 */
2853 keys: () => Promise<string[]>;
2854 };
2855 /**
2856 * The time and timers, each an event through the host: `clock.now` reads
2857 * the time; `clock.sleep`, `after` and `every` wait until it has passed.
2858 *
2859 * A timer's callback is the plugin's own function, kept in its environment
2860 * and run there when the wait resolves; a hot reload of the plugin cancels
2861 * its pending waits with the old environment.
2862 */
2863 clock: {
2864 /**
2865 * Resolves milliseconds since the epoch, now.
2866 *
2867 * @example
2868 * const startedAt = await $.clock.now()
2869 */
2870 now: () => Promise<number>;
2871 /**
2872 * Resolves after `ms` milliseconds; rejects at once when `signal` aborts.
2873 *
2874 * @param ms how long, in milliseconds
2875 * @param options `signal`: ends the wait early with a rejection (pass
2876 * `next.signal` so a hook's wait ends with its dispatch)
2877 * @example
2878 * await $.clock.sleep(500, { signal: next.signal })
2879 */
2880 sleep: (ms: number, options?: SleepOptions) => Promise<void>;
2881 /**
2882 * Calls `fn` once after `ms` milliseconds; `cancel()` before then stops it.
2883 *
2884 * One `clock.after` dispatch: `fn` runs when it resolves, and never when
2885 * a hook refuses it.
2886 */
2887 after: TimerCall;
2888 /**
2889 * Calls `fn` every `ms` milliseconds (at least 1) until `cancel()`.
2890 *
2891 * One `clock.every` dispatch per period: `fn` runs when it resolves and
2892 * the next period is asked; a refused period ends the interval.
2893 *
2894 * @example
2895 * const tick = $.clock.every(1000, () => $.ui.status("polling"))
2896 */
2897 every: TimerCall;
2898 };
2899 /**
2900 * The network, through the host.
2901 */
2902 http: {
2903 /**
2904 * Fetches `url` through the host (never the plugin's own network) and
2905 * resolves `{ status, ok, headers, text }` once the body is read.
2906 *
2907 * http or https, to whatever the host process can reach, unless the
2908 * administrator's policy switches refuse it; an `auth` handle from
2909 * `$.session.authorize()` rides https only, to a first-party host.
2910 *
2911 * @param url the URL (http or https)
2912 * @param init `{ method, headers, body, auth, socketPath }` (body a
2913 * string; socketPath a Unix socket to go over instead of TCP)
2914 * @returns `{ status, ok, headers, text }` once the body is read
2915 * @example
2916 * const { ok, text } = await $.http.fetch("https://example.com/status")
2917 * @example
2918 * await $.http.fetch("http://bridge/reload", {
2919 * method: "POST",
2920 * socketPath: `${runDirectory}/bridge.sock`,
2921 * })
2922 */
2923 fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>;
2924 };
2925 /**
2926 * Commands on the host, run as the user the session runs as. CLI only.
2927 *
2928 * Local execution, not a network path: what a command of its own reaches
2929 * is its own, as for the Bash tool and a settings `command` hook.
2930 */
2931 process: {
2932 /**
2933 * Runs a command on the host by its argument vector (no shell) and
2934 * resolves `{ exitCode, stdout, stderr }` once it exits, any exit code.
2935 *
2936 * One shot: the whole output is read, so a background process left
2937 * writing holds the call until the timeout. Rejects when the command
2938 * cannot start or is still running then. Git runs with repo hooks off.
2939 *
2940 * @param argv the command and its arguments, `argv[0]` the executable
2941 * @param init `{ cwd, env, stdin, timeoutMs }` (cwd the session's by
2942 * default; timeout 30 s by default, ten minutes at most)
2943 * @returns `{ exitCode, stdout, stderr }` once the child exits
2944 * @example
2945 * const { exitCode, stdout } = await $.process.run(["git", "status"])
2946 */
2947 run: (argv: readonly string[], init?: ProcessRunInit) => Promise<ProcessRunResult>;
2948 };
2949 /**
2950 * What the settings files, `--settings` and managed policy hold, as the
2951 * engine runs under it; read only.
2952 *
2953 * Every key crosses as the source holds it, `env` and the helper commands
2954 * included: nothing is filtered. The OAuth session and the global config
2955 * (~/.claude.json) are not settings and are never read.
2956 */
2957 settings: {
2958 /**
2959 * Resolves with the settings merged over every source, as the engine
2960 * reads them, or with one source's settings as loaded (`{ source }`).
2961 *
2962 * A snapshot in plain data each call; a source with no file answers
2963 * `{}`. The sources (SettingsSource) rise in precedence from `user` to
2964 * `policy`: the merge takes a key from the last source that has it.
2965 *
2966 * @param args `{ source }` to read one source; nothing for the merge
2967 * @returns the settings object, keyed as a settings.json is
2968 * @example
2969 * const { permissions } = await $.settings.read()
2970 * const policy = await $.settings.read({ source: "policy" })
2971 */
2972 read: (args?: SettingsReadArgs) => Promise<Settings>;
2973 };
2974 /**
2975 * The environment of this process, the one every Bash child, MCP server
2976 * and `$.process.run` command started after inherits.
2977 *
2978 * `get` and `set` take the variable's name as a string literal, so what a
2979 * module reads and writes is read off its source: `claude plugin validate`
2980 * lists the names, and a name the module does not spell is refused.
2981 */
2982 env: {
2983 /**
2984 * Resolves with the variable's value, or `undefined` when it is unset.
2985 *
2986 * `name` must be a string literal; `claude plugin validate` lists the
2987 * names your module reads and writes.
2988 *
2989 * @example
2990 * const home = await $.env.get("HOME")
2991 */
2992 get: (name: string) => Promise<string | undefined>;
2993 /**
2994 * Sets the variable for this process and everything it starts after, or
2995 * unsets it when `value` is `undefined`.
2996 *
2997 * `name` must be a string literal; `claude plugin validate` lists the
2998 * names your module reads and writes.
2999 *
3000 * @example
3001 * await $.env.set("GIT_PAGER", "cat")
3002 */
3003 set: (name: string, value: string | undefined) => Promise<void>;
3004 };
3005 }
3006
3007 /**
3008 * The name of an event the engine defines itself (a key of CoreEventOf);
3009 * EventName adds the declared plugin nouns' events.
3010 */
3011 type CoreEventName = keyof CoreEventOf;
3012
3013 /**
3014 * The argument of each event the engine defines itself: its call sites'
3015 * (EngineEventOf), the classic hooks' (ClassicEventOf), the calls on `$`.
3016 */
3017 type CoreEventOf = EngineEventOf & ClassicEventOf & OpEventOf;
3018
3019 type CwdChangedHookInput = BaseHookInput & {
3020 hook_event_name: 'CwdChanged';
3021 old_cwd: string;
3022 new_cwd: string;
3023 };
3024
3025 type DirectoryAddedHookInput = BaseHookInput & {
3026 hook_event_name: 'DirectoryAdded';
3027 /**
3028 * Absolute path of the directory that was added.
3029 */
3030 directory: string;
3031 /**
3032 * How the directory was added: "slash_command" for /add-dir, "register_repo_root" for the SDK control_request.
3033 */
3034 source: 'slash_command' | 'register_repo_root';
3035 };
3036
3037 /**
3038 * The `children` field every element constructor's props carry, appended
3039 * beside its own props type: one child, or a list that may nest.
3040 *
3041 * JSX types a lone child as the child itself (`<Text dimColor>done</Text>`
3042 * passes the string, `<Text>{count}</Text>` the number), and a mapped list
3043 * beside a sibling as a nested list (`<Box>{rows.map(row)}<Text>ok</Text>`).
3044 */
3045 export type ElementChildren = {
3046 children?: RenderChildren;
3047 };
3048
3049 /**
3050 * An element as `$.ui.resolve(e)` hands it out: a constructor from props to
3051 * the frozen plain-data element, `children` among the props as JSX passes.
3052 *
3053 * `const { Box } = $.ui.resolve(e)` then `<Box gap={1}>...</Box>` compiles to
3054 * `h(Box, { gap: 1 }, ...children)`, and `h` calls a function tag with its
3055 * props, so the table's constructors are the JSX tags.
3056 */
3057 export type ElementConstructor<P> = (props: P & ElementChildren) => RenderElement;
3058
3059 /**
3060 * Every element name of every surface: what a table handed out is completed to
3061 * (an omitted one draws a fragment; see `ui.resolve`).
3062 */
3063 export type ElementName = {
3064 [P in RenderSurface]: keyof Elements[P];
3065 }[RenderSurface];
3066
3067 /**
3068 * The element constructors each surface draws, by `e.surface`: what
3069 * `$.ui.resolve(e)` returns and a `ui.resolve` hook passes on; no globals.
3070 *
3071 * All carry `Box`, `Text`, `Button`, `Link`, `Code`, `Markdown`; every remote
3072 * surface `Svg`; all but mobile `Input` and `Select`; terminal and desktop
3073 * `Client`; terminal `Raster` and `Image`. Narrowed on `e.surface`, that table.
3074 */
3075 export type Elements = {
3076 terminal: {
3077 Box: ElementConstructor<BoxProps>;
3078 Text: ElementConstructor<TextProps>;
3079 Button: ElementConstructor<ButtonProps>;
3080 Input: ElementConstructor<InputProps>;
3081 Select: ElementConstructor<SelectProps>;
3082 Link: ElementConstructor<LinkProps>;
3083 Code: ElementConstructor<CodeProps>;
3084 Markdown: ElementConstructor<MarkdownProps>;
3085 /**
3086 * A region one of the plugin's surface modules draws (ClientModule), named
3087 * by `module`: a string literal, the module's path relative to this file.
3088 *
3089 * The engine reads the surface module off the hooks module's source
3090 * before anything runs, so a variable, a template with a substitution or
3091 * a computed path as `module` is refused at load, naming the line.
3092 */
3093 Client: ElementConstructor<ClientProps>;
3094 Raster: ElementConstructor<RasterProps>;
3095 Image: ElementConstructor<ImageProps>;
3096 };
3097 desktop: {
3098 Box: ElementConstructor<BoxProps>;
3099 Text: ElementConstructor<TextProps>;
3100 Button: ElementConstructor<ButtonProps>;
3101 Input: ElementConstructor<InputProps>;
3102 Select: ElementConstructor<SelectProps>;
3103 Svg: ElementConstructor<SvgProps>;
3104 Link: ElementConstructor<LinkProps>;
3105 Code: ElementConstructor<CodeProps>;
3106 Markdown: ElementConstructor<MarkdownProps>;
3107 Client: ElementConstructor<ClientProps>;
3108 };
3109 /**
3110 * No `Input` or `Select`: the control protocol carries presses (ui_press)
3111 * but no ui_input or ui_select yet; not a limit of the device.
3112 *
3113 * The table grows when those messages exist.
3114 */
3115 mobile: {
3116 Box: ElementConstructor<BoxProps>;
3117 Text: ElementConstructor<TextProps>;
3118 Button: ElementConstructor<ButtonProps>;
3119 Svg: ElementConstructor<SvgProps>;
3120 Link: ElementConstructor<LinkProps>;
3121 Code: ElementConstructor<CodeProps>;
3122 Markdown: ElementConstructor<MarkdownProps>;
3123 };
3124 /**
3125 * The desktop's table without `Client`: a remote `Client`'s module, presses
3126 * and posts (ui_client_module, ui_client_press, ui_message) name no surface.
3127 *
3128 * They are the desktop's alone today, not a limit of the editor's webview:
3129 * the table gains `Client` when those asks name a surface.
3130 */
3131 vscode: {
3132 Box: ElementConstructor<BoxProps>;
3133 Text: ElementConstructor<TextProps>;
3134 Button: ElementConstructor<ButtonProps>;
3135 Input: ElementConstructor<InputProps>;
3136 Select: ElementConstructor<SelectProps>;
3137 Svg: ElementConstructor<SvgProps>;
3138 Link: ElementConstructor<LinkProps>;
3139 Code: ElementConstructor<CodeProps>;
3140 Markdown: ElementConstructor<MarkdownProps>;
3141 };
3142 };
3143
3144 /**
3145 * The table `ui.resolve` answers for an argument of surface `P`.
3146 */
3147 export type ElementTable<P extends RenderSurface = RenderSurface> = Elements[P];
3148
3149 /**
3150 * 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.
3151 */
3152 type ElicitationHookInput = BaseHookInput & {
3153 hook_event_name: 'Elicitation';
3154 mcp_server_name: string;
3155 message: string;
3156 mode?: 'form' | 'url';
3157 url?: string;
3158 elicitation_id?: string;
3159 requested_schema?: Record<string, unknown>;
3160 };
3161
3162 /**
3163 * 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.
3164 */
3165 type ElicitationResultHookInput = BaseHookInput & {
3166 hook_event_name: 'ElicitationResult';
3167 mcp_server_name: string;
3168 elicitation_id?: string;
3169 mode?: 'form' | 'url';
3170 action: 'accept' | 'decline' | 'cancel';
3171 content?: Record<string, unknown>;
3172 };
3173
3174 /**
3175 * The input of `engine.create`: the fold that builds `$`, once per load,
3176 * core innermost.
3177 *
3178 * A hook is written in post-order: `const built = await next(e)` is `$` as
3179 * built so far; `return { ...built, voice: { say } }` adds this plugin's noun.
3180 * See EngineEventOf's `engine.create` for what a step may and may not do.
3181 */
3182 export type EngineCreateInput = {
3183 /**
3184 * The modules this fold builds, in list order, first outermost (managed
3185 * plugins first, so an org plugin's withholding wins).
3186 *
3187 * The whole set at a load, this plugin alone at its reload, the ones added
3188 * or changed at a refresh that keeps the rest: a module added later that
3189 * does not hook this event is built against the table as it stands.
3190 */
3191 plugins: readonly string[];
3192 };
3193
3194 /**
3195 * What an `engine.create` hook returns: `$` as built so far with this
3196 * plugin's nouns added, less any it withheld.
3197 *
3198 * Every declared noun is optional here. Between hooks it crosses the chain
3199 * as interface descriptors; a hook sees objects (EngineInterfaceBuilt).
3200 */
3201 export type EngineCreateResult = Partial<EngineInterface> & {
3202 readonly [noun: string]: unknown;
3203 };
3204
3205 /**
3206 * The events the engine raises at its call sites, and `engine.create`; the
3207 * classic settings hooks' events are ClassicEventOf.
3208 *
3209 * At every one, a hook that fails (throws, overruns its budget: HookBudget,
3210 * answers a wrong shape) is skipped: the hooks beneath and core run in its
3211 * place, or its last `next` result stands; the failure is reported by name.
3212 */
3213 export type EngineEventOf = {
3214 /**
3215 * Fires when the engine is about to run a tool. `next(e)` runs the hooks
3216 * beneath, then core (the permission prompt, the tool itself).
3217 *
3218 * Return `{ deny: reason }` to refuse or `{ result }` to answer yourself; a
3219 * hook that returns while its `next` is pending aborts what runs beneath.
3220 * The managed-settings hooks run first: their deny is the call's result.
3221 */
3222 'tool.call': ToolCallInput;
3223 /**
3224 * Fires when the engine decides whether a tool call may run, after the
3225 * `tool.call` and PreToolUse hooks and before the mode settles an ask.
3226 *
3227 * `next(e)` resolves to the engine's verdict (rules, mode, the tool's own
3228 * check, PreToolUse's decision); return any `{ decision }`. `$.tool.check`
3229 * runs the same chain and executes nothing.
3230 *
3231 * @example
3232 * on("tool.check", { tool: "Read" }, () => ({ decision: "allow" }))
3233 */
3234 'tool.check': ToolCheckInput;
3235 /**
3236 * Fires when the engine is about to draw a component: once per input value
3237 * (props, viewport width), plugin load or `$.ui.invalidate("ui.render")`.
3238 *
3239 * A repaint reuses the answer; a clock invalidates. `next(e)` resolves to the
3240 * drawing: return it, wrap it, draw your own, or rewrite `props`. A tree that
3241 * does not validate draws the engine's own; `--plugin-dir` is told why.
3242 */
3243 'ui.render': RenderInput;
3244 /**
3245 * Fires when the plugins load (not per draw), once per surface, component
3246 * and plugin: `e` names the surface and component, never the props.
3247 *
3248 * `next(e)` resolves to the surface's table, which `$.ui.resolve(e)` then
3249 * reads. Return it, one with an element restyled for every other plugin,
3250 * or one with a key left out (a fragment there); own table: hook skipped.
3251 */
3252 'ui.resolve': ResolveInput;
3253 /**
3254 * Fires when a `Button` a render hook drew is pressed on a surface; `e` is
3255 * `{ plugin, element, component, surface }`, `element` the button's `key`.
3256 *
3257 * `next(e)` runs the hooks beneath, then core: the element's own `onPress`
3258 * closure, in its plugin's environment, resolving to `{ element }`. Return
3259 * `next(e)` to let the press through, or `{ element }` to take it.
3260 */
3261 'ui.press': UiPressArgument;
3262 /**
3263 * Fires when an `Input` a render hook drew changes or is submitted; `e` is
3264 * `{ plugin, element, component, surface, kind, value }`.
3265 *
3266 * `next(e)` runs the hooks beneath, then the element's own `onInput` or
3267 * `onSubmit` with `e.value` as the chain left it, resolving to `{ element,
3268 * value }`; `next({ ...e, value })` rewrites the typing, an answer takes it.
3269 */
3270 'ui.input': UiInputArgument;
3271 /**
3272 * Fires when a `Select` a render hook drew is picked from; `e` is
3273 * `{ plugin, element, component, surface, value }`.
3274 *
3275 * `next(e)` runs the hooks beneath, then the element's own `onSelect` with
3276 * `e.value` as the chain left it, resolving to `{ element, value }`;
3277 * `next({ ...e, value })` rewrites the pick, an answer takes it.
3278 */
3279 'ui.select': UiSelectArgument;
3280 /**
3281 * Fires when a `Client` THIS plugin drew posts from its surface module
3282 * (`surface.post(data)`); only this plugin's hooks see it.
3283 *
3284 * `next.origin` names `client`: `data` came from code. Core answers `{}`;
3285 * `next({ ...e, data })` rewrites the data; `{ props }` hands the posting
3286 * instance its next props without a redraw. One per instance per frame.
3287 */
3288 'ui.message': UiMessageArgument;
3289 /**
3290 * Fires before a site's window moves: the person's wheel or scroll keys on
3291 * a `Pane` body or the `AbovePrompt` band, at its edges too; `$.ui.scroll`.
3292 *
3293 * `next(e)` moves it to `e.offset` and draws: `{}`; `next({ ...e, offset
3294 * })` elsewhere; no `next` (`{}` or `{ deny }`) leaves it undrawn, so a hook
3295 * drawing its own rows under a header moves them by `e.by` and invalidates.
3296 *
3297 * @example
3298 * on("ui.scroll", { requestId: "log" }, ($, e) => (scrollOwnRows(e.by), {}))
3299 */
3300 'ui.scroll': UiScrollInput;
3301 /**
3302 * Fires before a site's focus ring moves: the person's Tab, arrows or click
3303 * in a `Pane` or the band; an `autoFocus` element taking it; `$.ui.focus`.
3304 *
3305 * `next(e)` lands it on `e.element` (absent: one of the engine's stops) and
3306 * draws: `{}`; `next({ ...e, element })` on another of `e.plugin`'s; no
3307 * `next` (`{}` or `{ deny }`) keeps it where it was, drawn as it was.
3308 *
3309 * @example
3310 * on("ui.focus", { requestId: "list" }, ($, e, next) => (mark(e), next(e)))
3311 */
3312 'ui.focus': UiFocusInput;
3313 /**
3314 * Fires when the engine offers an agent type to the model, in the agent
3315 * listing and again at dispatch; `next(e)` resolves to `{ isOffered: true }`.
3316 *
3317 * Return `{ isOffered: false }` to keep the type out of the listing and
3318 * refuse its dispatch. A hook that fails passes it through.
3319 *
3320 * @example
3321 * on("agent.offer", { agent: "Plan" }, () => ({ isOffered: false }))
3322 */
3323 'agent.offer': AgentOfferInput;
3324 /**
3325 * Fires when the Agent tool is about to start a subagent, everything
3326 * decided and its model not yet resolved.
3327 *
3328 * `next(e)` resolves to `{ model }`. Return it, `next({ ...e, model })`,
3329 * `{ model }` of your own (an alias resolves like the tool's parameter), or
3330 * `{ deny: reason }`.
3331 */
3332 'agent.spawn': AgentSpawnInput;
3333 /**
3334 * Fires when a prompt is submitted, before the turn starts. `next(e)` runs
3335 * the hooks beneath and the UserPromptSubmit settings hooks.
3336 *
3337 * Rewrite with `next({ ...e, text })` (the user message on screen follows)
3338 * or stop it with `{ drop: reason }`; a broken plugin never blocks a prompt.
3339 * A prompt typed while a turn ran fires at Enter, with that turn's id.
3340 */
3341 'prompt.submit': PromptSubmitInput;
3342 /**
3343 * Fires when a text is about to be put in the prompt box as the person's
3344 * draft (a plugin's `$.prompt.fill`); `next(e)` writes it by `e.mode`.
3345 *
3346 * `replace` over the draft, `append` after it, `insert` at the cursor;
3347 * rewrite `text` or `mode` going down, or answer `{ isFilled: false }`
3348 * without `next` to keep it out, as core does under a dialog or headless.
3349 *
3350 * @example
3351 * on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
3352 */
3353 'prompt.fill': PromptFillInput;
3354 /**
3355 * Fires when a text is proposed as the prompt box's dim suggestion, Tab to
3356 * take: the engine's guess after a turn, or a plugin's `$.prompt.suggest`.
3357 *
3358 * `next(e)` shows it: `{ isShown }`. Rewrite with `next({ ...e, text })`,
3359 * or answer `{ isShown: false }` without `next` to drop it; core answers
3360 * that too while the box holds text or a turn runs.
3361 *
3362 * @example
3363 * on("prompt.suggest", { origin: { kind: "suggestion" } }, hide)
3364 */
3365 'prompt.suggest': PromptSuggestInput;
3366 /**
3367 * Fires when the person edits the main prompt box: a key the editor took as
3368 * an edit, or a paste; `next(e)` resolves the box the editor shows.
3369 *
3370 * `e` is the draft before and the splice (`start`, `end`, `inputText`); a
3371 * burst of keys is one edit. Rewrite `inputText` going down or the box
3372 * coming up; `{ text: e.text, cursor: e.cursor }` without `next` consumes.
3373 *
3374 * @example
3375 * on("prompt.edit", ($, e, next) => next({ ...e, inputText: up(e) }))
3376 */
3377 'prompt.edit': PromptEditInput;
3378 /**
3379 * Fires once per named section of the system prompt, when the engine
3380 * assembles it; `next(e)` resolves to `{ text }` as core computed it.
3381 *
3382 * Sections are cached by name for the session until
3383 * `$.ui.invalidate("prompt.section")`: an unstable answer spends the
3384 * model's prompt cache on every call. A hook that fails passes it through.
3385 *
3386 * @example
3387 * on("prompt.section", { name: "memory" }, () => ({ text: null }))
3388 */
3389 'prompt.section': PromptSectionInput;
3390 /**
3391 * Fires once per conversation, when the engine computes the context blocks
3392 * its first user message carries; `next(e)` resolves to `{ blocks }`.
3393 *
3394 * Append, drop, reorder or rewrite with `next({ ...e, blocks })`; the
3395 * engine renders what comes back, in order, until
3396 * `$.ui.invalidate("prompt.context")` or a re-read (compaction, `/clear`).
3397 *
3398 * @example
3399 * on("prompt.context", () => ({ blocks: [] }))
3400 */
3401 'prompt.context': PromptContextInput;
3402 /**
3403 * Fires once per message the engine injects for the model on its own (a
3404 * reminder, a mode transition, a mentioned file), as a request carries it.
3405 *
3406 * `next(e)` resolves to `{ text }`; `{ text: null }` leaves it out. The
3407 * answer holds per attachment for the process (asked again on resume or
3408 * `$.ui.invalidate`); the transcript keeps the engine's record.
3409 *
3410 * @example
3411 * on("prompt.attachment", { type: "todo_reminder" }, () => ({ text: null }))
3412 */
3413 'prompt.attachment': PromptAttachmentInput;
3414 /**
3415 * Fires once per tool, when the engine first renders the tool's schema in
3416 * a session; `next(e)` resolves to `{ description, isDeferred? }`.
3417 *
3418 * Cached for the session until `$.ui.invalidate("tool.describe")`: an
3419 * unstable answer spends the model's prompt cache. An explicit `isDeferred`
3420 * moves the tool behind ToolSearch (true) or into the prompt's list (false).
3421 *
3422 * @example
3423 * on("tool.describe", { tool: "Bash" }, ($, e) => ({ ...e, description }))
3424 * @example
3425 * on("tool.describe", { tool: "Monitor" }, pin) // {...e, isDeferred: false}
3426 */
3427 'tool.describe': ToolDescribeInput;
3428 /**
3429 * Fires when a slash command is about to run (`/name args` typed, or a
3430 * plugin's `$.command.run`); `next(e)` resolves to `{ text }`, its output.
3431 *
3432 * Core is the engine's command (a registered one has none). Rewrite `args`
3433 * with `next`, or return `{ text }` without it to answer in its place; one
3434 * after `next` replaces a printed output, not a panel or prompt it opened.
3435 *
3436 * @example
3437 * on("command.run", { command: "hello" }, () => ({ text: "hello" }))
3438 */
3439 'command.run': CommandRunInput;
3440 /**
3441 * Fires once per command, when the engine lists it for the typeahead and
3442 * `/help`; `next(e)` resolves to `{ description, argumentHint, isHidden }`.
3443 *
3444 * Listed answers are cached for the session until
3445 * `$.ui.invalidate("command.describe")`. A hook that fails passes it
3446 * through.
3447 *
3448 * @example
3449 * on("command.describe", ($, e, next) => next({ ...e, isHidden: true }))
3450 */
3451 'command.describe': CommandDescribeInput;
3452 /**
3453 * Fires when a `/config` row is about to change, from the menu or a
3454 * plugin's `$.config.set`; `next(e)` resolves to `{ value }` once written.
3455 *
3456 * Return `{ deny: reason }` to leave the row as it is (the menu says why),
3457 * or `next({ ...e, value })` to clamp it; a value of the wrong kind for
3458 * the row is refused. A row a trusted source owns is core's to refuse.
3459 *
3460 * @example
3461 * on("config.set", { key: "theme" }, () => ({ deny: "the theme stays" }))
3462 */
3463 'config.set': ConfigSetInput;
3464 /**
3465 * Fires once per `/config` row, when the menu lists it and for
3466 * `$.config.list`; `next(e)` resolves to `{ label, description, isHidden }`.
3467 *
3468 * Relabel, re-describe or hide with `next({ ...e, isHidden: true })`; the
3469 * answers are cached until `$.ui.invalidate("config.describe")` or the
3470 * loaded plugins change. A hook that fails passes the row through.
3471 *
3472 * @example
3473 * on("config.describe", { key: "tips" }, hide) // answers isHidden: true
3474 */
3475 'config.describe': ConfigDescribeInput;
3476 /**
3477 * Fires when the engine expands a skill's prompt for the model (`/name`,
3478 * the Skill tool, a preload); `next(e)` resolves to `{ text }` as computed.
3479 *
3480 * Return `{ text }` with the text the model reads instead. A hook that
3481 * fails passes it through.
3482 *
3483 * @example
3484 * on("skill.prompt", { skill: "commit" }, () => ({ text: "A haiku." }))
3485 */
3486 'skill.prompt': SkillPromptInput;
3487 /**
3488 * Fires when the engine composes a git text the model is to write (`kind`:
3489 * `commit`, `pr`, `exemption`, `remedy`); `next(e)` resolves to `{ text }`.
3490 *
3491 * Return `{ text }` with the text the model reads instead. A hook that
3492 * fails passes it through.
3493 *
3494 * @example
3495 * on("attribution.text", { kind: "commit" }, () => ({ text: "" }))
3496 */
3497 'attribution.text': AttributionTextInput;
3498 /**
3499 * Fires once per process for each loaded plugin, before the first prompt,
3500 * then once per fresh load of one (never `/clear`); `next(e)` is `{ cwd }`.
3501 *
3502 * Observe. The first is awaited: a `$.tool.register` is listed by turn one.
3503 * A later one runs its hooks alone: an enable, a worker respawn, or a reload
3504 * (changed modules only; all if one hooks `engine.create`/`plugin.register`).
3505 *
3506 * @example
3507 * on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
3508 */
3509 'session.start': SessionStartInput;
3510 /**
3511 * Fires when a delivery reaches the session (a relay's event, a peer's
3512 * message, a Remote Control prompt), before it is queued; `{ text }`.
3513 *
3514 * Rewrite with `next({ ...e, text })`, or return `{ consumed: reason }` to
3515 * take it: nothing is queued, shown or read by the model. `origin` and
3516 * `event` pass on as received; `session.send`, its dual, is reserved.
3517 *
3518 * @example
3519 * on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
3520 */
3521 'session.receive': SessionReceiveInput;
3522 /**
3523 * Fires when the conversation is about to be compacted (`/compact`, the
3524 * threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
3525 *
3526 * Rewrite `instructions` or `messages` on the way down, the messages on
3527 * the way up, or answer `{ messages }` of your own; `{ skip: reason }`
3528 * leaves the conversation as it is. `trigger` passes on as received.
3529 *
3530 * @example
3531 * on("session.compact", { trigger: "precompute" }, () => ({ skip: "off" }))
3532 */
3533 'session.compact': SessionCompactInput;
3534 /**
3535 * Fires when a remote client joins the session's roster of attached
3536 * surfaces: it said so (ui_attach), or it first asked to draw.
3537 *
3538 * Observe (a phone joined: draw the lobby); `next(e)` resolves to
3539 * `{ clientId }`, a different return changes nothing. `$.session.surfaces()`
3540 * reads the roster; a render hook still reads `e.surface` per ask.
3541 *
3542 * @example
3543 * on("session.attach", { surface: "mobile" }, ($, e, next) => next(e))
3544 */
3545 'session.attach': SessionAttachInput;
3546 /**
3547 * Fires when a client leaves the roster: it detached, or the session ended
3548 * with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
3549 */
3550 'session.detach': SessionDetachInput;
3551 /**
3552 * Fires when the engine measures the session and a unit moved: after each
3553 * main-thread turn, and when a rate-limit window moves a whole point.
3554 *
3555 * Observe; `next(e)` echoes `{ changed }`. `$.session.usage()`'s figures,
3556 * pushed, not polled: compare them with your own threshold here, call the
3557 * op for the breakdown. One at a time, a burst folding into one more.
3558 *
3559 * @example
3560 * on("session.measure", ($, e, next) => (toastPast90(e.rateLimits), next(e)))
3561 */
3562 'session.measure': SessionMeasureInput;
3563 /**
3564 * Fires once when the session ends (exit, /clear, resume, logout, signal, a
3565 * `-p` run done), after its SessionEnd settings hooks; `e.reason` says which.
3566 *
3567 * `e.resume.id` is `--resume`'s id; `next(e)` runs the engine's end step for
3568 * the plugins (at an exit the attached clients leave): `{ sessionId }`. The
3569 * SessionEnd bound afresh, 1.5 s by default; a `kill -9` raises nothing.
3570 *
3571 * @example
3572 * on("session.end", async ($, e, next) => (await keep(e.resume), next(e)))
3573 */
3574 'session.end': SessionEndInput;
3575 /**
3576 * Fires once per hooks module about to join the chain, at load (the set
3577 * folded and built, nothing swapped in) and at reload; core allows.
3578 *
3579 * Return `{ refuse: reason }` and it never joins: no hook, no noun, no tool
3580 * of it; the transcript names who refused. Its judges, `$` whole, are the
3581 * plugins admitted before it and the binary's; judge by `tier` and `uses`.
3582 *
3583 * @example
3584 * on("plugin.register", { tier: "user" }, () => ({ refuse: "managed only" }))
3585 */
3586 'plugin.register': PluginRegisterInput;
3587 /**
3588 * Fires when a model turn begins, before its first model call; `next(e)`
3589 * resolves to `{ turnId }`. Observe: a different return changes nothing.
3590 */
3591 'turn.start': TurnStartInput;
3592 /**
3593 * Fires when the engine is about to send a model request of a turn, main's
3594 * or a subagent's (`e.agentId`); `next(e)` resolves to the whole response.
3595 *
3596 * `next({ ...e, model })` or `effort` sends another; the turn, the index and
3597 * the message count are pinned. An answer without `next` sends no request.
3598 * It streams (StreamNext): the hook's budget counts its own code alone.
3599 */
3600 'turn.step': TurnStepInput;
3601 /**
3602 * Fires when a model turn has ended, at the point its duration is reported;
3603 * `next(e)` resolves to `{ text }`, the answer. `e.reason` says why.
3604 *
3605 * Return `{ text }` with a different text to show it beneath the answer (a
3606 * synopsis, a TL;DR line); the transcript's record is never rewritten. A
3607 * hook that fails leaves the answer as it was.
3608 */
3609 'turn.complete': TurnCompleteInput;
3610 /**
3611 * Runs while `$` is being built, once per load or reload of this plugin
3612 * and before any other hook of it; `next(e)` resolves to `$` built so far.
3613 *
3614 * A step may ADD nouns and WITHHOLD nouns (leave one out, or return without
3615 * `next`); it may NOT REPLACE one another step added: the step fails, named
3616 * with both plugins. A step that fails unloads its plugin; `$` is rebuilt.
3617 */
3618 'engine.create': EngineCreateInput;
3619 };
3620
3621 /**
3622 * `$`, the first parameter of every hook. Frozen; core's interface plus
3623 * every noun the plugins' `engine.create` steps added.
3624 *
3625 * Flat, `<noun>.<event>`; it does not carry `on`, since registration happens
3626 * before `$` exists. An interface so a plugin types the noun it provides by
3627 * declaration merging, the way a jQuery plugin types `$.fn`.
3628 *
3629 * @example
3630 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
3631 */
3632 export interface EngineInterface extends CoreEngineInterface {
3633 }
3634
3635 /**
3636 * What `next(e)` resolves to at `engine.create`: `$` as the steps beneath
3637 * built it, typed as `$` is, open to nouns no declaration names yet.
3638 *
3639 * A withheld noun is on it as a stub (a step inside withheld it, or the
3640 * last fold did and this is a reload), and the host refuses an op on one a
3641 * step outside withholds later; a typed module bootstraps at load on it.
3642 */
3643 export type EngineInterfaceBuilt = EngineInterface & {
3644 readonly [noun: string]: unknown;
3645 };
3646
3647 /**
3648 * The engine's events' results.
3649 */
3650 export type EngineResultOf = {
3651 /**
3652 * `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`.
3653 */
3654 'tool.call': ToolCallResult;
3655 /**
3656 * `{ decision, reason?, rule? }`.
3657 */
3658 'tool.check': ToolCheckResult;
3659 /**
3660 * The tree to draw; `{ type: "engine", ref }` is core's own drawing.
3661 */
3662 'ui.render': RenderElement;
3663 /**
3664 * The surface's element table (Elements[e.surface]): constructors from props
3665 * to a RenderElement.
3666 */
3667 'ui.resolve': ElementTable;
3668 /**
3669 * `{ element }`: the element whose handler the press reached.
3670 */
3671 'ui.press': UiPressResult;
3672 /**
3673 * `{ element, value }`: the field whose handler the input reached, and
3674 * the text it received.
3675 */
3676 'ui.input': UiInputResult;
3677 /**
3678 * `{ element, value }`: the picker whose handler the pick reached, and
3679 * the value it received.
3680 */
3681 'ui.select': UiSelectResult;
3682 /**
3683 * `{ props? }`: the posting instance's next props, when a hook hands some.
3684 */
3685 'ui.message': UiMessageResult;
3686 /**
3687 * `{}` once the window moved, or `{ deny }`.
3688 */
3689 'ui.scroll': UiScrollResult;
3690 /**
3691 * `{}` once the ring moved, or `{ deny }`.
3692 */
3693 'ui.focus': UiFocusResult;
3694 /**
3695 * `{ isOffered }`.
3696 */
3697 'agent.offer': AgentOfferResult;
3698 /**
3699 * `{ model }` or `{ deny }`.
3700 */
3701 'agent.spawn': AgentSpawnResult;
3702 /**
3703 * `{ text, context? }` or `{ drop }`.
3704 */
3705 'prompt.submit': PromptSubmitResult;
3706 /**
3707 * `{ isFilled }`.
3708 */
3709 'prompt.fill': PromptFillResult;
3710 /**
3711 * `{ isShown }`.
3712 */
3713 'prompt.suggest': PromptSuggestResult;
3714 /**
3715 * `{ text, cursor }`, the box the editor shows next.
3716 */
3717 'prompt.edit': PromptEditResult;
3718 /**
3719 * `{ text }` (null leaves the section out).
3720 */
3721 'prompt.section': PromptSectionResult;
3722 /**
3723 * `{ blocks }` (a block left out is not sent).
3724 */
3725 'prompt.context': PromptContextResult;
3726 /**
3727 * `{ text }` (null leaves the attachment out).
3728 */
3729 'prompt.attachment': PromptAttachmentResult;
3730 /**
3731 * `{ description, isDeferred? }`.
3732 */
3733 'tool.describe': ToolDescribeResult;
3734 /**
3735 * `{ text }` (the command's output, when it printed one).
3736 */
3737 'command.run': CommandRunResult;
3738 /**
3739 * `{ description, argumentHint, isHidden }`.
3740 */
3741 'command.describe': CommandDescribeResult;
3742 /**
3743 * `{ value }` once written, or `{ deny }`.
3744 */
3745 'config.set': ConfigSetResult;
3746 /**
3747 * `{ label, description, isHidden }`.
3748 */
3749 'config.describe': ConfigDescribeResult;
3750 /**
3751 * `{ text }`.
3752 */
3753 'skill.prompt': SkillPromptResult;
3754 /**
3755 * `{ text }`.
3756 */
3757 'attribution.text': AttributionTextResult;
3758 /**
3759 * `{ cwd }`.
3760 */
3761 'session.start': SessionStartResult;
3762 /**
3763 * `{ text }`, or `{ consumed }`.
3764 */
3765 'session.receive': SessionReceiveResult;
3766 /**
3767 * `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
3768 */
3769 'session.compact': SessionCompactResult;
3770 /**
3771 * `{ clientId }`.
3772 */
3773 'session.attach': SessionAttachResult;
3774 /**
3775 * `{ clientId }`.
3776 */
3777 'session.detach': SessionDetachResult;
3778 /**
3779 * `{ changed }`.
3780 */
3781 'session.measure': SessionMeasureResult;
3782 /**
3783 * `{ sessionId }`.
3784 */
3785 'session.end': SessionEndResult;
3786 /**
3787 * `{ allow: true }`, or `{ refuse }`.
3788 */
3789 'plugin.register': PluginRegisterResult;
3790 /**
3791 * `{ turnId }`.
3792 */
3793 'turn.start': TurnStartResult;
3794 /**
3795 * The response: `{ turnId, index, answer, toolUses, stopReason, usage }`.
3796 */
3797 'turn.step': TurnStepResult;
3798 /**
3799 * `{ text }`.
3800 */
3801 'turn.complete': TurnCompleteResult;
3802 /**
3803 * `$` as built so far, with this plugin's interface added and any it
3804 * withheld left out; `next(e)` resolves to EngineInterfaceBuilt.
3805 */
3806 'engine.create': EngineCreateResult;
3807 };
3808
3809 /**
3810 * The engine's own events as calls on `$`, one signature each:
3811 * `$.<noun>.<event>(input)` resolves to its result, or to its stream.
3812 *
3813 * The engine raises its events through these same calls; a plugin's call
3814 * runs the same chain with the calling hook alone skipped. `input` may leave
3815 * out what the engine fills (`tool_use_id`, the parent agent).
3816 */
3817 export type EventCalls = {
3818 tool: {
3819 call: ToolCallOverloads;
3820 check: (input: ToolCheckArgs) => Promise<ToolCheckResult>;
3821 describe: (input: ToolDescribeInput) => Promise<ToolDescribeResult>;
3822 };
3823 command: {
3824 run: (input: CommandRunArgs) => Promise<CommandRunResult>;
3825 describe: (input: CommandDescribeInput) => Promise<CommandDescribeResult>;
3826 };
3827 config: {
3828 set: (input: ConfigSetArgs) => Promise<ConfigSetResult>;
3829 describe: (input: ConfigDescribeInput) => Promise<ConfigDescribeResult>;
3830 };
3831 prompt: {
3832 submit: (input: PromptSubmitArgs) => Promise<PromptSubmitResult>;
3833 fill: (input: PromptFillArgs) => Promise<PromptFillResult>;
3834 suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
3835 section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
3836 context: (input: PromptContextInput) => Promise<PromptContextResult>;
3837 attachment: (input: PromptAttachmentInput) => Promise<PromptAttachmentResult>;
3838 };
3839 skill: {
3840 prompt: (input: SkillPromptInput) => Promise<SkillPromptResult>;
3841 };
3842 attribution: {
3843 text: (input: AttributionTextInput) => Promise<AttributionTextResult>;
3844 };
3845 agent: {
3846 offer: (input: AgentOfferInput) => Promise<AgentOfferResult>;
3847 spawn: (input: AgentSpawnArgs) => Promise<AgentSpawnResult>;
3848 };
3849 session: {
3850 start: (input: SessionStartInput) => Promise<SessionStartResult>;
3851 receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
3852 compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
3853 attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
3854 detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
3855 measure: (input: SessionMeasureInput) => Promise<SessionMeasureResult>;
3856 end: (input: SessionEndInput) => Promise<SessionEndResult>;
3857 };
3858 turn: {
3859 start: (input: TurnStartInput) => Promise<TurnStartResult>;
3860 step: (input: TurnStepInput) => HookStream<TurnStepChunk, TurnStepResult>;
3861 complete: (input: TurnCompleteInput) => Promise<TurnCompleteResult>;
3862 };
3863 ui: {
3864 render: <C extends RenderComponent>(input: RenderInput<C>) => Promise<RenderElement>;
3865 resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
3866 scroll: (input: UiScrollArgs) => Promise<UiScrollResult>;
3867 focus: (input: UiFocusArgs) => Promise<UiFocusResult>;
3868 };
3869 };
3870
3871 /**
3872 * The name of an event: a key of EventOf, the engine's own (CoreEventName)
3873 * and the declared plugin nouns' (NounEventName).
3874 */
3875 export type EventName = keyof EventOf;
3876
3877 /**
3878 * The argument of each event, by event name: what a hook receives as `e`
3879 * and what the call on `$` takes. Plain data, frozen to every depth.
3880 *
3881 * The engine's own events (CoreEventOf: a plugin's `$.fs.write(...)` is
3882 * a dispatch the hooks above it see) and the methods of the plugin nouns
3883 * declared on EngineInterface (NounEventOf).
3884 */
3885 export type EventOf = CoreEventOf & NounEventOf;
3886
3887 /**
3888 * The result of event `N`: what its hooks return and what their `next(e)`
3889 * resolves to.
3890 */
3891 export type EventResult<N extends EventName = EventName> = ResultOf[N];
3892
3893 /**
3894 * The hook signature of each event, `($, e, next)`, as one mapped type over
3895 * EventOf; a streaming event's is the generator form (StreamHook).
3896 *
3897 * With one handler type per event, `Events[E]` for a generic E would be a
3898 * union; as one mapped type it stays a single function type the engine
3899 * calls without a cast (TS 4.6 correlated unions).
3900 *
3901 * @param $ the engine interface, frozen, the same object at every invocation;
3902 * at `engine.create` the empty table, since `$` exists after the fold
3903 * @param e the event's argument, frozen to every depth (`e.command = "ls"`
3904 * is a type error and throws); a rewrite is a copy passed to `next`
3905 * @param next the rest of the chain; a chain a hook raises through `$` skips
3906 * this hook and runs every other, its plugin's others too
3907 */
3908 export type Events = {
3909 [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>>;
3910 };
3911
3912 type ExitReason = 'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other';
3913
3914 type FileChangedHookInput = BaseHookInput & {
3915 hook_event_name: 'FileChanged';
3916 file_path: string;
3917 event: 'change' | 'add' | 'unlink';
3918 };
3919
3920 /**
3921 * `T` with every property read-only to every depth, arrays and tuples kept
3922 * as declared: how a hook's `e` is typed.
3923 *
3924 * `e.command = 'x'` is a type error; `next({ ...e, command: 'x' })` compiles.
3925 */
3926 export type Frozen<T> = T extends (...args: never[]) => unknown ? T : T extends readonly unknown[] ? {
3927 [K in keyof T]: Frozen<T[K]>;
3928 } : T extends object ? {
3929 readonly [K in keyof T]: Frozen<T[K]>;
3930 } : T;
3931
3932 /**
3933 * One file `$.fs.ancestors` found: the directory it stands in, the name it
3934 * was asked for by, and its text as the engine's memory loader reads it.
3935 */
3936 export type FsAncestor = {
3937 /**
3938 * The directory the file stands in, absolute.
3939 */
3940 dir: string;
3941 /**
3942 * The spelling the caller asked for it by.
3943 */
3944 name: string;
3945 /**
3946 * The file's text, with what its `@include`s bring after it.
3947 */
3948 content: string;
3949 /**
3950 * The file and then each file its `@` imports brought, in load order,
3951 * path and text apiece; `content` is these texts joined.
3952 */
3953 parts: readonly FsAncestorPart[];
3954 };
3955
3956 /**
3957 * One file of an ancestor entry: the file itself or one it imported.
3958 */
3959 export type FsAncestorPart = {
3960 /**
3961 * The file's path, absolute.
3962 */
3963 path: string;
3964 /**
3965 * Its text as the engine's memory loader reads it.
3966 */
3967 content: string;
3968 };
3969
3970 /**
3971 * The argument of `$.fs.ancestors`: the file names to look for in each
3972 * directory, the file to walk down to, and the directory to walk beneath.
3973 */
3974 export type FsAncestorsRequest = {
3975 /**
3976 * Relative `.md` file names, each looked for in every directory.
3977 */
3978 names: readonly string[];
3979 /**
3980 * The file the walk goes on down to the directory of, relative to the
3981 * working directory or absolute; absent, it ends at the working directory.
3982 */
3983 of?: string;
3984 /**
3985 * The directory the walk starts beneath, relative to the working directory
3986 * or absolute; absent, the walk starts at the filesystem root.
3987 *
3988 * Only directories strictly inside it are read, so with `of` a file under
3989 * the project root the walk reads the directories between the two, as the
3990 * engine reads a nested CLAUDE.md; a file not inside it finds nothing.
3991 */
3992 below?: string;
3993 };
3994
3995 /**
3996 * What `$.fs.read(path, { as: "bytes" })` resolves with: the file's bytes,
3997 * base64, since only plain data crosses into a plugin's environment.
3998 */
3999 export type FsBytes = {
4000 /**
4001 * The file's content, standard padded base64;
4002 * `Uint8Array.fromBase64(base64)` gives the bytes back.
4003 */
4004 base64: string;
4005 };
4006
4007 /**
4008 * One entry of `$.fs.list`: the entry itself, a link not followed.
4009 */
4010 export type FsEntry = {
4011 /**
4012 * The entry's name (no directory part).
4013 */
4014 name: string;
4015 /**
4016 * `file`, `dir`, or `other`, of the entry itself: a symbolic link is
4017 * `other` (`$.fs.stat` says what it leads to, and with `resolve` where).
4018 */
4019 kind: 'file' | 'dir' | 'other';
4020 /**
4021 * Bytes, for a file.
4022 */
4023 size: number;
4024 /**
4025 * True when the entry is a symbolic link.
4026 */
4027 isLink: boolean;
4028 };
4029
4030 /**
4031 * How `$.fs.read` answers: `text` (UTF-8, the default) or `bytes` (base64).
4032 */
4033 export type FsReadAs = 'text' | 'bytes';
4034
4035 /**
4036 * The options of `$.fs.read` that ask for the bytes: the call answers
4037 * `{ base64 }`.
4038 */
4039 export type FsReadBytesOptions = {
4040 /**
4041 * `bytes`.
4042 */
4043 as: 'bytes';
4044 };
4045
4046 /**
4047 * `$.fs.read`: the file's text, or with `{ as: "bytes" }` its bytes as
4048 * `{ base64 }`.
4049 */
4050 export type FsReadCall = {
4051 (path: string): Promise<string>;
4052 (path: string, options: FsReadBytesOptions): Promise<FsBytes>;
4053 (path: string, options: FsReadOptions): Promise<string | FsBytes>;
4054 };
4055
4056 /**
4057 * The options of `$.fs.read`.
4058 */
4059 export type FsReadOptions = {
4060 /**
4061 * `bytes` answers `{ base64 }` for a binary file; `text` (the default) the
4062 * file's text.
4063 */
4064 as: FsReadAs;
4065 };
4066
4067 /**
4068 * What `$.fs.stat` resolves with: what the path leads to, whether the path
4069 * itself is a symbolic link, and where it lands when asked.
4070 */
4071 export type FsStat = {
4072 /**
4073 * `file`, `dir`, or `other`, of what the path leads to: a link is
4074 * followed, and one that leads nowhere is `other`.
4075 */
4076 kind: 'file' | 'dir' | 'other';
4077 /**
4078 * Bytes, for a file.
4079 */
4080 size: number;
4081 /**
4082 * Last modification, milliseconds since the epoch.
4083 */
4084 mtimeMs: number;
4085 /**
4086 * True when the path itself is a symbolic link; `kind`, `size` and
4087 * `mtimeMs` then describe what it points at, or the link when that is gone.
4088 */
4089 isLink: boolean;
4090 /**
4091 * Where the path landed when asked with `{ resolve: true }`: absolute,
4092 * every symbolic link followed, `.` and `..` folded; else absent.
4093 *
4094 * Absent too when the path leads nowhere or a hook above withheld it, so
4095 * a guard denies without it; and a hard link, a volume or file-id spelling
4096 * (macOS `/.vol/`) or a case alias keeps its own spelling, `isLink` false.
4097 *
4098 * @remarks a deny-list on spellings is thus best effort; an allow-list on
4099 * `realPath` under a root resolved the same way is the robust guard.
4100 */
4101 realPath?: string;
4102 };
4103
4104 /**
4105 * The options of `$.fs.stat`.
4106 */
4107 export type FsStatOptions = {
4108 /**
4109 * True to resolve where the path lands as well.
4110 *
4111 * The answer then carries `realPath` when the path leads somewhere, at
4112 * the cost of one more file system call: where it landed then, not a hold
4113 * on what a tool opens afterwards.
4114 */
4115 resolve: boolean;
4116 };
4117
4118 /**
4119 * Every event (`*`), or every event under a namespace (`classic.*`: each
4120 * one whose name starts with `classic.`).
4121 */
4122 export type Glob = '*' | `${Namespace}.*`;
4123
4124 /**
4125 * The hook `on(pattern, hook)` takes for a glob or a negation: one function
4126 * placed on every selected event, `e` and the result typed as their union.
4127 *
4128 * `next.event` says which event a run is; `next.is(pattern, e)` narrows `e`
4129 * to one of them. At `engine.create` (a negation may select it) `$` is the
4130 * empty table and the hook observes the fold, as a `*` hook does.
4131 */
4132 export type GlobHook<P extends Pattern, N extends EventName = Selected<P>> = ($: EngineInterface, e: Frozen<Args<N>>, next: GlobNext<P>) => EventResult<N> | Promise<EventResult<N>>;
4133
4134 /**
4135 * `next` in a hook on a glob or a negation: an overload per selected event,
4136 * then one over their union for an `e` not yet narrowed.
4137 *
4138 * `is` narrows `e` to the selected events its pattern names; `event` is one
4139 * of the selected names.
4140 */
4141 export type GlobNext<P extends Pattern, N extends EventName = Selected<P>> = OrderedOverloads<N> & {
4142 (e: Args<N>): Promise<GlobNextResult<N>>;
4143 /**
4144 * Continues this dispatch at a tier, as Next's `to` (a managed hook's),
4145 * over the selected events' union for an `e` not yet narrowed.
4146 */
4147 readonly to: (e: Args<N>, tier: TargetTier) => Promise<GlobNextResult<N>>;
4148 readonly signal: AbortSignal;
4149 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<Args<Extract<N, Selected<M>>>>;
4150 readonly event: N;
4151 readonly origin: Origin;
4152 readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
4153 readonly budget: NextBudget;
4154 };
4155
4156 /**
4157 * What `next(e)` resolves to in a glob hook before `e` is narrowed: the
4158 * NextResult of each selected event, as a union.
4159 */
4160 type GlobNextResult<N extends EventName> = {
4161 [K in N]: NextResult<K>;
4162 }[N];
4163
4164 /**
4165 * One hook, `($, e, next)`, on event `E`.
4166 */
4167 export type Hook<E extends EventName = EventName> = Events[E];
4168
4169 /**
4170 * The time bounds every hook runs under, in milliseconds: the engine's own
4171 * constants are typed by these members, and `next.budget` reads the live one.
4172 *
4173 * Each bounds the hook's OWN time: the clock stops while a `next(e)` call or
4174 * any `$` call of the hook's is in flight (a `$.clock` wait excepted), so a
4175 * slow chain beneath or a minute-long `$.model.complete` costs it nothing.
4176 *
4177 * @example
4178 * await $.model.complete(ask) // a minute; next.budget.remainingMs unmoved
4179 */
4180 export type HookBudget = {
4181 /**
4182 * A hook's budget per dispatch, from its call to its return; past it the
4183 * hook is absent (its `.catch` asked, else `next(e)` run on its behalf).
4184 *
4185 * A streaming hook's (`turn.step`, an async generator) spans its whole
4186 * run and counts only while its own code runs: never at a `yield`, never
4187 * while it reads the stream beneath. Not per chunk: the sum of its work.
4188 */
4189 readonly ms: 10_000;
4190 /**
4191 * A `.catch` handler's grace: a fresh budget from the moment it is called,
4192 * on the same clock (its `next` replay and its `$` calls are free).
4193 *
4194 * Past it the hook is absent as if it had no handler; `next.error.budget`
4195 * and `next.budget.ms` both read it there. `engine.create` has no budget.
4196 */
4197 readonly catchMs: 1_000;
4198 /**
4199 * How long a hook may keep running after `next.signal` aborted (the person
4200 * interrupted, a hook above settled first, its own budget ran out).
4201 *
4202 * Past it the hook is reported as lingering; the dispatch had already gone
4203 * on without it when the signal aborted.
4204 */
4205 readonly lingerMs: 5_000;
4206 };
4207
4208 /**
4209 * Why a hook failed, as its `.catch` handler reads it on `next.error`: plain
4210 * frozen data.
4211 *
4212 * `throw`: the hook threw, or returned what the site refuses, `message`
4213 * saying what; `timeout`: it outran its budget, `message` then what its last
4214 * `next()` rejected with, if it did. `budget` is the handler's own grace.
4215 */
4216 export type HookFailure = {
4217 readonly kind: 'throw' | 'timeout';
4218 /**
4219 * The thrown error's message, or for a timeout what the hook's last
4220 * `next()` rejected with; absent for a timeout with nothing rejected.
4221 */
4222 readonly message?: string;
4223 /**
4224 * The grace the handler runs under, in milliseconds; past it, the hook is
4225 * absent as if it had no handler.
4226 */
4227 readonly budget: number;
4228 };
4229
4230 /**
4231 * The hook type per pattern: an event's own (Events), `*`'s (AnyEventHook),
4232 * or a glob's over the events it selects (GlobHook), as one conditional type.
4233 *
4234 * One type, so the two-argument `on` stays ONE generic signature: as an
4235 * overload set the language service offers no tool-name completions inside
4236 * `e.tool === "`; as an index into a table TS intersects every argument.
4237 */
4238 export type HookFor<P extends Pattern> = P extends '*' ? AnyEventHook : P extends EventName ? Events[P] : GlobHook<P>;
4239
4240 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;
4241
4242 /**
4243 * The hook event `E` takes: an async generator over its chunks for a
4244 * streaming event (`turn.step`), `($, e, next) => result` for every other.
4245 */
4246 export type HookOf<E extends EventName> = Events[E];
4247
4248 /**
4249 * What a hooks module exports: `register`, and nothing the loader reads
4250 * besides.
4251 */
4252 export type HooksModule = {
4253 register: Register;
4254 };
4255
4256 /**
4257 * What `next(e)` returns on a streaming event: the stream of everything
4258 * beneath, chunk by chunk, whose return value is the result from beneath.
4259 *
4260 * `yield* next(e)` forwards the chunks and evaluates to that result; a
4261 * transforming hook reads `for await (const chunk of stream)` and then
4262 * `await stream.result`. Each call runs what is beneath afresh.
4263 */
4264 export type HookStream<C, R> = AsyncGenerator<C, R> & {
4265 /**
4266 * Settles with what beneath returned once the stream has been read to
4267 * its end; rejects if the stream is closed before that.
4268 */
4269 readonly result: Promise<R>;
4270 };
4271
4272 /**
4273 * Options of `$.http.fetch`.
4274 */
4275 export type HttpInit = {
4276 /**
4277 * `GET` (default), `POST`, ...
4278 */
4279 method?: string;
4280 /**
4281 * Request headers.
4282 */
4283 headers?: Record<string, string>;
4284 /**
4285 * The request body, as text.
4286 */
4287 body?: string;
4288 /**
4289 * The handle `$.session.authorize()` answered: the engine sets the
4290 * session's credential header itself, only for a first-party host.
4291 */
4292 auth?: string;
4293 /**
4294 * The absolute path of a Unix domain socket the request goes over instead
4295 * of TCP (near 100 B at most): one per session, in a private directory.
4296 *
4297 * The URL still gives path, query and Host; redirects stay on it; no proxy;
4298 * `https:` is TLS verified against the URL's host (always, once `auth`
4299 * rides), so a credential reaches only its host. No relative path, no NUL.
4300 *
4301 * @example
4302 * await $.http.fetch(url, { socketPath: `${runDirectory}/bridge.sock` })
4303 */
4304 socketPath?: string;
4305 };
4306
4307 /**
4308 * What `$.http.fetch` resolves with.
4309 */
4310 export type HttpResponse = {
4311 /**
4312 * The HTTP status code.
4313 */
4314 status: number;
4315 /**
4316 * True for a 2xx status.
4317 */
4318 ok: boolean;
4319 /**
4320 * Response headers, lower-cased names.
4321 */
4322 headers: Record<string, string>;
4323 /**
4324 * The body, as text.
4325 */
4326 text: string;
4327 };
4328
4329 /**
4330 * A `$.ui.blit` argument swapping one of the caller's mounted keyed Images
4331 * to its next picture; every call sends it, so a stream needs no generation.
4332 *
4333 * The surface writes them with its frames, some sixty a second: byte and
4334 * `file` sources fold to the last per frame; every `shm` source reaches the
4335 * terminal (it unlinks each), and is denied while frames are not written.
4336 *
4337 * @example await $.ui.blit({ requestId: 'browser', key: 'view',
4338 * source: { shm: '/tb-4', format: 'rgb', width: 1280, height: 720 } })
4339 */
4340 export type ImageBlitArgs = {
4341 /**
4342 * The site the Image is drawn in, by the `requestId` this plugin draws it
4343 * under.
4344 */
4345 requestId: string;
4346 /**
4347 * The Image's `key` in that drawing.
4348 */
4349 key: string;
4350 /**
4351 * The next picture (ImageSource): bytes, or a name the terminal reads.
4352 */
4353 source: ImageSource;
4354 /**
4355 * Refused unless it is the mounted Image's width in cells. Absent, that.
4356 */
4357 columns?: number;
4358 /**
4359 * Refused unless it is the mounted Image's height in cells. Absent, that.
4360 */
4361 rows?: number;
4362 };
4363
4364 /**
4365 * The props of `Image`, the terminal surface's picture leaf: pixels over a
4366 * box of cells where the terminal can (kitty, Ghostty), the `alt` elsewhere.
4367 *
4368 * A leaf: no children, `hover` or `onPress`; the cells are text, so the
4369 * picture scrolls and clips as a word does. Drawn again with another `source`
4370 * it is replaced in place; keyed, `$.ui.blit` swaps it at the frame rate.
4371 *
4372 * @example const { bytes } = await $.fs.read('chart.png', { as: 'bytes' })
4373 * <Image source={{ png: bytes.toBase64() }} columns={40} rows={12} alt="p95" />
4374 * @example <Image key="view" source={{ shm: '/tb-7', format: 'rgb', width: 960,
4375 * height: 600 }} columns={80} rows={25} alt="the page" />
4376 */
4377 export type ImageProps = {
4378 /**
4379 * The element's address within the drawing: what `$.ui.blit` names to swap.
4380 *
4381 * Unique among the Images of one tree; absent, only a redraw changes it.
4382 */
4383 key?: string;
4384 /**
4385 * The picture (ImageSource): `{ png }` or `{ rgba, width, height }` bytes,
4386 * or `{ file, format }` / `{ shm, format, width, height }` read here.
4387 */
4388 source: ImageSource;
4389 /** How many terminal columns wide, 1 to 255; the picture is scaled to fill
4390 * the box and the site clips what its body cannot show. */
4391 columns: number;
4392 /**
4393 * How many terminal rows tall, 1 to 255.
4394 */
4395 rows: number;
4396 /**
4397 * What the picture says, drawn dim in its place where the picture cannot
4398 * be (and read by a screen reader); required, may be a single space.
4399 */
4400 alt: string;
4401 };
4402
4403 /**
4404 * The picture an `Image` shows: base64 bytes the plugin holds (at most 2 MiB
4405 * decoded), or the name of a file or POSIX shared-memory object it does not.
4406 *
4407 * A name is one another process on this machine wrote; the terminal, running
4408 * as the person, opens, reads and decodes it itself, so no pixel crosses `$`
4409 * and the engine never touches it. One it will not read (not a regular file,
4410 * under `/proc`, `/sys` or `/dev`, gone, across ssh) draws a blank box, its
4411 * words in the debug log; it unlinks a shared-memory object once read, so
4412 * each frame is a fresh one. A source equal to the last drawn sends nothing;
4413 * `generation` makes new content under an unchanged name a new source.
4414 *
4415 * @example { rgba: pixels.toBase64(), width: 64, height: 32 }
4416 * @example { file: '/dev/shm/frame-3.rgba', format: 'rgba', width: 640,
4417 * height: 400 }
4418 * @example { shm: '/tb-view-2', format: 'rgb', width: 1280, height: 720 }
4419 */
4420 export type ImageSource = {
4421 /**
4422 * A whole PNG file, base64.
4423 */
4424 png: string;
4425 } | {
4426 /**
4427 * `width * height` RGBA pixels, 4 bytes each, base64.
4428 */
4429 rgba: string;
4430 /**
4431 * Pixels per row, 1 to 2048.
4432 */
4433 width: number;
4434 /**
4435 * Rows of pixels, 1 to 2048.
4436 */
4437 height: number;
4438 } | {
4439 /**
4440 * The absolute path of a regular file holding a whole PNG, at most
4441 * 3072 bytes of path; read by the terminal, left in place.
4442 */
4443 file: string;
4444 /**
4445 * The file is a whole PNG; the terminal decodes it and sizes it itself.
4446 */
4447 format: 'png';
4448 /**
4449 * A whole number that changes when the file's content does under the
4450 * same path, so a redraw reads it again; absent, the path alone tells.
4451 */
4452 generation?: number;
4453 } | {
4454 /**
4455 * The absolute path of a regular file of `width * height` raw pixels, at
4456 * most 3072 bytes of path; read by the terminal, left in place.
4457 *
4458 * On Linux a file under `/dev/shm` is memory.
4459 */
4460 file: string;
4461 /**
4462 * `rgba`, 4 bytes a pixel, or `rgb`, 3.
4463 */
4464 format: 'rgba' | 'rgb';
4465 /**
4466 * Pixels per row, 1 to 4096.
4467 */
4468 width: number;
4469 /**
4470 * Rows of pixels, 1 to 4096.
4471 */
4472 height: number;
4473 /**
4474 * A whole number that changes when the file's content does under the
4475 * same path, so a redraw reads it again; absent, the path alone tells.
4476 */
4477 generation?: number;
4478 } | {
4479 /**
4480 * The name of a POSIX shared-memory object of `width * height` raw
4481 * pixels: `/` then up to 254 of `A-Z a-z 0-9 . _ -` (macOS takes 30).
4482 *
4483 * The terminal unlinks it after reading, so a name feeds one Image
4484 * drawn once and is never sent again on a redraw; POSIX terminals only.
4485 */
4486 shm: string;
4487 /**
4488 * `rgba`, 4 bytes a pixel, or `rgb`, 3.
4489 */
4490 format: 'rgba' | 'rgb';
4491 /**
4492 * Pixels per row, 1 to 4096.
4493 */
4494 width: number;
4495 /**
4496 * Rows of pixels, 1 to 4096.
4497 */
4498 height: number;
4499 /**
4500 * A whole number that changes when a fresh object reuses a name, so a
4501 * redraw reads it again; absent, the name alone tells.
4502 */
4503 generation?: number;
4504 };
4505
4506 /**
4507 * The keys of object pattern `P` that object member `E` cannot satisfy, `D`
4508 * levels down; `never` when there is none, which is what keeps the member.
4509 *
4510 * A key `E` does not have (an open record has every string key), or one
4511 * whose value `P` narrows to nothing.
4512 */
4513 type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
4514 [K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
4515 }[keyof P];
4516
4517 /**
4518 * The props of `Input`, every surface's one-line text field: an address,
4519 * optional texts, and the closures a change and a submit run. A leaf.
4520 *
4521 * Focused through the same ring as `Button` (`abovePrompt:focus`); while it
4522 * has focus every printable key reaches it alone and Esc returns them; a
4523 * change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
4524 */
4525 export type InputProps = {
4526 /**
4527 * The element's address: `e.element` at `ui.input`, what a matcher names.
4528 */
4529 key: string;
4530 /**
4531 * Text drawn before the field.
4532 */
4533 label?: string;
4534 /**
4535 * Text drawn dim in an empty field.
4536 */
4537 placeholder?: string;
4538 /**
4539 * The text the field holds when drawn; the person's typing replaces it
4540 * until the hook draws another.
4541 */
4542 value?: string;
4543 /**
4544 * What Enter does, in a word or two, drawn beside the field while it has
4545 * focus (`send`). Defaults to `submit`.
4546 */
4547 submitLabel?: string;
4548 /**
4549 * The site's focus ring starts here when the site takes the keyboard,
4550 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
4551 *
4552 * A pane opened with `focus`, or the person's focus chord or click, is the
4553 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
4554 * origin this plugin. A ring the person has moved stays where it was put.
4555 */
4556 autoFocus?: true;
4557 /**
4558 * Runs on every change of the text, in the plugin's own environment: the
4559 * bottom of a `ui.input` chain of kind `change`.
4560 */
4561 onInput?: (value: string, e: UiInputArgument) => void;
4562 /**
4563 * Runs on Enter with the text, in the plugin's own environment: the bottom
4564 * of a `ui.input` chain of kind `submit`. No model turn unless it asks one.
4565 */
4566 onSubmit: (value: string, e: UiInputArgument) => void;
4567 };
4568
4569 /**
4570 * Every tier an instruction file can belong to, for checking a hook's
4571 * answer; the kind type is derived from this list.
4572 */
4573 const INSTRUCTION_FILE_KINDS: readonly ["managed", "user", "project", "local", "memory"];
4574
4575 /**
4576 * One instruction file behind the `claudeMd` block: where it was read, its
4577 * tier, its text as loaded, and the file that `@`-imported it if one did.
4578 */
4579 export type InstructionFile = {
4580 /**
4581 * The file's path, absolute.
4582 */
4583 path: string;
4584 /**
4585 * Its tier.
4586 */
4587 kind: InstructionFileKind;
4588 /**
4589 * The text as loaded (comments and frontmatter already stripped).
4590 */
4591 content: string;
4592 /**
4593 * The path of the file whose `@` import brought this one, when one did.
4594 */
4595 parent?: string;
4596 };
4597
4598 /**
4599 * What tier an instruction file belongs to: the organization's managed
4600 * policy, the person's own, the project's checked-in or private ones, memory.
4601 */
4602 export type InstructionFileKind = (typeof INSTRUCTION_FILE_KINDS)[number];
4603
4604 type InstructionsLoadedHookInput = BaseHookInput & {
4605 hook_event_name: 'InstructionsLoaded';
4606 file_path: string;
4607 memory_type: 'User' | 'Project' | 'Local' | 'Managed';
4608 load_reason: 'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact';
4609 globs?: string[];
4610 trigger_file_path?: string;
4611 parent_file_path?: string;
4612 };
4613
4614 /**
4615 * What `$.ui.invalidate` takes: a render event, or one of the six events
4616 * whose answers the engine caches for the session.
4617 */
4618 export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'prompt.attachment' | 'tool.describe' | 'command.describe' | 'config.describe';
4619
4620 /**
4621 * Whether tag key `K` selects members of `I`: it does when each member gives
4622 * it ONE literal (`component: "ToolUse"` on the ToolUse variant).
4623 *
4624 * A key that is the same union on every member is a filter at runtime; it
4625 * is left out of the selection so that it cannot defeat the narrowing the
4626 * other keys give.
4627 */
4628 type IsDiscriminant<I, K> = I extends unknown ? K extends KnownKeys<I> ? IsSingleLiteral<I[K]> : true : never;
4629
4630 /**
4631 * Whether `V` is made of literals only: `"a" | "b"` is, `string` is not.
4632 */
4633 type IsLiteralValued<V> = string extends V ? false : number extends V ? false : boolean extends V ? false : [V] extends [string | number | boolean] ? true : false;
4634
4635 /**
4636 * Whether `V` is exactly one string, number or boolean literal.
4637 */
4638 type IsSingleLiteral<V> = [V] extends [string | number | boolean] ? IsUnion<V> extends true ? false : true : false;
4639
4640 /**
4641 * Whether `T` is a union of two or more members.
4642 */
4643 type IsUnion<T, U = T> = T extends unknown ? [U] extends [T] ? false : true : never;
4644
4645 /**
4646 * Plain data: what JSON holds, and what crosses between a plugin's hooks
4647 * module and its surface module whole (a `Client`'s props, a post's data).
4648 *
4649 * A function, a class instance, `undefined` or a cycle is not plain data;
4650 * the engine refuses one where it checks, and drops it where it clones.
4651 */
4652 export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
4653 readonly [key: string]: JsonValue;
4654 };
4655
4656 /**
4657 * What `next` takes in a matched hook: the variants of `e` the matcher can
4658 * match (KeptMembers), as declared, so a rewrite of a pinned field passes.
4659 */
4660 type KeptEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? KeptMembers<Args<N>, M> : never : never;
4661
4662 /**
4663 * The members of the argument union `E` matcher `P` can match, as declared;
4664 * what `next` takes, so a rewrite may change a field the matcher pinned.
4665 *
4666 * A member is dropped when `P` names a key it lacks, or gives a key, at any
4667 * depth, a value none of that key's values can equal (ImpossibleKeys).
4668 */
4669 type KeptMembers<E, P> = E extends unknown ? [ImpossibleKeys<E, P, []>] extends [never] ? E : never : never;
4670
4671 /**
4672 * The declared keys of `T`, the string and number index signatures left out.
4673 */
4674 type KnownKeys<T> = keyof {
4675 [K in keyof T as string extends K ? never : number extends K ? never : K]: 0;
4676 };
4677
4678 /**
4679 * The events whose overload must come after the rest, lest it shadow them.
4680 *
4681 * `classic.PreToolUse` shares `tool.call`'s envelope, `turn.abort` every
4682 * turn event's `turnId`, and an object of any shape is assignable to NoArgs.
4683 */
4684 type LateOverload = 'classic.PreToolUse' | 'turn.abort' | NoArgsEvent;
4685
4686 /**
4687 * The props of `Link`, a hyperlink every surface draws: an OSC 8 span on the
4688 * terminal (else its text then the URL in dim), an anchor on desktop.
4689 *
4690 * An inline element: its children are the text, strings and inline
4691 * elements; absent children the `label`, absent both the URL. The engine
4692 * bounds `href` before the tree crosses.
4693 */
4694 export type LinkProps = {
4695 /**
4696 * Where the link goes: an `https:` URL (or `http://localhost`), at most
4697 * 2048 characters of printable ASCII, spelled as `new URL(href).href`.
4698 *
4699 * No `user@host` part, no raw `@`, space or non-ASCII letter (encode them);
4700 * anything else refuses the tree the Link is in.
4701 */
4702 href: string;
4703 /**
4704 * The text drawn when the element has no children; absent both, the URL
4705 * itself is the text.
4706 */
4707 label?: string;
4708 };
4709
4710 /**
4711 * What a matcher value selects by: itself, or `unknown` for a RegExp, which
4712 * selects nothing.
4713 */
4714 type Literal<X> = X extends RegExp ? unknown : X;
4715
4716 /**
4717 * What a `Markdown` carries across the boundary: its address, text, dimness
4718 * and which links it answers; `onLinkPress` stays behind, a `press` instead.
4719 */
4720 export type MarkdownLeafProps = {
4721 /**
4722 * The element's address: what `e.element` carries and what a matcher
4723 * names; present whenever the element carries a `press`.
4724 */
4725 key?: string;
4726 /**
4727 * The markdown drawn, bounded as a Text's string is.
4728 */
4729 text: string;
4730 /**
4731 * The whole block dim, as `Text`'s `dimColor`; absent draws as false.
4732 */
4733 dimColor?: boolean;
4734 /**
4735 * Which links a press belongs to, by `href` as written; absent, with a
4736 * `press`, every link drawn. Compared with the pressed target only.
4737 */
4738 pressableLinks?: readonly string[];
4739 };
4740
4741 /**
4742 * The props of `Markdown`, a block of markdown every surface draws as it
4743 * draws an assistant reply's text: its own renderer, links, tables, fences.
4744 *
4745 * A leaf: no children. `text` is the element's data as a `Text`'s string is,
4746 * bounded the same way. With `onLinkPress` the links it draws are the
4747 * plugin's to answer: a press on one raises `ui.press` addressed to `key`.
4748 */
4749 export type MarkdownProps = {
4750 /**
4751 * The element's address: `e.element` at `ui.press`, what a matcher names.
4752 * Required with `onLinkPress`, since a press needs one; else optional.
4753 */
4754 key?: string;
4755 /**
4756 * The markdown drawn, as an assistant reply would write it.
4757 *
4758 * At most 10000 characters, tab and newline its only control characters;
4759 * a link whose scheme is not `https:`, `http:` or `file:` draws as text,
4760 * never clickable. Not drawn around the approval dialog.
4761 */
4762 text: string;
4763 /**
4764 * The whole block dim, as `Text`'s `dimColor`: a thought, an aside.
4765 */
4766 dimColor?: boolean;
4767 /**
4768 * What a press on a link in `text` runs, in the plugin's own environment:
4769 * the bottom of a `ui.press` chain whose `e.link` names the link.
4770 *
4771 * A press is a plain single click where the surface reports clicks (the
4772 * fullscreen terminal): it opens nothing and lands once no double-click
4773 * followed; a ctrl, alt or terminal-kept cmd click opens it as before.
4774 */
4775 onLinkPress?: (link: PressedLink, e: UiPressArgument) => void;
4776 /**
4777 * Which links in `text` a press belongs to, by `href` as the markdown
4778 * writes it; absent, every link drawn. Only with `onLinkPress`.
4779 *
4780 * A link left out keeps the surface's own behaviour. At most 256 entries
4781 * of at most 2048 characters; compared with the pressed link's target,
4782 * never opened.
4783 */
4784 pressableLinks?: readonly string[];
4785 };
4786
4787 /**
4788 * The argument a matched hook receives: `e` narrowed by `M` (Narrowed), per
4789 * event the registration covers.
4790 */
4791 export type MatchedEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Narrowed<Args<N>, M> : never : never;
4792
4793 /**
4794 * The hook `on(pattern, matcher, hook)` takes: `($, e, next)` with `e`
4795 * narrowed by the matcher (MatchedEvent), and a tagged result the same way.
4796 *
4797 * On a streaming event it is the generator form (MatchedStreamHook). `next`
4798 * takes the variants the matcher keeps, as declared (KeptEvent); `next.is`
4799 * names the events the registration covers and narrows as the matcher does.
4800 */
4801 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>, {
4802 [K in MatchedNames<P, M>]: Narrowed<Args<K>, M>;
4803 }>) => MatchedResult<P, M> | Promise<MatchedResult<P, M>>;
4804
4805 /**
4806 * The events a matched registration on `P` covers: the event named, or for a
4807 * glob every selected event whose input has each key the matcher names.
4808 */
4809 type MatchedNames<P, M = never> = P extends EventName ? P : {
4810 [N in Selected<P & string>]: [M] extends [never] ? N : keyof M extends AnyKeyOf<Args<N>> ? N : never;
4811 }[Selected<P & string>];
4812
4813 /**
4814 * What a matched hook returns: the event's result, narrowed by `M` where the
4815 * result is a union tagged by the matcher's tag keys.
4816 */
4817 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;
4818
4819 /**
4820 * The hook `on(event, matcher, hook)` takes on a streaming event: the
4821 * generator form, `e` narrowed by the matcher, `next(e)` the stream beneath.
4822 */
4823 export type MatchedStreamHook<P extends StreamingEventName, M> = ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: MatchedStreamNext<P, M>) => StreamHookBody<Chunk<P>, MatchedResult<P, M>>;
4824
4825 /**
4826 * What a matched streaming hook's `next.is(pattern, e)` narrows `e` to:
4827 * the streaming event's argument narrowed by the matcher.
4828 */
4829 type MatchedStreamNarrowings<P extends StreamingEventName, M> = {
4830 [K in P]: Narrowed<Args<K>, M>;
4831 };
4832
4833 /**
4834 * A matched streaming hook's `next`: the variants the matcher keeps, the
4835 * result tagged the same way, `next.is` narrowing as the matcher does.
4836 */
4837 type MatchedStreamNext<P extends StreamingEventName, M> = StreamNext<P, KeptEvent<P, M>, MatchedResult<P, M>, MatchedStreamNarrowings<P, M>>;
4838
4839 /**
4840 * What `on(event, matcher, hook)` takes for an argument of type `I`: the
4841 * shape of the `e` the hook wants, a partial of it at any depth.
4842 *
4843 * A leaf is `===` or a RegExp (`{ command: /^p4 / }`); an array is any-of;
4844 * an object is a partial of an OBJECT, so `{ command: { startsWith } }` is
4845 * a type error where `e` is typed and free where it is `unknown`.
4846 */
4847 export type Matcher<I, All = I> = I extends unknown ? {
4848 readonly [K in KnownKeys<I>]?: MatcherValue<I[K], MatcherValueOf<All, K>>;
4849 } & (string extends keyof I ? OpenMatcher<I, All> : unknown) : never;
4850
4851 /**
4852 * Any matcher at all, for a field typed `unknown` (a tool's input, a
4853 * result's output): the kinds the engine accepts, unchecked there.
4854 *
4855 * The four kinds: a scalar is `===`; a RegExp tests the value as a string
4856 * (`{ command: /^p4 / }`); an array matches if any element does; an object
4857 * is a partial of an object. `{ startsWith: 'p4' }` never matches a string.
4858 */
4859 type MatcherData = string | number | boolean | null | RegExp | readonly MatcherData[] | {
4860 readonly [key: string]: MatcherData;
4861 };
4862
4863 /**
4864 * The declared keys of every variant of `I` (index signatures aside).
4865 */
4866 type MatcherKeys<I> = I extends unknown ? KnownKeys<I> : never;
4867
4868 /**
4869 * What matches one value of type `V`, by the runtime's kinds:
4870 * a scalar leaf takes the value or a RegExp; an object, a partial of it.
4871 *
4872 * For an array, what matches one ELEMENT of it, since a pattern against an
4873 * array value holds when some element matches; for `unknown`, any matcher.
4874 * A scalar matches by `===`, a RegExp tests the value as a string.
4875 */
4876 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;
4877
4878 /**
4879 * What a matcher gives a key whose value is `V` on this variant and `Across`
4880 * over every variant: one MatcherOne, or an array of them matched as one-of.
4881 *
4882 * The one-of is typed over every variant, so `{ tool: ['Bash', 'Read'] }`
4883 * types on the Bash variant; with a nested pattern beside it, the pattern is
4884 * checked against a variant the one-of names, not against each of them.
4885 */
4886 type MatcherValue<V, Across = V> = MatcherOne<V> | readonly MatcherOne<Across>[];
4887
4888 /**
4889 * The type of key `K` across the variants of `I` that declare it.
4890 */
4891 type MatcherValueOf<I, K> = I extends unknown ? K extends KnownKeys<I> ? I[K] : never : never;
4892
4893 /**
4894 * One block of an MCP result: `type` and the fields that kind of block carries.
4895 */
4896 export type McpContentBlock = {
4897 /**
4898 * The block's kind: `text`, `image`, `audio`, `resource`, `resource_link`.
4899 */
4900 type: string;
4901 /**
4902 * Set on a `text` block.
4903 */
4904 text?: string;
4905 /**
4906 * Set on a `resource_link` (or embedded `resource`) block.
4907 */
4908 uri?: string;
4909 /**
4910 * Declared by an image, audio or resource block.
4911 */
4912 mimeType?: string;
4913 [field: string]: unknown;
4914 };
4915
4916 /**
4917 * The MCP server serving this tool, for `mcp__*` tools: `name` is the server's config key (for `source: "sdk"`, exactly the name the SDK host registered in `sdkMcpServers` / `mcp_set_servers`; for any other source, the key as authored in that configuration - untrusted text, the same value `mcp_status` and system/init report, to be escaped before display), `source` is where its definition came from - `sdk` (an in-process server the SDK host runs; only the host can register one, so a configured server of the same name never reads `sdk`), `plugin` (a server a plugin ships or registers at runtime), or a config scope (`user`, `project`, `local`, `dynamic` for --mcp-config / `mcp_set_servers` process servers, `managed`, `enterprise`, `claudeai`, `agent`). Key trust on `source`, not on the name or the tool-name prefix. Absent for non-MCP tools.
4918 */
4919 type McpServerProvenance = {
4920 name: string;
4921 /**
4922 * sdk | plugin | user | project | local | dynamic | managed | enterprise | claudeai | agent - an open set; treat unknown values as an unrecognized configured source, never as sdk.
4923 */
4924 source: string;
4925 };
4926
4927 /**
4928 * The MCP branch of a `tool.call` hook's `e` (and of `$.tool.call`'s input):
4929 * one variant per declared tool, else the loose McpToolCallInputFallback.
4930 *
4931 * `$.mcp.call(server, tool, args)` takes none of these: its parameters are
4932 * positional, the server and tool by name, then the arguments object.
4933 */
4934 export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
4935 [N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
4936 }[keyof McpToolInputs & string];
4937
4938 /**
4939 * The `e` a `tool.call` (or `classic.PreToolUse`) hook receives for an MCP
4940 * tool while no MCP tool is declared: every `mcp__*` name, loose arguments.
4941 *
4942 * McpToolInputs has no entries until `/plugin-types` writes the connected
4943 * tools' declarations; also the `input` of `$.tool.call({ tool:
4944 * "mcp__<server>__<tool>", ... })`. Not `$.mcp.call`'s, which is positional:
4945 *
4946 * @example
4947 * on("tool.call", { tool: "mcp__gh__issue" }, ($, e, next) => audit(e.title))
4948 */
4949 type McpToolCallInputFallback = {
4950 /**
4951 * The name of the tool being called (`mcp__<server>__<tool>`); comparing
4952 * it narrows `e`. Reserved: a rewrite of it is ignored by core.
4953 */
4954 tool: McpToolName;
4955 /**
4956 * The tool_use block's id: the same at every event of the call and in
4957 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
4958 */
4959 tool_use_id: string;
4960 [argument: string]: unknown;
4961 };
4962
4963 /**
4964 * The inputs of the MCP tools this project knows, keyed by full tool name,
4965 * for declaration merging; empty by default, then every MCP tool is loose.
4966 *
4967 * A `.d.ts` in the plugin author's project (written by `/plugin-types <dir>`
4968 * from the connected servers' JSON Schemas, or by hand) adds entries under
4969 * `declare module "claude-code"`; `e.tool === <name>` then narrows to them.
4970 *
4971 * @example
4972 * interface McpToolInputs { "mcp__my_server__send": { to: string } }
4973 */
4974 export interface McpToolInputs {
4975 }
4976
4977 /**
4978 * The name of an MCP tool as the engine spells it: `mcp__<server>__<tool>`.
4979 */
4980 export type McpToolName = `mcp__${string}__${string}`;
4981
4982 /**
4983 * An MCP tools/call result as the SDK returns it, plain data.
4984 */
4985 export type McpToolResult = {
4986 /**
4987 * The result's content blocks, in order (text, image, resource,
4988 * resource_link, ...).
4989 */
4990 content: McpContentBlock[];
4991 /**
4992 * True when the server reported the call as failed; the blocks then describe
4993 * the error.
4994 */
4995 isError: boolean;
4996 /**
4997 * The server's structured result, when its tool declares an output schema.
4998 */
4999 structuredContent?: unknown;
5000 };
5001
5002 /**
5003 * 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.
5004 */
5005 type MessageDisplayHookInput = BaseHookInput & {
5006 hook_event_name: 'MessageDisplay';
5007 /**
5008 * UUID of the current turn.
5009 */
5010 turn_id: string;
5011 /**
5012 * UUID of the assistant message being displayed. Stable across every flush of the same message. Not the API msg_... id.
5013 */
5014 message_id: string;
5015 /**
5016 * Zero-based index of this delta within the message. Increments by one per flush.
5017 */
5018 index: number;
5019 /**
5020 * True on the message's last flush. Exactly one flush per message has it.
5021 */
5022 final: boolean;
5023 /**
5024 * 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.
5025 */
5026 delta: string;
5027 };
5028
5029 /**
5030 * What `$.model.complete` takes.
5031 */
5032 export type ModelCompleteRequest = {
5033 /**
5034 * An alias (`haiku`) or a full model id; resolved and allowlist-checked like
5035 * a `--model` value.
5036 */
5037 model: string;
5038 /**
5039 * The one user message; the reply's text comes back.
5040 */
5041 prompt: string;
5042 /**
5043 * Precedes the completion as its system prompt, after the CLI's identity
5044 * block. Default none.
5045 */
5046 system?: string;
5047 /**
5048 * The reply's token cap: any positive integer up to what one reply can
5049 * hold, the model's own output limit or 64000, whichever is lower.
5050 *
5051 * Default 1024. The reply comes back whole, not streamed, and a provider
5052 * ends such a request at ten minutes, hence the 64000. One past the limit
5053 * is refused, naming it.
5054 */
5055 maxTokens?: number;
5056 };
5057
5058 /**
5059 * What `$.model.fork` takes.
5060 */
5061 export type ModelForkRequest = {
5062 /**
5063 * The one user message, appended to the session's own transcript.
5064 *
5065 * The reply's text and usage come back, or null on an API error or a cold
5066 * transcript.
5067 */
5068 prompt: string;
5069 };
5070
5071 /**
5072 * What `$.model.fork` resolves to when the fork answered: the reply's text
5073 * and what the fork cost.
5074 */
5075 export type ModelForkResult = {
5076 /**
5077 * The non-error replies' text, joined by newlines.
5078 */
5079 text: string;
5080 /**
5081 * The fork's token counts, so a plugin can account for what it spent.
5082 */
5083 usage: ModelForkUsage;
5084 };
5085
5086 /**
5087 * What one fork cost, as the API counted it: the four token counts of the
5088 * fork's completions summed.
5089 */
5090 export type ModelForkUsage = {
5091 input_tokens: number;
5092 output_tokens: number;
5093 cache_read_input_tokens: number;
5094 cache_creation_input_tokens: number;
5095 };
5096
5097 /**
5098 * The prefixes a glob may name: one or more whole leading segments of an
5099 * event name (`tool` of `tool.call`), derived, plugin nouns included.
5100 */
5101 export type Namespace<N extends string = EventName> = N extends `${infer Head}.${infer Rest}` ? Head | `${Head}.${Namespace<Rest>}` : never;
5102
5103 /**
5104 * How many object or array levels a matcher narrows `e` through, counted as
5105 * a tuple's length: the runtime's own limit, which refuses a deeper matcher.
5106 *
5107 * Past it a field keeps its declared type; nothing becomes `any`.
5108 */
5109 type NarrowDepth = 8;
5110
5111 /**
5112 * `e` in a matched hook: the members of the argument union `E` matcher `P`
5113 * can match, each with the keys `P` names narrowed to what a match implies.
5114 *
5115 * A scalar narrows to the literal, a one-of to what its alternatives give,
5116 * an object key recursively, an array some element of which must match to
5117 * a non-empty tuple; other keys, `unknown` and RegExp-matched fields keep.
5118 */
5119 export type Narrowed<E, P> = E extends unknown ? NarrowedMember<E, P, []> : never;
5120
5121 /**
5122 * A value of declared type `V` under a one-of, folded over the tuple into
5123 * `Found`: the union of what each alternative narrows `V` to (NarrowedByOne).
5124 *
5125 * An alternative that cannot match adds nothing, so a one-of none of whose
5126 * alternatives can is `never`; a one-of typed as a plain array rather than
5127 * a tuple narrows by the union of its elements at once.
5128 */
5129 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>;
5130
5131 /**
5132 * A value of declared type `V` under one matcher node `Q` that is not a
5133 * one-of, member of `V` by member; a member that cannot match is `never`.
5134 *
5135 * An array some element of which must match becomes NonEmpty; a RegExp
5136 * keeps the member; an object pattern recurses into an object member, one
5137 * level down; a scalar keeps a member as narrow, and replaces a wider one.
5138 */
5139 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;
5140
5141 /**
5142 * One object member `E` under object pattern `P`, `D` levels down: `never`
5143 * when a key of `P` is impossible on it (ImpossibleKeys), else `E` narrowed.
5144 *
5145 * Each key `P` names is narrowed (NarrowedValue); every other key, and each
5146 * key's optionality, stays as declared.
5147 */
5148 type NarrowedMember<E, P, D extends readonly unknown[]> = [
5149 ImpossibleKeys<E, P, D>
5150 ] extends [never] ? {
5151 [K in keyof E]: K extends keyof P ? NarrowedValue<E[K], P[K], D> : E[K];
5152 } : never;
5153
5154 /**
5155 * A value of declared type `V` where the matcher gives `Q`, `D` levels
5156 * down: NarrowedByAny under a one-of (an array), NarrowedByOne otherwise.
5157 *
5158 * As declared once `D` reaches NarrowDepth, or for a field typed `unknown`
5159 * (a tool's input), which no pattern narrows.
5160 */
5161 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>;
5162
5163 /**
5164 * `!` before a name or a glob: every event except the ones it selects. `!*`
5165 * would select none, so it is no pattern.
5166 */
5167 type Negation = `!${Exclude<EventName | Glob, '*'>}`;
5168
5169 /**
5170 * The rest of the chain, as one hook receives it: made once per dispatch per
5171 * hook, frozen; `next(e)` resolves to the downstream result.
5172 *
5173 * Each call runs the hooks below again; core is the last, and below it `next`
5174 * rejects. Called with no argument it rejects, naming the hook. A hook that
5175 * returns without calling it ends the chain; returning nothing is a failure.
5176 *
5177 * @template S what `next.is(pattern, e)` narrows `e` to, per event: the event's
5178 * argument, or, under a matcher, that argument narrowed by it (MatchedHook)
5179 * @template T the tool `e` names, when it names one: on `tool.call` it types
5180 * the result (NextResultFor); an `e` without `tool` takes the line beneath
5181 */
5182 export type Next<N extends EventName = EventName, E = Args<N>, O = NextResult<N>, S extends {
5183 [K in N]?: unknown;
5184 } = {
5185 [K in N]: Args<K>;
5186 }> = {
5187 <T extends string>(e: E & ToolNamed<T>): Promise<NextResultFor<N, O, T>>;
5188 (e: E): Promise<O>;
5189 /**
5190 * Continues this dispatch at a tier: `next(e)` with every link between
5191 * this hook's own tier and that one skipped, by tier and narrowing only.
5192 *
5193 * A managed hook's: prepend may name append, builtin or core, append core;
5194 * it never skips a tier with more authority, so no user hook skips the
5195 * org's. A literal on the hook's own `next`; skipped links are traced.
5196 */
5197 readonly to: {
5198 <T extends string>(e: E & ToolNamed<T>, tier: TargetTier): Promise<NextResultFor<N, O, T>>;
5199 (e: E, tier: TargetTier): Promise<O>;
5200 };
5201 /**
5202 * Aborts when the call this dispatch belongs to is abandoned: the user
5203 * interrupted, a hook above settled first, or this hook ran out of budget.
5204 *
5205 * Anything the hook started (timers, requests) should stop on it. It is an
5206 * AbortSignal of the plugin's own environment, driven by the chain's.
5207 */
5208 readonly signal: AbortSignal;
5209 /**
5210 * Whether this dispatch's event is selected by `pattern` (a name, a glob,
5211 * a negation), as a type predicate on `e`: `next.is("tool.call", e)`.
5212 *
5213 * Under a matcher the narrowing includes it. `pattern` names events this
5214 * hook covers (PatternOver); a name outside them is a compile error.
5215 */
5216 readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<S[Extract<N, Selected<M>>]>;
5217 /**
5218 * The name of this dispatch's event, as a value, for a glob hook to log or
5219 * switch on.
5220 */
5221 readonly event: N;
5222 /**
5223 * Who raised this dispatch: the calling plugin's name and the tier it sits
5224 * in (Origin); the engine reads `{ plugin: "engine", tier: "core" }`.
5225 *
5226 * Set by the host alone, from the environment the call came from (its own
5227 * MessagePort) and that plugin's seat; nothing a plugin writes reaches it.
5228 * Every hook of one dispatch sees the same origin, and `next.to` keeps it.
5229 *
5230 * @example
5231 * return next.origin.tier === "prepend" ? next.to(e, "append") : next(e)
5232 */
5233 readonly origin: Origin;
5234 /**
5235 * What settled beneath this hook on its latest `next()` call, the one
5236 * started last: an entry per link beneath, nearest first, the engine's last.
5237 *
5238 * Empty before `next` is called; filled even when `next` rejected; a link
5239 * still running joins in place later, nothing listed leaves; it ends short
5240 * of the engine at a link that answered its last call itself. Data, frozen.
5241 */
5242 readonly trace: readonly TraceEntry<N, E, O>[];
5243 /**
5244 * How much time this hook runs under and how much is left (NextBudget),
5245 * read fresh on each access; HookBudget says what the clock counts.
5246 *
5247 * It stands still while a `next` or `$` call of the hook's is in flight;
5248 * in a `.catch` handler it is the grace, `ms` being `next.error.budget`.
5249 *
5250 * @example
5251 * if (next.budget.remainingMs < 2_000) return next(e) // skip the polish
5252 */
5253 readonly budget: NextBudget;
5254 };
5255
5256 /**
5257 * The budget the code reading `next.budget` runs under: the whole allowance
5258 * and what is left of it now, plain data read fresh on each access.
5259 *
5260 * In a hook `ms` is HookBudget's `ms`; in a `.catch` handler its `catchMs`
5261 * (equal to `next.error.budget`); on a `next` nothing meters (the engine's
5262 * own, a test's root one) `ms` is 0 and `remainingMs` Infinity.
5263 *
5264 * @example
5265 * if (next.budget.remainingMs < 2_000) return next(e) // skip the slow path
5266 */
5267 export type NextBudget = {
5268 /**
5269 * The whole budget in milliseconds; 0 where nothing meters this `next`.
5270 */
5271 readonly ms: number;
5272 /**
5273 * What is left of it now, in milliseconds, never below 0; Infinity where
5274 * nothing meters. It stands still while a `next` or `$` call is in flight.
5275 */
5276 readonly remainingMs: number;
5277 };
5278
5279 /**
5280 * What `next(e)` resolves to for event `N`: the event's result, except at
5281 * `engine.create`, where the steps beneath return `$` as built so far.
5282 *
5283 * A withheld noun is on that `$` as a stub, so the built table is typed
5284 * whole where what a hook returns (EngineCreateResult) is partial.
5285 */
5286 export type NextResult<N extends EventName> = N extends 'engine.create' ? EngineInterfaceBuilt : EventResult<N>;
5287
5288 /**
5289 * What `next(e)` resolves to once `e.tool` is the literal `T`: on `tool.call`
5290 * the result typed for that tool; on every other event, `O` as declared.
5291 *
5292 * `result` is Bash's record after `e.tool === "Bash"`; an un-narrowed `e`
5293 * names every tool, and `result` stays `unknown`.
5294 */
5295 export type NextResultFor<N extends EventName, O, T extends string> = [
5296 N
5297 ] extends ['tool.call'] ? ToolCallResult<T> : O;
5298
5299 /**
5300 * The argument of a call on `$` that takes nothing (`$.session.cwd()`): an
5301 * object with no keys.
5302 */
5303 type NoArgs = Record<never, never>;
5304
5305 /**
5306 * The events whose argument is exactly NoArgs (`session.cwd`, a declared
5307 * plugin noun's `() => ...`); their overloads come last (LateOverload).
5308 */
5309 type NoArgsEvent = {
5310 [N in EventName]: Args<N> extends NoArgs ? NoArgs extends Args<N> ? N : never : never;
5311 }[EventName];
5312
5313 /**
5314 * What an `engine.create` hook receives as `$`: nothing. Every property
5315 * reads as `never`, so `$.model` inside the hook is a compile error.
5316 */
5317 export type NoEngineInterface = {
5318 readonly [noun: string]: never;
5319 };
5320
5321 /**
5322 * Array type `V`, of element `Item`, once some element of it is known to
5323 * match: a tuple of at least one `Item`, readonly when `V` is.
5324 *
5325 * So `e` still passes wherever the declared array is taken; a `V` that is
5326 * already a non-empty tuple is kept as it is.
5327 */
5328 type NonEmpty<V, Item> = V extends readonly [unknown, ...unknown[]] ? V : V extends Item[] ? [Item, ...Item[]] : readonly [Item, ...Item[]];
5329
5330 type NotificationHookInput = BaseHookInput & {
5331 hook_event_name: 'Notification';
5332 message: string;
5333 title?: string;
5334 notification_type: string;
5335 };
5336
5337 /**
5338 * The declared plugin nouns' methods as event rows (NounEventRow), one per
5339 * `<noun>.<method>` that is a function; a member that is not is no event.
5340 */
5341 type NounEvent = {
5342 [K in PluginNoun]: {
5343 [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;
5344 }[keyof EngineInterface[K] & string];
5345 }[PluginNoun];
5346
5347 /**
5348 * The name of a declared plugin noun's event (`voice.speak`).
5349 */
5350 type NounEventName = keyof NounEventOf & string;
5351
5352 /**
5353 * The events of the plugin nouns declared on EngineInterface, by name: the
5354 * argument of each `<noun>.<method>`. Empty until a plugin declares a noun.
5355 *
5356 * @example
5357 * declare module "claude-code" { interface EngineInterface { voice: Voice } }
5358 */
5359 export type NounEventOf = {
5360 [E in NounEvent as E['name']]: E['args'];
5361 };
5362
5363 /**
5364 * The result of a declared plugin noun's event as its hooks see it:
5365 * `{ value }` (the method's answer) or `{ deny }`.
5366 */
5367 type NounEventResult<N extends NounEventName> = ValueOrDeny<NounValueOf[N]>;
5368
5369 /**
5370 * One method of a declared plugin noun as an event row: its event's name,
5371 * argument (the method's first parameter) and value (its awaited result).
5372 */
5373 type NounEventRow<Name extends string, Args, Value> = {
5374 name: Name;
5375 args: Args;
5376 value: Value;
5377 };
5378
5379 /**
5380 * What each declared plugin noun's method answers (the `value` of its
5381 * event's result), by event name.
5382 */
5383 type NounValueOf = {
5384 [E in NounEvent as E['name']]: E['value'];
5385 };
5386
5387 /**
5388 * Registers `hook` on the events `pattern` selects: one by name, every one
5389 * under a namespace (`classic.*`), all (`*`), or all but some (`!tool.*`).
5390 *
5391 * One function stands on every selected event (`next.event` says which),
5392 * under a matcher for the inputs it matches; a plugin's registrations nest
5393 * in order, first outermost; a repeat throws. Returns the Registration.
5394 *
5395 * @see HookBudget the time each hook has per dispatch (its own time: waits
5396 * on `next` and `$` are free), read live from `next.budget`
5397 */
5398 export type On = {
5399 <P extends Pattern>(pattern: P, hook: NoInfer<HookFor<P>>): Registration<HookFor<P>>;
5400 <P extends Pattern, const M extends Matcher<Args<MatchedNames<P>>>>(pattern: P, matcher: M, hook: NoInfer<MatchedHook<P, M>>): Registration<MatchedHook<P, M>>;
5401 };
5402
5403 /**
5404 * The part of a transcript message the surface that drew it has on screen:
5405 * units `first` to `last` of the message's `of`, counted from its start.
5406 *
5407 * The terminal counts the rows the site laid out, from its first (the blank
5408 * row the engine draws above a message is its row 0; a hook's tree starts at
5409 * its own); other surfaces count in their unit, so compare `first / of` there.
5410 *
5411 * @remarks While `null` the terminal holds the site at the rows it last laid
5412 * out (a scroller's geometry needs real rows); on screen, draw anything.
5413 * @example if (e.props.onScreen) shown.set(e.requestId, e.props.onScreen)
5414 * else shown.delete(e.requestId) // the band's legend lists `shown`
5415 */
5416 type OnScreen = {
5417 /**
5418 * The unit inside the viewport, from 0: on the terminal, `7` when the
5419 * message's top seven rows are scrolled away.
5420 */
5421 first: number;
5422 /**
5423 * The unit inside the viewport, inclusive; at least `first`.
5424 */
5425 last: number;
5426 /**
5427 * The message's whole extent in the same unit, as laid out (a hook's tree
5428 * taller than the engine's counts its own rows); more than `last`.
5429 *
5430 * One surface's numbers say nothing of another's: what the phone shows the
5431 * terminal may not, and each `ui.render` carries its own surface's.
5432 */
5433 of: number;
5434 };
5435
5436 /**
5437 * The keys a variant with a string index signature (an MCP tool's input)
5438 * takes beyond its own: another variant's key as typed there; others free.
5439 *
5440 * So a misspelt value for a key some variant declares (`command: 5`) is
5441 * refused on every variant, not admitted by the open one.
5442 */
5443 type OpenMatcher<I, All> = {
5444 readonly [K in Exclude<MatcherKeys<All>, KnownKeys<I>>]?: MatcherValue<MatcherValueOf<All, K>>;
5445 } & Readonly<Record<string, unknown>>;
5446
5447 /**
5448 * The name of a call on `$` the host serves, as an event.
5449 */
5450 export type OpEventName = keyof OpEventOf;
5451
5452 /**
5453 * The calls on `$` the host serves, as events: `e` is the call's argument as
5454 * it crosses to the host, and every one is hookable by name and by `on("*")`.
5455 *
5456 * A hook above the caller passes it on, rewrites it, refuses it with
5457 * `{ deny }` or answers with `{ value }`; core is the host's implementation.
5458 * The calling hook alone is skipped, and `next.origin` names the caller.
5459 */
5460 export type OpEventOf = {
5461 /**
5462 * The argument of `$.model.complete(request)`.
5463 */
5464 'model.complete': ModelCompleteRequest;
5465 /**
5466 * The argument of `$.model.classify(text, labels, options)`.
5467 */
5468 'model.classify': {
5469 text: string;
5470 labels: readonly string[];
5471 options?: ClassifyOptions;
5472 };
5473 /**
5474 * The argument of `$.model.fork(request)`.
5475 */
5476 'model.fork': ModelForkRequest;
5477 /**
5478 * The clip and how to play it (`shouldLoop`, `gain`); the signal does not
5479 * cross.
5480 */
5481 'audio.play': {
5482 clip: AudioClip;
5483 shouldLoop: boolean;
5484 gain?: number;
5485 };
5486 /**
5487 * The argument of `$.audio.speak(text, { voice })`.
5488 */
5489 'audio.speak': SpeakRequest;
5490 /**
5491 * The argument of `$.mcp.call(server, tool, args)`.
5492 */
5493 'mcp.call': {
5494 server: string;
5495 tool: string;
5496 args: Record<string, unknown>;
5497 };
5498 /**
5499 * The argument of `$.session.cwd()`.
5500 */
5501 'session.cwd': NoArgs;
5502 /**
5503 * The argument of `$.session.root()`.
5504 */
5505 'session.root': NoArgs;
5506 /**
5507 * The argument of `$.session.model()`.
5508 */
5509 'session.model': NoArgs;
5510 /**
5511 * The argument of `$.session.turns()`.
5512 */
5513 'session.turns': NoArgs;
5514 /**
5515 * The argument of `$.session.id()`.
5516 */
5517 'session.id': NoArgs;
5518 /**
5519 * The argument of `$.session.messages()`.
5520 */
5521 'session.messages': NoArgs;
5522 /**
5523 * The argument of `$.session.repo()`.
5524 */
5525 'session.repo': NoArgs;
5526 /**
5527 * The argument of `$.session.surface()`.
5528 *
5529 * @deprecated with `$.session.surface()`; hook `session.surfaces`
5530 */
5531 'session.surface': NoArgs;
5532 /**
5533 * The argument of `$.session.surfaces()`.
5534 */
5535 'session.surfaces': NoArgs;
5536 /**
5537 * The argument of `$.session.authorize()`.
5538 */
5539 'session.authorize': NoArgs;
5540 /**
5541 * The argument of `$.session.usage({ breakdown, columns })`.
5542 */
5543 'session.usage': SessionUsageArgs;
5544 /**
5545 * The argument of `$.turn.abort({ turnId })`.
5546 */
5547 'turn.abort': {
5548 turnId: string;
5549 };
5550 /**
5551 * The argument of `$.prompt.read()`.
5552 */
5553 'prompt.read': NoArgs;
5554 /**
5555 * The argument of `$.tool.list()`.
5556 */
5557 'tool.list': NoArgs;
5558 /**
5559 * The argument of `$.tool.register(spec)`.
5560 */
5561 'tool.register': Required<ToolSpec>;
5562 /**
5563 * The argument of `$.command.list()`.
5564 */
5565 'command.list': NoArgs;
5566 /**
5567 * The argument of `$.command.register(spec)`.
5568 */
5569 'command.register': CommandSpec;
5570 /**
5571 * The argument of `$.config.list()`.
5572 */
5573 'config.list': NoArgs;
5574 /**
5575 * The argument of `$.agent.list()`.
5576 */
5577 'agent.list': NoArgs;
5578 /**
5579 * The argument of `$.agent.register(spec)`: the agent type as the plugin
5580 * defined it. A hook above rewrites any of it; the type stays the caller's.
5581 */
5582 'agent.register': AgentSpec;
5583 /**
5584 * The argument of `$.ui.toast(text, { timeoutMs })`.
5585 */
5586 'ui.toast': {
5587 text: string;
5588 timeoutMs?: number;
5589 };
5590 /**
5591 * The argument of `$.ui.status(text)`; `text` undefined clears the line.
5592 */
5593 'ui.status': {
5594 text: string | undefined;
5595 };
5596 /**
5597 * The argument of `$.ui.log(text, { to })`; `to` is always present
5598 * (UiLogSink), and `next({ ...e, to: "debug" })` keeps a line off screen.
5599 */
5600 'ui.log': {
5601 text: string;
5602 to: UiLogSink;
5603 };
5604 /**
5605 * The argument of `$.ui.notice(tool_use_id, text)`.
5606 */
5607 'ui.notice': {
5608 tool_use_id: string;
5609 text: string | undefined;
5610 };
5611 /**
5612 * The argument of `$.ui.invalidate(event)`.
5613 */
5614 'ui.invalidate': {
5615 event: InvalidatableEventName;
5616 };
5617 /**
5618 * The argument of `$.ui.open({ id, title, focus })`; a hook above the
5619 * opener may retitle it or refuse it with `{ deny }`, never rename it.
5620 */
5621 'ui.open': PaneOpenArgs;
5622 /**
5623 * The argument of `$.ui.close({ id })` with `origin` `plugin`; the engine
5624 * raises it too, for the person (`person`) and an unload (`unload`).
5625 */
5626 'ui.close': PaneCloseInput;
5627 /**
5628 * The argument of `$.ui.panes()`.
5629 */
5630 'ui.panes': NoArgs;
5631 /**
5632 * The argument of `$.ui.blit(...)`: a Raster's `cells` or a keyed Image's
5633 * `source`; a hook above may rewrite either with `next`, or `{ deny }`.
5634 */
5635 'ui.blit': UiBlitArgs;
5636 /**
5637 * The argument of `$.fs.read(path, { as })`: `as` is `text` unless the
5638 * caller asked for `bytes`.
5639 */
5640 'fs.read': {
5641 path: string;
5642 as: FsReadAs;
5643 };
5644 /**
5645 * The argument of `$.fs.write(path, text)`.
5646 */
5647 'fs.write': {
5648 path: string;
5649 text: string;
5650 };
5651 /**
5652 * The argument of `$.fs.list(path)`.
5653 */
5654 'fs.list': {
5655 path: string;
5656 };
5657 /**
5658 * The argument of `$.fs.exists(path)`.
5659 */
5660 'fs.exists': {
5661 path: string;
5662 };
5663 /**
5664 * The argument of `$.fs.stat(path, { resolve })`: `resolve` is false
5665 * unless the caller asked where the path lands.
5666 */
5667 'fs.stat': {
5668 path: string;
5669 resolve: boolean;
5670 };
5671 /**
5672 * The argument of `$.fs.ancestors({ names, of, below })`.
5673 */
5674 'fs.ancestors': FsAncestorsRequest;
5675 /**
5676 * The argument of `$.store.get(key)`.
5677 */
5678 'store.get': {
5679 key: string;
5680 };
5681 /**
5682 * The argument of `$.store.set(key, value)`.
5683 */
5684 'store.set': {
5685 key: string;
5686 value: unknown;
5687 };
5688 /**
5689 * The argument of `$.store.delete(key)`.
5690 */
5691 'store.delete': {
5692 key: string;
5693 };
5694 /**
5695 * The argument of `$.store.keys()`.
5696 */
5697 'store.keys': NoArgs;
5698 /**
5699 * The argument of `$.clock.now()`.
5700 */
5701 'clock.now': NoArgs;
5702 /**
5703 * The argument of `$.clock.sleep(ms, { signal })`; the signal does not
5704 * cross, it aborts the dispatch.
5705 */
5706 'clock.sleep': ClockWait;
5707 /**
5708 * The argument of `$.clock.after(ms, fn)`: the wait before `fn`, which
5709 * stays in the plugin's environment and runs once the dispatch resolves.
5710 */
5711 'clock.after': ClockWait;
5712 /**
5713 * The argument of `$.clock.every(ms, fn)`, dispatched once per period:
5714 * `fn` runs each time a dispatch resolves, and the next period is asked.
5715 */
5716 'clock.every': ClockWait;
5717 /**
5718 * The argument of `$.http.fetch(url, init)`.
5719 */
5720 'http.fetch': {
5721 url: string;
5722 init?: HttpInit;
5723 };
5724 /**
5725 * The argument of `$.process.run(argv, init)`.
5726 */
5727 'process.run': {
5728 argv: readonly string[];
5729 init?: ProcessRunInit;
5730 };
5731 /**
5732 * The argument of `$.settings.read({ source })`.
5733 */
5734 'settings.read': SettingsReadArgs;
5735 /**
5736 * The argument of `$.env.get(name)`; `name` is identity, pinned.
5737 */
5738 'env.get': {
5739 name: string;
5740 };
5741 /**
5742 * The argument of `$.env.set(name, value)`; `name` is identity, pinned,
5743 * and no `value` unsets.
5744 */
5745 'env.set': {
5746 name: string;
5747 value?: string;
5748 };
5749 };
5750
5751 /**
5752 * The result of a call on `$` as its event's hooks see it: `{ value }` (the
5753 * call's answer) or `{ deny }`.
5754 */
5755 export type OpEventResult<N extends OpEventName = OpEventName> = ValueOrDeny<OpValueOf[N]>;
5756
5757 /**
5758 * What each call on `$` answers (the `value` of its event's result), by event
5759 * name.
5760 */
5761 export type OpValueOf = {
5762 'model.complete': string;
5763 'model.classify': string | undefined;
5764 'model.fork': ModelForkResult | null;
5765 'audio.play': void;
5766 'audio.speak': SpeakResult;
5767 'mcp.call': McpToolResult;
5768 'session.cwd': string;
5769 'session.root': string;
5770 'session.model': string;
5771 'session.turns': number;
5772 'session.id': string;
5773 'session.messages': SessionMessage[];
5774 'session.repo': SessionRepo | null;
5775 'session.surface': RenderSurface | null;
5776 'session.surfaces': readonly RenderSurface[];
5777 /**
5778 * The credential handle, or null where the build or the provider has no
5779 * first-party credential to hold.
5780 */
5781 'session.authorize': SessionAuthorization;
5782 'session.usage': SessionUsage;
5783 'turn.abort': void;
5784 /**
5785 * The box as it stands; the empty box where the session draws none.
5786 */
5787 'prompt.read': PromptBox;
5788 'tool.list': ToolInfo[];
5789 'tool.register': {
5790 tool: string;
5791 };
5792 'command.list': CommandInfo[];
5793 'command.register': {
5794 command: string;
5795 };
5796 'config.list': ConfigRow[];
5797 'agent.list': AgentInfo[];
5798 'agent.register': {
5799 agent: string;
5800 };
5801 'ui.toast': void;
5802 'ui.status': void;
5803 'ui.log': void;
5804 'ui.notice': void;
5805 'ui.invalidate': void;
5806 'ui.open': void;
5807 'ui.close': void;
5808 /**
5809 * The calling plugin's open panes, placed then unplaced, in open order.
5810 */
5811 'ui.panes': readonly UiPane[];
5812 'ui.blit': UiBlitResult;
5813 /**
5814 * The text; `{ base64 }` when asked for bytes.
5815 */
5816 'fs.read': string | FsBytes;
5817 'fs.write': void;
5818 'fs.list': FsEntry[];
5819 'fs.exists': boolean;
5820 'fs.stat': FsStat;
5821 'fs.ancestors': readonly FsAncestor[];
5822 'store.get': unknown;
5823 'store.set': void;
5824 'store.delete': void;
5825 'store.keys': string[];
5826 /**
5827 * Milliseconds since the epoch.
5828 */
5829 'clock.now': number;
5830 'clock.sleep': void;
5831 'clock.after': void;
5832 'clock.every': void;
5833 'http.fetch': HttpResponse;
5834 'process.run': ProcessRunResult;
5835 'settings.read': Settings;
5836 'env.get': string | undefined;
5837 'env.set': void;
5838 };
5839
5840 /**
5841 * One call signature per event in `Names`, intersected, the ambiguous ones
5842 * (LateOverload) after the rest: `next` for a hook covering several events.
5843 *
5844 * An empty group contributes nothing (Overloads<never> is unknown).
5845 */
5846 type OrderedOverloads<Names extends EventName> = Overloads<Exclude<Names, LateOverload>> & Overloads<Extract<Names, 'classic.PreToolUse'>> & Overloads<Extract<Names, 'turn.abort'>> & Overloads<Extract<Names, NoArgsEvent>>;
5847
5848 /**
5849 * Who raised a dispatch, as `next.origin` holds it: the calling plugin's
5850 * name and the tier it sits in; the engine reads `engine` in `core`.
5851 *
5852 * The same pair a `next.trace` entry names its link by, and an event's
5853 * `provider` its subject's definer by. Set by the host from where the call
5854 * came from and where that plugin was seated; nothing a plugin writes.
5855 */
5856 export type Origin = {
5857 /**
5858 * Whose hook made the `$` call, by name; `"engine"` for a call site,
5859 * `"client"` for a `Client` surface module's `ui.message` post.
5860 */
5861 readonly plugin: string;
5862 /**
5863 * Where that plugin sits among the chain's tiers (Tier); `"core"` for the
5864 * engine, the owning plugin's for a `client` post.
5865 */
5866 readonly tier: Tier;
5867 };
5868
5869 /**
5870 * One call signature per event in `Names`, intersected into an overload set.
5871 */
5872 type Overloads<Names extends EventName> = UnionToIntersection<{
5873 [N in Names]: (e: Args<N>) => Promise<NextResult<N>>;
5874 }[Names]>;
5875
5876 /**
5877 * The argument of `$.ui.close`: the pane to close (`{ id }`). `origin` is
5878 * the engine's to set: a plugin's call reads `plugin` at the hooks.
5879 */
5880 export type PaneCloseArgs = Omit<PaneCloseInput, 'origin'>;
5881
5882 /**
5883 * The input of `ui.close`: the pane closing and why (PaneCloseOrigin).
5884 * Closing an id that is not open does nothing.
5885 */
5886 export type PaneCloseInput = {
5887 /**
5888 * What `$.ui.open` named the pane; pinned: `next(e)` passes it on.
5889 */
5890 id: string;
5891 /**
5892 * Who closes it, set by the engine: a hook that answers without `next`
5893 * keeps the pane open on `plugin` and `person`, never on `unload`.
5894 */
5895 origin: PaneCloseOrigin;
5896 };
5897
5898 /**
5899 * Why a pane closes, as the engine stamped it at `ui.close`.
5900 *
5901 * `unload` drops a pane nothing draws any more (its plugin unloaded, or its
5902 * drawing threw): it is gone before the hooks hear of it, and its opener's
5903 * hooks do not run. `next(e)` passes the origin on as received; none sets it.
5904 */
5905 export type PaneCloseOrigin = {
5906 /**
5907 * `plugin`, a plugin's `$.ui.close`; `person`, the person's close mark or
5908 * close key; `unload`, the engine's own.
5909 */
5910 kind: 'plugin' | 'person' | 'unload';
5911 };
5912
5913 /**
5914 * The argument of `$.ui.open`: which pane, its title, whether it asks the
5915 * person's keyboard, its dialog manners, its size: rows inline, columns docked.
5916 *
5917 * An open answering the person's input (a command or prompt they entered, a
5918 * press) is placed at any width; one the plugin makes on its own waits
5919 * undrawn below 144 terminal columns, 110 once they asked for that id.
5920 */
5921 export type PaneOpenArgs = {
5922 /**
5923 * Names the pane: 1-64 of letters, digits, `_` and `-`. One pane per id:
5924 * opening an open id delivers the new title, never a second instance.
5925 *
5926 * Pinned at the hooks: `next(e)` passes it on; the title and focus rewrite.
5927 */
5928 id: string;
5929 /**
5930 * The pane's tab while more than one pane is open (with one, no title is
5931 * drawn), and the `title` its hook sees; the id when omitted.
5932 *
5933 * An unpaired surrogate half (a `.slice()` through an emoji) is drawn as
5934 * U+FFFD; a control character is refused.
5935 */
5936 title?: string;
5937 /**
5938 * A request, not a grant: the surface focuses (and raises) the pane only
5939 * while the prompt has the keys over an empty composer.
5940 *
5941 * An element of the band or a pane the person holds, text in the
5942 * composer, a dialog or a survey each refuse it: the pane opens without
5943 * the keyboard.
5944 */
5945 focus?: true;
5946 /**
5947 * While the pane holds the keyboard, the key that hands it back (Escape)
5948 * also closes it as the person's close does: `ui.close`, origin `person`.
5949 *
5950 * So does Escape at an idle, empty prompt once the prompt has the keys
5951 * again (the person typed, or `focus` was refused); over text, a running
5952 * turn, a dialog, a footer selection, a viewed agent's transcript or a
5953 * prompt mode of its own the key stays theirs.
5954 *
5955 * A hook may refuse that close and keep it open. Left out, Escape returns
5956 * the keys to the prompt and the pane stays. Each open sets it anew, as it
5957 * sets the title.
5958 */
5959 closeOnEscape?: true;
5960 /**
5961 * While the pane is on screen the surface holds its transient toasts (the
5962 * notification line under the prompt) and shows them once it closes.
5963 *
5964 * As it does behind the engine's own side panel; pinned warnings still
5965 * show. Left out, toasts show as they come. Each open sets it anew.
5966 */
5967 holdToasts?: true;
5968 /**
5969 * The body rows the pane's content wants while seated inline above the
5970 * prompt: it opens that tall, up to what the layout spares, not a third.
5971 *
5972 * A request, not a grant: a size the person dragged or keyed the block
5973 * to wins, this session's or a kept one, and the dock ignores it. A
5974 * positive whole number; left out, a third. Each open sets it anew.
5975 */
5976 rows?: number;
5977 /**
5978 * The body columns the pane's content wants while docked beside a
5979 * fullscreen transcript: the dock opens that wide, floor to ceiling.
5980 *
5981 * A request, not a grant: a width the person dragged or keyed the dock
5982 * to wins, this session's or a kept one, and the inline block ignores
5983 * it. A positive whole number; left out, the share. Each open sets it anew.
5984 *
5985 * @example
5986 * await $.ui.open({ id: "browser", focus: true, rows: 24, columns: 100 })
5987 */
5988 columns?: number;
5989 };
5990
5991 /**
5992 * What `on(pattern, hook)` and `next.is(pattern, e)` take: an event's name,
5993 * a glob (`*`, `classic.*`), or a negation of either (`!tool.describe`).
5994 */
5995 export type Pattern = EventName | Glob | Negation;
5996
5997 /**
5998 * The patterns `next.is` takes in a hook covering the events `N`: their
5999 * names, `*`, a glob over one of their namespaces, or a negation.
6000 *
6001 * A name none of them has is a compile error, as is a glob over a namespace
6002 * none is under; a negation that selects none of them narrows `e` to never.
6003 */
6004 type PatternOver<N extends EventName> = N | '*' | `${Namespace<N>}.*` | Negation;
6005
6006 type PermissionBehavior = 'allow' | 'deny' | 'ask';
6007
6008 type PermissionDeniedHookInput = BaseHookInput & {
6009 hook_event_name: 'PermissionDenied';
6010 tool_name: string;
6011 tool_input: unknown;
6012 tool_use_id: string;
6013 reason: string;
6014 mcp_server?: McpServerProvenance;
6015 };
6016
6017 /**
6018 * 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.
6019 */
6020 type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';
6021
6022 /**
6023 * A `classic.PermissionRequest` answer's `decision`, as the classic hook's
6024 * `hookSpecificOutput.decision`: allow (with a rewrite or rules) or deny.
6025 */
6026 export type PermissionRequestDecision = {
6027 behavior: 'allow';
6028 updatedInput?: Record<string, unknown>;
6029 updatedPermissions?: PermissionUpdates;
6030 } | {
6031 behavior: 'deny';
6032 message?: string;
6033 interrupt?: true;
6034 };
6035
6036 type PermissionRequestHookInput = BaseHookInput & {
6037 hook_event_name: 'PermissionRequest';
6038 tool_name: string;
6039 tool_input: unknown;
6040 permission_suggestions?: PermissionUpdate[];
6041 mcp_server?: McpServerProvenance;
6042 };
6043
6044 type PermissionRuleValue = {
6045 toolName: string;
6046 ruleContent?: string;
6047 };
6048
6049 type PermissionUpdate = {
6050 type: 'addRules';
6051 rules: PermissionRuleValue[];
6052 behavior: PermissionBehavior;
6053 destination: PermissionUpdateDestination;
6054 } | {
6055 type: 'replaceRules';
6056 rules: PermissionRuleValue[];
6057 behavior: PermissionBehavior;
6058 destination: PermissionUpdateDestination;
6059 } | {
6060 type: 'removeRules';
6061 rules: PermissionRuleValue[];
6062 behavior: PermissionBehavior;
6063 destination: PermissionUpdateDestination;
6064 } | {
6065 type: 'setMode';
6066 mode: PermissionMode;
6067 destination: PermissionUpdateDestination;
6068 } | {
6069 type: 'addDirectories';
6070 directories: string[];
6071 destination: PermissionUpdateDestination;
6072 } | {
6073 type: 'removeDirectories';
6074 directories: string[];
6075 destination: PermissionUpdateDestination;
6076 };
6077
6078 type PermissionUpdateDestination = 'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg';
6079
6080 /**
6081 * The permission rules a PermissionRequest allow may add: the shape of the
6082 * request's own `permission_suggestions` (the SDK's PermissionUpdate list).
6083 */
6084 type PermissionUpdates = NonNullable<ClassicHookInputs['PermissionRequest']['permission_suggestions']>;
6085
6086 /**
6087 * How `$.audio.play` plays a clip: looped until `signal` aborts, or once.
6088 *
6089 * A loop needs the signal that ends it; a single play takes one as an option.
6090 */
6091 export type PlayOptions = {
6092 /**
6093 * Repeat the clip until `signal` aborts (the promise then resolves).
6094 */
6095 shouldLoop: true;
6096 /**
6097 * Linear gain, from 0 to 4; default 1.
6098 */
6099 gain?: number;
6100 /**
6101 * Stops the clip: playback ends at once and the promise resolves.
6102 */
6103 signal: AbortSignal;
6104 } | {
6105 /**
6106 * Play once.
6107 */
6108 shouldLoop?: false;
6109 /**
6110 * Linear gain, from 0 to 4; default 1.
6111 */
6112 gain?: number;
6113 /**
6114 * Stops the clip early, as above.
6115 */
6116 signal?: AbortSignal;
6117 };
6118
6119 /**
6120 * The nouns a plugin declared on `$` by merging into EngineInterface; never
6121 * one the engine's own events are under (`tool`, `session`, `ui`).
6122 */
6123 type PluginNoun = Exclude<keyof EngineInterface & string, keyof CoreEngineInterface | Namespace<CoreEventName>>;
6124
6125 /**
6126 * A plugin's options as `register(on, options)` receives them: the values of
6127 * the fields its manifest's `userConfig` declares, defaults filled in.
6128 *
6129 * Stored in settings.json `pluginConfigs[<plugin>].options` (sensitive ones
6130 * in secure storage), validated against the declared `type` before the module
6131 * loads; a required field with no value fails the load, naming the field. A
6132 * string field that declares `options` holds one of them: `/config` draws it
6133 * as a picker over them, and a stored value outside them counts as unset, so
6134 * its default applies. A `--plugin-dir` plugin's key is its plugin.json
6135 * `<name>` (or `<name>@inline`).
6136 */
6137 export type PluginOptions = Readonly<Record<string, string | number | boolean | readonly string[]>>;
6138
6139 /**
6140 * The input of `plugin.register`: one hooks module the engine is about to
6141 * load, read off its manifest and its scanned source. Every field is pinned.
6142 *
6143 * `tier` and `uses` are the host's reading of the module, what a gate holds
6144 * it to; `name`, `root`, `version` and `provenance` are its own word (its
6145 * manifest, its place), so a rule keyed on them is one a rename walks past.
6146 */
6147 export type PluginRegisterInput = {
6148 /**
6149 * The plugin's name, as its own plugin.json declares it.
6150 */
6151 name: string;
6152 /**
6153 * Where its hooks would stand among the chain's tiers (Tier); never
6154 * `core`, the engine's own.
6155 */
6156 tier: Exclude<Tier, 'core'>;
6157 /**
6158 * The plugin's directory (the one holding plugin.json), absolute.
6159 */
6160 root: string;
6161 /**
6162 * Its manifest's `version`, when it states one.
6163 */
6164 version?: string;
6165 /**
6166 * Where the plugin came from, as the loader keys it: `<name>@<marketplace>`
6167 * installed, `<name>@inline` by `--plugin-dir`, `<name>@builtin` bundled.
6168 */
6169 provenance: string;
6170 /**
6171 * What the module hooks and calls, as scanned (PluginRegisterUses).
6172 */
6173 uses: PluginRegisterUses;
6174 };
6175
6176 /**
6177 * What a `plugin.register` hook returns and what `next(e)` resolves to:
6178 * `{ allow: true }` from core, or `{ refuse: reason }`.
6179 */
6180 export type PluginRegisterResult = {
6181 /**
6182 * The module loads: its `engine.create` step runs and its hooks join.
6183 */
6184 allow: true;
6185 refuse?: undefined;
6186 } | {
6187 /**
6188 * The module does not load: no step, no hooks, no tools or commands;
6189 * the transcript names the plugin that refused and this reason.
6190 */
6191 refuse: string;
6192 allow?: undefined;
6193 };
6194
6195 /**
6196 * What a hooks module uses, as the host scanned its source before loading it:
6197 * the same lists `claude plugin validate` prints and the host's rule reads.
6198 *
6199 * Exact, since a module that spells `on`, `$` or `$.env` other than literally
6200 * does not load.
6201 */
6202 export type PluginRegisterUses = {
6203 /**
6204 * The patterns its `on(...)` registrations name, as written (`tool.call`,
6205 * `*`, `classic.*`, `!tool.describe`), in registration order, each once.
6206 */
6207 events: readonly string[];
6208 /**
6209 * What it calls on `$`, spelled `noun.method` (`fs.write`, `http.fetch`),
6210 * sorted, each once.
6211 */
6212 calls: readonly string[];
6213 /**
6214 * The environment variables its `$.env.get` and `$.env.set` calls name;
6215 * absent when it calls neither.
6216 */
6217 env?: {
6218 /**
6219 * The names its `$.env.get` calls spell, sorted, each once.
6220 */
6221 reads: readonly string[];
6222 /**
6223 * The names its `$.env.set` calls spell, sorted, each once.
6224 */
6225 writes: readonly string[];
6226 };
6227 };
6228
6229 /**
6230 * Whose element: the plugin whose hook drew it, stamped by the runtime as the
6231 * tree leaves it; a Box's or Text's `group`, a Client's or Raster's own.
6232 *
6233 * A Button's `press` names its plugin the same way, beside its handle. Two
6234 * plugins under one `hover.scope` string never share a group.
6235 */
6236 type PluginStamp = {
6237 plugin: string;
6238 };
6239
6240 type PostCompactHookInput = BaseHookInput & {
6241 hook_event_name: 'PostCompact';
6242 trigger: 'manual' | 'auto';
6243 /**
6244 * The conversation summary produced by compaction
6245 */
6246 compact_summary: string;
6247 };
6248
6249 type PostModelSwitchHookInput = (BaseHookInput & {
6250 hook_event_name: 'PostModelSwitch';
6251 }) & {
6252 /**
6253 * Resolved model id the session was running before the switch
6254 */
6255 from_model: string;
6256 /**
6257 * Resolved model id the session runs after the switch
6258 */
6259 to_model: string;
6260 /**
6261 * What was asked for (alias such as "opus", a full id, or null for "default")
6262 */
6263 requested_model: string | null;
6264 /**
6265 * 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
6266 */
6267 source: 'command' | 'picker' | 'sdk' | 'auto' | 'resume';
6268 /**
6269 * 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)
6270 */
6271 context_tokens: number;
6272 /**
6273 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
6274 */
6275 prompt_cache_warm: boolean;
6276 cache_ttl: '5m' | '1h';
6277 /**
6278 * 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
6279 */
6280 estimated_cache_write_usd: number;
6281 /**
6282 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
6283 */
6284 pricing: 'configured' | 'catalog' | 'default';
6285 };
6286
6287 /**
6288 * 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.
6289 */
6290 type PostToolBatchHookInput = BaseHookInput & {
6291 hook_event_name: 'PostToolBatch';
6292 tool_calls: PostToolBatchToolCall[];
6293 };
6294
6295 type PostToolBatchToolCall = {
6296 tool_name: string;
6297 tool_input: unknown;
6298 tool_use_id: string;
6299 tool_response?: unknown;
6300 };
6301
6302 type PostToolUseFailureHookInput = BaseHookInput & {
6303 hook_event_name: 'PostToolUseFailure';
6304 tool_name: string;
6305 tool_input: unknown;
6306 tool_use_id: string;
6307 error: string;
6308 is_interrupt?: boolean;
6309 /**
6310 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
6311 */
6312 duration_ms?: number;
6313 mcp_server?: McpServerProvenance;
6314 };
6315
6316 type PostToolUseHookInput = BaseHookInput & {
6317 hook_event_name: 'PostToolUse';
6318 tool_name: string;
6319 tool_input: unknown;
6320 tool_response: unknown;
6321 tool_use_id: string;
6322 /**
6323 * Tool execution time in milliseconds. Excludes permission-prompt and hook time.
6324 */
6325 duration_ms?: number;
6326 mcp_server?: McpServerProvenance;
6327 };
6328
6329 type PreCompactHookInput = BaseHookInput & {
6330 hook_event_name: 'PreCompact';
6331 trigger: 'manual' | 'auto';
6332 custom_instructions: string | null;
6333 };
6334
6335 type PreModelSwitchHookInput = (BaseHookInput & {
6336 hook_event_name: 'PreModelSwitch';
6337 }) & {
6338 /**
6339 * Resolved model id the session was running before the switch
6340 */
6341 from_model: string;
6342 /**
6343 * Resolved model id the session runs after the switch
6344 */
6345 to_model: string;
6346 /**
6347 * What was asked for (alias such as "opus", a full id, or null for "default")
6348 */
6349 requested_model: string | null;
6350 /**
6351 * 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)
6352 */
6353 source: 'command' | 'picker' | 'sdk';
6354 /**
6355 * 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)
6356 */
6357 context_tokens: number;
6358 /**
6359 * Whether the current model's prompt cache is likely still warm (a switch then forfeits it)
6360 */
6361 prompt_cache_warm: boolean;
6362 cache_ttl: '5m' | '1h';
6363 /**
6364 * 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
6365 */
6366 estimated_cache_write_usd: number;
6367 /**
6368 * configured: priced at the managed modelPricing setting; catalog: list price; default: to_model unknown, the default tier was assumed
6369 */
6370 pricing: 'configured' | 'catalog' | 'default';
6371 };
6372
6373 /**
6374 * The link a press landed on: one a `Markdown` drew, pressed where the
6375 * surface reports presses (a plain click in the fullscreen terminal).
6376 *
6377 * What the surface knows of the cell pressed, not which occurrence: two
6378 * links written with one target read the same here.
6379 */
6380 export type PressedLink = {
6381 /**
6382 * The link's target as the surface drew it: for an `https:` link, the
6383 * href as the markdown wrote it.
6384 */
6385 href: string;
6386 };
6387
6388 /**
6389 * The decision of a `classic.PreToolUse` result: `allow`, `ask`, `deny`, or
6390 * none.
6391 */
6392 export type PreToolUseDecision = {
6393 /**
6394 * Lets the call run without a permission prompt (the managed-settings
6395 * hooks ran first; a deny from them ended the chain above).
6396 */
6397 allow: true;
6398 ask?: undefined;
6399 deny?: undefined;
6400 } | {
6401 /**
6402 * Asks the user before the call runs; the text is shown as the reason.
6403 */
6404 ask: string;
6405 allow?: undefined;
6406 deny?: undefined;
6407 } | {
6408 /**
6409 * Refuses the call; the model receives the text as the reason.
6410 */
6411 deny: string;
6412 allow?: undefined;
6413 ask?: undefined;
6414 } | {
6415 allow?: undefined;
6416 ask?: undefined;
6417 deny?: undefined;
6418 };
6419
6420 type PreToolUseHookInput = BaseHookInput & {
6421 hook_event_name: 'PreToolUse';
6422 tool_name: string;
6423 tool_input: unknown;
6424 tool_use_id: string;
6425 mcp_server?: McpServerProvenance;
6426 };
6427
6428 /**
6429 * What a `classic.PreToolUse` hook returns: one of `allow`, `ask`, `deny`,
6430 * or none of them, which passes the call on to the normal permission flow.
6431 */
6432 export type PreToolUseResult = PreToolUseDecision & {
6433 /**
6434 * Replaces the tool's arguments; validated against the tool's schema before
6435 * the tool runs.
6436 */
6437 updatedInput?: Record<string, unknown>;
6438 /**
6439 * Extra context handed to the model with the call, one entry per note.
6440 */
6441 additionalContext?: string[];
6442 };
6443
6444 /**
6445 * Options of `$.process.run`.
6446 */
6447 export type ProcessRunInit = {
6448 /**
6449 * The child's working directory, relative to the session's or absolute;
6450 * absent, the session's working directory.
6451 */
6452 cwd?: string;
6453 /**
6454 * Variables set over the host process's own environment.
6455 */
6456 env?: Record<string, string>;
6457 /**
6458 * Text written to the child's standard input, then closed.
6459 */
6460 stdin?: string;
6461 /**
6462 * How long the child may run before it is killed and the call rejects,
6463 * in milliseconds; 30 seconds when absent, ten minutes at most.
6464 */
6465 timeoutMs?: number;
6466 };
6467
6468 /**
6469 * What `$.process.run` resolves with once the child has exited.
6470 */
6471 export type ProcessRunResult = {
6472 /**
6473 * The child's exit status; a child ended by a signal reads as 1.
6474 */
6475 exitCode: number;
6476 /**
6477 * What the child wrote to standard output, as text, cut at the output
6478 * limit.
6479 */
6480 stdout: string;
6481 /**
6482 * What the child wrote to standard error, as text, cut at the output
6483 * limit.
6484 */
6485 stderr: string;
6486 };
6487
6488 /**
6489 * The input of `prompt.attachment`: one message the engine injects into the
6490 * conversation for the model on its own, as a request is about to carry it.
6491 *
6492 * A reminder, a mode transition, a listing, a mentioned file, a hook's
6493 * context: the person never typed it and mostly never sees it. Only an
6494 * attachment that carries text for the model is raised.
6495 */
6496 export type PromptAttachmentInput = {
6497 /**
6498 * As the engine names the attachment's kind; the key a matcher narrows on.
6499 * Pinned. Builds add and retire kinds: match by name.
6500 *
6501 * Among them `todo_reminder`, `plan_mode`, `plan_mode_exit`, `auto_mode`,
6502 * `auto_mode_exit`, `instructions`, `nested_memory`, `skill_listing`,
6503 * `deferred_tools_delta`, `edited_text_file`, `file`, `queued_command`.
6504 */
6505 type: string;
6506 /**
6507 * What the model reads for this attachment, inside the engine's framing;
6508 * rewritable with `next({ ...e, text })`.
6509 *
6510 * The `<system-reminder>` wrapper (or the system channel that replaces it)
6511 * goes around what the chain answers, never inside it. An attachment
6512 * rendered as several text blocks hands them joined by newlines.
6513 */
6514 text: string;
6515 /**
6516 * Who authored the text (PromptAttachmentOrigin): the engine, a settings
6517 * hook, or a plugin's chain context.
6518 *
6519 * Pinned: a different value is refused, one left out is kept.
6520 */
6521 origin: PromptAttachmentOrigin;
6522 /**
6523 * The loop whose request carries the attachment: a subagent's id, the `id`
6524 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
6525 *
6526 * Pinned: a different value is refused, one left out is kept. A subagent
6527 * a hook spawned through `$.agent.spawn` is resolved past that hook.
6528 */
6529 agentId?: string;
6530 };
6531
6532 /**
6533 * Who authored the text an injected attachment carries, as the engine knows
6534 * it from the attachment itself; a closed set, pinned on the event.
6535 *
6536 * A hooks module reads `e.origin.kind` to tell the engine's own prose from a
6537 * settings hook's output or another plugin's context. `next(e)` passes it on
6538 * as received; one left out is put back; no hook sets one.
6539 */
6540 export type PromptAttachmentOrigin = {
6541 /**
6542 * The engine's own prose or framing: a reminder, a mode transition, a
6543 * listing, a notice, an announced context block.
6544 *
6545 * A file the person mentioned, as the engine presents it, and a prompt
6546 * or notification delivered into a running turn are the engine's too.
6547 */
6548 kind: 'engine';
6549 } | {
6550 /**
6551 * A settings hook's output the engine injects for the model: its
6552 * additional context, a blocking error's note, a stopped continuation.
6553 */
6554 kind: 'hook';
6555 /**
6556 * The settings hook event that produced it (`SessionStart`,
6557 * `UserPromptSubmit`, `PostToolUse`, ...).
6558 */
6559 event: string;
6560 } | {
6561 /**
6562 * Text a plugin's hook attached through a chain's `context`
6563 * (`prompt.submit`, `tool.call`), as the model reads it.
6564 */
6565 kind: 'plugin';
6566 /**
6567 * The chain's event that attached it.
6568 */
6569 event: string;
6570 };
6571
6572 /**
6573 * What a `prompt.attachment` hook returns: the text the model reads for that
6574 * attachment, or null to leave the attachment out of the request.
6575 */
6576 export type PromptAttachmentResult = {
6577 text: string | null;
6578 };
6579
6580 /**
6581 * The person's prompt box as it stands: the draft and where the cursor is in
6582 * it; what `$.prompt.read()` resolves and `$.prompt.fill` hands back.
6583 *
6584 * No selection: the terminal's box has none of its own, and a surface that
6585 * binds one adds it here.
6586 */
6587 export type PromptBox = {
6588 /**
6589 * The draft as typed so far; `''` where the session draws no box.
6590 */
6591 text: string;
6592 /**
6593 * Where the next typed character lands: an offset into `text` in UTF-16
6594 * code units, 0 at the start, `text.length` at the end.
6595 */
6596 cursor: number;
6597 };
6598
6599 /**
6600 * One block of the context the first user message carries: a name the
6601 * engine keys it by and the text under it.
6602 */
6603 export type PromptContextBlock = {
6604 /**
6605 * The key the block renders under (`# name`): `claudeMd`, `userEmail`,
6606 * `attachedProject`, `currentDate`, or a plugin's own.
6607 *
6608 * The field a matcher narrows on; unique among one context's blocks.
6609 */
6610 name: string;
6611 /**
6612 * The block's text; `claudeMd`'s is the instruction files framed as the
6613 * engine frames them, empty when it announces none.
6614 */
6615 text: string;
6616 };
6617
6618 /**
6619 * The context blocks of a conversation's first user message, in the order
6620 * the engine renders them: what `prompt.context` takes and answers alike.
6621 */
6622 export type PromptContextBlocks = {
6623 /**
6624 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
6625 * `attachedProject`, `currentDate`, each only when present.
6626 */
6627 blocks: readonly PromptContextBlock[];
6628 };
6629
6630 /**
6631 * The input of `prompt.context`: the context blocks the engine prepends to a
6632 * conversation's first user message, and the files behind `claudeMd`.
6633 */
6634 export type PromptContextInput = {
6635 /**
6636 * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
6637 * `attachedProject`, `currentDate`, each only when present.
6638 */
6639 blocks: readonly PromptContextBlock[];
6640 /**
6641 * The files behind `claudeMd`, in the order it renders them, `@` imports
6642 * included; empty when it renders none.
6643 *
6644 * Undefined when a hook above rewrote the `claudeMd` text: the files
6645 * behind that text are then unknown, and a hook adds none of its own.
6646 */
6647 instructionFiles?: readonly InstructionFile[];
6648 };
6649
6650 /**
6651 * What a `prompt.context` hook returns: the blocks the conversation
6652 * carries, in order; one left out is not sent.
6653 */
6654 export type PromptContextResult = {
6655 /**
6656 * What the conversation carries, in order.
6657 */
6658 blocks: readonly PromptContextBlock[];
6659 /**
6660 * The files now behind `claudeMd`; left out, the ones from below stand.
6661 *
6662 * Kept in step with the `claudeMd` text at every link: a changed list
6663 * renders the text the next reader gets, a rewritten text makes the files
6664 * unknown from there on. Every kind is the hook's to add, drop or rewrite.
6665 */
6666 instructionFiles?: readonly InstructionFile[];
6667 };
6668
6669 /**
6670 * The input of `prompt.edit` (prompt-edit/): one edit the person makes in the
6671 * prompt box, as the draft before it and the splice the editor made of it.
6672 */
6673 export type PromptEditInput = {
6674 /**
6675 * Who edits (PromptEditOrigin): the person at the composer. Pinned:
6676 * `next(e)` passes it on as received.
6677 */
6678 origin: PromptEditOrigin;
6679 /**
6680 * The one key that made the edit, in `Client` `onKey`'s shape, when one
6681 * did; absent for a paste and for a burst of keys folded into one edit.
6682 *
6683 * Pinned: which key the person pressed is a fact, not the hook's to change.
6684 */
6685 key?: ClientKeyEvent;
6686 /**
6687 * The draft before the edit. `next({ ...e, text })` applies the edit to
6688 * another draft instead.
6689 */
6690 text: string;
6691 /**
6692 * Where the person's caret stood in `text` before the edit, 0 to
6693 * `text.length`.
6694 */
6695 cursor: number;
6696 /**
6697 * Where in `text` the edit begins: the start of the span it replaces, or
6698 * where what was typed goes in; a bare cursor move begins where it lands.
6699 */
6700 start: number;
6701 /**
6702 * Where the replaced span of `text` ends: `start` for an insertion or a
6703 * move, past it for a deletion (Backspace, a kill).
6704 */
6705 end: number;
6706 /**
6707 * What goes in between `start` and `end`: the typed or pasted text, `''` for
6708 * a deletion or a move.
6709 *
6710 * `next({ ...e, inputText })` puts in another; the cursor lands after it.
6711 */
6712 inputText: string;
6713 };
6714
6715 /**
6716 * Who edits the prompt box at `prompt.edit`, as the engine stamps it where
6717 * the edit starts; a closed set a matcher narrows on.
6718 *
6719 * `next(e)` passes it on as received; no hook sets one.
6720 */
6721 export type PromptEditOrigin = {
6722 /**
6723 * The person, typing or pasting into the main prompt box.
6724 */
6725 kind: 'composer';
6726 };
6727
6728 /**
6729 * What a `prompt.edit` hook returns and what `next(e)` resolves to: the box
6730 * after the edit (PromptBox), which the editor then shows.
6731 *
6732 * From core, `e.text` with the splice applied and the cursor after what went
6733 * in. Rewrite it (`{ ...r, text, cursor }`) to change what lands; answer
6734 * `{ text: e.text, cursor: e.cursor }` without `next` to consume the key.
6735 */
6736 export type PromptEditResult = PromptBox;
6737
6738 /**
6739 * `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it: no
6740 * `origin` (the engine sets the calling plugin's), `mode` optional.
6741 */
6742 export type PromptFillArgs = {
6743 /**
6744 * What the box is to take (PromptFillInput `text`).
6745 */
6746 text: string;
6747 /**
6748 * Where it goes (PromptFillMode); `replace` when left out.
6749 */
6750 mode?: PromptFillMode;
6751 };
6752
6753 /**
6754 * What `$.prompt.fill` resolves to: whether the box took the text, and the
6755 * box afterwards (PromptBox) as the caller's own `$.prompt.read()` reads it.
6756 *
6757 * The box goes to a plugin whose module calls `$.prompt.read`, through the
6758 * hooks on it; one that never does, or is refused there, gets the empty box.
6759 */
6760 export type PromptFilled = {
6761 /**
6762 * True once the box holds the text; false where no box could take it or a
6763 * hook kept it out (PromptFillResult).
6764 */
6765 isFilled: boolean;
6766 /**
6767 * The draft after the fill; unchanged when `isFilled` is false; `''` where
6768 * no box is drawn or the caller may not read it (see above).
6769 */
6770 text: string;
6771 /**
6772 * Where the person types next: an offset into `text`, past the fill's text
6773 * for `insert`, at the end for `replace` and `append`.
6774 */
6775 cursor: number;
6776 };
6777
6778 /**
6779 * The input of `prompt.fill` (prompt-fill/): a text about to be put in the
6780 * prompt box as the person's draft, over it, after it, or at the cursor.
6781 */
6782 export type PromptFillInput = {
6783 /**
6784 * What the box takes; the person edits it or presses Enter.
6785 * `next({ ...e, text })` writes another.
6786 */
6787 text: string;
6788 /**
6789 * Where the text goes (PromptFillMode): over the draft, after it, or in at
6790 * the cursor. `next({ ...e, mode })` moves it; left out of a rewrite, kept.
6791 */
6792 mode: PromptFillMode;
6793 /**
6794 * Who writes (PromptFillOrigin), set by the engine where the write
6795 * starts. Pinned: `next(e)` passes it on as received.
6796 */
6797 origin: PromptFillOrigin;
6798 };
6799
6800 /**
6801 * Where a `prompt.fill` puts its text: over the whole draft, after it, or
6802 * into it at the cursor.
6803 *
6804 * `replace` empties the box first and leaves the cursor at the text's end;
6805 * `append` keeps the draft and adds the text after it, cursor at the end;
6806 * `insert` splices the text in at the cursor and moves the cursor past it,
6807 * so what the person had typed stays on either side.
6808 */
6809 export type PromptFillMode = 'replace' | 'append' | 'insert';
6810
6811 /**
6812 * Who writes the prompt box at `prompt.fill`, as the engine stamps it where
6813 * the write starts; a closed set a matcher narrows on.
6814 *
6815 * `next(e)` passes it on as received; no hook sets one.
6816 */
6817 export type PromptFillOrigin = {
6818 /**
6819 * The engine writing the box on its own account; reserved for its own
6820 * sites, none of which raises `prompt.fill` as shipped.
6821 */
6822 kind: 'engine';
6823 } | {
6824 /**
6825 * A plugin's `$.prompt.fill`.
6826 */
6827 kind: 'plugin';
6828 /**
6829 * The filling plugin's name.
6830 */
6831 name: string;
6832 };
6833
6834 /**
6835 * What a `prompt.fill` hook returns and what `next(e)` resolves to: whether
6836 * the text went into the prompt box.
6837 */
6838 export type PromptFillResult = {
6839 /**
6840 * True once the box holds the text; false where no box can take it (a
6841 * dialog holds the keys, a headless session has none).
6842 *
6843 * A hook answering `{ isFilled: false }` without `next` keeps the text
6844 * out.
6845 */
6846 isFilled: boolean;
6847 };
6848
6849 /**
6850 * Where a `prompt.submit` submission came from, as the engine knows it at
6851 * the site it was queued from; a closed set, never a text prefix.
6852 *
6853 * A hooks module reads `e.origin.kind` to tell the user's own Enter from a
6854 * notification, a peer session, a schedule or another plugin. `next(e)`
6855 * passes it on as received; an answer may leave it out; no hook sets one.
6856 */
6857 export type PromptOrigin = {
6858 /**
6859 * The user's own gesture at the terminal, as the engine stamped it
6860 * (never presumed from an unstamped command).
6861 *
6862 * Enter at the prompt, typed or queued, or a click on a transcript
6863 * link; a channel the engine cannot attest (a same-user socket) is
6864 * never stamped, and arrives as `unclassified`.
6865 */
6866 kind: 'composer';
6867 } | {
6868 /**
6869 * The user's message through the Remote Control bridge (a phone or
6870 * web client).
6871 */
6872 kind: 'bridge';
6873 } | {
6874 /**
6875 * The SDK host's own turn (`claude -p`, the Agent SDK), not typed at
6876 * a terminal.
6877 */
6878 kind: 'sdk';
6879 } | {
6880 /**
6881 * A background task's notification, dequeued when the session went
6882 * idle or delivered into a running turn (`turnId` set).
6883 */
6884 kind: 'task-notification';
6885 } | {
6886 /**
6887 * A scheduled task, routine or /loop firing its stored prompt.
6888 */
6889 kind: 'scheduled-trigger';
6890 } | {
6891 /**
6892 * Another Claude session's message ("Another Claude session sent a
6893 * message"), as a turn of its own or delivered into a running one.
6894 */
6895 kind: 'peer';
6896 } | {
6897 /**
6898 * Another session's SendMessage delivery, model-authored and framed
6899 * as a notification.
6900 */
6901 kind: 'peer-send-message';
6902 } | {
6903 /**
6904 * A delivery a coordinating session composed for one of its threads.
6905 */
6906 kind: 'projects-relay';
6907 } | {
6908 /**
6909 * A message from a channel an MCP server relays (Slack, Telegram).
6910 */
6911 kind: 'channel';
6912 /**
6913 * The channel server's name.
6914 */
6915 server: string;
6916 } | {
6917 /**
6918 * A coordinating session's hand-off to a worker session.
6919 */
6920 kind: 'coordinator';
6921 } | {
6922 /**
6923 * A background observer agent's report to the agent it observes.
6924 */
6925 kind: 'observer';
6926 } | {
6927 /**
6928 * An activity digest delivered to an observer agent.
6929 */
6930 kind: 'observer-activity';
6931 } | {
6932 /**
6933 * A programmatic follow-up to a user's UI action, user-initiated but
6934 * not typed this turn.
6935 */
6936 kind: 'auto-continuation';
6937 } | {
6938 /**
6939 * A turn with no provenance the engine can name: one the ingress
6940 * could not classify, or a command queued with no stamp at all.
6941 *
6942 * An idle notice or a delivery receipt the engine queued isMeta with
6943 * no stamp is one too; the engine frames that shape as a non-user
6944 * source.
6945 */
6946 kind: 'unclassified';
6947 } | {
6948 /**
6949 * The session's owner pinging it from Slack.
6950 */
6951 kind: 'slack-ping';
6952 } | {
6953 /**
6954 * A plugin's `$.prompt.submit`; the model reads the prompt under the
6955 * plugin's name unless a hook leaves the origin out of its answer.
6956 */
6957 kind: 'plugin';
6958 /**
6959 * The submitting plugin's name.
6960 */
6961 name: string;
6962 };
6963
6964 /**
6965 * The input of `prompt.section`: one named section of the system prompt, at
6966 * the moment the engine assembles it.
6967 */
6968 export type PromptSectionInput = {
6969 /**
6970 * As the engine names the section (`env_info_simple`, `memory`, ...); the
6971 * key a matcher narrows on.
6972 */
6973 name: string;
6974 /**
6975 * The section's text as core computed it, or null when core omits it.
6976 */
6977 text: string | null;
6978 };
6979
6980 /**
6981 * What a `prompt.section` hook returns: the text the prompt carries for that
6982 * section, or null to leave it out.
6983 */
6984 export type PromptSectionResult = {
6985 text: string | null;
6986 };
6987
6988 /**
6989 * `prompt.submit`'s input as a plugin's call takes it: `origin`, `turnId`
6990 * and `wait` are the engine's to set, `context` the hooks' to attach.
6991 *
6992 * `origin` is the calling plugin's name; `turnId` is the turn a prompt typed
6993 * mid-turn ran over; `wait` is false, as a plugin's prompt runs once idle.
6994 */
6995 export type PromptSubmitArgs = Omit<PromptSubmitInput, 'origin' | 'turnId' | 'wait' | 'context'>;
6996
6997 /**
6998 * A pasted or attached non-text item of a submitted prompt; its kind, never
6999 * its bytes.
7000 */
7001 export type PromptSubmitAttachment = {
7002 /**
7003 * The item's kind.
7004 */
7005 type: 'image' | 'audio' | 'document';
7006 /**
7007 * The item's MIME type (`image/png`), when known.
7008 */
7009 mediaType?: string;
7010 /**
7011 * The pasted file's name, when it had one.
7012 */
7013 filename?: string;
7014 };
7015
7016 /**
7017 * The input of `prompt.submit`: the prompt as typed, after the input became
7018 * a user message and before it enters the session.
7019 */
7020 export type PromptSubmitInput = {
7021 /**
7022 * The prompt's text as it will reach the model (pastes already expanded).
7023 */
7024 text: string;
7025 /**
7026 * Present only when the submission carried images or other non-text items.
7027 */
7028 attachments?: readonly PromptSubmitAttachment[];
7029 /**
7030 * What the model reads beside the prompt and the user never sees, each
7031 * entry one block after the prompt as typed; absent as the engine raises it.
7032 *
7033 * A hook attaches on the way down: `next({ ...e, context: [...(e.context
7034 * ?? []), mine] })`, keeping which it likes; none empty, any length: past
7035 * 100,000 characters (200,000 together) the model reads a head and path.
7036 */
7037 context?: readonly string[];
7038 /**
7039 * The id of the model turn that was running when the prompt was submitted
7040 * (`turn.start`'s `turnId`): typed over that turn, or delivered into it.
7041 *
7042 * A queued delivery (a peer session's message) reaches the model inside a
7043 * running turn. Absent for a prompt submitted while the session was idle,
7044 * and for a plugin's own (`$.prompt.submit`), which runs once it is idle.
7045 */
7046 turnId?: string;
7047 /**
7048 * Whether the user asked the prompt to wait its turn (`chat:queueSubmit`,
7049 * `ctrl+x enter` by default): true for that submission, false otherwise.
7050 *
7051 * The engine queues every prompt typed mid-turn either way; the flag is
7052 * for hooks, so one that cancels the running turn on a plain Enter can
7053 * leave a waiting prompt alone. False for a prompt a plugin submitted.
7054 */
7055 wait: boolean;
7056 /**
7057 * Where the submission came from (PromptOrigin), set by the engine where
7058 * it was queued: the user's Enter, a notification, a peer, a plugin.
7059 *
7060 * `next(e)` passes it on as received; no hook may set one.
7061 */
7062 origin: PromptOrigin;
7063 };
7064
7065 /**
7066 * What a `prompt.submit` hook returns and what `next(e)` resolves to: the
7067 * prompt that entered, `{ text, context?, origin? }`, or `{ drop: reason }`.
7068 *
7069 * `next(e)` resolves once the prompt entered the session and its turn
7070 * started, or it was queued behind the running one; not when the turn ends,
7071 * which is `turn.complete`. A hook answering without `next` enters nothing.
7072 */
7073 export type PromptSubmitResult = {
7074 /**
7075 * The prompt that entered; from core, the text that arrived at the
7076 * bottom. A rewrite passes it down, `next({ ...e, text })`.
7077 */
7078 text: string;
7079 /**
7080 * What entered beside the prompt for the model, never shown the user:
7081 * from core, the context that arrived (`e.context`).
7082 *
7083 * Each entry is one block after the prompt as typed. A hook attaches
7084 * context on the way down; one put here after `next` resolved is not
7085 * attached (the prompt had entered), and is logged.
7086 */
7087 context?: readonly string[];
7088 /**
7089 * Where the prompt entered from: from core, `e.origin` as received;
7090 * absent, the prompt is the user's own.
7091 *
7092 * A hook may put back the origin it received; it may not set another.
7093 */
7094 origin?: PromptOrigin;
7095 drop?: undefined;
7096 } | {
7097 /**
7098 * The prompt did not enter: a hook's refusal, answered without `next`,
7099 * or a settings hook's block beneath.
7100 *
7101 * The text is shown to the user as the reason.
7102 */
7103 drop: string;
7104 text?: undefined;
7105 context?: undefined;
7106 origin?: undefined;
7107 };
7108
7109 /**
7110 * `prompt.suggest`'s input as a plugin's `$.prompt.suggest(args)` takes it:
7111 * `origin` is the engine's to set (the calling plugin's name).
7112 */
7113 export type PromptSuggestArgs = Omit<PromptSuggestInput, 'origin'>;
7114
7115 /**
7116 * The input of `prompt.suggest` (prompt-suggest/): a text about to be shown
7117 * dim in the empty prompt box, for Tab (or the right arrow) to take.
7118 */
7119 export type PromptSuggestInput = {
7120 /**
7121 * The proposed prompt: shown, not written; taking it puts it in the box
7122 * for editing. `next({ ...e, text })` proposes another.
7123 */
7124 text: string;
7125 /**
7126 * Who proposes (PromptSuggestOrigin), set by the engine where the
7127 * proposal starts. Pinned: `next(e)` passes it on as received.
7128 */
7129 origin: PromptSuggestOrigin;
7130 };
7131
7132 /**
7133 * Who proposes the text at `prompt.suggest`, as the engine stamps it where
7134 * the proposal starts; a closed set a matcher narrows on.
7135 *
7136 * `next(e)` passes it on as received; no hook sets one.
7137 */
7138 export type PromptSuggestOrigin = {
7139 /**
7140 * The engine's own guess at the person's next prompt, generated after
7141 * a turn (the prompt-suggestion service).
7142 */
7143 kind: 'suggestion';
7144 } | {
7145 /**
7146 * A plugin's `$.prompt.suggest`.
7147 */
7148 kind: 'plugin';
7149 /**
7150 * The proposing plugin's name.
7151 */
7152 name: string;
7153 };
7154
7155 /**
7156 * What a `prompt.suggest` hook returns and what `next(e)` resolves to:
7157 * whether the text is now the box's dim suggestion.
7158 */
7159 export type PromptSuggestResult = {
7160 /**
7161 * True once the box has the suggestion to show, at once or as soon as a
7162 * dialog gives the box back; false where it cannot show.
7163 *
7164 * It cannot while the box holds text, a turn runs, the text is blank, or
7165 * the session is headless. A hook answering `{ isShown: false }` without
7166 * `next` keeps it from showing.
7167 */
7168 isShown: boolean;
7169 };
7170
7171 /**
7172 * A `$.ui.blit` argument repainting one of the caller's mounted Rasters.
7173 *
7174 * `columns` and `rows`, when given, must be the mounted size (a resize is a
7175 * redraw, `$.ui.invalidate("ui.render")`, not a blit).
7176 */
7177 export type RasterBlitArgs = {
7178 /**
7179 * The site the Raster is drawn in, by the `requestId` this plugin draws
7180 * it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
7181 */
7182 requestId: string;
7183 /**
7184 * The Raster's `key` in that drawing.
7185 */
7186 key: string;
7187 /**
7188 * The new cells, encoded as the element's `cells` are (RasterProps), for
7189 * the mounted `columns * rows`.
7190 */
7191 cells: string;
7192 /**
7193 * The width the cells are laid out for; refused unless it is the mounted
7194 * Raster's. Absent, the mounted width.
7195 */
7196 columns?: number;
7197 /**
7198 * The height the cells are laid out for; refused unless it is the mounted
7199 * Raster's. Absent, the mounted height.
7200 */
7201 rows?: number;
7202 };
7203
7204 /**
7205 * The props of `Raster`, the terminal surface's cell-grid leaf: a fixed box
7206 * of cells, each a glyph, a foreground and a background, packed in `cells`.
7207 *
7208 * A leaf: no children, `hover` or `onPress` yet; repainted in place by
7209 * `$.ui.blit`. Terminal only for now (elsewhere a fragment); its palette
7210 * paints 1024 distinct color pairs at once and the rest as their nearest.
7211 */
7212 export type RasterProps = {
7213 /**
7214 * The element's address within the drawing: what `$.ui.blit` names to
7215 * repaint it, unique among the Rasters of one tree.
7216 */
7217 key: string;
7218 /**
7219 * How many terminal columns wide, 1 to 512; the site clips what its body
7220 * cannot show.
7221 */
7222 columns: number;
7223 /**
7224 * How many terminal rows tall, 1 to 256.
7225 */
7226 rows: number;
7227 /**
7228 * Every cell, row-major: standard padded base64 of `columns * rows`
7229 * little-endian u32 triplets `[codePoint, foreground, background]`.
7230 *
7231 * A code point is one printable width-1 BMP character (blocks, box drawing,
7232 * braille too), or the tree is refused naming the cell's index; a color is
7233 * `0x00RRGGBB`, or `0x01000000` (bit 24 alone) for the terminal's default.
7234 *
7235 * @example const words = Uint32Array.of(0x2588, 0xff8800, 0x01000000)
7236 * const cells = new Uint8Array(words.buffer).toBase64() // one orange cell
7237 */
7238 cells: string;
7239 };
7240
7241 /**
7242 * The hooks module's entry: `export function register(on, options)`. `on`
7243 * registers hooks; `options` is the plugin's configuration (PluginOptions).
7244 *
7245 * The options are fixed for this activation: a change to them reloads the
7246 * plugin and `register` runs again with the new object. Hooks close over it.
7247 * Its return is dropped, a promise awaited: `on => on(...)` is a module.
7248 *
7249 * @example
7250 * on("tool.call", ($, e, next) => e.tool === "Bash" ? { deny: "no" } : next(e))
7251 */
7252 export type Register = (on: On, options: PluginOptions) => unknown;
7253
7254 /**
7255 * What `on(...)` returns for a hook of type `F`: the registration, which
7256 * takes one `.catch` (CatchHandler); without it a failed hook is absent.
7257 *
7258 * A second `.catch` on one registration throws, as does one after
7259 * register() returned and one on `engine.create`, whose hook has no budget
7260 * and whose failure is the load's.
7261 */
7262 export type Registration<F> = {
7263 /**
7264 * Sets the handler run when the hook throws or overruns its budget; its
7265 * answer within the grace stands as the hook's result for the dispatch.
7266 *
7267 * The budget is HookBudget's `ms` and the grace its `catchMs`, both on
7268 * the clock that stops while the code waits on `next` or `$`.
7269 */
7270 readonly catch: (handler: CatchHandler<F>) => void;
7271 };
7272
7273 /**
7274 * What an element takes as `children`, as JSX passes them: a node, a number
7275 * (drawn as its string), a value the factory drops, or a list that may nest.
7276 *
7277 * `false`, `null` and `undefined` are dropped, so `{ok && <Text>hi</Text>}`
7278 * and `{n > 0 ? <Text>{n}</Text> : null}` type; a mapped list beside a
7279 * sibling nests. The element holds the flat, normalized list of RenderNode.
7280 */
7281 export type RenderChildren = RenderNode | number | boolean | null | undefined | readonly RenderChildren[];
7282
7283 /**
7284 * Everything `ui.render` can draw: one name per component that has a render
7285 * site; a matcher narrows on it.
7286 *
7287 * The permission dialog is drawn by the engine alone, since its answer
7288 * authorises an action; a plugin adds context with `$.ui.notice`. `Pane` is
7289 * the one component whose instances a plugin opens (`$.ui.open`).
7290 */
7291 export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'ToolProgress' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
7292
7293 /**
7294 * What a render hook returns, and what `next(e)` resolves to: a plain-data
7295 * tree of elements (a Box or Text is a StyledElement), strings as children.
7296 *
7297 * Props are an allowlisted subset of Ink's Box/Text props (the ones
7298 * ElementProps declares); a tree with any other prop fails validation as a
7299 * whole and the engine's own component is drawn with the original props.
7300 */
7301 export type RenderElement = StyledElement<'Box', BoxHoverProps> | StyledElement<'Text', TextHoverProps> | {
7302 /**
7303 * A button, on every surface: `[ label ]` on the terminal, a native
7304 * button on a desktop; a press raises `ui.press` (`e.element` the key).
7305 *
7306 * Built by `<Button>` or the table's `t.Button`. The `onPress` closure
7307 * stays in the plugin's own environment under `press.handle`; the host
7308 * holds the handle for the lifetime of the drawing. A leaf: no children.
7309 */
7310 type: 'Button';
7311 props: {
7312 /**
7313 * The element's address: what `e.element` carries and what a matcher
7314 * names (`{ element: "explain" }`).
7315 */
7316 key: string;
7317 /**
7318 * The text drawn on the button.
7319 */
7320 label: string;
7321 /**
7322 * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it
7323 * while the plugin's site holds the focus; anything else is refused.
7324 *
7325 * The band after ctrl+x tab or a click, a focused `Pane`: on keydown,
7326 * lowercased; never from the composer, save a bare digit in an empty
7327 * one pressing a band Button. Two on one hotkey: the later wins.
7328 */
7329 hotkey?: string;
7330 /**
7331 * An engine keybinding action (`"app:cycleDiffBase"`) whose chord
7332 * presses the Button from the prompt; an unknown name is refused.
7333 *
7334 * Chords, or a modified key Global or an active context binds, on
7335 * the terminal while mounted, no dialog up, no engine handler of it
7336 * mounted; a pane's over the band's over another's, the last drawn.
7337 */
7338 action?: string;
7339 /**
7340 * Drawn without chrome: the hotkey in the accent color, a colon,
7341 * then the label (`1: Yes`); without a `hotkey`, the label alone.
7342 *
7343 * The focus still inverts it. In JSX the label may be the one string
7344 * child (`<Button hotkey="1" plain onPress={...}>Yes</Button>`); the
7345 * key defaults to the label.
7346 */
7347 plain?: true;
7348 /**
7349 * The label dim at rest, as `Text`'s `dimColor`, and at full strength
7350 * under the pointer or the focus; absent draws as false.
7351 */
7352 dimColor?: TextProps['dimColor'];
7353 /**
7354 * The site's ring starts on this element when the site takes the
7355 * keyboard; the first drawn of several. Absent draws as before.
7356 */
7357 autoFocus?: true;
7358 };
7359 /**
7360 * Where the handler lives: the plugin whose hook drew the element, and
7361 * the handle its environment keeps the `onPress` closure under.
7362 *
7363 * The runtime stamps the plugin as the tree leaves that hook.
7364 */
7365 press: {
7366 plugin: string;
7367 handle: number;
7368 };
7369 /**
7370 * Label style overrides (the Text set) the surface applies while the
7371 * nearest keyed Box, or the group `scope` names, is hovered; plain data.
7372 */
7373 hover?: TextHoverProps;
7374 } | {
7375 /**
7376 * A one-line text field on every surface; a change and Enter raise
7377 * `ui.input` (`e.element` the key, `e.kind` which, `e.value` the text).
7378 *
7379 * Built by `<Input>` or the table's `t.Input`. The `onInput` and
7380 * `onSubmit` closures stay in the plugin's own environment under
7381 * `press.handle`, held as a Button's is. A leaf: no children.
7382 */
7383 type: 'Input';
7384 props: {
7385 /**
7386 * The element's address: what `e.element` carries and what a matcher
7387 * names (`{ element: "reply" }`).
7388 */
7389 key: string;
7390 /**
7391 * Text drawn before the field.
7392 */
7393 label?: string;
7394 /**
7395 * Text drawn dim in an empty field.
7396 */
7397 placeholder?: string;
7398 /**
7399 * The text the field holds when drawn.
7400 */
7401 value?: string;
7402 /**
7403 * What Enter does, drawn beside the field while it has focus.
7404 */
7405 submitLabel?: string;
7406 /**
7407 * The site's ring starts on this element when the site takes the
7408 * keyboard; the first drawn of several. Absent draws as before.
7409 */
7410 autoFocus?: true;
7411 };
7412 /**
7413 * Where the handlers live: the plugin whose hook drew the element, and
7414 * the handle its environment keeps the closures under.
7415 *
7416 * The runtime stamps the plugin as the tree leaves that hook.
7417 */
7418 press: {
7419 plugin: string;
7420 handle: number;
7421 };
7422 children?: undefined;
7423 } | {
7424 /**
7425 * A one-of-several picker on every surface; a pick raises `ui.select`
7426 * (`e.element` the key, `e.value` the option's value).
7427 *
7428 * Built by `<Select>` or the table's `t.Select`. The `onSelect` closure
7429 * stays in the plugin's own environment under `press.handle`, held as
7430 * a Button's is. A leaf: no children.
7431 */
7432 type: 'Select';
7433 props: {
7434 /**
7435 * The element's address: what `e.element` carries and what a matcher
7436 * names (`{ element: "peer" }`).
7437 */
7438 key: string;
7439 /**
7440 * Text drawn before the current value.
7441 */
7442 label?: string;
7443 /**
7444 * What can be picked, in the order drawn: each a value and the text
7445 * drawn for it.
7446 */
7447 options: readonly SelectOption[];
7448 /**
7449 * Which option is selected when drawn.
7450 */
7451 value?: string;
7452 /**
7453 * The site's ring starts on this element when the site takes the
7454 * keyboard; the first drawn of several. Absent draws as before.
7455 */
7456 autoFocus?: true;
7457 };
7458 /**
7459 * Where the handler lives: the plugin whose hook drew the element, and
7460 * the handle its environment keeps the closure under.
7461 *
7462 * The runtime stamps the plugin as the tree leaves that hook.
7463 */
7464 press: {
7465 plugin: string;
7466 handle: number;
7467 };
7468 children?: undefined;
7469 } | {
7470 /**
7471 * A hyperlink every surface draws: an OSC 8 span on the terminal (its
7472 * text then the URL in dim where unsupported), an anchor on desktop.
7473 *
7474 * Inline: its children are the text, strings and inline elements;
7475 * absent children the label, absent both the URL. `href` is `https:`
7476 * (or `http://localhost`) and bounded, or the tree is refused.
7477 */
7478 type: 'Link';
7479 props: LinkProps;
7480 children?: RenderNode[];
7481 } | {
7482 /**
7483 * Source code every surface draws with the engine's highlighter, tokens
7484 * coloured by language; under `format: 'diff'`, unified-diff hunks.
7485 *
7486 * A leaf: a dim gutter numbers the lines from `startLine`; a diff has
7487 * both gutters, markers, add and remove backgrounds. `source` is
7488 * bounded as a Text's string is, or the tree is refused.
7489 */
7490 type: 'Code';
7491 props: CodeProps;
7492 children?: undefined;
7493 } | {
7494 /**
7495 * A block of markdown every surface draws as it draws an assistant
7496 * reply's text: its own renderer, theme, hyperlinks and highlighting.
7497 *
7498 * Built by `<Markdown>` or the table's `t.Markdown`. A leaf: `text` is
7499 * bounded as a Text's string is, or the tree is refused. Without a
7500 * `press` its links are the surface's own, opened as it opens links.
7501 */
7502 type: 'Markdown';
7503 props: MarkdownLeafProps;
7504 children?: undefined;
7505 } | {
7506 /**
7507 * A `Markdown` whose plugin answers the links it drew (`onLinkPress`):
7508 * a press on one raises `ui.press` with `e.link`, the surface opens none.
7509 */
7510 type: 'Markdown';
7511 props: MarkdownLeafProps;
7512 /**
7513 * Where the `onLinkPress` handler lives: the plugin whose hook drew
7514 * the element, and the handle its environment keeps the closure under.
7515 *
7516 * The runtime stamps the plugin as the tree leaves that hook.
7517 */
7518 press: {
7519 plugin: string;
7520 handle: number;
7521 };
7522 children?: undefined;
7523 } | {
7524 /**
7525 * A region one of the plugin's SURFACE MODULES, named by path, draws and
7526 * handles input for on the drawing thread, without `$` (ClientModule).
7527 *
7528 * `Client` from the table. One instance per plugin, drawing and `key`
7529 * lives while the node stays in the tree, and talks to the plugin's
7530 * hooks through `ui.message`. The desktop carries it as data.
7531 */
7532 type: 'Client';
7533 props: ClientProps;
7534 /**
7535 * Whose surface module `props.module` names: the plugin whose hook
7536 * drew the element, stamped by the runtime as the tree leaves it.
7537 */
7538 client: {
7539 plugin: string;
7540 };
7541 children?: undefined;
7542 } | {
7543 /**
7544 * A vector drawing, the remote surfaces' alone: the SVG markup is the
7545 * element's data, drawn in an isolated box, off the page.
7546 *
7547 * A leaf: hooks above wrap or replace it whole, nothing reaches inside;
7548 * a press other plugins should see goes on an enclosing Button. On a
7549 * surface whose table lacks it the tree is refused.
7550 */
7551 type: 'Svg';
7552 props: SvgProps;
7553 children?: undefined;
7554 } | {
7555 /**
7556 * A grid of terminal cells, the terminal surface's alone: each cell a
7557 * glyph, a foreground and a background, packed in `props.cells`.
7558 *
7559 * A leaf, one node however many cells; hooks above wrap or replace it
7560 * whole. A mounted one is repainted in place by its plugin's
7561 * `$.ui.blit`. On a surface whose table lacks it the tree is refused.
7562 */
7563 type: 'Raster';
7564 props: RasterProps;
7565 /**
7566 * Whose Raster: the plugin whose hook drew the element, stamped by the
7567 * runtime as the tree leaves it; the one plugin whose blit reaches it.
7568 */
7569 raster: {
7570 plugin: string;
7571 };
7572 children?: undefined;
7573 } | {
7574 /**
7575 * A picture, the terminal surface's alone: `props.source` drawn over a
7576 * box of cells where the terminal can, `props.alt` where it cannot.
7577 *
7578 * A leaf: hooks above wrap or replace it whole; a press other plugins
7579 * should see goes on an enclosing Button; keyed, its plugin's
7580 * `$.ui.blit` swaps it. On a surface without it the tree is refused.
7581 */
7582 type: 'Image';
7583 props: ImageProps;
7584 /**
7585 * Whose Image: the plugin whose hook drew the element, stamped by the
7586 * runtime as the tree leaves it; the one plugin whose blit reaches it.
7587 */
7588 image: {
7589 plugin: string;
7590 };
7591 children?: undefined;
7592 } | {
7593 /**
7594 * The component core draws itself, with the props held under `ref`.
7595 */
7596 type: 'engine';
7597 /**
7598 * Which drawing: the number core answered from `next(e)`, under which
7599 * it holds the props it received; 0 draws the original props.
7600 */
7601 ref: number;
7602 };
7603
7604 /**
7605 * The render event: `ui.render`, one event for every component that has a
7606 * render site.
7607 */
7608 export type RenderEventName = 'ui.render';
7609
7610 /**
7611 * The input of `ui.render`: a union discriminated by `component`, one member
7612 * per RenderComponent and per RenderSurface.
7613 */
7614 export type RenderInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = C extends RenderComponent ? P extends RenderSurface ? RenderInputOf<C, P> : never : never;
7615
7616 /**
7617 * One `ui.render` input, for a component narrowed to one surface.
7618 */
7619 export type RenderInputOf<C extends RenderComponent, P extends RenderSurface> = {
7620 /**
7621 * Where the tree will be drawn; one literal per member, so
7622 * `if (e.surface === "terminal")` narrows `e` and `$.ui.resolve(e)`.
7623 *
7624 * Over the wire it is what the client declared, a rendering fact and not a
7625 * trust signal: do not key policy on it.
7626 */
7627 surface: P;
7628 /**
7629 * Which component this instance is; the key a matcher narrows on.
7630 */
7631 component: C;
7632 /**
7633 * The instance: the tool_use_id for a dialog or tool row, the message id
7634 * for a message, the agent id for a spinner.
7635 *
7636 * Two drawings of one component are two instances.
7637 */
7638 requestId: string;
7639 /**
7640 * The size of what the surface draws into, in character cells, and whether
7641 * its layout docks a pane; absent where no surface has measured.
7642 *
7643 * Part of the envelope: a rewrite keeps it. On the terminal, the interactive
7644 * screen's, where a change of width re-draws every hooked site once the
7645 * resize settles; on a remote surface, what it reported.
7646 */
7647 viewport?: RenderViewport;
7648 /**
7649 * The component's plain-data props.
7650 */
7651 props: RenderPropsOf[C];
7652 };
7653
7654 /**
7655 * A node of a render tree: an element, or a string (text).
7656 */
7657 export type RenderNode = RenderElement | string;
7658
7659 /**
7660 * The plain-data props of each renderable component, as `ui.render` sees
7661 * them under `e.props`; a hook rewrites them with `next({ ...e, props })`.
7662 *
7663 * A rewrite is validated by the component and an invalid one draws the
7664 * original. This table is the plugin-facing render contract; the author's
7665 * file notes which surfaces raise each member (RENDER_SURFACES_OF).
7666 */
7667 export type RenderPropsOf = {
7668 /**
7669 * The dialog the AskUserQuestion tool opens.
7670 *
7671 * Raised on every surface.
7672 */
7673 AskUserQuestion: {
7674 /**
7675 * The name of the tool whose call opened the dialog (`AskUserQuestion`).
7676 */
7677 tool: string;
7678 /**
7679 * The tool's `questions` input, as the dialog will draw them; a rewrite
7680 * must still fit the tool's schema or the original is drawn.
7681 */
7682 questions: unknown[];
7683 /**
7684 * The call's `metadata.source` (who asked) when the model gave one.
7685 * Analytics only; never drawn.
7686 */
7687 metadataSource?: string;
7688 };
7689 /**
7690 * A user-role transcript row: the person's prompt (`> ...`), a background
7691 * task's notification, or a message another agent, teammate or session sent.
7692 *
7693 * `origin`, `task` and `from` tell them apart and are read-only; a rewrite
7694 * of `text` draws in the row alone: the stored message, and the model's
7695 * framing of another party's words as that party's, stay as they were.
7696 *
7697 * Raised on every surface.
7698 */
7699 UserMessage: {
7700 /**
7701 * What the row shows: the prompt as typed, a notification's summary, or
7702 * a message's body less the engine's framing (summary line included).
7703 *
7704 * A rewrite is printable, bounded text and draws where the engine draws
7705 * the body; a teammate block of several frames or with a summary line
7706 * keeps the engine's drawing, one string not being those parts.
7707 */
7708 text: string;
7709 /**
7710 * Where the stored message came from, as `prompt.submit` named it: the
7711 * composer's, a task notification's, a peer's, a channel's, a plugin's.
7712 *
7713 * `unclassified` for a teammate's (its drain stamps none) and for a
7714 * message stored before stamps. Read-only.
7715 */
7716 origin: PromptOrigin;
7717 /**
7718 * Whether the view draws the row in full: the ctrl+o transcript,
7719 * `--verbose`, a surface with no ctrl+o (an export). Read-only.
7720 *
7721 * False, a message row is one dim line naming its sender; a hook that
7722 * draws a compact row of its own passes when true, so ctrl+o shows all.
7723 */
7724 isExpanded: boolean;
7725 /**
7726 * What a notification row (`origin.kind` `task-notification`) reports
7727 * on: its background task; absent on every other row. Read-only.
7728 */
7729 task?: UserMessageTask;
7730 /**
7731 * Who sent the message the row carries: another agent of this session, a
7732 * teammate, another session, a channel; absent otherwise. Read-only.
7733 */
7734 from?: UserMessageFrom;
7735 /**
7736 * Which of its rows the transcript's viewport shows now: `null` while
7737 * drawn outside it, absent where the surface does not say. Read-only.
7738 *
7739 * Reported once drawn and again when it changes: on a scroll, for the
7740 * messages at the viewport's edges only. A rewrite carries it on as
7741 * received; one that changes or drops it is refused.
7742 */
7743 onScreen?: OnScreen | null;
7744 };
7745 /**
7746 * One text block of an assistant reply in the transcript; a rewrite
7747 * changes the drawing and leaves the stored message alone (ctrl+o).
7748 *
7749 * Raised on every surface.
7750 */
7751 AssistantMessage: {
7752 /**
7753 * The block's text, markdown, as the transcript will draw it.
7754 */
7755 text: string;
7756 /**
7757 * True on the block that draws the bullet opening a reply.
7758 */
7759 isFirstOfReply: boolean;
7760 /**
7761 * Which of its rows the transcript's viewport shows now: `null` while
7762 * drawn outside it, absent where the surface does not say. Read-only.
7763 *
7764 * Reported once drawn and again when it changes: on a scroll, for the
7765 * messages at the viewport's edges only. A rewrite carries it on as
7766 * received; one that changes or drops it is refused.
7767 */
7768 onScreen?: OnScreen | null;
7769 };
7770 /**
7771 * A tool call's row in the transcript (`Bash(ls -la)` and its result); the
7772 * call was decided by `tool.call`, so a rewrite here changes the row alone.
7773 *
7774 * Raised on every surface.
7775 */
7776 ToolUse: {
7777 /**
7778 * The id `tool.call` carried for this call (`e.tool_use_id` there); the
7779 * same value as the row's `requestId`, where it is looked for. Read-only.
7780 */
7781 tool_use_id: string;
7782 /**
7783 * Which one the row draws (`Bash`, `Read`, a plugin's tool), as
7784 * `tool.call` named it.
7785 */
7786 tool: string;
7787 /**
7788 * The call's input, as the model sent it.
7789 */
7790 input: unknown;
7791 /**
7792 * True while the call is still running.
7793 */
7794 isRunning: boolean;
7795 /**
7796 * True when the call ended in an error (a refusal at the dialog is one).
7797 */
7798 isErrored: boolean;
7799 /**
7800 * True when an abort ended the call: the user's Esc or a plugin's
7801 * `$.turn.abort` cut it while it ran, or dropped it before it ran.
7802 *
7803 * The row draws `Interrupted` for it, as the transcript marker does.
7804 */
7805 isInterrupted: boolean;
7806 /**
7807 * The stored result once the call has resolved (`{ stdout, stderr, ... }`
7808 * for Bash: `BuiltinToolResults[tool]`); undefined while it runs.
7809 *
7810 * For a call that errored, was refused or an abort cut, it is the text
7811 * the model read (an `isInterrupted` call: the abort's own). An expanded
7812 * group's rows draw it inline; a standalone row's is its own `ToolResult`.
7813 */
7814 output?: unknown;
7815 /**
7816 * Which of its rows the transcript's viewport shows now: `null` while
7817 * drawn outside it, absent where the surface does not say. Read-only.
7818 *
7819 * Reported once drawn and again when it changes: on a scroll, for the
7820 * messages at the viewport's edges only. A rewrite carries it on as
7821 * received; one that changes or drops it is refused.
7822 */
7823 onScreen?: OnScreen | null;
7824 };
7825 /**
7826 * The result block drawn under a standalone tool row in the transcript,
7827 * which the tool's own result renderer draws from `output`.
7828 *
7829 * A rewrite of `output` is checked against the tool's output schema (one
7830 * that does not fit draws nothing; one the renderer cannot read hits the
7831 * row's error boundary). The stored result is untouched.
7832 *
7833 * Raised on every surface.
7834 */
7835 ToolResult: {
7836 /**
7837 * The id `tool.call` carried for the call this result belongs to
7838 * (`e.tool_use_id` there); the same value as `requestId`. Read-only.
7839 */
7840 tool_use_id: string;
7841 /**
7842 * Which one the result belongs to (`Bash`, `Read`, a plugin's tool).
7843 * Read-only.
7844 */
7845 tool: string;
7846 /**
7847 * The tool's own result object (`{ stdout, stderr, interrupted, ... }` for
7848 * Bash), the same one `ToolUse.output` carries; a rewrite is drawn.
7849 *
7850 * A built-in tool's is `BuiltinToolResults[tool]`, the record
7851 * `tool.call` resolved as `result`.
7852 */
7853 output: unknown;
7854 /**
7855 * True when the call ended in an error, which draws the error text and not
7856 * `output`. Read-only.
7857 */
7858 isErrored: boolean;
7859 /**
7860 * Which of its rows the transcript's viewport shows now: `null` while
7861 * drawn outside it, absent where the surface does not say. Read-only.
7862 *
7863 * Reported once drawn and again when it changes: on a scroll, for the
7864 * messages at the viewport's edges only. A rewrite carries it on as
7865 * received; one that changes or drops it is refused.
7866 */
7867 onScreen?: OnScreen | null;
7868 };
7869 /**
7870 * A run of tool calls the transcript folds into one count line (`Read 3
7871 * files, ran 2 shell commands`): reads, searches, listings.
7872 *
7873 * A hook that sets `isExpanded` unfolds the group where it is, and each row
7874 * it unfolds into is a `ToolUse` drawing a `ToolUse` hook then sees.
7875 *
7876 * Raised on every surface.
7877 */
7878 ToolGroup: {
7879 /**
7880 * In the order the model made them.
7881 */
7882 calls: ReadonlyArray<ToolGroupCall>;
7883 /**
7884 * True while the group is the live one: a call in it may still be
7885 * running and the model's next call may join it.
7886 */
7887 isActive: boolean;
7888 /**
7889 * Whether each call draws as its own `ToolUse` row (true under
7890 * `--verbose` and in the ctrl+o transcript) or the group draws one line.
7891 *
7892 * The one prop of the three a rewrite changes on the screen.
7893 */
7894 isExpanded: boolean;
7895 /**
7896 * Which of its rows the transcript's viewport shows now: `null` while
7897 * drawn outside it, absent where the surface does not say. Read-only.
7898 *
7899 * Reported once drawn and again when it changes: on a scroll, for the
7900 * messages at the viewport's edges only. A rewrite carries it on as
7901 * received; one that changes or drops it is refused.
7902 */
7903 onScreen?: OnScreen | null;
7904 };
7905 /**
7906 * The output row a slash command printed in the transcript, under its echo
7907 * (`/cost`'s lines, the `text` a `command.run` hook answered).
7908 *
7909 * What the run resolved as text, a `local` command's or a plugin's alike. A
7910 * rewrite of `text` draws there and the stored row keeps what the model
7911 * reads; a hook's own tree draws in the row's place, the transcript's width.
7912 *
7913 * Raised on every surface.
7914 */
7915 CommandOutput: {
7916 /**
7917 * Which one printed the row, as `command.run` named it (no slash); a
7918 * hook on its own command matches by it.
7919 *
7920 * Read-only: a rewrite carries it on as received; one that changes or
7921 * drops it is refused and the engine draws its own row.
7922 */
7923 command: string;
7924 /**
7925 * The arguments the run had, as the echo above the row shows them
7926 * (`***` for a command that marks its arguments sensitive). Read-only.
7927 */
7928 args: string;
7929 /**
7930 * The row's text: what the command printed, or the `text` a hook
7931 * answered under its plugin's name; markdown, as the row draws it.
7932 */
7933 text: string;
7934 /**
7935 * True when the row is the run's error line (a command that threw),
7936 * which draws in the error colour and not dim. Read-only.
7937 */
7938 isErrored: boolean;
7939 /**
7940 * Which of its rows the transcript's viewport shows now: `null` while
7941 * drawn outside it, absent where the surface does not say. Read-only.
7942 *
7943 * Reported once drawn and again when it changes: on a scroll, for the
7944 * messages at the viewport's edges only. A rewrite carries it on as
7945 * received; one that changes or drops it is refused.
7946 */
7947 onScreen?: OnScreen | null;
7948 };
7949 /**
7950 * One row of the live tool-progress region under a running tool call; today
7951 * the run-in-background pill. One instance per row.
7952 *
7953 * A union on `kind`: other progress kinds join as their props become plain
7954 * data, each with its own fields, so a hook matches `{ props: { kind:
7955 * "background_hint" } }` or branches on `e.props.kind` and stays right.
7956 *
7957 * Raised on the terminal surface only.
7958 */
7959 ToolProgress: {
7960 /**
7961 * The tool call the row belongs to, as `tool.call` and the `ToolUse` row
7962 * carry it. Read-only: a rewrite carries it on as received.
7963 *
7964 * While several foreground calls share one pill, the first of them.
7965 */
7966 tool_use_id: string;
7967 /**
7968 * Which progress row: the run-in-background pill. Read-only.
7969 */
7970 kind: 'background_hint';
7971 /**
7972 * The pill's text as the engine draws it, dim, under the tool call:
7973 * `(ctrl+b to run in background)`, or with the person's own binding.
7974 *
7975 * A rewrite is drawn in its place, dim; `""` draws nothing. A hook that
7976 * returns a tree draws that instead.
7977 */
7978 hint: string;
7979 };
7980 /**
7981 * The line that animates while a turn runs (`Sauteing... (12s, 300
7982 * tokens)`); a remote surface draws its own.
7983 *
7984 * The row reads `word` (or `message` while one overrides it), then
7985 * `suffix`, then the dim parenthetical the engine keeps (elapsed time,
7986 * tokens, effort); a hook rewrites the first three or draws its own tree.
7987 *
7988 * Raised on the terminal surface only.
7989 */
7990 Spinner: {
7991 /**
7992 * Animated by the line (`Sauteing`), as sampled for this turn.
7993 */
7994 word: string;
7995 /**
7996 * The text drawn instead of the word while a state overrides it, else null.
7997 */
7998 message: string | null;
7999 /**
8000 * What the engine draws right after the word or message to say the turn is
8001 * still going: one ellipsis character.
8002 *
8003 * Left off a text that already ends in an ellipsis, so a rewritten
8004 * `message` ending in one shows one. A rewrite is drawn as given (`""`
8005 * draws the text bare, `" ~"` draws `Sauteing ~`); left out, the engine's.
8006 */
8007 suffix: string;
8008 /**
8009 * What the turn is doing.
8010 */
8011 mode: 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use';
8012 };
8013 /**
8014 * The line that closes a turn in the transcript (`Baked for 3s`); a
8015 * remote surface draws its own footer.
8016 *
8017 * Raised on the terminal surface only.
8018 */
8019 TurnDuration: {
8020 /**
8021 * The past-tense word the line drew (`Baked`), as sampled for this line.
8022 */
8023 word: string;
8024 /**
8025 * The turn's duration in milliseconds, as the line formats it (`3s`,
8026 * `1m 4s`).
8027 */
8028 durationMs: number;
8029 /**
8030 * Which of its rows the transcript's viewport shows now: `null` while
8031 * drawn outside it, absent where the surface does not say. Read-only.
8032 *
8033 * Reported once drawn and again when it changes: on a scroll, for the
8034 * messages at the viewport's edges only. A rewrite carries it on as
8035 * received; one that changes or drops it is refused.
8036 */
8037 onScreen?: OnScreen | null;
8038 };
8039 /**
8040 * One dim status line under the logo (the model source, an experiment
8041 * enrollment, a settings hint), with a trailing `/command`.
8042 *
8043 * Raised on the terminal surface only.
8044 */
8045 InfoNotice: {
8046 /**
8047 * The notice's text, flattened to one string.
8048 */
8049 text: string;
8050 /**
8051 * The slash command appended after the text, or null when the notice has
8052 * none.
8053 */
8054 command: string | null;
8055 /**
8056 * Which of its rows the transcript's viewport shows now: `null` while
8057 * drawn outside it, absent where the surface does not say. Read-only.
8058 *
8059 * Reported once drawn and again when it changes: on a scroll, for the
8060 * messages at the viewport's edges only. A rewrite carries it on as
8061 * received; one that changes or drops it is refused.
8062 */
8063 onScreen?: OnScreen | null;
8064 };
8065 /**
8066 * The dim mode labels at the right of the prompt footer (`focus`, `memory
8067 * paused`), joined by ` & `. One instance.
8068 *
8069 * A hook adds a mode by rewriting `modes`, removes one by filtering, or
8070 * draws its own tree.
8071 *
8072 * Raised on the terminal and desktop surfaces only.
8073 */
8074 SessionMode: {
8075 /**
8076 * The labels the footer shows, in order; empty when there are none.
8077 */
8078 modes: readonly string[];
8079 };
8080 /**
8081 * The dim hint line under the prompt (`? for shortcuts`, `esc to
8082 * interrupt`, the pills beside them). One instance.
8083 *
8084 * A hook rewrites `hint` and the rewrite is drawn in the line's place, or
8085 * draws its own tree; `isDraft` and `isWorking` say what the line is for.
8086 *
8087 * Raised on the terminal surface only.
8088 */
8089 PromptHint: {
8090 /**
8091 * True while the prompt holds typed text. Read-only.
8092 */
8093 isDraft: boolean;
8094 /**
8095 * True while a model turn is running. Read-only.
8096 */
8097 isWorking: boolean;
8098 /**
8099 * The line's text as the engine draws it; one string, so a rewrite
8100 * replaces the line.
8101 *
8102 * Read from the drawn line the way the screen reader reads it, one space
8103 * between parts.
8104 */
8105 hint: string;
8106 };
8107 /**
8108 * The band directly above the prompt input, where the surveys draw; the
8109 * engine draws nothing of its own here.
8110 *
8111 * A hook draws a tree, or passes; one instance. The person collapses it
8112 * (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab): an Input
8113 * types, a Button arms the hotkeys, a tree taller than it scrolls.
8114 *
8115 * Raised on the terminal surface only.
8116 */
8117 AbovePrompt: {
8118 /**
8119 * True while a survey holds the band; a hook yields to it. Read-only.
8120 */
8121 hasSurvey: boolean;
8122 /**
8123 * True while a model turn is running. Read-only.
8124 */
8125 isWorking: boolean;
8126 /**
8127 * Rows the band may take: in fullscreen, what the bottom slot has left
8128 * above the prompt; otherwise the terminal's height. Read-only.
8129 *
8130 * That slot is capped at half the terminal's rows, the prompt's included.
8131 * A tree of at most `maxRows` rows shows whole; a taller one scrolls in a
8132 * window of `scroll.bodyRows`, and a bare digit arms no Button's hotkey.
8133 */
8134 maxRows: number;
8135 /**
8136 * Cells across the band: the terminal's width, or the transcript
8137 * column's while a `Pane` is docked beside it. Read-only.
8138 *
8139 * A tree wider than this wraps or truncates as its Text props say; size
8140 * a table or a rule to it rather than to `viewport.columns`.
8141 */
8142 bodyColumns: number;
8143 /**
8144 * The band's window over a tree taller than `maxRows`: engine-owned,
8145 * moved by the wheel, and by the person's keys while the band is focused.
8146 *
8147 * `bodyRows` is `maxRows` less the `n more` row. Read-only.
8148 */
8149 scroll: SiteScroll;
8150 /**
8151 * Which transcript is on screen above the band: the main conversation's
8152 * (no `agentId`) or one agent's, opened from the tasks list.
8153 *
8154 * The same band under either; a switch re-runs the hook with the new
8155 * view. Read-only: a rewrite carries it on as received; one that changes
8156 * or drops it is refused, the hook that passed it failing.
8157 */
8158 view: SiteView;
8159 };
8160 /**
8161 * The framed region a plugin opened with `$.ui.open({ id })`: one instance
8162 * per id (`requestId`), its body the hook's tree, one shown, the rest tabs.
8163 *
8164 * Placed by the surface (docked in fullscreen, else above the prompt) and
8165 * keyed by the person (ctrl+x tab, Esc), who closes it from the engine's mark
8166 * or ctrl+x x: `ui.close` with origin `person`, which a hook may refuse.
8167 *
8168 * Raised on every surface.
8169 */
8170 Pane: {
8171 /**
8172 * Its tab's label while more than one pane is open (with one, the engine
8173 * draws no title): the `title` it was opened with, or its id.
8174 *
8175 * A click on a tab, or Tab onto it and Enter, shows that pane. Read-only
8176 * here; another `$.ui.open` (or a hook on `ui.open`) retitles.
8177 */
8178 title: string;
8179 /**
8180 * True while the person has given the pane the keyboard: Tab walks its
8181 * elements, a Button's `hotkey` presses it, the arrows scroll. Read-only.
8182 */
8183 isFocused: boolean;
8184 /**
8185 * Cells across the body, inside the frame. Read-only.
8186 */
8187 bodyColumns: number;
8188 /**
8189 * Where the surface seated the pane: `dock` beside the transcript (the
8190 * terminal in fullscreen from 110 columns), or `inline` above the prompt.
8191 *
8192 * Read-only: a rewrite carries it on as received; one that changes or
8193 * drops it is refused, the hook that passed it failing.
8194 */
8195 placement: 'dock' | 'inline';
8196 /**
8197 * The body's window over the tree: engine-owned, moved by the person's
8198 * keys while the pane is focused. Read-only.
8199 */
8200 scroll: SiteScroll;
8201 /**
8202 * Which transcript is on screen beside the pane: the main conversation's
8203 * (no `agentId`) or one agent's, opened from the tasks list.
8204 *
8205 * The pane stays open across a switch, one instance re-rendered for the
8206 * view, so a hook draws for the agent in view. Read-only: a rewrite carries
8207 * it on as received; one that changes or drops it is refused.
8208 */
8209 view: SiteView;
8210 };
8211 };
8212
8213 /**
8214 * What a `ui.render` hook returns and what `next(e)` resolves to: a
8215 * RenderElement tree, the same for every component.
8216 */
8217 export type RenderResultOf = {
8218 [C in RenderComponent]: RenderElement;
8219 };
8220
8221 /**
8222 * Where a render event's component is drawn: `terminal` is Ink, which draws
8223 * the hook's whole tree; the rest are remote surfaces drawing it themselves.
8224 *
8225 * `desktop` is Claude Code Desktop, `mobile` the Claude mobile app, `vscode`
8226 * Claude Code for VS Code. A remote surface asks over the wire (ui_render),
8227 * draws with the props the hook handed core, and draws the tree where it has
8228 * a slot for it.
8229 *
8230 * Each surface's ask is its own evaluation, since a tree may hold an element
8231 * only some surfaces draw (Svg, Client).
8232 */
8233 export type RenderSurface = 'terminal' | 'desktop' | 'mobile' | 'vscode';
8234
8235 /**
8236 * The size of what a surface draws into, in character cells of the
8237 * surface's monospace metric, and whether its layout docks a pane.
8238 *
8239 * On the terminal, the conversation's columns and screen rows; on a remote
8240 * surface, the pane's width and height over the advance and line height of
8241 * its code font. Cell-based until the first element lays out in pixels.
8242 */
8243 export type RenderViewport = {
8244 /**
8245 * Cells across. A tree wider than this wraps or truncates, as its Text
8246 * props say.
8247 */
8248 columns: number;
8249 /**
8250 * Cells down the whole surface, not the room left for this component.
8251 *
8252 * Informational: a change of height alone re-draws nothing and keys no
8253 * new evaluation, so a hook reads it as of the last width or props change.
8254 */
8255 rows: number;
8256 /**
8257 * Whether this surface docks a pane beside the transcript, so a pane a
8258 * plugin opens unasked is a sidebar, not a takeover; absent is unknown.
8259 *
8260 * What `command.run`'s `presentation.isFullscreen` says. The terminal always
8261 * says: `true` fullscreen, `false` on the main screen, fixed per session; a
8262 * remote surface once its client reports it with the size, absent before.
8263 *
8264 * @remarks The desktop and VS Code report it once they place panes; the
8265 * mobile app, which has no dock, `false`. A change re-draws the sites.
8266 * @example if (e.viewport?.isFullscreen === true) void $.ui.open({ id })
8267 */
8268 isFullscreen?: boolean;
8269 };
8270
8271 /**
8272 * The input of `ui.resolve`: which surface's elements, for which component;
8273 * a union with one member per surface (ResolveInputOf).
8274 *
8275 * Resolved when the plugins load, ahead of any drawing, so it names the
8276 * surface and the component and not the props; a `ui.render` argument is
8277 * one (it carries both), which is what `$.ui.resolve(e)` takes.
8278 */
8279 export type ResolveInput<C extends RenderComponent = RenderComponent, P extends RenderSurface = RenderSurface> = P extends RenderSurface ? ResolveInputOf<C, P> : never;
8280
8281 /**
8282 * One `ui.resolve` input, for a component on one surface.
8283 */
8284 export type ResolveInputOf<C extends RenderComponent, P extends RenderSurface> = {
8285 /**
8286 * Where the table draws; one literal per member, so a hook that narrows
8287 * it narrows the table `next(e)` resolves to.
8288 */
8289 surface: P;
8290 /**
8291 * Which drawing the table is resolved for; the key a matcher narrows on.
8292 */
8293 component: C;
8294 };
8295
8296 /**
8297 * What each event's hook returns, and what its `next(e)` resolves to, by event
8298 * name.
8299 */
8300 export type ResultOf = EngineResultOf & ClassicResultOf & {
8301 [N in OpEventName]: OpEventResult<N>;
8302 } & {
8303 [N in NounEventName]: NounEventResult<N>;
8304 };
8305
8306 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';
8307
8308 /**
8309 * The members of `T` assignable to `S`; all of `T` when none is.
8310 */
8311 type Select<T, S> = [Extract<T, S>] extends [never] ? T : Extract<T, S>;
8312
8313 /**
8314 * The events a pattern selects, as a union of names: the one named, every
8315 * one under a glob's namespace, or every one a negation does not exclude.
8316 */
8317 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>;
8318
8319 /**
8320 * The literal each tag key of `I` is held to by matcher `M`: one-of arrays
8321 * flattened, RegExps widened to `unknown`.
8322 */
8323 type Selection<I, M> = {
8324 [K in keyof M & TagKeys<I>]: Literal<M[K] extends readonly (infer One)[] ? One : M[K]>;
8325 };
8326
8327 /**
8328 * One option of a `Select`: the value `onSelect` and `ui.select` carry, and
8329 * the text drawn for it (the value when absent).
8330 */
8331 export type SelectOption = {
8332 value: string;
8333 label?: string;
8334 };
8335
8336 /**
8337 * The props of `Select`, every surface's one-of-several picker: an address,
8338 * a label, the options, the one selected, the closure a pick runs. A leaf.
8339 *
8340 * Focused through the same ring as `Button` (`abovePrompt:focus`); keys reach
8341 * it only while it has focus (arrows move, Enter picks) and Esc always
8342 * returns to the prompt; a pick raises `ui.select`, its bottom `onSelect`.
8343 */
8344 export type SelectProps = {
8345 /**
8346 * The element's address: `e.element` at `ui.select`, what a matcher names.
8347 */
8348 key: string;
8349 /**
8350 * Text drawn before the current value.
8351 */
8352 label?: string;
8353 /**
8354 * What can be picked, in the order drawn; at least one, values unique.
8355 */
8356 options: readonly SelectOption[];
8357 /**
8358 * Which option is selected when drawn; the person's pick replaces it
8359 * until the hook draws another.
8360 */
8361 value?: string;
8362 /**
8363 * The site's focus ring starts here when the site takes the keyboard,
8364 * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
8365 *
8366 * A pane opened with `focus`, or the person's focus chord or click, is the
8367 * take. Of several in one site the first drawn wins; it raises `ui.focus`,
8368 * origin this plugin. A ring the person has moved stays where it was put.
8369 */
8370 autoFocus?: true;
8371 /**
8372 * Runs on a pick with the option's value, in the plugin's own environment:
8373 * the bottom of a `ui.select` chain. No model turn unless it asks one.
8374 */
8375 onSelect: (value: string, e: UiSelectArgument) => void;
8376 };
8377
8378 /**
8379 * The input of `session.attach`: a surface joined the session's roster of
8380 * attached clients (a phone opened the session; the desktop app connected).
8381 *
8382 * A remote client attaches by saying so (ui_attach) or by its first ask to
8383 * draw; the terminal's attachment is the REPL's binding and raises nothing.
8384 * Every field is the engine's: a hook observes, `next(e)` passes them on.
8385 */
8386 export type SessionAttachInput = {
8387 /**
8388 * Where the client draws: what it declared, a rendering fact.
8389 */
8390 surface: RenderSurface;
8391 /**
8392 * The client's own id, unique in the roster; two phones are two clients on
8393 * one surface. A client that never named itself is `<surface>:default`.
8394 */
8395 clientId: string;
8396 /**
8397 * The size the client draws into, in character cells, and whether its
8398 * layout docks a pane, when it said.
8399 */
8400 viewport?: RenderViewport;
8401 };
8402
8403 /**
8404 * What a `session.attach` hook returns and what `next(e)` resolves to:
8405 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
8406 */
8407 export type SessionAttachResult = {
8408 clientId: string;
8409 };
8410
8411 /**
8412 * What `$.session.authorize()` answers: an opaque handle for the session's
8413 * Anthropic credential and its kind, or null when there is none to hold.
8414 *
8415 * The secret itself stays with the engine; the handle is its plugin-side
8416 * face, spent through `$.http.fetch(url, { auth: handle })`.
8417 */
8418 export type SessionAuthorization = {
8419 handle: string;
8420 kind: 'bearer' | 'api-key';
8421 } | null;
8422
8423 /**
8424 * `session.compact`'s input as a plugin's `$.session.compact(args)` takes
8425 * it: `trigger` (`plugin`), `messages` and `agentId` are the engine's.
8426 */
8427 export type SessionCompactArgs = {
8428 /**
8429 * What the summary should keep or stress, as typed after `/compact`;
8430 * absent, the engine's own compaction prompt alone.
8431 */
8432 instructions?: string;
8433 };
8434
8435 /**
8436 * A compaction that stands: the conversation as it reads afterwards, and
8437 * the token counts the engine recorded when it was the one compacting.
8438 */
8439 export type SessionCompacted = {
8440 /**
8441 * The conversation after the compaction, oldest first: from core, its
8442 * summary and the messages it kept; from a hook, whatever it hands up.
8443 *
8444 * What the transcript becomes (kept, on `precompute`, for the compaction
8445 * that comes). A message with the engine's `handle` stands as the engine
8446 * has it; one without is built from its `role`, `text` and tool blocks.
8447 */
8448 messages: readonly SessionMessage[];
8449 /**
8450 * The conversation's size before, in tokens; absent when core did not
8451 * record it.
8452 */
8453 tokensBefore?: number;
8454 /**
8455 * Its size afterwards, in tokens; absent on `precompute` and when core
8456 * did not record it.
8457 */
8458 tokensAfter?: number;
8459 skip?: undefined;
8460 };
8461
8462 /**
8463 * The input of `session.compact`: one compaction of the conversation, about
8464 * to run; `messages` is the transcript it runs over.
8465 */
8466 export type SessionCompactInput = {
8467 /**
8468 * What is compacting (SessionCompactTrigger); the key a matcher narrows
8469 * on. Pinned: `next(e)` passes it on as received.
8470 */
8471 trigger: SessionCompactTrigger;
8472 /**
8473 * The id of the loop compacting, for a subagent's or a fork's own
8474 * transcript; absent for the main conversation (tool.call's `agentId`).
8475 *
8476 * Pinned: left out of a rewrite it is put back, changed it fails the hook.
8477 * `$.session.messages()` is the main conversation whatever this names.
8478 */
8479 agentId?: string;
8480 /**
8481 * What the summary should keep or stress: the text after `/compact`, a
8482 * plugin's, or absent.
8483 *
8484 * `next({ ...e, instructions })` changes what the summarizer is told.
8485 */
8486 instructions?: string;
8487 /**
8488 * The transcript being compacted, in `$.session.messages()`'s shape, each
8489 * message carrying the engine's `handle`; a subagent's own under `agentId`.
8490 *
8491 * `next({ ...e, messages })` changes what is summarized: a message kept
8492 * with its handle is the engine's own, whole; one without is read as built.
8493 */
8494 messages: readonly SessionMessage[];
8495 };
8496
8497 /**
8498 * What a `session.compact` hook returns and what `next(e)` resolves to: the
8499 * compaction (`{ messages, tokensBefore?, tokensAfter? }`) or `{ skip }`.
8500 *
8501 * There is no summary string: the summary is a message.
8502 */
8503 export type SessionCompactResult = SessionCompacted | SessionCompactSkipped;
8504
8505 /**
8506 * A compaction vetoed: on `precompute` nothing is computed or kept; on any
8507 * other trigger the conversation stays as it is and one line says why.
8508 *
8509 * Core answers it too, when a classic PreCompact hook blocks.
8510 */
8511 export type SessionCompactSkipped = {
8512 /**
8513 * Why, as the notice reads.
8514 */
8515 skip: string;
8516 messages?: undefined;
8517 };
8518
8519 /**
8520 * Who compacts: the person's `/compact` (`manual`), the engine at its
8521 * threshold or on a prompt too long (`auto`), a plugin, or a `precompute`.
8522 *
8523 * `precompute` is the one dispatch that installs nothing: its result is kept
8524 * for the compaction that comes, if the conversation it ran over still leads.
8525 */
8526 export type SessionCompactTrigger = 'manual' | 'auto' | 'plugin' | 'precompute';
8527
8528 /**
8529 * The context window broken down as /context breaks it down: the rows, the
8530 * grid and the lists beneath it, in the SDK's `get_context_usage` shape.
8531 *
8532 * Less that reply's internal-build sections. Token counts are the engine's
8533 * estimates as numbers, never formatted: a `full` breakdown counts with the
8534 * token-count API where it can, a `summary` one estimates throughout.
8535 */
8536 export type SessionContextBreakdown = {
8537 /**
8538 * One row per category, the free space and the compaction buffer among
8539 * them; `kind` says which is which.
8540 */
8541 categories: ContextCategory[];
8542 /**
8543 * Tokens in use, unclamped: past `rawMaxTokens` when over the window.
8544 */
8545 totalTokens: number;
8546 /**
8547 * The window measured against, the same figure as `rawMaxTokens`.
8548 */
8549 maxTokens: number;
8550 /**
8551 * The window measured against, in tokens: the model's limit, or a smaller
8552 * compaction window (`autocompactSource` says which).
8553 */
8554 rawMaxTokens: number;
8555 /**
8556 * How that window was settled (ContextWindowSource); the SDK's reply
8557 * carries it under this name too, outside its typed schema.
8558 */
8559 autocompactSource: ContextWindowSource;
8560 /**
8561 * `totalTokens` over `rawMaxTokens` as a whole percentage, 0 to 100 and
8562 * past it when over.
8563 */
8564 percentage: number;
8565 /**
8566 * The grid, row by row: 10 by 10, 20 by 10 for a window of a million or
8567 * more, 5 wide when asked for under 80 `columns`.
8568 */
8569 gridRows: ContextGridSquare[][];
8570 /**
8571 * Which model the breakdown was computed for, as `/model` shows it.
8572 */
8573 model: string;
8574 /**
8575 * Each memory file in the context, with its path and tokens.
8576 */
8577 memoryFiles: ContextMemoryFile[];
8578 /**
8579 * Each MCP tool's schema, with its server and tokens.
8580 */
8581 mcpTools: ContextMcpTool[];
8582 /**
8583 * The custom agents the Agent tool describes, each with its tokens.
8584 */
8585 agents: ContextAgent[];
8586 /**
8587 * The slash-command listing, counted; absent when the session lists none.
8588 */
8589 slashCommands?: ContextSlashCommands;
8590 /**
8591 * The skill listing, counted, with one entry per skill; absent when the
8592 * session lists none.
8593 */
8594 skills?: ContextSkills;
8595 /**
8596 * The token count at which auto-compaction runs; absent when it is off.
8597 */
8598 autoCompactThreshold?: number;
8599 /**
8600 * Whether auto-compaction is on for the session.
8601 */
8602 isAutoCompactEnabled: boolean;
8603 /**
8604 * The last response's own token counts, or null before one came back.
8605 */
8606 apiUsage: ContextApiUsage | null;
8607 };
8608
8609 /**
8610 * The live context window as the status line reads it, and by category as
8611 * /context breaks it down when the call asked (`{ breakdown }`).
8612 *
8613 * `tokens` and `percent` are the last API response's input side against the
8614 * model's window, absent until the first response of the live window: a
8615 * fresh session, or one just compacted, until its next response.
8616 */
8617 export type SessionContextUsage = {
8618 /**
8619 * Input tokens the last response was answered over: uncached, cache-written
8620 * and cache-read together (the status line's `total_input_tokens`).
8621 */
8622 tokens?: number;
8623 /**
8624 * The context window of the session's model, in tokens (the status line's
8625 * `context_window_size`).
8626 */
8627 window: number;
8628 /**
8629 * `tokens` over `window` as a whole percentage, 0 to 100 (the status
8630 * line's `used_percentage`).
8631 */
8632 percent?: number;
8633 /**
8634 * The window by category, as /context breaks it down: present only when
8635 * the call passed `breakdown`, and only with a session bound.
8636 *
8637 * It measures against the compaction window (`rawMaxTokens`), which may be
8638 * smaller than `window`, and estimates every category, so its
8639 * `totalTokens` need not equal `tokens`.
8640 */
8641 breakdown?: SessionContextBreakdown;
8642 };
8643
8644 /**
8645 * What the session has cost, as `/cost` and the status line total it.
8646 */
8647 export type SessionCost = {
8648 /**
8649 * US dollars, summed over every priced API response this session.
8650 */
8651 usd: number;
8652 };
8653
8654 type SessionCronSummary = {
8655 id: string;
8656 /**
8657 * Cron expression, e.g. "0 9 * * 1-5".
8658 */
8659 schedule: string;
8660 /**
8661 * False for one-shot wakeups whose cron field encodes a single fire time; true for tasks that re-fire on every match.
8662 */
8663 recurring: boolean;
8664 /**
8665 * Prompt text submitted when the cron fires. Capped at 1000 chars; clipped values append an in-string "... [+N chars]" marker.
8666 */
8667 prompt: string;
8668 };
8669
8670 /**
8671 * The input of `session.detach`: a client left the session's roster. Every
8672 * field is the engine's: a hook observes, and `next(e)` passes them on.
8673 */
8674 export type SessionDetachInput = {
8675 /**
8676 * Where the client drew.
8677 */
8678 surface: RenderSurface;
8679 /**
8680 * The id it attached under.
8681 */
8682 clientId: string;
8683 /**
8684 * Why it left: it detached, or the session ended under it.
8685 */
8686 reason: SessionDetachReason;
8687 };
8688
8689 /**
8690 * Why a client left the roster: `detach`, it said so (ui_detach); `end`, the
8691 * session ended with it still attached.
8692 */
8693 export type SessionDetachReason = 'detach' | 'end';
8694
8695 /**
8696 * What a `session.detach` hook returns and what `next(e)` resolves to:
8697 * `{ clientId }`, echoed by core; a hook's own value changes nothing.
8698 */
8699 export type SessionDetachResult = {
8700 clientId: string;
8701 };
8702
8703 type SessionEndHookInput = BaseHookInput & {
8704 hook_event_name: 'SessionEnd';
8705 reason: ExitReason;
8706 };
8707
8708 /**
8709 * The input of `session.end`: the session is ending, why, and how to come back
8710 * to it.
8711 *
8712 * Every field is the engine's: a hook observes, and `next(e)` passes them on.
8713 */
8714 export type SessionEndInput = {
8715 /**
8716 * Why it ends (SessionEndReason), the word the classic SessionEnd hook
8717 * receives as its `reason`.
8718 */
8719 reason: SessionEndReason;
8720 /**
8721 * The ending session's id (`$.session.id()` until now); after a `/clear`
8722 * or a resume the process goes on under another.
8723 */
8724 sessionId: string;
8725 /**
8726 * What `claude --resume` takes to return to it.
8727 */
8728 resume: SessionResume;
8729 };
8730
8731 /**
8732 * Why the session ended: the classic SessionEnd hook's own `reason`, word for
8733 * word.
8734 *
8735 * `prompt_input_exit`, the person left (/exit, ctrl+c, ctrl+d); `clear`, a
8736 * /clear started a fresh one; `resume`, another took its place; `logout`;
8737 * `other`, a `-p` run finished or the process got SIGINT, SIGTERM or SIGHUP.
8738 */
8739 export type SessionEndReason = ClassicHookInputs['SessionEnd']['reason'];
8740
8741 /**
8742 * What a `session.end` hook returns and what `next(e)` resolves to:
8743 * `{ sessionId }`, echoed by core; a hook's own value changes nothing.
8744 */
8745 export type SessionEndResult = {
8746 sessionId: string;
8747 };
8748
8749 /**
8750 * The input of `session.measure`: what `$.session.usage()` answers at this
8751 * moment, and which of its units moved since the last measurement a hook saw.
8752 *
8753 * The same figures the op reads, without `context.breakdown`: call
8754 * `$.session.usage({ breakdown })` from the hook when the categories matter.
8755 * Every field is the engine's: a hook observes, and `next(e)` passes them on.
8756 */
8757 export type SessionMeasureInput = {
8758 /**
8759 * The live context window (`$.session.usage()`'s `context`): the window,
8760 * and its fill once a response of the live window reported one.
8761 *
8762 * Never carries `breakdown` here.
8763 */
8764 context: SessionContextUsage;
8765 /**
8766 * The rate-limit windows the last response reported, each with its
8767 * `percentUsed`; empty off a subscription or before the first reading.
8768 */
8769 rateLimits: SessionRateLimit[];
8770 /**
8771 * What the session has cost so far; absent where the host keeps no ledger.
8772 */
8773 cost?: SessionCost;
8774 /**
8775 * Which units differ from the last measurement raised (UsageUnit), never
8776 * empty; the first measurement names every unit it has a figure for.
8777 *
8778 * `context`: the fill moved; `rateLimits`: a window moved a whole point,
8779 * appeared or left, or the account's limit status changed; `cost`: the
8780 * total grew.
8781 */
8782 changed: UsageUnit[];
8783 };
8784
8785 /**
8786 * What a `session.measure` hook returns and what `next(e)` resolves to:
8787 * `{ changed }`, echoed by core; a hook's own value changes nothing.
8788 */
8789 export type SessionMeasureResult = {
8790 changed: UsageUnit[];
8791 };
8792
8793 /**
8794 * One message of the transcript as `$.session.messages()` returns it.
8795 */
8796 export type SessionMessage = {
8797 /**
8798 * Who wrote it.
8799 */
8800 role: 'user' | 'assistant';
8801 /**
8802 * Its text blocks joined; '' when it has none.
8803 */
8804 text: string;
8805 /**
8806 * The tool_use blocks of an assistant message, each with its outcome
8807 * (`result`, `text`, `isError`) once the transcript holds it.
8808 */
8809 toolUses: ToolUseSummary[];
8810 /**
8811 * The tool_result blocks of a user message: `{ tool_use_id, text, isError,
8812 * result }`.
8813 */
8814 toolResults?: ToolResultSummary[];
8815 /**
8816 * An opaque token the engine stamps on a message it hands a
8817 * `session.compact` hook, so a list handed back maps to its own messages.
8818 *
8819 * Absent on `$.session.messages()` and on a message a hook built.
8820 */
8821 handle?: string;
8822 };
8823
8824 /**
8825 * One rate-limit window as the rate-limit notices read it.
8826 */
8827 export type SessionRateLimit = {
8828 /**
8829 * Which window: `five_hour`, `seven_day`, or a Claude gateway's
8830 * `spend_limit`.
8831 */
8832 kind: string;
8833 /**
8834 * How much of the window is used, 0 to 100 with at most one decimal:
8835 * 23.5, or 7, never 7.000000000000001; past 100 on an exceeded spend limit.
8836 */
8837 percentUsed: number;
8838 /**
8839 * When the window resets, as an ISO 8601 timestamp.
8840 */
8841 resetsAt?: string;
8842 };
8843
8844 /**
8845 * An external-event wake the delivery's text parsed as (a GitHub relay
8846 * event, a signal's notice): the envelope's attributes and its JSON body.
8847 */
8848 export type SessionReceiveEvent = {
8849 /**
8850 * The producing service (`github`).
8851 */
8852 source: string;
8853 /**
8854 * The event's discriminator (`pull_request.closed`, `check_suite`).
8855 */
8856 kind: string;
8857 /**
8858 * The envelope's JSON body (`{ pr: "acme/app#12", outcome: "merged" }`).
8859 */
8860 data: Record<string, unknown>;
8861 /**
8862 * The `data` keys whose values are free text a third party wrote (a
8863 * commenter's `author` and `comment`), as the producer marked them.
8864 *
8865 * Empty when none; the server asserts every other key's value, not these.
8866 */
8867 untrustedKeys: readonly string[];
8868 };
8869
8870 /**
8871 * The input of `session.receive`: one inbound delivery (a relay's event, a
8872 * peer's message, a Remote Control prompt), sanitized, before it is queued.
8873 */
8874 export type SessionReceiveInput = {
8875 /**
8876 * Where the delivery came from, as the bridge classified it; the key a
8877 * matcher narrows on. `next(e)` passes it on as received.
8878 */
8879 origin: SessionReceiveOrigin;
8880 /**
8881 * The delivery's body as the model would read it (a content-block
8882 * delivery's text blocks, joined).
8883 */
8884 text: string;
8885 /**
8886 * The external-event wake the text parsed as (`source` `github` for a
8887 * subscribed pull request's event); passed on as received.
8888 *
8889 * Present only for a delivery the server itself rendered as a wake (a
8890 * webhook relay, the session inbox), by its asserted origin; anyone else's
8891 * wake-shaped text stays `text`. Its `untrustedKeys` name third-party text.
8892 */
8893 event?: SessionReceiveEvent;
8894 };
8895
8896 /**
8897 * Where an inbound delivery came from, as the bridge classified it from the
8898 * server's stamps: `prompt.submit`'s `e.origin`, less what never arrives.
8899 */
8900 export type SessionReceiveOrigin = {
8901 /**
8902 * `bridge` the user's own from a Remote Control client; `peer` another
8903 * session; `unclassified` one the bridge could not place.
8904 *
8905 * `task-notification` a relay's event (a GitHub webhook) or a trigger;
8906 * `scheduled-trigger` a routine; `peer-send-message` another session's
8907 * SendMessage; `projects-relay` and `slack-ping` as at `prompt.submit`.
8908 */
8909 kind: 'bridge' | 'task-notification' | 'scheduled-trigger' | 'peer' | 'peer-send-message' | 'projects-relay' | 'slack-ping' | 'unclassified';
8910 };
8911
8912 /**
8913 * What a `session.receive` hook returns and what `next(e)` resolves to: the
8914 * delivery that was queued, `{ text }`, or `{ consumed: reason }`.
8915 *
8916 * `next(e)` resolves once the delivery is queued; a hook answering without
8917 * `next` queues nothing.
8918 */
8919 export type SessionReceiveResult = {
8920 /**
8921 * The body the delivery was queued with; from core, `e.text` as it
8922 * arrived at the bottom.
8923 *
8924 * A rewrite passes it down, `next({ ...e, text })`.
8925 */
8926 text: string;
8927 consumed?: undefined;
8928 } | {
8929 /**
8930 * Takes the delivery, answered without `next`: it is not queued, not
8931 * written to the transcript and never reaches the model.
8932 *
8933 * The reason is logged, the plugin named.
8934 */
8935 consumed: string;
8936 text?: undefined;
8937 };
8938
8939 /**
8940 * What `$.session.repo()` answers: the repository's root and its origin remote,
8941 * when the session is in one.
8942 */
8943 export type SessionRepo = {
8944 /**
8945 * The repository's root, absolute: the main working tree's for a worktree.
8946 */
8947 root: string;
8948 /**
8949 * The `origin` remote's URL as git has it (push URL preferred), or null when
8950 * the repository has none.
8951 */
8952 remote: string | null;
8953 /**
8954 * Whether the remote is one of the repositories this build treats as its
8955 * own; false in a build that has none or when the remote is unrecognized.
8956 *
8957 * The engine matches the build's own list of repositories with its
8958 * hardened remote parser. A plugin reads this to behave differently in a
8959 * public repository; which repositories are the build's is its to say.
8960 */
8961 internal: boolean;
8962 /**
8963 * The repository the allowlist matched, as `owner/name`; null when
8964 * `internal` is false.
8965 *
8966 * A working copy without a remote that the engine still recognises is
8967 * named by its own checkout configuration; a remote's name is its path.
8968 */
8969 name: string | null;
8970 };
8971
8972 /**
8973 * How to come back to the session that ended: what `claude --resume` takes.
8974 */
8975 export type SessionResume = {
8976 /**
8977 * What `claude --resume <id>` takes, the ending session's own.
8978 *
8979 * It resumes a session that wrote a transcript: one that never ran a
8980 * prompt, or ran with persistence off, left nothing under this id.
8981 */
8982 id: string;
8983 };
8984
8985 type SessionStartHookInput = BaseHookInput & {
8986 hook_event_name: 'SessionStart';
8987 source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork';
8988 agent_type?: string;
8989 model?: string;
8990 session_title?: string;
8991 /**
8992 * resume/fork: seconds since the resumed transcript's last assistant response
8993 */
8994 seconds_since_last_response?: number;
8995 /**
8996 * 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)
8997 */
8998 context_tokens?: number;
8999 /**
9000 * resume/fork: seconds_since_last_response exceeds the prompt-cache TTL, so the first request re-caches context_tokens
9001 */
9002 prompt_cache_likely_expired?: boolean;
9003 /**
9004 * resume/fork: estimated cost of re-caching context_tokens on the session model - the managed modelPricing when set, otherwise list price; excludes the response
9005 */
9006 estimated_cache_write_usd?: number;
9007 };
9008
9009 /**
9010 * The input of `session.start`: the session the process starts with, read the
9011 * way `$.session` reads it at that moment.
9012 */
9013 export type SessionStartInput = {
9014 /**
9015 * The directory the session runs in, absolute (`$.session.cwd()`).
9016 */
9017 cwd: string;
9018 /**
9019 * Where the session draws at start (`$.session.surfaces()[0]`): `terminal`
9020 * under the REPL; null for a `-p` run or the SDK, which draw nowhere yet.
9021 */
9022 surface: RenderSurface | null;
9023 /**
9024 * Whether a person is at the prompt: true under the REPL, false for a `-p`
9025 * run or the SDK.
9026 */
9027 isInteractive: boolean;
9028 };
9029
9030 /**
9031 * What a `session.start` hook returns and what `next(e)` resolves to:
9032 * `{ cwd }`, echoed by core; a hook's own value does not change the session.
9033 */
9034 export type SessionStartResult = {
9035 cwd: string;
9036 };
9037
9038 /**
9039 * What `$.session.usage()` answers: the context window's fill, the account's
9040 * rate-limit windows and the session's cost, as the status line has them.
9041 *
9042 * A figure the engine does not have is left out, never zeroed: `rateLimits`
9043 * is empty off a subscription, `cost` absent where the host keeps no ledger.
9044 */
9045 export type SessionUsage = {
9046 /**
9047 * The live context window: the status line's `context_window` figures.
9048 */
9049 context: SessionContextUsage;
9050 /**
9051 * The rate-limit windows the last API response reported (`five_hour`,
9052 * `seven_day`, a gateway's `spend_limit`); empty when none has a reading.
9053 */
9054 rateLimits: SessionRateLimit[];
9055 /**
9056 * What the session has cost so far, as /cost totals it; absent only where
9057 * the host keeps no cost ledger (the CLI always has one).
9058 */
9059 cost?: SessionCost;
9060 };
9061
9062 /**
9063 * What `$.session.usage(args)` takes: nothing for the status line's figures
9064 * alone; `breakdown` to have the window broken down as /context breaks it.
9065 */
9066 export type SessionUsageArgs = {
9067 /**
9068 * Asks for `context.breakdown` and says how it is counted
9069 * (ContextBreakdownDetail); absent, none is computed and the call is free.
9070 *
9071 * `full` sends one token-count request per tool and memory file, as
9072 * /context does; `summary` estimates locally and sends none.
9073 */
9074 breakdown?: ContextBreakdownDetail;
9075 /**
9076 * The width the breakdown's grid will be drawn in, in terminal columns;
9077 * absent, the full-width grid. Read only with `breakdown`.
9078 *
9079 * Under 80 the grid is the narrow one /context draws there, 5 wide. A thin
9080 * client's breakdown is the remote workspace's, whose grid ignores this.
9081 */
9082 columns?: number;
9083 };
9084
9085 /**
9086 * What `$.settings.read` answers: an object keyed as a settings.json is
9087 * (`permissions`, `env`, `hooks`, `model`, `enabledPlugins`, ...).
9088 *
9089 * Each key is as https://code.claude.com/docs/en/settings documents it and
9090 * https://json.schemastore.org/claude-code-settings.json types it. A
9091 * snapshot in plain data: a write to it changes nothing the engine reads.
9092 */
9093 export type Settings = Readonly<Record<string, unknown>>;
9094
9095 /**
9096 * What `$.settings.read(args)` takes.
9097 */
9098 export type SettingsReadArgs = {
9099 /**
9100 * The one source read, as loaded; absent, the settings merged over every
9101 * source, as the engine runs under them.
9102 */
9103 source?: SettingsSource;
9104 };
9105
9106 /**
9107 * One source of settings by the name a plugin gives it, lowest precedence
9108 * first; the engine's own name is the same word with `Settings` appended.
9109 *
9110 * `user` is ~/.claude/settings.json, `project` .claude/settings.json,
9111 * `local` .claude/settings.local.json, `flag` what `--settings` and the
9112 * SDK's inline settings carry, and `policy` the managed settings, every
9113 * managed tier merged.
9114 */
9115 export type SettingsSource = 'user' | 'project' | 'local' | 'flag' | 'policy';
9116
9117 type SetupHookInput = BaseHookInput & {
9118 hook_event_name: 'Setup';
9119 trigger: 'init' | 'maintenance';
9120 };
9121
9122 /**
9123 * Where a site's window sits over the tree a hook drew in it (a pane's body,
9124 * the band): the engine's to move (the person scrolls), the plugin's to read.
9125 */
9126 export type SiteScroll = {
9127 /**
9128 * The first row of the tree the window shows; 0 at the top. Read-only.
9129 */
9130 offset: number;
9131 /**
9132 * How many rows of the tree the window shows at once: the rows the
9133 * surface gave the body. Read-only.
9134 */
9135 bodyRows: number;
9136 };
9137
9138 /**
9139 * Which transcript the person has on screen where a site draws: the main
9140 * conversation's, or one agent's, opened from the tasks list.
9141 *
9142 * The person's to switch, the plugin's to read: a switch re-runs the site's
9143 * hooks with the new view, the site itself staying where it is.
9144 */
9145 export type SiteView = {
9146 /**
9147 * The agent whose transcript is in view: the `id` `$.agent.list()` gives
9148 * it, the `agentId` its `turn.step` and `tool.call` events carry.
9149 *
9150 * Absent while the main conversation is in view. Read-only.
9151 */
9152 agentId?: string;
9153 };
9154
9155 /**
9156 * The input of `skill.prompt`: one skill's prompt, at the moment the engine
9157 * expanded it for the model.
9158 *
9159 * Typed as `/name`, called through the Skill tool, or preloaded into a
9160 * subagent: the same event at each.
9161 */
9162 export type SkillPromptInput = {
9163 /**
9164 * Which skill (`commit`); the key a matcher narrows on.
9165 */
9166 skill: string;
9167 /**
9168 * The prompt's text as the skill computed it (its text blocks, joined).
9169 */
9170 text: string;
9171 };
9172
9173 /**
9174 * What a `skill.prompt` hook returns: the text the model reads for that
9175 * skill.
9176 */
9177 export type SkillPromptResult = {
9178 text: string;
9179 };
9180
9181 /**
9182 * Options of `$.clock.sleep`.
9183 */
9184 export type SleepOptions = {
9185 /**
9186 * Aborting it rejects the sleep at once.
9187 */
9188 signal?: AbortSignal;
9189 };
9190
9191 /**
9192 * Options of `$.audio.speak`.
9193 */
9194 export type SpeakOptions = {
9195 /**
9196 * The system voice's exact name as the platform lists it (`Samantha`, or the
9197 * name of a voice you installed). Absent: the synthesizer's default voice.
9198 */
9199 voice?: string;
9200 };
9201
9202 /**
9203 * The argument of `$.audio.speak(text, options)` as the event carries it.
9204 */
9205 type SpeakRequest = SpeakOptions & {
9206 /**
9207 * What to say, as plain text, of at most 4096 characters.
9208 */
9209 text: string;
9210 };
9211
9212 /**
9213 * What `$.audio.speak` resolves with once the utterance has ended.
9214 */
9215 export type SpeakResult = {
9216 /**
9217 * Which synthesizer spoke: `system`, the platform's own (`say` on macOS).
9218 */
9219 via: 'system';
9220 };
9221
9222 /**
9223 * `next` in a `*` hook: the set of events is open at runtime, so `e` is
9224 * `unknown` until `next.is(pattern, e)` narrows it to events it knows.
9225 *
9226 * The callable is an overload per known event (OrderedOverloads), then
9227 * `(e: unknown) => Promise<unknown>` last: `next(e)` with `e` still unknown
9228 * resolves to `unknown`.
9229 */
9230 export type StarNext = OrderedOverloads<EventName> & {
9231 (e: unknown): Promise<unknown>;
9232 /**
9233 * Continues this dispatch at a tier, as Next's `to` (a managed hook's):
9234 * `e` still unknown resolves to `unknown`.
9235 */
9236 readonly to: (e: unknown, tier: TargetTier) => Promise<unknown>;
9237 readonly signal: AbortSignal;
9238 readonly is: <M extends Pattern>(pattern: M, e: unknown) => e is Frozen<Args<Selected<M>>>;
9239 readonly event: EventName;
9240 readonly origin: Origin;
9241 readonly trace: readonly TraceEntry<EventName, unknown, unknown>[];
9242 readonly budget: NextBudget;
9243 };
9244
9245 type StopFailureHookInput = BaseHookInput & {
9246 hook_event_name: 'StopFailure';
9247 error: SDKAssistantMessageError;
9248 error_details?: string;
9249 last_assistant_message?: string;
9250 };
9251
9252 type StopHookInput = BaseHookInput & {
9253 hook_event_name: 'Stop';
9254 stop_hook_active: boolean;
9255 /**
9256 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
9257 */
9258 last_assistant_message?: string;
9259 /**
9260 * 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.
9261 */
9262 background_tasks?: BackgroundTaskSummary[];
9263 /**
9264 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
9265 */
9266 session_crons?: SessionCronSummary[];
9267 };
9268
9269 /**
9270 * The hook a streaming event takes: `async function* ($, e, next) {}`,
9271 * yielding the event's chunks and returning its result.
9272 *
9273 * `return yield* next(e)` passes; `for await (const c of next(e)) yield
9274 * f(c)` transforms; yielding without `next` answers alone. A chunk yielded
9275 * stays: a hook that fails mid-stream is left, the rest from beneath it.
9276 *
9277 * @example on('turn.step', async function* ($, e, next) {
9278 * const r = yield* next(e); return { ...r } })
9279 */
9280 export type StreamHook<N extends StreamingEventName> = ($: EngineInterface, e: Frozen<Args<N>>, next: StreamNext<N>) => StreamHookBody<Chunk<N>, EventResult<N>>;
9281
9282 /**
9283 * What a hook on a streaming event evaluates to: the async generator an
9284 * `async function*` makes, yielding `C` and returning `R` or nothing.
9285 *
9286 * Returning nothing lets its last `next(e)`'s result stand. A plain
9287 * function is a type error here even when it returns `next(e)`: the hook
9288 * is the generator, not a function that hands one back.
9289 */
9290 export type StreamHookBody<C, R> = AsyncGenerator<C, R | void> & {
9291 /**
9292 * Absent on a generator; present on `next(e)`, which is not a hook body.
9293 */
9294 readonly result?: never;
9295 };
9296
9297 /**
9298 * The events that stream: their hooks are async generators, `next(e)` is
9299 * the stream of everything beneath, and the result is what it returns.
9300 *
9301 * `turn.step` alone: the model's response arrives in pieces, and a hook
9302 * that saw it whole could not change what had already been shown.
9303 */
9304 export type StreamingEventName = 'turn.step';
9305
9306 /**
9307 * The rest of the chain as a hook on a streaming event receives it: Next,
9308 * except that `next(e)` is the stream beneath (HookStream), not a promise.
9309 *
9310 * Each call opens a fresh stream; for `turn.step` each is a model request,
9311 * so a hook that calls it twice makes two. Not calling it yields the hook's
9312 * own chunks and returns its own result, and nothing beneath runs.
9313 *
9314 * @template S what `next.is(pattern, e)` narrows `e` to, as Next's
9315 * @see HookBudget `ms`: the hook's budget counts its own code, never a wait
9316 * at a `yield` or on this stream, however long the response beneath takes
9317 */
9318 export type StreamNext<N extends StreamingEventName = StreamingEventName, E = Args<N>, O = NextResult<N>, S extends {
9319 [K in N]?: unknown;
9320 } = {
9321 [K in N]: Args<K>;
9322 }> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin' | 'budget'> & {
9323 (e: E): HookStream<Chunk<N>, O>;
9324 /**
9325 * Continues this dispatch at a tier, as Next's `to`: the stream beneath
9326 * with the links between this hook's tier and that one skipped.
9327 */
9328 readonly to: (e: E, tier: TargetTier) => HookStream<Chunk<N>, O>;
9329 /**
9330 * What settled beneath on the latest `next()` stream, as Next's; a
9331 * streaming link's entry counts the chunks it yielded up (`chunks`).
9332 */
9333 readonly trace: readonly TraceEntry<N, E, O>[];
9334 };
9335
9336 /**
9337 * The shape a `Box` and a `Text` share in a render tree: allowlisted props,
9338 * an optional `hover`, the group stamp a `hover.scope` earns, and children.
9339 *
9340 * `Tag` is which of the two; `Hover` is that element's hover props. Every
9341 * surface draws both: Ink's Box and Text on the terminal, a flex div and a
9342 * styled span on the desktop.
9343 */
9344 type StyledElement<Tag extends 'Box' | 'Text', Hover> = {
9345 type: Tag;
9346 /**
9347 * A Box's layout, position, spacing and border props and the `key` that
9348 * makes it a hover scope; a Text's colors and styles. Others are refused.
9349 */
9350 props?: Record<string, string | number | boolean>;
9351 /**
9352 * Style overrides the surface applies while the pointer is over the
9353 * nearest keyed Box, or over any member of the group `scope` names.
9354 *
9355 * Plain data, no hook. Nothing that moves a sibling: `borderStyle`
9356 * restyles a border the Box has, `display` only reveals a Box drawn
9357 * `"none"` (under a keyed Box or in a scope), an offset moves a placed Box.
9358 */
9359 hover?: Hover;
9360 /**
9361 * Whose group `hover.scope` names; absent without a `scope`.
9362 */
9363 group?: PluginStamp;
9364 /**
9365 * In order: a Box holds elements and strings (core wraps each string in
9366 * a Text); a Text holds strings and inline elements, never an engine node.
9367 */
9368 children?: RenderNode[];
9369 };
9370
9371 type SubagentStartHookInput = BaseHookInput & {
9372 hook_event_name: 'SubagentStart';
9373 agent_id: string;
9374 agent_type: string;
9375 };
9376
9377 type SubagentStopHookInput = BaseHookInput & {
9378 hook_event_name: 'SubagentStop';
9379 stop_hook_active: boolean;
9380 agent_id: string;
9381 agent_transcript_path: string;
9382 agent_type: string;
9383 /**
9384 * Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.
9385 */
9386 last_assistant_message?: string;
9387 /**
9388 * 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.
9389 */
9390 background_tasks?: BackgroundTaskSummary[];
9391 /**
9392 * Session-scoped cron tasks (CronCreate, ScheduleWakeup, /loop) that will wake this session later. Empty array when none are scheduled.
9393 */
9394 session_crons?: SessionCronSummary[];
9395 };
9396
9397 /**
9398 * The props of `Svg`, the remote surfaces' vector leaf: the markup is the
9399 * element's data, as a string is a Text's, drawn isolated.
9400 *
9401 * A leaf: no children. The surface never lets the markup reach the page
9402 * (the engine bounds it; the desktop and the editor draw it as an image, or
9403 * in a sandboxed frame when `isInteractive`; the mobile app in a web view).
9404 */
9405 export type SvgProps = {
9406 /**
9407 * The SVG document, `<svg ...>...</svg>`, at most 131072 characters.
9408 */
9409 source: string;
9410 /**
9411 * What the drawing says, for a reader that cannot see it; required, since
9412 * a surface without the element draws nothing else of it.
9413 */
9414 alt: string;
9415 /**
9416 * CSS pixels; absent, the box takes the markup's own width up to the slot.
9417 */
9418 width?: number;
9419 /**
9420 * CSS pixels; absent, the markup's own height at the drawn width.
9421 */
9422 height?: number;
9423 /**
9424 * `true` draws the SVG in a script-less sandboxed frame so hover, CSS
9425 * `:hover`, SMIL animation and `<title>` tooltips work; absent, an image.
9426 *
9427 * It never enables script or event-handler attributes (the frame has no
9428 * allow-scripts and the scrub strips them); presses that other plugins
9429 * should observe go on an enclosing element.
9430 */
9431 isInteractive?: boolean;
9432 };
9433
9434 /**
9435 * The keys of `I` a matcher may select variants by: literal-valued in every
9436 * variant, and one literal per variant (IsDiscriminant).
9437 */
9438 type TagKeys<I> = {
9439 [K in MatcherKeys<I>]: IsLiteralValued<MatcherValueOf<I, K>> extends true ? IsDiscriminant<I, K> extends true ? K : never : never;
9440 }[MatcherKeys<I>];
9441
9442 /**
9443 * A tier `next.to(e, tier)` may name: one a floor can reach past a tier of
9444 * less authority to, so never `prepend` or `user`, which nothing skips to.
9445 */
9446 export type TargetTier = Exclude<Tier, 'prepend' | 'user'>;
9447
9448 type TaskCompletedHookInput = BaseHookInput & {
9449 hook_event_name: 'TaskCompleted';
9450 task_id: string;
9451 task_subject: string;
9452 task_description?: string;
9453 teammate_name?: string;
9454 /**
9455 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9456 */
9457 team_name?: string;
9458 };
9459
9460 type TaskCreatedHookInput = BaseHookInput & {
9461 hook_event_name: 'TaskCreated';
9462 task_id: string;
9463 task_subject: string;
9464 task_description?: string;
9465 teammate_name?: string;
9466 /**
9467 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9468 */
9469 team_name?: string;
9470 };
9471
9472 type TeammateIdleHookInput = BaseHookInput & {
9473 hook_event_name: 'TeammateIdle';
9474 teammate_name: string;
9475 /**
9476 * @deprecated Sessions have a single implicit team; this carries the session-derived team name and will be removed in a future release.
9477 */
9478 team_name: string;
9479 };
9480
9481 /**
9482 * The `Text` props a `hover` may override (its colors and styles, not its
9483 * wrapping) and `scope`, the hover group it joins; a `Button`'s label too.
9484 */
9485 export type TextHoverProps = {
9486 /**
9487 * Names a hover group of this plugin's: every element it draws with the
9488 * same `scope`, in any site on the surface, lights while any is hovered.
9489 *
9490 * Another plugin's elements under the same string are a different group.
9491 * One to 64 characters, no control characters; no keyed Box needed. On the
9492 * terminal a Text nested in a Text follows its group but cannot heat it.
9493 */
9494 scope?: string;
9495 color?: string;
9496 backgroundColor?: string;
9497 dimColor?: boolean;
9498 bold?: boolean;
9499 italic?: boolean;
9500 underline?: boolean;
9501 strikethrough?: boolean;
9502 inverse?: boolean;
9503 };
9504
9505 /**
9506 * The props of `Text`: the color and style props of Ink's Text a tree may
9507 * set. Colors are a theme key or a raw color.
9508 */
9509 export type TextProps = {
9510 /**
9511 * Style overrides applied by the surface while the pointer is over the
9512 * nearest enclosing keyed `Box`, or, given a `scope`, over its group.
9513 *
9514 * No hook runs and nothing crosses to the plugin. Refused outside a keyed
9515 * Box unless it names a `scope`.
9516 */
9517 hover?: TextHoverProps;
9518 color?: string;
9519 backgroundColor?: string;
9520 dimColor?: boolean;
9521 bold?: boolean;
9522 italic?: boolean;
9523 underline?: boolean;
9524 strikethrough?: boolean;
9525 inverse?: boolean;
9526 wrap?: 'wrap' | 'end' | 'middle' | 'truncate' | 'truncate-start' | 'truncate-middle' | 'truncate-end';
9527 };
9528
9529 /**
9530 * One of the chain's five tiers (TIERS), outermost first; on every
9531 * `next.trace` entry, and what `next.to(e, tier)` names.
9532 *
9533 * `prepend` and `append` are the managed plugins an administrator lists,
9534 * `user` everything a person installs, `builtin` the plugins bundled in the
9535 * binary, `core` the engine's innermost link.
9536 */
9537 export type Tier = (typeof TIERS)[number];
9538
9539 /**
9540 * The chain's five tiers, outermost first: earlier is outer is more
9541 * authority, and same-event hooks nest in this order and no other way.
9542 *
9543 * The managed plugins an administrator prepends, everything a person
9544 * installs, the managed plugins appended, the plugins bundled in the binary,
9545 * the engine's innermost link; a built-in's `$` calls still raise everywhere.
9546 */
9547 const TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
9548
9549 /**
9550 * A pending timer from `$.clock.after` / `$.clock.every`.
9551 */
9552 export type Timer = {
9553 /**
9554 * Stops it; a stopped timer never fires again.
9555 */
9556 cancel: () => void;
9557 };
9558
9559 /**
9560 * A timer on `$.clock` (`after`, `every`): `fn` runs after `ms` milliseconds,
9561 * once or until `cancel()`.
9562 */
9563 export type TimerCall = (ms: number, fn: () => void) => Timer;
9564
9565 /**
9566 * Options of `$.ui.toast`.
9567 */
9568 export type ToastOptions = {
9569 /**
9570 * How long the line stays, in milliseconds; default 4000.
9571 */
9572 timeoutMs?: number;
9573 };
9574
9575 /**
9576 * `tool.call`'s input as the call takes it: `tool_use_id` and `agentId` may
9577 * ride along (a hook passing its event's input on) and are dropped.
9578 *
9579 * The run gets its own id and runs in the session's loop.
9580 */
9581 export type ToolCallArgs = ToolCallEnvelope extends infer I ? I extends ToolCallEnvelope ? Omit<I, 'tool_use_id'> & ToolCallReserved<I['tool']> : never : never;
9582
9583 /**
9584 * The envelope the two tool events share: the tool, the id of this call, and
9585 * the tool's arguments spread beside them (`e.command` for Bash).
9586 *
9587 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
9588 * is a string and a rewrite is checked against Bash's schema. The `e` of
9589 * `classic.PreToolUse` exactly; `tool.call`'s adds the loop (ToolCallInput).
9590 */
9591 export type ToolCallEnvelope = BuiltinToolCallInput | McpToolCallInput;
9592
9593 /**
9594 * The input of `tool.call`: the tool, the id of this call, the tool's
9595 * arguments beside them (`e.command` for Bash), and `agentId` in a subagent.
9596 *
9597 * A union discriminated by `tool`: after `if (e.tool === "Bash")`, `e.command`
9598 * is a string and a rewrite is checked against Bash's schema. `tool`,
9599 * `tool_use_id` and `agentId` are reserved: a rewrite of any is refused.
9600 */
9601 export type ToolCallInput = ToolCallEnvelope & AgentLoop;
9602
9603 /**
9604 * `$.tool.call(input)`: resolves with `result` typed for the tool `input`
9605 * names (ToolCallResult), or loosely for an input that names none literally.
9606 */
9607 type ToolCallOverloads = {
9608 <T extends string>(input: ToolCallArgs & ToolNamed<T>): Promise<ToolCallResult<T>>;
9609 (input: ToolCallArgs): Promise<ToolCallResult>;
9610 };
9611
9612 /**
9613 * The keys `tool.call`'s input carries beside the tool's own arguments, none
9614 * of which the tool sees (the engine strips them before the tool runs).
9615 *
9616 * `consent` is the person's own words for the press that raised the call
9617 * (`The user pressed "1: Yes" on ...`): the run's context carries it as a human
9618 * turn, which the permission path reads as the user's request.
9619 */
9620 export type ToolCallReserved<T> = {
9621 tool: T;
9622 tool_use_id?: string;
9623 consent?: string;
9624 };
9625
9626 /**
9627 * What a `tool.call` hook returns and what `next(e)` and `$.tool.call(input)`
9628 * resolve to: the tool's result (`{ result, context? }`) or `{ deny }`.
9629 *
9630 * From core the result is `{ ref, result, text }` or, when the tool reported
9631 * an error, `{ ref, result, text, isError }`; `ref` names core's messages.
9632 *
9633 * @template Name the tool the call went to, typing `result` per built-in
9634 * tool (BuiltinToolResults) once `e.tool` is narrowed; else `unknown`
9635 */
9636 export type ToolCallResult<Name extends string = string> = {
9637 /**
9638 * Refuses the call: the model receives the text as an error result.
9639 * Absent when the call was answered.
9640 */
9641 deny: string;
9642 result?: undefined;
9643 context?: undefined;
9644 ref?: undefined;
9645 text?: undefined;
9646 isError?: undefined;
9647 } | {
9648 /**
9649 * The tool's output: from core the tool's record, typed per built-in
9650 * tool once `e.tool` and `isError` are narrowed; from a hook, its own.
9651 *
9652 * Core validates a hook's answer against the tool's output schema when
9653 * it has one, maps it for the model with the tool's own mapper, and
9654 * records it in the transcript as the tool's result. Absent on a deny.
9655 */
9656 result: ToolResultOf<Name>;
9657 /**
9658 * What the model reads after the tool's result and the user never
9659 * sees. From core, none.
9660 *
9661 * One reminder, as a PostToolUse hook's is, after the managed tier's
9662 * review; none on a plugin's own `$.tool.call`. Kept whole from `next`,
9663 * none empty, any length: past 100,000 (200,000 together) head + path.
9664 */
9665 context?: readonly string[];
9666 /**
9667 * Set by core on what `next(e)` resolves to: names the messages core
9668 * produced for the call (they stay on the host side).
9669 *
9670 * A hook that returns the object it got makes core use them verbatim.
9671 * Absent on a hook's own `{ result }` and on a deny.
9672 */
9673 ref?: number;
9674 /**
9675 * Set by core: the result as the model reads it (text blocks joined),
9676 * present whatever the tool, where `result`'s shape varies per tool.
9677 *
9678 * Absent on a hook's own `{ result }`.
9679 */
9680 text?: string;
9681 isError?: undefined;
9682 deny?: undefined;
9683 } | {
9684 /**
9685 * Set by core, present only when the tool reported an error (it threw,
9686 * was interrupted, or answered an error): `text` is what the model read.
9687 */
9688 isError: true;
9689 /**
9690 * What the transcript stored for the errored call: the error text, or
9691 * undefined when nothing was stored; never the tool's typed record.
9692 */
9693 result: unknown;
9694 /**
9695 * The error as the model reads it.
9696 */
9697 text?: string;
9698 /**
9699 * As on an answered result: names the messages core produced.
9700 */
9701 ref?: number;
9702 /**
9703 * As on an answered result.
9704 */
9705 context?: readonly string[];
9706 deny?: undefined;
9707 };
9708
9709 /**
9710 * `tool.check`'s input as `$.tool.check` takes it: the tool and its
9711 * arguments; `tool_use_id` is the engine's to set, never a query's.
9712 */
9713 type ToolCheckArgs = Pick<ToolCheckInput, 'tool' | 'input'>;
9714
9715 /**
9716 * The verdict of `tool.check`: run the tool, put it to the mode's decider
9717 * (the dialog, the auto-mode classifier, a headless host), or refuse it.
9718 */
9719 type ToolCheckDecision = 'allow' | 'ask' | 'deny';
9720
9721 /**
9722 * The input of `tool.check`: the tool, its arguments, and the call's id when
9723 * the engine is deciding a real call.
9724 *
9725 * All three are the question's identity and are pinned: a hook decides
9726 * about this call, it does not change it (`tool.call` rewrites a call).
9727 */
9728 type ToolCheckInput = {
9729 /**
9730 * As the model names it (`Bash`, `mcp__server__tool`); the key a matcher
9731 * narrows on.
9732 */
9733 tool: string;
9734 /**
9735 * The tool's arguments as the permission decision reads them
9736 * (`{ command }` for Bash, `{ file_path, ... }` for the file tools).
9737 */
9738 input: unknown;
9739 /**
9740 * The call being decided, on a real call only; absent on a query.
9741 *
9742 * `next.origin` names who raised it: `{ plugin: 'engine', tier: 'core' }`
9743 * for the model's own call, the plugin for its `$.tool.call` or its query.
9744 */
9745 tool_use_id?: string;
9746 };
9747
9748 /**
9749 * What a `tool.check` hook returns and what `next(e)` resolves to: the
9750 * verdict, why, and the settings rule behind it when one decided.
9751 *
9752 * From core, the engine's declarative decision for the session's mode and
9753 * rules. A hook may answer any verdict in either direction; the last word up
9754 * the chain is the decision.
9755 */
9756 type ToolCheckResult = {
9757 /**
9758 * `allow` runs the tool; `ask` puts it to the mode's decider; `deny`
9759 * refuses it, the reason the model's error.
9760 */
9761 decision: ToolCheckDecision;
9762 /**
9763 * Why, in a sentence: from core the rule or check that decided; from a
9764 * hook, what the model reads on a deny and the dialog shows on an ask.
9765 */
9766 reason?: string;
9767 /**
9768 * The settings rule that decided, as written (`Bash(git push:*)`).
9769 *
9770 * Absent for a mode or a tool's own check.
9771 */
9772 rule?: string;
9773 };
9774
9775 /**
9776 * Where a `tool.describe` answer places the tool: `true` behind ToolSearch
9777 * (its schema loads when the model asks for it), `false` in the prompt's list.
9778 *
9779 * Left out of an answer, the placement beneath stands.
9780 */
9781 export type ToolDeferral = boolean;
9782
9783 /**
9784 * The input of `tool.describe`: one tool's description, at the moment the
9785 * engine first renders the tool's schema for the model.
9786 */
9787 export type ToolDescribeInput = {
9788 /**
9789 * As the model sees the name (`Bash`, `mcp__server__tool`); the key a
9790 * matcher narrows on.
9791 */
9792 tool: string;
9793 /**
9794 * The tool's description as it computed it.
9795 */
9796 description: string;
9797 /**
9798 * Present, and true, when the engine lists the tool behind ToolSearch (its
9799 * schema loads when the model asks for it by name); absent for one listed.
9800 *
9801 * By the engine's rule an MCP server's tool, or one that asks to be,
9802 * unless a rule keeps it in front.
9803 */
9804 isDeferred?: true;
9805 /**
9806 * Who provides this tool: the plugin and its tier; `{ plugin: "engine",
9807 * tier: "core" }` for a built-in. Pinned: a rewrite is refused.
9808 *
9809 * A configured MCP server's tool is `mcp:<server>`, in `prepend` when the
9810 * policy settings source configures the server, else `user`.
9811 */
9812 provider: Origin;
9813 };
9814
9815 /**
9816 * What a `tool.describe` hook returns: the description the model sees for that
9817 * tool and, when the hook moves it, where the tool waits (ToolDeferral).
9818 *
9819 * `{ description }` alone, or `{ ...(await next(e)), description }`, changes
9820 * the text and keeps the engine's placement; `isDeferred: true` puts the tool
9821 * behind ToolSearch, `isDeferred: false` puts its schema in the prompt's list.
9822 */
9823 export type ToolDescribeResult = {
9824 description: string;
9825 isDeferred?: ToolDeferral;
9826 };
9827
9828 /**
9829 * `{ tool, tool_use_id, ...args }` as one flat object type, generic over
9830 * the tool name and its parsed arguments.
9831 */
9832 type ToolEnvelope<Name, Arguments> = {
9833 /**
9834 * The name of the tool being called (`Bash`, `mcp__<server>__<tool>`);
9835 * comparing it narrows `e`. Reserved: a rewrite of it is ignored by core.
9836 */
9837 tool: Name;
9838 /**
9839 * The tool_use block's id: the same at every event of the call and in
9840 * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
9841 */
9842 tool_use_id: string;
9843 } & Arguments;
9844
9845 /**
9846 * One tool call of a ToolGroup, as `ui.render` sees it under `calls`.
9847 */
9848 export type ToolGroupCall = {
9849 /**
9850 * The id `tool.call` carried for this call (`e.tool_use_id` there), so a
9851 * hook that saw the call finds its row in the group. Read-only.
9852 *
9853 * Absent on a desktop host that predates it.
9854 */
9855 tool_use_id?: string;
9856 /**
9857 * Which one the call ran (`Bash`, `Read`, `Grep`, ...).
9858 */
9859 tool: string;
9860 /**
9861 * The call's input, as the model sent it.
9862 */
9863 input: unknown;
9864 /**
9865 * True while the call is still running.
9866 */
9867 isRunning: boolean;
9868 /**
9869 * True when the call ended in an error.
9870 */
9871 isErrored: boolean;
9872 /**
9873 * True when an abort ended the call, as on `ToolUse`.
9874 */
9875 isInterrupted: boolean;
9876 /**
9877 * As on `ToolUse`; undefined while the call runs.
9878 */
9879 output?: unknown;
9880 };
9881
9882 /**
9883 * One tool as `$.tool.list()` returns it.
9884 */
9885 export type ToolInfo = {
9886 /**
9887 * What the model calls it by.
9888 */
9889 name: string;
9890 /**
9891 * What it does, in the tool's own words (its description; a first sentence at
9892 * most for MCP tools without one).
9893 */
9894 description: string;
9895 /**
9896 * True for an MCP server's tool.
9897 */
9898 mcp: boolean;
9899 };
9900
9901 /**
9902 * `{ tool, tool_use_id, ...args }` as one flat object type.
9903 *
9904 * The docs of `tool` and `tool_use_id` live on the `keyof` operand: a mapped
9905 * type takes its properties' docs from there.
9906 */
9907 export type ToolInputOf<Name extends string, Arguments> = {
9908 [K in keyof ToolEnvelope<Name, Arguments>]: ToolEnvelope<Name, Arguments>[K];
9909 };
9910
9911 /**
9912 * An input that names its tool as the literal `T`: what `next` and
9913 * `$.tool.call` read to type the call's result per tool (NextResultFor).
9914 */
9915 type ToolNamed<T extends string> = {
9916 /**
9917 * The name of the tool being called (`Bash`).
9918 */
9919 readonly tool: T;
9920 };
9921
9922 /**
9923 * The structured result of the tool named `Name`: its BuiltinToolResults
9924 * entry for a built-in tool, else `unknown`.
9925 *
9926 * Agent's is its entry or an AgentCallRecord (what a plugin-raised call
9927 * answers). `unknown` covers an MCP tool, a name the results table lacks
9928 * (one merged into the inputs table alone too), and `Name` left at `string`.
9929 */
9930 export type ToolResultOf<Name extends string> = string extends Name ? unknown : Name extends keyof BuiltinToolResults & string ? BuiltinToolResults[Name] | (Name extends 'Agent' ? AgentCallRecord : never) : unknown;
9931
9932 /**
9933 * One tool_result block of a user message.
9934 */
9935 export type ToolResultSummary = {
9936 /**
9937 * The id of the call this result answers (`tool.call`'s `e.tool_use_id`).
9938 */
9939 tool_use_id: string;
9940 /**
9941 * The result as the model read it (text blocks joined).
9942 */
9943 text: string;
9944 /**
9945 * True when the tool reported an error.
9946 */
9947 isError: boolean;
9948 /**
9949 * What the transcript stored for the call: the tool's record on an answered
9950 * one (`tool.call`'s `result`), the error text when `isError`.
9951 *
9952 * Absent when nothing was stored. Headless (`-p`), a tool may store the
9953 * record less its bulk (Bash blanks `stdout`); `text` is what the model
9954 * read either way.
9955 */
9956 result?: unknown;
9957 };
9958
9959 /**
9960 * What `$.tool.register` takes.
9961 */
9962 export type ToolSpec = {
9963 /**
9964 * The tool's short name (letters, digits, `_`, `-`; up to 64); the model
9965 * calls it as `mcp__<plugin>__<name>`.
9966 */
9967 name: string;
9968 /**
9969 * What the tool does, for the model (and the person where tools are
9970 * listed); an unpaired surrogate half in it is drawn as U+FFFD.
9971 */
9972 description: string;
9973 /**
9974 * A JSON schema object for the input (`{ type: "object", properties,
9975 * required }`); default `{ type: "object" }`.
9976 */
9977 inputSchema?: Record<string, unknown>;
9978 };
9979
9980 /**
9981 * One tool_use block of an assistant message, with its outcome once the
9982 * transcript holds the call's tool_result (paired by `tool_use_id`).
9983 */
9984 export type ToolUseSummary = {
9985 /**
9986 * The call's id, as `tool.call` carried it (`e.tool_use_id` there).
9987 */
9988 tool_use_id: string;
9989 /**
9990 * Which one was called (`Read`, `Bash`, `mcp__server__tool`), as
9991 * `tool.call` named it (`e.tool` there).
9992 */
9993 tool: string;
9994 /**
9995 * The arguments the model gave it.
9996 */
9997 input: Record<string, unknown>;
9998 /**
9999 * What the transcript stored for the call: the tool's record on an answered
10000 * one (`tool.call`'s `result`), the error text on a refused or errored one.
10001 *
10002 * Absent while the call is in flight or when nothing was stored. Headless
10003 * (`-p`), a tool may store the record less its bulk (Bash blanks `stdout`);
10004 * `text` holds either way.
10005 */
10006 result?: unknown;
10007 /**
10008 * The result as the model read it; absent while the call is in flight.
10009 */
10010 text?: string;
10011 /**
10012 * Present only when the tool reported an error, as on `tool.call`'s result.
10013 */
10014 isError?: true;
10015 };
10016
10017 /**
10018 * One settled run of a link beneath the caller, as `next.trace` lists it:
10019 * data, not a handle.
10020 *
10021 * `received` and `returned` are the live references where the hook runs
10022 * beside the chain; in a hooks module its own copies, as `e` is.
10023 */
10024 export type TraceEntry<N extends EventName = EventName, E = Args<N>, O = NextResult<N>> = {
10025 /**
10026 * The link's place in the chain, 0 the outermost.
10027 */
10028 readonly index: number;
10029 /**
10030 * The hook's plugin; `"engine"` for the engine's own core or bottom.
10031 */
10032 readonly plugin: string;
10033 /**
10034 * The link's tier (Tier); `"core"` for the engine's own core or bottom.
10035 */
10036 readonly tier: Tier;
10037 readonly event: N;
10038 readonly outcome: TraceOutcome;
10039 /**
10040 * Why the link was skipped without running, when it was: `bypassed by
10041 * <plugin>`, whose `next.to` went beneath this tier. Absent when it ran.
10042 */
10043 readonly reason?: string;
10044 /**
10045 * Its own wall time, its `next()` calls' time in flight taken out.
10046 *
10047 * The engine entry's is everything beneath the last hook: in a hooks
10048 * module, the host round trip.
10049 */
10050 readonly ms: number;
10051 /**
10052 * How many chunks the link yielded up, on a streaming event; absent on
10053 * every other. A link left mid-stream counts what it yielded before.
10054 */
10055 readonly chunks?: number;
10056 readonly received: E;
10057 /**
10058 * What the link settled on; undefined when it was skipped or rejected.
10059 */
10060 readonly returned: O | undefined;
10061 };
10062
10063 /**
10064 * What the chain decided for one link, as `next.trace` names it.
10065 *
10066 * `returned`: its result stood; `passed`: it returned, by reference, what its
10067 * last `next()` resolved to (a hooks module's hook answers with a copy of its
10068 * own, so it reads `returned`); `skipped`: it failed before `next`, or a
10069 * `next.to` above continued beneath its tier (`reason` says which), and
10070 * beneath ran in its place; `kept`: it failed after `next`, and that run's
10071 * result stands; `expired`: its budget ran out (what stands follows
10072 * skipped/kept); `caught`: it threw or its budget ran out, and its `.catch`
10073 * handler's result stands; `rejected`: the link rejected; the deepest such
10074 * entry is where the rejection came from, and the ones above it let it pass.
10075 */
10076 export type TraceOutcome = 'caught' | 'expired' | 'kept' | 'passed' | 'rejected' | 'returned' | 'skipped';
10077
10078 /**
10079 * What every `turn.complete` carries whatever its reason: the answer, the
10080 * duration, the interrupt flag, the turn's id, its loop and what it cost.
10081 */
10082 type TurnCompleteFields = {
10083 /**
10084 * The assistant's final visible text this turn ("" if none, e.g.
10085 * thinking-only).
10086 */
10087 answer: string;
10088 /**
10089 * Wall-clock length of the turn in milliseconds.
10090 */
10091 durationMs: number;
10092 /**
10093 * True when the turn ended by interruption (`reason === 'aborted'`).
10094 */
10095 isAborted: boolean;
10096 /**
10097 * The turn's id, the same one its `turn.start` and every `turn.step`
10098 * carried; a subagent's run raises no `turn.start`, its steps carry it.
10099 */
10100 turnId: string;
10101 /**
10102 * The loop the turn ran in: a subagent's id, as `$.agent.spawn` resolves
10103 * it, each run of its loop one turn; absent on the main loop.
10104 *
10105 * Pinned: a different value is refused, one left out is kept. Every hook
10106 * sees a subagent's turn, so a hook that spawns sees its children's turns
10107 * too and bounds itself.
10108 */
10109 agentId?: string;
10110 /**
10111 * What the turn cost: its responses' token counts summed and the model of
10112 * the last, read off the API responses the engine already holds.
10113 *
10114 * Absent when the turn got no response (interrupted before one, an API
10115 * error).
10116 */
10117 usage?: TurnUsage;
10118 };
10119
10120 /**
10121 * The input of `turn.complete`: the assistant's final message of a turn, at
10122 * the moment the turn ends (where the turn's duration is reported).
10123 *
10124 * `reason` says why it ended; `refusal` exists on a refusal alone.
10125 */
10126 export type TurnCompleteInput = TurnCompleteFields & (TurnCompleteRefused | TurnCompleteUnrefused);
10127
10128 /**
10129 * Why a turn ended: the model answered, the user interrupted it, the model
10130 * refused with no fallback model to retry on, or an API error ended it.
10131 */
10132 export type TurnCompleteReason = 'answer' | 'aborted' | 'refusal' | 'error';
10133
10134 /**
10135 * The end of a turn the model refused with no fallback model to retry on:
10136 * what the API said of the refusal rides along.
10137 */
10138 type TurnCompleteRefused = {
10139 reason: 'refusal';
10140 refusal: TurnRefusal;
10141 };
10142
10143 /**
10144 * What a `turn.complete` hook returns and what `next(e)` resolves to:
10145 * `{ text }`; a text other than a main-loop answer's is shown beneath it.
10146 *
10147 * Core fills `usage` from `e.usage` when the turn had one; a hook above reads
10148 * it, and one that answers its own may leave it out.
10149 */
10150 export type TurnCompleteResult = {
10151 text: string;
10152 usage?: TurnUsage;
10153 };
10154
10155 /**
10156 * The end of a turn that was not a refusal: answered, interrupted, or dead
10157 * on an API error (retries exhausted, the context limit), nothing more.
10158 */
10159 type TurnCompleteUnrefused = {
10160 reason: Exclude<TurnCompleteReason, 'refusal'>;
10161 };
10162
10163 /**
10164 * What the API said about a refusal that ended a turn: the classifier's
10165 * category and its explanation, each null when the API sent none.
10166 */
10167 export type TurnRefusal = {
10168 category: string | null;
10169 explanation: string | null;
10170 };
10171
10172 /**
10173 * The input of `turn.start`: the prompt a model turn begins with, after
10174 * `prompt.submit` settled the text and the UserPromptSubmit settings hooks ran.
10175 */
10176 export type TurnStartInput = {
10177 /**
10178 * The user's text as the turn proceeds with it ("" for a turn started without
10179 * a typed prompt, e.g. a continuation).
10180 */
10181 text: string;
10182 /**
10183 * The turn's id, minted here; the same one every `turn.step` and the
10184 * `turn.complete` of this turn carry.
10185 */
10186 turnId: string;
10187 };
10188
10189 /**
10190 * What a `turn.start` hook returns and what `next(e)` resolves to:
10191 * `{ turnId }`, echoed by core; a hook's own value does not change the turn.
10192 */
10193 export type TurnStartResult = {
10194 turnId: string;
10195 };
10196
10197 /**
10198 * One piece of a `turn.step` response as it streams through the chain:
10199 * what a hook's `next(e)` yields and what the hook yields up in turn.
10200 *
10201 * Text, thinking, a tool call's start and arguments, and the stop are
10202 * plain data a hook reads and rewrites; `engine` is the rest, passed on
10203 * unread. What leaves the outermost hook is what is shown and recorded.
10204 */
10205 export type TurnStepChunk = TurnStepTextChunk | TurnStepThinkingChunk | TurnStepToolChunk | TurnStepInputChunk | TurnStepStopChunk | TurnStepEngineChunk;
10206
10207 /**
10208 * An item of the engine's stream the other chunk kinds do not model (the
10209 * envelope, a block's start and end, a retry marker), opaque by `ref`.
10210 *
10211 * Pass it on where it came. A hook that yields its own response has none
10212 * to yield, and the engine supplies what the response needs around the
10213 * chunks it does yield.
10214 */
10215 export type TurnStepEngineChunk = {
10216 kind: 'engine';
10217 /**
10218 * The engine's handle on the item; opaque, this step's only.
10219 */
10220 ref: number;
10221 };
10222
10223 /**
10224 * The input of `turn.step`: one model request inside a turn, at the moment
10225 * the engine is about to send it; the bottom of the chain sends it.
10226 *
10227 * The transcript is not on it: `messageCount` says how many messages the
10228 * request carries, and `$.session.messages()` reads them. A hook rewrites
10229 * `model` or `effort` going down; the rest is pinned.
10230 */
10231 export type TurnStepInput = {
10232 /**
10233 * The turn this step belongs to (`turn.start`'s id; inside a subagent's
10234 * loop, the id the run's `turn.complete` will carry). Pinned.
10235 */
10236 turnId: string;
10237 /**
10238 * The step's position in the turn, from 0. Pinned.
10239 */
10240 index: number;
10241 /**
10242 * Which model the request names, as the engine resolved it for this step
10243 * (the session's, a fallback's). `next({ ...e, model })` names another.
10244 */
10245 model: string;
10246 /**
10247 * How hard the request asks the model to think: the session's setting or
10248 * the model's default, absent for a model without effort; rewritable.
10249 */
10250 effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number;
10251 /**
10252 * How many messages the request carries (the conversation so far, the
10253 * turn's tool results included). Pinned: the messages are the engine's.
10254 */
10255 messageCount: number;
10256 /**
10257 * The loop the request is made in: a subagent's id, the `id`
10258 * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
10259 *
10260 * Pinned: a different value is refused, one left out is kept. A subagent
10261 * a hook spawned through `$.agent.spawn` steps past that hook, as its tool
10262 * calls do; every other hook sees its steps.
10263 */
10264 agentId?: string;
10265 };
10266
10267 /**
10268 * A piece of a tool call's arguments as they arrive: JSON text, partial,
10269 * for the `tool` chunk of the same `index`.
10270 *
10271 * The arguments the tool runs with are the pieces concatenated and parsed
10272 * once the block ends; pieces that do not parse leave the call without
10273 * arguments it can run on, as a model that wrote broken JSON would.
10274 */
10275 export type TurnStepInputChunk = ChunkRef & {
10276 kind: 'input';
10277 index: number;
10278 /**
10279 * The next piece of the arguments' JSON text.
10280 */
10281 json: string;
10282 };
10283
10284 /**
10285 * What a `turn.step` hook returns and what `next(e)` resolves to: the
10286 * model's response to the step's request, once its blocks are all in.
10287 *
10288 * From the bottom, the response the engine streamed; a hook's own value
10289 * changes what the hooks above it read, never what the engine streamed.
10290 */
10291 export type TurnStepResult = {
10292 /**
10293 * The turn this step belongs to, as received.
10294 */
10295 turnId: string;
10296 /**
10297 * The step's position in the turn, as received.
10298 */
10299 index: number;
10300 /**
10301 * The visible text of the response ("" when it only called tools, only
10302 * thought, or no request was made).
10303 */
10304 answer: string;
10305 /**
10306 * The tool calls the response made, in order; empty for a text-only step.
10307 */
10308 toolUses: readonly TurnStepToolUse[];
10309 /**
10310 * Why the model stopped; null when no response arrived (the request
10311 * failed or was interrupted before a message, or no request was made).
10312 */
10313 stopReason: TurnStopReason;
10314 /**
10315 * What the request cost as the API reported it, and the model that
10316 * answered; null when no response arrived or it carried no usage.
10317 */
10318 usage: TurnUsage | null;
10319 };
10320
10321 /**
10322 * The response is whole: why the model stopped and what the request cost,
10323 * as the step's result will carry them. The last chunk of one response.
10324 */
10325 export type TurnStepStopChunk = ChunkRef & {
10326 kind: 'stop';
10327 stopReason: TurnStopReason;
10328 usage: TurnUsage | null;
10329 };
10330
10331 /**
10332 * A piece of the response's visible text as it arrives, in block `index`.
10333 *
10334 * The text the person watches stream and the text the transcript records
10335 * are both the concatenation of these, in order, per block: a hook that
10336 * rewrites them rewrites both, one that drops them all drops the block.
10337 */
10338 export type TurnStepTextChunk = ChunkRef & {
10339 kind: 'text';
10340 /**
10341 * The content block the piece belongs to, from 0 within one response.
10342 */
10343 index: number;
10344 text: string;
10345 };
10346
10347 /**
10348 * A piece of the model's thinking as it arrives, in block `index`: what
10349 * the person sees of it live.
10350 *
10351 * The thinking block the transcript keeps is the one the model signed, as
10352 * the engine received it; thinking a hook streams without the engine's
10353 * block behind it is shown and not recorded.
10354 */
10355 export type TurnStepThinkingChunk = ChunkRef & {
10356 kind: 'thinking';
10357 index: number;
10358 text: string;
10359 };
10360
10361 /**
10362 * The model begins a tool call in block `index`: the tool's name and the
10363 * call's id; its arguments follow as `input` chunks of the same index.
10364 *
10365 * A block whose `tool` chunk never comes out of the chain is no tool call:
10366 * the engine records none and runs none.
10367 */
10368 export type TurnStepToolChunk = ChunkRef & {
10369 kind: 'tool';
10370 index: number;
10371 /**
10372 * The call's `tool_use_id`.
10373 */
10374 id: string;
10375 /**
10376 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
10377 */
10378 name: string;
10379 };
10380
10381 /**
10382 * One tool call the model asked for in a step: the tool's name and its
10383 * arguments.
10384 */
10385 export type TurnStepToolUse = {
10386 /**
10387 * The tool's name (`Read`, `Bash`, `mcp__server__tool`).
10388 */
10389 name: string;
10390 /**
10391 * The arguments the model gave it, as the tool schema shapes them.
10392 */
10393 input: unknown;
10394 };
10395
10396 /**
10397 * Why the model stopped, as a `turn.step` result and its stop chunk carry
10398 * it: one of the API's stop reasons, or null when no response arrived.
10399 */
10400 type TurnStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'compaction' | 'refusal' | 'model_context_window_exceeded' | null;
10401
10402 /**
10403 * What a model turn, or one response inside it, cost as the API reported it:
10404 * the four token counts (`$.model.fork`'s usage shape) and the model's id.
10405 *
10406 * A turn's counts are its responses' summed; its model is the last response's.
10407 */
10408 export type TurnUsage = ModelForkUsage & {
10409 /**
10410 * Which model answered, by the id the API reports.
10411 */
10412 model: string;
10413 };
10414
10415 /**
10416 * What a plugin's `$.ui.blit(args)` takes: a Raster's next `cells`
10417 * (RasterBlitArgs) or a keyed Image's next `source` (ImageBlitArgs).
10418 *
10419 * Either names an element this plugin's own `ui.render` hook drew, still
10420 * mounted; a hook above may rewrite the cells or the source, never the
10421 * address or which kind it is.
10422 */
10423 export type UiBlitArgs = RasterBlitArgs | ImageBlitArgs;
10424
10425 /**
10426 * What `$.ui.blit` resolves to and what a `ui.blit` hook's `{ value }`
10427 * holds: `{}` once the cells or source are the next frame's, or why not.
10428 */
10429 export type UiBlitResult = {
10430 /**
10431 * Absent when the cells or source were taken; else why not.
10432 *
10433 * Nothing of this plugin's is mounted there (another plugin's reads so),
10434 * the size is not the mounted one, the cells or source are bad, or the
10435 * Image draws its `alt` there, the reason spelled out for a fallback.
10436 */
10437 deny?: string;
10438 };
10439
10440 /**
10441 * What a plugin's `$.ui.focus(args)` takes: one of its own elements, by the
10442 * `key` it drew it under, in one of its sites that holds the keyboard now.
10443 *
10444 * The engine resolves it to that site's ring and raises `ui.focus` under
10445 * the plugin's origin; the keyboard is the person's to give, so a site that
10446 * does not hold it, or holds it on another plugin's element, is `{ deny }`.
10447 */
10448 export type UiFocusArgs = {
10449 /**
10450 * The site, by the `requestId` this plugin draws it under: one of its
10451 * panes' ids, or the band's.
10452 */
10453 requestId: string;
10454 /**
10455 * The element's `key`: a `Button`, `Input` or `Select` this plugin drew in
10456 * that site; of several under one key, the first in document order.
10457 */
10458 key: string;
10459 };
10460
10461 /**
10462 * The render components whose site keeps a focus ring: a pane's body and
10463 * the band above the prompt, each a ring over the elements hooks drew there.
10464 */
10465 export type UiFocusComponent = 'Pane' | 'AbovePrompt';
10466
10467 /**
10468 * The input of `ui.focus`: a site's focus ring about to move onto one of the
10469 * elements a hook drew in it (a `Button`, `Input` or `Select`), or off them.
10470 *
10471 * Every key but `element` is the engine's word, pinned: `next(e)` passes
10472 * them on, a rewrite that leaves one out keeps it, one that changes it fails
10473 * the hook. `element` is the hook's to rewrite; the ring has not moved yet.
10474 */
10475 export type UiFocusInput = {
10476 /**
10477 * Which site: a `Pane` body or the `AbovePrompt` band.
10478 */
10479 component: UiFocusComponent;
10480 /**
10481 * The instance the `ui.render` hook drawing the site sees: the pane's id,
10482 * or the band's one id.
10483 */
10484 requestId: string;
10485 /**
10486 * Whose `ui.render` hook drew the element taking the ring; absent with
10487 * `element`. Read-only.
10488 */
10489 plugin?: string;
10490 /**
10491 * The `key` of the element taking the ring, as `ui.press` names it; absent
10492 * for one of the engine's own stops (a pane's close mark or another's tab).
10493 *
10494 * `next({ ...e, element })` lands it on another element `plugin` drew in
10495 * the site instead; one not drawn there is core's `{ deny }`.
10496 */
10497 element?: string;
10498 /**
10499 * Who moves it (UiFocusOrigin), set by the engine where the move starts.
10500 */
10501 origin: UiFocusOrigin;
10502 };
10503
10504 /**
10505 * Who moves the ring at `ui.focus`, as the engine stamps it where the move
10506 * starts; a closed set a matcher narrows on.
10507 *
10508 * `next(e)` passes it on as received; no hook sets one.
10509 */
10510 export type UiFocusOrigin = {
10511 /**
10512 * The person, by Tab, the arrows or a click while the site holds the
10513 * keyboard.
10514 */
10515 kind: 'person';
10516 } | {
10517 /**
10518 * A plugin's `$.ui.focus`, or its `autoFocus` element taking the ring
10519 * as the site takes the keyboard.
10520 */
10521 kind: 'plugin';
10522 /**
10523 * The focusing plugin's name.
10524 */
10525 name: string;
10526 };
10527
10528 /**
10529 * What a `ui.focus` hook returns, what `next(e)` resolves to, and what
10530 * `$.ui.focus` hands back: `{}` once the ring moved, or why it did not.
10531 *
10532 * As `ui.scroll` spells it.
10533 */
10534 export type UiFocusResult = {
10535 /**
10536 * Absent when the ring is where the chain left it; else why nothing
10537 * moved.
10538 *
10539 * A hook kept the ring (no `next`); the site is not this plugin's, does
10540 * not hold the keyboard, or another plugin's element holds it; no element
10541 * of `plugin` is drawn under `element`; another move landed first.
10542 */
10543 deny?: string;
10544 };
10545
10546 /**
10547 * The argument of `ui.input`: a change of, or a submit from, an `Input` a
10548 * render hook drew. Flat and frozen like every event's.
10549 *
10550 * Another plugin addresses one field by matcher:
10551 * `on("ui.input", { plugin: "roster", element: "reply" }, ...)`.
10552 */
10553 export type UiInputArgument = {
10554 /**
10555 * Whose `ui.render` hook drew the element.
10556 */
10557 plugin: string;
10558 /**
10559 * The `key` the hook gave its `Input`: its address, what a matcher names.
10560 */
10561 element: string;
10562 /**
10563 * The render component the element was drawn in (`AbovePrompt`,
10564 * `ToolUse`, ...).
10565 */
10566 component: RenderComponent;
10567 /**
10568 * The instance the element was drawn in: the `requestId` the `ui.render`
10569 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
10570 */
10571 requestId: string;
10572 /**
10573 * Where the typing came from, one literal per member, so
10574 * `if (e.surface === "terminal")` narrows `e`.
10575 */
10576 surface: RenderSurface;
10577 /**
10578 * `change` after every edit of the text; `submit` on Enter.
10579 */
10580 kind: 'change' | 'submit';
10581 /**
10582 * The field's whole text at that moment; a hook above may rewrite it for
10583 * the plugins beneath and the element's own handler.
10584 */
10585 value: string;
10586 };
10587
10588 /**
10589 * What a `ui.input` hook returns and what `next(e)` resolves to.
10590 *
10591 * Beneath every hook, core runs the element's `onInput` (kind `change`) or
10592 * `onSubmit` (kind `submit`) closure in its plugin's environment with the
10593 * value as the chain left it, and answers `{ element, value }`.
10594 */
10595 export type UiInputResult = {
10596 /**
10597 * Which handler the input reached, by its Input's `key`.
10598 */
10599 element: string;
10600 /**
10601 * The text the handler received.
10602 */
10603 value: string;
10604 };
10605
10606 /**
10607 * Options of `$.ui.log`.
10608 */
10609 export type UiLogOptions = {
10610 /**
10611 * Where the line goes (UiLogSink); `transcript` when left out. A hook on
10612 * `ui.log` reads it as `e.to` and may send the line elsewhere.
10613 */
10614 to?: UiLogSink;
10615 };
10616
10617 /**
10618 * Where a `$.ui.log` line goes: `transcript`, a dim row of its own (and the
10619 * debug log, as every line); `debug`, the debug log alone, nothing on screen.
10620 *
10621 * The debug log is `claude --debug` or the `--debug-file`; either way the
10622 * line is led by the plugin's name.
10623 */
10624 export type UiLogSink = 'transcript' | 'debug';
10625
10626 /**
10627 * The argument of `ui.message`: what a `Client` instance's surface module
10628 * posted (`surface.post(data)`), addressed by where the instance is drawn.
10629 *
10630 * The origin is `client`: code sent it, on nobody's behalf, so `data` is
10631 * input to validate, not a fact. Everything but `data` is the engine's word
10632 * and a hook may not rewrite it.
10633 */
10634 export type UiMessageArgument = {
10635 /**
10636 * Where the instance is drawn: `terminal`, or `desktop` once it has them.
10637 */
10638 surface: RenderSurface;
10639 /**
10640 * The render component the `Client` was drawn in (`AbovePrompt`, `Pane`,
10641 * ...).
10642 */
10643 component: RenderComponent;
10644 /**
10645 * The engine's id for the drawing the `Client` sits in: the `requestId` the
10646 * `ui.render` hook that drew it saw.
10647 */
10648 requestId: string;
10649 /**
10650 * The `Client`'s `key`: which instance posted.
10651 */
10652 element: string;
10653 /**
10654 * The `Client`'s `module`: which surface module runs there, as its path
10655 * under the plugin's folder.
10656 */
10657 module: string;
10658 /**
10659 * What the instance posted: plain data (JsonValue), bounded as a tree's
10660 * text is; typed `unknown` since it came from code. Rewritable.
10661 */
10662 data: unknown;
10663 };
10664
10665 /**
10666 * What a `ui.message` hook returns and what `next(e)` resolves to.
10667 *
10668 * Core answers `{}`: the message was heard and nothing changes. A hook that
10669 * answers `{ props }` hands the posting instance its next props directly, its
10670 * local state kept, with no `ui.render` run; the plugin's next redraw hands
10671 * props again as usual.
10672 */
10673 export type UiMessageResult = {
10674 /**
10675 * The instance's next props, plain data (JsonValue) bounded as a `Client`'s
10676 * props are; absent leaves the instance's props as they were.
10677 */
10678 props?: unknown;
10679 };
10680
10681 /**
10682 * One of this plugin's open panes as `$.ui.panes()` lists it: the pane's
10683 * id and title, and where it stands with the person right now.
10684 *
10685 * Where a surface seated it (`dock` or `inline`) is that surface's to say, on
10686 * the `Pane` render props (`placement`); a session may draw on several.
10687 */
10688 export type UiPane = {
10689 /**
10690 * What `$.ui.open({ id })` named it, which `$.ui.close` and its
10691 * `ui.render` `requestId` name too.
10692 */
10693 id: string;
10694 /**
10695 * Its tab's label: the `title` of its latest open, or the id.
10696 */
10697 title: string;
10698 /**
10699 * True for the one pane the surface shows; the rest are tabs behind it.
10700 */
10701 isShown: boolean;
10702 /**
10703 * True while the person has given it the keyboard.
10704 */
10705 isFocused: boolean;
10706 /**
10707 * False while it waits undrawn: opened unasked on a terminal too narrow
10708 * for an unrequested pane, until an open the width or the person admits.
10709 */
10710 isPlaced: boolean;
10711 };
10712
10713 /**
10714 * The argument of `ui.press`: a press on a `Button` a render hook drew, or
10715 * on an answered `Markdown` link. Flat and frozen like every event's.
10716 *
10717 * Another plugin addresses one button by matcher:
10718 * `on("ui.press", { plugin: "explainer", element: "explain" }, ...)`.
10719 */
10720 export type UiPressArgument = {
10721 /**
10722 * Whose `ui.render` hook drew the element.
10723 */
10724 plugin: string;
10725 /**
10726 * The `key` the hook gave its `Button` or `Markdown`: its address, what a
10727 * matcher names.
10728 */
10729 element: string;
10730 /**
10731 * The render component the element was drawn in (`ToolUse`,
10732 * `AssistantMessage`, ...).
10733 */
10734 component: RenderComponent;
10735 /**
10736 * The instance the element was drawn in: the `requestId` the `ui.render`
10737 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
10738 */
10739 requestId: string;
10740 /**
10741 * Where the press came from, one literal per member, so
10742 * `if (e.surface === "terminal")` narrows `e`.
10743 */
10744 surface: RenderSurface;
10745 /**
10746 * Where the press landed, when the element is a `Markdown` whose links
10747 * its plugin answers (`onLinkPress`); absent for a `Button`.
10748 *
10749 * A hook may rewrite its `href` for the hooks and the closure beneath; one
10750 * that adds or drops it fails, and the press goes on beneath it.
10751 */
10752 link?: PressedLink;
10753 };
10754
10755 /**
10756 * What a `ui.press` hook returns and what `next(e)` resolves to.
10757 *
10758 * Beneath every hook, core runs the element's `onPress` closure in its
10759 * plugin's environment with `e` as the chain left it, and answers
10760 * `{ element }`.
10761 */
10762 export type UiPressResult = {
10763 /**
10764 * Which handler the press reached, by its Button's `key`.
10765 */
10766 element: string;
10767 };
10768
10769 /**
10770 * What a plugin's `$.ui.scroll(args)` takes: what to bring into view, in
10771 * which of its sites, and where in the window it lands.
10772 *
10773 * The engine resolves it to a window and an offset and raises `ui.scroll`
10774 * under the plugin's origin; a transcript row is the person's to move, so
10775 * it is revealed only while the plugin answers the person's own input.
10776 */
10777 export type UiScrollArgs = {
10778 /**
10779 * What to reveal (UiScrollTarget): a render instance by `requestId`, one
10780 * of this plugin's elements by `key`, or the `start` or `end` of `in`.
10781 */
10782 to: UiScrollTarget;
10783 /**
10784 * The site to scroll, by the `requestId` this plugin draws it under: one
10785 * of its panes' ids, or the band's.
10786 *
10787 * Required with `start` and `end`; with `{ key }` it picks the site when
10788 * the key is drawn in several.
10789 */
10790 in?: string;
10791 /**
10792 * Where the target lands in the window (UiScrollBlock); `nearest` when
10793 * left out, so a row already showing does not move.
10794 */
10795 block?: UiScrollBlock;
10796 };
10797
10798 /**
10799 * Where in its scrollable a revealed row lands, as the DOM's
10800 * `scrollIntoView({ block })` names it.
10801 *
10802 * `nearest` moves the least that shows the row whole, and not at all when
10803 * it already shows; `start`, `center` and `end` put its top, middle or
10804 * bottom at that edge of the window. A row taller than the window shows
10805 * its top.
10806 */
10807 export type UiScrollBlock = 'start' | 'center' | 'end' | 'nearest';
10808
10809 /**
10810 * The render components whose site the engine scrolls: a pane's body and
10811 * the band above the prompt, each a window over the tree a hook drew there.
10812 */
10813 export type UiScrollComponent = 'Pane' | 'AbovePrompt';
10814
10815 /**
10816 * The input of `ui.scroll`: a site's window asked to move over the tree a
10817 * hook drew in it (a pane's body, the band above the prompt).
10818 *
10819 * Every key but `offset` is the engine's word, pinned: `next(e)` passes
10820 * them on, a rewrite that leaves one out keeps it, one that changes or adds
10821 * one fails the hook. `offset` is the hook's to rewrite; nothing moved yet.
10822 */
10823 export type UiScrollInput = {
10824 /**
10825 * Which site: a `Pane` body or the `AbovePrompt` band.
10826 */
10827 component: UiScrollComponent;
10828 /**
10829 * The instance the `ui.render` hook drawing the site sees: the pane's id,
10830 * or the band's one id.
10831 */
10832 requestId: string;
10833 /**
10834 * The first row the window is to show, 0 at the top: the row it shows
10835 * now plus `by`, clamped to the tree, or where `$.ui.scroll` resolved.
10836 *
10837 * `next({ ...e, offset })` moves it elsewhere (a clamp); one past the
10838 * tree's end lands at the end. Nothing has moved when a hook reads it.
10839 */
10840 offset: number;
10841 /**
10842 * The rows the move asks for, signed, negative toward the top; what the
10843 * DOM's `scrollBy` takes. Read-only.
10844 *
10845 * The person's: a wheel tick `-1` or `1` at rest, more as ticks crowd or
10846 * summed in flight; an arrow a row while the engine has rows to scroll, a
10847 * page key `bodyRows`, Home and End `contentRows`. A plugin's: its distance.
10848 */
10849 by: number;
10850 /**
10851 * How many rows of the tree the window shows at once, as drawn now.
10852 * Read-only.
10853 */
10854 bodyRows: number;
10855 /**
10856 * How many rows the tree has, as drawn now: the window's last offset is
10857 * `contentRows - bodyRows`, none when the tree fits. Read-only.
10858 */
10859 contentRows: number;
10860 /**
10861 * Who moves it (UiScrollOrigin), set by the engine where the move starts.
10862 */
10863 origin: UiScrollOrigin;
10864 /**
10865 * The body cell the person's wheel or trackpad was over (UiScrollPointer);
10866 * absent for the scroll keys and for `$.ui.scroll`. Read-only.
10867 *
10868 * Moves summed while a dispatch was in flight carry the latest one's. A
10869 * hook pinning a list over rows it scrolls itself tells a tick over the
10870 * list (`row` among its list's rows) from one over the body.
10871 */
10872 pointer?: UiScrollPointer;
10873 };
10874
10875 /**
10876 * Who moves the window at `ui.scroll`, as the engine stamps it where the
10877 * move starts; a closed set a matcher narrows on.
10878 *
10879 * `next(e)` passes it on as received; no hook sets one.
10880 */
10881 export type UiScrollOrigin = {
10882 /**
10883 * The person, by the wheel over the site or its scroll keys while
10884 * they hold it.
10885 */
10886 kind: 'person';
10887 } | {
10888 /**
10889 * A plugin's `$.ui.scroll`.
10890 */
10891 kind: 'plugin';
10892 /**
10893 * The scrolling plugin's name.
10894 */
10895 name: string;
10896 };
10897
10898 /**
10899 * The cell the pointer was over when the person's wheel raised `ui.scroll`,
10900 * in the site's body: the box its `ui.render` hook draws into, as painted.
10901 *
10902 * The DOM's `clientY - body.top` in cells, the window's offset not added: a
10903 * hook drawing its own window reads `row` as its tree's row, one the engine
10904 * scrolls adds the `scroll.offset` it drew with. The frame lies outside.
10905 */
10906 export type UiScrollPointer = {
10907 /**
10908 * 0 at the body's left edge, as `bodyColumns` counts them; negative, or
10909 * `bodyColumns` and past, over an inline pane's side borders.
10910 */
10911 column: number;
10912 /**
10913 * 0 at the body's first showing row, as `bodyRows` counts them.
10914 *
10915 * The tree's row is `scroll.offset + row` under the engine's window, and
10916 * `row` itself under a hook's own (offset 0); negative over a pane's top
10917 * border or tab row, `bodyRows` or more over its bottom border.
10918 */
10919 row: number;
10920 };
10921
10922 /**
10923 * What a `ui.scroll` hook returns, what `next(e)` resolves to, and what
10924 * `$.ui.scroll` hands back: `{}` once the window moved, or why it did not.
10925 */
10926 export type UiScrollResult = {
10927 /**
10928 * Absent when the window is where the chain left it; else why nothing
10929 * moved, as `tool.call` and `config.set` spell a refusal.
10930 *
10931 * A hook kept the window (no `next`); the target is not this plugin's;
10932 * another move landed first (`the window moved meanwhile`); a transcript
10933 * row is not the person's ask (`not person-initiated`) or none scrolls.
10934 */
10935 deny?: string;
10936 };
10937
10938 /**
10939 * What `$.ui.scroll` brings into view: never a row number, always a thing
10940 * drawn somewhere.
10941 *
10942 * `{ requestId }` names a render instance by the id its `ui.render` hook
10943 * saw (a transcript message's, a tool row's tool_use_id), scrolled into view
10944 * inside whatever scrolls it. `{ key }` names an element this plugin drew
10945 * with that `key`, inside the site it drew it in. `start` and `end` are the
10946 * top and bottom of the site `in` names; `end` keeps up with a tree that
10947 * grows (rows the plugin just added count) until anything next moves it.
10948 */
10949 export type UiScrollTarget = {
10950 requestId: string;
10951 } | {
10952 key: string;
10953 } | 'start' | 'end';
10954
10955 /**
10956 * The argument of `ui.select`: a pick from a `Select` a render hook drew.
10957 * Flat and frozen like every event's.
10958 *
10959 * Another plugin addresses one picker by matcher:
10960 * `on("ui.select", { plugin: "roster", element: "peer" }, ...)`.
10961 */
10962 export type UiSelectArgument = {
10963 /**
10964 * Whose `ui.render` hook drew the element.
10965 */
10966 plugin: string;
10967 /**
10968 * The `key` the hook gave its `Select`: its address, what a matcher names.
10969 */
10970 element: string;
10971 /**
10972 * The render component the element was drawn in (`AbovePrompt`,
10973 * `ToolUse`, ...).
10974 */
10975 component: RenderComponent;
10976 /**
10977 * The instance the element was drawn in: the `requestId` the `ui.render`
10978 * hook that drew it saw (a tool row's tool_use_id, a pane's id).
10979 */
10980 requestId: string;
10981 /**
10982 * Where the pick came from, one literal per member, so
10983 * `if (e.surface === "terminal")` narrows `e`.
10984 */
10985 surface: RenderSurface;
10986 /**
10987 * The picked option's value; a hook above may rewrite it for the plugins
10988 * beneath and the element's own handler.
10989 */
10990 value: string;
10991 };
10992
10993 /**
10994 * What a `ui.select` hook returns and what `next(e)` resolves to.
10995 *
10996 * Beneath every hook, core runs the element's `onSelect` closure in its
10997 * plugin's environment with the value as the chain left it, and answers
10998 * `{ element, value }`.
10999 */
11000 export type UiSelectResult = {
11001 /**
11002 * Which handler the pick reached, by its Select's `key`.
11003 */
11004 element: string;
11005 /**
11006 * What the handler received: the option's value as the chain left it.
11007 */
11008 value: string;
11009 };
11010
11011 /**
11012 * The intersection of a union's members (`A | B` to `A & B`), by inferring
11013 * one parameter type from the contravariant positions.
11014 */
11015 type UnionToIntersection<U> = (U extends unknown ? (member: U) => void : never) extends (member: infer I) => void ? I : never;
11016
11017 /**
11018 * One unit of what `$.session.usage()` answers, by its key there: the
11019 * context window's fill, the rate-limit windows, the session's cost.
11020 */
11021 export type UsageUnit = 'context' | 'rateLimits' | 'cost';
11022
11023 /**
11024 * Who sent the message a `UserMessage` row carries, when someone other than
11025 * the person did: another agent, a teammate, another session, a channel.
11026 *
11027 * Read-only. The sender's words are not the person's: the model reads them
11028 * framed as that sender's whatever a hook draws for the row.
11029 */
11030 type UserMessageFrom = {
11031 /**
11032 * The sender's name as the row shows it: a subagent's name, else its type;
11033 * a teammate's; another session's title; a channel's sender, else server.
11034 *
11035 * One printable line: control and format characters stripped, whitespace
11036 * collapsed, length bounded. Absent (no `from`) for a teammate block whose
11037 * frames name different senders or none.
11038 */
11039 name: string;
11040 };
11041
11042 /**
11043 * The background task a `UserMessage` notification row reports on: a
11044 * subagent, a background shell, a workflow, a remote agent, a monitor.
11045 *
11046 * Every field is the notification's own, so the row names the same task on
11047 * every draw, a resumed session's included; the session's record of it
11048 * (name, type, description) is `$.agent.list()`'s, by `id`. Each string is
11049 * one printable line, bounded (a forged envelope's bytes capped). Read-only.
11050 */
11051 type UserMessageTask = {
11052 /**
11053 * The task's id as the notification names it; for a subagent, the
11054 * `agentId` its `turn.complete` carried and `$.agent.list()` keys.
11055 */
11056 id?: string;
11057 /**
11058 * How the task ended: `completed`, `failed` or `killed` (stopped, by the
11059 * person or by Claude), or another word its producer wrote.
11060 */
11061 status?: string;
11062 /**
11063 * What kind of task, when the notification says (`remote_agent`, an
11064 * artifact watch's kind); a subagent's and a shell's leave it out.
11065 */
11066 type?: string;
11067 /**
11068 * Which call started the task: its `tool_use_id`, when the notification
11069 * carries it.
11070 */
11071 toolUseId?: string;
11072 /**
11073 * How long the task ran, in milliseconds, when the notification says; the
11074 * row draws it after the summary (`2m 2s`).
11075 */
11076 durationMs?: number;
11077 };
11078
11079 type UserPromptExpansionHookInput = BaseHookInput & {
11080 hook_event_name: 'UserPromptExpansion';
11081 expansion_type: 'slash_command' | 'mcp_prompt';
11082 command_name: string;
11083 command_args: string;
11084 command_source?: string;
11085 prompt: string;
11086 };
11087
11088 type UserPromptSubmitHookInput = BaseHookInput & {
11089 hook_event_name: 'UserPromptSubmit';
11090 prompt: string;
11091 /**
11092 * 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.
11093 */
11094 source?: 'user' | 'sdk' | 'system' | 'loop_wakeup' | 'schedule_wakeup' | 'poll_event';
11095 session_title?: string;
11096 };
11097
11098 /**
11099 * The result of a call on `$` as the hooks on its event see it: `{ value }`,
11100 * the call's answer, or `{ deny }`, the reason the caller's promise rejects.
11101 */
11102 type ValueOrDeny<Value> = {
11103 value: Value;
11104 deny?: undefined;
11105 } | {
11106 deny: string;
11107 value?: undefined;
11108 };
11109
11110 type WorktreeCreateHookInput = BaseHookInput & {
11111 hook_event_name: 'WorktreeCreate';
11112 name: string;
11113 };
11114
11115 type WorktreeRemoveHookInput = BaseHookInput & {
11116 hook_event_name: 'WorktreeRemove';
11117 worktree_path: string;
11118 };
11119
11120 /**
11121 * The globals of a hooks module's environment: these and no others (no DOM,
11122 * no Node). No code generation either: `eval` and `new Function` over a
11123 * string throw, and there is no `WebAssembly` (deliberately; a module that
11124 * needs compiled code runs it in a process of its own through `$.process.run`).
11125 * A surface module's environment (Client) has the same globals and a
11126 * `console`; neither has timers (a hooks module waits on `$.clock`, a
11127 * surface module on `surface.every`).
11128 */
11129 global {
11130 /**
11131 * The JSX factory (classic runtime, `@jsx h`; the engine prepends the
11132 * pragma): a plain-data element from a string tag or a component.
11133 *
11134 * JSX compiles to bare `h(...)` calls resolved by name, so a module (hooks or
11135 * surface) never declares, imports or takes as a parameter anything named
11136 * `h` or `Fragment` where it writes JSX, and carries no `@jsx` pragma of its
11137 * own: either silently points its JSX away from this factory, and a
11138 * `<Client>` tag written under another factory is not found when the
11139 * module's surface modules are read off its source.
11140 */
11141 const h: (
11142 tag: string | ((props: never) => RenderNode | null | undefined),
11143 props: Record<string, unknown> | null | undefined,
11144 ...children: unknown[]
11145 ) => RenderNode | null | undefined
11146
11147 /**
11148 * `<>...</>`: a column Box around the children.
11149 */
11150 const Fragment: (props: { children?: RenderNode[] }) => RenderElement
11151
11152 /**
11153 * JSX over the element table: every tag is a constructor from
11154 * `$.ui.resolve(e)` (`const { Box, Text } = $.ui.resolve(e)`), typed by
11155 * its props; there are no intrinsic (string) tags.
11156 */
11157 namespace JSX {
11158 type Element = RenderElement
11159 type Children = RenderChildren
11160 type ElementType = (props: never) => RenderNode | null | undefined
11161 interface IntrinsicElements {}
11162 interface ElementChildrenAttribute {
11163 children: unknown
11164 }
11165 interface IntrinsicAttributes {
11166 key?: string
11167 }
11168 }
11169
11170 interface AbortSignal {
11171 readonly aborted: boolean
11172 readonly reason: unknown
11173 throwIfAborted(): void
11174 addEventListener(
11175 type: 'abort',
11176 listener: () => void,
11177 options?: { once?: boolean },
11178 ): void
11179 removeEventListener(type: 'abort', listener: () => void): void
11180 }
11181 var AbortSignal: {
11182 prototype: AbortSignal
11183 abort(reason?: unknown): AbortSignal
11184 timeout(milliseconds: number): AbortSignal
11185 any(signals: AbortSignal[]): AbortSignal
11186 }
11187 interface AbortController {
11188 readonly signal: AbortSignal
11189 abort(reason?: unknown): void
11190 }
11191 var AbortController: {
11192 prototype: AbortController
11193 new (): AbortController
11194 }
11195 interface TextEncoder {
11196 readonly encoding: string
11197 encode(input?: string): Uint8Array
11198 }
11199 var TextEncoder: { prototype: TextEncoder; new (): TextEncoder }
11200 interface TextDecoder {
11201 readonly encoding: string
11202 decode(input?: ArrayBufferView | ArrayBuffer): string
11203 }
11204 var TextDecoder: { prototype: TextDecoder; new (label?: string): TextDecoder }
11205 interface URLSearchParams {
11206 append(name: string, value: string): void
11207 delete(name: string): void
11208 get(name: string): string | null
11209 getAll(name: string): string[]
11210 has(name: string): boolean
11211 set(name: string, value: string): void
11212 toString(): string
11213 forEach(callback: (value: string, key: string) => void): void
11214 }
11215 var URLSearchParams: {
11216 prototype: URLSearchParams
11217 new (init?: string | Record<string, string> | string[][]): URLSearchParams
11218 }
11219 interface URL {
11220 hash: string
11221 host: string
11222 hostname: string
11223 href: string
11224 readonly origin: string
11225 password: string
11226 pathname: string
11227 port: string
11228 protocol: string
11229 search: string
11230 readonly searchParams: URLSearchParams
11231 username: string
11232 toString(): string
11233 toJSON(): string
11234 }
11235 var URL: {
11236 prototype: URL
11237 new (url: string, base?: string | URL): URL
11238 canParse(url: string, base?: string): boolean
11239 }
11240 function atob(data: string): string
11241 function btoa(data: string): string
11242 function structuredClone<T>(value: T): T
11243 var crypto: {
11244 readonly subtle: {
11245 digest(
11246 algorithm: string | { name: string },
11247 data: ArrayBufferView | ArrayBuffer,
11248 ): Promise<ArrayBuffer>
11249 }
11250 randomUUID(): string
11251 getRandomValues<T extends ArrayBufferView>(array: T): T
11252 }
11253 var performance: { now(): number }
11254 }
11255}
11256
11257declare module 'claude-code/testing' {
11258 import type { Args } from 'claude-code';
11259 import type { Chunk } from 'claude-code';
11260 import type { ClientKeyEvent } from 'claude-code';
11261 import type { ClientPointerEvent } from 'claude-code';
11262 import type { Elements } from 'claude-code';
11263 import type { EventCalls } from 'claude-code';
11264 import type { EventName } from 'claude-code';
11265 import type { HookStream } from 'claude-code';
11266 import type { JsonValue } from 'claude-code';
11267 import type { On } from 'claude-code';
11268 import type { PressedLink } from 'claude-code';
11269 import type { Register } from 'claude-code';
11270 import type { RenderComponent } from 'claude-code';
11271 import type { RenderElement } from 'claude-code';
11272 import type { RenderPropsOf } from 'claude-code';
11273 import type { RenderSurface } from 'claude-code';
11274 import type { RenderViewport } from 'claude-code';
11275 import type { ResultOf } from 'claude-code';
11276 import type { StreamingEventName } from 'claude-code';
11277 import type { Tier } from 'claude-code';
11278 import type { UiInputArgument } from 'claude-code';
11279 import type { UiInputResult } from 'claude-code';
11280 import type { UiPressResult } from 'claude-code';
11281 import type { UiSelectResult } from 'claude-code';
11282
11283 /**
11284 * A value that matches by a rule inside `toEqual` and its kin
11285 * (`expect.any`, `expect.objectContaining`), known by its text in a failure.
11286 */
11287 export type AsymmetricMatcher = {
11288 readonly text: string;
11289 };
11290
11291 /**
11292 * The same checks on what a promise received settles with, each resolving
11293 * once the promise has settled and the check passed.
11294 */
11295 export type AsyncMatchers = {
11296 [K in keyof Matchers]: (...args: Parameters<Matchers[K]>) => Promise<void>;
11297 };
11298
11299 /**
11300 * Which `Client` of a mounted drawing an act or a read means, by the `key`
11301 * its element carries; optional while the drawing holds exactly one.
11302 */
11303 export type ClientScope = {
11304 in?: string;
11305 };
11306
11307 /**
11308 * A class, as `toThrow`, `toBeInstanceOf` and `expect.any` take it.
11309 */
11310 export type Constructor = abstract new (...args: never[]) => unknown;
11311
11312 /**
11313 * A group of tests: its name leads the title of each test declared inside,
11314 * and its body runs at once, while the file loads.
11315 *
11316 * @param name the group's name
11317 * @param body declares the group's tests
11318 */
11319 export const describe: (name: string, body: () => void) => void;
11320
11321 /**
11322 * The element each surface-dependent act of a mounted drawing reaches: a
11323 * handle carries the act only where the surface's table has the element.
11324 *
11325 * `input` needs `Input` and `select` needs `Select` (every surface but
11326 * mobile today); `key`, `pointer`, `post`, `advance` and `resize` reach a
11327 * `Client` (terminal and desktop today). The rest need nothing but a tree.
11328 */
11329 export type ElementOfAct = {
11330 input: 'Input';
11331 select: 'Select';
11332 key: 'Client';
11333 pointer: 'Client';
11334 post: 'Client';
11335 advance: 'Client';
11336 resize: 'Client';
11337 };
11338
11339 /**
11340 * What a mounted drawing's `find` and `findAll` match an element on, every
11341 * field given at once: its tag, its `key`, and the text it shows.
11342 *
11343 * `text` matches the element's whole shown text (string children, a Button
11344 * or Link's label, a Markdown's text, a Code's source, an Input's value):
11345 * a string by inclusion, a RegExp by test.
11346 *
11347 * @example
11348 * await ui.findAll({ type: 'Text', text: /overdue/, in: 'board' })
11349 */
11350 export type ElementQuery = {
11351 type?: string;
11352 key?: string;
11353 text?: string | RegExp;
11354 /**
11355 * Searches what this `Client`'s surface module drew (by the `Client`'s
11356 * key) instead of the plugin's own tree.
11357 */
11358 in?: string;
11359 };
11360
11361 /**
11362 * What a test holds as `$`, the engine's own: every call on it is made as
11363 * the REPL, the query loop and the render sites make theirs, over every plugin.
11364 *
11365 * `next.origin` is the engine, and the whole chain runs over the plugins
11366 * loaded. A tool call's `tool_use_id` is minted when left out; `$.ui.mount`
11367 * is a surface the test names drawing an instance, `$.ui.press` a press on it.
11368 */
11369 export type Engine = {
11370 [N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress & EngineMount : EngineNoun<N>;
11371 };
11372
11373 /**
11374 * One call on the engine's `$`: the event's input whole, as an engine call
11375 * site passes it, to its result, or for a streaming event to its stream.
11376 */
11377 export type EngineCall<E extends EventName> = E extends StreamingEventName ? (e: Args<E>) => HookStream<Chunk<E>, ResultOf[E]> : (e: Args<E>) => Promise<ResultOf[E]>;
11378
11379 /**
11380 * A surface drawing a component instance through the plugins, then driven
11381 * by key through a handle typed by that surface (Mounted).
11382 *
11383 * `ui.render` raised there for those props, the tree validated by that
11384 * table, its `Client`s running; the reads and `press` on every surface,
11385 * `input` where the table has `Input`, the `Client` acts where `Client`.
11386 *
11387 * @example
11388 * for (const surface of SURFACES) run(await $.ui.mount({ ...HINT, surface }))
11389 */
11390 export type EngineMount = {
11391 /**
11392 * Raises the plugins' drawing of the component on the surface and holds
11393 * it, as that surface showing the instance does.
11394 *
11395 * Resolves once the tree validated and every `Client` in it drew once.
11396 *
11397 * @param target whose elements, the surface, the component, its props,
11398 * the instance's requestId, and what the surface measured
11399 * @returns the mounted drawing; rejects when no `surface` (or an unknown
11400 * one) is named, when the surface cannot draw the tree the chain
11401 * returned (with the reason: an element its table lacks, a prop not
11402 * allowed), or when a `Client`'s module failed or drew nothing
11403 */
11404 mount: <P extends RenderSurface, C extends RenderComponent>(target: MountTarget<P, C>) => Promise<Mounted<P, C>>;
11405 };
11406
11407 /**
11408 * One noun of the engine's `$`: each of its events as the engine calls it,
11409 * `tool.call` and `ui.render` typed per tool and component, `ui.resolve` out.
11410 */
11411 export type EngineNoun<N extends keyof EventCalls> = {
11412 [V in EngineNounEvent<N>]: `${N}.${V}` extends 'tool.call' | 'ui.render' ? EventCalls[N][V] : EngineCall<`${N}.${V}` & EventName>;
11413 };
11414
11415 /**
11416 * The events of one noun a test's `$` carries: every one but `ui.resolve`,
11417 * which a render hook calls on its own `$` and the engine never raises.
11418 */
11419 export type EngineNounEvent<N extends keyof EventCalls> = Exclude<keyof EventCalls[N] & string, `${N}.resolve` extends 'ui.resolve' ? 'resolve' : never>;
11420
11421 /**
11422 * A surface pressing a Button a test rendered, or a Markdown's link: the
11423 * `ui.press` chain over every plugin hooked on it, its own closure last.
11424 */
11425 export type EnginePress = {
11426 /**
11427 * Presses the Button, as a click or its hotkey does; with `link`, the
11428 * Markdown's link, as a click on it does.
11429 *
11430 * `e.surface` is the surface of the drawing that holds it.
11431 *
11432 * @param target whose element, its key, the instance and surface when
11433 * several hold it, and for a Markdown the link
11434 * @returns what the chain settled on; rejects when no such element is
11435 * drawn, or several are and neither instance nor surface tells them apart
11436 */
11437 press: (target: PressTarget) => Promise<UiPressResult | undefined>;
11438 };
11439
11440 /**
11441 * The checks on a value (`expect(received)`), and with them the matchers
11442 * that stand inside an expected value (`expect.any(Number)`).
11443 */
11444 export type Expect = Expecting & Matching;
11445
11446 /**
11447 * Checks a value: `expect(received).toEqual(expected)` throws an
11448 * AssertionError naming both sides when it fails, a message given leading.
11449 *
11450 * `.not` negates; `.resolves` and `.rejects` check what a promise settles
11451 * with; `expect.any(Number)` and its kin stand inside an expected value.
11452 */
11453 export const expect: Expect;
11454
11455 /**
11456 * What `expect(received)` answers: the checks, their negation, and the
11457 * checks on what a promise received resolves or rejects with.
11458 */
11459 export type Expectation = Negatable<Matchers> & {
11460 /**
11461 * The checks on what the promise received resolves with; a rejection
11462 * fails them.
11463 */
11464 resolves: Negatable<AsyncMatchers>;
11465 /**
11466 * The checks on what the promise received rejects with; a resolution
11467 * fails them.
11468 */
11469 rejects: Negatable<AsyncMatchers>;
11470 };
11471
11472 /**
11473 * `expect(received, message?)`: the checks on a value, a message of the
11474 * test's own leading a failure's.
11475 */
11476 export type Expecting = (received: unknown, message?: string) => Expectation;
11477
11478 /**
11479 * One element of a mounted drawing as `find` returns it: the description
11480 * the plugin's hook (or a `Client`'s module) built, read as plain data.
11481 *
11482 * What every surface is handed to draw, not what any surface painted: the
11483 * same on the terminal, the desktop, VS Code and mobile.
11484 */
11485 export type FoundElement = {
11486 /**
11487 * The element's tag: `Box`, `Text`, `Button`, `Input`, `Client`, ...
11488 */
11489 type: string;
11490 /**
11491 * What its props carry as `key`, when they do.
11492 */
11493 key: string | undefined;
11494 /**
11495 * Its props, plain data: a Button's `label`, a Text's `color`, ...;
11496 * handlers never cross (a Button's `onPress` is not here).
11497 */
11498 props: Record<string, unknown>;
11499 /**
11500 * What it shows: its string children in document order and, for the
11501 * leaves that draw a prop as text, that prop (ElementQuery `text`).
11502 */
11503 text: string;
11504 /**
11505 * Its children as drawn: strings and element descriptions.
11506 */
11507 children: unknown[];
11508 };
11509
11510 /**
11511 * The checks `expect(received)` offers; each throws an AssertionError when
11512 * it fails, naming what was expected and what was received.
11513 */
11514 export type Matchers = {
11515 /**
11516 * Passes when received is the value, by `Object.is`.
11517 *
11518 * @param expected the value
11519 */
11520 toBe: (expected: unknown) => void;
11521 /**
11522 * Passes when received equals the value in structure, properties holding
11523 * undefined ignored; `expect.any` and its kin match inside it.
11524 *
11525 * @param expected the value
11526 */
11527 toEqual: (expected: unknown) => void;
11528 /**
11529 * As `toEqual`, but undefined properties and prototypes count.
11530 *
11531 * @param expected the value
11532 */
11533 toStrictEqual: (expected: unknown) => void;
11534 /**
11535 * Passes when received holds at least the object's properties, equal.
11536 *
11537 * @param expected the object
11538 */
11539 toMatchObject: (expected: object) => void;
11540 /**
11541 * Passes when a string received includes the item, or an iterable
11542 * received has an element that is it.
11543 *
11544 * @param item the substring or element
11545 */
11546 toContain: (item: unknown) => void;
11547 /**
11548 * Passes when an iterable received has an element equal to the item.
11549 *
11550 * @param item the element
11551 */
11552 toContainEqual: (item: unknown) => void;
11553 /**
11554 * Passes when received's `length` is the number.
11555 *
11556 * @param length the number
11557 */
11558 toHaveLength: (length: number) => void;
11559 /**
11560 * Passes when received holds a property at the path (`a.b`, or the keys
11561 * in order), equal to the value when one is given.
11562 *
11563 * @param path the property's path
11564 * @param value what it must equal, when given
11565 */
11566 toHaveProperty: (path: string | readonly string[], value?: unknown) => void;
11567 /**
11568 * Passes when received is undefined.
11569 */
11570 toBeUndefined: () => void;
11571 /**
11572 * Passes when received is anything but undefined.
11573 */
11574 toBeDefined: () => void;
11575 /**
11576 * Passes when received is null.
11577 */
11578 toBeNull: () => void;
11579 /**
11580 * Passes when received is truthy.
11581 */
11582 toBeTruthy: () => void;
11583 /**
11584 * Passes when received is falsy.
11585 */
11586 toBeFalsy: () => void;
11587 /**
11588 * Passes when received is NaN.
11589 */
11590 toBeNaN: () => void;
11591 /**
11592 * Passes when received is greater than the bound.
11593 *
11594 * @param bound the bound
11595 */
11596 toBeGreaterThan: (bound: number | bigint) => void;
11597 /**
11598 * Passes when received is the bound or greater.
11599 *
11600 * @param bound the bound
11601 */
11602 toBeGreaterThanOrEqual: (bound: number | bigint) => void;
11603 /**
11604 * Passes when received is less than the bound.
11605 *
11606 * @param bound the bound
11607 */
11608 toBeLessThan: (bound: number | bigint) => void;
11609 /**
11610 * Passes when received is the bound or less.
11611 *
11612 * @param bound the bound
11613 */
11614 toBeLessThanOrEqual: (bound: number | bigint) => void;
11615 /**
11616 * Passes when a string received includes the text, or the pattern matches
11617 * it.
11618 *
11619 * @param pattern the text or pattern
11620 */
11621 toMatch: (pattern: string | RegExp) => void;
11622 /**
11623 * Passes when a string received starts with the prefix.
11624 *
11625 * @param prefix the prefix
11626 */
11627 toStartWith: (prefix: string) => void;
11628 /**
11629 * Passes when a string received ends with the suffix.
11630 *
11631 * @param suffix the suffix
11632 */
11633 toEndWith: (suffix: string) => void;
11634 /**
11635 * Passes when received is an instance of the class.
11636 *
11637 * @param expected the class
11638 */
11639 toBeInstanceOf: (expected: Constructor) => void;
11640 /**
11641 * Passes when calling received throws (or, under `rejects`, the rejection
11642 * is) an error as described: by substring, pattern, class or message.
11643 *
11644 * @param expected the description; any throw passes without one
11645 */
11646 toThrow: (expected?: ThrowExpectation) => void;
11647 };
11648
11649 /**
11650 * The matchers that stand inside an expected value, each matching received
11651 * there by a rule instead of by equality.
11652 */
11653 export type Matching = {
11654 /**
11655 * Matches any instance of the class, a primitive by its wrapper
11656 * (`expect.any(Number)`).
11657 *
11658 * @param expected the class
11659 * @returns the matcher
11660 */
11661 any: (expected: Constructor) => AsymmetricMatcher;
11662 /**
11663 * Matches anything but null and undefined.
11664 *
11665 * @returns the matcher
11666 */
11667 anything: () => AsymmetricMatcher;
11668 /**
11669 * Matches a string that includes the text.
11670 *
11671 * @param text the substring
11672 * @returns the matcher
11673 */
11674 stringContaining: (text: string) => AsymmetricMatcher;
11675 /**
11676 * Matches a string the pattern matches.
11677 *
11678 * @param pattern the pattern, or the source of one
11679 * @returns the matcher
11680 */
11681 stringMatching: (pattern: string | RegExp) => AsymmetricMatcher;
11682 /**
11683 * Matches an object holding at least the shape's properties, equal.
11684 *
11685 * @param shape the properties
11686 * @returns the matcher
11687 */
11688 objectContaining: (shape: object) => AsymmetricMatcher;
11689 /**
11690 * Matches an array holding an element equal to each of the items.
11691 *
11692 * @param items the elements
11693 * @returns the matcher
11694 */
11695 arrayContaining: (items: readonly unknown[]) => AsymmetricMatcher;
11696 };
11697
11698 /**
11699 * The world beneath the plugins, mocked noun by noun: each member registers
11700 * hooks of the test's on `on`, visible where the test calls it.
11701 */
11702 export type Mock = {
11703 /**
11704 * Answers `$.clock` from a clock in memory that moves only when the test
11705 * moves it: `clock.now` reads it, and each wait is held.
11706 *
11707 * A held wait resolves when an advance crosses the time it is due, and is
11708 * dropped when its dispatch aborts; one held past a hook's budget (ten
11709 * seconds of real time) is let go, as a hook that overran.
11710 *
11711 * @param on the test's `on`
11712 * @param options where the clock starts (`now`, 0 when not given)
11713 * @returns the clock: its time, and the calls that move it
11714 */
11715 clock: (on: On, options?: MockClockOptions) => MockClock;
11716 /**
11717 * Answers `$.store` from a store in memory: `get`, `set`, `delete` and
11718 * `keys` over it, as the engine keeps a plugin's own.
11719 *
11720 * @param on the test's `on`
11721 * @param entries what the store holds at the start (nothing when not given)
11722 */
11723 store: (on: On, entries?: Readonly<Record<string, unknown>>) => void;
11724 /**
11725 * Answers `$.env.get` from a set of variables; one not listed is unset.
11726 *
11727 * @param on the test's `on`
11728 * @param variables the environment the plugins read
11729 */
11730 env: (on: On, variables: Readonly<Record<string, string>>) => void;
11731 };
11732
11733 /**
11734 * The world beneath the plugins, mocked noun by noun: `mock.clock`,
11735 * `mock.store` and `mock.env`.
11736 *
11737 * Each registers hooks of the test's on the `on` it is handed, visible where
11738 * the test calls it, and answers its noun from memory.
11739 */
11740 export const mock: Mock;
11741
11742 /**
11743 * The clock `mock.clock` hands back: the time its hooks answer, and the only
11744 * ways it moves.
11745 */
11746 export type MockClock = {
11747 /**
11748 * The time now, in milliseconds: what `$.clock.now()` resolves beneath the
11749 * plugins.
11750 *
11751 * @returns the time
11752 */
11753 now: () => number;
11754 /**
11755 * Moves the clock on, resolving each wait due on the way (`$.clock.sleep`,
11756 * `after`, `every`, this clock's `sleep`) in the order it comes due.
11757 *
11758 * The clock reads each wait's time as it resolves, and what one started
11759 * runs before the next resolves.
11760 *
11761 * @param ms how far to move, in milliseconds
11762 * @returns resolves once the clock is there and the event loop settled
11763 */
11764 advance: (ms: number) => Promise<void>;
11765 /**
11766 * Moves the clock to a time at or past now, as `advance` would.
11767 *
11768 * @param ms the time, in milliseconds
11769 * @returns resolves once the clock is there and the event loop settled
11770 */
11771 set: (ms: number) => Promise<void>;
11772 /**
11773 * Lets what is already under way run as far as it can without the clock
11774 * moving: every wait due now resolves and the event loop settles.
11775 *
11776 * The same as `advance(0)`; the name for the step between starting a
11777 * dispatch unawaited and looking at what it did.
11778 *
11779 * @returns resolves once the event loop settled, the time where it was
11780 */
11781 settle: () => Promise<void>;
11782 /**
11783 * Resolves once the clock has moved this far past now: how a hook of the
11784 * test's answers late.
11785 *
11786 * @param ms how far, in milliseconds
11787 * @returns resolves when an advance crosses that time
11788 */
11789 sleep: (ms: number) => Promise<void>;
11790 };
11791
11792 /**
11793 * Where a mocked clock starts: `now`, in milliseconds (0 when not given).
11794 */
11795 export type MockClockOptions = {
11796 now?: number;
11797 };
11798
11799 /**
11800 * A drawing of component `C` the test mounted on surface `P`: reads over its
11801 * description, acts on its elements by key, `Client` acts where `P` has one.
11802 *
11803 * Narrowed by the `surface` the test passed, as `e.surface` narrows
11804 * `$.ui.resolve(e)`: no `input` on `mobile`, no `key` on `vscode`, whose
11805 * tables (Elements) lack `Input` and `Client`; over a union, their meet.
11806 */
11807 export type Mounted<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
11808 [K in keyof MountedMembers<P, C> as K extends keyof ElementOfAct ? ElementOfAct[K] extends keyof Elements[P] ? K : never : K]: MountedMembers<P, C>[K];
11809 };
11810
11811 /**
11812 * Every member a mounted drawing of component `C` can have; `Mounted<P, C>`
11813 * keeps the ones surface `P` has the element for (ElementOfAct).
11814 *
11815 * Each act resolves once the loop settled and what a plugin invalidated
11816 * was drawn again. The kit exercises the mod (its hooks, its description
11817 * under the surface's rules, its `Client` modules), never a surface's paint.
11818 */
11819 export type MountedMembers<P extends RenderSurface, C extends RenderComponent = RenderComponent> = {
11820 /**
11821 * Where this drawing is, as the test named it.
11822 */
11823 readonly surface: P;
11824 /**
11825 * The tree as last drawn: what the plugins' `ui.render` chain returned
11826 * for this instance, validated by the surface's table, as plain data.
11827 *
11828 * With `in`, what that `Client`'s surface module last drew instead.
11829 *
11830 * @param scope `{ in }`: a `Client`'s key, to read its module's tree
11831 * @returns the tree; rejects with the refusal when the surface could not
11832 * draw what the chain returned, or with a `Client`'s fault line
11833 * @example
11834 * expect(await ui.drawn()).toMatchObject({ type: 'Box' })
11835 */
11836 drawn: (scope?: ClientScope) => Promise<RenderElement>;
11837 /**
11838 * The first element matching the query, outermost first in document
11839 * order, or undefined.
11840 *
11841 * @param query tag, key and shown text to match; `in` to search a Client
11842 * @returns the element's description, or undefined when none matches
11843 * @example
11844 * expect((await ui.find({ key: 'count' }))?.text).toBe('3 notes')
11845 */
11846 find: (query: ElementQuery) => Promise<FoundElement | undefined>;
11847 /**
11848 * Every element matching the query, in document order.
11849 *
11850 * @param query tag, key and shown text to match; `in` to search a Client
11851 * @returns the matching elements' descriptions
11852 * @example
11853 * expect(await ui.findAll({ type: 'Button' })).toHaveLength(2)
11854 */
11855 findAll: (query: ElementQuery) => Promise<FoundElement[]>;
11856 /**
11857 * Presses the Button keyed `key`, as the person activating it on this
11858 * surface does: the `ui.press` chain, the Button's own `onPress` last.
11859 *
11860 * `e.surface` is this drawing's. With `link`, presses that link of the
11861 * Markdown keyed `key` instead. A Button a `Client`'s module drew is
11862 * pressed the same way, by its key.
11863 *
11864 * @param target the key; another plugin's name to press its Button; a link
11865 * @returns what the chain settled on
11866 * @example
11867 * await ui.press({ key: 'save' })
11868 */
11869 press: (target: MountPressTarget) => Promise<UiPressResult | undefined>;
11870 /**
11871 * Types into the Input keyed `key`: the `ui.input` chain with the text as
11872 * `e.value`, the Input's own handler last.
11873 *
11874 * `kind` `submit` (the default) is Enter with that text, `change` an edit
11875 * that leaves it in the field.
11876 *
11877 * @param target the key and the text; `kind`; another plugin's name
11878 * @returns what the chain settled on
11879 * @example
11880 * await ui.input({ key: 'title', text: 'groceries' })
11881 */
11882 input: (target: MountInputTarget) => Promise<UiInputResult | undefined>;
11883 /**
11884 * Picks `value` in the Select keyed `key`: the `ui.select` chain, the
11885 * Select's own `onSelect` last.
11886 *
11887 * @param target the key and the option's value; another plugin's name
11888 * @returns what the chain settled on
11889 * @example
11890 * await ui.select({ key: 'sort', value: 'date' })
11891 */
11892 select: (target: MountSelectTarget) => Promise<UiSelectResult | undefined>;
11893 /**
11894 * Hands a `Client`'s `onKey` listener one key, as a key pressed while
11895 * its region has the focus does.
11896 *
11897 * `in` names the `Client` by key; optional when the drawing holds one.
11898 *
11899 * @param event the key (`{ key: 'right' }`, `{ key: 'a', ctrl: true }`)
11900 * @example
11901 * await ui.key({ key: 'return', in: 'board' })
11902 */
11903 key: (event: MountKeyEvent) => Promise<void>;
11904 /**
11905 * Hands a `Client`'s `onPointer` listener one event, in the cells of its
11906 * region as every surface that draws a `Client` reports them.
11907 *
11908 * @param event the event (`{ type: 'down', x: 3, y: 0, button: 'left' }`)
11909 * @example
11910 * await ui.pointer({ type: 'down', x: 2, y: 0, button: 'left' })
11911 */
11912 pointer: (event: MountPointerEvent) => Promise<void>;
11913 /**
11914 * Posts as a `Client`'s own `surface.post(data)` does: the plugin's
11915 * `ui.message` hooks run with `e.data`, `e.surface` this drawing's.
11916 *
11917 * A `{ props }` they answer reaches the instance, which redraws with
11918 * its state kept.
11919 *
11920 * @param data plain data (JsonValue)
11921 * @param scope `{ in }`: which `Client`, when the drawing holds several
11922 * @example
11923 * await ui.post({ pick: 2 })
11924 */
11925 post: (data: JsonValue, scope?: ClientScope) => Promise<void>;
11926 /**
11927 * Moves the drawing's frame clock on: each `surface.every(ms, fn)` timer
11928 * of its `Client`s fires at every interval of its own the move crosses.
11929 *
11930 * @param ms how far, in milliseconds
11931 * @example
11932 * await ui.advance(250)
11933 */
11934 advance: (ms: number) => Promise<void>;
11935 /**
11936 * Lays a `Client`'s region out at a size, as the surface measuring it
11937 * does: what its module reads as `surface.columns` and `surface.rows`.
11938 *
11939 * @param size cells across and down; `in`: which `Client`
11940 * @example
11941 * await ui.resize({ columns: 40, rows: 3 })
11942 */
11943 resize: (size: MountResizeTarget) => Promise<void>;
11944 /**
11945 * Draws the instance again, as the engine does when its props change (a
11946 * tool row's output arrived): the `ui.render` chain with the next props.
11947 *
11948 * A plugin's own `$.ui.invalidate` needs no call: the drawing follows it
11949 * before the next read.
11950 *
11951 * @param props the component's next props; the current ones when absent
11952 * @example
11953 * await ui.redraw({ ...TOOL_ROW, isRunning: false, output: 'done' })
11954 */
11955 redraw: (props?: RenderPropsOf[C]) => Promise<void>;
11956 /**
11957 * Lets the drawing go, as the surface dropping the instance does: its
11958 * `Client`s and their timers end. Later acts on the handle reject.
11959 *
11960 * @example
11961 * await ui.unmount()
11962 */
11963 unmount: () => Promise<void>;
11964 };
11965
11966 /**
11967 * What a mounted drawing's `input` takes: the Input's key, the text, which
11968 * of the two inputs it is (`submit` when unsaid), another plugin's name.
11969 */
11970 export type MountInputTarget = {
11971 key: string;
11972 text: string;
11973 kind?: UiInputArgument['kind'];
11974 plugin?: string;
11975 };
11976
11977 /**
11978 * What a mounted drawing's `key` takes: the key as a `Client`'s `onKey`
11979 * listener receives it (ClientKeyEvent), and which `Client` when several.
11980 */
11981 export type MountKeyEvent = ClientKeyEvent & ClientScope;
11982
11983 /**
11984 * What a mounted drawing's `pointer` takes: the event as a `Client`'s
11985 * `onPointer` listener receives it, in its region's cells, and which one.
11986 */
11987 export type MountPointerEvent = ClientPointerEvent & ClientScope;
11988
11989 /**
11990 * What a mounted drawing's `press` takes: the Button's key, another
11991 * plugin's name when the Button is not the mounted plugin's, a link.
11992 */
11993 export type MountPressTarget = {
11994 key: string;
11995 plugin?: string;
11996 /**
11997 * Presses this link of the Markdown keyed `key` instead of a Button.
11998 */
11999 link?: PressedLink;
12000 };
12001
12002 /**
12003 * What a mounted drawing's `resize` takes: a `Client` region's size in
12004 * cells, as the surface measuring it hands it, and which `Client`.
12005 */
12006 export type MountResizeTarget = {
12007 columns: number;
12008 rows: number;
12009 in?: string;
12010 };
12011
12012 /**
12013 * What a mounted drawing's `select` takes: the Select's key, the picked
12014 * option's value, another plugin's name when the Select is not its own.
12015 */
12016 export type MountSelectTarget = {
12017 key: string;
12018 value: string;
12019 plugin?: string;
12020 };
12021
12022 /**
12023 * What `$.ui.mount` takes: whose elements the test will act on, the surface
12024 * that draws, and the component instance the engine asks the plugins for.
12025 *
12026 * The envelope a `ui.render` hook sees as `e` (`surface`, `component`,
12027 * `requestId`, `viewport`, `props`) plus `plugin`. `surface` is never
12028 * defaulted: one body run over several surfaces is what shows independence.
12029 *
12030 * @example
12031 * $.ui.mount({ plugin: 'notes', surface, component: 'Pane', props: PANE })
12032 */
12033 export type MountTarget<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
12034 /**
12035 * Whose elements the handle's acts address by bare `key`: the plugin
12036 * under test, usually. An act names another plugin to reach its element.
12037 */
12038 plugin: string;
12039 /**
12040 * What draws: its element table validates every tree the plugins
12041 * return, and every dispatch the handle raises carries it as `e.surface`.
12042 *
12043 * One of `terminal`, `desktop`, `vscode`, `mobile`.
12044 */
12045 surface: P;
12046 /**
12047 * Which component the engine asks the plugins to draw (`Pane`,
12048 * `AbovePrompt`, `ToolUse`, ...): what a `ui.render` matcher narrows on.
12049 */
12050 component: C;
12051 /**
12052 * The component's props, what the hook reads as `e.props`.
12053 */
12054 props: RenderPropsOf[C];
12055 /**
12056 * The instance drawn (a pane's id, a tool row's tool_use_id); one is
12057 * minted when absent. Two mounts of one component are two instances.
12058 */
12059 requestId?: string;
12060 /**
12061 * What the surface measured, as the hook reads it under `e.viewport`;
12062 * absent when the surface has not measured, as on `e`.
12063 *
12064 * Cells across and down in the surface's monospace metric and whether it
12065 * docks a pane. A `Client` in the drawing starts laid out at this size
12066 * (0 by 0 when absent) until the handle's `resize` lays its region out.
12067 */
12068 viewport?: RenderViewport;
12069 };
12070
12071 /**
12072 * A set of checks and, under `not`, the same set passing where they fail.
12073 */
12074 export type Negatable<M> = M & {
12075 /**
12076 * The checks negated.
12077 */
12078 not: M;
12079 };
12080
12081 /**
12082 * Written inline in a test and loaded as a plugin folder is: its name, the
12083 * tier it loads in (`user` when not given), and its hooks module's `register`.
12084 *
12085 * `register` is written `register(on) { ... }` and is self-contained, as a
12086 * module's is: it closes over nothing of the test file.
12087 */
12088 export type Plugin = {
12089 name: string;
12090 tier?: PluginTier;
12091 register: Register;
12092 };
12093
12094 /**
12095 * A tier a plugin loads in: every tier but the engine's own.
12096 */
12097 export type PluginTier = Exclude<Tier, 'core'>;
12098
12099 /**
12100 * What `$.ui.press` takes: the plugin whose `ui.render` hook drew the element,
12101 * the `key` it gave it, the instance and surface when several, a `link`.
12102 */
12103 export type PressTarget = {
12104 plugin: string;
12105 key: string;
12106 /**
12107 * Which instance holds it, when the plugin drew the key in several.
12108 */
12109 requestId?: string;
12110 /**
12111 * Which surface's drawing, when the key is drawn on more than one; the
12112 * press carries the surface of the drawing it lands in either way.
12113 */
12114 surface?: RenderSurface;
12115 /**
12116 * For a Markdown answering its links: which of them the press lands on.
12117 */
12118 link?: PressedLink;
12119 };
12120
12121 /**
12122 * One test: it passes when its body returns or resolves, and fails when it
12123 * throws, rejects or outlasts its time (5000 ms, or `timeoutMs`).
12124 *
12125 * The body gets the engine's `$` and an `on` whose hooks sit beneath every
12126 * plugin; `plugins` load inline plugins beside the one under test. A failure
12127 * carries what the engine reported meanwhile: each hook it skipped, and why.
12128 *
12129 * @param name the test's name, led in its title by the describes around it
12130 * @param rest the body, `($, on) => ...`, or the options then the body
12131 */
12132 export const test: (name: string, ...rest: TestRest) => void;
12133
12134 /**
12135 * A test: the engine's `$`, and `on`, a plugin's registrar, whose hooks sit
12136 * beneath every plugin; beneath them the bottom hook throws, naming its event.
12137 *
12138 * The plugins load at the test's first call on `$`, so a test registers its
12139 * hooks before it, as a module registers its own in `register()`.
12140 */
12141 export type TestBody = ($: Engine, on: On) => unknown;
12142
12143 /**
12144 * What `test` takes beside its name: the inline plugins it loads beside the
12145 * one under test, and how long it may run (5000 ms when not given).
12146 */
12147 export type TestOptions = {
12148 plugins?: readonly Plugin[];
12149 timeoutMs?: number;
12150 };
12151
12152 /**
12153 * What follows a test's name: its body, or its options then its body.
12154 */
12155 export type TestRest = readonly [body: TestBody] | readonly [options: TestOptions, body: TestBody];
12156
12157 /**
12158 * What `toThrow` compares the thrown error with: a substring or pattern of
12159 * its message, its class, a value carrying the whole message, or nothing.
12160 */
12161 export type ThrowExpectation = string | RegExp | Constructor | WithMessage;
12162
12163 /**
12164 * Says which tier the plugin under test loads in, once, at the top of the
12165 * file: `prepend`, `user` (when unsaid), `append` or `builtin`.
12166 *
12167 * @param tier the tier
12168 */
12169 export const tier: (tier: PluginTier) => void;
12170
12171 /**
12172 * An error-like value `toThrow` compares by its whole message.
12173 */
12174 export type WithMessage = {
12175 message: string;
12176 };
12177}
12178
12179// The inputs of the built-in tools this build has, from each tool's
12180// input schema. Merges into ToolCallInput (BuiltinToolInputs) so
12181// `e.tool === "Bash"` narrows to the tool's arguments.
12182declare module 'claude-code' {
12183 interface BuiltinToolInputs {
12184 Agent: {
12185 /** A short (3-5 word) description of the task */
12186 description: string
12187 /** The task for the agent to perform */
12188 prompt: string
12189 /** The type of specialized agent to use for this task */
12190 subagent_type?: string
12191 /** 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. */
12192 model?: "sonnet" | "opus" | "haiku" | "fable"
12193 /** 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. */
12194 run_in_background?: boolean
12195 /** Name for the spawned agent. Makes it addressable via SendMessage({to: name}) while running. */
12196 name?: string
12197 /** Deprecated; ignored. The session has a single implicit team. */
12198 team_name?: string
12199 /** Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it. */
12200 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"
12201 /** 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). */
12202 isolation?: "worktree" | "remote"
12203 }
12204 Bash: {
12205 /** The command to execute */
12206 command: string
12207 /** Optional timeout in milliseconds (max 600000) */
12208 timeout?: number
12209 /** 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" */
12210 description?: string
12211 /** Set to true to run this command in the background. */
12212 run_in_background?: boolean
12213 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
12214 dangerouslyDisableSandbox?: boolean
12215 }
12216 CronCreate: {
12217 /** 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). */
12218 cron: string
12219 /** The prompt to enqueue at each fire time. */
12220 prompt: string
12221 /** 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. */
12222 recurring?: boolean
12223 /** 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. */
12224 durable?: boolean
12225 }
12226 CronDelete: {
12227 /** Job ID returned by CronCreate. */
12228 id: string
12229 }
12230 CronList: {}
12231 Edit: {
12232 /** The absolute path to the file to modify */
12233 file_path: string
12234 /** The text to replace */
12235 old_string: string
12236 /** The text to replace it with (must be different from old_string) */
12237 new_string: string
12238 /** Replace all occurrences of old_string (default false) */
12239 replace_all?: boolean
12240 }
12241 EnterWorktree: {
12242 /** 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`. */
12243 name?: string
12244 /** 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`. */
12245 path?: string
12246 }
12247 ExitWorktree: {
12248 /** "keep" leaves the worktree and branch on disk; "remove" deletes both. */
12249 action: "keep" | "remove"
12250 /** Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise. */
12251 discard_changes?: boolean
12252 }
12253 ListAgents: {
12254 /** Not available in this build; leave unset. */
12255 channel?: string
12256 /** Not available in this build; leave unset. */
12257 q?: string
12258 }
12259 NotebookEdit: {
12260 /** The absolute path to the Jupyter notebook file to edit (must be absolute, not relative) */
12261 notebook_path: string
12262 /** 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. */
12263 cell_id?: string
12264 /** The new source for the cell */
12265 new_source: string
12266 /** 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. */
12267 cell_type?: "code" | "markdown"
12268 /** The type of edit to make (replace, insert, delete). Defaults to replace. */
12269 edit_mode?: "replace" | "insert" | "delete"
12270 }
12271 PowerShell: {
12272 /** The PowerShell command to execute */
12273 command: string
12274 /** Optional timeout in milliseconds (max 600000) */
12275 timeout?: number
12276 /** Clear, concise description of what this command does in active voice. */
12277 description?: string
12278 /** Set to true to run this command in the background. */
12279 run_in_background?: boolean
12280 /** Set this to true to dangerously override sandbox mode and run commands without sandboxing. */
12281 dangerouslyDisableSandbox?: boolean
12282 }
12283 Read: {
12284 /** The absolute path to the file to read */
12285 file_path: string
12286 /** The line number to start reading from. Only provide if the file is too large to read at once */
12287 offset?: number
12288 /** The number of lines to read. Only provide if the file is too large to read at once. */
12289 limit?: number
12290 /** Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum 20 pages per request. */
12291 pages?: string
12292 }
12293 ReportFindings: {
12294 /** Effort level the review ran at */
12295 level?: "low" | "medium" | "high" | "xhigh" | "max"
12296 /** Verified findings, most-severe first; empty if none survived */
12297 findings: Array<{
12298 /** Repo-relative path of the file the finding is in */
12299 file: string
12300 /** 1-indexed line the finding anchors to */
12301 line?: number
12302 /** One-sentence statement of the defect */
12303 summary: string
12304 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
12305 short_summary?: string
12306 /** Concrete inputs/state → wrong output/crash */
12307 failure_scenario: string
12308 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
12309 category?: string
12310 /** Set when a verify pass ran; absent on inline-only reviews */
12311 verdict?: "CONFIRMED" | "PLAUSIBLE"
12312 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
12313 outcome?: "fixed" | "skipped" | "no_change_needed"
12314 }>
12315 }
12316 ScheduleWakeup: {
12317 /** Seconds from now to wake up. Clamped to [60, 3600] by the runtime. Required unless `stop` is true. */
12318 delaySeconds?: number
12319 /** One short sentence explaining the chosen delay. Goes to telemetry and is shown to the user. Be specific. Required unless `stop` is true. */
12320 reason?: string
12321 /** 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. */
12322 prompt?: string
12323 /** 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. */
12324 stop?: boolean
12325 /** 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. */
12326 noop?: boolean
12327 }
12328 SendMessage: {
12329 /** 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 */
12330 to: unknown & unknown
12331 /** 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. */
12332 summary?: string
12333 /** 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. */
12334 message: string
12335 /** 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. */
12336 notify_when_idle?: boolean
12337 }
12338 Skill: {
12339 /** The name of a skill from the available-skills list. Do not guess names. */
12340 skill: string
12341 /** Optional arguments for the skill */
12342 args?: string
12343 }
12344 TaskOutput: {
12345 /** The task ID to get output from */
12346 task_id: string
12347 /** Whether to wait for completion */
12348 block: boolean
12349 /** Max wait time in ms */
12350 timeout: number
12351 }
12352 TaskStop: {
12353 /** The ID of the background task to stop. Agent-team teammates and named background agents are also accepted by agent ID or name. */
12354 task_id?: string
12355 /** Deprecated: use task_id instead */
12356 shell_id?: string
12357 }
12358 ToolSearch: {
12359 /** Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search. */
12360 query: string
12361 /** Maximum number of results to return (default: 5) */
12362 max_results: number
12363 }
12364 WebFetch: {
12365 /** The URL to fetch content from */
12366 url: string
12367 /** The prompt to run on the fetched content */
12368 prompt: string
12369 }
12370 WebSearch: {
12371 /** The search query to use */
12372 query: string
12373 /** Only include search results from these domains */
12374 allowed_domains?: string[]
12375 /** Never include search results from these domains */
12376 blocked_domains?: string[]
12377 }
12378 Workflow: {
12379 /** 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(). */
12380 script?: string
12381 /** Name of a predefined workflow (built-in or from .claude/workflows/). Resolves to a self-contained script. */
12382 name?: string
12383 /** Ignored — set the workflow description in the script's `meta` block. */
12384 description?: string
12385 /** Ignored — set the workflow title in the script's `meta` block. */
12386 title?: string
12387 /** 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). */
12388 args?: unknown
12389 /** 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`. */
12390 scriptPath?: string
12391 /** 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. */
12392 resumeFromRunId?: string
12393 }
12394 Write: {
12395 /** The absolute path to the file to write (must be absolute, not relative) */
12396 file_path: string
12397 /** The content to write to the file */
12398 content: string
12399 }
12400 }
12401}
12402
12403// The structured results of the same tools, from each tool's output
12404// schema. Merges into ToolCallResult (BuiltinToolResults) so after
12405// `e.tool === "Bash"` the `result` of `next(e)` is the tool's record.
12406declare module 'claude-code' {
12407 interface BuiltinToolResults {
12408 Agent: {
12409 agentId: string
12410 /** @internal Count of leading harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
12411 harnessNoteCount?: number
12412 /** @internal Count of trailing harness-authored content blocks (hand-back provenance bookkeeping; not a stable consumer field) */
12413 harnessTailCount?: number
12414 /** @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 */
12415 harnessSectionHash?: string
12416 agentType?: string
12417 /** @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) */
12418 handback?: "send" | "flagged" | "withheld"
12419 content: Array<{
12420 type: "text"
12421 text: string
12422 citations?: unknown[] | null
12423 }>
12424 resolvedModel?: string
12425 modelsUsed?: string[]
12426 totalToolUseCount: number
12427 totalDurationMs: number
12428 totalTokens: number
12429 usage: {
12430 input_tokens: number
12431 output_tokens: number
12432 cache_creation_input_tokens: number | null
12433 cache_read_input_tokens: number | null
12434 server_tool_use: {
12435 web_search_requests: number
12436 web_fetch_requests: number
12437 } | null
12438 service_tier: string | null
12439 cache_creation: {
12440 ephemeral_1h_input_tokens: number
12441 ephemeral_5m_input_tokens: number
12442 } | null
12443 inference_geo?: string | null
12444 speed?: string | null
12445 iterations?: unknown
12446 output_tokens_details?: {
12447 thinking_tokens?: number | null
12448 } | null
12449 }
12450 toolStats?: {
12451 readCount: number
12452 searchCount: number
12453 bashCount: number
12454 editFileCount: number
12455 linesAdded: number
12456 linesRemoved: number
12457 otherToolCount: number
12458 frameCount?: number
12459 }
12460 status: "completed"
12461 prompt: string
12462 worktreePath?: string
12463 worktreeBranch?: string
12464 } | {
12465 status: "async_launched"
12466 isAsync?: true
12467 /** The ID of the async agent */
12468 agentId: string
12469 /** The description of the task */
12470 description: string
12471 /** Model in use at the backgrounding transition (a pre-background swap is reflected here) */
12472 resolvedModel?: string
12473 /** Ordered distinct models used before backgrounding (length > 1 means a mid-run swap) */
12474 modelsUsed?: string[]
12475 /** The prompt for the agent */
12476 prompt: string
12477 /** Path to the output file for checking agent progress */
12478 outputFile: string
12479 /** Whether the calling agent has Read/Bash tools to check progress */
12480 canReadOutputFile?: boolean
12481 } | {
12482 status: "remote_launched"
12483 /** The ID of the remote agent task */
12484 taskId: string
12485 /** The URL of the cloud session */
12486 sessionUrl: string
12487 /** The description of the task */
12488 description: string
12489 /** The prompt for the agent */
12490 prompt: string
12491 /** Path to the output file for checking agent progress */
12492 outputFile: string
12493 }
12494 Bash: {
12495 /** The standard output of the command */
12496 stdout: string
12497 /** The standard error output of the command */
12498 stderr: string
12499 /** Path to raw output file for large MCP tool outputs */
12500 rawOutputPath?: string
12501 /** Whether the command was interrupted */
12502 interrupted: boolean
12503 /** Flag to indicate if stdout contains image data */
12504 isImage?: boolean
12505 /** ID of the background task if command is running in background */
12506 backgroundTaskId?: string
12507 /** True if the user manually backgrounded the command with Ctrl+B */
12508 backgroundedByUser?: boolean
12509 /** @internal True if a plugin's turn abort moved the running command to the background */
12510 backgroundedByTurnAbort?: boolean
12511 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
12512 backgroundedToDeliverMessage?: boolean
12513 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
12514 timedOutAfterMs?: number
12515 /** Model-facing note that the session cwd was not changed by a backgrounded command containing a directory-change builtin (cd/pushd/popd/chdir) */
12516 backgroundCwdHint?: string
12517 /** 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) */
12518 backgroundEndsWithFinalResponse?: true
12519 /** Flag to indicate if sandbox mode was overridden */
12520 dangerouslyDisableSandbox?: boolean
12521 /** Semantic interpretation for non-error exit codes with special meaning */
12522 returnCodeInterpretation?: string
12523 /** Whether the command is expected to produce no output on success */
12524 noOutputExpected?: boolean
12525 /** Structured content blocks */
12526 structuredContent?: unknown[]
12527 /** Path to the persisted full output in tool-results dir (set when output is too large for inline) */
12528 persistedOutputPath?: string
12529 /** Total size of the output in bytes (set when output is too large for inline) */
12530 persistedOutputSize?: number
12531 /** Model-facing note listing readFileState entries whose mtime bumped during this command (set when WRITE_COMMAND_MARKERS matches) */
12532 staleReadFileStateHint?: string
12533 /** Model-facing system-reminder appended when a gh command reports a GitHub API rate-limit error */
12534 ghRateLimitHint?: string
12535 /** 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. */
12536 gitOperation?: {
12537 commit?: {
12538 sha: string
12539 kind: "committed" | "amended" | "cherry-picked"
12540 branch?: string
12541 }
12542 push?: {
12543 branch: string
12544 }
12545 branch?: {
12546 ref: string
12547 action: "merged" | "rebased"
12548 }
12549 pr?: {
12550 number: number
12551 url?: string
12552 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
12553 }
12554 }
12555 /** @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. */
12556 bashEditDiff?: {
12557 files: {
12558 filePath: string
12559 hunks: {
12560 oldStart: number
12561 oldLines: number
12562 newStart: number
12563 newLines: number
12564 lines: string[]
12565 }[]
12566 created?: true
12567 deleted?: true
12568 }[]
12569 moreFiles: number
12570 changedFiles?: string[]
12571 unavailable?: true
12572 skipped?: true
12573 shared?: true
12574 }
12575 }
12576 CronCreate: {
12577 id: string
12578 humanSchedule: string
12579 recurring: boolean
12580 durable?: boolean
12581 }
12582 CronDelete: {
12583 id: string
12584 }
12585 CronList: {
12586 jobs: {
12587 id: string
12588 cron: string
12589 humanSchedule: string
12590 prompt: string
12591 recurring?: boolean
12592 durable?: boolean
12593 }[]
12594 }
12595 Edit: {
12596 /** The file path that was edited */
12597 filePath: string
12598 /** The original string that was replaced */
12599 oldString: string
12600 /** The new string that replaced it */
12601 newString: string
12602 /** The original file contents before editing */
12603 originalFile: string | null
12604 /** Diff patch showing the changes */
12605 structuredPatch: {
12606 oldStart: number
12607 oldLines: number
12608 newStart: number
12609 newLines: number
12610 lines: string[]
12611 }[]
12612 /** Whether the user modified the proposed changes */
12613 userModified: boolean
12614 /** Whether all occurrences were replaced */
12615 replaceAll: boolean
12616 gitDiff?: {
12617 filename: string
12618 status: "modified" | "added"
12619 additions: number
12620 deletions: number
12621 changes: number
12622 patch: string
12623 /** GitHub owner/repo when available */
12624 repository?: string | null
12625 }
12626 /** True when the edit was held for the machine owner to review instead of written; the file is unchanged */
12627 staged?: boolean
12628 }
12629 EnterWorktree: {
12630 worktreePath: string
12631 worktreeBranch?: string
12632 message: string
12633 }
12634 ExitWorktree: {
12635 action: "keep" | "remove"
12636 originalCwd: string
12637 worktreePath: string
12638 worktreeBranch?: string
12639 tmuxSessionName?: string
12640 discardedFiles?: number
12641 discardedCommits?: number
12642 message: string
12643 }
12644 ListAgents: {
12645 /** Formatted list of reachable agents */
12646 listing: string
12647 }
12648 NotebookEdit: {
12649 /** The new source code that was written to the cell */
12650 new_source: string
12651 /** The previous cell source (replace/delete only). Enables cell-relative diff rendering without re-reading the notebook. */
12652 old_source?: string
12653 /** The ID of the cell that was edited */
12654 cell_id?: string
12655 /** The type of the cell */
12656 cell_type: "code" | "markdown"
12657 /** The programming language of the notebook */
12658 language: string
12659 /** The edit mode that was used */
12660 edit_mode: string
12661 /** Error message if the operation failed */
12662 error?: string
12663 /** The path to the notebook file */
12664 notebook_path: string
12665 /** The original notebook content before modification */
12666 original_file: string
12667 /** The updated notebook content after modification */
12668 updated_file: string
12669 }
12670 PowerShell: {
12671 /** The standard output of the command */
12672 stdout: string
12673 /** The standard error output of the command */
12674 stderr: string
12675 /** Whether the command was interrupted */
12676 interrupted: boolean
12677 /** Semantic interpretation for non-error exit codes with special meaning */
12678 returnCodeInterpretation?: string
12679 /** Flag to indicate if stdout contains image data */
12680 isImage?: boolean
12681 /** Path to persisted full output when too large for inline */
12682 persistedOutputPath?: string
12683 /** Total output size in bytes when persisted */
12684 persistedOutputSize?: number
12685 /** ID of the background task if command is running in background */
12686 backgroundTaskId?: string
12687 /** True if the user manually backgrounded the command with Ctrl+B */
12688 backgroundedByUser?: boolean
12689 /** @internal True if a plugin's turn abort moved the running command to the background */
12690 backgroundedByTurnAbort?: boolean
12691 /** @internal True if the command was moved to the background so a message queued for the model could reach it */
12692 backgroundedToDeliverMessage?: boolean
12693 /** Set when the command hit its timeout and was auto-backgrounded; the timeout value in ms */
12694 timedOutAfterMs?: number
12695 /** 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) */
12696 backgroundEndsWithFinalResponse?: true
12697 /** 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. */
12698 gitOperation?: {
12699 commit?: {
12700 sha: string
12701 kind: "committed" | "amended" | "cherry-picked"
12702 branch?: string
12703 }
12704 push?: {
12705 branch: string
12706 }
12707 branch?: {
12708 ref: string
12709 action: "merged" | "rebased"
12710 }
12711 pr?: {
12712 number: number
12713 url?: string
12714 action: "created" | "edited" | "merged" | "commented" | "closed" | "reopened" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled"
12715 }
12716 }
12717 }
12718 Read: {
12719 type: "text"
12720 file: {
12721 /** The path to the file that was read */
12722 filePath: string
12723 /** The content of the file */
12724 content: string
12725 /** Number of lines in the returned content */
12726 numLines: number
12727 /** The starting line number */
12728 startLine: number
12729 /** Total number of lines in the file */
12730 totalLines: number
12731 /** 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). */
12732 truncatedByTokenCap?: boolean
12733 }
12734 /** Set when this Read completed a saved Artifact source file: the Artifact and the version of it that now counts as viewed. */
12735 artifactRead?: {
12736 slug: string
12737 ver: string
12738 }
12739 } | {
12740 type: "image"
12741 file: {
12742 /** Base64-encoded image data */
12743 base64: string
12744 /** The MIME type of the image */
12745 type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
12746 /** Original file size in bytes */
12747 originalSize: number
12748 /** Image dimension info for coordinate mapping */
12749 dimensions?: {
12750 /** Original image width in pixels */
12751 originalWidth?: number
12752 /** Original image height in pixels */
12753 originalHeight?: number
12754 /** Displayed image width in pixels (after resizing) */
12755 displayWidth?: number
12756 /** Displayed image height in pixels (after resizing) */
12757 displayHeight?: number
12758 }
12759 }
12760 } | {
12761 type: "notebook"
12762 file: {
12763 /** The path to the notebook file */
12764 filePath: string
12765 /** Array of notebook cells */
12766 cells: unknown[]
12767 }
12768 } | {
12769 type: "pdf"
12770 file: {
12771 /** The path to the PDF file */
12772 filePath: string
12773 /** Base64-encoded PDF data */
12774 base64: string
12775 /** Original file size in bytes */
12776 originalSize: number
12777 }
12778 } | {
12779 type: "parts"
12780 file: {
12781 /** The path to the PDF file */
12782 filePath: string
12783 /** Original file size in bytes */
12784 originalSize: number
12785 /** Number of pages extracted */
12786 count: number
12787 /** Directory containing extracted page images */
12788 outputDir: string
12789 }
12790 /** Document page number of the first extracted page (1 when no range was requested); labels the page images in the model-facing tool_result */
12791 firstPage?: number
12792 /** 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 */
12793 pages?: Array<{
12794 /** Base64-encoded page image; empty when the page could not be processed */
12795 base64: string
12796 /** The MIME type of the image */
12797 mediaType: "image/jpeg" | "image/png" | "image/gif" | "image/webp"
12798 /** Why the page could not be processed as an image; set only when base64 is empty */
12799 error?: string
12800 }>
12801 } | {
12802 type: "file_unchanged"
12803 file: {
12804 /** The path to the file */
12805 filePath: string
12806 }
12807 /** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result */
12808 source?: "seeded"
12809 }
12810 ReportFindings: {
12811 /** Number of findings reported */
12812 count: number
12813 /** Effort level the review ran at */
12814 level?: "low" | "medium" | "high" | "xhigh" | "max"
12815 /** Echoed for the result body */
12816 findings: Array<{
12817 /** Repo-relative path of the file the finding is in */
12818 file: string
12819 /** 1-indexed line the finding anchors to */
12820 line?: number
12821 /** One-sentence statement of the defect */
12822 summary: string
12823 /** Compressed label for compact UI (≤60 chars): the claim alone, no rationale or consequence clause */
12824 short_summary?: string
12825 /** Concrete inputs/state → wrong output/crash */
12826 failure_scenario: string
12827 /** Short kebab-case slug of the finding type, e.g. "correctness", "simplification", "efficiency", "test-coverage" */
12828 category?: string
12829 /** Set when a verify pass ran; absent on inline-only reviews */
12830 verdict?: "CONFIRMED" | "PLAUSIBLE"
12831 /** Set ONLY when re-reporting after applying fixes: what happened to this finding */
12832 outcome?: "fixed" | "skipped" | "no_change_needed"
12833 }>
12834 }
12835 ScheduleWakeup: {
12836 /** Epoch ms timestamp when the next wakeup will fire */
12837 scheduledFor: number
12838 /** Actual delay used after clamping to runtime bounds */
12839 clampedDelaySeconds: number
12840 /** True if the requested delaySeconds was outside [60, 3600] */
12841 wasClamped: boolean
12842 /** True when the model ended the loop via `stop: true` */
12843 stopped?: boolean
12844 /** How many pending dynamic-loop wakeups stop:true cancelled. 0 means nothing was pending — a recurring /loop cron is not cancelled by stop:true. */
12845 cancelledWakeups?: number
12846 }
12847 SendMessage: unknown
12848 Skill: {
12849 /** Whether the skill is valid */
12850 success: boolean
12851 /** The name of the skill */
12852 commandName: string
12853 /** Tools allowed by this skill */
12854 allowedTools?: string[]
12855 /** Resolved model the skill turn runs on when a frontmatter model override took effect; omitted otherwise */
12856 model?: string
12857 /** Execution status */
12858 status?: "inline"
12859 /** True when the skill instructions were loaded read-only (nothing was executed) */
12860 readOnly?: boolean
12861 } | {
12862 /** Whether the skill completed successfully */
12863 success: boolean
12864 /** The name of the skill */
12865 commandName: string
12866 /** Execution status */
12867 status: "forked"
12868 /** The ID of the sub-agent that executed the skill */
12869 agentId: string
12870 /** The result from the forked skill execution */
12871 result: string
12872 /** True when the sub-agent was launched in the background: `result` describes the launch, and the skill outcome arrives later as a task notification. */
12873 background?: boolean
12874 }
12875 TaskOutput: unknown
12876 TaskStop: {
12877 /** Status message about the operation */
12878 message: string
12879 /** The ID of the task that was stopped */
12880 task_id: string
12881 /** The type of the task that was stopped */
12882 task_type: string
12883 /** The command or description of the stopped task */
12884 command?: string
12885 }
12886 ToolSearch: {
12887 matches: string[]
12888 query: string
12889 total_deferred_tools: number
12890 pending_mcp_servers?: string[]
12891 failed_mcp_servers?: {
12892 name: string
12893 errorCode?: string
12894 error?: string
12895 }[]
12896 }
12897 WebFetch: {
12898 /** Size of the fetched content in bytes */
12899 bytes: number
12900 /** HTTP response code */
12901 code: number
12902 /** HTTP response code text */
12903 codeText: string
12904 /** Processed result from applying the prompt to the content */
12905 result: string
12906 /** Time taken to fetch and process the content */
12907 durationMs: number
12908 /** The URL that was fetched */
12909 url: string
12910 artifactRead?: {
12911 slug: string
12912 ver?: string
12913 seeded?: false
12914 }
12915 }
12916 WebSearch: {
12917 /** The search query that was executed */
12918 query: string
12919 /** Search results and/or text commentary from the model */
12920 results: Array<{
12921 /** ID of the tool use */
12922 tool_use_id: string
12923 /** Array of search hits */
12924 content: Array<{
12925 /** The title of the search result */
12926 title: string
12927 /** The URL of the search result */
12928 url: string
12929 }>
12930 } | string>
12931 /** Time taken to complete the search operation */
12932 durationSeconds: number
12933 /** Number of web searches performed */
12934 searchCount?: number
12935 }
12936 Workflow: {
12937 status: "async_launched" | "remote_launched"
12938 taskId: string
12939 /** 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. */
12940 taskType?: "local_workflow" | "remote_agent"
12941 /** 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. */
12942 workflowName?: string
12943 /** 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. */
12944 runId?: string
12945 summary?: string
12946 /** Directory where subagent transcripts are written during execution */
12947 transcriptDir?: string
12948 /** Path to the persisted workflow script for this invocation. Editable via Write/Edit; pass back as `scriptPath` to re-run without resending the script. */
12949 scriptPath?: string
12950 /** CCR session URL when status is remote_launched */
12951 sessionUrl?: string
12952 /** Non-blocking heads-up (e.g. local git state diverges from the pushed branch the cloud session will clone) */
12953 warning?: string
12954 /** Set if syntax check failed */
12955 error?: string
12956 }
12957 Write: {
12958 /** Whether a new file was created or an existing file was updated */
12959 type: "create" | "update"
12960 /** The path to the file that was written */
12961 filePath: string
12962 /** The content that was written to the file */
12963 content: string
12964 /** 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) */
12965 structuredPatch: {
12966 oldStart: number
12967 oldLines: number
12968 newStart: number
12969 newLines: number
12970 lines: string[]
12971 }[]
12972 /** The original file content before the write (null for new files, or when the previous content was too large to include) */
12973 originalFile: string | null
12974 gitDiff?: {
12975 filename: string
12976 status: "modified" | "added"
12977 additions: number
12978 deletions: number
12979 changes: number
12980 patch: string
12981 /** GitHub owner/repo when available */
12982 repository?: string | null
12983 }
12984 /** True when the user edited the proposed content in the permission dialog before accepting */
12985 userModified?: boolean
12986 /** True when the write was held for the machine owner to review instead of written; the file is unchanged */
12987 staged?: boolean
12988 }
12989 }
12990}