Follow Discord
Sweep 25 Sep 2026 · 19:33Z Build v2.1.283 504 read Stable v2.1.274 Latest v2.1.283 Next v2.1.283 Feeds RSS JSON llms.txt llms-full.txt Unofficial
Mods API · 03 of 03

Types

Every declaration in the file, verbatim, with the doc comment above it.

Declarations570over 12 pages
Mined from2.1.283the shipped binary

Every named declaration in the file, 570 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 13,820 lines of TypeScript mined from build 2.1.283. 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, 151 to 200 of 570

InvalidatableEventName type # line 4968

In the first published surface (2.1.259) · changed in 2.1.265, 2.1.269, 2.1.277

What $.ui.invalidate takes: a render event, or one of the six events whose answers the engine caches for the session.

  export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'prompt.attachment' | 'tool.describe' | 'command.describe' | 'config.describe';

IsDiscriminant type # line 4978

In the first published surface (2.1.259)

Whether tag key K selects members of I: it does when each member gives it ONE literal (component: "ToolUse" on the ToolUse variant).

A key that is the same union on every member is a filter at runtime; it is left out of the selection so that it cannot defeat the narrowing the other keys give.

  type IsDiscriminant<I, K> = I extends unknown ? K extends KnownKeys<I> ? IsSingleLiteral<I[K]> : true : never;

IsLiteralValued type # line 4983

In the first published surface (2.1.259)

Whether V is made of literals only: "a" | "b" is, string is not.

  type IsLiteralValued<V> = string extends V ? false : number extends V ? false : boolean extends V ? false : [V] extends [string | number | boolean] ? true : false;

IsSingleLiteral type # line 4988

In the first published surface (2.1.259)

Whether V is exactly one string, number or boolean literal.

  type IsSingleLiteral<V> = [V] extends [string | number | boolean] ? IsUnion<V> extends true ? false : true : false;

IsUnion type # line 4993

In the first published surface (2.1.259)

Whether T is a union of two or more members.

  type IsUnion<T, U = T> = T extends unknown ? [U] extends [T] ? false : true : never;

JsonValue type # line 5002

Added in 2.1.267

Plain data: what JSON holds, and what crosses between a plugin's hooks module and its surface module whole (a Client's props, a post's data).

A function, a class instance, undefined or a cycle is not plain data; the engine refuses one where it checks, and drops it where it clones.

  export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
      readonly [key: string]: JsonValue;
  };

KeptEvent type # line 5010

In the first published surface (2.1.259) · changed in 2.1.265

What next takes in a matched hook: the variants of e the matcher can match (KeptMembers), as declared, so a rewrite of a pinned field passes.

  type KeptEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? KeptMembers<Args<N>, M> : never : never;

KeptMembers type # line 5019

In the first published surface (2.1.259)

The members of the argument union E matcher P can match, as declared; what next takes, so a rewrite may change a field the matcher pinned.

A member is dropped when P names a key it lacks, or gives a key, at any depth, a value none of that key's values can equal (ImpossibleKeys).

  type KeptMembers<E, P> = E extends unknown ? [ImpossibleKeys<E, P, []>] extends [never] ? E : never : never;

KnownKeys type # line 5024

In the first published surface (2.1.259)

The declared keys of T, the string and number index signatures left out.

  type KnownKeys<T> = keyof {
      [K in keyof T as string extends K ? never : number extends K ? never : K]: 0;
  };

LateOverload type # line 5034

Added in 2.1.265

The events whose overload must come after the rest, lest it shadow them.

classic.PreToolUse shares tool.call's envelope, turn.abort every turn event's turnId, and an object of any shape is assignable to NoArgs.

  type LateOverload = 'classic.PreToolUse' | 'turn.abort' | NoArgsEvent;

LinkProps type # line 5044

Added in 2.1.260

The props of Link, a hyperlink every surface draws: an OSC 8 span on the terminal (else its text then the URL in dim), an anchor on desktop.

An inline element: its children are the text, strings and inline elements; absent children the label, absent both the URL. The engine bounds href before the tree crosses.

15 lines
  export type LinkProps = {
      /**
       * Where the link goes: an `https:` URL (or `http://localhost`), at most
       * 2048 characters of printable ASCII, spelled as `new URL(href).href`.
       *
       * No `user@host` part, no raw `@`, space or non-ASCII letter (encode them);
       * anything else refuses the tree the Link is in.
       */
      href: string;
      /**
       * The text drawn when the element has no children; absent both, the URL
       * itself is the text.
       */
      label?: string;
  };

Literal type # line 5064

In the first published surface (2.1.259)

What a matcher value selects by: itself, or unknown for a RegExp, which selects nothing.

  type Literal<X> = X extends RegExp ? unknown : X;

MarkdownLeafProps type # line 5070

Added in 2.1.274

What a Markdown carries across the boundary: its address, text, dimness and which links it answers; onLinkPress stays behind, a press instead.

20 lines
  export type MarkdownLeafProps = {
      /**
       * The element's address: what `e.element` carries and what a matcher
       * names; present whenever the element carries a `press`.
       */
      key?: string;
      /**
       * The markdown drawn, bounded as a Text's string is.
       */
      text: string;
      /**
       * The whole block dim, as `Text`'s `dimColor`; absent draws as false.
       */
      dimColor?: boolean;
      /**
       * Which links a press belongs to, by `href` as written; absent, with a
       * `press`, every link drawn. Compared with the pressed target only.
       */
      pressableLinks?: readonly string[];
  };

MarkdownProps type # line 5099

Added in 2.1.274

The props of Markdown, a block of markdown every surface draws as it draws an assistant reply's text: its own renderer, links, tables, fences.

A leaf: no children. text is the element's data as a Text's string is, bounded the same way. With onLinkPress the links it draws are the plugin's to answer: a press on one raises ui.press addressed to key.

38 lines
  export type MarkdownProps = {
      /**
       * The element's address: `e.element` at `ui.press`, what a matcher names.
       * Required with `onLinkPress`, since a press needs one; else optional.
       */
      key?: string;
      /**
       * The markdown drawn, as an assistant reply would write it; a `<context>`
       * block, hidden in a reply's own text, is drawn here as written.
       *
       * At most 10000 characters, tab and newline its only control characters;
       * a link whose scheme is not `https:`, `http:` or `file:` draws as text,
       * never clickable. Not drawn around the approval dialog.
       */
      text: string;
      /**
       * The whole block dim, as `Text`'s `dimColor`: a thought, an aside.
       */
      dimColor?: boolean;
      /**
       * What a press on a link in `text` runs, in the plugin's own environment:
       * the bottom of a `ui.press` chain whose `e.link` names the link.
       *
       * A press is a plain single click where the surface reports clicks (the
       * fullscreen terminal): it opens nothing and lands once no double-click
       * followed; a ctrl, alt or terminal-kept cmd click opens it as before.
       */
      onLinkPress?: (link: PressedLink, e: UiPressArgument) => void;
      /**
       * Which links in `text` a press belongs to, by `href` as the markdown
       * writes it; absent, every link drawn. Only with `onLinkPress`.
       *
       * A link left out keeps the surface's own behaviour. At most 256 entries
       * of at most 2048 characters; compared with the pressed link's target,
       * never opened.
       */
      pressableLinks?: readonly string[];
  };

MatchedEvent type # line 5142

In the first published surface (2.1.259) · changed in 2.1.265

The argument a matched hook receives: e narrowed by M (Narrowed), per event the registration covers.

  export type MatchedEvent<P extends Pattern, M> = MatchedNames<P, M> extends infer N extends EventName ? N extends unknown ? Narrowed<Args<N>, M> : never : never;

MatchedHook type # line 5152

In the first published surface (2.1.259) · changed in 2.1.265, 2.1.268, 2.1.269

The hook on(pattern, matcher, hook) takes: ($, e, next) with e narrowed by the matcher (MatchedEvent), and a tagged result the same way.

On a streaming event it is the generator form (MatchedStreamHook). next takes the variants the matcher keeps, as declared (KeptEvent); next.is names the events the registration covers and narrows as the matcher does.

  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>, {
      [K in MatchedNames<P, M>]: Narrowed<Args<K>, M>;
  }>) => MatchedResult<P, M> | Promise<MatchedResult<P, M>>;

MatchedNames type # line 5160

In the first published surface (2.1.259) · changed in 2.1.265

The events a matched registration on P covers: the event named, or for a glob every selected event whose input has each key the matcher names.

  type MatchedNames<P, M = never> = P extends EventName ? P : {
      [N in Selected<P & string>]: [M] extends [never] ? N : keyof M extends AnyKeyOf<Args<N>> ? N : never;
  }[Selected<P & string>];

MatchedResult type # line 5168

In the first published surface (2.1.259) · changed in 2.1.265

What a matched hook returns: the event's result, narrowed by M where the result is a union tagged by the matcher's tag keys.

  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;

MatchedStreamHook type # line 5174

Added in 2.1.269

The hook on(event, matcher, hook) takes on a streaming event: the generator form, e narrowed by the matcher, next(e) the stream beneath.

  export type MatchedStreamHook<P extends StreamingEventName, M> = ($: EngineInterface, e: Frozen<MatchedEvent<P, M>>, next: MatchedStreamNext<P, M>) => StreamHookBody<Chunk<P>, MatchedResult<P, M>>;

MatchedStreamNarrowings type # line 5180

Added in 2.1.269

What a matched streaming hook's next.is(pattern, e) narrows e to: the streaming event's argument narrowed by the matcher.

  type MatchedStreamNarrowings<P extends StreamingEventName, M> = {
      [K in P]: Narrowed<Args<K>, M>;
  };

MatchedStreamNext type # line 5188

Added in 2.1.269

A matched streaming hook's next: the variants the matcher keeps, the result tagged the same way, next.is narrowing as the matcher does.

  type MatchedStreamNext<P extends StreamingEventName, M> = StreamNext<P, KeptEvent<P, M>, MatchedResult<P, M>, MatchedStreamNarrowings<P, M>>;

Matcher type # line 5198

In the first published surface (2.1.259)

What on(event, matcher, hook) takes for an argument of type I: the shape of the e the hook wants, a partial of it at any depth.

A leaf is === or a RegExp ({ command: /^p4 / }); an array is any-of; an object is a partial of an OBJECT, so { command: { startsWith } } is a type error where e is typed and free where it is unknown.

  export type Matcher<I, All = I> = I extends unknown ? {
      readonly [K in KnownKeys<I>]?: MatcherValue<I[K], MatcherValueOf<All, K>>;
  } & (string extends keyof I ? OpenMatcher<I, All> : unknown) : never;

MatcherData type # line 5210

In the first published surface (2.1.259)

Any matcher at all, for a field typed unknown (a tool's input, a result's output): the kinds the engine accepts, unchecked there.

The four kinds: a scalar is ===; a RegExp tests the value as a string ({ command: /^p4 / }); an array matches if any element does; an object is a partial of an object. { startsWith: 'p4' } never matches a string.

  type MatcherData = string | number | boolean | null | RegExp | readonly MatcherData[] | {
      readonly [key: string]: MatcherData;
  };

MatcherKeys type # line 5217

In the first published surface (2.1.259)

The declared keys of every variant of I (index signatures aside).

  type MatcherKeys<I> = I extends unknown ? KnownKeys<I> : never;

MatcherOne type # line 5227

In the first published surface (2.1.259) · changed in 2.1.267

What matches one value of type V, by the runtime's kinds: a scalar leaf takes the value or a RegExp; an object, a partial of it.

For an array, what matches one ELEMENT of it, since a pattern against an array value holds when some element matches; for unknown, any matcher. A scalar matches by ===, a RegExp tests the value as a string.

  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;

MatcherValue type # line 5237

In the first published surface (2.1.259)

What a matcher gives a key whose value is V on this variant and Across over every variant: one MatcherOne, or an array of them matched as one-of.

The one-of is typed over every variant, so { tool: ['Bash', 'Read'] } types on the Bash variant; with a nested pattern beside it, the pattern is checked against a variant the one-of names, not against each of them.

  type MatcherValue<V, Across = V> = MatcherOne<V> | readonly MatcherOne<Across>[];

MatcherValueOf type # line 5242

In the first published surface (2.1.259)

The type of key K across the variants of I that declare it.

  type MatcherValueOf<I, K> = I extends unknown ? K extends KnownKeys<I> ? I[K] : never : never;

McpContentBlock type # line 5247

In the first published surface (2.1.259)

One block of an MCP result: type and the fields that kind of block carries.

19 lines
  export type McpContentBlock = {
      /**
       * The block's kind: `text`, `image`, `audio`, `resource`, `resource_link`.
       */
      type: string;
      /**
       * Set on a `text` block.
       */
      text?: string;
      /**
       * Set on a `resource_link` (or embedded `resource`) block.
       */
      uri?: string;
      /**
       * Declared by an image, audio or resource block.
       */
      mimeType?: string;
      [field: string]: unknown;
  };

McpServerProvenance type # line 5270

Added in 2.1.274

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.

  type McpServerProvenance = {
      name: string;
      /**
       * sdk | plugin | user | project | local | dynamic | managed | enterprise | claudeai | agent - an open set; treat unknown values as an unrecognized configured source, never as sdk.
       */
      source: string;
  };

McpToolCallInput type # line 5285

In the first published surface (2.1.259)

The MCP branch of a tool.call hook's e (and of $.tool.call's input): one variant per declared tool, else the loose McpToolCallInputFallback.

$.mcp.call(server, tool, args) takes none of these: its parameters are positional, the server and tool by name, then the arguments object.

  export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
      [N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
  }[keyof McpToolInputs & string];

McpToolCallInputFallback type # line 5300

In the first published surface (2.1.259)

The e a tool.call (or classic.PreToolUse) hook receives for an MCP tool while no MCP tool is declared: every mcp__* name, loose arguments.

McpToolInputs has no entries until /plugin-types writes the connected tools' declarations; also the input of $.tool.call({ tool: "mcp__<server>__<tool>", ... }). Not $.mcp.call's, which is positional:

on("tool.call", { tool: "mcp__gh__issue" }, ($, e, next) => audit(e.title))
13 lines
  type McpToolCallInputFallback = {
      /**
       * The name of the tool being called (`mcp__<server>__<tool>`); comparing
       * it narrows `e`. Reserved: a rewrite of it is ignored by core.
       */
      tool: McpToolName;
      /**
       * The tool_use block's id: the same at every event of the call and in
       * `$.ui.notice`. Reserved: a rewrite of it is ignored by core.
       */
      tool_use_id: string;
      [argument: string]: unknown;
  };

McpToolInputs interface # line 5325

In the first published surface (2.1.259)

The inputs of the MCP tools this project knows, keyed by full tool name, for declaration merging; empty by default, then every MCP tool is loose.

A .d.ts in the plugin author's project (written by /plugin-types <dir> from the connected servers' JSON Schemas, or by hand) adds entries under declare module "claude-code"; e.tool === <name> then narrows to them.

interface McpToolInputs { "mcp__my_server__send": { to: string } }
  export interface McpToolInputs {
  }

McpToolName type # line 5331

In the first published surface (2.1.259)

The name of an MCP tool as the engine spells it: mcp__<server>__<tool>.

  export type McpToolName = `mcp__${string}__${string}`;

McpToolResult type # line 5336

In the first published surface (2.1.259)

An MCP tools/call result as the SDK returns it, plain data.

16 lines
  export type McpToolResult = {
      /**
       * The result's content blocks, in order (text, image, resource,
       * resource_link, ...).
       */
      content: McpContentBlock[];
      /**
       * True when the server reported the call as failed; the blocks then describe
       * the error.
       */
      isError: boolean;
      /**
       * The server's structured result, when its tool declares an output schema.
       */
      structuredContent?: unknown;
  };

MemberOfFunction type # line 5360

Added in 2.1.281

memberOf(family, e): the member of a family for the instance being drawn, keyed by e.requestId; of an atom over a family, that member's.

const open = await read($, memberOf(isOpen, e))
  export type MemberOfFunction = {
      <T>(family: Atom<T>, e: Pick<RenderInput, 'requestId'>): Atom<T>;
      <P extends string, K extends string>(family: StateName<P, K>, e: Pick<RenderInput, 'requestId'>): StateName<P, K> & Readonly<Required<Pick<StateAddress, 'id'>>>;
  };

MessageDisplayHookInput type # line 5368

Added in 2.1.265

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.

23 lines
  type MessageDisplayHookInput = BaseHookInput & {
      hook_event_name: 'MessageDisplay';
      /**
       * UUID of the current turn.
       */
      turn_id: string;
      /**
       * UUID of the assistant message being displayed. Stable across every flush of the same message. Not the API msg_... id.
       */
      message_id: string;
      /**
       * Zero-based index of this delta within the message. Increments by one per flush.
       */
      index: number;
      /**
       * True on the message's last flush. Exactly one flush per message has it.
       */
      final: boolean;
      /**
       * 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.
       */
      delta: string;
  };

ModelApiError type # line 5400

Added in 2.1.280

Which kind of API failure ended a model call (a completion, a fork), in the word Claude Code classifies every API error with (StopFailure's).

rate_limit, overloaded and server_error may clear on their own; authentication_failed, billing_error, invalid_request, model_not_found will not; unknown fits none of the named kinds.

  export type ModelApiError = ClassicHookInputs['StopFailure']['error'];

ModelCompleteRequest type # line 5405

In the first published surface (2.1.259) · changed in 2.1.280

What $.model.complete takes.

53 lines
  export type ModelCompleteRequest = {
      /**
       * An alias (`haiku`) or a full model id; resolved and allowlist-checked like
       * a `--model` value.
       */
      model: string;
      /**
       * The one user message.
       *
       * The result always says what happened: the reply's text and usage when
       * the model answered, else a `reason` (an API error with its status, a
       * reply with no text, or the call cut short).
       */
      prompt: string;
      /**
       * Precedes the completion as its system prompt, after the CLI's identity
       * block. Default none.
       */
      system?: string;
      /**
       * The reply's token cap: any positive integer up to what one reply can
       * hold, the model's own output limit or 64000, whichever is lower.
       *
       * Default 1024. The reply comes back whole, not streamed, and a provider
       * ends such a request at ten minutes, hence the 64000. One past the limit
       * is refused, naming it.
       */
      maxTokens?: number;
      /**
       * How hard the model thinks about it (ModelEffort): `low` for a cheap
       * label, `max` for a hard judgment. Default: the model's own.
       *
       * Sent as the request's effort where the model takes one and dropped
       * where it does not, as the session's own requests do; a value outside
       * the five levels is refused.
       *
       * @example
       * await $.model.complete({ model: "haiku", prompt, effort: "low" })
       */
      effort?: ModelEffort;
      /**
       * How long the whole call may take, in milliseconds, before it resolves
       * `aborted` and the request is abandoned; default none.
       *
       * A `$` call's time never counts against the calling hook's budget, so this
       * is how a hook bounds the completion itself, by the clock. A positive whole
       * number, held to what a timer holds (2147483647); anything else is refused.
       *
       * @example
       * await $.model.complete({ model: "haiku", prompt, timeoutMs: 8000 })
       */
      timeoutMs?: number;
  };

ModelCompleteResult type # line 5470

Added in 2.1.280

What one model call resolves to: the reply when the model answered (isAnswered), else which of three things left it without text (reason).

$.model.complete's result whole, and $.model.fork's once it had something to fork. What the provider did never rejects the call, so a plugin branches on isAnswered and reason; usage rides every arm.

const r = await $.model.complete(ask); if (!r.isAnswered) log(r.reason)
85 lines
  export type ModelCompleteResult = {
      /**
       * True: the model answered; `text` and `usage` are its reply.
       *
       * @example
       * if (r.isAnswered) spent += r.usage.output_tokens
       */
      isAnswered: true;
      /**
       * The reply's text: a completion's text blocks joined; on a fork, the
       * non-error replies' text joined by newlines.
       */
      text: string;
      /**
       * What the call cost (ModelUsage); on a fork its completions summed.
       *
       * On a fork `cache_read_input_tokens` is how much of the transcript
       * the main thread's prompt cache served: near zero, the fork paid for
       * the whole prefix (the entry lapsed, or the model changed since).
       */
      usage: ModelUsage;
  } | {
      isAnswered: false;
      /**
       * The API answered with an error and no reply carried text.
       *
       * @example
       * if (!r.isAnswered && r.reason === "api-error") retry(r.status)
       */
      reason: 'api-error';
      /**
       * The error reply's HTTP status (429, 500, 529, ...); null when no
       * response arrived at all (a dropped connection, a provider timeout).
       */
      status: number | null;
      /**
       * Which kind of failure, as Claude Code classifies API errors; never
       * the error's text or body.
       *
       * `rate_limit`, `overloaded`, `invalid_request`,
       * `authentication_failed`, `server_error`, ...; `unknown` when it fits
       * none of the named kinds.
       */
      error: ModelApiError;
      /**
       * What the call cost before it failed: all zeros for a completion (its
       * one request was the one refused); on a fork, the turns before it.
       */
      usage: ModelUsage;
  } | {
      isAnswered: false;
      /**
       * The model replied and its reply carried no text.
       *
       * A completion whose content held no text block, or a fork answered
       * with a tool attempt alone (denied, as every fork tool is) or nothing.
       *
       * @example
       * if (!r.isAnswered && r.reason === "empty-reply") $.ui.log("no words")
       */
      reason: 'empty-reply';
      /**
       * What the call cost.
       */
      usage: ModelUsage;
  } | {
      isAnswered: false;
      /**
       * The call was cut before a reply came; whatever had come back is
       * discarded.
       *
       * The dispatch that made the call was aborted while it ran (escape on
       * the turn whose hook called; the plugin's environment unloaded), or a
       * completion's own `timeoutMs` elapsed and the request was abandoned.
       *
       * @example
       * if (!r.isAnswered && r.reason === "aborted") return next(e)
       */
      reason: 'aborted';
      /**
       * What the call cost before it was cut: all zeros for a completion (no
       * response arrived); on a fork, what came back before the abort.
       */
      usage: ModelUsage;
  };

ModelEffort type # line 5562

Added in 2.1.280

How hard a request asks the model to think, by the levels the engine and turn.step name: low to max, xhigh between high and max.

A model that takes no effort setting is sent none, whatever is asked.

  export type ModelEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';

ModelForkRequest type # line 5567

In the first published surface (2.1.259)

What $.model.fork takes.

  export type ModelForkRequest = {
      /**
       * The one user message, appended to the session's own transcript as the
       * main thread last sent it.
       *
       * The result always says what happened: the reply's text and usage when
       * the fork answered, else a `reason` (nothing to fork yet, an API error
       * with its status, a reply with no text, or the turn's abort cut it).
       */
      prompt: string;
  };

ModelForkResult type # line 5589

Added in 2.1.268 · changed in 2.1.280

What $.model.fork resolves to: a completion's result (ModelCompleteResult) or that there was nothing to fork yet.

The completion's arms are the reply when the fork answered, else api-error, empty-reply or aborted, usage on each.

const r = await $.model.fork({ prompt }); if (!r.isAnswered) log(r.reason)
14 lines
  export type ModelForkResult = ModelCompleteResult | {
      isAnswered: false;
      /**
       * Nothing to fork, so no request was made: this conversation's main
       * thread has produced no response yet.
       *
       * A new session before its first turn ends; again right after a
       * `/clear`, or a resume that starts the conversation afresh.
       *
       * @example
       * if (!r.isAnswered && r.reason === "nothing-to-fork") return next(e)
       */
      reason: 'nothing-to-fork';
  };

ModelUsage type # line 5619

Added in 2.1.280

What one model call cost, as the API counted it: the four token counts in the API's spelling, summed over the call's responses when it made several.

The one shape every place that reports a call's cost uses: $.model.complete's result on every arm and $.model.fork's on each arm where a request was made (ModelCompleteResult), session.compact's result when core ran the summarizer, turn.step and turn.complete (TurnUsage, which adds the model that answered), and the context breakdown's apiUsage (the live window's last response). All four counts are always present; a count the response left out reads as zero.

const r = await $.model.complete(ask); if (r.isAnswered) spend(r.usage)
23 lines
  export type ModelUsage = {
      /**
       * Uncached input tokens the call was answered over: the part of the
       * prompt neither read from nor written to the prompt cache.
       */
      input_tokens: number;
      /**
       * Tokens the call generated.
       */
      output_tokens: number;
      /**
       * Input tokens the prompt cache served.
       *
       * On a fork, how much of the main thread's transcript the cache still
       * held: near zero, the fork paid for the whole prefix (the entry had
       * lapsed, or the model changed since it was made).
       */
      cache_read_input_tokens: number;
      /**
       * Input tokens the call wrote to the prompt cache.
       */
      cache_creation_input_tokens: number;
  };

Namespace type # line 5647

Added in 2.1.265

The prefixes a glob may name: one or more whole leading segments of an event name (tool of tool.call), derived, plugin nouns included.

  export type Namespace<N extends string = EventName> = N extends `${infer Head}.${infer Rest}` ? Head | `${Head}.${Namespace<Rest>}` : never;

NarrowDepth type # line 5655

In the first published surface (2.1.259)

How many object or array levels a matcher narrows e through, counted as a tuple's length: the runtime's own limit, which refuses a deeper matcher.

Past it a field keeps its declared type; nothing becomes any.

  type NarrowDepth = 8;

Narrowed type # line 5665

In the first published surface (2.1.259)

e in a matched hook: the members of the argument union E matcher P can match, each with the keys P names narrowed to what a match implies.

A scalar narrows to the literal, a one-of to what its alternatives give, an object key recursively, an array some element of which must match to a non-empty tuple; other keys, unknown and RegExp-matched fields keep.

  export type Narrowed<E, P> = E extends unknown ? NarrowedMember<E, P, []> : never;

NarrowedByAny type # line 5675

In the first published surface (2.1.259)

A value of declared type V under a one-of, folded over the tuple into Found: the union of what each alternative narrows V to (NarrowedByOne).

An alternative that cannot match adds nothing, so a one-of none of whose alternatives can is never; a one-of typed as a plain array rather than a tuple narrows by the union of its elements at once.

  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>;

NarrowedByOne type # line 5685

In the first published surface (2.1.259)

A value of declared type V under one matcher node Q that is not a one-of, member of V by member; a member that cannot match is never.

An array some element of which must match becomes NonEmpty; a RegExp keeps the member; an object pattern recurses into an object member, one level down; a scalar keeps a member as narrow, and replaces a wider one.

  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;

NarrowedMember type # line 5694

In the first published surface (2.1.259)

One object member E under object pattern P, D levels down: never when a key of P is impossible on it (ImpossibleKeys), else E narrowed.

Each key P names is narrowed (NarrowedValue); every other key, and each key's optionality, stays as declared.

  type NarrowedMember<E, P, D extends readonly unknown[]> = [
  ImpossibleKeys<E, P, D>

NarrowedValue type # line 5707

In the first published surface (2.1.259)

A value of declared type V where the matcher gives Q, D levels down: NarrowedByAny under a one-of (an array), NarrowedByOne otherwise.

As declared once D reaches NarrowDepth, or for a field typed unknown (a tool's input), which no pattern narrows.

  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>;
Feedback