Every named declaration in the file, 833 of them, verbatim and in the order Claude Code wrote them, 50 to a page. This is the page to land on from a signature: a verb that returns ToolCallResult links here, at whichever page it is on, and what you get is the declaration itself rather than a description of it.
The source is 22,468 lines of TypeScript mined from build 2.1.330. Anything longer than 12 lines is folded; click the line count to open it. To find a name on another page, search every symbol.
Names on this page, 101 to 150 of 833
DeclaredAttachmentInput type
#
line 4633
Added in 2.1.287
One prompt.attachment input of a type PromptAttachmentDetailOf names: the attachment's text, and under detail the facts it was rendered from.
A row the engine made holds them, unless its session keeps no plan file. That one, or one edited by hand, carries no detail key: read it as it may be.
42 lines
type DeclaredAttachmentInput<K extends keyof PromptAttachmentDetailOf> = {
/**
* As the engine names the attachment's kind, one of the names that
* carry a `detail`; the key a matcher narrows on. Pinned.
*/
type: K;
/**
* What the model reads for this attachment, inside the engine's framing;
* rewritable with `next({ ...e, text })`.
*
* The `<system-reminder>` wrapper (or the system channel that replaces
* it) goes around what the chain answers, never inside it.
*/
text: string;
/**
* Who authored the text (PromptAttachmentOrigin): the engine, a settings
* hook, or a plugin's chain context.
*
* Pinned: a different value is refused, one left out is kept.
*/
origin: PromptAttachmentOrigin;
/**
* The loop whose request carries the attachment: a subagent's id, the
* `id` `$.agent.list()` gives it; absent on main.
*
* Pinned: a different value is refused, one left out is kept. A loop
* forked from another carries the rows made for that one.
*/
agentId?: string;
/**
* Facts of the row the engine computed as it rendered `text`, by `type`:
* what a hook with words of its own reads in place of the engine's.
*
* Pinned: a different value is refused, one left out is kept. Not all
* the text says: a host's own plan instructions are in `text` alone.
* Absent on a row that does not hold its facts.
*
* @example
* if (e.detail === undefined) return next(e)
*/
detail?: PromptAttachmentDetailOf[K];
};
DeclaredEvents type
#
line 4680
Added in 2.1.281
The state events of each declared value in a union of [plugin, key] pairs, one variant per pair (it distributes), so a matcher narrows e.
type DeclaredEvents<Pair> = Pair extends readonly [
infer P extends keyof PluginState & string,
DeclaredEventsOf type
#
line 4689
Added in 2.1.281
e of state.get and of state.set for one declared value: its typed reference, and for a write the change, of the declared type.
type DeclaredEventsOf<P extends keyof PluginState & string, K extends keyof PluginState[P] & string> = {
get: StateRef<P, K>;
set: StateRef<P, K> & DeclaredStateChange<P, K>;
};
DeclaredPair type
#
line 4698
Added in 2.1.281
Every named value the enabled contracts declare, as one union of [plugin, key] pairs; never while PluginState is empty.
type DeclaredPair = {
[P in keyof PluginState & string]: {
[K in keyof PluginState[P] & string]: readonly [plugin: P, key: K];
}[keyof PluginState[P] & string];
}[keyof PluginState & string];
DeclaredStateChange type
#
line 4708
Added in 2.1.281
What a state.set on one declared value carries beside its reference: the value being written and the one that stood there, of the declared type.
type DeclaredStateChange<P extends keyof PluginState & string, K extends keyof PluginState[P] & string> = {
value: StateValue<P, K>;
previous: StateValue<P, K> | undefined;
/**
* The version the caller's write is conditional on, when it gave one.
*/
ifVersion?: number;
};
Derived type
#
line 4724
Added in 2.1.281
A value computed from other values, as derive(sources, fn) makes it: read runs fn again only when a source's version moved.
It holds nothing on the host: the cache is the plugin's own, lost with a reload of its code, and rebuilt by the next read.
export type Derived<T> = {
/**
* The atoms and references it is computed from, read in this order.
*/
readonly sources: readonly (Atom<unknown> | StateAddress)[];
/**
* The function over the sources' values, in the order they were given.
*/
readonly compute: (...values: never[]) => T;
};
DeriveFunction type
#
line 4745
Added in 2.1.281
derive(sources, fn): a value computed from atoms and references, cached by their versions: read runs fn again only when one moved.
Pure: it builds a description and calls nothing; reading it while drawing subscribes the drawing to every source.
const busy = derive([workers], list => list.filter(w => w.isBusy).length)
export type DeriveFunction = <const S extends readonly unknown[], T>(sources: S, compute: (...values: SourceValues<S>) => T) => Derived<T>;
DirectoryAddedHookInput type
#
line 4747
Added in 2.1.265
type DirectoryAddedHookInput = BaseHookInput & {
hook_event_name: 'DirectoryAdded';
/**
* Absolute path of the directory that was added.
*/
directory: string;
/**
* How the directory was added: "slash_command" for /add-dir, "register_repo_root" for the SDK control_request.
*/
source: 'slash_command' | 'register_repo_root';
};
ElementChildren type
#
line 4767
In the first published surface (2.1.259) · changed in 2.1.267
The children field every element constructor's props carry, appended beside its own props type: one child, or a list that may nest.
JSX types a lone child as the child itself (<Text dimColor>done</Text> passes the string, <Text>{count}</Text> the number), and a mapped list beside a sibling as a nested list (<Box>{rows.map(row)}<Text>ok</Text>).
export type ElementChildren = {
children?: RenderChildren;
};
ElementConstructor type
#
line 4779
In the first published surface (2.1.259)
An element as $.ui.resolve(e) hands it out: a constructor from props to the frozen plain-data element, children among the props as JSX passes.
const { Box } = $.ui.resolve(e) then <Box gap={1}>...</Box> compiles to h(Box, { gap: 1 }, ...children), and h calls a function tag with its props, so the table's constructors are the JSX tags.
export type ElementConstructor<P> = (props: P & ElementChildren) => RenderElement;
ElementName type
#
line 4785
In the first published surface (2.1.259)
Every element name of every surface: what a table handed out is completed to (an omitted one draws a fragment; see ui.resolve).
export type ElementName = {
[P in RenderSurface]: keyof Elements[P];
}[RenderSurface];
Elements interface
#
line 4802
In the first published surface (2.1.259) · changed in 2.1.260, 2.1.265, 2.1.267, 2.1.268, 2.1.271, 2.1.273, 2.1.274, 2.1.275, 2.1.299, 2.1.318, 2.1.323, 2.1.326
Each surface's primitive tags and their prop types, by e.surface, for the surfaces the plugin was compiled against.
A surface declares its own three (jsx, elements, components): an interface, so one not listed here adds its table by declaration merging. With the surface fixed, that table exactly; with none fixed, only what all share.
declare module "claude-code" { interface Elements { slack: SlackTable } }
91 lines
export interface Elements {
/**
* The terminal's, drawn with Ink: the nine every surface here carries and
* `Client`.
*
* The one surface with `Raster` and `Image`, and the one without `Svg`.
*/
terminal: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Input: ElementConstructor<InputProps>;
Select: ElementConstructor<SelectProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
Markdown: ElementConstructor<MarkdownProps>;
Progress: ElementConstructor<ProgressProps>;
/**
* A region one of the plugin's surface modules draws (ClientModule), named
* by `module`: a string literal, the module's path relative to this file.
*
* The engine reads the surface module off the hooks module's source
* before anything runs, so a variable, a template with a substitution or
* a computed path as `module` is refused at load, naming the line.
*/
Client: ElementConstructor<ClientProps>;
Raster: ElementConstructor<RasterProps>;
Image: ElementConstructor<ImageProps>;
};
/**
* Claude Code Desktop's: the nine every surface here carries, `Svg`,
* `Client` and `Shader`.
*/
desktop: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Input: ElementConstructor<InputProps>;
Select: ElementConstructor<SelectProps>;
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
Markdown: ElementConstructor<MarkdownProps>;
Progress: ElementConstructor<ProgressProps>;
Client: ElementConstructor<ClientProps>;
Shader: ElementConstructor<ShaderProps>;
};
/**
* An app is sent an `Input` or `Select` only if it named it in `draws` on
* its `ui_attach`, and an empty Box otherwise; a `Progress` the same way, and
* its Box and Text otherwise. A hook cannot tell which the app got.
*
* On a tool row (`ToolUse`) in mobile apps, a `borderStyle` or
* `backgroundColor` on the Box that holds the row and something else asks for
* a card under the row;
* otherwise a tree that keeps the row usually draws as one quiet line under
* it, with the rest behind a tap, so plain Text suits a small status.
*/
mobile: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Input: ElementConstructor<InputProps>;
Select: ElementConstructor<SelectProps>;
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
Markdown: ElementConstructor<MarkdownProps>;
Progress: ElementConstructor<ProgressProps>;
Shader: ElementConstructor<ShaderProps>;
};
/**
* The desktop's table without `Client`: a remote `Client`'s module, presses
* and posts (ui_client_module, ui_client_press, ui_message) name no surface.
*
* They are the desktop's alone until those asks name a surface, no limit of
* the editor's webview. Nor has it `Shader`, since it draws no backdrop.
*/
vscode: {
Box: ElementConstructor<BoxProps>;
Text: ElementConstructor<TextProps>;
Button: ElementConstructor<ButtonProps>;
Input: ElementConstructor<InputProps>;
Select: ElementConstructor<SelectProps>;
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
Markdown: ElementConstructor<MarkdownProps>;
Progress: ElementConstructor<ProgressProps>;
};
}
ElementTable type
#
line 4897
In the first published surface (2.1.259)
The table ui.resolve answers for an argument of surface P.
export type ElementTable<P extends RenderSurface = RenderSurface> = Elements[P];
ElicitationHookInput type
#
line 4902
Added in 2.1.265
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.
type ElicitationHookInput = BaseHookInput & {
hook_event_name: 'Elicitation';
mcp_server_name: string;
message: string;
mode?: 'form' | 'url';
url?: string;
elicitation_id?: string;
requested_schema?: Record<string, unknown>;
};
ElicitationResultHookInput type
#
line 4915
Added in 2.1.265
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.
type ElicitationResultHookInput = BaseHookInput & {
hook_event_name: 'ElicitationResult';
mcp_server_name: string;
elicitation_id?: string;
mode?: 'form' | 'url';
action: 'accept' | 'decline' | 'cancel';
content?: Record<string, unknown>;
};
EngineCreateInput type
#
line 4932
In the first published surface (2.1.259)
The input of engine.create: the fold that builds $, once per load, core innermost.
A hook is written in post-order: const built = await next(e) is $ as built so far; return { ...built, voice: { say } } adds this plugin's noun. See EngineEventOf's engine.create for what a step may and may not do.
export type EngineCreateInput = {
/**
* The modules this fold builds, in list order, first outermost (managed
* plugins first, so an org plugin's withholding wins).
*
* The whole set at a load, this plugin alone at its reload, the ones added
* or changed at a refresh that keeps the rest: a module added later that
* does not hook this event is built against the table as it stands.
*/
plugins: readonly string[];
};
EngineCreateResult type
#
line 4951
In the first published surface (2.1.259)
What an engine.create hook returns: $ as built so far with this plugin's nouns added, less any it withheld.
Every declared noun is optional here. Between hooks it crosses the chain as interface descriptors; a hook sees objects (EngineInterfaceBuilt).
export type EngineCreateResult = Partial<EngineInterface> & {
readonly [noun: string]: unknown;
};
EngineEventOf type
#
line 4966
In the first published surface (2.1.259)
The events the engine raises at its call sites, and engine.create; the classic settings hooks' events are ClassicEventOf.
At every one, a hook that fails (throws, overruns its budget: HookBudget, answers a wrong shape) is skipped: the hooks beneath and core run in its place, or its last next result stands; the failure is reported by name.
1006 lines
export type EngineEventOf = {
/**
* Fires when the engine is about to run a tool. Each `next(e)` runs the
* hooks beneath, then core (the permission prompt, the tool itself).
*
* `{ deny: reason }` refuses and `{ result }` answers in place of `next`: a
* deny after `next(e)` resolved undoes nothing it ran; returning with `next`
* pending aborts what runs beneath. Managed-settings hooks' deny comes first.
*
* In a session off the person's machine (cloud, SSH, a VM but for Cowork's) a
* call to their devices or browser is refused once a hook of any tier wrote
* it, changed it or ran it again, here, at `turn.step` or at a classic event.
* So is one made beneath such a call, or by an agent a mod spawned, retyped
* or registered.
*
* @remarks A guard that fails is skipped and the tool runs, so give it
* `.catch(($, e, next) => next.called ? next(e) : { deny: "no" })`. A hook
* that checks the result refuses in its `.catch` even where `next` was called.
*/
'tool.call': ToolCallInput;
/**
* Fires when the engine decides whether a tool call may run, after the
* `tool.call` and PreToolUse hooks and before the mode settles an ask.
*
* `next(e)` resolves to the engine's verdict (rules, mode, the tool's own
* check, PreToolUse's decision) and runs no tool: return any `{ decision }`,
* a deny after it too. `$.tool.check` runs the same chain, executing nothing.
* A settings `mcp_tool` hook's call passes here too (`next.origin`), and
* so may a plugin's file or process call, for a matcher that names `op`.
* On a call to the person's devices from off their machine a hook only
* tightens, here, at `tool.judge` and at the classic permission events.
*
* @remarks A guard that fails is skipped, leaving the verdict beneath.
* Nothing has run, so give it `.catch(() => ({ decision: "deny" }))`.
* @example
* on("tool.check", { tool: "Read" }, () => ({ decision: "allow" }))
*/
'tool.check': ToolCheckInput;
/**
* Fires when auto mode is about to ask its classifier about a call, after
* every rule, hook and check that only a person may answer.
*
* `next(e)` asks it, once however often it runs, and runs no tool: the
* server's verdict where it judged the model's call, else the local
* classifier's. A call auto mode settles with no classifier raises none.
*
* @remarks A hook that fails is skipped and the classifier decides, so give
* a guard `.catch(() => ({ decision: "deny" }))`. The classifier's allow is
* no proof the call ran: a hook's ask or a change of mode may still hold it.
* @example
* // "lab" is this plugin: its own `$.agent.call` of a read needs no classifier
* on("tool.judge", ($, e, next) => next.origin.plugin === "lab" &&
* e.isReadOnly ? { decision: "allow" } : next(e))
*/
'tool.judge': ToolJudgeInput;
/**
* Fires when a call has been allowed and is about to run: after `tool.call`,
* PreToolUse, `tool.check` and whoever settled an ask; never for a refusal.
*
* `e` is the call as allowed, all of it pinned: a rewrite is refused.
* `next(e)` runs the tool; `{ result, context? }` answers in its place, a
* success PostToolUse sees; `{ deny }` is the call's error, as a tool's own.
*
* @remarks One check, one run: a second `next(e)` starts nothing and
* resolves to a `{ deny }`, whatever became of the first. A guard that
* fails is skipped and the tool runs, so give it
* `.catch(($, e, next) => next.called ? next(e) : { deny: "no" })`.
* Where a tool still runs on an aborted turn it fires, `next.signal`
* aborted; a turn aborted while a hook holds the call does not run it,
* and the call reads as interrupted. Who hears a call is settled ahead
* of its permission check: a plugin that loads during the call's ask
* misses that call. As at
* `tool.call`, a hook that may match a tool, even one that only passes
* `next(e)` on, turns off for that tool what would carry its output past
* the hook: the move to the background, a served call's live output,
* Code Mode's wait for a stopped result. An answer of your own after
* `next(e)` drops what the tool sent beside its result (a skill's text
* and allowed tools); a limit it set, or a settings hook's stop, stays.
* An answer aborts a run it left going, and waits for it to end.
* @example
* on("tool.run", { tool: "mcp__lab__ping" }, () => ({ result: "pong" }))
*/
'tool.run': ToolCallInput;
/**
* Fires when the engine is about to draw a component: once per input value
* (props, viewport width), plugin load or `$.ui.invalidate("ui.render")`.
*
* A repaint reuses the answer; a clock invalidates. `next(e)` resolves to the
* drawing: return it, wrap it, draw your own, or rewrite `props`. An invalid
* tree, or a throw while drawn, draws the engine's; `--plugin-dir` is told.
*
* @remarks Also on a write of `$.state` it read while drawn, at the redraw
* rate; an invalidate is any plugin's whose matcher may select it. On the
* terminal a new row is blank until its first answer, and `/export` waits.
* A hook its `$` calls hold past 30 seconds in all is skipped.
*/
'ui.render': RenderInput;
/**
* Fires when the plugins load (not per draw), once per surface, component
* and plugin: `e` names the surface and component, never the props.
*
* `next(e)` resolves to the surface's table, which `$.ui.resolve(e)` then
* reads. Return it, one with an element restyled for every other plugin,
* or one with a key left out (a fragment there); own table: hook skipped.
*/
'ui.resolve': ResolveInput;
/**
* Fires when a `Button` a render hook drew is pressed on a surface; `e` is
* `{ plugin, element, component, surface }`, `element` the button's `key`.
*
* `next(e)` runs the hooks beneath, then core: the element's own `onPress`
* closure, in its plugin's environment, resolving to `{ element }`. Return
* `next(e)` to let the press through, or `{ element }` to take it.
*/
'ui.press': UiPressArgument;
/**
* Fires when an `Input` a render hook drew changes or is submitted; `e` is
* `{ plugin, element, component, surface, kind, value }`.
*
* `next(e)` runs the hooks beneath, then the element's own `onInput` or
* `onSubmit` with `e.value` as the chain left it, resolving to `{ element,
* value }`; `next({ ...e, value })` rewrites the typing, an answer takes it.
*/
'ui.input': UiInputArgument;
/**
* Fires when a `Select` a render hook drew is picked from; `e` is
* `{ plugin, element, component, surface, value }`.
*
* `next(e)` runs the hooks beneath, then the element's own `onSelect` with
* `e.value` as the chain left it, resolving to `{ element, value }`;
* `next({ ...e, value })` rewrites the pick, an answer takes it.
*/
'ui.select': UiSelectArgument;
/**
* Fires when a `Client` THIS plugin drew posts from its surface module
* (`surface.post(data)`); only this plugin's hooks see it.
*
* `next.origin` names `client`: `data` came from code. Core answers `{}`;
* `next({ ...e, data })` rewrites the data; `{ props }` hands the posting
* instance its next props without a redraw. One per instance per frame.
*/
'ui.message': UiMessageArgument;
/**
* Fires when a `Client` THIS plugin drew failed on a surface: its module
* did not load, its drawing failed, or its code failed after it had drawn.
*
* Only this plugin's hooks see it; `e.phase` says when, `e.reason` why.
* Observe only: core answers `{}`. The engine then draws that site again,
* unasked: fall back by leaving the `Client` out.
*
* @remarks A `Client` born in that redraw that fails is heard too, and the
* engine draws nothing again for it: to go on, ask (`$.ui.invalidate`).
* @example
* on("ui.fault", ($, e, next) => ($.ui.log(e.reason), next(e)))
*/
'ui.fault': UiFaultInput;
/**
* Fires when the person clicks or taps the backdrop where no part of the
* app covers it. Only the hooks of the plugin that set the theme see it.
*
* Observe only. It may be a stray click, so it does not count as the
* person asking for anything, as a `ui.press` does. To answer it, change
* what the `Backdrop` hook draws, such as a `Shader`'s `values`, and redraw.
*
* @example
* on("ui.pointer", ($, e, next) => (clicks++, $.ui.invalidate("ui.render"), next(e)))
*/
'ui.pointer': UiPointerInput;
/**
* Fires before a site's window moves: the person's wheel or scroll keys on
* a `Pane` body or the `AbovePrompt` band, at its edges too; `$.ui.scroll`.
*
* `next(e)` moves it to `e.offset` and draws: `{}`; `next({ ...e, offset
* })` elsewhere; no `next` (`{}` or `{ deny }`) leaves it undrawn, so a hook
* drawing its own rows under a header moves them by `e.by` and invalidates.
*
* @example
* on("ui.scroll", { requestId: "log" }, ($, e) => (scrollOwnRows(e.by), {}))
*/
'ui.scroll': UiScrollInput;
/**
* Fires before a site's focus ring moves: the person's Tab, arrows or click
* in a `Pane` or the band; an `autoFocus` element taking it; `$.ui.focus`.
*
* `next(e)` lands it on `e.element` (absent: one of the engine's stops) and
* draws: `{}`; `next({ ...e, element })` on another of `e.plugin`'s; no
* `next` (`{}` or `{ deny }`) keeps it where it was, drawn as it was.
*
* @example
* on("ui.focus", { requestId: "list" }, ($, e, next) => (mark(e), next(e)))
*/
'ui.focus': UiFocusInput;
/**
* Fires when the engine offers an agent type to the model, in the agent
* listing and again at dispatch; `next(e)` resolves to `{ isOffered: true }`.
*
* Return `{ isOffered: false }` to keep the type out of the listing and
* refuse its dispatch. A hook that fails passes it through. The offer to
* resume an agent of the type carries that agent's `agentId`.
*
* @remarks So give a guard here
* `.catch(($, e, next) => next.called ? next(e) : { isOffered: false })`.
* @example
* on("agent.offer", { agent: "Plan" }, () => ({ isOffered: false }))
*/
'agent.offer': AgentOfferInput;
/**
* Fires when the Agent tool, or a workflow script's `agent()`
* (`e.workflow`), is about to start an agent, its model not yet resolved.
*
* Also for a fork a command starts with no tool call (`e.fork`, an empty
* `tool_use_id`): `/subtask`, `/btw`'s fork key, and `/fork` where it starts
* a subagent. A fork the engine starts by itself, to answer an artifact's
* comment or a Slack thread, does not raise it.
*
* `next(e)` resolves to `{ model }`. Return it, `next({ ...e, model })`,
* `{ model }` of your own (an alias resolves like the tool's parameter), or
* `{ deny: reason }`.
*
* @remarks A guard that fails is skipped and the subagent starts, so give
* it `.catch(($, e, next) => next.called ? next(e) : { deny: "no" })`.
*/
'agent.spawn': AgentSpawnInput;
/**
* Fires before an agent's report reaches its parent, for each run that ends
* or is stopped. `next(e)` answers auto mode's review and delivers nothing.
*
* What the outermost hook returns is delivered: `{ text }`, under the review's
* warning if it gave one. `{ consumed: reason }` takes it: the parent gets no
* notice and waits no longer, and a call that waited answers the reason.
*
* @remarks What the agent wrote is reviewed once, as with no hook, and with
* no `next` all the same; a hook's text is not. A `review` or `warning` a
* hook writes is dropped. A warning goes with whatever text is delivered;
* of a consumed report, with the agent's next one in this process.
* @remarks A hook that throws is skipped as on any event: before its `next`
* the report goes on without it, after it what `next` answered is delivered.
* @remarks Final text is seen before it is reviewed; the hand-back tool's
* message after the call's own verdict, which `next` answers. A run that
* failed or was stopped in the background has no review: `none`.
* @remarks Each report is asked about anew, a first run's or a resumed one's.
* A run that only waits on agents of its own reports once they have; left
* none by a consume, it ends as its last turn left it, with no further one.
* @remarks The engine stops naming a consumed report's output file. A model's
* own Read of that file, a script's read of the transcript, the agent itself
* when resumed and SubagentStop hooks still see it.
* @remarks Not raised for a workflow's `agent()`, a teammate (see
* `session.receive`), a remote agent, an observer, or a run with hooks off.
* @example
* on("agent.report", { subagentType: "lab:runner" }, async ($, e, next) =>
* (await $.store.set(e.agentId, await next(e)), { consumed: "kept" }))
*/
'agent.report': AgentReportInput;
/**
* Fires when a prompt is submitted, before the turn starts. `next(e)` runs
* the hooks beneath and the UserPromptSubmit settings hooks, then it enters.
*
* Rewrite with `next({ ...e, text })` (the user message on screen follows)
* or, in its place, stop it with `{ drop: reason }`; a broken plugin never
* blocks one. Typed while a turn ran, it fires at Enter, with that turn's id.
*
* @remarks So a guard that fails lets the prompt through, unless given
* `.catch(($, e, next) => next.called ? next(e) : { drop: "no" })`.
*/
'prompt.submit': PromptSubmitInput;
/**
* Fires when a text is about to be put in the prompt box as the person's
* draft (a plugin's `$.prompt.fill`); `next(e)` writes it by `e.mode`.
*
* `replace` over the draft, `append` after it, `insert` at the cursor;
* rewrite `text` or `mode` going down, or answer `{ isFilled: false }`
* without `next` to keep it out, as core does under a dialog or headless.
*
* @example
* on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
*/
'prompt.fill': PromptFillInput;
/**
* Fires when a text is proposed as the prompt box's dim suggestion, Tab to
* take: the engine's guess after a turn, or a plugin's `$.prompt.suggest`.
*
* `next(e)` shows it: `{ isShown }`. Rewrite with `next({ ...e, text })`,
* or answer `{ isShown: false }` without `next` to drop it; core answers
* that too while the box holds text or a turn runs.
*
* @example
* on("prompt.suggest", () => ({ isShown: false }))
*/
'prompt.suggest': PromptSuggestInput;
/**
* Fires when the person edits the main prompt box: a key the editor took as
* an edit, or a paste; `next(e)` resolves the box the editor shows.
*
* `e` is the draft before and the splice (`start`, `end`, `inputText`); a
* burst of keys is one edit. Rewrite `inputText` going down or the box
* coming up; `{ text: e.text, cursor: e.cursor }` without `next` consumes.
*
* @example
* on("prompt.edit", ($, e) => ({ text: e.text, cursor: e.cursor }))
*/
'prompt.edit': PromptEditInput;
/**
* Fires after the main prompt box's text changed and no `prompt.edit`
* carried it: a recalled history entry, a clear, a plugin's fill.
*
* `e` is the box as it stands and `e.origin` who changed it. Observe only:
* the change is in the box. One per batch of changes, one at a time.
*
* @example
* on("prompt.change", ($, e, next) => ($.ui.status(e.origin.kind), next(e)))
*/
'prompt.change': PromptChangeInput;
/**
* Fires as the person types in the main prompt box, for the token at the
* cursor; `next(e)` resolves to `{ suggestions }`, rows for the typeahead.
*
* Nothing waits on it: the engine's own rows draw first and these join
* beneath them, unhighlighted, for the word still being typed. Taking one
* writes its `text` over the token. Only while a plugin hooks it.
*
* @example
* on("prompt.autocomplete", () => ({ suggestions: [{ text: "#123" }] }))
*/
'prompt.autocomplete': PromptAutocompleteInput;
/**
* Fires once per named section of the system prompt, when the engine
* assembles it; `next(e)` resolves to `{ text }` as core computed it.
*
* `e.name` is the section's id, on every model the one `prompt.compose`
* lists. Cached, so keep it steady: after `$.ui.invalidate("prompt.section")`
* a changed answer waits for a new thread or a compaction, unless it carries
* `breakPromptCache: true` (PromptSectionResult). A failed hook passes through.
*
* @example
* on("prompt.section", { name: "memory" }, () => ({ text: null }))
*/
'prompt.section': PromptSectionInput;
/**
* Fires once per conversation, when the engine computes the context blocks
* its first user message carries; `next(e)` resolves to `{ blocks }`.
*
* Append, drop, reorder or rewrite with `next({ ...e, blocks })`; the
* answer stands until `$.ui.invalidate("prompt.context")` or a re-read
* (compaction, `/clear`). `PromptContextResult` says what the model is sent.
*
* @example
* on("prompt.context", () => ({ blocks: [] }))
*/
'prompt.context': PromptContextInput;
/**
* Fires when the engine renders a system prompt; `next(e)` resolves to
* `{ sections }`, each `{ id, text, scope }`, in the order they are sent.
*
* The ids depend on the prompt composed (`lean`, `bare` in `e.traits`): read
* them off `next(e)`. Append (as `session`), replace, reorder or drop; a list
* with a `shared` section after a `session` one skips the hook.
*/
'prompt.compose': PromptComposeInput;
/**
* Fires once per message the engine injects for the model on its own (a
* reminder, a mode transition, a mentioned file), as a request carries it.
*
* `next(e)` resolves to `{ text }`; `{ text: null }` leaves it out. The
* answer holds per attachment for the process (asked again on resume or
* `$.ui.invalidate`); the transcript keeps the engine's record.
*
* @example
* on("prompt.attachment", { type: "todo_reminder" }, () => ({ text: null }))
*/
'prompt.attachment': PromptAttachmentInput;
/**
* Fires once per path a prompt names after an `@`, a directory aside,
* before the engine reads it; `next(e)` reads it and resolves `{ type }`.
*
* No `tool.call` is raised for this read. Add `context` to what `next`
* gave, read another `path` with `next({ ...e, path })`, or answer
* `{ deny: reason }` so nothing is read.
*
* @remarks A guard that fails is skipped and the file is read, so give it
* `.catch(($, e, next) => next.called ? next(e) : { deny: "no" })`.
* @example
* on("prompt.mention", { path: /\.env$/ }, () => ({ deny: "a secret" }))
*/
'prompt.mention': PromptMentionInput;
/**
* Fires when the engine first renders the tool's schema in a session;
* `next(e)` resolves to `{ description, isDeferred? }`.
*
* An MCP tool behind ToolSearch fires twice: its short text, then the one
* loaded. Cached until `$.ui.invalidate("tool.describe")`: a changed answer
* for a tool a thread has sent waits for a new thread or a compaction, unless
* it carries `breakPromptCache: true` (ToolDescribeResult).
*
* @remarks Fires again when an MCP server replaced under the same name brings
* another `mcpServer`. A description changed then waits the same way, and
* `breakPromptCache` sends it only after `$.ui.invalidate`.
* @remarks Twice for an MCP tool behind ToolSearch: its short text, then
* the one loaded.
* @remarks An explicit `isDeferred` moves the tool behind ToolSearch (true)
* or into the prompt's list (false).
* @example
* on("tool.describe", { tool: "Bash" }, ($, e) => ({ ...e, description }))
* @example
* on("tool.describe", { tool: "Monitor" }, pin) // {...e, isDeferred: false}
*/
'tool.describe': ToolDescribeInput;
/**
* Fires once per tool before a loop's first request, and again when its
* model calls the tool; `next(e)` resolves to `{ isOffered: true }`.
*
* `{ isOffered: false }` keeps the tool from that loop's model for the
* loop's life, compactions and resumes included; at a call it refuses that
* call alone. A tool that joins later is asked once, as it joins.
*
* @remarks `tool.list` shapes the pool: a tool it leaves out is gone for the
* model, every agent and a mod's own `$.tool.call`. This shapes only what
* one model is shown of the pool: the agent's children inherit a tool not
* offered, and `$.tool.call` still runs it.
* @remarks A fork keeps its parent's list, and its calls are asked. The
* answers hold only while some hook is on the event. A hook that fails
* passes the tool through. A command that sends the conversation ahead of
* a turn (`/compact`, `/btw`) asks first, as the loop.
* @remarks The hand-back tool is asked at each run; not offered, the agent's
* final text is its report. Where the server decides auto mode's checks and
* cannot be handed that text, it is not asked, and stays offered.
* StructuredOutput and EndConversation are never asked, nor is a list for
* the loops the engine runs for itself (an agent hook's, a compaction's). A
* Batch tool follows the tool it batches. ToolSearch, not offered, is left
* out while no offered tool is deferred, and is there to load one that is;
* it finds no hidden tool.
* @example
* on("tool.offer", { tool: "Agent" }, ($, e) => ({ isOffered: !e.agentId }))
*/
'tool.offer': ToolOfferInput;
/**
* Fires when a slash command is about to run (`/name args` typed, or a
* plugin's `$.command.run`); `next(e)` resolves to `{ text }`, its output.
*
* Core is the engine's command (a registered one has none). Rewrite `args`
* with `next`, or return `{ text }` without it to answer in its place; one
* after `next` replaces a printed output, not a panel or prompt it opened.
*
* @remarks A guard that fails is skipped and the command runs, so give it
* `.catch(($, e, next) => next.called ? next(e) : { text: "no" })`.
* @example
* on("command.run", { command: "hello" }, () => ({ text: "hello" }))
*/
'command.run': CommandRunInput;
/**
* Fires once per command, when the engine lists it for the typeahead and
* `/help`; `next(e)` resolves to `{ description, argumentHint, isHidden }`.
*
* Listed answers are cached for the session until
* `$.ui.invalidate("command.describe")`. A hook that fails passes it
* through.
*
* @example
* on("command.describe", ($, e, next) => next({ ...e, isHidden: true }))
*/
'command.describe': CommandDescribeInput;
/**
* Fires when a `/config` row is about to change, from the menu or a
* plugin's `$.config.set`; `next(e)` resolves to `{ value }` once written.
*
* Return `{ deny: reason }` to leave the row as it is (the menu says why),
* or `next({ ...e, value })` to clamp it; a value of the wrong kind for
* the row is refused. A row a trusted source owns is core's to refuse.
*
* @remarks A guard that fails is skipped and the row is written, so give
* it `.catch(($, e, next) => next.called ? next(e) : { deny: "no" })`.
* @example
* on("config.set", { key: "theme" }, () => ({ deny: "the theme stays" }))
*/
'config.set': ConfigSetInput;
/**
* Fires once per `/config` row, when the menu lists it and for
* `$.config.list`; `next(e)` resolves to `{ label, description, isHidden }`.
*
* Relabel, re-describe or hide with `next({ ...e, isHidden: true })`; the
* answers are cached until `$.ui.invalidate("config.describe")` or the
* loaded plugins change. A hook that fails passes the row through.
*
* @example
* on("config.describe", { key: "tips" }, hide) // answers isHidden: true
*/
'config.describe': ConfigDescribeInput;
/**
* Fires when a record is about to be logged to the destination `e.to`
* names: a built-in's `$.telemetry.log`, or the engine's own events.
*
* `e.to` is pinned: a hook rewrites what the record carries, never where
* it goes. `next(e)` resolves `{ value: undefined }`; `{ deny }` rejects the
* caller. Beneath the hooks the engine exports its own collector records.
* Where sec-default is seated, a collector record passes the `user` tier by.
*
* @example
* on("telemetry.log", { to: "collector" }, ($, e, next) => next(e))
*/
'telemetry.log': TelemetryLogInput;
/**
* Fires when one use of a feature is marked (`$.telemetry.mark`), as the
* CLI's own feature events mark one; always for `anthropic`, no `to`.
*
* `next(e)` resolves `{ value: undefined }`; `{ deny }` rejects the caller.
* The engine does nothing with a mark: the built-ins hooked here do.
*
* @example
* on("telemetry.mark", { kind: "bad" }, ($, e, next) => next(e))
*/
'telemetry.mark': TelemetryMarkInput;
/**
* Fires when the engine expands a skill's prompt for the model (`/name`,
* the Skill tool, a preload); `next(e)` resolves to `{ text }` as computed.
*
* Return `{ text }` with the text the model reads instead. A hook that
* fails passes it through.
*
* @example
* on("skill.prompt", { skill: "commit" }, () => ({ text: "A haiku." }))
*/
'skill.prompt': SkillPromptInput;
/**
* Fires when the engine composes a git text the model is to write (`kind`:
* `commit`, `pr`, `exemption`, `remedy`); `next(e)` resolves to `{ text }`.
*
* Return `{ text }` with the text the model reads instead. A hook that
* fails passes it through.
*
* @example
* on("attribution.text", { kind: "commit" }, () => ({ text: "" }))
*/
'attribution.text': AttributionTextInput;
/**
* Fires when the engine asks which version control system a folder uses;
* `next(e)` resolves to the working copy (VcsWorkingCopy) or null.
*
* Experimental: may change.
*
* Asked for a conversation's first request, after a compaction and when the
* loop's own folder changes. Core answers Git. Copies nest: answer where
* yours is as near as the one beneath or nearer, else return that one.
*
* `detect` of the `root` it answered names the same `root`.
*
* Every copy of one repository answers the same `mainRoot`.
*
* Hooks written so resolve nested copies nearest first, in any load order.
*
* `$.vcs.detect` takes any file's path; a hook hears the folder holding it.
*
* The parent of `root` gives the enclosing system, the calling hook skipped.
*
* On a managed login a person's hook is asked only where nothing else claims the folder.
*
* Another system's answer names it and its branch in the environment block
* and drops the Git status block and, for the session, the shell tools'
* commit and pull-request steps; Git's safety cautions stay. Add your own
* with `prompt.context` and `tool.describe`. `$.session.repo()` reads it
* too. Trust, settings, memory, permissions and the sandbox never do. A
* hook that fails passes it through. Not raised where the session's files
* are on another machine.
*
* Grep and file suggestions honor `.ignore` and `.rgignore` without Git.
*
* @example
* on("vcs.detect", async ($, e, next) => {
* const below = await next(e)
* const found = await $.process.run(["acme", "root"], { cwd: e.path })
* const root = found.stdout.trim()
* const isAsNearOrNearer = root.length >= (below?.root.length ?? 0)
* if (found.exitCode !== 0 || !isAsNearOrNearer) return below
* return {
* vcs: "acme", root, mainRoot: root, revision: "1234", branch: null,
* defaultBranch: null, remote: "ssl:acme:1666",
* }
* })
* on("prompt.context", async ($, e, next) => {
* const result = await next(e)
* const copy = await $.vcs.detect({ path: "." })
* const block = { name: "acmeStatus", text: `At change ${copy?.revision}.` }
* return copy?.vcs === "acme"
* ? { ...result, blocks: [...result.blocks, block] }
* : result
* })
*/
'vcs.detect': VcsDetectInput;
/**
* Fires when a mod asks what changed in a working copy, as `/diff` does
* where `vcs.detect` names a system other than Git; match it on `vcs`.
*
* Experimental: may change.
*
* Core answers `{ unknown: null }`, and `/diff` then looks for Git; a hook's
* own reason shows instead. An answer may cost a server call. A hook that
* fails passes it through. Not raised where the session's files are on
* another machine.
*
* Git isn't served here yet: `/diff` reads it itself.
*
* On a managed login a person's hook is asked only where no other answers.
*
* A diff over two sets of paths is the union of each.
*
* Stat-only is the same files without patches.
*
* @example
* on("vcs.diff", { vcs: "acme" }, async ($, e) => {
* if (e.base === "default") return { unknown: "acme has no mainline" }
* const kept = e.paths?.map(path => `--only=${path}`) ?? ["--all"]
* const argv = ["acme", "changes", "--json", ...kept]
* const found = await $.process.run(argv, { cwd: e.path })
* if (found.exitCode !== 0) return { unknown: "acme did not answer" }
* const files = JSON.parse(found.stdout).map(one => ({
* path: one.path, renamedFrom: null, added: one.plus, removed: one.minus,
* isBinary: false, isUntracked: one.isNew,
* ...(!e.isStatOnly && { patch: one.hunks }),
* }))
* return { base: "change 1234", files }
* })
*/
'vcs.diff': VcsDiffInput;
/**
* Fires when a working copy is needed, before anything is made: for a
* subagent run with `isolation: "worktree"` (the Agent tool, a workflow's
* `agent()`), or for a session: by EnterWorktree, the `--worktree` flag, a
* Remote Control spawn in a worktree, or an app that is about to open one.
* A review reference (`--worktree "#123"`, a URL) stays Git's, as does a
* sub-folder picked over Remote Control: no hook hears it. No `vcs.*` hook
* hears a `name` with a part that starts with a dash.
*
* At launch and at a spawn no session is bound. `$.process`, `$.fs`, `$.settings`
* and `$.store` work, and `$.model.fork` answers `nothing-to-fork`. These reject:
* `$.tool`, `$.command`, `$.config`, `$.mcp`, `$.agent` but for `limits`,
* `$.ui.ask`, `$.prompt.compose`, and `$.session.messages` and `send`.
* `session.start` follows the move, for the mods that the copy enables.
*
* `next(e)` makes it as the engine would unhooked: a WorktreeCreate hook
* where one is set, a host's callback among them, else a Git worktree.
* Answer `{ path, vcs }` in its place and the copy is this mod's: the engine
* vets the folder, runs no version control there, and asks `vcs.status` and
* `vcs.release` about it. `{ deny }` refuses. A hook that fails is skipped.
* On a mod's own `$.vcs.isolate`, `next(e)` makes a Git worktree for that
* mod, in a trusted workspace only, and runs no WorktreeCreate hook.
*
* Systems can sit side by side or nest: claim only when yours is the nearest
* one holding `from`, else pass on with `next`. On `vcs.status` and
* `vcs.release`, a matcher on `vcs` hears only your own copies.
*
* Where a second folder costs too much, answer `path: e.from` and the agent
* is isolated in place: it runs in its parent's folder under the parent's
* fences and guards, reads that it shares the folder, and `vcs.status` and
* `vcs.release` are asked about `name`, so answer for that work alone. It
* gives no file isolation: claims and conflicts are the mod's, at `tool.run`
* by `agentId` (a workflow's agent that is run again is asked about again,
* under its new one). The engine removes, locks and sweeps nothing there.
* The agent is not told `branch`: a mod that wants it told appends it with
* `$.session.append` under the agent's `agentId`, at `turn.start`.
*
* It may be asked again for a name it already made: by `--worktree <name>`,
* and by a resume, for a copy that is missing or empty or a subagent's after
* a restart. On a resume's ask `next(e)` makes nothing and denies, any folder
* but the recorded one is left unused, and nothing is isolated in place. The
* engine relies on:
* - `isolate` twice with one name is the same copy.
* - A fresh copy's `status` is empty and answers the same `revision`: where
* a clone carries local changes, report against creation or reset them.
* - `release` right after `isolate` changes nothing `from` can observe.
* - Releasing a copy already gone is released.
*
* Experimental: may change.
*
* @example
* on("vcs.isolate", async ($, e, next) => {
* if (!(await $.fs.exists(`${e.from}/.acme`))) return next(e)
* const argv = ["acme", "copy", "--name", e.name, "--base", e.base]
* const made = await $.process.run(argv, { cwd: e.from })
* if (made.exitCode !== 0) return { deny: made.stderr }
* const [path, revision] = made.stdout.trim().split("\n")
* return { path, vcs: "acme", revision }
* })
* @example
* // in place: a changelist, shelved first so that a late edit is not lost
* on("vcs.isolate", { for: "agent" }, async ($, e, next) => {
* if (!(await $.fs.exists(`${e.from}/.acme`))) return next(e)
* const argv = ["acme", "changelist", "open", e.name]
* const made = await $.process.run(argv, { cwd: e.from })
* if (made.exitCode !== 0) return { deny: made.stderr }
* return { path: e.from, vcs: "acme", branch: made.stdout.trim() }
* })
* on("vcs.status", { vcs: "acme" }, async ($, e) => {
* const argv = ["acme", "changelist", "files", e.name ?? "default"]
* const ran = await $.process.run(argv, { cwd: e.path })
* if (ran.exitCode !== 0) return { unknown: ran.stderr }
* const paths = ran.stdout.split("\n").filter(Boolean)
* return { changes: paths.map(path => ({ path, state: "modified" })),
* unpublished: 0 }
* })
* on("vcs.release", { vcs: "acme" }, async ($, e) => {
* for (const verb of ["shelve", "revert"]) {
* const argv = ["acme", "changelist", verb, e.name]
* const ran = await $.process.run(argv, { cwd: e.path })
* if (ran.exitCode !== 0) return { kept: ran.stderr }
* }
* return { isReleased: true }
* })
* @example
* // the model picks each command; it meets the permission check as the asker's
* // the mod picks the folder: what a command prints can steer the model
* on("vcs.isolate", async ($, e) => {
* const path = `${await $.env.get("HOME")}/acme-copies/${e.name}`
* let prompt = `Make an acme copy of ${e.from} at ${path}. Reply with ` +
* "one shell command, or DONE once it is made."
* for (let step = 0; step < 8; step++) {
* const reply = await $.model.fork({ prompt })
* if (!reply.isAnswered) return { deny: reply.reason }
* const command = reply.text.trim()
* if (command === "DONE") return { path, vcs: "acme" }
* const ran = await $.agent.call({ tool: "Bash", input: { command },
* agentId: e.parentAgentId })
* prompt += `\n$ ${command}\n${ran.deny ?? ran.text}`
* }
* return { deny: "no acme copy after 8 steps" }
* })
*/
'vcs.isolate': VcsIsolateInput;
/**
* Fires when the working copies of the repository holding `path` are asked
* for: EnterWorktree is to enter one by its path, a mod calls `$.vcs.list`,
* or a session recorded in a mod's copy is resumed after a restart.
*
* `next(e)` answers Git's worktrees, the main one among them, or none. On a
* mod's own call it answers only what `$.vcs.list` says it does, and none
* where a mod called EnterWorktree. Where the folder is not your system's,
* pass on with `next`; where systems share it, add your copies to what
* `next` answers. A hook that fails is skipped.
*
* EnterWorktree asks about the folder it is called from and refuses a path
* that is not on the list. A copy only a hook lists is entered, by its
* listed or its real path, once the person approves and the folder passes
* the vet of a `vcs.isolate` answer. Past that vet the engine runs no
* version control there and never asks `vcs.release` to take it away, until
* `vcs.isolate` answers it anew. A Git worktree, or a folder under
* `.claude/worktrees` of a Git checkout, is entered as it is unhooked.
*
* A session's resume asks about the folder Claude Code was started in, which
* may be the copy itself, and may ask before a session is bound (see
* `vcs.isolate`).
* A listed copy is entered again unprompted, and kept at every exit.
* That holds only where `vcs.detect` of it answers it as `root`, with a `mainRoot` elsewhere.
*
* Experimental: may change.
*
* @example
* on("vcs.list", async ($, e, next) => {
* const { exitCode, stdout } = await $.process.run(
* ["acme", "copies"], { cwd: e.path })
* if (exitCode !== 0) return next(e)
* return stdout.split("\n").filter(Boolean).map(path => ({ path, vcs: "acme" }))
* })
*/
'vcs.list': VcsListInput;
/**
* Fires when the engine asks what changed in a working copy and what
* removing it would lose: the subagent or the Remote Control session that
* worked there ended, ExitWorktree is to remove the session's, or the session
* is exiting inside it.
*
* `next(e)` answers for a copy the engine made, `{ unknown }` for any
* other. An agent's or a Remote Control session's copy is kept, and the
* person is asked about their own session's, where the answer lists a
* change, counts an unpublished revision, names a `revision` other than
* `since`, or is unknown. A hook can keep a worktree the engine made and
* reads but not call it clean: where the engine finds work there, its answer
* stands. Nor can it call clean the session's worktree, unless a mod made it.
* A mod's copy reads as unknown while an agent isolated in place inside it is
* not released. At exit an answer that takes too long reads as unknown. No
* hook is asked about a resumed session's worktree, or at the delete of a
* background session (`claude rm`), and a mod's copy is then kept. Resumed
* with `--worktree`, the hook is asked, and a mod's clean copy reads as
* unknown.
*
* A law the engine relies on: for a copy with its own folder, report
* everything removing that folder would lose, work kept there under other
* names included.
*
* On a mod's own `$.vcs.status`, `next(e)` also answers for the trusted
* workspace's Git repository and its worktrees, and is `{ unknown }` where
* that mod may not run Git or list a change.
*
* Experimental: may change.
*
* @example
* on("vcs.status", { vcs: "acme" }, async ($, e) => {
* const { exitCode, stdout, stderr } = await $.process.run(
* ["acme", "status", "--json"], { cwd: e.path })
* return exitCode === 0 ? JSON.parse(stdout) : { unknown: stderr }
* })
*/
'vcs.status': VcsStatusInput;
/**
* Fires when the engine would take a working copy away: it read clean with
* nothing unpublished, or what it holds is to be discarded (`isDiscard`).
* Raised at the end of a subagent or a Remote Control session, by
* ExitWorktree and by the exit dialog. The session may still stand in its
* copy then: give a process another `cwd`.
*
* `next(e)` removes a copy the engine made and answers `{ kept }` for any
* other: a copy a mod made goes only by a hook's own hand, and is kept where
* no mod hooks this. On a mod's own `$.vcs.release`, `next(e)` removes only
* a worktree made on that mod's own `$.vcs.isolate`, clean or to be discarded.
*
* Experimental: may change.
*
* @example
* on("vcs.release", { vcs: "acme" }, async ($, e) => {
* const { exitCode, stderr } = await $.process.run(
* ["acme", "drop", e.name, ...(e.isDiscard ? ["--force"] : [])])
* return exitCode === 0 ? { isReleased: true } : { kept: stderr }
* })
*/
'vcs.release': VcsReleaseInput;
/**
* Fires once per process for each loaded plugin, before the first prompt,
* then once per fresh load of one (never `/clear`); `next(e)` is `{ cwd }`.
*
* Observe. The first is awaited: a `$.tool.register` is listed by turn one.
* A later one runs its hooks alone: an enable, a worker respawn, or a reload
* (changed modules only; all if one hooks `engine.create`/`plugin.register`).
*
* @example
* on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
*/
'session.start': SessionStartInput;
/**
* Fires when a delivery reaches the session, before it is queued: a relay's
* event, a peer's message, a Remote Control prompt, room events; `{ text }`.
*
* Rewrite with `next({ ...e, text })`, or return `{ consumed: reason }` to
* take it: nothing is queued, shown or read by the model. `origin`,
* `event` and `agentId` pass on as received; `session.send` is its dual.
*
* @example
* on("session.receive", { origin: "peer" }, () => ({ consumed: "muted" }))
*/
'session.receive': SessionReceiveInput;
/**
* Fires once per row a conversation of this session keeps (a prompt, a
* response block, a tool result, a notice), before it is stored.
*
* `next({ ...e, message })` rewrites `content`: stored and sent after. The
* screen, an SDK stream or Remote Control may show the row just before its
* rewrite; the model and the transcript file never read that form.
*
* @example
* on("session.append", { door: "tool-result" }, ($, e, n) => n(scrub(e)))
*/
'session.append': SessionAppendInput;
/**
* Fires when a plain-text message is about to leave this conversation for
* another agent or session (the SendMessage tool, or `$.session.send`).
*
* `e.origin` says who sends, `e.agentId` which loop. Rewrite `text` or
* readdress `to` with `next` (a new `to` is judged again); `{ isDelivered:
* false, reason }` without `next` refuses it. `next(e)` resolves queued.
*
* @example
* on("session.send", ($, e, next) => next({ ...e, text: redact(e.text) }))
*/
'session.send': SessionSendInput;
/**
* Fires when the conversation is about to be compacted (`/compact`, the
* threshold, a plugin, or ahead of time); `next(e)` resolves `{ messages }`.
*
* Rewrite `instructions` or `messages` on the way down, the messages on
* the way up, or answer `{ messages }` of your own; `{ skip: reason }`
* leaves the conversation as it is. `trigger` passes on as received.
*
* @example
* on("session.compact", { trigger: "precompute" }, () => ({ skip: "off" }))
*/
'session.compact': SessionCompactInput;
/**
* Fires when a remote client joins the session's roster of attached
* surfaces: it said so (ui_attach), or it first asked to draw.
*
* Observe (a phone joined: draw the lobby); `next(e)` resolves to
* `{ clientId }`, a different return changes nothing. `$.session.surfaces()`
* reads the roster; a render hook still reads `e.surface` per ask.
*
* @example
* on("session.attach", { surface: "mobile" }, ($, e, next) => next(e))
*/
'session.attach': SessionAttachInput;
/**
* Fires when a client leaves the roster: it detached, or the session ended
* with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
*
* With reason `end` it runs inside `session.end`'s one short bound: there
* `next.budget` reads that bound and `next.signal` aborts at it.
*/
'session.detach': SessionDetachInput;
/**
* Fires when the engine measures the session and a unit moved: after each
* main-thread turn, and when a rate-limit window moves a whole point.
*
* Observe; `next(e)` echoes `{ changed }`. `$.session.usage()`'s figures,
* pushed, not polled: compare them with your own threshold here, call the
* op for the breakdown. One at a time, a burst folding into one more.
*
* @example
* on("session.measure", ($, e, next) => (toastPast90(e.rateLimits), next(e)))
*/
'session.measure': SessionMeasureInput;
/**
* Fires when the person presses Stop: Esc or Ctrl+C on a turn, a client's
* Stop, Ctrl+C at an idle prompt where it stops running scripts.
*
* A client's Stop fires per request, so one sent two ways may fire twice;
* with no turn running it fires in a headless session, not at a terminal.
* Never for send now, a priority message, `$.turn.abort` or a denied
* permission. Observe; `next(e)` echoes `{ isTurnRunning }`. The Stop goes
* on whatever a hook does, and input it queues is refused until
* it returns or the person sends input.
*
* Order: raised before the abort, and nothing waits on it. The outermost
* hooking mod's host hears it before that mod's `next(e)` on an interrupted
* call settles, so note the Stop before your first `await`. A mod beneath
* hears it once those above pass it on; across a hop, that may be a round
* trip later. `next.signal` may abort first.
*
* @example
* on("session.stop", ($, e, next) => ((isStopped = true), next(e)))
*/
'session.stop': SessionStopInput;
/**
* Fires once when the session ends (exit, /clear, resume, logout, signal, a
* `-p` run done), after its SessionEnd settings hooks; `e.reason` says which.
*
* `next(e)` runs the engine's end step, `{ sessionId }`; `e.resume.id` is
* `--resume`'s. Exits stay fast whatever is loaded: the whole chain shares
* one short wall-clock bound, which `next.budget` reads (SessionEndInput).
*
* @example
* on("session.end", async ($, e, next) => (await save(next.budget), next(e)))
*/
'session.end': SessionEndInput;
/**
* Fires once per hooks module about to join the chain, at load (the set
* folded and built, nothing swapped in) and at reload; core allows.
*
* Return `{ refuse: reason }` and it never joins: no hook, no noun, no tool
* of it; the debug log names who refused. Its judges, `$` whole, are the
* plugins admitted before it and the binary's; judge by `tier`, `uses` and
* `provides`. Pass `provides` on with entries removed to keep out those alone.
*
* @remarks A judge that fails is skipped and the module joins, so give it
* `.catch(($, e, next) => next.called ? next(e) : { refuse: "no" })`.
* @example
* on("plugin.register", { tier: "user" }, () => ({ refuse: "managed only" }))
*/
'plugin.register': PluginRegisterInput;
/**
* Fires when a model turn begins, main's or a subagent's (`e.agentId`),
* before its first model call; `next(e)` resolves to `{ turnId }`.
*
* Observe: a different return changes nothing. For the main loop alone,
* return `next(e)` first when `e.agentId !== undefined`. Every hook hears
* an agent's start, the spawner's too, as at its `turn.step`s, but for the
* hook whose `$` call ran a skill or command as a fork.
*/
'turn.start': TurnStartInput;
/**
* Fires when the engine is about to send a model request of a turn, main's
* or a subagent's (`e.agentId`); `next(e)` resolves to the whole response.
*
* `next({ ...e, model })` or `effort` sends another; the turn, the index and
* the message count are pinned. An answer without `next` sends no request.
* It streams (StreamNext): the hook's budget counts its own code alone.
*/
'turn.step': TurnStepInput;
/**
* Fires when a model turn has ended, at the point its duration is reported;
* `next(e)` resolves to `{ text }`, the answer. `e.reason` says why.
*
* Return `{ text }` with a different text to show it beneath the answer (a
* synopsis, a TL;DR line); the transcript's record is never rewritten. A
* hook that fails leaves the answer as it was.
*
* @remarks Every hook hears an agent's end (`e.agentId`), the spawner's
* too; a hook that heard the turn's start hears its end after it.
*/
'turn.complete': TurnCompleteInput;
/**
* Runs while `$` is being built, once per load or reload of this plugin
* and before any other hook of it; `next(e)` resolves to `$` built so far.
*
* A step may ADD nouns and, in `prepend` or `append`, WITHHOLD them (leave
* one out, or return without `next`). It fails, and its plugin unloads, when
* it REPLACES another's; in `user` or `builtin`, also past its own stub. A
* name two steps add is the first adder's, the innermost where they load
* together, but a `prepend` or `append` step takes one from a `user` step.
* Throwing or answering a wrong shape unloads it too, where another event's
* hook is skipped.
*/
'engine.create': EngineCreateInput;
};
EngineInterface interface
#
line 5984
In the first published surface (2.1.259)
$, the first parameter of every hook. Frozen; core's interface plus every noun the plugins' engine.create steps added.
Flat, <noun>.<event>; it does not carry on, since registration happens before $ exists. An interface so a plugin types the noun it provides by declaration merging, the way a jQuery plugin types $.fn.
declare module "claude-code" { interface EngineInterface { voice: Voice } }
export interface EngineInterface extends CoreEngineInterface {
}
EngineInterfaceBuilt type
#
line 5995
In the first published surface (2.1.259)
What next(e) resolves to at engine.create: $ as the steps beneath built it, typed as $ is, open to nouns no declaration names yet.
A withheld noun is on it as a stub (a step inside withheld it, or the last fold did and this is a reload), and the host refuses an op on one a step outside withholds later; a typed module bootstraps at load on it.
export type EngineInterfaceBuilt = EngineInterface & {
readonly [noun: string]: unknown;
};
EngineResultOf type
#
line 6002
In the first published surface (2.1.259)
The engine's events' results.
245 lines
export type EngineResultOf = {
/**
* `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`.
*/
'tool.call': ToolCallResult;
/**
* `{ decision, reason?, rule?, hook?, setting?, plugin?, ceiling? }`.
*/
'tool.check': ToolCheckResult;
/**
* `{ decision, reason?, plugin? }`.
*/
'tool.judge': ToolJudgeResult;
/**
* `{ result, context? }`, `{ deny }`, or core's `{ ref, result }`, read
* before any PostToolUse hook has had it.
*/
'tool.run': ToolCallResult;
/**
* The tree to draw; `{ type: "engine", ref }` is core's own drawing.
*/
'ui.render': RenderElement;
/**
* The surface's element table (Elements[e.surface]): constructors from props
* to a RenderElement.
*/
'ui.resolve': ElementTable;
/**
* `{ element }`: the element whose handler the press reached.
*/
'ui.press': UiPressResult;
/**
* `{ element, value }`: the field whose handler the input reached, and
* the text it received.
*/
'ui.input': UiInputResult;
/**
* `{ element, value }`: the picker whose handler the pick reached, and
* the value it received.
*/
'ui.select': UiSelectResult;
/**
* `{ props? }`: the posting instance's next props, when a hook hands some.
*/
'ui.message': UiMessageResult;
/**
* `{}`: the fault was heard.
*/
'ui.fault': UiFaultResult;
/**
* `{}`: the click was heard.
*/
'ui.pointer': UiPointerResult;
/**
* `{}` once the window moved, or `{ deny }`.
*/
'ui.scroll': UiScrollResult;
/**
* `{}` once the ring moved, or `{ deny }`.
*/
'ui.focus': UiFocusResult;
/**
* `{ isOffered }`.
*/
'agent.offer': AgentOfferResult;
/**
* `{ model }` or `{ deny }`.
*/
'agent.spawn': AgentSpawnResult;
/**
* `{ text, review, warning? }` (the report to deliver) or `{ consumed }`.
*/
'agent.report': AgentReportResult;
/**
* `{ text, context? }` or `{ drop }`.
*/
'prompt.submit': PromptSubmitResult;
/**
* `{ isFilled }`.
*/
'prompt.fill': PromptFillResult;
/**
* `{ isShown }`.
*/
'prompt.suggest': PromptSuggestResult;
/**
* `{ text, cursor }`, the box the editor shows next.
*/
'prompt.edit': PromptEditResult;
/**
* `{ text }`.
*/
'prompt.change': PromptChangeResult;
/**
* `{ suggestions }`, the rows the plugins add to the typeahead.
*/
'prompt.autocomplete': PromptAutocompleteResult;
/**
* `{ text }` (null leaves the section out).
*/
'prompt.section': PromptSectionResult;
/**
* `{ blocks }` (a block left out is not sent).
*/
'prompt.context': PromptContextResult;
/**
* `{ sections }`, every `shared` one ahead of every `session` one (a
* section left out is not sent).
*/
'prompt.compose': PromptComposeResult;
/**
* `{ text }` (null leaves the attachment out).
*/
'prompt.attachment': PromptAttachmentResult;
/**
* `{ type, context? }` (null when nothing was attached) or `{ deny }`.
*/
'prompt.mention': PromptMentionResult;
/**
* `{ description, isDeferred? }`.
*/
'tool.describe': ToolDescribeResult;
/**
* `{ isOffered }`.
*/
'tool.offer': ToolOfferResult;
/**
* `{ text }` (the command's output, when it printed one).
*/
'command.run': CommandRunResult;
/**
* `{ description, argumentHint, isHidden }`.
*/
'command.describe': CommandDescribeResult;
/**
* `{ value }` once written, or `{ deny }`.
*/
'config.set': ConfigSetResult;
/**
* `{ label, description, isHidden }`.
*/
'config.describe': ConfigDescribeResult;
/**
* `{ value: undefined }`, or `{ deny }`.
*/
'telemetry.log': TelemetryLogResult;
/**
* `{ value: undefined }`, or `{ deny }`.
*/
'telemetry.mark': TelemetryMarkResult;
/**
* `{ text }`.
*/
'skill.prompt': SkillPromptResult;
/**
* `{ text }`.
*/
'attribution.text': AttributionTextResult;
/**
* The working copy the folder is in, or null.
*/
'vcs.detect': VcsDetectResult;
/**
* `{ base, files }`, or `{ unknown }` with the reason, null from core.
*/
'vcs.diff': VcsDiffResult;
/**
* `{ path, vcs, branch?, revision? }`, or `{ deny }`.
*/
'vcs.isolate': VcsIsolateResult;
/**
* A list of `{ path, vcs, branch? }`, possibly empty.
*/
'vcs.list': VcsListResult;
/**
* `{ changes, unpublished, revision? }`, or `{ unknown }`.
*/
'vcs.status': VcsStatusResult;
/**
* `{ isReleased: true, note? }`, or `{ kept }`.
*/
'vcs.release': VcsReleaseResult;
/**
* `{ cwd }`.
*/
'session.start': SessionStartResult;
/**
* `{ text }`, or `{ consumed }`.
*/
'session.receive': SessionReceiveResult;
/**
* `{ message, uuid }`, the row as stored.
*/
'session.append': SessionAppendResult;
/**
* `{ isDelivered: true }`, or `{ isDelivered: false, reason }`.
*/
'session.send': SessionSendResult;
/**
* `{ messages, tokensBefore?, tokensAfter? }`, or `{ skip }`.
*/
'session.compact': SessionCompactResult;
/**
* `{ clientId }`.
*/
'session.attach': SessionAttachResult;
/**
* `{ clientId }`.
*/
'session.detach': SessionDetachResult;
/**
* `{ changed }`.
*/
'session.measure': SessionMeasureResult;
/**
* `{ isTurnRunning }`.
*/
'session.stop': SessionStopResult;
/**
* `{ sessionId }`.
*/
'session.end': SessionEndResult;
/**
* `{ allow: true }`, or `{ refuse }`.
*/
'plugin.register': PluginRegisterResult;
/**
* `{ turnId }`.
*/
'turn.start': TurnStartResult;
/**
* The response: `{ turnId, index, answer, toolUses, stopReason, usage }`,
* and `serverToolUses` when the API ran tools of its own in the request.
*/
'turn.step': TurnStepResult;
/**
* `{ text }`.
*/
'turn.complete': TurnCompleteResult;
/**
* `$` as built so far, with this plugin's interface added and any it
* withheld left out; `next(e)` resolves to EngineInterfaceBuilt.
*/
'engine.create': EngineCreateResult;
};
EnvSetResult type
#
line 6252
Added in 2.1.301
What $.env.set resolves to and what an env.set hook's { value } holds: {} once the variable is set or unset, or why it was not.
14 lines
type EnvSetResult = {
/**
* Absent when the write was made; else why not, in one line.
*
* In a session that takes its settings from its organization, the engine
* holds a plugin's write, a built-in's too, where a person's own settings
* file could not set the variable there.
*
* @remarks The engine's hold resolves; a hook's own `{ deny }` rejects the
* caller, and one given after `next(e)` was answered fails the hook: deny
* in its place. A hook above may answer another `{ value }`: no write.
*/
deny?: string;
};
EventCalls type
#
line 6276
In the first published surface (2.1.259) · changed in 2.1.260, 2.1.265, 2.1.267, 2.1.268, 2.1.269, 2.1.271, 2.1.275, 2.1.277, 2.1.280, 2.1.284, 2.1.285, 2.1.286, 2.1.290, 2.1.299, 2.1.326, 2.1.328, 2.1.329, 2.1.330
The engine's own events as calls on $, one signature each: $.<noun>.<event>(input) resolves to its result, or to its stream.
The engine raises its events through these same calls; a plugin's call runs the same chain with the calling hook skipped, and a person's hooks where the organization's mod calls (Tier). input may leave out what the engine fills (tool_use_id, the parent agent).
74 lines
export type EventCalls = {
tool: {
call: ToolCallOverloads;
check: (input: ToolCheckArgs) => Promise<ToolCheckResult>;
judge: (input: ToolJudgeInput) => Promise<ToolJudgeResult>;
run: (input: ToolCallInput) => Promise<ToolCallResult>;
describe: (input: ToolDescribeInput) => Promise<ToolDescribeResult>;
offer: (input: ToolOfferInput) => Promise<ToolOfferResult>;
};
command: {
run: (input: CommandRunArgs) => Promise<CommandRunResult>;
describe: (input: CommandDescribeInput) => Promise<CommandDescribeResult>;
};
config: {
set: (input: ConfigSetArgs) => Promise<ConfigSetResult>;
describe: (input: ConfigDescribeInput) => Promise<ConfigDescribeResult>;
};
prompt: {
submit: (input: PromptSubmitArgs) => Promise<PromptSubmitResult>;
fill: (input: PromptFillArgs) => Promise<PromptFillResult>;
suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
context: (input: PromptContextInput) => Promise<PromptContextResult>;
attachment: (input: PromptAttachmentInput) => Promise<PromptAttachmentResult>;
mention: (input: PromptMentionInput) => Promise<PromptMentionResult>;
compose: (input?: PromptComposeArgs) => Promise<PromptComposeResult>;
};
skill: {
prompt: (input: SkillPromptArgs) => Promise<SkillPromptResult>;
};
attribution: {
text: (input: AttributionTextInput) => Promise<AttributionTextResult>;
};
vcs: {
detect: (input: VcsDetectInput) => Promise<VcsDetectResult>;
diff: (input: VcsDiffInput) => Promise<VcsDiffResult>;
isolate: (input: VcsIsolateInput) => Promise<VcsIsolateResult>;
list: (input: VcsListInput) => Promise<VcsListResult>;
status: (input: VcsStatusInput) => Promise<VcsStatusResult>;
release: (input: VcsReleaseInput) => Promise<VcsReleaseResult>;
};
agent: {
offer: (input: AgentOfferInput) => Promise<AgentOfferResult>;
spawn: (input: AgentSpawnArgs) => Promise<AgentSpawnResult>;
report: (input: AgentReportInput) => Promise<AgentReportResult>;
};
session: {
start: (input: SessionStartInput) => Promise<SessionStartResult>;
receive: (input: SessionReceiveInput) => Promise<SessionReceiveResult>;
append: (input: SessionAppendInput) => Promise<SessionAppendResult>;
send: (input: SessionSendArgs) => Promise<SessionSendResult>;
compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
measure: (input: SessionMeasureInput) => Promise<SessionMeasureResult>;
stop: (input: SessionStopInput) => Promise<SessionStopResult>;
end: (input: SessionEndInput) => Promise<SessionEndResult>;
};
telemetry: {
log: (input: TelemetryLogArgs) => Promise<TelemetryLogResult>;
mark: (input: TelemetryMarkInput) => Promise<TelemetryMarkResult>;
};
turn: {
start: (input: TurnStartInput) => Promise<TurnStartResult>;
step: (input: TurnStepInput) => HookStream<TurnStepChunk, TurnStepResult>;
complete: (input: TurnCompleteInput) => Promise<TurnCompleteResult>;
};
ui: {
render: <C extends RenderComponent>(input: RenderInput<C>) => Promise<RenderElement>;
resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
scroll: (input: UiScrollArgs) => Promise<UiScrollResult>;
focus: (input: UiFocusArgs) => Promise<UiFocusResult>;
};
};
EventName type
#
line 6355
In the first published surface (2.1.259)
The name of an event: a key of EventOf, the engine's own (CoreEventName) and the declared plugin nouns' (NounEventName).
export type EventName = keyof EventOf;
EventOf type
#
line 6365
In the first published surface (2.1.259) · changed in 2.1.265
The argument of each event, by event name: what a hook receives as e and what the call on $ takes. Plain data, frozen to every depth.
The engine's own events (CoreEventOf: a plugin's $.fs.write(...) is a dispatch the hooks above it see) and the methods of the plugin nouns declared on EngineInterface (NounEventOf).
export type EventOf = CoreEventOf & NounEventOf;
EventResult type
#
line 6371
In the first published surface (2.1.259)
The result of event N: what its hooks return and what their next(e) resolves to.
export type EventResult<N extends EventName = EventName> = ResultOf[N];
Events type
#
line 6388
In the first published surface (2.1.259) · changed in 2.1.268, 2.1.269
The hook signature of each event, ($, e, next), as one mapped type over EventOf; a streaming event's is the generator form (StreamHook).
With one handler type per event, Events[E] for a generic E would be a union; as one mapped type it stays a single function type the engine calls without a cast (TS 4.6 correlated unions).
$- the engine interface, frozen, the same object at every invocation; at
engine.createthe empty table, since$exists after the fold e- the event's argument, frozen to every depth (
e.command = "ls"is a type error and throws); a rewrite is a copy passed tonext next- the rest of the chain; a chain a hook raises through
$skips this hook and runs every other, its plugin's others too
export type Events = {
[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>>;
};
ExitReason type
#
line 6392
Added in 2.1.265
type ExitReason = 'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other';
FileChangedHookInput type
#
line 6394
Added in 2.1.265
type FileChangedHookInput = BaseHookInput & {
hook_event_name: 'FileChanged';
file_path: string;
event: 'change' | 'add' | 'unlink';
};
Frozen type
#
line 6407
Added in 2.1.268 · changed in 2.1.290
T with every property read-only to every depth, arrays and tuples kept as declared: how a hook's e is typed.
e.command = 'x' is a type error; next({ ...e, command: 'x' }) compiles. A string is kept as typed, so a union that names some strings keeps them.
export type Frozen<T> = T extends string | ((...args: never[]) => unknown) ? T : T extends readonly unknown[] ? {
[K in keyof T]: Frozen<T[K]>;
} : T extends object ? {
readonly [K in keyof T]: Frozen<T[K]>;
} : T;
FsAncestor type
#
line 6417
In the first published surface (2.1.259) · changed in 2.1.275
One file $.fs.ancestors found: the directory it stands in, the name it was asked for by, and its text as the engine's memory loader reads it.
19 lines
export type FsAncestor = {
/**
* The directory the file stands in, absolute.
*/
dir: string;
/**
* The spelling the caller asked for it by.
*/
name: string;
/**
* The file's text, with what its `@include`s bring after it.
*/
content: string;
/**
* The file and then each file its `@` imports brought, in load order,
* path and text apiece; `content` is these texts joined.
*/
parts: readonly FsAncestorPart[];
};
FsAncestorPart type
#
line 6440
Added in 2.1.275
One file of an ancestor entry: the file itself or one it imported.
export type FsAncestorPart = {
/**
* The file's path, absolute.
*/
path: string;
/**
* Its text as the engine's memory loader reads it.
*/
content: string;
};
FsAncestorsRequest type
#
line 6459
In the first published surface (2.1.259) · changed in 2.1.277
The argument of $.fs.ancestors: the file names to look for in each directory, the file to walk down to, and the directory to walk beneath.
Where a rule or a hold confines the session's reads, a file is found only where every name its path goes by may be read; under a hold a folder above the working directory gives only instruction files of its own.
24 lines
export type FsAncestorsRequest = {
/**
* Relative `.md` file names, each looked for in every directory.
*/
names: readonly string[];
/**
* The file the walk goes on down to the directory of, relative to the
* working directory or absolute; absent, it ends at the working directory.
*
* Without `below`, a plain name or one under `.claude`, in the working
* directory or above it, is judged as the engine's start-up load is; any
* other file by the main session, and with none bound the call rejects.
*/
of?: string;
/**
* The directory the walk starts beneath, relative to the working directory
* or absolute; absent, the walk starts at the filesystem root.
*
* Only directories strictly inside it are read, each file as the main
* session's rules on reads judge it, as the engine reads a nested
* CLAUDE.md; a file not inside it finds nothing.
*/
below?: string;
};
FsBytes type
#
line 6488
Added in 2.1.277
What $.fs.read(path, { as: "bytes" }) resolves with: the file's bytes, base64, since only plain data crosses into a plugin's environment.
export type FsBytes = {
/**
* The bytes read, standard padded base64;
* `Uint8Array.fromBase64(base64)` gives the bytes back.
*/
base64: string;
};
FsEntry type
#
line 6499
In the first published surface (2.1.259) · changed in 2.1.277, 2.1.284
One entry of $.fs.list: the entry itself, a link not followed.
30 lines
export type FsEntry = {
/**
* The entry's name (no directory part).
*/
name: string;
/**
* `file`, `dir`, or `other`, of the entry itself: a symbolic link is
* `other` (`$.fs.stat` says what it leads to, and with `resolve` where).
*/
kind: 'file' | 'dir' | 'other';
/**
* Bytes, for a file.
*/
size: number;
/**
* Last modification, milliseconds since the epoch, for a file, as
* `$.fs.stat` spells it; 0 for a directory, a link or any other kind.
*
* The listing reads a regular file's size and time in its one call and
* looks no other entry up: `$.fs.stat` answers a directory's.
*
* @example
* const newest = [...entries].sort((a, b) => b.mtimeMs - a.mtimeMs)[0]
*/
mtimeMs: number;
/**
* True when the entry is a symbolic link.
*/
isLink: boolean;
};
FsReadAs type
#
line 6533
Added in 2.1.277
How $.fs.read answers: text (UTF-8, the default) or bytes (base64).
export type FsReadAs = 'text' | 'bytes';
FsReadBytesOptions type
#
line 6539
Added in 2.1.277 · changed in 2.1.326
The options of $.fs.read that ask for the bytes: the call answers { base64 }.
14 lines
export type FsReadBytesOptions = {
/**
* `bytes`.
*/
as: 'bytes';
/**
* Where the read starts, in bytes (FsReadOptions).
*/
offset?: number;
/**
* The most bytes to read, up to 4 MiB (FsReadOptions).
*/
length?: number;
};
FsReadCall type
#
line 6558
Added in 2.1.277 · changed in 2.1.326
$.fs.read: the file's text, or with { as: "bytes" } its bytes as { base64 }; with offset or length, that range of it.
export type FsReadCall = {
(path: string): Promise<string>;
(path: string, options: FsReadBytesOptions): Promise<FsBytes>;
(path: string, options: FsReadTextOptions): Promise<string>;
(path: string, options: FsReadOptions): Promise<string | FsBytes>;
};
FsReadOptions type
#
line 6568
Added in 2.1.277 · changed in 2.1.326
The options of $.fs.read: how it answers, and which bytes of the file.
22 lines
export type FsReadOptions = {
/**
* `bytes` answers `{ base64 }` for a binary file; `text` (the default) the
* file's text.
*/
as?: FsReadAs;
/**
* Where the read starts, a whole number of bytes from the file's start.
* Absent, the start; past the end, the read is empty.
*/
offset?: number;
/**
* The most bytes to read, a whole number up to 4 MiB; fewer come back where
* the file ends first. Absent, the rest, refused when over 4 MiB.
*/
length?: number;
/**
* Never given: it keeps a string or an array, which has a `length` too, from
* passing as options.
*/
[Symbol.iterator]?: never;
};
FsReadTextOptions type
#
line 6595
Added in 2.1.326
The options of $.fs.read that ask for the text: the call answers a string, U+FFFD at an edge where the range cuts a character.
19 lines
export type FsReadTextOptions = {
/**
* `text`, the default.
*/
as?: 'text';
/**
* Where the read starts, in bytes (FsReadOptions).
*/
offset?: number;
/**
* The most bytes to read, up to 4 MiB (FsReadOptions).
*/
length?: number;
/**
* Never given: it keeps a string or an array, which has a `length` too, from
* passing as options.
*/
[Symbol.iterator]?: never;
};
FsStat type
#
line 6619
In the first published surface (2.1.259) · changed in 2.1.277
What $.fs.stat resolves with: what the path leads to, whether the path itself is a symbolic link, and where it lands when asked.
32 lines
export type FsStat = {
/**
* `file`, `dir`, or `other`, of what the path leads to: a link is
* followed, and one that leads nowhere is `other`.
*/
kind: 'file' | 'dir' | 'other';
/**
* Bytes, for a file.
*/
size: number;
/**
* Last modification, milliseconds since the epoch.
*/
mtimeMs: number;
/**
* True when the path itself is a symbolic link; `kind`, `size` and
* `mtimeMs` then describe what it points at, or the link when that is gone.
*/
isLink: boolean;
/**
* Where the path landed when asked with `{ resolve: true }`: absolute,
* every symbolic link followed, `.` and `..` folded; else absent.
*
* Absent too when the path leads nowhere or a hook above withheld it, so
* a guard denies without it; and a hard link, a volume or file-id spelling
* (macOS `/.vol/`) or a case alias keeps its own spelling, `isLink` false.
*
* @remarks a deny-list on spellings is thus best effort; an allow-list on
* `realPath` under a root resolved the same way is the robust guard.
*/
realPath?: string;
};
FsStatOptions type
#
line 6655
Added in 2.1.277
The options of $.fs.stat.
export type FsStatOptions = {
/**
* True to resolve where the path lands as well.
*
* The answer then carries `realPath` when the path leads somewhere, at
* the cost of one more file system call: where it landed then, not a hold
* on what a tool opens afterwards.
*/
resolve: boolean;
};
Glob type
#
line 6673
Added in 2.1.265
Every event (*), or every event under a namespace (classic.*: each one whose name starts with classic.).
But a telemetry event, which is hooked by name (telemetry.log, or telemetry.* for all): * does not select one for an installed plugin.
export type Glob = '*' | `${Namespace}.*`;
GlobHook type
#
line 6683
Added in 2.1.265 · changed in 2.1.268
The hook on(pattern, hook) takes for a glob or a negation: one function placed on every selected event, e and the result typed as their union.
next.event says which event a run is; next.is(pattern, e) narrows e to one of them. At engine.create (a negation may select it) $ is the empty table and the hook observes the fold, as a * hook does.
export type GlobHook<P extends Pattern, N extends EventName = Selected<P>> = ($: EngineInterface, e: Frozen<Args<N>>, next: GlobNext<P>) => EventResult<N> | Promise<EventResult<N>>;
GlobNext type
#
line 6692
Added in 2.1.265 · changed in 2.1.267, 2.1.268, 2.1.275, 2.1.328
next in a hook on a glob or a negation: an overload per selected event, then one over their union for an e not yet narrowed.
is narrows e to the selected events its pattern names; event is one of the selected names.
14 lines
export type GlobNext<P extends Pattern, N extends EventName = Selected<P>> = OrderedOverloads<N> & {
(e: Args<N>): Promise<GlobNextResult<N>>;
/**
* Continues this dispatch at a tier, as Next's `to` (a managed hook's),
* over the selected events' union for an `e` not yet narrowed.
*/
readonly to: (e: Args<N>, tier: TargetTier) => Promise<GlobNextResult<N>>;
readonly signal: AbortSignal;
readonly is: <M extends PatternOver<N>>(pattern: M, e: unknown) => e is Frozen<Args<Extract<N, Selected<M>>>>;
readonly event: N;
readonly origin: NextOrigin;
readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
readonly budget: NextBudget;
};
GlobNextResult type
#
line 6711
Added in 2.1.265
What next(e) resolves to in a glob hook before e is narrowed: the NextResult of each selected event, as a union.
type GlobNextResult<N extends EventName> = {
[K in N]: NextResult<K>;
}[N];
Hook type
#
line 6718
In the first published surface (2.1.259)
One hook, ($, e, next), on event E.
export type Hook<E extends EventName = EventName> = Events[E];
HookBudget type
#
line 6738
Added in 2.1.275
The time bounds every hook runs under, in milliseconds: the engine's own constants are typed by these members, and next.budget reads the live one.
Each bounds the hook's OWN time: the clock stops while a next(e) call or any $ call of the hook's is in flight (a $.clock wait excepted), so a slow chain beneath or a minute-long $.model.complete costs it nothing. On tool.list and ui.render a hook's $ calls hold it for 30 seconds in all, then fail it; on plugin.register for 10 seconds, $.ui.ask aside: a person answers in their own time. On tool.call, tool.check, tool.judge, tool.run and classic.PreToolUse for 20 minutes, a stream's reads included, not counted while next(e), $.ui.ask, $.tool.call, $.agent.call, $.agent.spawn or $.mcp.call is in flight, and not at all for a tool.call or tool.run hook on a tool its own plugin registered: it is that tool's body.
await $.model.complete(ask) // a minute; next.budget.remainingMs unmoved
27 lines
export type HookBudget = {
/**
* A hook's budget per dispatch, from its call to its return; past it the
* hook is absent (its `.catch` asked, else `next(e)` run on its behalf).
*
* A streaming hook's (an async generator) counts only while its own code
* runs, never at a `yield` or while it reads beneath: on `turn.step` the
* sum over the response; on `process.spawn` per piece, anew at each pull.
*/
readonly ms: 10_000;
/**
* A `.catch` handler's grace: a fresh budget from the moment it is called,
* on the same clock (its `next` replay and its `$` calls are free).
*
* Past it the hook is absent as if it had no handler; `next.error.budget`
* and `next.budget.ms` both read it there. `engine.create` has no budget.
*/
readonly catchMs: 1_000;
/**
* How long a hook may keep running after `next.signal` aborted (the person
* interrupted, a hook above settled first, its own budget ran out).
*
* Past it the hook is reported as lingering; the dispatch had already gone
* on without it when the signal aborted.
*/
readonly lingerMs: 5_000;
};
HookFailure type
#
line 6774
Added in 2.1.267 · changed in 2.1.292, 2.1.300, 2.1.301
Why a hook failed, as its .catch handler reads it on next.error: plain frozen data.
throw: it threw, returned what the site refuses, or its hooks worker ended under it, message saying what; timeout: it outran its budget, message then what its last next() rejected with, if it did.
13 lines
export type HookFailure = {
readonly kind: 'throw' | 'timeout';
/**
* What was thrown or why the worker ended, or for a timeout what the last
* `next()` rejected with; absent for a timeout with nothing rejected.
*/
readonly message?: string;
/**
* The grace the handler runs under, in milliseconds; past it, the hook is
* absent as if it had no handler.
*/
readonly budget: number;
};
HookFor type
#
line 6796
In the first published surface (2.1.259) · changed in 2.1.265
The hook type per pattern: an event's own (Events), *'s (AnyEventHook), or a glob's over the events it selects (GlobHook), as one conditional type.
One type, so the two-argument on stays ONE generic signature: as an overload set the language service offers no tool-name completions inside e.tool === "; as an index into a table TS intersects every argument.
export type HookFor<P extends Pattern> = P extends '*' ? AnyEventHook : P extends EventName ? Events[P] : GlobHook<P>;