# zidane

> The root entry point, with the agent, providers, tools and presets re-exported alongside the runtime helpers that have no narrower entry.

Import: `import { … } from 'zidane'`. Source: [src/index.ts](https://github.com/Tahul/zidane/blob/main/src/index.ts).

Use `zidane` for one import that covers everything, including helpers that live only here: logging, metrics and tracing hooks, conversation compaction, the system-prompt freezing helpers (`systemSnapshotTurn`, `latestSystemSnapshot`, `catalogChangeNotes`), token estimates, history repair, MCP sign-in and the GitHub client. Symbols with a narrower entry point (`zidane/agent`, `zidane/providers`, `zidane/tools`) are documented on that page. In Edge and Worker bundles, import from those narrower entries to keep the module graph small.

```ts
import { consoleSink, createAgent, createLogger, createLoggingHooks, estimateTokens } from 'zidane'
import { basic } from 'zidane/presets'
import { anthropic } from 'zidane/providers/anthropic'

const agent = createAgent({ ...basic, provider: anthropic() })
const logger = createLogger(consoleSink({ minLevel: 'info' }), { service: 'docs' })
const uninstall = createLoggingHooks({ logger }).install(agent.hooks)

const prompt = 'List the files in this directory.'
console.log(`about ${estimateTokens(prompt)} prompt tokens`)
await agent.run({ prompt })
uninstall()
```

## Functions

### `anchorPreviewFor`

Function.

Extract the first \~200 chars of text-bearing content from a turn — the
preview surfaced in `from` / `up_to` direction prompts so the model
knows where the slice begins.

```ts
function anchorPreviewFor(turn: SessionTurn): string
```

**Parameters**

- `turn` (`SessionTurn`): Anchor turn to preview.

**Returns** `string`

Source: [src/compact/messages.ts:402](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L402)

### `announcedDigest`

Function.

Digest of a section as the model was last told it: the newest note of
`kind` carrying a digest after the snapshot, else the snapshot's digest.

```ts
function announcedDigest(
  frozen: FrozenSystemPrompt,
  turns: readonly SessionTurn[],
  kind: string,
): string | undefined
```

**Parameters**

- `frozen` (`FrozenSystemPrompt`): The frozen prompt.
- `turns` (`readonly SessionTurn[]`): Session turns, oldest first.
- `kind` (`string`): Section kind.

**Returns** `string | undefined`

Source: [src/system-freeze.ts:114](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L114)

### `announcedResetMs`

Function.

The wait a provider message announces (`try again in …`, `resets in …`),
every unit summed (`2h30m14s`), in ms; `undefined` when it names none.

```ts
function announcedResetMs(message: string): number | undefined
```

**Parameters**

- `message` (`string`): Upstream error text.

**Returns** `number | undefined`

Source: [src/errors.ts:618](https://github.com/Tahul/zidane/blob/main/src/errors.ts#L618)

### `applyCompactSummaryCutoff`

Function.

Wire-level cutoff for [`SessionContentBlock`](https://zidane.si/docs/reference/types.md#SessionContentBlock)'s `compact-summary`
markers.

Elision is MONOTONE across every marker in the session: a turn whose
id appears in ANY marker's `replacesTurnIds` never reaches the wire
again — the summary that absorbed it stands in for it permanently.
(Honoring only the newest marker would resurrect the older marker's
replaced turns whenever a re-compaction failed to subsume it, e.g. after a
PTL head-drop. That showed up as a session re-compacting an unchanged
866k-token wire on every turn.)

Per marker:

1. A marker turn never passes through verbatim (providers don't
   know the `compact-summary` block type).
2. An ACTIVE marker — one not itself replaced by a newer marker —
   renders as a synthesized plain user-text turn carrying its
   summary, positioned at the slot of its **first replaced turn**
   so the summary appears CHRONOLOGICALLY where the content it
   summarizes used to live:
   - older unreplaced turns (PTL head-drops) come first
   - then the synthesized summary
   - then later unreplaced turns (preserved tail + new prompts)
     A marker with no surviving replaced slot (empty or dangling
     `replacesTurnIds`) renders at its own chronological position.
3. A SUBSUMED marker (its id is in a newer marker's replaced set —
   i.e. its summary text fed the newer summary) contributes only
   elision: its replaced turns stay gone, its text does not render.
4. Every other turn passes through by reference, including turns
   no marker replaced (PTL head-drops stay visible verbatim until
   a later compaction absorbs them — the runner compacts the WIRE
   view, so they are always at the head of the next scope).

If no marker exists, the input array is returned unchanged.

Note on role-alternation: when the marker is immediately followed by
a new user turn (the common case — user submits a prompt right after
compacting), the wire output ends in `[…, synthetic_user, new_user]`.
Anthropic folds adjacent same-role messages server-side; other
providers tolerate them via their own normalization passes. The
harness does NOT fold them here — keeping them separate preserves
the per-turn `turnId` tags that the TUI's select-turn mode relies on.

Pure: a fresh array is returned only when a marker is found. Input
turns are never mutated. New `SessionTurn`s allocated: the synthetic
markers, plus a copy of every preserved assistant turn older than the
newest marker whose replayable thinking was stripped (see
`withoutReplayedThinking`). The output is WIRE-shaped, not
display-shaped: hosts rendering a transcript should read the session
turns, not this view.

```ts
function applyCompactSummaryCutoff(turns: SessionTurn[]): SessionTurn[]
```

**Parameters**

- `turns` (`SessionTurn[]`): Session turns in chronological order, including any `compact-summary` marker turns.

**Returns** `SessionTurn[]`

Source: [src/loop-compaction.ts:101](https://github.com/Tahul/zidane/blob/main/src/loop-compaction.ts#L101)

### `authFailureOf`

Function.

The sign-in failure behind `err`: an [`AgentAuthError`](https://zidane.si/docs/reference/errors.md#AgentAuthError) anywhere on its
`cause` chain, else a provider error that came back 401 (the credential
was sent and refused). `undefined` for anything else.

```ts
function authFailureOf(err: unknown): AuthFailure | undefined
```

**Parameters**

- `err` (`unknown`): The error a run, or a call, failed with.

**Returns** `AuthFailure | undefined`

Source: [src/errors.ts:712](https://github.com/Tahul/zidane/blob/main/src/errors.ts#L712)

### `buildFromCompactPrompt`

Function.

Builds the summary prompt for summarizing from an anchor turn onward.

```ts
function buildFromCompactPrompt(anchorPreview: string): string
```

**Parameters**

- `anchorPreview` (`string`): Short text preview of the anchor turn.

**Returns** `string`

Source: [src/compact/prompt.ts:142](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L142)

### `buildFullCompactPrompt`

Function.

Builds the summary prompt for summarizing the whole conversation.

```ts
function buildFullCompactPrompt(): string
```

**Returns** `string`

Source: [src/compact/prompt.ts:128](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L128)

### `buildPersistedStub`

Function.

Render the byte-stable `<persisted-output>` stub the model sees in place
of the original `tool_result`.

Format choices:

- XML wrapper because models reliably parse it as structural.
- Byte count + path in attributes so the model can decide whether to
  `read_file` the persisted blob without scanning the preview.
- Preview always shows the head — how `shell` cuts its own output is
  irrelevant here because the model has the full path if it needs the
  tail.
- No timestamps, no random UUIDs inside the stub: every byte must be
  reproducible from the inputs, otherwise re-emission on subsequent
  turns would bust the prompt cache.

Exported for tests (asserting the byte-stable contract) and for SDK
consumers wiring their own persistence middleware against the same
surface.

```ts
function buildPersistedStub(input: BuildStubInput): string
```

**Parameters**

- `input` (`BuildStubInput`): Tool name, original size, persisted path and the output to preview.

**Returns** `string`

Source: [src/loop-persistence.ts:785](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L785)

### `buildPostCompactAttachments`

Function.

Build the synthetic turns to append after a `compact-summary` marker.

Returns a `PostCompactAttachments` envelope; the caller is responsible
for `session.appendTurns([summaryTurn, ...result.turns])`. The two
synthetic turns are always emitted together (or both omitted when
nothing was restored) so the `tool_use ↔ tool_result` adjacency
invariant holds regardless of caller code path.

Failure isolation: a single file's read failure never blocks the rest
of restoration — that file is skipped silently and processing
continues. The returned `restoredFiles` count reflects what actually
landed in the synthesized turns.

```ts
function buildPostCompactAttachments(
  opts: PostCompactRestoreOptions,
): Promise<PostCompactAttachments>
```

**Parameters**

- `opts` (`PostCompactRestoreOptions`): Files, skills, execution context and budgets. See [`PostCompactRestoreOptions`](https://zidane.si/docs/reference/index.md#PostCompactRestoreOptions).

**Returns** `Promise<PostCompactAttachments>`

Source: [src/compact/restore.ts:448](https://github.com/Tahul/zidane/blob/main/src/compact/restore.ts#L448)

### `buildTailCompactPrompt`

Function.

Builds the summary prompt for summarizing everything before the preserved tail.

```ts
function buildTailCompactPrompt(): string
```

**Returns** `string`

Source: [src/compact/prompt.ts:133](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L133)

### `buildUpToCompactPrompt`

Function.

Builds the summary prompt for summarizing up to an anchor turn.

```ts
function buildUpToCompactPrompt(anchorPreview: string): string
```

**Parameters**

- `anchorPreview` (`string`): Short text preview of the anchor turn.

**Returns** `string`

Source: [src/compact/prompt.ts:151](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L151)

### `buildZidaneExtensionSkill`

Function.

The inline `zidane-extension` skill. Carries the authoring reference IN its
body (`EXTENSION_AUTHORING_CHEATSHEET`) so it works in every host —
incl. compiled binaries where the on-disk docs aren't resolvable. The shipped
`EXTENSIONS.md` (prose long-form) is appended as a "see also" only when found
on disk. `source: 'inline'` (the `defineSkill` default) survives the
project-trust gate.

```ts
function buildZidaneExtensionSkill(opts?: { cwd?: string }): SkillConfig
```

**Parameters**

- `opts?` (`{ cwd?: string }`, default `{}`): Options. `cwd` is the directory used to locate the shipped docs. Defaults to `process.cwd()`.

**Returns** `SkillConfig`

Source: [src/extension-authoring.ts:792](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L792)

### `buildZidaneSkillEditSkill`

Function.

The inline skill auto-activated in "edit skill" sessions. Body = the
session preset (which skill, which directory, what the next messages will
be about) + a compact SKILL.md authoring reference — the skill-editing
counterpart of [`buildZidaneExtensionSkill`](https://zidane.si/docs/reference/index.md#buildZidaneExtensionSkill).

```ts
function buildZidaneSkillEditSkill(
  marker: SkillEditMarker,
  opts?: { cwd?: string },
): SkillConfig
```

**Parameters**

- `marker` (`SkillEditMarker`): Marker naming the skill's directory and name.
- `opts?` (`{ cwd?: string }`, default `{}`): Options. `cwd` is the directory used to locate the shipped docs. Defaults to `process.cwd()`.

**Returns** `SkillConfig`

Source: [src/extension-authoring.ts:871](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L871)

### `catalogChangeNotes`

Function.

Notes for each SDK-appended section whose live text differs from what the
model was last told (see [`announcedDigest`](https://zidane.si/docs/reference/index.md#announcedDigest)). A section the model was
told about that is now absent is announced as emptied; tools changes list
the entries added and removed. Deterministic.

```ts
function catalogChangeNotes(
  input: { frozen: FrozenSystemPrompt; sections: FrozenPromptSections; turns: readonly SessionTurn[] },
): SectionChangeNote[]
```

**Parameters**

- `input` (`{ frozen: FrozenSystemPrompt; sections: FrozenPromptSections; turns: readonly SessionTurn[] }`): The frozen prompt, the session turns and this run's sections.

**Returns** `SectionChangeNote[]`

Source: [src/system-freeze.ts:137](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L137)

### `classifyGithubAnswer`

Function.

What an answer means. A rate limit is a 429; a 403 that says so in its
headers (`remaining: 0` or a `retry-after`); or a GraphQL answer — GitHub
reports those with HTTP 200 — carrying `RATE_LIMITED`, `remaining: 0`, or
a "rate limit exceeded" message. A 403 that merely mentions a rate limit in
its body is NOT one: SAML / SSO enforcement and missing scopes are 403s too,
and pausing a host for them would stop every read.

```ts
function classifyGithubAnswer(
  input: { graphql: boolean; headers: Headers; status: number; text: string },
): GithubAnswerClass
```

**Parameters**

- `input` (`{ graphql: boolean; headers: Headers; status: number; text: string }`): HTTP status, response headers, body text and whether the request was GraphQL.

**Returns** `GithubAnswerClass`

Source: [src/github/client.ts:392](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L392)

### `classifyProviderLimit`

Function.

The classification for a rate limit, spent quota or overload: the human
message from [`describeProviderLimit`](https://zidane.si/docs/reference/index.md#describeProviderLimit), the native code kept for
branching, and the reset stamped as `resetsAt`. Not retryable when a
spent quota declares no reset (waiting does not refill a balance) or the
reset is more than a minute away; otherwise the provider's own verdict
stands.

```ts
function classifyProviderLimit(
  limit: ProviderLimit,
  options: { providerCode?: string; retryable?: boolean },
): ClassifiedError
```

**Parameters**

- `limit` (`ProviderLimit`): What was hit, who by, and when it resets.
- `options` (`{ providerCode?: string; retryable?: boolean }`): Upstream `providerCode` and the provider's `retryable` verdict.

**Returns** `ClassifiedError`

Source: [src/errors.ts:595](https://github.com/Tahul/zidane/blob/main/src/errors.ts#L595)

### `cleanupPersistedSession`

Function.

Remove every persisted blob belonging to a session. Called by the chat
layer from its session-delete path so closing a session frees the disk
footprint alongside the SQLite row.

Idempotent — missing directory (session never persisted anything) is a
no-op, not an error. Wraps the `rm -rf` so a permissions blip on one
blob doesn't propagate to the caller; the chat layer can't usefully
recover from "couldn't unlink a result file" mid-delete.

```ts
function cleanupPersistedSession(persistRoot: string): Promise<void>
```

**Parameters**

- `persistRoot` (`string`): Absolute directory that holds the session's persisted blobs.

**Returns** `Promise<void>`

Source: [src/loop-persistence.ts:845](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L845)

### `clearGithubPullMemory`

Function.

Forget remembered PRs (tests).

```ts
function clearGithubPullMemory(): void
```

Source: [src/github/pulls.ts:161](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L161)

### `clearMcpSignIn`

Function.

Sign out of `name`: drop tokens, registration and discovery, keep a
stored client secret (configuration, not session state).

```ts
function clearMcpSignIn(store: McpCredentialStore, name: string): void
```

**Parameters**

- `store` (`McpCredentialStore`): Credential store.
- `name` (`string`): Server name.

Source: [src/mcp/oauth-provider.ts:422](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L422)

### `collectNewlyStaleReadPaths`

Function.

Paths whose earlier reads were NEWLY made stale by this batch's successful
mutations — i.e. the prior transcript holds a `read_file` of the path that
is more recent than the path's last successful mutation. Reads older than
that mutation were already noticed when it landed, so repeated edits to the
same file yield exactly one notice per read→edit transition, not one per
edit.

Pure; mirrors `applyStaleReadElision`'s detection exactly (same tool
names, same success markers) so the two policies never drift on WHAT counts
as stale — only on how the staleness is represented.

```ts
function collectNewlyStaleReadPaths(
  priorTurns: readonly Pick<SessionTurn, 'content'>[],
  batch: readonly { name: string; output: string | ToolResultContent[]; path: unknown }[],
): string[]
```

**Parameters**

- `priorTurns` (`readonly Pick<SessionTurn, 'content'>[]`): Transcript turns that precede the current batch.
- `batch` (`readonly { name: string; output: string | ToolResultContent[]; path: unknown }[]`): Tool calls of the current batch, with their target path and output.

**Returns** `string[]`

Source: [src/loop-stale-reads.ts:297](https://github.com/Tahul/zidane/blob/main/src/loop-stale-reads.ts#L297)

### `commandBlocksToContent`

Function.

Persisted form of output blocks inside a display-only `command` turn:
plain blocks → `text` content; `detail` blocks → `tool_result` content
with the label/syntax carried in namespaced metadata (rebuilt into the
collapsed rendering on reload). Shared by the command emit flush and
`ctx.appendNote` so both persist identically.

```ts
function commandBlocksToContent(
  blocks: readonly CommandOutputBlock[],
): SessionContentBlock[]
```

**Parameters**

- `blocks` (`readonly CommandOutputBlock[]`): Output blocks collected from a command run.

**Returns** `SessionContentBlock[]`

Source: [src/chat/commands.ts:371](https://github.com/Tahul/zidane/blob/main/src/chat/commands.ts#L371)

### `commandBlockToEvent`

Function.

Map ONE command-output block to its LIVE transcript event — the
in-memory mirror of [`commandBlocksToContent`](https://zidane.si/docs/reference/index.md#commandBlocksToContent)'s persisted shape
(whose replay side lives in `eventsFromTurns`). One definition shared
by the command emit flush and the `ctx.appendNote` host impl so live
rendering can never drift from reloaded rendering — the exact drift
that shipped `custom` blocks rendering only after a reload.

Precedence matches the persisted side: `custom` > `detail` > markdown.

```ts
function commandBlockToEvent(block: CommandOutputBlock): StreamEvent
```

**Parameters**

- `block` (`CommandOutputBlock`): The output block to convert.

**Returns** `StreamEvent`

Source: [src/chat/commands.ts:406](https://github.com/Tahul/zidane/blob/main/src/chat/commands.ts#L406)

### `commandLabel`

Function.

A short name for a command line: the program, or the script an interpreter runs
(`node …/typescript-language-server --stdio` → `typescript-language-server (node)`).

```ts
function commandLabel(args: string): string
```

**Parameters**

- `args` (`string`): The command line.

**Returns** `string`: The label.

Source: [src/perf/ps.ts:117](https://github.com/Tahul/zidane/blob/main/src/perf/ps.ts#L117)

### `compactConversation`

Function.

Summarizes older turns of a conversation with one provider call.

Retries with a shortened head on `prompt_too_long` and retries transient provider errors a limited number of times. Does not modify `opts.turns`.

Throws [`CompactInvalidInputError`](https://zidane.si/docs/reference/index.md#CompactInvalidInputError) when the inputs cannot be compacted, [`CompactPromptTooLongError`](https://zidane.si/docs/reference/index.md#CompactPromptTooLongError) when the retry budget runs out, and rethrows aborts from `opts.signal` unchanged.

```ts
function compactConversation(opts: CompactOptions): Promise<CompactResult>
```

**Parameters**

- `opts` (`CompactOptions`): Compaction options. See [`CompactOptions`](https://zidane.si/docs/reference/index.md#CompactOptions).

**Returns** `Promise<CompactResult>`: The summary, usage and the turn ids it covers.

Source: [src/compact/compact.ts:384](https://github.com/Tahul/zidane/blob/main/src/compact/compact.ts#L384)

### `configureGithubClient`

Function.

Configure this process's client. Hosts call it at startup with the store
every zidane process shares (`createFileGithubStateStore(dataDir)`);
without it state lives in memory. `client` replaces the client outright
(tests).

```ts
function configureGithubClient(
  opts: { client?: GithubClient | null; store?: GithubStateStore },
): void
```

**Parameters**

- `opts` (`{ client?: GithubClient | null; store?: GithubStateStore }`): `store` becomes the shared state store. `client` replaces the process client; `null` resets it.

Source: [src/github/client.ts:789](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L789)

### `consoleSink`

Function.

Human-readable terminal sink. Renders each record as
`<ISO timestamp> <LEVEL> <message> <attrs as kv pairs>`.

Honors `process.stderr` by default so log lines don't interleave with
the agent's stdout-bound output (chat responses, JSON results).

```ts
function consoleSink(options?: ConsoleSinkOptions): LogSink
```

**Parameters**

- `options?` (`ConsoleSinkOptions`, default `{}`): Minimum level and output stream. All fields are optional.

**Returns** `LogSink`

Source: [src/logger.ts:160](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L160)

### `createExtension`

Function.

Scaffolds a new extension folder: `index.ts`, plus the optional files
`input` asks for. Throws when the name is invalid or the folder exists.

```ts
function createExtension(
  input: CreateExtensionInput,
  deps: CreateExtensionDeps,
): CreateExtensionResult
```

**Parameters**

- `input` (`CreateExtensionInput`): The name, scope, folder and optional files.
- `deps` (`CreateExtensionDeps`): Where user and project extensions go.

**Returns** `CreateExtensionResult`

Source: [src/extension-authoring.ts:393](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L393)

### `createFileGithubStateStore`

Function.

State backed by `<dir>/github-state.json`. Reads re-parse only when the
file's mtime moved; writes merge with what is on disk first, so two
processes writing at once lose nothing that matters. A failed write
(read-only home, full disk) switches the store to memory only.

```ts
function createFileGithubStateStore(
  dir: string,
  opts?: { now?: () => number },
): GithubStateStore
```

**Parameters**

- `dir` (`string`): Directory that holds `github-state.json`.
- `opts?` (`{ now?: () => number }`, default `{}`): Optional clock override, `now`, in epoch milliseconds.

**Returns** `GithubStateStore`

Source: [src/github/state-file.ts:26](https://github.com/Tahul/zidane/blob/main/src/github/state-file.ts#L26)

### `createGithubClient`

Function.

Creates a GitHub client with its own answer cache, request limit and rate-limit handling.

```ts
function createGithubClient(options?: GithubClientOptions): GithubClient
```

**Parameters**

- `options?` (`GithubClientOptions`, default `{}`): Fetch, clock, state store and token source overrides.

**Returns** `GithubClient`

Source: [src/github/client.ts:573](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L573)

### `createGpuReader`

Function.

A GPU reader for a sampler: `ioreg` at most every `everyMs` (macOS only),
the last figure in between.

```ts
function createGpuReader(
  everyMs?: number,
  read?: () => Promise<PerfGpu | null>,
): { due: (now: number) => boolean; read: (now: number) => Promise<PerfGpu | null> }
```

**Parameters**

- `everyMs?` (`number`, default `GPU_EVERY_MS`): The least time between two reads.
- `read?` (`() => Promise<PerfGpu | null>`, default `readGpu`): The reader (tests); default `readGpu`.

**Returns** `{ due: (now: number) => boolean; read: (now: number) => Promise<PerfGpu | null> }`: `(now) => figure`; `due(now)` says whether that call runs `ioreg`.

Source: [src/perf/gpu.ts:54](https://github.com/Tahul/zidane/blob/main/src/perf/gpu.ts#L54)

### `createHostPerf`

Function.

Creates the host's monitor. Nothing runs until the first watch.

```ts
function createHostPerf(options: HostPerfOptions): HostPerf
```

**Parameters**

- `options` (`HostPerfOptions`): The host's label, MCP processes and session titles.

**Returns** `HostPerf`

Source: [src/perf/host.ts:77](https://github.com/Tahul/zidane/blob/main/src/perf/host.ts#L77)

### `createLogger`

Function.

Build a Logger from a sink. Stateless and cheap; create one per agent
(or per app) and use `.with()` to attach correlation ids per-call.

```ts
function createLogger(
  sink: LogSink,
  baseAttributes?: Readonly<Record<string, unknown>>,
): Logger
```

**Parameters**

- `sink` (`LogSink`): Destination for every record.
- `baseAttributes?` (`Readonly<Record<string, unknown>>`, default `{}`): Attributes merged into every record. Defaults to none.

**Returns** `Logger`

Source: [src/logger.ts:98](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L98)

### `createLoggingHooks`

Function.

Install a bundle of hook handlers that emit a structured line per
relevant lifecycle event, automatically attaching correlation ids
(`runId`, `turnId`, `callId`, `childId`, `depth`, `agentName`).

```ts
function createLoggingHooks(options: LoggingHooksOptions): LoggingHookSet
```

**Parameters**

- `options` (`LoggingHooksOptions`): Target logger plus optional `level` and `includeLifecycle`.

**Returns** `LoggingHookSet`

**Example**

```ts
const logger = createLogger(consoleSink({ minLevel: 'debug' }), { service: 'tui' })
const lh = createLoggingHooks({ logger })
const uninstall = lh.install(agent.hooks)
try { await agent.run({ prompt }) }
finally { uninstall() }
```

Source: [src/logger.ts:407](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L407)

### `createMainThreadMeter`

Function.

Creates the meter.

```ts
function createMainThreadMeter(
  cpu?: ThreadCpu | null,
  now?: () => number,
): MainThreadMeter
```

**Parameters**

- `cpu?` (`ThreadCpu | null`): The thread's CPU time (tests); default `process.threadCpuUsage`.
- `now?` (`() => number`): Wall clock, ms (tests).

**Returns** `MainThreadMeter`

Source: [src/perf/event-loop.ts:59](https://github.com/Tahul/zidane/blob/main/src/perf/event-loop.ts#L59)

### `createMemoryGithubStateStore`

Function.

State in this process only.

```ts
function createMemoryGithubStateStore(): GithubStateStore
```

**Returns** `GithubStateStore`

Source: [src/github/state.ts:72](https://github.com/Tahul/zidane/blob/main/src/github/state.ts#L72)

### `createMemoryMcpCredentialStore`

Function.

In-memory store — primarily for tests, but valid as a no-persistence option
(tokens evaporate on process exit, the user re-auths every cold start).

```ts
function createMemoryMcpCredentialStore(
  seed?: Record<string, McpCredentialEntry>,
): McpCredentialStore
```

**Parameters**

- `seed?` (`Record<string, McpCredentialEntry>`): Entries to start with, keyed by server name.

**Returns** `McpCredentialStore`

Source: [src/mcp/oauth-provider.ts:109](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L109)

### `createMetricsHooks`

Function.

Build a set of metrics hook handlers that can be installed on an agent.

```ts
function createMetricsHooks(options: MetricsHooksOptions): MetricsHookSet
```

**Parameters**

- `options` (`MetricsHooksOptions`): Meter plus optional `namespace`, `baseAttributes` and `onError`.

**Returns** `MetricsHookSet`

**Example**

```ts
import { metrics } from '@opentelemetry/api'
const meter = metrics.getMeter('zidane')
const m = createMetricsHooks({ meter, baseAttributes: { service: 'tui' } })
const uninstall = m.install(agent.hooks)
try { await agent.run({ prompt }) }
finally { uninstall() }
```

Source: [src/metrics.ts:170](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L170)

### `createMutationValidationHooks`

Function.

Build host-side hooks for post-mutation validation without changing the
built-in edit/write tools. The helper only observes successful mutations
reported through `tool:after.outcome`; validation commands and recovery
prompts remain host policy.

```ts
function createMutationValidationHooks(
  options: MutationValidationHooksOptions,
): AgentHookMap
```

**Parameters**

- `options` (`MutationValidationHooksOptions`): Validator and optional failure handling. `validate` is required.

**Returns** `AgentHookMap`

Source: [src/mutation-validation.ts:95](https://github.com/Tahul/zidane/blob/main/src/mutation-validation.ts#L95)

### `createOwnedProcesses`

Function.

The owned-process reader a sampler calls once a tick: the local registries, and the other host's last answers.

```ts
function createOwnedProcesses(deps: OwnedDeps): () => Promise<Owned>
```

**Parameters**

- `deps` (`OwnedDeps`): The local registries and the other host.

**Returns** `() => Promise<Owned>`: A reader for one tick: the owned pids, the MCP processes and the session processes, local and the other host's.

Source: [src/perf/owned.ts:116](https://github.com/Tahul/zidane/blob/main/src/perf/owned.ts#L116)

### `createReadonlySqliteSessionStore`

Function.

Serves `load`, `getMeta` and `getTurns` from `driver` exactly as the
regular store does. `close` closes the driver.

```ts
function createReadonlySqliteSessionStore(
  driver: SqliteDriver,
): ReadonlySqliteSessionStore
```

**Parameters**

- `driver` (`SqliteDriver`): A connection opened read-only on a migrated sessions database.

**Returns** `ReadonlySqliteSessionStore`

Source: [src/session/sqlite-readonly.ts:26](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-readonly.ts#L26)

### `createRing`

Function.

Creates a ring.

```ts
function createRing<T>(capacity: number): Ring<T>
```

**Type parameters**

- `T`

**Parameters**

- `capacity` (`number`): How many items it keeps.

**Returns** `Ring<T>`

Source: [src/perf/ring.ts:18](https://github.com/Tahul/zidane/blob/main/src/perf/ring.ts#L18)

### `createRingBufferSink`

Function.

In-memory bounded log buffer backing the in-TUI logs viewer. Always
capturing and never touches I/O, so it's safe on the logging hot path.
Retains the most recent `capacity` records, dropping the oldest on
overflow. Kept simple (a plain array trimmed with `splice`) — TUI log
volume is low, so a true head-indexed ring isn't worth the complexity.

```ts
function createRingBufferSink(options?: RingBufferSinkOptions): RingBufferSink
```

**Parameters**

- `options?` (`RingBufferSinkOptions`, default `{}`): Buffer capacity and minimum level. All fields are optional.

**Returns** `RingBufferSink`

Source: [src/logger.ts:245](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L245)

### `createSampler`

Function.

A sampling loop over `collect`: it starts with the first subscriber, stops with the last, never overlaps two ticks, and keeps the last `capacity` samples.

```ts
function createSampler<T>(options: SamplerOptions<T>): Sampler<T>
```

**Type parameters**

- `T`

**Parameters**

- `options` (`SamplerOptions<T>`): What to sample (`collect`), the activity callback, the interval, the capacity and the timers.

**Returns** `Sampler<T>`

Source: [src/perf/sampler.ts:62](https://github.com/Tahul/zidane/blob/main/src/perf/sampler.ts#L62)

### `createSqliteDriver`

Function.

Wraps a `bun:sqlite` `Database` or a `node:sqlite` `DatabaseSync` as a
[`SqliteDriver`](https://zidane.si/docs/reference/index.md#SqliteDriver): a bounded statement cache, `get` normalized to
`undefined` on no row (bun returns `null`), and a manual `BEGIN IMMEDIATE`.

```ts
function createSqliteDriver(
  db: SqliteDatabaseLike,
  options?: { close?: () => void },
): SqliteDriver
```

**Parameters**

- `db` (`SqliteDatabaseLike`): An open database handle.
- `options?` (`{ close?: () => void }`, default `{}`): `close` overrides how the handle is closed (bun: `db.close(false)`).

**Returns** `SqliteDriver`

Source: [src/session/sqlite-driver.ts:61](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L61)

### `createSqliteSessionStore`

Function.

Opens the session store over `driver`: runs the schema setup and
migrations on it (idempotent, cheap on an up-to-date file), then serves
every `SessionStore` method from it. The driver stays usable for the
caller's own queries on the same connection.

```ts
function createSqliteSessionStore(
  driver: SqliteDriver,
  options: SqliteSessionStoreOptions,
): SessionStore
```

**Parameters**

- `driver` (`SqliteDriver`): An open connection (`createSqliteDriver`).
- `options` (`SqliteSessionStoreOptions`): Database path and an optional shared write queue.

**Returns** `SessionStore`

Source: [src/session/sqlite-store.ts:168](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-store.ts#L168)

### `createSqliteWriteQueue`

Function.

A [`SqliteWriteQueue`](https://zidane.si/docs/reference/index.md#SqliteWriteQueue); one per connection, shared by every writer on it.

```ts
function createSqliteWriteQueue(): SqliteWriteQueue
```

**Returns** `SqliteWriteQueue`

Source: [src/session/sqlite-driver.ts:187](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L187)

### `createToolStateController`

Function.

Creates the controller that owns an agent's tool state snapshot and per-call staging views.

```ts
function createToolStateController(store?: ToolStateStore): ToolStateController
```

**Parameters**

- `store?` (`ToolStateStore`): Durable backing store. When omitted, state lives in memory for the agent's lifetime.

**Returns** `ToolStateController`

Source: [src/tool-state.ts:217](https://github.com/Tahul/zidane/blob/main/src/tool-state.ts#L217)

### `createTracingHooks`

Function.

Build a set of tracing hook handlers that can be installed on an agent.

```ts
function createTracingHooks(options: TracingHooksOptions): TracingHookSet
```

**Parameters**

- `options` (`TracingHooksOptions`): Tracer seam and span options. `startSpan` is required.

**Returns** `TracingHookSet`

**Examples**

```ts
const tracing = createTracingHooks({
  startSpan: (name, attrs) => Sentry.startInactiveSpan({ name, attributes: attrs }),
})
const uninstall = tracing.install(agent.hooks)
try { await agent.run({ prompt }) }
finally { uninstall() }
```

```ts
import { trace, context, propagation } from '@opentelemetry/api'

const tracer = trace.getTracer('zidane')
const tracing = createTracingHooks({
  startSpan: (name, attrs, parentCtx) => {
    const ctx = parentCtx ? propagation.extract(context.active(), parentCtx) : context.active()
    return tracer.startSpan(name, { attributes: attrs }, ctx)
  },
  getActiveTraceContext: () => {
    const carrier: Record<string, string> = {}
    propagation.inject(context.active(), carrier)
    return carrier
  },
})
```

Source: [src/tracing.ts:253](https://github.com/Tahul/zidane/blob/main/src/tracing.ts#L253)

### `defaultRepeatGuardNormalize`

Function.

Built-in normalizer used when the consumer doesn't supply one. Shell-shaped
tools get [`normalizeShellCommand`](https://zidane.si/docs/reference/index.md#normalizeShellCommand); everything else falls back to a
stable JSON encoding. Returns `undefined` when there's no meaningful payload
to key on (so the call is excluded from streak tracking rather than keyed on
`'{}'`). Consumers needing semantic keying for their own tools (e.g.
collapsing a query's whitespace) supply a normalizer via
`RepeatGuardConfig.normalize`.

```ts
function defaultRepeatGuardNormalize(
  name: string,
  input: Record<string, unknown>,
): string | undefined
```

**Parameters**

- `name` (`string`): Tool name.
- `input` (`Record<string, unknown>`): Tool call input.

**Returns** `string | undefined`

Source: [src/behaviors/repeat-guard.ts:184](https://github.com/Tahul/zidane/blob/main/src/behaviors/repeat-guard.ts#L184)

### `defaultRepeatGuardTracked`

Function.

Default tracked-tool predicate: the built-in `shell` and `read_file` tools.
`shell` is an auto-approved, side-effect-light retry magnet; `read_file` is
the re-read loop magnet. Both are the loop shapes the abort escalation exists
for. Consumers that want to track additional tools (e.g. an MCP query runner)
pass them via
`RepeatGuardConfig.tools`.

```ts
function defaultRepeatGuardTracked(name: string): boolean
```

**Parameters**

- `name` (`string`): Tool name.

**Returns** `boolean`

Source: [src/behaviors/repeat-guard.ts:99](https://github.com/Tahul/zidane/blob/main/src/behaviors/repeat-guard.ts#L99)

### `describeProviderLimit`

Function.

The one human message for a rate limit, a spent quota or an overload:
`Claude rate limit reached. Resets in 1 h 45 min.`, `OpenAI quota reached`,
`Claude is overloaded`. Every provider classifier words these through
here, so the run line, a subagent's output, the fallback notice and the OS
notification all read the same.

```ts
function describeProviderLimit(limit: ProviderLimit): string
```

**Parameters**

- `limit` (`ProviderLimit`): What was hit, who by, and when it resets.

**Returns** `string`

Source: [src/errors.ts:564](https://github.com/Tahul/zidane/blob/main/src/errors.ts#L564)

### `detectTurnInterruption`

Function.

Inspect a session's trailing turn to classify whether the run was
interrupted mid-tool-call. Pure / synchronous — does not modify the input.

Pair with [`filterUnresolvedToolUses`](https://zidane.si/docs/reference/index.md#filterUnresolvedToolUses) on the resume path: filter
first so the result reflects the post-cleanup state (a turn whose orphans
were stripped reads as 'completed', not 'interrupted').

```ts
function detectTurnInterruption<T extends { content: SessionContentBlock[]; role: string }>(
  turns: T[],
): TurnInterruptionState
```

**Type parameters**

- `T` (`extends { content: SessionContentBlock[]; role: string }`)

**Parameters**

- `turns` (`T[]`): Turns of the session, oldest first.

**Returns** `TurnInterruptionState`

Source: [src/session/messages.ts:832](https://github.com/Tahul/zidane/blob/main/src/session/messages.ts#L832)

### `editSessionMetadata`

Function.

THE canonical seed for "open an editing session with preset context" —
the session metadata both hosts stamp at creation time. The engines read
the marker back and inject + auto-activate the matching inline preset
skill ([`buildZidaneExtensionSkill`](https://zidane.si/docs/reference/index.md#buildZidaneExtensionSkill) / [`buildZidaneSkillEditSkill`](https://zidane.si/docs/reference/index.md#buildZidaneSkillEditSkill)),
so the preset rides as real conversation context from turn one.

```ts
function editSessionMetadata(target: EditSessionTarget): Record<string, unknown>
```

**Parameters**

- `target` (`EditSessionTarget`): The extension or skill the editing session targets.

**Returns** `Record<string, unknown>`

Source: [src/extension-authoring.ts:92](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L92)

### `effectiveContextWindow`

Function.

Effective context window — what the next user turn can actually pack
before the provider reserves space for the assistant's reply. Equals
`rawWindow - OUTPUT_RESERVE_TOKENS`, clamped to `>= 1` so a tiny
(or absurd) window doesn't yield zero / negative thresholds.

Pass `null` through unchanged so callers can pipe a raw window lookup
directly without an intermediate check.

```ts
function effectiveContextWindow(rawWindow: number | null): number | null
```

**Parameters**

- `rawWindow` (`number | null`): Raw context window in tokens, or `null` when unknown.

**Returns** `number | null`

Source: [src/compact/policy.ts:34](https://github.com/Tahul/zidane/blob/main/src/compact/policy.ts#L34)

### `ensureEndsWithUserMessage`

Function.

Guarantee a message list ends with a `role: 'user'` message, appending a
synthetic directive when it doesn't.

Why: Anthropic's API (and several OpenAI-compat reasoning models — opus
4.7, the o-series translation layers on Bedrock/Vertex) rejects requests
whose final message is `role: 'assistant'` with
"This model does not support assistant message prefill. The conversation
must end with a user message."

Triggers in zidane:

- Compaction over a session whose last turn is the agent's response
  (the common case — autocompact fires right after `agent.run()`).
- Schema enforcement after an assistant text turn (no `tool_use`, so
  `ensureToolResultPairing` doesn't synthesize a user tail).
- `context:transform` hooks that strip the trailing user turn.

The pair-repair pass [`ensureToolResultPairing`](https://zidane.si/docs/reference/index.md#ensureToolResultPairing) already covers the
orphan-`tool_use` case via mode 2; this helper closes the plain-text
assistant-tail case. They compose: run pair-repair first, then this
pass, so an assistant turn with orphan tool_uses gets its synthetic
`tool_result` user turn AND this pass is a no-op (the synthetic turn
is already user-role).

Empty input passes through unchanged — the caller's "nothing to send"
guard is responsible for that case; we don't materialize a conversation
out of an empty list.

Idempotent: returns the input reference unchanged when the list is
already user-terminated (or empty).

```ts
function ensureEndsWithUserMessage(
  messages: SessionMessage[],
  provider: Provider,
  directive?: string,
): SessionMessage[]
```

**Parameters**

- `messages` (`SessionMessage[]`): Wire-ready message list.
- `provider` (`Provider`): Provider whose `userMessage()` shape we use so the
  synthetic turn matches the wire format the rest of
  the list already follows.
- `directive?` (`string`, default `DEFAULT_USER_TAIL_DIRECTIVE`): Text to put in the synthetic user message. Defaults
  to `DEFAULT_USER_TAIL_DIRECTIVE` ("Continue.").
  Compaction overrides this with a summary-specific cue.

**Returns** `SessionMessage[]`

Source: [src/session/messages.ts:908](https://github.com/Tahul/zidane/blob/main/src/session/messages.ts#L908)

### `ensureToolResultPairing`

Function.

Defensive repair pass that rewrites a message list so it satisfies the
wire-level `tool_use` ↔ `tool_result` adjacency contract every modern
provider enforces.

Anthropic 400s on orphans with `'tool_use' ids were found without
'tool_result' blocks immediately after` (and its inverse, `tool_result
must be preceded by a tool_call with the same toolCallId`). OpenAI's
Chat Completions API rejects most mismatches with a 400 too.

Six repair modes — modeled after Anthropic's Claude Code defenses:

| # | Corruption | Repair |
| - | - | - |
| 1 | assistant `tool_use` whose next user msg lacks a matching `tool_result` | **Prepend** a synthetic `tool_result` block carrying [`SYNTHETIC_TOOL_RESULT_PLACEHOLDER`](https://zidane.si/docs/reference/index.md#SYNTHETIC_TOOL_RESULT_PLACEHOLDER) with `isError: true` |
| 2 | assistant `tool_use` followed by nothing (or by a non-user msg) | **Insert** a new synthetic user message with the same placeholder |
| 3 | user `tool_result` with no preceding assistant `tool_call` | **Strip** the orphan block; if it empties the msg, replace with [`ORPHANED_TOOL_RESULT_MARKER`](https://zidane.si/docs/reference/index.md#ORPHANED_TOOL_RESULT_MARKER) text block |
| 4 | duplicate `tool_call.id` across assistant messages (CC-1212) | **Strip** later instances + their matching tool_results |
| 5 | duplicate `tool_result.callId` within a single user message | **Dedupe** by `callId`, keep first |
| 6 | assistant message emptied by mode-4 stripping | **Replace** content with [`TOOL_USE_INTERRUPTED_MARKER`](https://zidane.si/docs/reference/index.md#TOOL_USE_INTERRUPTED_MARKER) text block |

**Repair, not drop.** Dropping orphan blocks would (a) silently rewrite
history the model had reasoned over and (b) cascade — dropping an assistant
tool_call would orphan its tool_result, which would then get dropped too,
removing any trace of "what the model tried to do" from the transcript. This
pass preserves the model's tool_use shape and patches the dangling result
with an `is_error` placeholder so the model sees "I tried X, the result was
lost" and can retry intelligently.

Adjacency contract: `tool_result` blocks must live in the user message
IMMEDIATELY following the assistant message that emitted the matching
`tool_use`. The pass enforces strict adjacency — a tool_result two
messages downstream of its tool_call is still an orphan.

Idempotent: returns the input reference unchanged when no repairs were
necessary. Re-running on already-repaired output is a no-op.

Pure: does not mutate input messages or their content arrays — every
repair allocates a fresh array / object.

```ts
function ensureToolResultPairing(
  messages: SessionMessage[],
  options?: EnsureToolResultPairingOptions,
): SessionMessage[]
```

**Parameters**

- `messages` (`SessionMessage[]`): Wire messages to repair. They are not modified.
- `options?` (`EnsureToolResultPairingOptions`, default `{}`): Repair callback. See [`EnsureToolResultPairingOptions`](https://zidane.si/docs/reference/index.md#EnsureToolResultPairingOptions).

**Returns** `SessionMessage[]`

Source: [src/session/messages-pairing.ts:122](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L122)

### `estimateTokens`

Function.

Approximate token count for `text`: `text.length` (UTF-16 code units, not
bytes) divided by [`BYTES_PER_TOKEN`](https://zidane.si/docs/reference/index.md#BYTES_PER_TOKEN), rounded up. Mirrors Claude Code's
`BYTES_PER_TOKEN = 4` heuristic — acceptable for budget arithmetic
(sizing summarization scopes, enforcing per-file caps in restoration).

A rough estimate. Use a real tokenizer when exact counts matter (cost
reporting, hard caps); this is for budget gates where being off by some
percent is fine.

Pure. Exported so callers (TUI, SDK consumers) can do their own
pre-budgeting against the same heuristic the harness uses internally.

```ts
function estimateTokens(text: string): number
```

**Parameters**

- `text` (`string`): String to estimate.

**Returns** `number`

Source: [src/compact/utils.ts:62](https://github.com/Tahul/zidane/blob/main/src/compact/utils.ts#L62)

### `extensionDirForCwd`

Function.

If `cwd` sits inside a zidane extension, return that extension's root dir,
else `null`. Mirrors the discovery layout
`<scope>/.{agents,zidane}/extensions/<name>/` — the root is the `<name>` dir
(parent `extensions`, grandparent `.agents` / `.zidane`) holding an entry
file. Walks up from `cwd`, so the nearest enclosing extension wins. Lets the
hosts surface the authoring skill for a plain `zidane` launched from an
extension folder, not just sessions opened through the edit/create flow.

```ts
function extensionDirForCwd(cwd?: string): string | null
```

**Parameters**

- `cwd?` (`string`): Directory to start the upward walk from. Defaults to `process.cwd()`.

**Returns** `string | null`

Source: [src/extension-authoring.ts:468](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L468)

### `extensionScaffold`

Function.

The `index.ts` of a new extension: a setting and one command (palette
entry and slash command) that toasts it. With `ui` / `tui`, a status slot
whose `Status` component comes from the matching entry. The `id` MUST equal
the folder name, or discovery refuses the extension.

```ts
function extensionScaffold(
  name: string,
  opts?: Pick<ExtensionScaffoldOptions, 'ui' | 'tui'>,
): string
```

**Parameters**

- `name` (`string`): Extension id. Must equal the extension's folder name.
- `opts?` (`Pick<ExtensionScaffoldOptions, 'ui' | 'tui'>`, default `{}`): Whether the extension has a `ui` and / or a `tui` entry.

**Returns** `string`

Source: [src/extension-authoring.ts:135](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L135)

### `fanoutSink`

Function.

Fan a single record out to several sinks. Each sink's `emit` is guarded
so one throwing sink can't starve the others (mirrors `createLogger`'s
"a sink must never crash the run" contract).

```ts
function fanoutSink(sinks: readonly LogSink[]): LogSink
```

**Parameters**

- `sinks` (`readonly LogSink[]`): Sinks that receive every record, in order.

**Returns** `LogSink`

Source: [src/logger.ts:202](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L202)

### `filterUnresolvedToolUses`

Function.

Drop ASSISTANT turns whose every `tool_call` block is unresolved
(no matching `tool_result` block anywhere later in the transcript).
Tool_call blocks with at least one matching tool_result are kept — modes
1/3 of [`ensureToolResultPairing`](https://zidane.si/docs/reference/index.md#ensureToolResultPairing) handle the partial-pair case at
wire-send time.

Use case: session resume. A turn that emitted three `tool_use` blocks but
never persisted the matching `tool_result` turn (process death, crash,
`kill -9`) leaves the transcript with an orphan that Anthropic rejects on
the FIRST API call after reload. Dropping the whole assistant turn — not
just the orphan blocks — preserves text-only turns that legitimately
carry reasoning the model wants to see again.

Does NOT mint fresh ids: re-id'ing on every resume would cause
exponential transcript growth across repeated resumes of an interrupted
session.

Pure: returns the input reference unchanged when no turn was dropped.

```ts
function filterUnresolvedToolUses<T extends { content: SessionContentBlock[]; role: string }>(
  turns: T[],
): T[]
```

**Type parameters**

- `T` (`extends { content: SessionContentBlock[]; role: string }`)

**Parameters**

- `turns` (`T[]`): Turns of the session, oldest first.

**Returns** `T[]`

Source: [src/session/messages.ts:766](https://github.com/Tahul/zidane/blob/main/src/session/messages.ts#L766)

### `formatTokenUsage`

Function.

Render a one-line token summary suitable for spawn-end markers, child
tool-result text, and any other per-run "what did this cost?" surface.

`in 52413 (cache 50000) / 4075 out`

The `in` total includes cached reads and cache-creation tokens (see
`effectiveInputTokens`); the `(cache N)` parenthetical breaks out
the cached portion so the user can tell at a glance how much was reused
vs new. The parenthetical is omitted when its value is zero, so
non-caching providers and brand-new runs read simply as `in N / M out`.

Output-side caching is not a concept any current provider exposes —
Anthropic's `cacheRead` / `cacheCreation` are both input-billed. If a
future provider ships an output cache, extend `TokenUsageLike` with
output-cache fields and add a parallel `(cache N)` slot on the `out`
side here; today the right side is always plain `${N} out`.

```ts
function formatTokenUsage(stats: TokenUsageLike): string
```

**Parameters**

- `stats` (`TokenUsageLike`): Cumulative token counts. Missing, negative or non-finite values count as 0.

**Returns** `string`

Source: [src/stats.ts:132](https://github.com/Tahul/zidane/blob/main/src/stats.ts#L132)

### `githubApiBase`

Function.

REST root for a host (github.com or Enterprise).

```ts
function githubApiBase(host: string): string
```

**Parameters**

- `host` (`string`): API host.

**Returns** `string`

Source: [src/github/client.ts:187](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L187)

### `githubClient`

Function.

This process's client: one quota view and one answer cache for every GitHub reader.

```ts
function githubClient(): GithubClient
```

**Returns** `GithubClient`

Source: [src/github/client.ts:777](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L777)

### `githubPullConfirmedAt`

Function.

When this process last confirmed a PR current with GitHub (epoch ms), if it did.

```ts
function githubPullConfirmedAt(ref: GithubPullRef): number | undefined
```

**Parameters**

- `ref` (`GithubPullRef`): Pull request to look up.

**Returns** `number | undefined`

Source: [src/github/pulls.ts:146](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L146)

### `githubTokenFingerprint`

Function.

`sha256(host + token)`, 16 hex chars: safe for keys and files, never the token.

```ts
function githubTokenFingerprint(host: string, token: string): Promise<string>
```

**Parameters**

- `host` (`string`): API host. Normalized before hashing.
- `token` (`string`): The token to fingerprint.

**Returns** `Promise<string>`

Source: [src/github/client.ts:294](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L294)

### `hasAuthorizationHeader`

Function.

True when an HTTP transport's auth headers already include an explicit
Authorization. Used by the bootstrap escape-hatch: a user who provided
their own bearer token shouldn't be auto-promoted to OAuth on a 401.

Case-insensitive — Node normalizes outgoing headers to lowercase but
users hand-write `Authorization` in configs.

```ts
function hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean
```

**Parameters**

- `headers` (`Record<string, string> | undefined`): Configured request headers, if any.

**Returns** `boolean`

Source: [src/mcp/oauth-provider.ts:492](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L492)

### `isGhRateLimitError`

Function.

`primary` (the hourly quota is spent), `secondary` (too fast), or `null`.

```ts
function isGhRateLimitError(stderr: string): 'primary' | 'secondary' | null
```

**Parameters**

- `stderr` (`string`): Standard error text of a failed `gh` command.
  Mirrored by `ghRateLimitKind` in `extensions/git-flow/shared.ts`: change both together.

**Returns** `'primary' | 'secondary' | null`

Source: [src/github/gh-cli.ts:12](https://github.com/Tahul/zidane/blob/main/src/github/gh-cli.ts#L12)

### `isSqliteBusyError`

Function.

True when `err` is SQLite reporting a held lock (SQLITE_BUSY, SQLITE_LOCKED).

```ts
function isSqliteBusyError(err: unknown): boolean
```

**Parameters**

- `err` (`unknown`): Error thrown by a SQLite call.

**Returns** `boolean`

Source: [src/session/sqlite-driver.ts:135](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L135)

### `isStandardSchema`

Function.

Checks whether `value` carries a Standard Schema `~standard` marker with a string `vendor`.

```ts
function isStandardSchema(value: unknown): value is StandardSchemaLike<unknown>
```

**Parameters**

- `value` (`unknown`): Value to check.

**Returns** `value is StandardSchemaLike<unknown>`

Source: [src/zod.ts:46](https://github.com/Tahul/zidane/blob/main/src/zod.ts#L46)

### `isThinkingLevel`

Function.

Type guard for canonical `ThinkingLevel` strings (e.g. `metadata.effort` read off a persisted session).

```ts
function isThinkingLevel(
  value: unknown,
): value is 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'adaptive'
```

**Parameters**

- `value` (`unknown`): Any value, usually a string read from storage or settings.

**Returns** `value is 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'adaptive'`

Source: [src/thinking-levels.ts:23](https://github.com/Tahul/zidane/blob/main/src/thinking-levels.ts#L23)

### `isToolStateOps`

Function.

Runtime guard for a journaled op list — adapters validate before restoring.

```ts
function isToolStateOps(value: unknown): value is ToolStateOp[]
```

**Parameters**

- `value` (`unknown`): Value to check.

**Returns** `value is ToolStateOp[]`

Source: [src/tool-state.ts:418](https://github.com/Tahul/zidane/blob/main/src/tool-state.ts#L418)

### `isValidCallbackPort`

Function.

Unprivileged TCP port: the loopback listener can't bind below 1024 without root.

```ts
function isValidCallbackPort(port: unknown): port is number
```

**Parameters**

- `port` (`unknown`): Value to check.

**Returns** `port is number`

Source: [src/mcp/server-config.ts:281](https://github.com/Tahul/zidane/blob/main/src/mcp/server-config.ts#L281)

### `jsonSink`

Function.

One-JSON-object-per-line sink. Suitable for piping into log aggregators
(Datadog Agent, Fluent Bit, Loki, Vector) that expect JSONL.

```ts
function jsonSink(options?: ConsoleSinkOptions): LogSink
```

**Parameters**

- `options?` (`ConsoleSinkOptions`, default `{}`): Minimum level and output stream. All fields are optional.

**Returns** `LogSink`

Source: [src/logger.ts:178](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L178)

### `labelSessions`

Function.

Names each process's session as the reader does, and titles it, read once per session.

```ts
function labelSessions(
  sessions: ReadonlyMap<number, string>,
  titleOf: (sessionId: string) => string | undefined,
  keyOf?: (sessionId: string) => string,
): Map<number, PerfProcessSession>
```

**Parameters**

- `sessions` (`ReadonlyMap<number, string>`): The session id of each process (`Owned.sessions`).
- `titleOf` (`(sessionId: string) => string | undefined`): A session's title; `undefined` while it has none.
- `keyOf?` (`(sessionId: string) => string`): The reader's key for a session id (the desktop app's `SessionKey`). Default: the id.

**Returns** `Map<number, PerfProcessSession>`: The session of each process, by pid.

Source: [src/perf/owned.ts:182](https://github.com/Tahul/zidane/blob/main/src/perf/owned.ts#L182)

### `latestSystemSnapshot`

Function.

The newest frozen prompt recorded for `key`. A cleared snapshot for the
same key, or one with no key, ends the search with `undefined`; snapshots
for other keys are skipped.

```ts
function latestSystemSnapshot(
  turns: readonly SessionTurn[],
  key?: string,
): FrozenSystemPrompt | undefined
```

**Parameters**

- `turns` (`readonly SessionTurn[]`): Session turns, oldest first.
- `key?` (`string`): The prompt key the snapshot was recorded under; omitted matches keyless snapshots.

**Returns** `FrozenSystemPrompt | undefined`

Source: [src/system-freeze.ts:87](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L87)

### `localReliabilityBehavior`

Function.

Opt-in behavior overlay for brittle/local OpenAI-compatible endpoints.
Returns plain `AgentBehavior` so hosts can spread it before or after their
own overrides; no built-in profile uses this helper by default.

```ts
function localReliabilityBehavior(overrides?: AgentBehavior): AgentBehavior
```

**Parameters**

- `overrides?` (`AgentBehavior`, default `{}`): Behavior fields that replace the defaults. `readFileDefaults` is merged key by key.

**Returns** `AgentBehavior`

Source: [src/behaviors/local-reliability.ts:23](https://github.com/Tahul/zidane/blob/main/src/behaviors/local-reliability.ts#L23)

### `loginMcpServer`

Function.

Run the full interactive OAuth flow for `config`. Only supports `sse` and
`streamable-http` transports — `stdio` MCP servers don't speak OAuth.

Throws on:

- Wrong transport.
- Abort signal.
- Browser-side error (user denied, server rejected, etc.).
- Code exchange failure.
- Post-exchange connect failure.

Always closes the loopback callback server before returning, success or
failure.

```ts
function loginMcpServer(
  config: McpServerConfig,
  options: LoginMcpServerOptions,
): Promise<LoginMcpServerResult>
```

**Parameters**

- `config` (`McpServerConfig`): Server to sign in to. Must use the `sse` or `streamable-http` transport and have a `url`.
- `options` (`LoginMcpServerOptions`): Credential store and flow settings. See [`LoginMcpServerOptions`](https://zidane.si/docs/reference/index.md#LoginMcpServerOptions).

**Returns** `Promise<LoginMcpServerResult>`

Source: [src/mcp/login.ts:132](https://github.com/Tahul/zidane/blob/main/src/mcp/login.ts#L132)

### `maybePersistToolResult`

Function.

Decide-and-persist for a single tool result. Pure decision + filesystem
side-effect; returns the new wire-level `output` string when substitution
happened, otherwise tells the caller to leave the result alone.

Atomicity: the local fallback writes through `<path>.tmp` + `rename` so a
concurrent read (or a crash mid-write) never sees a half-written blob. A
routed write (`input.writeBlob`, e.g. a sandbox `writeFile`) is not atomic;
see the field doc for why that's safe here.

Text-only `ToolResultContent[]` results are flattened and persisted as
text. Mixed structured content still bypasses persistence because the inline
image/document bytes are the point of the call and a mixed result is not
representable as a single `.txt` file without dropping media.

```ts
function maybePersistToolResult(input: PersistInput): Promise<PersistOutcome>
```

**Parameters**

- `input` (`PersistInput`): Tool name, call id, output and persistence settings.

**Returns** `Promise<PersistOutcome>`

Source: [src/loop-persistence.ts:558](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L558)

### `mcpOAuthProviderFor`

Function.

The provider for `config`: carries its pre-registered client
(`config.oauth`) and scope when it has one. Every host builds its
providers through this, so a static client is honored by bootstrap,
token refresh, Test and Sign in alike.

The secret comes from the config (`${VAR}` expanded) or, failing that,
from the credential store, where a host UI saved it.

```ts
function mcpOAuthProviderFor(
  config: Pick<McpServerConfig, 'name' | 'oauth'>,
  opts: Omit<McpOAuthProviderOptions, 'name' | 'staticClient'>,
): McpOAuthProvider
```

**Parameters**

- `config` (`Pick<McpServerConfig, 'name' | 'oauth'>`): Server name and optional pre-registered client settings (`oauth`).
- `opts` (`Omit<McpOAuthProviderOptions, 'name' | 'staticClient'>`): Provider options other than `name` and `staticClient`. `scope` overrides the config scope.

**Returns** `McpOAuthProvider`

Source: [src/mcp/oauth-provider.ts:396](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L396)

### `migrateSessionArtifactDirs`

Function.

Fold older artifact layouts into the session-first one
(`<userDir>/sessions/<sessionId>/<kind>/`).

Two source layouts are folded in:

1. pre-6.x `<userDir>/<sessionId>/{tasks,mcp-warnings}/` — one top-level
   entry per session, so a few hundred sessions bury `credentials.json`
   under noise. This is what is actually on users' disks.
2. kind-first `<userDir>/{tasks,mcp-warnings}/<sessionId>/` — a shape that
   only ever existed in dev builds between the two designs. Handled so a
   contributor who ran one doesn't end up with artifacts in three places.

`tool-results/<sessionId>/` is deliberately NOT a source: those blobs are
referenced by absolute path from inside session transcripts and re-read by
the model, so relocating them without rewriting every transcript would
strand them. See [`resolvePersistDir`](https://zidane.si/docs/reference/index.md#resolvePersistDir) and [`resolveLegacyPersistDir`](https://zidane.si/docs/reference/index.md#resolveLegacyPersistDir).

Sync + best-effort by design. It runs on the chat bootstrap path, so it
must not make startup fail on a read-only or half-permissioned storage
dir; every filesystem call is individually guarded and failures are
counted, not thrown. `renameSync` within one directory tree can't hit
EXDEV, so the moves are atomic metadata updates, not copies.

Idempotent and cheap to re-run: one `readdirSync` of the user dir, plus one
of each kind-first root that still exists. A migrated tree has no sources
left to match, so there's no "migration done" marker to keep in sync — the
filesystem shape IS the marker.

Conflicts are left alone: if the destination already exists, the source
stays put and counts as `failed` rather than having its contents merged or
clobbered. Nothing is ever deleted except an emptied source shell
(`rmdirSync`, which refuses non-empty dirs), so an unexpected layout
survives for the operator to inspect.

Note that a pending conflict is re-counted on EVERY sweep: nothing but
session-delete can resolve it (both copies are live data), so each boot
legitimately re-observes it and reports `failed: 1`. The effects stay
idempotent — nothing moves, nothing is removed — only the counter repeats.

Known mixed-version race, accepted: a still-running pre-migration process
holds its tasksDir at the old path and this sweep renames it away. Open
write streams keep working (the inode moves with the rename), but log paths
already quoted in that session's turns go stale, and the old process's
defensive mkdir may recreate the source dir — which the next boot
re-migrates. Task logs are ephemeral debug output, so a liveness heuristic
isn't worth the complexity.

```ts
function migrateSessionArtifactDirs(
  opts: { userDir: string },
): SessionArtifactDirMigration
```

**Parameters**

- `opts` (`{ userDir: string }`): Storage directory (must be absolute) to scan for older artifact layouts.

**Returns** `SessionArtifactDirMigration`

Source: [src/loop-persistence.ts:345](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L345)

### `normalizeGithubHost`

Function.

Normalizes a host name to lowercase and maps `api.github.com` and `www.github.com` to `github.com`. Defaults to `github.com`.

```ts
function normalizeGithubHost(host: string | undefined): string
```

**Parameters**

- `host` (`string | undefined`): Host name, or `undefined` for `github.com`.

**Returns** `string`

Source: [src/github/client.ts:178](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L178)

### `normalizeProviders`

Function.

Normalize `AgentOptions.provider` into a non-empty provider list.

In multi-provider setups every provider needs a non-blank, unique name —
model entries reference providers by `Provider.name`, so a blank or
duplicate name would make the reference ambiguous (and surface as a
baffling `duplicate provider name ""` otherwise). A single provider
has no such constraint: its name plays no role in target resolution. Throws at agent construction rather than at
run time.

```ts
function normalizeProviders(provider: Provider | Provider[]): Provider[]
```

**Parameters**

- `provider` (`Provider | Provider[]`): A single provider or an ordered list of providers.

**Returns** `Provider[]`

Source: [src/model-targets.ts:16](https://github.com/Tahul/zidane/blob/main/src/model-targets.ts#L16)

### `normalizeShellCommand`

Function.

Canonicalize a shell command so semantically-identical invocations collapse
to one streak key:

- strip a leading `cd <path> &&` (or `cd <path>;`) prefix — the model often
  re-prefixes the same command with a `cd` into the project root.
- strip a trailing verify-tail of the shape `& sleep N ; <anything>` or
  `; sleep N && <anything>` that the model appends to poll a just-started
  process (`… & sleep 2 ; curl localhost`).
- collapse runs of whitespace to single spaces and trim.

Conservative on purpose: it does NOT reorder flags or parse the command —
it only removes the two wrappers we actually saw inflate distinct-looking
retries of the same core command, plus whitespace noise.

```ts
function normalizeShellCommand(command: string): string
```

**Parameters**

- `command` (`string`): Shell command text.

**Returns** `string`

Source: [src/behaviors/repeat-guard.ts:150](https://github.com/Tahul/zidane/blob/main/src/behaviors/repeat-guard.ts#L150)

### `originTotals`

Function.

CPU and memory summed per origin.

```ts
function originTotals(processes: readonly PerfProcess[]): Record<PerfOrigin, PerfTotals>
```

**Parameters**

- `processes` (`readonly PerfProcess[]`): One sample's.

**Returns** `Record<PerfOrigin, PerfTotals>`

Source: [src/perf/processes.ts:118](https://github.com/Tahul/zidane/blob/main/src/perf/processes.ts#L118)

### `pinnedMcpRedirectUri`

Function.

The loopback redirect a pinned `oauth.callbackPort` produces: the URL to
register with the provider. Pass the same `callbackPath` given to
`loginMcpServer`, if any.

```ts
function pinnedMcpRedirectUri(
  config: Pick<McpServerConfig, 'oauth'>,
  callbackPath?: string,
): string | undefined
```

**Parameters**

- `config` (`Pick<McpServerConfig, 'oauth'>`): Server config. Only `oauth.callbackPort` is read.
- `callbackPath?` (`string`, default `DEFAULT_OAUTH_CALLBACK_PATH`): Path of the callback URL.

**Returns** `string | undefined`: The redirect URL, or `undefined` when no callback port is pinned.

Source: [src/mcp/server-config.ts:293](https://github.com/Tahul/zidane/blob/main/src/mcp/server-config.ts#L293)

### `queueGithubPull`

Function.

Read a PR together with whatever else is asked for in the next \~10 ms
(interactive and background reads travel apart: they spend the quota
differently).

```ts
function queueGithubPull(
  ref: GithubPullRef,
  opts?: GithubPullReadOptions,
): Promise<GithubPullRead>
```

**Parameters**

- `ref` (`GithubPullRef`): Pull request to read.
- `opts?` (`GithubPullReadOptions`, default `{}`): Read options. `interactive` selects the queue.

**Returns** `Promise<GithubPullRead>`

Source: [src/github/pulls.ts:615](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L615)

### `rateLimitResetFromJson`

Function.

The reset of a quota from `gh api rate_limit` output (epoch seconds in
`resources.<name>.reset`), as local epoch ms; `undefined` when unreadable.

```ts
function rateLimitResetFromJson(
  json: string,
  resource?: 'core' | 'graphql',
): number | undefined
```

**Parameters**

- `json` (`string`): Output of `gh api rate_limit`.
- `resource?` (`'core' | 'graphql'`, default `'graphql'`): Quota to read the reset of.

**Returns** `number | undefined`

Source: [src/github/gh-cli.ts:26](https://github.com/Tahul/zidane/blob/main/src/github/gh-cli.ts#L26)

### `readGithubPull`

Function.

One PR.

```ts
function readGithubPull(
  ref: GithubPullRef,
  opts?: GithubPullReadOptions,
): Promise<GithubPullRead>
```

**Parameters**

- `ref` (`GithubPullRef`): Pull request to read. An invalid ref answers `unavailable`.
- `opts?` (`GithubPullReadOptions`, default `{}`): Read options.

**Returns** `Promise<GithubPullRead>`

Source: [src/github/pulls.ts:511](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L511)

### `readGithubPulls`

Function.

Many PRs, in the order asked. See the module doc for how they travel. An
open PR's merge state isn't covered by `updated_at` (checks don't move it),
so an open one read more than `PULL_FRESH_MS` ago is read again even
when nothing else moved.

```ts
function readGithubPulls(
  items: readonly { known?: KnownGithubPull; ref: GithubPullRef }[],
  opts?: Omit<GithubPullReadOptions, 'known'>,
): Promise<GithubPullRead[]>
```

**Parameters**

- `items` (`readonly { known?: KnownGithubPull; ref: GithubPullRef }[]`): Pull requests to read, each with an optional copy the caller already holds.
- `opts?` (`Omit<GithubPullReadOptions, 'known'>`, default `{}`): Options applied to every read.

**Returns** `Promise<GithubPullRead[]>`

Source: [src/github/pulls.ts:525](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L525)

### `readOsThreads`

Function.

The OS threads of a process, busiest first.

```ts
function readOsThreads(pid: number): Promise<PerfOsThread[]>
```

**Parameters**

- `pid` (`number`): The process.

**Returns** `Promise<PerfOsThread[]>`: Empty on a platform without a reader, or when the process has gone.

Source: [src/perf/os-threads.ts:48](https://github.com/Tahul/zidane/blob/main/src/perf/os-threads.ts#L48)

### `readProcessTree`

Function.

The trees under `roots` (`descendants`), the monitor's own commands left
out. On Linux each row's CPU time is read from `/proc`: its `ps` rounds
it to whole seconds.

```ts
function readProcessTree(roots: readonly number[]): Promise<PsRow[]>
```

**Parameters**

- `roots` (`readonly number[]`): The trees' roots.

**Returns** `Promise<PsRow[]>`

Source: [src/perf/ps.ts:188](https://github.com/Tahul/zidane/blob/main/src/perf/ps.ts#L188)

### `readSkillEditMarker`

Function.

Parse a persisted [`SkillEditMarker`](https://zidane.si/docs/reference/index.md#SkillEditMarker) back out of session metadata.
Tolerant: anything that isn't `{ dir: string, name: string }` → `null`
(older sessions, manual metadata edits, type drift).

```ts
function readSkillEditMarker(raw: unknown): SkillEditMarker | null
```

**Parameters**

- `raw` (`unknown`): Value read from `session.metadata`, of unknown shape.

**Returns** `SkillEditMarker | null`

Source: [src/extension-authoring.ts:105](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L105)

### `reasoningWireAction`

Function.

Single source of truth for whether a signature-bearing reasoning block
(`thinking` / `redacted_thinking`) may be forwarded to a provider. The
wire builders ([`toAnthropic`](https://zidane.si/docs/reference/session.md#toAnthropic), the OpenAI and Google message shapers)
and the host-facing [`sanitizeHistoryForProvider`](https://zidane.si/docs/reference/index.md#sanitizeHistoryForProvider) apply this same
policy — keeping them one function means the sanitizer can never drift
from what the wire actually sends.

Rules, each driven by an API constraint hit in production:

- target `anthropic`:
  - `redacted_thinking` → keep (native Anthropic block; must be echoed).
  - `thinking` tagged `openai`, `google` or `google-vertex` → drop
    (OpenAI `encrypted_content` and Gemini thought signatures are not
    valid Anthropic HMACs; 400s).
  - unsigned `thinking` → drop (`ThinkingBlockParam` requires a
    signature; unsigned blocks come from non-signing producers).
  - signed but UNTAGGED `thinking` (pre-tagging sessions) → keep: it is
    most plausibly legacy Anthropic output, and the signature-400
    recovery converges if it is not.

- target `openai` or a Gemini-wire scope (`google`, `google-vertex`, a
  `googleCompatible` route's):
  - `redacted_thinking` → drop (Anthropic-only block type).
  - `thinking` tagged `anthropic` → drop (an Anthropic HMAC is valid
    nowhere else).
  - `thinking` signed by any other producer, or signed but UNTAGGED →
    strip-signature: there is no signature-error recovery on these paths,
    so forwarding a possibly-foreign signature risks an unrecoverable
    400\. The reasoning text survives; only the opaque signature is
    withheld. Gemini's are kept only for the route that issued them.

```ts
function reasoningWireAction(
  block: { signature?: string; signatureProducer?: SignatureProducer; type: 'thinking' } | { type: 'redacted_thinking' },
  target: ReasoningWireTarget,
): ReasoningWireAction
```

**Parameters**

- `block` (`{ signature?: string; signatureProducer?: SignatureProducer; type: 'thinking' } | { type: 'redacted_thinking' }`): A `thinking` or `redacted_thinking` block.
- `target` (`ReasoningWireTarget`): Provider the history is sent to.

**Returns** `ReasoningWireAction`

Source: [src/session/messages.ts:476](https://github.com/Tahul/zidane/blob/main/src/session/messages.ts#L476)

### `remintDuplicateToolCallIds`

Function.

Re-mint tool-call ids that collide with ids already present in the
transcript (or with an earlier sibling in the same turn), BEFORE the turn
is persisted and its tools dispatched.

Why this exists: some providers/serving stacks emit non-globally-unique
tool_use ids (per-turn counters like `call_0`, retry-replay duplicates,
Kimi-K2.6 on Fireworks). The wire-time pairing pass
([`ensureToolResultPairing`](https://zidane.si/docs/reference/index.md#ensureToolResultPairing)) can only STRIP such duplicates — which
erases the model's tool calls and results from the wire view, stalls
progress, and re-accumulates repairs quadratically because the persisted
session keeps the corrupted ids. Re-minting at persist time keeps the
pairing intact instead: the call, its execution, and its tool_result all
carry the fresh id, so the pairing pass has nothing to strip on any later
turn.

Fresh ids are `${oldId}_r{n}` with `n` bumped until unique — deterministic
shape, Anthropic-wire-safe charset (given a safe input id), and visibly
traceable back to the original.

Alignment contract: `toolCalls` and the `tool_call` blocks inside
`content` are two views of the same emission and MUST be in the same
order (true for every provider — both are built from one source array).
Occurrences are matched positionally per old id so intra-turn duplicates
map to distinct fresh ids on both views.

Pure: returns the input references unchanged when no id collides.

```ts
function remintDuplicateToolCallIds(
  toolCalls: readonly { id: string; input: Record<string, unknown>; name: string }[],
  content: readonly SessionContentBlock[],
  priorIds: ReadonlySet<string>,
): RemintResult
```

**Parameters**

- `toolCalls` (`readonly { id: string; input: Record<string, unknown>; name: string }[]`): Tool calls of the new assistant turn.
- `content` (`readonly SessionContentBlock[]`): Content blocks of the same turn, with `tool_call` blocks in the same order as `toolCalls`.
- `priorIds` (`ReadonlySet<string>`): Tool call ids already in the transcript.

**Returns** `RemintResult`

Source: [src/session/messages-pairing.ts:405](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L405)

### `renderStaleReadNotice`

Function.

The notice text appended to a mutating tool's result under the `'notice'`
policy. Deterministic and free of counters/timestamps — append-only content
cannot break the cache, but a stable template keeps transcripts diffable and
the tests byte-exact.

```ts
function renderStaleReadNotice(paths: readonly string[]): string
```

**Parameters**

- `paths` (`readonly string[]`): Stale file paths, in the order they should be listed.

**Returns** `string`

Source: [src/loop-stale-reads.ts:355](https://github.com/Tahul/zidane/blob/main/src/loop-stale-reads.ts#L355)

### `resolveCompletionSubmit`

Function.

Resolves every provider reference in submitted text.
Groups references by provider, runs each provider's `resolveReferences` (when defined) and `onSubmit` hook, then returns the merged list.

```ts
function resolveCompletionSubmit<TItem>(
  text: string,
  providers: readonly CompletionProvider<TItem>[],
  options?: { cursor?: number; signal?: AbortSignal },
): Promise<CompletionReference<TItem>[]>
```

**Type parameters**

- `TItem`

**Parameters**

- `text` (`string`): The submitted prompt text.
- `providers` (`readonly CompletionProvider<TItem>[]`): Providers whose references are collected and resolved.
- `options?` (`{ cursor?: number; signal?: AbortSignal }`, default `{}`): Optional `cursor` (defaults to the end of `text`) and `signal` (defaults to a signal that never aborts) passed to provider hooks.

**Returns** `Promise<CompletionReference<TItem>[]>`

Source: [src/chat/completion-core.ts:388](https://github.com/Tahul/zidane/blob/main/src/chat/completion-core.ts#L388)

### `resolveExtensionDocsDir`

Function.

Locate the shipped `docs/` directory (`docs/EXTENSIONS.md` + siblings).

The docs ship via `package.json` `files`, so an installed consumer has
`<root>/node_modules/zidane/docs` and the repo itself has `<repo>/docs`.
Returns the first existing candidate, or `null` (the skill then falls back to
the literal `node_modules/zidane/docs` hint, which the model's file tools can
still attempt from cwd).

```ts
function resolveExtensionDocsDir(cwd?: string): string | null
```

**Parameters**

- `cwd?` (`string`): Directory used for the `node_modules/zidane/docs` fallback lookup. Defaults to `process.cwd()`.

**Returns** `string | null`

Source: [src/extension-authoring.ts:415](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L415)

### `resolveLegacyPersistDir`

Function.

Path of the pre-session-first blob directory (`<userDir>/tool-results/<sessionId>/`),
or `undefined` when the id doesn't match a shape zidane ever minted.

These blobs are deliberately NOT migrated — a persisted stub carries the
blob's absolute path inside the session transcript and the model re-reads it
with `read_file`, so moving the bytes without rewriting every transcript
strands them (see [`resolvePersistDir`](https://zidane.si/docs/reference/index.md#resolvePersistDir)). They keep resolving where they
are; this resolver exists so session delete still reclaims them. Same
positive id match, same reason.

```ts
function resolveLegacyPersistDir(
  opts: { sessionId: string; userDir: string },
): string | undefined
```

**Parameters**

- `opts` (`{ sessionId: string; userDir: string }`): Storage directory (must be absolute) and session id.

**Returns** `string | undefined`

Source: [src/loop-persistence.ts:279](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L279)

### `resolveLegacySessionDir`

Function.

Path of the pre-6.x per-session artifact shell (`<userDir>/<sessionId>/`), or
`undefined` when the id doesn't match a shape zidane ever minted.

Session delete sweeps this alongside the session subtree: when
[`migrateSessionArtifactDirs`](https://zidane.si/docs/reference/index.md#migrateSessionArtifactDirs) hits its conflict branch (the target
already existed), the shell is deliberately left in place and counted as
`failed` — and nothing else ever removes it, so deleting the session is the
one moment both copies are provably garbage. The positive id match is what
keeps an exotic host-minted id from resolving to a root like `tasks/`.

```ts
function resolveLegacySessionDir(
  opts: { sessionId: string; userDir: string },
): string | undefined
```

**Parameters**

- `opts` (`{ sessionId: string; userDir: string }`): Storage directory (must be absolute) and session id.

**Returns** `string | undefined`

Source: [src/loop-persistence.ts:260](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L260)

### `resolveMcpWarningsDir`

Function.

Resolve the per-session MCP diagnostic directory under
`<userDir>/sessions/<sessionId>/mcp-warnings/`.

Warning logs are cache/session artifacts like background task logs:
useful for debugging, safe to delete, and cleaned up with the session.

```ts
function resolveMcpWarningsDir(opts: { sessionId: string; userDir: string }): string
```

**Parameters**

- `opts` (`{ sessionId: string; userDir: string }`): Storage directory (must be absolute) and session id.

**Returns** `string`

Source: [src/loop-persistence.ts:207](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L207)

### `resolveModelTargets`

Function.

Resolve a run's model selection into an ordered, de-duplicated fallback
chain of provider+model targets. `targets[0]` is the primary.

Expansion rules:

- `undefined` → each provider's `meta.defaultModel`, in provider order.
- `string` → that model id on every provider, in provider order.
- array → entries in order; a `{ provider, model }` entry resolves to that
  one provider (throws on unknown names), while bare strings and
  provider-less objects fan out across all providers.

```ts
function resolveModelTargets(
  providers: readonly Provider[],
  model?: string | readonly (string | ModelTargetSpec)[],
): ModelTarget[]
```

**Parameters**

- `providers` (`readonly Provider[]`): Configured providers, in priority order. Must not be empty.
- `model?` (`string | readonly (string | ModelTargetSpec)[]`): Model id, or an ordered list of model ids and `{ provider, model }` entries. Omit to use each provider's default model.

**Returns** `ModelTarget[]`

Source: [src/model-targets.ts:55](https://github.com/Tahul/zidane/blob/main/src/model-targets.ts#L55)

### `resolvePersistDir`

Function.

Resolve the per-session persistence directory under
`<userDir>/sessions/<sessionId>/tool-results/`.

The chat layer calls this at session activation and forwards the result
via `behavior.persistDir`. Exposed as a public helper so SDK consumers
pick the same layout — single source of truth for "where do blobs live".

NOTE for anyone tempted to migrate old blobs into this path: don't. A
persisted stub embeds the blob's ABSOLUTE path in the session transcript
(see the `path="…"` attribute built in [`buildPersistedStub`](https://zidane.si/docs/reference/index.md#buildPersistedStub)) and the
MODEL re-reads it by calling `read_file` on that path. Moving the bytes
without rewriting every transcript strands them mid-conversation. Blobs
written under the old `<userDir>/tool-results/<sessionId>/` therefore stay
put and keep resolving forever; only new writes land here, and session
delete sweeps both (see [`resolveLegacyPersistDir`](https://zidane.si/docs/reference/index.md#resolveLegacyPersistDir)).

```ts
function resolvePersistDir(opts: { sessionId: string; userDir: string }): string
```

**Parameters**

- `opts` (`{ sessionId: string; userDir: string }`): Storage directory (must be absolute) and session id.

**Returns** `string`

Source: [src/loop-persistence.ts:179](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L179)

### `resolveSchemaInput`

Function.

Resolve a [`SchemaInput`](https://zidane.si/docs/reference/index.md#SchemaInput) to the plain JSON Schema object providers
expect. Zod schemas convert via the lazily-imported `z.toJSONSchema`
(v4 native); other Standard Schema vendors are rejected with a clear
error — conversion is vendor-specific and only zod is supported.

```ts
function resolveSchemaInput(schema: SchemaInput): Promise<Record<string, unknown>>
```

**Parameters**

- `schema` (`SchemaInput`): A plain JSON Schema object or a Standard Schema.

**Returns** `Promise<Record<string, unknown>>`

Source: [src/zod.ts:62](https://github.com/Tahul/zidane/blob/main/src/zod.ts#L62)

### `resolveSessionDir`

Function.

Resolve the root of a session's artifact subtree
(`<userDir>/sessions/<sessionId>/`).

This is what session delete removes: one recursive remove reclaims every
artifact kind at once, so adding a kind never touches the delete path.

```ts
function resolveSessionDir(opts: { sessionId: string; userDir: string }): string
```

**Parameters**

- `opts` (`{ sessionId: string; userDir: string }`): Storage directory (must be absolute) and session id (a single path segment).

**Returns** `string`

Source: [src/loop-persistence.ts:141](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L141)

### `resolveTasksDir`

Function.

Resolve the per-session background-tasks directory under
`<userDir>/sessions/<sessionId>/tasks/`.

The chat layer calls this at session activation and forwards the result via
`behavior.tasksDir`. Created on first write; cleanup is the session-delete
path's job — and since it lives inside the session's own subtree, that
cleanup is the same recursive remove that takes everything else.

```ts
function resolveTasksDir(opts: { sessionId: string; userDir: string }): string
```

**Parameters**

- `opts` (`{ sessionId: string; userDir: string }`): Storage directory (must be absolute) and session id.

**Returns** `string`

Source: [src/loop-persistence.ts:194](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L194)

### `runUsageAggregates`

Function.

All three aggregates against one handle.

```ts
function runUsageAggregates(database: UsageDatabase): UsageBuckets
```

**Parameters**

- `database` (`UsageDatabase`): A connection to a sessions database.

**Returns** `UsageBuckets`

Source: [src/session/sqlite-usage.ts:203](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L203)

### `sanitizeHistoryForProvider`

Function.

Host-facing history sanitizer — applies [`reasoningWireAction`](https://zidane.si/docs/reference/index.md#reasoningWireAction) to a
turn set BEFORE it is handed to an agent targeting `target`. The in-loop
wire builders already enforce the same policy per call, so this is for
hosts that seed history from an external durable store (or hydrate
pre-provenance-tagging sessions) and want the poison removed from their
source of truth in one call instead of re-deriving block semantics.

Returns new turn objects only where something changed (unchanged turns
pass through by reference). A turn whose content empties keeps the same
neutral marker the wire repair uses, so role boundaries stay intact.

```ts
function sanitizeHistoryForProvider<T extends { content: SessionContentBlock[] }>(
  turns: readonly T[],
  target: ReasoningWireTarget,
): { removed: number; stripped: number; turns: T[] }
```

**Type parameters**

- `T` (`extends { content: SessionContentBlock[] }`)

**Parameters**

- `turns` (`readonly T[]`): Turns to sanitize.
- `target` (`ReasoningWireTarget`): Provider the history is sent to.

**Returns** `{ removed: number; stripped: number; turns: T[] }`

Source: [src/session/messages.ts:505](https://github.com/Tahul/zidane/blob/main/src/session/messages.ts#L505)

### `saveMcpClientSecret`

Function.

Store (or, with an empty value, forget) the client secret a host UI
collected for `name`'s pre-registered client.

```ts
function saveMcpClientSecret(
  store: McpCredentialStore,
  name: string,
  secret: string | undefined,
): void
```

**Parameters**

- `store` (`McpCredentialStore`): Credential store.
- `name` (`string`): Server name.
- `secret` (`string | undefined`): Secret to store. An empty or `undefined` value removes it.

Source: [src/mcp/oauth-provider.ts:437](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L437)

### `sectionDigest`

Function.

Short stable digest of a section's text.

```ts
function sectionDigest(text: string): string
```

**Parameters**

- `text` (`string`): Section text.

**Returns** `string`

Source: [src/system-freeze.ts:36](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L36)

### `sectionDigests`

Function.

Digest of every section present, by section kind.

```ts
function sectionDigests(
  sections: Readonly<Record<string, string | undefined>>,
): Record<string, string>
```

**Parameters**

- `sections` (`Readonly<Record<string, string | undefined>>`): Section texts by kind; `undefined` entries are skipped.

**Returns** `Record<string, string>`

Source: [src/system-freeze.ts:45](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L45)

### `selectFilesFromReadState`

Function.

Convert a raw read-state map into a deduped, path-ranked list ready for
restoration. Multiple entries for the same path (different
`(offset, limit, maxBytes)` slices) collapse to one — keeping the most
recent `mtimeMs`.

Keys are the absolute paths `readStateKey` writes, and paths come back
absolute, so every execution context reads them the same way. Entries
outside `cwd` are dropped: they belong to another workspace.

Pure. Most callers want [`selectFilesFromSession`](https://zidane.si/docs/reference/index.md#selectFilesFromSession), which wraps
`getReadState(session)` + this function in one call so the host
doesn't have to reach into the tools layer.

```ts
function selectFilesFromReadState(
  readState: ReadonlyMap<string, { mtimeMs: number }>,
  cwd: string,
): RecentFile[]
```

**Parameters**

- `readState` (`ReadonlyMap<string, { mtimeMs: number }>`): Read-state map keyed by absolute path, with a `mtimeMs` per entry.
- `cwd` (`string`): Working directory whose files to keep.

**Returns** `RecentFile[]`

Source: [src/compact/restore.ts:256](https://github.com/Tahul/zidane/blob/main/src/compact/restore.ts#L256)

### `selectFilesFromSession`

Function.

Session-aware convenience: extract recently-read files directly from
a [`Session`](https://zidane.si/docs/reference/session.md#Session) via its per-session read-state map.

Hosts (TUI / SDK consumers) typically have a `Session` and a `cwd`
(the active agent's `handle.cwd`) on hand — this wrapper saves them
from reaching into `src/tools/read-state.ts` directly. Returns an
empty list when no read state has been recorded yet (fresh session,
or `behavior.dedupReads === false`).

Equivalent to:

```ts
const state = getReadState(session)
return state ? selectFilesFromReadState(state, cwd) : []
```

```ts
function selectFilesFromSession(session: Session, cwd: string): RecentFile[]
```

**Parameters**

- `session` (`Session`): Session whose read state to use.
- `cwd` (`string`): Working directory whose entries to keep.

**Returns** `RecentFile[]`

Source: [src/compact/restore.ts:292](https://github.com/Tahul/zidane/blob/main/src/compact/restore.ts#L292)

### `selectRecentFiles`

Function.

Pick the top `maxFiles` from `files` (descending by `mtimeMs`),
dropping any whose path appears in `excludePaths`.

Stable for equal mtimes — files with the same timestamp retain their
input order. Pure.

```ts
function selectRecentFiles(
  files: readonly RecentFile[],
  opts: { excludePaths?: readonly string[]; maxFiles: number },
): RecentFile[]
```

**Parameters**

- `files` (`readonly RecentFile[]`): Candidate files.
- `opts` (`{ excludePaths?: readonly string[]; maxFiles: number }`): Selection options. `maxFiles` caps the result; `excludePaths` lists paths to drop.

**Returns** `RecentFile[]`

Source: [src/compact/restore.ts:309](https://github.com/Tahul/zidane/blob/main/src/compact/restore.ts#L309)

### `shouldAutoCompact`

Function.

Decide whether auto-compaction should fire for the latest turn.

Order of checks is deliberate: cheapest / most common skips first
(`disabled` is one boolean read; `unknown-window` is the predictable
miss for custom models), invariant violations next, then the actual
threshold math. `already-compacting` runs last so the diagnostic
surfaces correctly when the predicate is called inside an existing
compaction window.

```ts
function shouldAutoCompact(input: AutoCompactInput): AutoCompactDecision
```

**Parameters**

- `input` (`AutoCompactInput`): Current usage, window and settings. See [`AutoCompactInput`](https://zidane.si/docs/reference/index.md#AutoCompactInput).

**Returns** `AutoCompactDecision`

Source: [src/compact/policy.ts:133](https://github.com/Tahul/zidane/blob/main/src/compact/policy.ts#L133)

### `sliceForCompaction`

Function.

Partition `turns` into `(toSummarize, preserved)` according to `scope`.

Throws [`CompactInvalidInputError`](https://zidane.si/docs/reference/index.md#CompactInvalidInputError) on degenerate inputs so the
caller doesn't pay for a doomed provider call:

- empty `turns`
- `scope: 'tail'` with `keepTurns >= turns.length` (nothing to summarize)
- `scope: { from | up_to }` with an anchor id that isn't in `turns`
- the resulting `toSummarize` slice contains no text-bearing content
  (only system turns or empty content)

Pure. Returns references to the original `SessionTurn` objects — the
caller can compare by identity (=== Object.is) to confirm.

```ts
function sliceForCompaction(
  turns: readonly SessionTurn[],
  scope: CompactScope,
  keepTurns: number,
): CompactionSlice
```

**Parameters**

- `turns` (`readonly SessionTurn[]`): Conversation in chronological order.
- `scope` (`CompactScope`): Which part of the conversation to summarize.
- `keepTurns` (`number`): Trailing turns to keep when `scope` is `'tail'`. Negative values count as 0.

**Returns** `CompactionSlice`

Source: [src/compact/messages.ts:58](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L58)

### `sqliteStoreFile`

Function.

The database file a store from [`createSqliteSessionStore`](https://zidane.si/docs/reference/index.md#createSqliteSessionStore) (or a
wrapper that called `adoptSqliteStoreFile`) works on; `undefined`
for any other store and for an in-memory database.

```ts
function sqliteStoreFile(store: SessionStore): SqliteStoreFile | undefined
```

**Parameters**

- `store` (`SessionStore`): Any session store.

**Returns** `SqliteStoreFile | undefined`

Source: [src/session/sqlite-store.ts:63](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-store.ts#L63)

### `stableStringify`

Function.

Deterministic JSON with sorted keys so key order doesn't split a streak.

```ts
function stableStringify(value: unknown): string
```

**Parameters**

- `value` (`unknown`): Value to encode. Object keys are sorted at every level.

**Returns** `string`

Source: [src/behaviors/repeat-guard.ts:206](https://github.com/Tahul/zidane/blob/main/src/behaviors/repeat-guard.ts#L206)

### `stagedToolState`

Function.

Resolve the staging handle behind a view. Returns `undefined` for a
missing view or a foreign implementation (a host that supplied its own
`ToolStateView`), which lets adapters degrade to "no durable staging"
instead of throwing.

```ts
function stagedToolState(view: ToolStateView | undefined): StagedToolState | undefined
```

**Parameters**

- `view` (`ToolStateView | undefined`): View handed to a tool, or `undefined`.

**Returns** `StagedToolState | undefined`

Source: [src/tool-state.ts:205](https://github.com/Tahul/zidane/blob/main/src/tool-state.ts#L205)

### `startOAuthCallback`

Function.

Start a one-shot OAuth callback server. The returned handle's `redirectUri`
should be passed to the authorization server as the `redirect_uri` query
parameter; `promise` resolves once the user finishes the browser flow.

Always `await handle.close()` in a `finally` block — even on success, the
server stays open until told to shut down (so it can serve the
"you can close this tab" page).

```ts
function startOAuthCallback(opts?: OAuthCallbackOptions): Promise<OAuthCallbackHandle>
```

**Parameters**

- `opts?` (`OAuthCallbackOptions`, default `{}`): Callback server settings. See [`OAuthCallbackOptions`](https://zidane.si/docs/reference/index.md#OAuthCallbackOptions).

**Returns** `Promise<OAuthCallbackHandle>`

Source: [src/mcp/oauth-callback.ts:127](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-callback.ts#L127)

### `stripImagesFromTurns`

Function.

Replace every attachment block in `turns` with a short text marker
(`[image]`, `[audio]`, `[video]` or `[document]`).

Covers two shapes:

- Top-level image, audio, video and document content blocks.
- The same block types inside `tool_result.output` array form
  (multimodal tool results — e.g. an MCP browser screenshot).

Unconditional by design: even on vision-capable models, the summary
call doesn't benefit from raw image bytes (the model can't refer to
them after the summary lands), and stripping uniformly avoids
`prompt_too_long` on image-heavy sessions.

Returns a fresh array; input turns / blocks are never mutated.

```ts
function stripImagesFromTurns(turns: readonly SessionTurn[]): SessionTurn[]
```

**Parameters**

- `turns` (`readonly SessionTurn[]`): Turns to flatten.

**Returns** `SessionTurn[]`

Source: [src/compact/messages.ts:135](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L135)

### `summaryToTurn`

Function.

Build a synthetic `SessionTurn` carrying a single `compact-summary`
block, ready to append to a session.

The turn's role is `'user'` so it sits at a conversational boundary
the way the model expects. The caller is responsible for
`session.appendTurns([turn])`. The id defaults to `crypto.randomUUID()`
(override via `input.id` for durable-execution replay stability).

Typical use after running `compactConversation`:

```ts
const result = await compactConversation({ provider, turns })
const turn = summaryToTurn({
  summary: result.summary,
  replacesTurnIds: result.summarizedTurnIds,
  model: result.model,
  usage: result.usage,
})
await session.appendTurns([turn])
```

```ts
function summaryToTurn(input: SummaryToTurnInput): SessionTurn
```

**Parameters**

- `input` (`SummaryToTurnInput`): Summary text, replaced turn ids, model, usage and optional id and timestamp.

**Returns** `SessionTurn`

Source: [src/compact/messages.ts:466](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L466)

### `systemSnapshotTurn`

Function.

The out-of-band `role: 'system'` turn recording a frozen prompt, or
clearing the one recorded for `key` (every key when omitted).

```ts
function systemSnapshotTurn(
  input: { createdAt: number; id: string } & ({ cleared: true; key?: string } | { snapshot: Omit<SystemPromptSnapshot, 'v' | 'cleared'>; system: string }),
): SessionTurn
```

**Parameters**

- `input` (`{ createdAt: number; id: string } & ({ cleared: true; key?: string } | { snapshot: Omit<SystemPromptSnapshot, 'v' | 'cleared'>; system: string })`): Turn id and time, plus the prompt and its snapshot, or `cleared` with an optional key.

**Returns** `SessionTurn`

Source: [src/system-freeze.ts:60](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L60)

### `treeProcesses`

Function.

One row per OS process of the tree, in the tree's order (`listed` ones left out).

```ts
function treeProcesses(input: TreeInput): PerfProcess[]
```

**Parameters**

- `input` (`TreeInput`): The tree, its roots and hosts, what Zidane owns and the CPU memory.

**Returns** `PerfProcess[]`: The processes.

Source: [src/perf/processes.ts:71](https://github.com/Tahul/zidane/blob/main/src/perf/processes.ts#L71)

### `truncateHeadForPtlRetry`

Function.

Shrink `turns` for a `prompt_too_long` retry and return a fresh array.

Drops whole rounds from the head until the remaining slice is at most
HALF the byte size of the input (always dropping at least one round).
Halving is the load-bearing property: the retry budget is small (3 by
default), so shrinkage must be geometric, not linear. Dropping a single
round per retry would never converge on a very long session where each
round is a rounding error against the overflow, and compaction would fail
with `prompt_too_long after 3 retries` even though a smaller prompt would
have succeeded.

A round is a contiguous `[user, assistant?, tool_results?]` group.

Adjacency-safe: only whole rounds are dropped, so the result still
respects every provider's `tool_use ↔ tool_result` adjacency rule.

Returns `turns` unchanged when only one round (or less) remains — the
caller is expected to interpret that as "cannot shrink further" and
give up the retry loop.

```ts
function truncateHeadForPtlRetry(turns: readonly SessionTurn[]): SessionTurn[]
```

**Parameters**

- `turns` (`readonly SessionTurn[]`): Turns of the failed attempt, oldest first.

**Returns** `SessionTurn[]`

Source: [src/compact/messages.ts:232](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L232)

### `usageAssistantDaily`

Function.

Usage per local day × model.

```ts
function usageAssistantDaily(database: UsageDatabase): UsageAssistantDayRow[]
```

**Parameters**

- `database` (`UsageDatabase`): A connection to a sessions database.

**Returns** `UsageAssistantDayRow[]`

Source: [src/session/sqlite-usage.ts:99](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L99)

### `usageSessionDaily`

Function.

Sessions created per local day.

```ts
function usageSessionDaily(database: UsageDatabase): UsageSessionDayRow[]
```

**Parameters**

- `database` (`UsageDatabase`): A connection to a sessions database.

**Returns** `UsageSessionDayRow[]`

Source: [src/session/sqlite-usage.ts:184](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L184)

### `usageUserDaily`

Function.

Human messages per local day × hour.

```ts
function usageUserDaily(database: UsageDatabase): UsageUserDayRow[]
```

**Parameters**

- `database` (`UsageDatabase`): A connection to a sessions database.

**Returns** `UsageUserDayRow[]`

Source: [src/session/sqlite-usage.ts:162](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L162)

### `utf8ByteLength`

Function.

UTF-8 byte length, matching `Buffer.byteLength(text, 'utf-8')` for
well-formed strings but without pulling `node:buffer` for a one-liner. A
high+low surrogate pair counts as a single 4-byte sequence (not 2 × 3-byte).
A lone surrogate is not handled like `Buffer` does. Cheap to call in hot loops.

Pure. Identical bytes for identical input across every JS runtime.

```ts
function utf8ByteLength(text: string): number
```

**Parameters**

- `text` (`string`): String to measure.

**Returns** `number`

Source: [src/compact/utils.ts:22](https://github.com/Tahul/zidane/blob/main/src/compact/utils.ts#L22)

### `validateExtensionName`

Function.

Why a proposed extension name is refused, or `null` when it is fine.

```ts
function validateExtensionName(name: string): string | null
```

**Parameters**

- `name` (`string`): The name as typed (trimmed here).

**Returns** `string | null`

Source: [src/extension-authoring.ts:335](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L335)

### `withZidaneExtensionSkill`

Function.

Inject the `zidane-extension` skill into an already-merged [`SkillsConfig`](https://zidane.si/docs/reference/skills.md#SkillsConfig).

Call this on the FINAL merged skills object (after folding extension / preset
skills): `composePresets` is last-wins on `catalog`, so injecting earlier
would be silently dropped whenever an extension also contributes skills.

Adds the skill to the catalog and, when an `enabled` allowlist is in force,
force-includes the name so the allowlist filter can't hide it (mirrors how
extension-contributed skill names are force-included). When skills are fully
disabled (`enabled === false`), the edit session still gets just this skill.

```ts
function withZidaneExtensionSkill(
  skills: SkillsConfig,
  opts?: { cwd?: string },
): SkillsConfig
```

**Parameters**

- `skills` (`SkillsConfig`): Merged skills configuration to extend.
- `opts?` (`{ cwd?: string }`, default `{}`): Options. `cwd` is the directory used to locate the shipped docs. Defaults to `process.cwd()`.

**Returns** `SkillsConfig`

Source: [src/extension-authoring.ts:822](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L822)

### `withZidaneSkillEditSkill`

Function.

Inject the skill-edit preset skill into an already-merged [`SkillsConfig`](https://zidane.si/docs/reference/skills.md#SkillsConfig).
Same contract as [`withZidaneExtensionSkill`](https://zidane.si/docs/reference/index.md#withZidaneExtensionSkill) — call on the FINAL merged
skills object.

```ts
function withZidaneSkillEditSkill(
  skills: SkillsConfig,
  marker: SkillEditMarker,
  opts?: { cwd?: string },
): SkillsConfig
```

**Parameters**

- `skills` (`SkillsConfig`): Merged skills configuration to extend.
- `marker` (`SkillEditMarker`): Marker naming the skill's directory and name.
- `opts?` (`{ cwd?: string }`, default `{}`): Options. `cwd` is the directory used to locate the shipped docs. Defaults to `process.cwd()`.

**Returns** `SkillsConfig`

Source: [src/extension-authoring.ts:894](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L894)

### `zodToJsonSchema`

Function.

Normalize a JSON Schema (e.g. from zod v4's z.toJSONSchema()) for use
as a ToolSpec.inputSchema.

Strips the $schema key that some providers reject.

```ts
function zodToJsonSchema(jsonSchema: Record<string, unknown>): Record<string, unknown>
```

**Parameters**

- `jsonSchema` (`Record<string, unknown>`): JSON Schema object, for example the output of `z.toJSONSchema()`.

**Returns** `Record<string, unknown>`

Source: [src/zod.ts:93](https://github.com/Tahul/zidane/blob/main/src/zod.ts#L93)

## Classes

### `AgentLengthResumeExhaustedError`

Class.

Thrown by the loop when consecutive `resumeOnMaxTokens` resumes keep
producing output-cap (`finishReason: 'length'`) turns with **no visible
text and no tool calls** — the degenerate reasoning spin: on providers
that don't accept prior reasoning back, each resume restarts reasoning
from scratch on a synthetic "Please continue.", burns the full output
budget, and makes zero progress. Unlike a text-producing truncation
(which keeps the generous internal resume bound and, on exhaustion,
still ends the run cleanly), this loop does not assemble an answer,
so it fails fast with a real error instead of silently "completing".

The run is finalized as `'error'` and the error re-throws so a caller's
`try`/`catch` can branch on `err instanceof AgentLengthResumeExhaustedError`
without string-sniffing.

```ts
class AgentLengthResumeExhaustedError extends Error
```

**Constructor**

```ts
new AgentLengthResumeExhaustedError(options: { consecutiveEmptyTurns: number })
```

Creates the error.

**Parameters**

- `options` (`{ consecutiveEmptyTurns: number }`): `consecutiveEmptyTurns` is the count of consecutive empty output-cap turns.

**Returns** `AgentLengthResumeExhaustedError`

**Properties**

- `code` (`'length_resume_exhausted'`, readonly): Stable error code, always `'length_resume_exhausted'`.
- `consecutiveEmptyTurns` (`number`, readonly): Consecutive output-cap turns that produced no visible text and no tool calls.

Source: [src/errors.ts:276](https://github.com/Tahul/zidane/blob/main/src/errors.ts#L276)

### `CompactInvalidInputError`

Class.

Raised when the caller's inputs make compaction meaningless before any
API call is attempted. Common cases:

- empty `turns`
- `keepTurns >= turns.length` (no older content to summarize)
- `'from'` / `'up_to'` anchor id not found in `turns`
- the resolved `toSummarize` slice has no text-bearing content

Synchronous — thrown from `compactConversation()` before the provider
call so the caller can recover without a network round-trip.

```ts
class CompactInvalidInputError extends Error
```

**Constructor**

```ts
new CompactInvalidInputError(message: string)
```

Creates the error.

**Parameters**

- `message` (`string`): Description of the invalid input.

**Returns** `CompactInvalidInputError`

Source: [src/compact/errors.ts:20](https://github.com/Tahul/zidane/blob/main/src/compact/errors.ts#L20)

### `CompactPromptTooLongError`

Class.

Raised when the provider rejects the compaction request with
`prompt_too_long` (or an equivalent) and the head-truncation retry
budget has been exhausted. Callers can inspect `ptlRetries` to log
how far the retry loop got before giving up.

```ts
class CompactPromptTooLongError extends Error
```

**Constructor**

```ts
new CompactPromptTooLongError(message: string, ptlRetries: number)
```

Creates the error.

**Parameters**

- `message` (`string`): Error message.
- `ptlRetries` (`number`): Number of head-truncation retries made before giving up.

**Returns** `CompactPromptTooLongError`

**Properties**

- `ptlRetries` (`number`, readonly): Number of head-truncation retries made before giving up.

Source: [src/compact/errors.ts:40](https://github.com/Tahul/zidane/blob/main/src/compact/errors.ts#L40)

### `DecisionError`

Class.

Thrown by `agent.decide(req, { throw: true })` when the decision failed.

```ts
class DecisionError extends Error
```

**Constructor**

```ts
new DecisionError(outcome: DecisionFailure)
```

Creates the error from a failed outcome.

**Parameters**

- `outcome` (`DecisionFailure`): The failed decision outcome. Its `message` becomes the error message and its `error`, if any, the cause.

**Returns** `DecisionError`

**Properties**

- `outcome` (`DecisionFailure`, readonly): The full failed outcome that caused this error.
- `reason` (`DecisionFailureReason`, readonly): Failure reason, copied from `outcome.reason`.

Source: [src/decisions/errors.ts:98](https://github.com/Tahul/zidane/blob/main/src/decisions/errors.ts#L98)

### `DecisionHttpError`

Class.

Non-2xx response from a decisions endpoint.

```ts
class DecisionHttpError extends Error
```

**Constructor**

```ts
new DecisionHttpError(status: number, message: string)
```

Creates the error with the response status.

**Parameters**

- `status` (`number`): HTTP status code of the response.
- `message` (`string`): Error message.

**Returns** `DecisionHttpError`

**Properties**

- `status` (`number`, readonly): HTTP status code of the non-2xx response.

Source: [src/decisions/errors.ts:13](https://github.com/Tahul/zidane/blob/main/src/decisions/errors.ts#L13)

### `DecisionInvalidResponseError`

Class.

The provider answered 2xx with a body that doesn't match the expected shape.

```ts
class DecisionInvalidResponseError extends Error
```

**Constructor**

```ts
new DecisionInvalidResponseError(message: string)
```

Creates the error.

**Parameters**

- `message` (`string`): Error message.

**Returns** `DecisionInvalidResponseError`

Source: [src/decisions/errors.ts:57](https://github.com/Tahul/zidane/blob/main/src/decisions/errors.ts#L57)

### `DecisionTimeoutError`

Class.

Abort reason of the decider's wall-clock cap.

```ts
class DecisionTimeoutError extends Error
```

**Constructor**

```ts
new DecisionTimeoutError(message: string)
```

Creates the error.

**Parameters**

- `message` (`string`): Error message.

**Returns** `DecisionTimeoutError`

Source: [src/decisions/errors.ts:73](https://github.com/Tahul/zidane/blob/main/src/decisions/errors.ts#L73)

### `DecisionUnsupportedError`

Class.

The input or questions can't be expressed on this provider's wire.

```ts
class DecisionUnsupportedError extends Error
```

**Constructor**

```ts
new DecisionUnsupportedError(message: string)
```

Creates the error.

**Parameters**

- `message` (`string`): Error message.

**Returns** `DecisionUnsupportedError`

Source: [src/decisions/errors.ts:41](https://github.com/Tahul/zidane/blob/main/src/decisions/errors.ts#L41)

### `McpOAuthProvider`

Class.

OAuth client provider for one MCP server. Persists tokens and registration in a [`McpCredentialStore`](https://zidane.si/docs/reference/index.md#McpCredentialStore) and never opens a browser by itself.

```ts
class McpOAuthProvider implements OAuthClientProvider
```

**Constructor**

```ts
new McpOAuthProvider(opts: McpOAuthProviderOptions)
```

Creates the provider.

**Parameters**

- `opts` (`McpOAuthProviderOptions`): Server name, store and optional callback and client settings.

**Returns** `McpOAuthProvider`

**Properties**

- `clientMetadata` (`{ client_name?: string; client_uri?: string; contacts?: string[]; grant_types?: string[]; jwks?: any; jwks_uri?: string; logo_uri?: string; policy_uri?: string; redirect_uris: string[]; response_types?: string[]; scope?: string; software_id?: string; software_statement?: string; software_version?: string; token_endpoint_auth_method?: string; tos_uri?: string }`, readonly): Metadata about this OAuth client.
- `redirectUrl` (`string | URL`, readonly): ALWAYS returns a URL — the placeholder in non-interactive mode — and
  that is load-bearing for token refresh. The SDK's `auth()` treats a
  provider without `redirectUrl` as a non-interactive GRANT flow
  (`client_credentials` / jwt-bearer): it routes into `fetchToken()`
  BEFORE the refresh-token branch, which throws for a PKCE public client
  (no `prepareTokenRequest`, no authorization code) — so a perfectly
  refreshable session surfaced as "auth required" and forced a manual
  re-login every time the access token expired. With the placeholder in
  place, `auth()` takes the authorization-code path: stored
  `refresh_token` → refresh → AUTHORIZED, no browser involved. When no
  refresh is possible it falls through to "start new authorization",
  whose redirect is a no-op here — the `UnauthorizedError` →
  `mcp:auth:required` signal.

**Methods**

#### `clientInformation()`

```ts
clientInformation(): OAuthClientInformationMixed | undefined
```

Loads information about this OAuth client, as registered already with the
server, or returns `undefined` if the client is not registered with the
server.

A provider that returns pre-registered credentials should include `issuer`, the URL of
the authorization server they were registered with; `auth` then does not
present them to any other.

**Returns** `OAuthClientInformationMixed | undefined`

#### `codeVerifier()`

```ts
codeVerifier(): string
```

Loads the PKCE code verifier for the current session, necessary to validate
the authorization result.

**Returns** `string`

#### `discoveryState()`

```ts
discoveryState(): OAuthDiscoveryState | undefined
```

Returns previously saved discovery state, or `undefined` if none is cached.

When available, `auth` restores the discovery state (authorization server
URL, resource metadata, etc.) instead of performing RFC 9728 discovery, reducing
latency on subsequent calls.

Providers should clear cached discovery state on repeated authentication failures
(via `invalidateCredentials` with scope `'discovery'` or `'all'`) to allow
re-discovery in case the authorization server has changed.

**Returns** `OAuthDiscoveryState | undefined`

#### `invalidateCredentials()`

```ts
invalidateCredentials(
  scope: 'client' | 'all' | 'tokens' | 'verifier' | 'discovery',
): Promise<void>
```

Wipe stored credentials when the server reports the cached state is no
longer valid. The SDK calls this with a scope hint:

- `'tokens'`  → access/refresh revoked, keep client registration
- `'client'`  → client registration invalidated, reset everything
- `'verifier'`→ PKCE state stale (e.g. mismatched state param)
- `'discovery'` → discovery metadata stale (servers re-keyed)
- `'all'`     → full reset

**Parameters**

- `scope` (`'client' | 'all' | 'tokens' | 'verifier' | 'discovery'`): Which part of the stored state to drop.

**Returns** `Promise<void>`

#### `redirectToAuthorization()`

```ts
redirectToAuthorization(url: URL): Promise<void>
```

Hands the authorization URL to `onAuthorizationUrl`. Does nothing when no handler is set.

**Parameters**

- `url` (`URL`): Authorization URL the user must visit.

**Returns** `Promise<void>`

#### `saveClientInformation()`

```ts
saveClientInformation(info: OAuthClientInformationMixed): void
```

Stores the dynamically registered client. Ignored when a static client is set.

**Parameters**

- `info` (`OAuthClientInformationMixed`): Client information returned by registration.

#### `saveCodeVerifier()`

```ts
saveCodeVerifier(verifier: string): void
```

Keeps the PKCE code verifier in memory for the pending authorization.

**Parameters**

- `verifier` (`string`): PKCE code verifier.

#### `saveDiscoveryState()`

```ts
saveDiscoveryState(state: OAuthDiscoveryState): void
```

Stores the discovery state for this server.

**Parameters**

- `state` (`OAuthDiscoveryState`): Discovery state to cache.

#### `saveTokens()`

```ts
saveTokens(
  tokens: { access_token: string; expires_in?: number; id_token?: string; issuer?: string; refresh_token?: string; scope?: string; token_type: string },
): void
```

Stores the tokens for this server.

**Parameters**

- `tokens` (`{ access_token: string; expires_in?: number; id_token?: string; issuer?: string; refresh_token?: string; scope?: string; token_type: string }`): Tokens to store.

#### `state()`

```ts
state(): string
```

The configured `state` (the SDK sends nothing when it is empty).

**Returns** `string`

#### `tokens()`

```ts
tokens(): { access_token: string; expires_in?: number; id_token?: string; issuer?: string; refresh_token?: string; scope?: string; token_type: string } | undefined
```

Loads any existing OAuth tokens for the current session, or returns
`undefined` if there are no saved tokens.

**Returns** `{ access_token: string; expires_in?: number; id_token?: string; issuer?: string; refresh_token?: string; scope?: string; token_type: string } | undefined`

Source: [src/mcp/oauth-provider.ts:181](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L181)

### `PerfProcessNotFoundError`

Class.

`perf.threads` asked for a process the host doesn't list.

```ts
class PerfProcessNotFoundError extends Error
```

**Constructor**

```ts
new PerfProcessNotFoundError(pid: number)
```

**Parameters**

- `pid` (`number`): The process asked for.

**Returns** `PerfProcessNotFoundError`

**Properties**

- `pid` (`number`, readonly): The process asked for.

Source: [src/perf/host.ts:48](https://github.com/Tahul/zidane/blob/main/src/perf/host.ts#L48)

## Constants

### `ANCHOR_PREVIEW_MAX_CHARS`

Constant.

Maximum length of an anchor turn's textual preview, in characters. Long
enough to give the model recognizable context (the first paragraph of
a typical user message), short enough that it doesn't blow the
cache-stability invariant for the prompt prefix.

```ts
const ANCHOR_PREVIEW_MAX_CHARS = 200
```

Source: [src/compact/messages.ts:394](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L394)

### `AUTO_COMPACT_MIN_GROWTH_FRACTION`

Constant.

Hysteresis floor that chat hosts pass as `minGrowthFraction` to
[`shouldAutoCompact`](https://zidane.si/docs/reference/index.md#shouldAutoCompact), which itself applies no floor when the input is
omitted. After a successful
compaction lands, the next compaction is suppressed until input usage
grows by at least this fraction of the effective context window beyond
the post-compact baseline.

`0.1` = 10% of the window. Picked so the immediate post-compact bounce
(summary turn + restored attachments + re-emitted system prefix) never
re-fires the trigger by itself, but a meaningful chunk of new work
(one or two large tool reads) does. Tune via the predicate's
`minGrowthFraction` input if a host needs different ergonomics.

```ts
const AUTO_COMPACT_MIN_GROWTH_FRACTION = 0.1
```

Source: [src/compact/policy.ts:54](https://github.com/Tahul/zidane/blob/main/src/compact/policy.ts#L54)

### `BASE_INSTRUCTIONS`

Constant.

Body shared by every direction. Lays out the 9-section scaffold,
mirrors Claude Code's `BASE_COMPACT_PROMPT` so a model already trained
on the layout produces the same shape.

```ts
const BASE_INSTRUCTIONS = ...
```

Source: [src/compact/prompt.ts:63](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L63)

### `buildCompactPrompt`

Constant.

Default public builder. Dispatches by direction to the four named
builders. Throws when `from` / `up_to` are passed without an
`anchorPreview` — those scopes only make sense with an anchor and a
silent fallback would produce a prompt that doesn't tell the model
where the slice begins.

```ts
const buildCompactPrompt: CompactPromptBuilder
```

Source: [src/compact/prompt.ts:204](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L204)

### `BYTES_PER_TOKEN`

Constant.

Same constant Claude Code's `CONTEXT_MANAGEMENT.md` documents.

```ts
const BYTES_PER_TOKEN = 4
```

Source: [src/compact/utils.ts:46](https://github.com/Tahul/zidane/blob/main/src/compact/utils.ts#L46)

### `DEFAULT_DECISION_TIMEOUT_MS`

Constant.

Default wall-clock cap for one decision, in milliseconds.

```ts
const DEFAULT_DECISION_TIMEOUT_MS = 5000
```

Source: [src/decisions/index.ts:38](https://github.com/Tahul/zidane/blob/main/src/decisions/index.ts#L38)

### `DEFAULT_MAX_VALUE_BYTES`

Constant.

Default per-value size budget: 64 KiB of JSON.

Deliberately far below any backend's hard ceiling (journal-entry limits
run to tens of MiB) because this is a design guard, not a protocol limit.
Durable tool state is for flags, ids, counters, and cursors; a value that
doesn't fit in 64 KiB is a payload, and payloads belong in the tool result
or in storage the tool owns. Raise it on the store if you disagree — but
know that everything here is rewritten on every commit.

```ts
const DEFAULT_MAX_VALUE_BYTES: number
```

Source: [src/tool-state.ts:130](https://github.com/Tahul/zidane/blob/main/src/tool-state.ts#L130)

### `EXTENSION_EDIT_METADATA_KEY`

Constant.

Session-metadata key marking an "edit / create extension" session. The value
is an [`ExtensionEditMarker`](https://zidane.si/docs/reference/index.md#ExtensionEditMarker). Both hosts stamp it at session creation so
the agent build can scope the docs skill to exactly these sessions (and it
survives reload because metadata is persisted).

```ts
const EXTENSION_EDIT_METADATA_KEY = 'zidane.extensionEdit'
```

Source: [src/extension-authoring.ts:40](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L40)

### `FROZEN_PROMPT_SECTION_KINDS`

Constant.

The SDK-appended sections, in announcement order.

```ts
const FROZEN_PROMPT_SECTION_KINDS: readonly ['skills', 'tools', 'mcp']
```

Source: [src/system-freeze.ts:29](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L29)

### `GEN_AI_ATTRIBUTES`

Constant.

OpenTelemetry Gen AI semantic-convention attribute keys used by the
built-in tracer. Exported so consumers integrating with raw OTel SDKs
(instead of going through `createTracingHooks`) can stay aligned with
the names the harness itself emits.

```ts
const GEN_AI_ATTRIBUTES: { readonly agentDepth: 'gen_ai.agent.depth'; readonly agentName: 'gen_ai.agent.name'; readonly agentParentRunId: 'gen_ai.agent.parent_run.id'; readonly agentRunId: 'gen_ai.agent.run.id'; readonly costInputTokens: 'gen_ai.cost.input_tokens'; readonly costOutputTokens: 'gen_ai.cost.output_tokens'; readonly costTotalTokens: 'gen_ai.cost.total_tokens'; readonly inputMessages: 'gen_ai.input.messages'; readonly inputMessagesDropped: 'gen_ai.agent.input_messages_dropped'; readonly mcpServer: 'gen_ai.mcp.server'; readonly mcpToolCount: 'gen_ai.mcp.tool_count'; readonly operationName: 'gen_ai.operation.name'; readonly outputMessages: 'gen_ai.output.messages'; readonly pipelineName: 'gen_ai.pipeline.name'; readonly requestFrequencyPenalty: 'gen_ai.request.frequency_penalty'; readonly requestMaxTokens: 'gen_ai.request.max_tokens'; readonly requestModel: 'gen_ai.request.model'; readonly requestPresencePenalty: 'gen_ai.request.presence_penalty'; readonly requestSeed: 'gen_ai.request.seed'; readonly requestTemperature: 'gen_ai.request.temperature'; readonly requestTopK: 'gen_ai.request.top_k'; readonly requestTopP: 'gen_ai.request.top_p'; readonly responseFinishReasons: 'gen_ai.response.finish_reasons'; readonly responseId: 'gen_ai.response.id'; readonly responseModel: 'gen_ai.response.model'; readonly responseStreaming: 'gen_ai.response.streaming'; readonly responseTimeToFirstTokenMs: 'gen_ai.client.time_to_first_token'; readonly responseTimeToFirstTokenSeconds: 'gen_ai.response.time_to_first_token'; readonly responseTokensPerSecond: 'gen_ai.response.tokens_per_second'; readonly system: 'gen_ai.system'; readonly systemInstructions: 'gen_ai.system_instructions'; readonly toolCallArguments: 'gen_ai.tool.call.arguments'; readonly toolCallId: 'gen_ai.tool.call.id'; readonly toolCallResult: 'gen_ai.tool.call.result'; readonly toolDefinitions: 'gen_ai.tool.definitions'; readonly toolDescription: 'gen_ai.tool.description'; readonly toolInputDeprecated: 'gen_ai.tool.input'; readonly toolMessage: 'gen_ai.tool.message'; readonly toolName: 'gen_ai.tool.name'; readonly toolOutputDeprecated: 'gen_ai.tool.output'; readonly toolType: 'gen_ai.tool.type'; readonly turn: 'gen_ai.agent.turn'; readonly usageCacheCreationInputTokens: 'gen_ai.usage.cache_creation_input_tokens'; readonly usageCacheReadInputTokens: 'gen_ai.usage.cache_read_input_tokens'; readonly usageCostUsd: 'gen_ai.usage.cost_usd'; readonly usageInputTokens: 'gen_ai.usage.input_tokens'; readonly usageInputTokensCached: 'gen_ai.usage.input_tokens.cached'; readonly usageInputTokensCacheWrite: 'gen_ai.usage.input_tokens.cache_write'; readonly usageOutputTokens: 'gen_ai.usage.output_tokens'; readonly usageOutputTokensReasoning: 'gen_ai.usage.output_tokens.reasoning'; readonly usageReasoningTokens: 'gen_ai.usage.reasoning_tokens'; readonly usageTotalTokens: 'gen_ai.usage.total_tokens' }
```

Source: [src/tracing.ts:325](https://github.com/Tahul/zidane/blob/main/src/tracing.ts#L325)

### `INTERRUPT_MESSAGE_FOR_TOOL_USE`

Constant.

Canonical tool_result text emitted when a tool call is interrupted by the
user mid-flight (Esc / Ctrl-C / external `AbortSignal`). Mirrors Claude
Code's `INTERRUPT_MESSAGE_FOR_TOOL_USE` so downstream consumers can pattern
match a single string across both harnesses. Always paired with
`isError: true` on the wire — the model treats it as a failed call rather
than a successful tool response.

```ts
const INTERRUPT_MESSAGE_FOR_TOOL_USE = '[Request interrupted by user for tool use]'
```

Source: [src/loop-tool-dispatch.ts:44](https://github.com/Tahul/zidane/blob/main/src/loop-tool-dispatch.ts#L44)

### `NO_TOOLS_PREAMBLE`

Constant.

No-tools guard. The runner sends `tools: []` to the provider already,
but some models still hallucinate tool-call intent on a long
conversation. The prose guard is cheap insurance.

```ts
const NO_TOOLS_PREAMBLE = ...
```

Source: [src/compact/prompt.ts:51](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L51)

### `ORPHANED_TOOL_RESULT_MARKER`

Constant.

Replacement text for a user message whose every content block was a
`tool_result` with no matching upstream `tool_call` (e.g. the assistant
pair was stripped by an earlier compaction). Same role as
[`TOOL_USE_INTERRUPTED_MARKER`](https://zidane.si/docs/reference/index.md#TOOL_USE_INTERRUPTED_MARKER) on the user side.

```ts
const ORPHANED_TOOL_RESULT_MARKER = '[Orphaned tool result removed due to conversation resume]'
```

Source: [src/session/messages-pairing.ts:39](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L39)

### `OUTPUT_RESERVE_TOKENS`

Constant.

Reserved output budget subtracted from the raw context window when
computing the effective ceiling for compaction / warning thresholds.

Aligned with Claude Code's `COMPACT_MAX_OUTPUT_TOKENS = 20_000` — covers
p99.99 of summary + response output. A turn that consumed N input tokens
leaves `effectiveWindow - N` headroom for the next prompt's response; once
headroom shrinks below the threshold, auto-compaction fires.

```ts
const OUTPUT_RESERVE_TOKENS = 20_000
```

Source: [src/compact/policy.ts:22](https://github.com/Tahul/zidane/blob/main/src/compact/policy.ts#L22)

### `ownCommands`

Constant.

The monitor's own commands (`ps` lists itself, and `ioreg` when it runs
alongside): not the host's. Held until a collector clears them at the start
of its next tick, since `ps` has exited by the time its output is parsed.

```ts
const ownCommands: Set<number>
```

Source: [src/perf/ps.ts:151](https://github.com/Tahul/zidane/blob/main/src/perf/ps.ts#L151)

### `PERSISTED_STUB_PREFIX`

Constant.

Byte-stable prefix every [`buildPersistedStub`](https://zidane.si/docs/reference/index.md#buildPersistedStub) output starts with.
Exported so wire-level passes (tail compaction) can recognize a persisted stub and preserve its path attribute
rather than replacing the stub with their own — losing the pointer to
the on-disk blob.

Bound to the literal opening of the XML tag; changing the stub format
requires updating this constant in lockstep (and shipping a migration
for in-flight sessions).

```ts
const PERSISTED_STUB_PREFIX = '<persisted-output tool="'
```

Source: [src/loop-persistence.ts:88](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L88)

### `PERSISTENCE_PREVIEW_BYTES`

Constant.

Bytes of head content included in the inline preview block. 2 KiB matches
Claude Code's `PREVIEW_SIZE_BYTES` — enough for the model to identify the
content class (error output / structured data / log shape) and decide
whether to call `read_file` on the persisted path for the full payload.

Tail-priority preview (matching `shell`'s truncation strategy) was
considered but rejected: most "what is this?" decisions get made from
the head, and the path is in the stub for the rare case where the tail
matters.

```ts
const PERSISTENCE_PREVIEW_BYTES: number
```

Source: [src/loop-persistence.ts:67](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L67)

### `SAMPLE_CAPACITY`

Constant.

Samples kept: 5 minutes at [`SAMPLE_INTERVAL_MS`](https://zidane.si/docs/reference/index.md#SAMPLE_INTERVAL_MS).

```ts
const SAMPLE_CAPACITY = 150
```

Source: [src/perf/sampler.ts:45](https://github.com/Tahul/zidane/blob/main/src/perf/sampler.ts#L45)

### `SAMPLE_INTERVAL_MS`

Constant.

Between two samples, ms.

```ts
const SAMPLE_INTERVAL_MS = 2_000
```

Source: [src/perf/sampler.ts:43](https://github.com/Tahul/zidane/blob/main/src/perf/sampler.ts#L43)

### `SHELL_CASCADE_CANCEL_MESSAGE`

Constant.

Canonical `tool_result.content` text emitted to siblings that were
cancelled by a `shell` error in the same batch. Distinct from
[`INTERRUPT_MESSAGE_FOR_TOOL_USE`](https://zidane.si/docs/reference/index.md#INTERRUPT_MESSAGE_FOR_TOOL_USE) (user-issued abort) and
[`TOOL_USE_SKIPPED_MESSAGE`](https://zidane.si/docs/reference/index.md#TOOL_USE_SKIPPED_MESSAGE) (steered) so consumers can split
the three causes by string-match.

```ts
const SHELL_CASCADE_CANCEL_MESSAGE: 'Cancelled: a sibling `shell` call in the same batch errored; re-run independently if still needed.'
```

Source: [src/loop-tool-dispatch.ts:79](https://github.com/Tahul/zidane/blob/main/src/loop-tool-dispatch.ts#L79)

### `SKILL_EDIT_METADATA_KEY`

Constant.

Session-metadata key marking an "edit skill" session — the skill-editing
counterpart of [`EXTENSION_EDIT_METADATA_KEY`](https://zidane.si/docs/reference/index.md#EXTENSION_EDIT_METADATA_KEY). The value is a
[`SkillEditMarker`](https://zidane.si/docs/reference/index.md#SkillEditMarker). Stamped at session creation by both hosts (via
[`editSessionMetadata`](https://zidane.si/docs/reference/index.md#editSessionMetadata)); persisted metadata means it survives reload.

```ts
const SKILL_EDIT_METADATA_KEY = 'zidane.skillEdit'
```

Source: [src/extension-authoring.ts:51](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L51)

### `SYNTHETIC_TOOL_RESULT_PLACEHOLDER`

Constant.

Placeholder content inserted into a synthetic `tool_result` when the harness
has to repair an orphan `tool_use`. Exported so downstream consumers
(training-data collectors, HFI submission) can reject any payload containing
it — the marker satisfies the wire-level pairing contract structurally but
the content itself is fake and would poison fine-tuning data.

```ts
const SYNTHETIC_TOOL_RESULT_PLACEHOLDER = '[Tool result missing due to internal error]'
```

Source: [src/session/messages-pairing.ts:22](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L22)

### `TOOL_USE_CANCELLED_MESSAGE`

Constant.

Canonical tool_result text emitted when a single tool call is cancelled
mid-flight via `agent.cancelTool(callId)` (typically the TUI's
"cancel this tool" affordance). Distinguished from
[`INTERRUPT_MESSAGE_FOR_TOOL_USE`](https://zidane.si/docs/reference/index.md#INTERRUPT_MESSAGE_FOR_TOOL_USE) (run-wide user abort) and
[`TOOL_USE_SKIPPED_MESSAGE`](https://zidane.si/docs/reference/index.md#TOOL_USE_SKIPPED_MESSAGE) (steered) so the model — and downstream
consumers — can tell the three apart by string match.

Always paired with `isError: true` on the wire so the model treats the
call as failed rather than as a successful response. The remaining tool
calls in the batch continue running, in contrast with a full-run abort.

```ts
const TOOL_USE_CANCELLED_MESSAGE = '[Tool call cancelled by user]'
```

Source: [src/loop-tool-dispatch.ts:67](https://github.com/Tahul/zidane/blob/main/src/loop-tool-dispatch.ts#L67)

### `TOOL_USE_INTERRUPTED_MARKER`

Constant.

Replacement text for an assistant message whose every content block was
stripped during pairing repair (e.g. the only blocks were orphan
`tool_call`s). Providers reject empty `content` arrays — the marker keeps
the turn shape valid while signaling "this assistant turn lost its
outputs" to the model so it can recover.

```ts
const TOOL_USE_INTERRUPTED_MARKER = '[Tool use interrupted]'
```

Source: [src/session/messages-pairing.ts:31](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L31)

### `TOOL_USE_SKIPPED_MESSAGE`

Constant.

Canonical tool_result text emitted when a tool call is skipped because a
steering message arrived between dispatches inside
`executeToolBatch`. Distinguished from
[`INTERRUPT_MESSAGE_FOR_TOOL_USE`](https://zidane.si/docs/reference/index.md#INTERRUPT_MESSAGE_FOR_TOOL_USE) so consumers can split "user
cancelled" from "framework superseded".

```ts
const TOOL_USE_SKIPPED_MESSAGE = '[Tool use skipped — superseded by user message]'
```

Source: [src/loop-tool-dispatch.ts:53](https://github.com/Tahul/zidane/blob/main/src/loop-tool-dispatch.ts#L53)

### `TRAILER`

Constant.

Trailer prompting the model to begin. Same on every direction.

```ts
const TRAILER = 'Provide your <analysis> and <summary> now.'
```

Source: [src/compact/prompt.ts:92](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L92)

### `ZIDANE_EXTENSION_SKILL_NAME`

Constant.

Name of the inline docs skill auto-activated in extension edit sessions.

```ts
const ZIDANE_EXTENSION_SKILL_NAME = 'zidane-extension'
```

Source: [src/extension-authoring.ts:43](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L43)

### `ZIDANE_SKILL_EDIT_SKILL_NAME`

Constant.

Name of the inline preset skill auto-activated in skill edit sessions.

```ts
const ZIDANE_SKILL_EDIT_SKILL_NAME = 'zidane-skill'
```

Source: [src/extension-authoring.ts:54](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L54)

## Interfaces

### `AgentCacheChange`

Interface.

A change a host is about to make, passed to `Agent.cacheImpact`.

```ts
interface AgentCacheChange
```

**Properties**

- `model?` (`string`): Model id the next request will use. Counts as a change when it differs from the last request's.
- `system?` (`boolean`): `true` when the host will change the system prompt.
- `thinking?` (`'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'adaptive'`): Thinking level the next request will use. Counts as a change when it differs from the last request's.
- `tools?` (`boolean`): `true` when the host will change the tool list.

Source: [src/agent-types.ts:460](https://github.com/Tahul/zidane/blob/main/src/agent-types.ts#L460)

### `AgentCacheImpact`

Interface.

What a change would cost the prompt cache, from `Agent.cacheImpact`.

```ts
interface AgentCacheImpact
```

**Properties**

- `expired` (`boolean`): The cache is already estimated expired (see `Agent.cacheExpiresAt`),
  or no request was sent yet: the next request reads the prompt again
  whether or not the change happens. `tokens` is still reported.
- `reasons` (`('system' | 'tools' | 'thinking' | 'model')[]`): Parts of the change that differ from the last request. Empty when nothing differs.
- `tokens` (`number`): Prompt tokens the next request would read again instead of from the
  cache: the last request's full prompt (`input + cacheRead + cacheCreation`
  of the last assistant turn). `0` when `reasons` is empty.

Source: [src/agent-types.ts:472](https://github.com/Tahul/zidane/blob/main/src/agent-types.ts#L472)

### `AgentCompactOptions`

Interface.

Options for `Agent.compact`.

```ts
interface AgentCompactOptions
```

**Properties**

- `keepTurns?` (`number`): Recent turns kept word for word after the summary. Defaults to
  `behavior.autoCompact.keepTurns`, then `behavior.compactKeepTurns`, then 4.
- `model?` (`string`): Model that writes the summary. Defaults to the model the last run ended
  on, or the provider's default model when the agent has not run yet. A
  model other than the last run's can't reuse its cached request.
- `signal?` (`AbortSignal`): Cancels the compaction. `agent.abort()` cancels it too.

Source: [src/agent-types.ts:412](https://github.com/Tahul/zidane/blob/main/src/agent-types.ts#L412)

### `AutoCompactConfig`

Interface.

Loop-native auto-compaction config (`AgentBehavior.autoCompact`).

Distinct from `compactStrategy` (wire-only tail elision of `tool_result`
text). Auto-compaction is the heavy lever: when the last turn's input
usage crosses `AutoCompactConfig.threshold` of the effective context
window, the loop runs a real LLM summary (`compactConversation`) over the
older turns, appends a `compact-summary` marker + restoration turns to the
session mid-run, and the next turn's wire view is the summary plus the
preserved tail. It mutates the session (durable summary turn), whereas
`compactStrategy` never touches `session.turns`.

The two compose: `compactStrategy: 'tail'` trims tool-output bytes every
turn; `autoCompact` summarizes the narrative when the window fills.

```ts
interface AutoCompactConfig
```

**Properties**

- `contextWindow?` (`number`): Raw model context window in tokens. The SDK core has no model catalog,
  so when omitted it falls back to `provider.meta.contextWindow` (a
  number, if the provider advertises one). When neither resolves, the
  trigger is inert — it can't compute a usage ratio. Chat hosts inject
  the picked model's window here from their catalog.
- `keepTurns?` (`number`): Trailing turns kept verbatim (passed to `compactConversation` as
  `scope: 'tail'` `keepTurns`). Defaults to `compactKeepTurns` when set,
  else `4`.
- `maxFailures?` (`number`): Consecutive-failure circuit breaker. After this many failed compaction
  attempts in a single run, the loop stops trying for the rest of the run
  (the reactive `context_exceeded` net still protects overflow). A
  successful compaction resets the counter. Default: `2`.
- `minGrowthFraction?` (`number`): Hysteresis floor — minimum fraction of the window that must be consumed
  by NEW content after a compaction before another can fire, so the
  post-compact bounce doesn't immediately re-trigger. Default: `0.1`.
- `model?` (`string`): Model id for the summary call — resolved against `provider`
  when set, else against the run's main provider. Defaults to the
  run's main model.
- `provider?` (`Provider`): Provider the summary call runs on. Defaults to the run's main
  provider. Pair with `model` to summarize on a different
  (cheaper / larger-window) model than the one driving the
  conversation. The trigger threshold still measures the MAIN model's
  window — it gauges the live conversation, not the summarizer.
- `releaseReplacedTurns?` (`boolean`): Release the in-memory bodies of turns each compaction summary replaces:
  large text `tool_result` outputs are written host-side to
  `<persistDir>/released/<callId>.txt` (exempt from the persist-dir LRU
  cap — once the stub round-trips into the session store the blob is the
  only remaining copy, so it lives and dies with the session) and the
  session's in-memory copy is swapped for a `<persisted-output …>` stub.
  Replaced turns never reach the wire again, so without this a
  long-lived host retains every pre-compaction tool output for the
  process's life. Requires `persistDir`; content stays retrievable from
  the stub's path. Off by default — hosts that need the lossless
  inline transcript (SFT capture, exporters) should leave it off.
- `restore?` (`boolean`): Re-inject recently-read files + active skills as synthetic tool-call
  pairs after the summary marker (via `buildPostCompactAttachments`) so
  the model keeps its working set. Default: `true`.
- `threshold?` (`number`): Fraction of the EFFECTIVE context window (raw window minus the output
  reserve) the last turn's input usage must reach to fire. Must be in the
  open interval `(0, 1)`; out-of-range disables the trigger. Default: `0.85`.

Source: [src/types.ts:474](https://github.com/Tahul/zidane/blob/main/src/types.ts#L474)

### `AutoCompactInput`

Interface.

Inputs to [`shouldAutoCompact`](https://zidane.si/docs/reference/index.md#shouldAutoCompact).

Kept as a struct so the call site reads as the predicate it is, and so
future inputs (per-session opt-out, recent-compaction cooldown, …) land
without re-threading every consumer.

```ts
interface AutoCompactInput
```

**Properties**

- `alreadyCompacting?` (`boolean`): Whether a compaction is already in flight for this session. Passing it
  through the predicate lets tests assert "doesn't double-fire" without
  spinning up the agent loop.
- `enabled` (`boolean`): User's master toggle. `false` → trigger never fires.
- `inputTokens` (`number`): Latest input-token count from the last `turn:after`. Must be a
  non-negative finite number; `NaN` / `±Infinity` / negative values
  are treated as "no usable signal" and the trigger skips
  conservatively (we'd rather defer compaction than fire on garbage).
- `lastCompactedInputTokens?` (`number`): Input-token count observed immediately AFTER the most recent successful
  compaction landed. Used together with `minGrowthFraction` to
  suppress thrashing — after compaction lowers the prefix from 85% → 35%,
  the next few turns drift back up; without hysteresis the trigger fires
  again the instant the threshold is re-crossed, often before the model
  has done any new work. Tracking the post-compact baseline lets the
  predicate require meaningful new growth before re-firing.

  `undefined` (no compaction yet this session) → hysteresis disabled.
- `minGrowthFraction?` (`number`): Minimum fraction of the effective context window that must be CONSUMED
  by new content (i.e. `inputTokens - lastCompactedInputTokens`) before
  a follow-up compaction fires. Expressed in the same units as
  `threshold`, e.g. `0.1` = 10% of the window. Defaults to `0`
  (no hysteresis) when omitted; chat hosts pick a value like `0.1`.

  Only consulted when `lastCompactedInputTokens` is set — first
  compaction in a session always fires off the absolute threshold.
- `rawContextWindow` (`number | null`): Model's raw context window. `null` for unknown / custom models — the
  trigger skips since we can't compute a ratio.
- `threshold` (`number`): Threshold expressed as a fraction of the effective context window
  (e.g. `0.8` = 80%). Values outside the open interval `(0, 1)` are
  rejected with `'invalid-threshold'` — `<= 0` is meaningless, and
  `>= 1` would schedule the trigger for "after we've already
  overflowed" which is too late to be useful.

Source: [src/compact/policy.ts:63](https://github.com/Tahul/zidane/blob/main/src/compact/policy.ts#L63)

### `ChildSpawnIdentity`

Interface.

Identity a nested spawn lifecycle event (`child:spawn:*`) adds to the
spawned agent's record.

`child:spawn:*` events describe a spawn fired BY a subagent (the spawned
agent sits at depth ≥ 2). Their payload is the spawned agent's own record
— `id` / `depth` / `task` / `callId` are the grandchild's, exactly as its
spawner's `spawn:*` saw them — so one handler can serve both families.
Unlike the other `child:*` events there is deliberately NO `childId`: on
those, `childId` + `depth` name the agent that originated the event, and
here `depth` already belongs to the spawned agent. The spawner is named
by `parentChildId` instead (its depth is `depth - 1`).

```ts
interface ChildSpawnIdentity
```

**Properties**

- `parentChildId` (`string`): Id of the subagent that ran the `spawn` call (the spawned agent's
  parent). Set by the first bubble hop and forwarded verbatim through
  deeper hops, so a root listener sees the true spawner, not its own
  direct child.

Source: [src/types.ts:3937](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3937)

### `CommandGenerateDataOptions`

Interface.

Options for `ctx.generateData` — a silent, schema-pinned model call.

```ts
interface CommandGenerateDataOptions
```

**Properties**

- `includeConversation?` (`boolean`): Fold a compacted transcript of the recent conversation into the call as
  context. Default false — most workflow values derive from data the
  command already gathered itself.
- `model?` (`string`): Model id to run the call on (must exist in the host's model catalog —
  see `ctx.runtime.models()` on the extension context). Omit to use the
  session's active model.
- `prompt` (`string`): Instruction describing the value to produce.
- `schema` (`SchemaInput`): Shape of the result — a zod v4 schema (return type inferred, no casts)
  or a plain JSON Schema object (name the type via the generic).
- `system?` (`string`): Optional system prompt override.

Source: [src/chat/commands.ts:117](https://github.com/Tahul/zidane/blob/main/src/chat/commands.ts#L117)

### `CompactHookContext`

Interface.

Base context for the compaction hooks (`compact:start` /
`compact:progress` / `compact:end`). Auto-compaction fires them at a
turn boundary inside a run when `behavior.autoCompact` is enabled and the
threshold trips; `agent.compact()` fires them between runs. Never during a
provider stream, so it carries run/turn coordinates rather than extending
[`StreamHookContext`](https://zidane.si/docs/reference/types.md#StreamHookContext).

```ts
interface CompactHookContext
```

**Properties**

- `reason` (`'auto' | 'manual'`): Why compaction ran: `'auto'` for the threshold trigger inside a run, `'manual'` for `agent.compact()`.
- `runId` (`string`): Run that triggered the compaction. For `reason: 'manual'`, the agent's latest run, or `''` before its first run.
- `sessionId?` (`string`): Bound session id, when the agent has a session.
- `turn` (`number`): 0-based index of the turn after which compaction fired. For `reason: 'manual'`, the latest run's last turn, or `0` before the first run.

Source: [src/types.ts:4028](https://github.com/Tahul/zidane/blob/main/src/types.ts#L4028)

### `CompactionSlice`

Interface.

Result of [`sliceForCompaction`](https://zidane.si/docs/reference/index.md#sliceForCompaction): the turns to summarize and the turns to keep.

```ts
interface CompactionSlice
```

**Properties**

- `preserved` (`readonly SessionTurn[]`): The portion that stays verbatim in the post-compact history.
- `toSummarize` (`readonly SessionTurn[]`): The portion of the conversation that will be summarized.

Source: [src/compact/messages.ts:34](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L34)

### `CompactOptions`

Interface.

Options for [`compactConversation`](https://zidane.si/docs/reference/index.md#compactConversation).

```ts
interface CompactOptions
```

**Properties**

- `clock?` (`RetryClock`): Clock for transient-error backoff: its `sleep` and, when it `replays`,
  its jitter source (see `retryJitter`), so a durable replay neither
  re-sleeps in real time nor picks a different delay. Default: a timer
  and `Math.random`.
- `keepTurns?` (`number`): Trailing turns left untouched when `scope: 'tail'`. Default: 4.
  Matches `AgentBehavior.compactKeepTurns` so a host that uses both
  mechanisms shares one knob.
- `maxOutputTokens?` (`number`): Maximum tokens the summary itself can occupy. Default: 20_000 — the
  p99.99 of summary output size in Claude Code's `COMPACT_MAX_OUTPUT`.
  Reasonable for any model with a 200k+ window.
- `maxPtlRetries?` (`number`): Retries with head-truncation when the provider reports
  `prompt_too_long`. Each retry halves the working set (dropping whole
  rounds from the head) before re-issuing the call, so shrinkage is
  geometric and converges even on very long sessions.
  Default: 3. Set 0 to fail-fast.
- `model?` (`string`): Model id used for the summary call. Default: `provider.meta.defaultModel`.
- `onAttempt?` (`(event: { attempt: number; kind: 'initial' | 'prefix-fallback' | 'ptl-retry' | 'transient-retry' }) => void`): Lifecycle hook for observability. Fires once per provider call,
  including retries. The `kind` field tells you whether the call is
  the initial attempt, the standalone call after a `prefixRequest`
  attempt fell back, a head-truncated retry, or a transient-error
  retry — useful for surfacing progress in a UI spinner.
- `onEnd?` (`(event: CompactEndEvent) => void`): Lifecycle hook fired exactly once after `onStart`, on both success
  and failure. Synchronous by design so observability cannot hang compaction.
- `onProgress?` (`(progress: CompactStreamProgress) => void`): Streaming-progress hook — fires on every streamed delta (text AND
  thinking) with a cumulative rough output-token estimate for the
  CURRENT provider attempt (the counter resets on retries). Lets hosts
  paint live "Compacting… \~N tokens" feedback instead of a silent
  multi-minute spinner. Deltas arrive at provider cadence — throttle
  on the consumer side. Synchronous and exception-safe by design.
- `onStart?` (`(event: CompactStartEvent) => void`): Lifecycle hook fired after preflight succeeds and before the first
  provider call starts. Useful for UI state ("Compacting...") and telemetry.
  Synchronous by design so observability cannot hang compaction.
- `prefixRequest?` (`Omit<StreamOptions, 'signal'>`): The conversation's next request exactly as the agent loop would send it:
  system, tools, wire messages, thinking and cache settings. When set, the
  summary call sends it unchanged plus the summary instruction at the end,
  so the provider reads the conversation from its prompt cache and the
  summarizer sees the same reasoning the model does. Only the output cap
  changes (`maxOutputTokens`); `model` and `thinking` come from the request.

  Falls back to the standalone summary call when the response calls a
  tool or has no text, or the call fails for any reason but an abort.
  Ignored when a custom `prompt` builder is set.
- `prompt?` (`CompactPromptBuilder`): Optional builder override. The default builder dispatches by
  direction to the named builders in `./prompt.ts`; pass a custom
  function to swap in a domain-specific summary prompt.
- `provider` (`Provider`): Provider used for the summary call. Called with empty tools list.
- `providerStreamTimeoutMs?` (`number`): INACTIVITY watchdog for the provider summary call in milliseconds —
  the clock resets on every streamed delta (text or thinking), so it
  bounds silence, not total duration. A hung stream fails after this
  much dead air; a healthy-but-slow stream (huge prompt → minutes of
  generation) is never killed mid-summary. Note the window also covers
  time-to-first-token: prompt ingestion on very large contexts emits
  nothing, which is why the default is generous. Set `0` to disable.
  Default: 300000 (5 minutes of silence).
- `scope?` (`CompactScope`): What to summarize. Default: `'tail'` — summarize everything before
  the last `keepTurns` turns. See [`CompactScope`](https://zidane.si/docs/reference/index.md#CompactScope).
- `shouldRethrowError?` (`(error: unknown) => boolean`): Errors matching this predicate are rethrown instead of being swallowed
  or retried. The agent loop passes its durable runtime's
  `isControlError`, so control errors (suspension, cancellation) escape.
- `signal?` (`AbortSignal`): Optional cancellation signal forwarded to `provider.stream()`.
- `summarize?` (`(input: { messages: SessionMessage[]; turns: readonly SessionTurn[] }) => Promise<{ summary: string } | null | undefined>`): Supplies the summary instead of the provider. Called once, after
  `onStart` and before any provider call, with the turns the summary
  would cover. A `{ summary }` answer is the result (no provider call, zero
  usage); `undefined` or `null` runs the summary call as usual. The agent
  loop passes the extension `compaction` interceptors here.
- `thinking?` (`'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'adaptive'`): Optional reasoning level. Default: `'off'` — summarization rarely benefits from thinking.
- `turns` (`readonly SessionTurn[]`): Conversation to compact, in chronological order.

Source: [src/compact/compact.ts:55](https://github.com/Tahul/zidane/blob/main/src/compact/compact.ts#L55)

### `CompactPromptOptions`

Interface.

Options passed to a [`CompactPromptBuilder`](https://zidane.si/docs/reference/index.md#CompactPromptBuilder).

```ts
interface CompactPromptOptions
```

**Properties**

- `anchorPreview?` (`string`): Short preview of the anchor turn's text — only used by `'from'` and
  `'up_to'`. Pass the first \~200 chars of the anchor turn so the model
  has a recognizable handle on where the slice begins / ends. Empty /
  undefined for `'full'` and `'tail'`.
- `direction` (`CompactDirection`): Which part of the conversation the summary covers.

Source: [src/compact/prompt.ts:21](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L21)

### `CompactResult`

Interface.

Outcome of a successful [`compactConversation`](https://zidane.si/docs/reference/index.md#compactConversation) call.

```ts
interface CompactResult
```

**Properties**

- `afterBytes` (`number`): UTF-8 byte length of the summary text (rough "after" measure).
- `beforeBytes` (`number`): Byte length of turns actually summarized (post-PTL-truncation).
- `droppedDueToPtl` (`readonly string[]`): Turn ids dropped by PTL head-truncation before reaching the
  provider. **Empty on first-try success.** These turns are NOT
  covered by the summary — callers should either leave them in the
  conversation history (they stay visible to the model verbatim,
  since the id-based cutoff only elides ids the marker explicitly
  claims) or surface a "compaction lost N turns of context" warning.

  The harness keeps these in the wire-level conversation by default;
  the safety contract is "the summary describes exactly what's in
  `summarizedTurnIds` — nothing more, nothing less".
- `model` (`string`): Model id used to produce the summary.
- `preservedTurns` (`readonly SessionTurn[]`): Turns left untouched (the preserved tail / verbatim slice).
- `ptlRetries` (`number`): Number of `prompt_too_long` retries that fired before success. 0 on first-try success.
- `summarizedTurnIds` (`readonly string[]`): Turn ids actually covered by the summary — i.e., the ids of turns
  that made it to the provider. **PTL-retry safe**: when head-truncation
  shrank the scope, only the surviving (post-truncation) turn ids
  appear here. Drives `summaryToTurn`'s `replacesTurnIds`; the wire-
  level cutoff in `applyCompactSummaryCutoff` reads the same field
  from the persisted marker.
- `summary` (`string`): The summary text, with any `<analysis>` block stripped.
- `usage` (`TurnUsage`): Token usage from the (last successful) summary call.

Source: [src/compact/compact.ts:269](https://github.com/Tahul/zidane/blob/main/src/compact/compact.ts#L269)

### `CompactStartEvent`

Interface.

Payload for `CompactOptions.onStart`.

```ts
interface CompactStartEvent
```

**Properties**

- `model` (`string`): Model id used for the summary call.
- `preservedTurnIds` (`readonly string[]`): Ids of the turns left untouched.
- `scope` (`CompactScope`): Resolved scope of this compaction.
- `summarizedTurnIds` (`readonly string[]`): Ids of the turns that will be sent to the summarizer.

Source: [src/compact/compact.ts:181](https://github.com/Tahul/zidane/blob/main/src/compact/compact.ts#L181)

### `CompactStartHookContext`

Interface.

Fired right before the summary call starts. See `compact:start`.

```ts
interface CompactStartHookContext extends CompactHookContext
```

**Properties**

- `effectiveWindow` (`number`): Effective window (raw minus output reserve) used for the ratio. `0` when the window is unknown.
- `reason` (`'auto' | 'manual'`, from `CompactHookContext`): Why compaction ran: `'auto'` for the threshold trigger inside a run, `'manual'` for `agent.compact()`.
- `runId` (`string`, from `CompactHookContext`): Run that triggered the compaction. For `reason: 'manual'`, the agent's latest run, or `''` before its first run.
- `sessionId?` (`string`, from `CompactHookContext`): Bound session id, when the agent has a session.
- `turn` (`number`, from `CompactHookContext`): 0-based index of the turn after which compaction fired. For `reason: 'manual'`, the latest run's last turn, or `0` before the first run.
- `usedFraction` (`number`): Fraction of the effective window the last turn's input reached. `0` when the window is unknown.

Source: [src/types.ts:4092](https://github.com/Tahul/zidane/blob/main/src/types.ts#L4092)

### `CompletionSubmitContext`

Interface.

Context passed to a provider's submit-time hooks.

```ts
interface CompletionSubmitContext<TItem = unknown> extends CompletionContext
```

**Type parameters**

- `TItem` (default `unknown`)

**Properties**

- `cursor` (`number`, from `CompletionContext`): UTF-16 code unit offset of the cursor (0-based).
- `references` (`readonly CompletionReference<TItem>[]`): The references owned by the provider that receive the hook.
- `text` (`string`, from `CompletionContext`): Full prompt text.

Source: [src/chat/completion-core.ts:85](https://github.com/Tahul/zidane/blob/main/src/chat/completion-core.ts#L85)

### `ConsoleSinkOptions`

Interface.

Options shared by [`consoleSink`](https://zidane.si/docs/reference/index.md#consoleSink) and [`jsonSink`](https://zidane.si/docs/reference/index.md#jsonSink).

```ts
interface ConsoleSinkOptions
```

**Properties**

- `minLevel?` (`LogLevel`): Minimum level to emit. Defaults to `'info'` — `debug` is dropped so
  the harness's lifecycle logging is not noisy by default. Set to
  `'debug'` to see every event.
- `stream?` (`{ write: (chunk: string) => void }`): Custom output stream. Defaults to `process.stderr` so logs don't pollute stdout.

Source: [src/logger.ts:131](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L131)

### `Counter`

Interface.

Instrument that only increases.

```ts
interface Counter
```

**Properties**

- `add` (`(value: number, attributes?: MetricAttributes) => void`): Adds a non-negative `value`, with optional attributes.

Source: [src/metrics.ts:66](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L66)

### `CreateExtensionDeps`

Interface.

Where [`createExtension`](https://zidane.si/docs/reference/index.md#createExtension) writes.

```ts
interface CreateExtensionDeps
```

**Properties**

- `resolveCheckoutRoot` (`(cwd: string) => string`): A cwd's checkout root (the working tree it sits in, or the folder itself): a project extension is a file of that checkout.
- `userDir` (`string`): The folder `user` extensions are discovered under (`~/.zidane`).

Source: [src/extension-authoring.ts:365](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L365)

### `CreateExtensionInput`

Interface.

A new extension to scaffold.

```ts
interface CreateExtensionInput extends ExtensionScaffoldOptions
```

**Properties**

- `cwd?` (`string`): The folder a project extension goes with.
- `name` (`string`): Lowercase words joined by hyphens, starting with a letter: the folder name and the extension `id`.
- `package?` (`boolean`, from `ExtensionScaffoldOptions`): Add `package.json`, `tsconfig.json` and `README.md`, so the folder is a publishable package.
- `scope?` (`'user' | 'project'`): `user` (default): `<userDir>/extensions/<name>`. `project`: `<checkout>/<prefix>/extensions/<name>` of `cwd`.
- `test?` (`boolean`, from `ExtensionScaffoldOptions`): Add `index.test.ts`, a test on `createTestHost`.
- `tui?` (`boolean`, from `ExtensionScaffoldOptions`): Add `tui.tsx` (terminal components) and a status slot drawn by it.
- `ui?` (`boolean`, from `ExtensionScaffoldOptions`): Add `ui.tsx` (desktop and web components) and a status slot drawn by it.

Source: [src/extension-authoring.ts:345](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L345)

### `CreateExtensionResult`

Interface.

A scaffolded extension.

```ts
interface CreateExtensionResult
```

**Properties**

- `dir` (`string`): Its folder (the cwd of the session that writes it).
- `name` (`string`): Its name (the folder's).
- `needsTrust?` (`boolean`): A project extension: it stays unloaded until the project is trusted.

Source: [src/extension-authoring.ts:355](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L355)

### `DecisionChoiceAnswer`

Interface.

Answer to a [`DecisionChoiceQuestion`](https://zidane.si/docs/reference/index.md#DecisionChoiceQuestion).

```ts
interface DecisionChoiceAnswer<V extends string = string>
```

**Type parameters**

- `V` (`extends string`, default `string`)

**Properties**

- `choice` (`V`): The chosen value, one of the question `choices` keys.
- `confidence?` (`number`): Model confidence in the choice in `[0, 1]`, when the provider reports it.
- `probabilities?` (`Readonly<Partial<Record<V, number>>>`): Probability per value, when the provider reports it.
- `type` (`'choice'`): Discriminant for a choice answer.

Source: [src/decisions/types.ts:76](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L76)

### `DecisionChoiceQuestion`

Interface.

Pick one of a fixed set of values. Keys are the values, entries describe when each applies.

```ts
interface DecisionChoiceQuestion<V extends string = string>
```

**Type parameters**

- `V` (`extends string`, default `string`)

**Properties**

- `choices` (`Readonly<Record<V, string>>`): Allowed values mapped to a description of when each applies.
- `instructions` (`string`): What to decide. The model picks one of `choices`.
- `type` (`'choice'`): Discriminant for a choice question.

Source: [src/decisions/types.ts:27](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L27)

### `DecisionPredicateAnswer`

Interface.

Answer to a [`DecisionPredicateQuestion`](https://zidane.si/docs/reference/index.md#DecisionPredicateQuestion).

```ts
interface DecisionPredicateAnswer
```

**Properties**

- `probability` (`number`): Estimated probability that the condition is true.
- `type` (`'predicate'`): Discriminant for a predicate answer.

Source: [src/decisions/types.ts:68](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L68)

### `DecisionPredicateQuestion`

Interface.

Is a condition true? Answered with a probability in `[0, 1]`.

```ts
interface DecisionPredicateQuestion
```

**Properties**

- `criteria?` (`{ false: string; true: string }`): Optional guidance describing when the condition is true / false.
- `instructions` (`string`): What to evaluate. The model answers whether the condition holds for the input.
- `type` (`'predicate'`): Discriminant for a predicate question.

Source: [src/decisions/types.ts:17](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L17)

### `DecisionRefusalAnswer`

Interface.

The model declined to answer this question.

```ts
interface DecisionRefusalAnswer
```

**Properties**

- `message?` (`string`): Explanation the model gave for declining, when present.
- `type` (`'refusal'`): Discriminant for a refusal answer.

Source: [src/decisions/types.ts:100](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L100)

### `DecisionScoreAnswer`

Interface.

Answer to a [`DecisionScoreQuestion`](https://zidane.si/docs/reference/index.md#DecisionScoreQuestion).

```ts
interface DecisionScoreAnswer
```

**Properties**

- `confidence?` (`number`): Model confidence in the score in `[0, 1]`, when the provider reports it.
- `probabilities?` (`readonly number[]`): Probability per level, indexed like `levels`, when the provider reports it.
- `score` (`number`): Probability-weighted average of level indices; can fall between levels.
- `type` (`'score'`): Discriminant for a score answer.

Source: [src/decisions/types.ts:88](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L88)

### `DecisionScoreQuestion`

Interface.

Rate the input against ordered levels (lowest first). Level indices start at 0.

```ts
interface DecisionScoreQuestion
```

**Properties**

- `instructions` (`string`): What to rate. The model scores the input against `levels`.
- `levels` (`readonly DecisionScoreLevel[]`): Ordered levels, lowest first. The index of a level is its score value.
- `type` (`'score'`): Discriminant for a score question.

Source: [src/decisions/types.ts:40](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L40)

### `EditSessionTarget`

Interface.

What an editing session targets. `dir` becomes the session's cwd; `name`
feeds the preset wording (and the skill marker).

```ts
interface EditSessionTarget
```

**Properties**

- `dir` (`string`): Absolute path of the extension or skill directory.
- `kind` (`'extension' | 'skill'`): Whether the session edits an extension or a skill.
- `name` (`string`): Name of the extension or skill.

Source: [src/extension-authoring.ts:74](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L74)

### `EnsureToolResultPairingOptions`

Interface.

Options for [`ensureToolResultPairing`](https://zidane.si/docs/reference/index.md#ensureToolResultPairing).

```ts
interface EnsureToolResultPairingOptions
```

**Properties**

- `onRepair?` (`(repair: PairingRepair) => void`): Fired once per repair the pass performed. Synchronous so the loop can
  stay on its hot path. Throwing from the callback aborts the pass —
  consumers wanting fail-fast (strict mode) can re-throw with their own
  typed error.

Source: [src/session/messages-pairing.ts:70](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L70)

### `ExtensionEditMarker`

Interface.

Per-edit-session marker persisted on `session.metadata[EXTENSION_EDIT_METADATA_KEY]`.

```ts
interface ExtensionEditMarker
```

**Properties**

- `dir` (`string`): Absolute path to the extension's directory (the session's cwd).

Source: [src/extension-authoring.ts:57](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L57)

### `FrozenPromptSections`

Interface.

The sections the SDK appended to a run's fresh system prompt, exactly as
appended; a section is `undefined` when the run had none.

```ts
interface FrozenPromptSections
```

**Properties**

- `mcp?` (`string`): The MCP server instructions (`# MCP Server Instructions`).
- `skills?` (`string`): The skills catalog (`<available_skills>`).
- `tools?` (`string`): The searchable tools catalog (`<searchable_tools>`).

Source: [src/types.ts:2970](https://github.com/Tahul/zidane/blob/main/src/types.ts#L2970)

### `FrozenSystemPrompt`

Interface.

The newest snapshot for a prompt key, with its prompt text and the index of the turn holding it.

```ts
interface FrozenSystemPrompt
```

**Properties**

- `index` (`number`): Index of the snapshot turn in the session's turns.
- `snapshot` (`SystemPromptSnapshot`): The snapshot's bookkeeping.
- `text` (`string`): The frozen system prompt.

Source: [src/system-freeze.ts:16](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L16)

### `GeometricThinkingDecay`

Interface.

Geometric thinking-budget taper: full budget through `afterTurn`, then
multiplied by `factor` each subsequent turn, clamped to `floor`.

Emits several distinct budgets on the way down, and on Anthropic each
distinct `thinking.budget_tokens` value is a full prompt-cache re-bill (the
budget is part of the cache key — measured, see
`AgentBehavior.thinkingDecay`). Prefer [`StepThinkingDecay`](https://zidane.si/docs/reference/index.md#StepThinkingDecay) when
caching is on.

```ts
interface GeometricThinkingDecay
```

**Properties**

- `afterTurn` (`number`): Last turn that gets the full thinking budget.
- `factor` (`number`): Multiplier applied to the budget on each turn after `afterTurn`.
- `floor` (`number`): Lowest thinking budget the taper reaches.

Source: [src/types.ts:792](https://github.com/Tahul/zidane/blob/main/src/types.ts#L792)

### `GithubClient`

Interface.

A GitHub API client that shares quota, pause and ETag state across its callers.

```ts
interface GithubClient
```

**Properties**

- `identity` (`(host?: string) => Promise<GithubIdentity>`): The current token's identity for a host (resolves the token).
- `observeAccount` (`(host: string, fingerprint: string, account: { login?: string; source?: string }) => void`): Record the login a token belongs to.
- `observeQuota` (`(host: string, fingerprint: string, resource: string, quota: { limit: number; remaining: number; resetAt: number; used?: number }) => void`): Record quotas read some other way (`GET /rate_limit`'s body).
- `pausedUntil` (`(input: { host?: string; resource: string }) => Promise<number | undefined>`): When background requests to `resource` resume, or `undefined` when they aren't paused.
- `recordExternalRateLimit` (`(input: { host?: string; resource: string; retryAt?: number }) => Promise<void>`): Record a rate limit seen outside this client (a `gh` command's stderr),
  so background work pauses too. `retryAt` is local epoch ms.
- `request` (`(req: GithubRequest) => Promise<GithubAnswer>`): Sends a request and resolves to its classified answer. Does not throw on HTTP errors.
- `reset` (`() => void`): Drop cached answers and tokens (tests, sign-out).
- `snapshot` (`() => { accounts: (GithubAccountEntry & { fingerprint: string })[]; pauses: GithubPauseView[]; quotas: GithubQuotaView[] }`): Every quota, pause and account the shared state holds.

Source: [src/github/client.ts:113](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L113)

### `GithubClientOptions`

Interface.

Options for [`createGithubClient`](https://zidane.si/docs/reference/index.md#createGithubClient).

```ts
interface GithubClientOptions
```

**Properties**

- `concurrency?` (`number`): Requests at once. Default 8.
- `fetch?` (`typeof fetch`): Fetch implementation. Default: the global `fetch`.
- `now?` (`() => number`): Clock in epoch milliseconds. Default: `Date.now`.
- `resolveToken?` (`(host: string) => Promise<{ source: string; token: string } | null>`): Token per host. Default: [`githubTokenSource`](https://zidane.si/docs/reference/extensions.md#githubTokenSource), which tests and hosts
  with their own credential store may swap.
- `store?` (`GithubStateStore`): Shared quota and pause state. Default: an in-memory store.

Source: [src/github/client.ts:136](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L136)

### `GithubIdentity`

Interface.

Who a host's current token is, as far as the client knows.

```ts
interface GithubIdentity
```

**Properties**

- `anonymous` (`boolean`): True when no token was found, so requests go out unauthenticated.
- `fingerprint` (`string`): Fingerprint of the token, from [`githubTokenFingerprint`](https://zidane.si/docs/reference/index.md#githubTokenFingerprint). Never the token itself.
- `host` (`string`): API host the token belongs to.
- `login?` (`string`): GitHub login of the token owner, when known.
- `source` (`string`): `GH_TOKEN`, `GITHUB_TOKEN`, `gh CLI`, a host-provided source, or `anonymous`.

Source: [src/github/client.ts:99](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L99)

### `GithubPullRef`

Interface.

Identifies one pull request.

```ts
interface GithubPullRef
```

**Properties**

- `number` (`number`): Pull request number.
- `owner` (`string`): Repository owner.
- `repo` (`string`): Repository name.

Source: [src/github/pulls.ts:65](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L65)

### `GithubRequest`

Interface.

A request to the GitHub API sent through [`GithubClient`](https://zidane.si/docs/reference/index.md#GithubClient).

```ts
interface GithubRequest
```

**Properties**

- `body?` (`unknown`): JSON body.
- `conditional?` (`boolean`): Revalidate a cached GET with its ETag (default true for GET).
- `headers?` (`Record<string, string>`): Extra headers (`accept`, …).
- `host?` (`string`): API host: `github.com` or an Enterprise host. Default `github.com`.
- `interactive?` (`boolean`): A user action (a click, a command), not a background sweep: may spend
  the reserved tenth of the quota and goes through a pause.
- `maxAgeMs?` (`number`): Serve a cached GET answer younger than this without asking GitHub.
- `method?` (`'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'`, default `'GET'`): HTTP method.
- `path` (`string`): A path under the API root (`repos/o/r/pulls/1`), or `graphql`.
- `signal?` (`AbortSignal`): Aborts the request. An aborted request answers `failed`.
- `timeoutMs?` (`number`): Deadline for headers and body together. Default 4 s.
- `token?` (`string`): Use this token instead of resolving one.

Source: [src/github/client.ts:54](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L54)

### `GithubStateStore`

Interface.

Storage for the shared GitHub quota, pause and account state.

```ts
interface GithubStateStore
```

**Properties**

- `read` (`() => GithubState`): The current state (re-read from disk when another process changed it).
- `update` (`(change: (state: GithubState) => void, opts?: { urgent?: boolean }) => void`): Change the state. `urgent` writes through at once (pauses: other
  processes must see them now); otherwise the write is debounced.

Source: [src/github/state.ts:61](https://github.com/Tahul/zidane/blob/main/src/github/state.ts#L61)

### `Histogram`

Interface.

Instrument that records a distribution of values.

```ts
interface Histogram
```

**Properties**

- `record` (`(value: number, attributes?: MetricAttributes) => void`): Records one measurement, with optional attributes.

Source: [src/metrics.ts:72](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L72)

### `HostPerf`

Interface.

A host's performance monitor: what `perf.watch`, `perf.history` and `perf.threads` answer from.

```ts
interface HostPerf
```

**Properties**

- `history` (`() => PerfSample[]`): The samples held, oldest first.
- `threads` (`(pid: number) => Promise<PerfOsThread[]>`): A process's OS threads, busiest first. Rejects with [`PerfProcessNotFoundError`](https://zidane.si/docs/reference/index.md#PerfProcessNotFoundError) for a pid outside the host's tree.
- `watch` (`(listener: (sample: PerfSample) => void) => () => void`): Gets each sample from now on; the first watcher starts sampling, the last unsubscribe stops it.

Source: [src/perf/host.ts:38](https://github.com/Tahul/zidane/blob/main/src/perf/host.ts#L38)

### `HostPerfOptions`

Interface.

What [`createHostPerf`](https://zidane.si/docs/reference/index.md#createHostPerf) needs of its host.

```ts
interface HostPerfOptions
```

**Properties**

- `intervalMs?` (`number`): Between two samples. Default 2 s.
- `label` (`string`): The host process's row: `Server`, `Daemon`. Its event loop is `<label> event loop`.
- `mcpInstances` (`() => readonly OwnedMcpInstance[]`): The MCP server processes of the host's sessions (its `mcpServers.instances()`).
- `sessionTitle` (`(sessionId: string) => Promise<string | undefined>`): A session's title; `undefined` while it has none.

Source: [src/perf/host.ts:26](https://github.com/Tahul/zidane/blob/main/src/perf/host.ts#L26)

### `InstrumentOptions`

Interface.

Options passed to the meter when an instrument is created.

```ts
interface InstrumentOptions
```

**Properties**

- `description?` (`string`): Human-readable description of the instrument.
- `unit?` (`string`): Unit of the measurement, for example `'ms'` or `'{token}'`.

Source: [src/metrics.ts:84](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L84)

### `KnownGithubPull`

Interface.

What a caller already holds for a PR, so an unchanged one isn't read again.

```ts
interface KnownGithubPull
```

**Properties**

- `resolvedAt?` (`number`): When it was last read (epoch ms).
- `state?` (`string`): Display state of the held copy. See [`GithubPullState`](https://zidane.si/docs/reference/extensions.md#GithubPullState).
- `updatedAt?` (`string`): GitHub's `updated_at` when it was last read.

Source: [src/github/pulls.ts:75](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L75)

### `Logger`

Interface.

Structured logger that writes records to a [`LogSink`](https://zidane.si/docs/reference/index.md#LogSink).

```ts
interface Logger
```

**Properties**

- `baseAttributes` (`Readonly<Record<string, unknown>>`, readonly): Inspectable baseline attributes — handy for tests and for hook
  handlers that want to clone-with-extra without recursing.
- `debug` (`(message: string, attrs?: Record<string, unknown>) => void`): Logs `message` at `debug` level with optional attributes.
- `error` (`(message: string, attrs?: Record<string, unknown>) => void`): Logs `message` at `error` level with optional attributes.
- `info` (`(message: string, attrs?: Record<string, unknown>) => void`): Logs `message` at `info` level with optional attributes.
- `warn` (`(message: string, attrs?: Record<string, unknown>) => void`): Logs `message` at `warn` level with optional attributes.
- `with` (`(extra: Record<string, unknown>) => Logger`): Returns a child logger that prepends the given attributes onto every
  subsequent emit. Equivalent to `pino.child` / `winston.child`. The
  parent and child share the same sink, so a child is cheap.

Source: [src/logger.ts:65](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L65)

### `LoggingHookSet`

Interface.

Value returned by [`createLoggingHooks`](https://zidane.si/docs/reference/index.md#createLoggingHooks).

```ts
interface LoggingHookSet
```

**Properties**

- `install` (`(hooks: Hookable<AgentHooks>) => () => void`): Attaches the logging hook handlers to the given agent hooks instance.
  Returns an `uninstall` function that detaches them.

Source: [src/logger.ts:383](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L383)

### `LoggingHooksOptions`

Interface.

Options for [`createLoggingHooks`](https://zidane.si/docs/reference/index.md#createLoggingHooks).

```ts
interface LoggingHooksOptions
```

**Properties**

- `includeLifecycle?` (`boolean`): When true (default), lifecycle events (`agent:start`, `turn:before`,
  `tool:before`, `tool:after`, `mcp:bootstrap:end`) emit at `debug` level so they
  stay quiet by default. Set false to mute them entirely regardless of
  the configured minimum level — useful when piping into a tracer
  that already captures lifecycle.
- `level?` (`LogLevel`): Minimum interesting level for harness-emitted lines. Default `'info'`.
  Set to `'debug'` to see every tool dispatch / stream event. Set to
  `'warn'` to mute the chatty ones and only see failures + budgets.
- `logger` (`Logger`): Logger that receives the harness-emitted lines.

Source: [src/logger.ts:363](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L363)

### `LoginMcpServerOptions`

Interface.

Options for [`loginMcpServer`](https://zidane.si/docs/reference/index.md#loginMcpServer).

```ts
interface LoginMcpServerOptions
```

**Properties**

- `callback?` (`OAuthCallbackHandle`): Where the code comes from instead of a loopback listener of this
  process: a remote sign-in, whose browser redirects to the CLIENT's
  loopback (`redirectUri`), the client forwarding the code. With it, no
  listener is bound here.
- `callbackPath?` (`string`): Override the loopback callback path. Default: `/callback`. Useful only
  for servers that pinned a different path during registration. Ignored
  when `oauth.callbackPort` is set (the pinned redirect is always `/callback`).
- `clientName?` (`string`): Override `client_name` shown on consent screens. Default: 'zidane'.
- `connectTimeoutMs?` (`number`): Maximum time for the PRE-authorization phase — the `client.connect()`
  that triggers discovery, dynamic registration, and the authorization
  redirect. Default: 30s.

  Separate from `timeoutMs` because it covers machine-speed HTTP,
  not a human in a browser. It exists because the MCP SDK's `connect()`
  accepts no `AbortSignal`: an unreachable or slow-loris server would
  otherwise hang here forever, un-cancellable, with the host UI parked on
  a spinner that no keystroke can dismiss.
- `hooks?` (`Hookable<AgentHooks, HookKeys<AgentHooks>>`): Agent hooks. The flow emits `mcp:auth:url`/`success`/`error` when wired.
- `onAuthorizationUrl?` (`(url: URL) => void | Promise<void>`): Invoked with the authorization URL once it's ready. Hosts typically
  (a) emit `mcp:auth:url` for the TUI, and (b) call `tryOpenBrowser`.
  The URL is identical to the one passed to the `mcp:auth:url` hook
  fired automatically — this callback is a synchronous hook for callers
  that don't want to wire the agent hook machinery.
- `renderCallbackPage?` (`OAuthCallbackPageRenderer`): Renders the post-redirect browser page — hosts pass their themed
  renderer (zidane's TUI: `renderDefaultCallbackPage`) so MCP logins
  end on the same screen as provider OAuth logins. The server name
  rides as `page.provider`.
- `scope?` (`string`): Override the requested OAuth scope.
- `signal?` (`AbortSignal`): Cancels the flow (esc / close modal / SIGINT).
- `state?` (`string`): OAuth `state` for the authorization URL (`McpOAuthProviderOptions.state`); the caller checks it.
  Omitted: a random one is generated and checked against the loopback callback here
  (some servers, e.g. CircleCI, reject an authorization request without `state`).
- `store` (`McpCredentialStore`): Persistence — same store the bootstrap path reads from.
- `timeoutMs?` (`number`): Maximum time to wait for the user to complete the browser flow, in ms.
  The user can also cancel via `signal`. Default: 5 minutes.

Source: [src/mcp/login.ts:35](https://github.com/Tahul/zidane/blob/main/src/mcp/login.ts#L35)

### `LoginMcpServerResult`

Interface.

Outcome of a successful [`loginMcpServer`](https://zidane.si/docs/reference/index.md#loginMcpServer) flow.

```ts
interface LoginMcpServerResult
```

**Properties**

- `tokens` (`{ access_token: string; expires_in?: number; id_token?: string; issuer?: string; refresh_token?: string; scope?: string; token_type: string }`): Stored OAuth tokens after a successful exchange.
- `tools` (`{ description?: string | null; inputSchema?: unknown; name: string }[]`): Upstream tool descriptors discovered after re-connecting with the new
  tokens. The server's `enabledTools` / `disabledTools` filters are NOT
  applied here — that's a bootstrap concern. Hosts that want filtering
  should pass the result through `connectMcpServers` rebuild on the next
  session activation rather than reusing this list verbatim.

Source: [src/mcp/login.ts:100](https://github.com/Tahul/zidane/blob/main/src/mcp/login.ts#L100)

### `LogRecord`

Interface.

One structured log entry.

```ts
interface LogRecord
```

**Properties**

- `attrs` (`Record<string, unknown>`): Structured fields. Correlation ids land here automatically.
- `level` (`LogLevel`): Severity of the record.
- `message` (`string`): Free-form message. Sinks render this as the human-facing line.
- `timestamp` (`number`): Unix ms — set by `Logger` at emit time.

Source: [src/logger.ts:47](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L47)

### `LogSink`

Interface.

Destination for log records.

```ts
interface LogSink
```

**Properties**

- `emit` (`(record: LogRecord) => void`): Receives one record. Errors thrown here are swallowed by the logger.

Source: [src/logger.ts:59](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L59)

### `MainThreadMeter`

Interface.

A host's main thread, measured: how busy it was, and (while on) how late its timers ran.

```ts
interface MainThreadMeter
```

**Properties**

- `read` (`() => { busy: number; lag: PerfLag | null }`): Busy share since the previous read (0–1), and the delay over that span when on.
- `sinceStart` (`() => number`): Busy share since the process started (0–1).
- `start` (`() => void`): Turns the delay histogram on.
- `stop` (`() => void`): Turns it off.

Source: [src/perf/event-loop.ts:20](https://github.com/Tahul/zidane/blob/main/src/perf/event-loop.ts#L20)

### `McpCredentialEntry`

Interface.

Per-server persisted state. Subfields are optional so a partial save
(e.g. `saveCodeVerifier` arriving before `saveTokens`) doesn't blow away
earlier subfields — the provider always patches, never replaces.

```ts
interface McpCredentialEntry
```

**Properties**

- `clientInformation?` (`OAuthClientInformationMixed`): Registered client information, from dynamic client registration.
- `clientSecret?` (`string`): Secret of a pre-registered client (`McpServerConfig.oauth`), entered in
  a host UI so it stays out of `mcps.json`. Configuration, not session
  state: sign-out and credential invalidation keep it.
- `discoveryState?` (`OAuthDiscoveryState`): Cached OAuth discovery state for the server.
- `tokens?` (`{ access_token: string; expires_in?: number; id_token?: string; issuer?: string; refresh_token?: string; scope?: string; token_type: string }`): OAuth access and refresh tokens.

Source: [src/mcp/oauth-provider.ts:79](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L79)

### `McpCredentialStore`

Interface.

Persistence for MCP OAuth credentials, keyed by server name.

```ts
interface McpCredentialStore
```

**Properties**

- `delete` (`(name: string) => void`): Removes the stored entry for a server.
- `load` (`(name: string) => McpCredentialEntry | undefined`): Returns the stored entry for a server, or `undefined` when none exists.
- `save` (`(name: string, entry: McpCredentialEntry) => void`): Replaces the stored entry for a server.

Source: [src/mcp/oauth-provider.ts:95](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L95)

### `McpOAuthClientConfig`

Interface.

`McpServerConfig.oauth`.

```ts
interface McpOAuthClientConfig
```

**Properties**

- `callbackPort?` (`number`): Fixed loopback port for the OAuth redirect (`http://127.0.0.1:<port>/callback`). Random when omitted.
- `clientId` (`string`): Client ID of the pre-registered OAuth app. `${VAR}` placeholders expand.
- `clientSecret?` (`string`): Client secret. Leave it out of config files when possible. `${VAR}` placeholders expand.
- `scope?` (`string`): Space-separated scopes to request.

Source: [src/types.ts:81](https://github.com/Tahul/zidane/blob/main/src/types.ts#L81)

### `McpOAuthProviderOptions`

Interface.

Options for [`McpOAuthProvider`](https://zidane.si/docs/reference/index.md#McpOAuthProvider) and [`mcpOAuthProviderFor`](https://zidane.si/docs/reference/index.md#mcpOAuthProviderFor).

```ts
interface McpOAuthProviderOptions
```

**Properties**

- `clientName?` (`string`): `client_name` used in dynamic client registration. Defaults to `'zidane'`.
  Some servers display this string to the user on the consent screen.
- `name` (`string`): Server name — used as the storage key.
- `onAuthorizationUrl?` (`(url: URL) => void | Promise<void>`): Invoked when the SDK wants the user agent to navigate to the authorization
  URL. Typically the host opens the browser AND emits a hook so the TUI can
  render the URL in a status row. No-op in non-interactive mode (the SDK
  still calls this before throwing `UnauthorizedError` from connect).
- `redirectUri?` (`string`): Loopback callback URI. Pass `undefined` for bootstrap (non-interactive
  mode — stored tokens + refresh only, never opens a browser).
- `scope?` (`string`): Override the requested OAuth scope. Default: unset (the SDK negotiates
  via the server's metadata).
- `state?` (`string`): OAuth `state` sent on the authorization URL. The caller checks it on the
  callback (a remote sign-in, where the redirect lands on another machine).
  Default: none.
- `staticClient?` (`McpStaticClient`): Pre-registered client. When set, `clientInformation()` returns it and
  the SDK never attempts dynamic client registration.
- `store` (`McpCredentialStore`): Persistence backend.

Source: [src/mcp/oauth-provider.ts:119](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L119)

### `McpStaticClient`

Interface.

A pre-registered OAuth client. With one set, the provider skips dynamic client registration.

```ts
interface McpStaticClient
```

**Properties**

- `clientId` (`string`): OAuth client id.
- `clientSecret?` (`string`): OAuth client secret. Omit for a public client.

Source: [src/mcp/oauth-provider.ts:160](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-provider.ts#L160)

### `Meter`

Interface.

Minimal Meter interface — structurally identical to OTel's `Meter`.
Hosts passing `metrics.getMeter(name)` (from `@opentelemetry/api`)
satisfy this without adaptation.

```ts
interface Meter
```

**Properties**

- `createCounter` (`(name: string, options?: InstrumentOptions) => Counter`): Creates a counter instrument with the given name.
- `createHistogram` (`(name: string, options?: InstrumentOptions) => Histogram`): Creates a histogram instrument with the given name.
- `createUpDownCounter` (`(name: string, options?: InstrumentOptions) => UpDownCounter`): Creates an up/down counter instrument with the given name.

Source: [src/metrics.ts:96](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L96)

### `MetricsHookSet`

Interface.

Value returned by [`createMetricsHooks`](https://zidane.si/docs/reference/index.md#createMetricsHooks).

```ts
interface MetricsHookSet
```

**Properties**

- `install` (`(hooks: Hookable<AgentHooks>) => () => void`): Attaches every metrics hook handler to the given agent hooks instance.
  Returns an `uninstall` function that detaches the handlers.

Source: [src/metrics.ts:135](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L135)

### `MetricsHooksOptions`

Interface.

Options for [`createMetricsHooks`](https://zidane.si/docs/reference/index.md#createMetricsHooks).

```ts
interface MetricsHooksOptions
```

**Properties**

- `baseAttributes?` (`MetricAttributes`): Optional baseline attributes applied to every measurement. Typical
  use: `{ service: 'tui', env: 'prod' }`. Per-event attributes win on
  key collision.
- `meter` (`Meter`): OpenTelemetry-shaped meter that creates the instruments.
- `namespace?` (`string`): Optional prefix prepended to every instrument name. Default: no prefix
  (instrument names follow OTel Gen AI semantic conventions verbatim,
  which is the most-portable shape). Set to e.g. `'zidane.'` to
  namespace inside a shared meter registry.
- `onError?` (`(kind: string, err: unknown) => void`): Error sink for meter failures. The helper still swallows the throw
  so a broken backend can't crash a run; this callback surfaces the
  failure for ops dashboards.

Source: [src/metrics.ts:110](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L110)

### `ModelTarget`

Interface.

A resolved provider+model pair the loop can dispatch a turn to. The run
resolves `AgentRunOptions.model` against the agent's providers into an
ordered list of these; `targets[0]` is the primary and the rest are
fallbacks tried in order when a stream fails terminally.

```ts
interface ModelTarget
```

**Properties**

- `contextWindow?` (`number`): Host-supplied window of this target's model — see `ModelTargetSpec.contextWindow`.
- `model` (`string`): Model id sent to the provider.
- `provider` (`Provider`): Provider that serves the model.

Source: [src/types.ts:3298](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3298)

### `ModelTargetSpec`

Interface.

One entry of the run-level model fallback list — a model id optionally
pinned to a specific provider (referenced by `Provider.name` against the
agent's provider list). Entries without `provider` fan out across every
configured provider, in provider order.

```ts
interface ModelTargetSpec
```

**Properties**

- `contextWindow?` (`number`): Context window (tokens) of this target's model, for hosts that size
  auto-compaction from their own model catalog (the SDK core has none).
  When a fallback advances onto this target, an explicit run-level
  `autoCompact.contextWindow` is re-based onto this value so the
  compaction trigger tracks the ACTIVE model, not the primary's window.
  Omitted: the window only re-derives when it was provider-meta-sourced
  to begin with.
- `model` (`string`): Model id.
- `provider?` (`string`): Name of the provider to pin the model to. Fans out across every provider when omitted.

Source: [src/types.ts:3275](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3275)

### `OAuthCallbackHandle`

Interface.

Handle to a running one-shot OAuth callback server.

```ts
interface OAuthCallbackHandle
```

**Properties**

- `close` (`() => Promise<void>`): Idempotent shutdown. Safe to call from a `finally` block whether the
  flow succeeded, failed, or was aborted. Resolves once the server stops
  accepting connections.
- `promise` (`Promise<OAuthCallbackResult>`): Resolves with `{ code, state }` on a successful callback. Rejects with:

  - The OAuth-spec `error` field (`access_denied`, `server_error`, ...)
    when the authorization server redirects with `?error=...`.
  - `'OAuth callback aborted'` when the external `AbortSignal` fires.
  - `'OAuth callback server closed'` when `close()` is called before any
    callback arrives.

  Single-shot — only the first matching request resolves the promise.
- `redirectUri` (`string`): Full URI to register with the authorization server, e.g.
  `http://127.0.0.1:51823/callback`. Stable for the lifetime of the
  handle.

Source: [src/mcp/oauth-callback.ts:45](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-callback.ts#L45)

### `OAuthCallbackOptions`

Interface.

Options for [`startOAuthCallback`](https://zidane.si/docs/reference/index.md#startOAuthCallback).

```ts
interface OAuthCallbackOptions
```

**Properties**

- `host?` (`string`): Override the loopback host. Defaults to `127.0.0.1`. Don't bind to
  `0.0.0.0` here — the OAuth code is a one-time secret and the server
  would otherwise accept it from any host on the LAN.
- `path?` (`string`): Path component the authorization server should redirect to. Defaults
  to `/callback`. Useful when matching a pre-registered URI that uses a
  different path.
- `port?` (`number`): Override the port. Defaults to `0` (OS-assigned). Pin to a fixed port
  only when the authorization server requires a pre-registered redirect
  URI; the random-port path is preferred so concurrent flows don't clash.
- `provider?` (`string`): Display name handed to the page renderer. Default: `'MCP server'`.
- `renderPage?` (`OAuthCallbackPageRenderer`): Renders the post-redirect browser page. Default: the page every
  zidane sign-in ends on.
- `signal?` (`AbortSignal`): Cancels the flow — rejects `promise` and closes the server.

Source: [src/mcp/oauth-callback.ts:72](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-callback.ts#L72)

### `OAuthCallbackResult`

Interface.

Result of a successful callback. `state` is forwarded verbatim from the
query string — callers verify it against their pre-flight value to defend
against CSRF (the MCP SDK does this internally when it controls `state`).

```ts
interface OAuthCallbackResult
```

**Properties**

- `code` (`string`): Authorization code from the redirect.
- `state?` (`string`): `state` query parameter from the redirect, when present.

Source: [src/mcp/oauth-callback.ts:37](https://github.com/Tahul/zidane/blob/main/src/mcp/oauth-callback.ts#L37)

### `Owned`

Interface.

One tick's reading.

```ts
interface Owned
```

**Properties**

- `mcp` (`Map<number, PerfProcessMcp>`): The MCP server each MCP process runs, by pid.
- `pids` (`Set<number>`): Every pid Zidane started for its own work, local and the other host's.
- `sessions` (`Map<number, string>`): The session each process was started for (its id on its host), by pid.

Source: [src/perf/owned.ts:72](https://github.com/Tahul/zidane/blob/main/src/perf/owned.ts#L72)

### `OwnedDaemon`

Interface.

Another host whose tree is sampled too (the desktop app's daemon), as far as this module needs it.

```ts
interface OwnedDaemon
```

**Properties**

- `mcpInstances` (`() => Promise<readonly OwnedMcpInstance[]>`): `mcp.instances`.
- `ownedProcesses` (`() => Promise<readonly OwnedPid[]>`): `daemon.ownedProcesses`.
- `pid` (`number`): The host's process id: a new pid is a new host, whose answers start empty.
- `sessionProcesses` (`() => Promise<readonly SessionPid[]>`): `daemon.sessionProcesses`.

Source: [src/perf/owned.ts:47](https://github.com/Tahul/zidane/blob/main/src/perf/owned.ts#L47)

### `OwnedMcpInstance`

Interface.

One MCP server process, as `mcp.instances` lists it.

```ts
interface OwnedMcpInstance
```

**Properties**

- `name` (`string`): The MCP server's name.
- `pid?` (`number`): Its process; absent before it started (or for a remote server).
- `sessions` (`number`): Sessions holding it now.
- `shared` (`boolean`): One process for every session (`true`), or one session's.

Source: [src/perf/owned.ts:35](https://github.com/Tahul/zidane/blob/main/src/perf/owned.ts#L35)

### `OwnedPid`

Interface.

One owned process; the role is not read here.

```ts
interface OwnedPid
```

**Properties**

- `pid` (`number`): The process id.

Source: [src/perf/owned.ts:21](https://github.com/Tahul/zidane/blob/main/src/perf/owned.ts#L21)

### `PairingRepair`

Interface.

One repair made by [`ensureToolResultPairing`](https://zidane.si/docs/reference/index.md#ensureToolResultPairing).

```ts
interface PairingRepair
```

**Properties**

- `callId?` (`string`): Tool-use / tool-result id this repair concerns. Absent for empty-marker repairs.
- `messageIndex` (`number`): Zero-based index into the INPUT `messages` array where the corruption was found.
- `mode` (`PairingRepairMode`): Which repair was performed. See [`PairingRepairMode`](https://zidane.si/docs/reference/index.md#PairingRepairMode).

Source: [src/session/messages-pairing.ts:60](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L60)

### `PerfChannel`

Interface.

One IPC channel's counters since start or the last reset.

```ts
interface PerfChannel
```

**Properties**

- `channel` (`string`): The channel's name.
- `count` (`number`): Messages counted.
- `direction` (`PerfChannelDirection`): Which way its messages go.
- `maxMs` (`number`): The slowest one, ms.
- `p95Ms` (`number`): 95th percentile, ms.
- `totalMs` (`number`): Time they took, summed, ms.

Source: [src/perf/types.ts:93](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L93)

### `PerfGpu`

Interface.

Whole-GPU use (every app's: macOS has no per-process figure).

```ts
interface PerfGpu
```

**Properties**

- `device` (`number`): Percent.
- `memory?` (`number`): In use, bytes.
- `renderer?` (`number`): The renderer's share, percent (Apple GPUs).
- `tiler?` (`number`): The tiler's share, percent (Apple GPUs).

Source: [src/perf/types.ts:135](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L135)

### `PerfLag`

Interface.

The host's event-loop delay over the last interval, ms.

```ts
interface PerfLag
```

**Properties**

- `max` (`number`): Longest delay, ms.
- `p50` (`number`): Median delay, ms.
- `p99` (`number`): 99th percentile, ms.

Source: [src/perf/types.ts:125](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L125)

### `PerfOsThread`

Interface.

One OS thread of a process. macOS gives no names (`label` empty).

```ts
interface PerfOsThread
```

**Properties**

- `cpu` (`number`): Percent of one core.
- `id` (`string`): The thread's id in its process.
- `label` (`string`): Its name; empty where the system gives none.

Source: [src/perf/types.ts:177](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L177)

### `PerfProcess`

Interface.

One process of the app, a host, or a program either started.

```ts
interface PerfProcess
```

**Properties**

- `cpu` (`number`): CPU over the last interval, percent of one core.
- `detail?` (`string`): More: the command line, the service, the page's URL.
- `kind` (`PerfProcessKind`): What the process is to the app.
- `label` (`string`): A short name: "Main process", "Server", `typescript-language-server (node)`.
- `mcp?` (`PerfProcessMcp`): An MCP server's process: its server, and whether sessions share it.
- `memory` (`number`): Resident memory, bytes.
- `origin` (`PerfOrigin`): Whose cost it is: the app's, or what a session or terminal launched.
- `parent` (`number | null`): The process it runs under in the tree shown (`null`: a root).
- `pid` (`number`): The process id.
- `session?` (`PerfProcessSession`): The session it runs for: a process a session started (`daemon.sessionProcesses`), or one under it.

Source: [src/perf/types.ts:29](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L29)

### `PerfProcessMcp`

Interface.

The MCP server a process runs (`mcp.instances`).

```ts
interface PerfProcessMcp
```

**Properties**

- `name` (`string`): The MCP server's name.
- `sessions` (`number`): Sessions holding it now.
- `shared` (`boolean`): One process for every session, or one session's.

Source: [src/perf/types.ts:61](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L61)

### `PerfProcessSession`

Interface.

The session a process runs for.

```ts
interface PerfProcessSession
```

**Properties**

- `id` (`string`): The session's key as the reader names it (a host sends its own session id).
- `title?` (`string`): Its title; absent while it has none.

Source: [src/perf/types.ts:53](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L53)

### `PerfSample`

Interface.

One sample: every 2 s while someone watches.

```ts
interface PerfSample
```

**Properties**

- `at` (`number`): Epoch ms.
- `channels` (`PerfChannel[]`): The most expensive channels, since `countersSince` (the desktop app's; a host keeps none).
- `cores` (`number`): Logical cores (100% CPU is one of them).
- `countersSince` (`number`): When the channel and frame counters started (epoch ms): the app's start or the last reset.
- `frames` (`PerfSlowFrame[]`): The most expensive slow-frame scripts, every window, since `countersSince` (the desktop app's; a host keeps none).
- `gpu` (`PerfGpu | null`): `null`: not measured (not macOS, or `ioreg` failed).
- `intervalMs` (`number`): Time since the previous sample, ms.
- `lag` (`PerfLag | null`): Absent before the first full interval.
- `launched` (`PerfTotals`): What sessions and terminals launched (origin `launched`).
- `processes` (`PerfProcess[]`): Every process sampled.
- `self` (`{ commandMs: number; cpu: number }`): The monitor's own cost: main-thread time spent sampling, percent of one core, and the wall time of its commands.
- `threads` (`PerfThread[]`): Every thread the app can name.
- `totals` (`PerfTotals`): Zidane's own processes (origin `app`).

Source: [src/perf/types.ts:147](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L147)

### `PerfSlowFrame`

Interface.

Where long frames (over 50 ms) spent their time: one script and function, summed.

```ts
interface PerfSlowFrame
```

**Properties**

- `count` (`number`): Long frames it ran in.
- `fn` (`string`): The function, or what invoked the script (an event, a timer).
- `maxMs` (`number`): Its longest, ms.
- `source` (`string`): The script's URL, as the page loaded it.
- `totalMs` (`number`): Its time in them, summed, ms.
- `window` (`string`): The window's title.

Source: [src/perf/types.ts:109](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L109)

### `PerfThread`

Interface.

A thread the app can name: a host's event loop, a worker, a window's main thread or worker.

```ts
interface PerfThread
```

**Properties**

- `busy` (`number`): Share of the interval it was busy (0–1). For a window, the time long
  frames blocked it; for a window's worker, the time a request waited on it.
- `heap?` (`number`): Its JavaScript heap in use, bytes.
- `id` (`string`): Stable across samples (`worker:<threadId>`, `renderer:<pid>`).
- `kind` (`'renderer' | 'main' | 'worker' | 'renderer-worker'`): A host's event loop, its worker, a window's main thread, or a window's worker.
- `label` (`string`): What it is called: "Main process event loop", "History pager", a window's title.
- `pid` (`number`): The process it runs in.

Source: [src/perf/types.ts:71](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L71)

### `PerfTotals`

Interface.

CPU (percent of one core) and resident memory (bytes), summed.

```ts
interface PerfTotals
```

**Properties**

- `cpu` (`number`): CPU, percent of one core.
- `memory` (`number`): Resident memory, bytes.

Source: [src/perf/types.ts:21](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L21)

### `PersistInput`

Interface.

Inputs to [`maybePersistToolResult`](https://zidane.si/docs/reference/index.md#maybePersistToolResult). Kept as a struct so the loop's
call site stays readable and additional optional knobs (compression,
mime detection, …) land without re-threading every call site.

```ts
interface PersistInput
```

**Properties**

- `callId` (`string`): `tool_use` id from the assistant turn. Used as the filename.
- `excludeTools?` (`readonly string[]`): Canonical tool names that bypass persistence.
- `maxBytes?` (`number`): Optional cap on the total bytes of persisted blobs under `persistDir`.
  When set (and > 0), after a successful write the helper sweeps the
  directory and removes the oldest `*.txt` blobs (by mtime) until the
  sum of remaining sizes is at or below the cap.

  Bound to the **current session** because `persistDir` is per-session
  (see [`resolvePersistDir`](https://zidane.si/docs/reference/index.md#resolvePersistDir)); eviction never crosses session
  boundaries. The new blob is always preserved — its mtime is the
  latest, so the LRU sort guarantees older blobs go first.

  Skipped when the value isn't a positive finite number. Also skipped when
  `writeBlob` is supplied: without remote stat/delete primitives, a
  local host sweep would inspect the wrong filesystem. Remote contexts rely
  on their own ephemeral teardown / storage quotas instead. Eviction failures
  (permissions, races) are surfaced through `ZIDANE_DEBUG` but never block
  the calling tool result; an over-cap dir is a housekeeping concern, not a
  correctness one.
- `output` (`string | ToolResultContent[]`): Result returned by the tool (post-`tool:transform`).
- `persistDir` (`string`): Persistence root directory. Created on first write.
- `shouldRethrowError?` (`(err: unknown) => boolean`): Write errors to rethrow instead of degrading to a stub: the loop passes
  its durable runtime's `isControlError`, so a control error
  (cancellation, suspension) from a routed write leaves the run as itself.
- `threshold` (`number`): Byte threshold; outputs at or below stay inline.
- `toolName` (`string`): Canonical tool name — checked against `excludeTools`.
- `writeBlob?` (`(path: string, content: string) => Promise<void>`): Optional writer that routes the blob through a specific filesystem. The
  agent loop passes `(path, content) => ctx.execution.writeFile(handle, …)`
  so the persisted blob lands on the SAME filesystem the model reads it back
  from (`read_file` → `ctx.execution.readFile`) — correct for docker /
  sandbox / remote / edge contexts, not only the host process.

  Omitted → falls back to a local atomic write (`<path>.tmp` + rename) on the
  host `fs`. A routed write is not atomic, which is
  immaterial here: the blob is written once and fully awaited BEFORE the stub
  that references it is emitted, so a crash mid-write loses both halves
  consistently — there is no torn-read window for a subsequent turn.

Source: [src/loop-persistence.ts:457](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L457)

### `PostCompactAttachments`

Interface.

Envelope returned by [`buildPostCompactAttachments`](https://zidane.si/docs/reference/index.md#buildPostCompactAttachments). The caller
spreads `turns` into `session.appendTurns([summaryTurn, ...turns])`.
Count fields drive UI banners ("restored 5 files + 2 skills").

```ts
interface PostCompactAttachments
```

**Properties**

- `estimatedTokens` (`number`): Rough total token cost of the restoration payload (sum of all content).
- `restoredFiles` (`number`): Count of files actually restored (post-budget).
- `restoredSkills` (`number`): Count of skills actually restored (post-budget).
- `turns` (`readonly SessionTurn[]`): Two synthetic turns when at least one item was restored, otherwise
  an empty array. The pair is `[assistant_with_tool_calls,
  user_with_tool_results]` — adjacent and well-formed for every
  provider's `tool_use ↔ tool_result` invariant.

Source: [src/compact/restore.ts:220](https://github.com/Tahul/zidane/blob/main/src/compact/restore.ts#L220)

### `PostCompactRestoreOptions`

Interface.

Options for [`buildPostCompactAttachments`](https://zidane.si/docs/reference/index.md#buildPostCompactAttachments).

```ts
interface PostCompactRestoreOptions
```

**Properties**

- `activeSkills?` (`readonly ActiveSkill[]`): Active skills to re-inject. Typically `agent.activeSkills`. Each entry
  yields a synthetic `skills_use` tool_call/tool_result pair carrying the
  skill's instructions (possibly truncated to the per-skill budget).
- `clock?` (`AgentClock`): Time + UUID source for the synthesized turns' `id` / `createdAt`.
  Defaults to [`DEFAULT_AGENT_CLOCK`](https://zidane.si/docs/reference/types.md#DEFAULT_AGENT_CLOCK) (`Date.now()` /
  `crypto.randomUUID()`). A replaying run passes the runtime's clock so
  the restoration turns are byte-identical on replay. The synthetic
  `tool_call`/`tool_result` `callId`s are already deterministic
  (`compact-restore-file-${i}`), so only the turn envelope needs the clock.
- `excludePaths?` (`readonly string[]`): Paths to skip — typically the file paths already covered by the
  compaction result's `preservedTurns`. Avoids double-injection when the
  recent reads sit in the preserved tail.
- `execution?` (`ExecutionContext`): Execution context used to fetch file content. **Required for file
  restoration.** Skills come pre-loaded (instructions live on the
  `SkillConfig`), so they don't need the context.
- `extraCalls?` (`readonly PostCompactExtraCall[]`): Other state to re-attach as synthetic tool call / result pairs, after
  the files and skills: a preset's `compact:restore` contributions (the
  applying plan as a `todoread` result). Not budgeted: callers keep them small.
- `fileTokenBudget?` (`number`): Total token budget for file restoration. Default: 50_000.
- `fileTokenPerFileCap?` (`number`): Per-file token cap. Default: 5_000.
- `handle?` (`ExecutionHandle`): Handle of the execution context. File restoration needs both `execution` and `handle`.
- `journal?` (`<T>(name: string, fn: () => Promise<T>) => Promise<T>`): Record the file reads as one step, so a replay restores the contents the
  live attempt read (and sent to the model), not the files as they are now.
  Absent: the reads just run.
- `maxFilesToRestore?` (`number`): Maximum file count. Default: 5.
- `readFileToolName?` (`string`): Canonical name of the file-read tool. Defaults to `read_file`. Aliases
  (e.g. `Read`) are NOT specified here — the agent loop's
  `rewriteMessagesToWire` handles wire conversion automatically.

  Override only when a host registered file-read under a different
  canonical name (not just an alias).
- `recentFiles?` (`readonly RecentFile[]`): Files to consider for restoration, ranked by recency. Typically derived
  via [`selectFilesFromReadState`](https://zidane.si/docs/reference/index.md#selectFilesFromReadState) from `getReadState(session)`.
  The helper takes the top `PostCompactRestoreOptions.maxFilesToRestore`
  by `mtimeMs` descending, fetches their current content, and synthesizes
  `read_file` tool_call/tool_result pairs.
- `runId?` (`string`): Optional `runId` to tag the synthetic turns with — useful for hosts
  that want the restoration turns to roll up under the same run as the
  compaction marker. Defaults to undefined (orphan turns).
- `shouldRethrowError?` (`(error: unknown) => boolean`): Errors matching this predicate are rethrown instead of being skipped as
  unreadable files. The agent loop passes its durable runtime's
  `isControlError`, so control errors (suspension, cancellation) escape.
- `signal?` (`AbortSignal`): Optional abort signal. Checked before each file read so a caller that
  bounds restoration (e.g. a host capping its compaction barrier) can stop
  the FS round-trips promptly instead of reading every candidate. File
  restoration already isolates per-file failures, so an abort mid-loop just
  returns whatever was gathered so far.
- `skillsUseToolName?` (`string`): Canonical name of the skill-activation tool. Defaults to `skills_use`.
  Same aliasing semantics as `readFileToolName`.
- `skillTokenBudget?` (`number`): Total token budget for skill restoration. Default: 25_000.
- `skillTokenPerSkillCap?` (`number`): Per-skill token cap. Default: 5_000.

Source: [src/compact/restore.ts:97](https://github.com/Tahul/zidane/blob/main/src/compact/restore.ts#L97)

### `ProviderLimit`

Interface.

A rate limit, spent quota or overload, as [`describeProviderLimit`](https://zidane.si/docs/reference/index.md#describeProviderLimit) words it.

```ts
interface ProviderLimit
```

**Properties**

- `provider` (`string`): Product the message names (`Claude`, `ChatGPT`, `OpenRouter`).
- `reason` (`ProviderLimitReason`): Which kind of limit: a rate limit, a spent quota or an overloaded provider.
- `resetsAt?` (`number`): When the limit resets, epoch ms; stamped by [`classifyProviderLimit`](https://zidane.si/docs/reference/index.md#classifyProviderLimit) from `retryAfterMs`.
- `retryAfterMs?` (`number`): Server-declared time until the limit resets.

Source: [src/errors.ts:38](https://github.com/Tahul/zidane/blob/main/src/errors.ts#L38)

### `PsRow`

Interface.

One OS process, as `ps` reports it.

```ts
interface PsRow
```

**Properties**

- `args` (`string`): The command line.
- `cpuSeconds` (`number`): CPU time used since it started (user + system), seconds.
- `pgid` (`number`): Its process group (`=== pid`: it leads one).
- `pid` (`number`): The process id.
- `ppid` (`number`): Its parent's process id.
- `rssKb` (`number`): Resident memory, KiB.

Source: [src/perf/ps.ts:13](https://github.com/Tahul/zidane/blob/main/src/perf/ps.ts#L13)

### `RecentFile`

Interface.

One file selected for restoration, with its last-read timestamp for ranking.

```ts
interface RecentFile
```

**Properties**

- `mtimeMs` (`number`): Wall-clock when the file was last read, in ms. Drives recency ranking.
- `path` (`string`): Path relative to the execution context's `handle.cwd`.

Source: [src/compact/restore.ts:79](https://github.com/Tahul/zidane/blob/main/src/compact/restore.ts#L79)

### `RemintResult`

Interface.

Result of [`remintDuplicateToolCallIds`](https://zidane.si/docs/reference/index.md#remintDuplicateToolCallIds).

```ts
interface RemintResult
```

**Properties**

- `content` (`SessionContentBlock[]`): Assistant content with matching `tool_call` block ids rewritten. Same reference when unchanged.
- `reminted` (`{ newId: string; oldId: string }[]`): One entry per re-minted occurrence, in emission order.
- `toolCalls` (`{ id: string; input: Record<string, unknown>; name: string }[]`): Tool calls with duplicate ids replaced. Same reference when unchanged.

Source: [src/session/messages-pairing.ts:365](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L365)

### `Ring`

Interface.

A fixed-capacity list that drops its oldest item when full.

```ts
interface Ring<T>
```

**Type parameters**

- `T`

**Properties**

- `clear` (`() => void`): Empties it.
- `items` (`() => T[]`): Oldest first.
- `last` (`() => T | undefined`): The newest item, if any.
- `push` (`(item: T) => void`): Adds an item, dropping the oldest when full.

Source: [src/perf/ring.ts:2](https://github.com/Tahul/zidane/blob/main/src/perf/ring.ts#L2)

### `RingBufferSink`

Interface.

Live handle over a [`createRingBufferSink`](https://zidane.si/docs/reference/index.md#createRingBufferSink) — the read side the logs viewer consumes.

```ts
interface RingBufferSink extends LogSink
```

**Properties**

- `emit` (`(record: LogRecord) => void`, from `LogSink`): Receives one record. Errors thrown here are swallowed by the logger.
- `getRecords` (`() => readonly LogRecord[]`): The buffered records, oldest first — the live array, so treat it as read-only. Bounded by `capacity`.
- `subscribe` (`(listener: () => void) => () => void`): Subscribe to appends. The callback fires after each retained record is
  pushed. Returns an unsubscribe fn. Used by the TUI logs viewer to
  re-render on new lines without polling.

Source: [src/logger.ts:218](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L218)

### `Sampler`

Interface.

A sampling loop that runs only while someone watches.

```ts
interface Sampler<T>
```

**Type parameters**

- `T`

**Properties**

- `active` (`() => boolean`): Whether the loop runs.
- `history` (`() => T[]`): The samples held, oldest first.
- `next` (`() => Promise<T>`): Resolves with the next sample, starting the loop for it if nobody watches.
- `subscribe` (`(listener: (sample: T) => void) => () => void`): Gets each sample from now on; the first subscriber starts the loop. Returns the unsubscribe.

Source: [src/perf/sampler.ts:31](https://github.com/Tahul/zidane/blob/main/src/perf/sampler.ts#L31)

### `SamplerOptions`

Interface.

What [`createSampler`](https://zidane.si/docs/reference/index.md#createSampler) samples, and how often.

```ts
interface SamplerOptions<T>
```

**Type parameters**

- `T`

**Properties**

- `capacity?` (`number`): Samples kept. Default [`SAMPLE_CAPACITY`](https://zidane.si/docs/reference/index.md#SAMPLE_CAPACITY).
- `collect` (`() => Promise<T>`): Takes one sample.
- `intervalMs?` (`number`): Between the end of one sample and the start of the next. Default [`SAMPLE_INTERVAL_MS`](https://zidane.si/docs/reference/index.md#SAMPLE_INTERVAL_MS).
- `onActive?` (`(active: boolean) => void`): Called when the loop starts and stops (the delay histogram, the windows' answers).
- `timers?` (`SamplerTimers`): The timer the loop waits on. Default real timers that never hold the process open.

Source: [src/perf/sampler.ts:17](https://github.com/Tahul/zidane/blob/main/src/perf/sampler.ts#L17)

### `Schedule`

Interface.

A stored schedule.

```ts
interface Schedule
```

**Properties**

- `action` (`ScheduleAction`): What a fire does: a prompt, or an extension handler.
- `catchUp` (`ScheduleCatchUp`): What a fire missed while no host ran does when a host comes back.
- `createdAt` (`number`): Made, epoch ms.
- `createdBy` (`ScheduleCreator`): Who made it: the user, the agent of a session, or an extension.
- `disabledReason?` (`string`): Why the host turned it off (its extension was removed, it expired). Cleared when you turn it on.
- `enabled` (`boolean`): Off: it never fires. Fires again from now when you turn it back on.
- `expiresAt?` (`number`): The host disables it after this time (epoch ms). Set on recurring schedules that the agent made.
- `id` (`string`): Schedule id.
- `lastFire?` (`ScheduleFire`): The last fire, for lists.
- `name?` (`string`): A short name for lists and the transcript. Absent: the start of the prompt or the handler name.
- `nextFireAt` (`number | null`): The next fire (epoch ms). `null`: none (a fired `at`, a cron with no next time, or disabled).
- `trigger` (`ScheduleTrigger`): When it fires.
- `updatedAt` (`number`): Last changed, epoch ms.

Source: [src/schedules/types.ts:101](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L101)

### `ScheduleFire`

Interface.

One fire of a schedule, newest first in `schedules.fires`.

```ts
interface ScheduleFire
```

**Properties**

- `dueAt` (`number`): The time the fire was due (epoch ms).
- `error?` (`string`): Why it failed.
- `firedAt` (`number`): The time it ran (epoch ms).
- `id` (`string`): Fire id.
- `late?` (`boolean`): It ran after a host was down past `dueAt`.
- `outcome` (`ScheduleFireOutcome`): What the fire did.
- `scheduleId` (`string`): The schedule that fired.
- `sessionId?` (`string`): The session the prompt went to (a `newSession` action: the session it created).

Source: [src/schedules/types.ts:81](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L81)

### `ScheduleInput`

Interface.

What `schedules.create` takes.

```ts
interface ScheduleInput
```

**Properties**

- `action` (`ScheduleAction`): What a fire does.
- `catchUp?` (`ScheduleCatchUp`): Absent: `once` for `at`, `skip` for `every` and `cron`.
- `enabled?` (`boolean`): Absent: `true`.
- `name?` (`string`): A short name for lists. Absent: the start of the prompt or the handler name.
- `trigger` (`ScheduleTrigger`): When it fires.

Source: [src/schedules/types.ts:131](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L131)

### `ScheduleListFilter`

Interface.

What `schedules.list` filters on.

```ts
interface ScheduleListFilter
```

**Properties**

- `createdBy?` (`'user' | 'extension' | 'agent' | { extension: string }`): Only the schedules of this creator kind, or of this extension.
- `sessionId?` (`string`): Only the schedules whose prompt goes to this session.

Source: [src/schedules/types.ts:161](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L161)

### `ScheduleNewSession`

Interface.

The session a `newSession` prompt action creates on each fire.

```ts
interface ScheduleNewSession
```

**Properties**

- `agentId?` (`string`): Agent profile id. Absent: the default.
- `cwd` (`string`): Working folder of the session. `''`: a chat without a folder.

Source: [src/schedules/types.ts:55](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L55)

### `SchedulePatch`

Interface.

What `schedules.update` takes: the fields to change. `expiresAt: null` keeps a schedule for good (you pinned it).

```ts
interface SchedulePatch
```

**Properties**

- `action?` (`ScheduleAction`): A new action.
- `catchUp?` (`ScheduleCatchUp`): A new catch-up rule.
- `enabled?` (`boolean`): On or off. Turning it on counts the next fire from now.
- `expiresAt?` (`null`): `null`: keep it for good (no expiry).
- `name?` (`string | null`): A new name; `null` clears it.
- `trigger?` (`ScheduleTrigger`): A new trigger: the next fire counts from now.

Source: [src/schedules/types.ts:145](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L145)

### `SessionArtifactDirMigration`

Interface.

Outcome of one [`migrateSessionArtifactDirs`](https://zidane.si/docs/reference/index.md#migrateSessionArtifactDirs) sweep.

```ts
interface SessionArtifactDirMigration
```

**Properties**

- `failed` (`number`): Relocations that failed (rename raced, permissions, target existed).
- `moved` (`number`): Artifact dirs relocated into their session subtree.
- `removed` (`number`): Emptied source shells removed (pre-6.x `<sessionId>/`, kind-first roots).

Source: [src/loop-persistence.ts:286](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L286)

### `SessionPid`

Interface.

One process started for a session, as `daemon.sessionProcesses` lists it.

```ts
interface SessionPid
```

**Properties**

- `pid` (`number`): The process id.
- `sessionId` (`string`): The session's id on its host.

Source: [src/perf/owned.ts:27](https://github.com/Tahul/zidane/blob/main/src/perf/owned.ts#L27)

### `SkillEditMarker`

Interface.

Per-edit-session marker persisted on `session.metadata[SKILL_EDIT_METADATA_KEY]`.

```ts
interface SkillEditMarker
```

**Properties**

- `dir` (`string`): Absolute path to the skill's directory (the session's cwd).
- `name` (`string`): The skill's name (frontmatter-first, as discovered).

Source: [src/extension-authoring.ts:63](https://github.com/Tahul/zidane/blob/main/src/extension-authoring.ts#L63)

### `Span`

Interface.

Minimal span shape — any tracer that provides these methods is compatible.

```ts
interface Span
```

**Properties**

- `addEvent?` (`(name: string, attrs?: Record<string, unknown>) => void`): Optional: record a structured event on the span. Used for non-span
  occurrences (gate blocks, validation rejects, budget hits, pairing
  repairs). Maps to OTel's `Span.addEvent` and Sentry's `addBreadcrumb`.
  Tracers without an event surface should treat this as a no-op (the
  helper falls back to `setAttributes` with an `event.*` key prefix).
- `end` (`() => void`): Close the span. Called exactly once per span.
- `setAttributes?` (`(attrs: Record<string, unknown>) => void`): Optional: attach additional attributes after the span is started (ignored if unsupported).

Source: [src/tracing.ts:69](https://github.com/Tahul/zidane/blob/main/src/tracing.ts#L69)

### `SpawnQueuedContext`

Interface.

`spawn:queued`: a top-level `spawn` call waiting for a free slot.

```ts
interface SpawnQueuedContext
```

**Properties**

- `callId?` (`string`): The waiting `spawn` call's id (see `SpawnHookContext.callId`).
- `depth` (`number`): The depth its child will run at (1: the top-level agent's child).
- `task` (`string`): Task of the waiting `spawn` call.
- `waitingFor` (`{ active: number; max: number }`): The slots taken and the cap, when the call started waiting.

Source: [src/types.ts:3854](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3854)

### `SqliteDatabaseLike`

Interface.

What [`createSqliteDriver`](https://zidane.si/docs/reference/index.md#createSqliteDriver) wraps: a `bun:sqlite` `Database` or a `node:sqlite` `DatabaseSync`.

```ts
interface SqliteDatabaseLike
```

**Properties**

- `close` (`() => unknown`): Close the handle.
- `exec` (`(sql: string) => unknown`): Run `sql`, which may hold several statements.
- `prepare` (`(sql: string) => { all: (...p: never[]) => unknown[]; get: (...p: never[]) => unknown; run: (...p: never[]) => unknown }`): Compile `sql` into a statement.

Source: [src/session/sqlite-driver.ts:36](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L36)

### `SqliteDriver`

Interface.

The connection surface the session store needs.

```ts
interface SqliteDriver
```

**Properties**

- `close` (`() => void`): Close the connection. Statements prepared from it are unusable afterwards.
- `exec` (`(sql: string) => void`): Run one statement that returns no rows (DDL, PRAGMA, BEGIN/COMMIT).
- `immediate` (`<T>(fn: () => T) => T`): Run `fn` in `BEGIN IMMEDIATE` … `COMMIT`; a throw rolls back. Does not nest.
- `prepare` (`(sql: string) => SqliteStatement`): A prepared statement for `sql`, from a bounded per-connection cache.

Source: [src/session/sqlite-driver.ts:24](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L24)

### `SqliteSessionStoreOptions`

Interface.

Options for [`createSqliteSessionStore`](https://zidane.si/docs/reference/index.md#createSqliteSessionStore).

```ts
interface SqliteSessionStoreOptions
```

**Properties**

- `path` (`string`): Path of the database file: named in migration messages, used for the v3 → v4 backup.
- `writes?` (`SqliteWriteQueue`): The connection's write queue. Pass it when other code writes on the same connection, so all writes share one order.

Source: [src/session/sqlite-store.ts:82](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-store.ts#L82)

### `SqliteStatement`

Interface.

A prepared statement. `get` returns `undefined` when no row matches.

```ts
interface SqliteStatement
```

**Properties**

- `all` (`(...params: SqlValue[]) => unknown[]`): Every row for `params`.
- `get` (`(...params: SqlValue[]) => unknown`): The first row for `params`, or `undefined`.
- `run` (`(...params: SqlValue[]) => unknown`): Execute with `params` bound; the result is the driver's run info.

Source: [src/session/sqlite-driver.ts:14](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L14)

### `SqliteStoreFile`

Interface.

The file behind a SQLite store, for readers on their own connection (`sqliteStoreFile`).

```ts
interface SqliteStoreFile
```

**Properties**

- `path` (`string`): Path of the database file.
- `settled` (`() => Promise<void> | undefined`): Settles once no write of this connection is waiting (`SqliteWriteQueue.pending`): another connection then sees them.

Source: [src/session/sqlite-store.ts:28](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-store.ts#L28)

### `SqliteWriteQueue`

Interface.

Serializes a connection's writes and retries SQLITE_BUSY on timers.

```ts
interface SqliteWriteQueue
```

**Properties**

- `pending` (`() => Promise<void> | undefined`): Settles once no write is waiting; `undefined` when none is. Reads await it to see their own writes.
- `run` (`<T>(fn: () => T) => Promise<T>`): Run a write. The fast path is synchronous (same timing as a direct
  call). On SQLITE_BUSY the write backs off on timers instead of sleeping
  in SQLite, and every write issued meanwhile queues behind it, so appends
  keep their order and a full save can't overtake a pending append.
- `runLowPriority` (`(fn: () => void) => Promise<boolean>`): Run a write at the lowest priority (a stream partial): only when no
  write is queued, and never queued itself. It is skipped (resolves
  `false`) when a write is already waiting, or when it meets another
  process's lock: then no retry holds the queue, so a commit issued after
  it never waits behind it. The caller keeps what it could not write for
  its next attempt.

Source: [src/session/sqlite-driver.ts:148](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L148)

### `StandardSchemaLike`

Interface.

Structural stand-in for a Standard Schema (zod v4 et al.) — enough surface
to detect the vendor and infer the output type WITHOUT importing zod's
types into our public API.

```ts
interface StandardSchemaLike<Output = unknown>
```

**Type parameters**

- `Output` (default `unknown`)

**Properties**

- `~standard` (`{ readonly types?: { readonly output: Output }; readonly vendor: string; readonly version: number }`, readonly): Vendor metadata of the Standard Schema.

Source: [src/zod.ts:23](https://github.com/Tahul/zidane/blob/main/src/zod.ts#L23)

### `StepThinkingDecay`

Interface.

Single-step thinking-budget taper: full budget through `afterTurn`, then
`floor` for the remainder of the run.

Exactly ONE budget change per run, so exactly one prompt-cache invalidation
— the cache-aware schedule. Distinguished from
[`GeometricThinkingDecay`](https://zidane.si/docs/reference/index.md#GeometricThinkingDecay) by the absence of `factor`.

```ts
interface StepThinkingDecay
```

**Properties**

- `afterTurn` (`number`): Last turn that gets the full thinking budget.
- `factor?` (`undefined`): Always absent. Distinguishes this schedule from [`GeometricThinkingDecay`](https://zidane.si/docs/reference/index.md#GeometricThinkingDecay).
- `floor` (`number`): Thinking budget used after `afterTurn`.

Source: [src/types.ts:809](https://github.com/Tahul/zidane/blob/main/src/types.ts#L809)

### `StreamProgressHookContext`

Interface.

Fired (throttled) while a parent turn streams, then once more unthrottled
right before `stream:end`. Drives live footer counters: tokens streamed so
far and a running price for the turn. `turn:after` is the settle point —
its `usage.cost` REPLACES `estCostUsd`, it never adds to it.

```ts
interface StreamProgressHookContext extends StreamHookContext
```

**Properties**

- `cacheCreation?` (`number`): Cache-creation tokens, when the provider reported them mid-stream.
- `cacheRead?` (`number`): Cache-read tokens, when the provider reported them mid-stream.
- `elapsedMs` (`number`): Wall-clock since the provider stream opened.
- `estCostUsd?` (`number`): Running USD estimate for THIS turn at catalog rates. Absent when the model
  has no rate, or the provider flagged the traffic as flat-rate. The input
  side is the provider's mid-stream figure when it sent one, otherwise the
  previous assistant turn's prompt split as a proxy (the first turn of a
  session prices output only until it settles).
- `estimated` (`boolean`): `true` when `outputTokens` is the character heuristic, not a provider count.
- `inputTokens?` (`number`): Prompt-side figures when the provider reported them mid-stream.
- `outputTokens` (`number`): Output tokens so far — provider-reported when available, else chars ÷ 4.
- `turnId` (`string`, from `StreamHookContext`): Id of the turn that is streaming.

Source: [src/types.ts:3997](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3997)

### `StreamUsageSnapshot`

Interface.

Cumulative in-flight usage a provider can surface mid-stream via
`StreamCallbacks.onUsage`. Every field is the running total so far, never
a delta; the loop keeps only the latest snapshot. Anthropic reports the
prompt side on `message_start` and the output count only in the final
`message_delta`; providers without mid-stream accounting never call it.
Every field is optional: omit `outputTokens` when the wire hasn't counted
it yet and the loop keeps its character estimate moving instead of
freezing the counter on a placeholder.

```ts
interface StreamUsageSnapshot
```

**Properties**

- `billable?` (`boolean`): `false` when the provider knows the traffic is flat-rate (subscription
  OAuth): the loop then reports tokens without a price, matching the
  turn-level rule that `usage.cost` stays absent on such turns.
- `cacheCreation?` (`number`): Cache-creation tokens counted so far.
- `cacheRead?` (`number`): Cache-read tokens counted so far.
- `inputTokens?` (`number`): Input tokens counted so far.
- `outputTokens?` (`number`): Output tokens counted so far.

Source: [src/types.ts:3974](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3974)

### `SummaryToTurnInput`

Interface.

Input shape for [`summaryToTurn`](https://zidane.si/docs/reference/index.md#summaryToTurn). Designed to align with the
fields of `CompactResult` so a caller can spread the runner's output
with a single `replacesTurnIds` rename — no field-by-field unpacking
required.

Primitive shape (no `CompactResult` import) keeps this module free of
dependencies on the runner — `compact.ts` imports from here, not the
other way around.

```ts
interface SummaryToTurnInput
```

**Properties**

- `compactedAt?` (`number`): Defaults to `Date.now()` when omitted.
- `id?` (`string`): Turn id. Defaults to `crypto.randomUUID()`. A replaying run passes an
  id from its runtime's clock so the marker turn is byte-identical on
  replay; pair it with a `compactedAt` from the same clock.
- `model` (`string`): Model id that produced the summary.
- `replacesTurnIds` (`readonly string[]`): Turn ids being replaced — typically `CompactResult.summarizedTurnIds`.
- `summary` (`string`): Summary text — typically `CompactResult.summary`.
- `usage` (`TurnUsage`): Token usage from the summary call.

Source: [src/compact/messages.ts:424](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L424)

### `SystemFreezeOptions`

Interface.

See `AgentRunOptions.systemFreeze`.

```ts
interface SystemFreezeOptions
```

**Properties**

- `notes?` (`(fresh: string, sections: FrozenPromptSections) => readonly (SystemNote & { text: string })[] | Promise<readonly (SystemNote & { text: string })[]>`): Notes announcing how the fresh prompt (and the sections the SDK appended to it) differs from the frozen one. Called only when the run sends a frozen prompt.
- `onCapture?` (`(fresh: string, sections: FrozenPromptSections) => void | Promise<void>`): Called with the run's fresh system prompt, and the sections the SDK appended to it, when the run sends the fresh prompt.
- `system?` (`string | ((fresh: string, sections: FrozenPromptSections) => string | undefined)`): The frozen system prompt, sent verbatim. As a function, it receives the
  run's fresh prompt and the sections the SDK appended to it, and returns
  the prompt to send, or `undefined` to send the fresh one (for instance
  when the host's own base prompt changed and the frozen text is stale).

Source: [src/types.ts:2980](https://github.com/Tahul/zidane/blob/main/src/types.ts#L2980)

### `SystemPromptSnapshot`

Interface.

A frozen system prompt's bookkeeping, carried by a `role: 'system'` turn
(see `SessionTurn.systemSnapshot`).

```ts
interface SystemPromptSnapshot
```

**Properties**

- `cleared?` (`boolean`): No prompt is frozen for `key` from this turn on (for every key when `key` is omitted): the next run captures a fresh one.
- `digests` (`Record<string, string>`): Digest of each section the host tracks, by section kind (`'skills'`, `'tools'`, `'mcp'`, plus the host's own).
- `effort?` (`'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'adaptive'`): Thinking level of the run that captured the prompt.
- `host?` (`Record<string, unknown>`): Host data stored with the snapshot; the SDK never reads it.
- `key?` (`string`): Which composition the prompt belongs to (a host profile id, an agent name…). Omitted: the conversation's only one.
- `v` (`1`): Format version of the snapshot record.

Source: [src/types.ts:3222](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3222)

### `TokenUsageLike`

Interface.

Common shape for token-usage helpers. Mirrors `AgentStats`'s cumulative
fields. Callers working with `TurnUsage` / `SessionRun.totalUsage`
(`input` / `output` / `cacheRead` / `cacheCreation`) map their fields in
at the call site — we don't accept both shapes here because
`AgentStats.output` is a structured-output payload (`Record<string,
unknown>`), not a token count, so the field name `output` is ambiguous.

```ts
interface TokenUsageLike
```

**Properties**

- `totalCacheCreation?` (`number`): Cumulative tokens written to the prompt cache.
- `totalCacheRead?` (`number`): Cumulative tokens read from the prompt cache.
- `totalIn?` (`number`): Cumulative input tokens, excluding cache tokens.
- `totalOut?` (`number`): Cumulative output tokens.

Source: [src/stats.ts:56](https://github.com/Tahul/zidane/blob/main/src/stats.ts#L56)

### `ToolGateResumeFields`

Interface.

What `tool:gate` carries for a call of a resumed checkpoint run. See `AgentHooks['tool:gate']`.

```ts
interface ToolGateResumeFields
```

**Properties**

- `resumed?` (`true`): The call passed the gate in a process that died: restore, don't ask. Its `result` is ignored, and its `block` too unless the call's body runs again (a safe call cut off, or a call with no step of its own).
- `resumeState?` (`Record<string, JsonValue>`): Per-call state the gate's handlers keep with the call's step record, by
  handler key: write it on a live call, read it back on a `resumed` one.
  Set by the loop on every call of a run that records steps, except the
  calls a replay-mode batch joins. Only a resumed checkpoint run reads it back.

Source: [src/agent-hooks.ts:25](https://github.com/Tahul/zidane/blob/main/src/agent-hooks.ts#L25)

### `ToolProgress`

Interface.

Live output a running tool reports through `ToolContext.reportProgress`, as
the `tool:progress` hook. It never reaches the model or the session: the
tool's result is unchanged.

```ts
interface ToolProgress
```

**Properties**

- `line?` (`number`): `wait`: the script line that waits.
- `stream` (`'output' | 'wait' | 'console' | 'stdout' | 'stderr'`): `output` and `console`: an item a codemode script printed (`text()`,
  `console.*`). `stdout` and `stderr`: a chunk of a running command.
- `text` (`string`): The new text. A chunk of a command can end mid-line. Empty for `wait`.
- `waitMs?` (`number`): `wait`: a codemode script's `sleep(ms)` started (`ms` > 0) or ended (0).

Source: [src/types.ts:2502](https://github.com/Tahul/zidane/blob/main/src/types.ts#L2502)

### `TracingHookSet`

Interface.

Value returned by [`createTracingHooks`](https://zidane.si/docs/reference/index.md#createTracingHooks) — install entrypoint.

```ts
interface TracingHookSet
```

**Properties**

- `install` (`(hooks: Hookable<AgentHooks>) => () => void`): Attach every hook handler to the given agent hooks instance.

Source: [src/tracing.ts:206](https://github.com/Tahul/zidane/blob/main/src/tracing.ts#L206)

### `TracingHooksOptions`

Interface.

Options for [`createTracingHooks`](https://zidane.si/docs/reference/index.md#createTracingHooks).

```ts
interface TracingHooksOptions
```

**Properties**

- `captureMessageContent?` (`boolean`): Capture the actual prompt / completion text on spans
  (`gen_ai.input.messages`, `gen_ai.output.messages`,
  `gen_ai.system_instructions`, `gen_ai.tool.definitions`,
  `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`).
  `gen_ai.input.messages` keeps the newest messages that fit in 128 KB;
  `gen_ai.agent.input_messages_dropped` counts the older ones left out.

  Defaults to `true` (required for the Sentry AI Agents conversation
  viewer). Full prompts and tool arguments can carry secrets and PII;
  captured content flows through `redact`, so pair the default with a
  redactor when payloads may hold secrets, or set `false` to keep all
  content-shaped data in-process.
- `conventions?` (`TracingConventions`): Which Gen-AI attribute conventions to emit.

  - `'sentry'` (default) — Sentry AI Agents conventions. Most common
    choice — Sentry, Datadog AI, Honeycomb derived dashboards and
    Langfuse all consume these.
  - `'otel'` — vendor-neutral OpenTelemetry Gen AI semconv v1.36.
    Diverges from Sentry on cache-token keys, cost keys, and TTFT unit.
  - `'both'` — emit every variant. Doubles the per-span attribute
    payload; pick when shipping to multiple backends with different
    ingestion conventions.
- `getActiveTraceContext?` (`() => Readonly<Record<string, string>> | undefined`): Optional callback the helper invokes on `spawn:before` (after opening
  the spawn span) to read the active trace context. Whatever it returns
  is written into `ctx.tracingContext` and forwarded to the child's
  `agent.run({ tracingContext })`. Typical use:

  ```ts
  getActiveTraceContext: () => {
    const carrier: Record<string, string> = {}
    propagation.inject(context.active(), carrier)
    return carrier
  }
  ```

  Returning `undefined` or an empty object leaves the carrier empty
  and the child runs with no parent context. The helper's own
  `propagator` is preferred over this when both are set (the
  propagator runs inside the helper; this callback is the escape
  hatch for hosts wanting full control).
- `interceptors?` (`Pick<InterceptorRegistry, 'has' | 'runInterceptorsSync'>`): The extension interceptors whose `tracing.redact` chain runs after
  `redact`. Default: those of the agent whose hooks `install` gets
  (`AgentOptions.extensionRuntime`); none for an agent without an extension runtime.
- `legacyAttributes?` (`boolean`): Emit legacy attribute keys (`inputTokens`, `outputTokens`, `toolName`,
  `displayName`, `finishReason`, `modelId`) alongside the new
  `gen_ai.*` semconv keys. Defaults to `true` so existing dashboards
  keep working. Set `false` once you've migrated all consumers off the
  legacy names.
- `namespace?` (`string`): Optional attribute namespace. Prepended to every span name with a `/`
  separator (e.g. `"agent"` → `agent/chat <model>`, `agent/execute_tool Bash`).

  Empty / undefined = no prefix.
- `onError?` (`(kind: string, err: unknown) => void`): Error sink for tracer failures. Without it, tracer failures are swallowed
  silently. Called when `Span.end()`, `setAttributes()`, `addEvent()`, or
  `startSpan()` throws — so degraded tracers stay visible. The helper
  still does not let tracer errors propagate into the agent loop.

  `kind` identifies which step failed (`'startSpan'`, `'end'`,
  `'setAttributes'`, `'addEvent'`, `'redact'`, `'getActiveTraceContext'`).
  Default: no-op (silent).
- `redact?` (`(kind: string, value: string, meta?: Readonly<Record<string, unknown>>) => string`): Optional in-process span redactor. When set, every potentially
  sensitive string (tool input, tool result, system prompt) flows
  through this fn before landing on a span attribute / event. Returning
  the input unchanged is a no-op.

  Composes with the harness-wide `tracing:redact` hook: if a host has
  already registered a hook handler that mutates `ctx.redacted`, the
  tracer reuses that pipeline; setting `redact` here registers an extra
  step that runs only for the tracer's attributes. The hook is the
  canonical path; `redact` is the convenience surface for tracer-only
  setups.
- `startSpan` (`StartSpan`): Tracer seam. Receives a span name + attributes; must return a `Span`.

Source: [src/tracing.ts:105](https://github.com/Tahul/zidane/blob/main/src/tracing.ts#L105)

### `TreeInput`

Interface.

What [`treeProcesses`](https://zidane.si/docs/reference/index.md#treeProcesses) turns into rows.

```ts
interface TreeInput
```

**Properties**

- `hosts` (`ReadonlySet<number>`): The host's own processes: a group leader started directly under one is launched work, unless owned.
- `listed?` (`ReadonlySet<number>`): Rows another source lists (the desktop app's Electron processes): their CPU baseline is kept, no row is made.
- `mcp?` (`ReadonlyMap<number, PerfProcessMcp>`): The MCP server each MCP process runs, by pid (`./owned.ts`).
- `now` (`number`): When the rows were read (epoch ms): the CPU's time base.
- `owned` (`ReadonlySet<number>`): The pids Zidane started for its own work (MCP servers, tool runs): never launched, though they lead a group.
- `previous` (`CpuMemory`): Read and updated: the rows' CPU seconds (rows seen now are kept, rows gone are dropped).
- `roots` (`ReadonlyMap<number, TreeRoot>`): The rows shown as roots (no parent), with their kind and label.
- `sessions?` (`ReadonlyMap<number, PerfProcessSession>`): The session each process a session started runs for, by pid: it and its subtree carry it.
- `tree` (`readonly PsRow[]`): The OS rows under the roots (`descendants`), roots included, parents first.

Source: [src/perf/processes.ts:44](https://github.com/Tahul/zidane/blob/main/src/perf/processes.ts#L44)

### `TreeRoot`

Interface.

How a tree's root shows: a host process (the daemon, a server).

```ts
interface TreeRoot
```

**Properties**

- `kind` (`PerfProcessKind`): What the root process is.
- `label` (`string`): Its row's name: "Daemon", "Server".

Source: [src/perf/processes.ts:36](https://github.com/Tahul/zidane/blob/main/src/perf/processes.ts#L36)

### `UpDownCounter`

Interface.

Instrument whose value can go up and down.

```ts
interface UpDownCounter
```

**Properties**

- `add` (`(value: number, attributes?: MetricAttributes) => void`): Adds a positive or negative `value`, with optional attributes.

Source: [src/metrics.ts:78](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L78)

### `UsageAssistantDayRow`

Interface.

One model's usage on one day (assistant turns and compaction summaries).

```ts
interface UsageAssistantDayRow
```

**Properties**

- `cacheCreation` (`number`): Tokens written to the prompt cache.
- `cacheRead` (`number`): Tokens read from the prompt cache.
- `cost` (`number`): USD.
- `day` (`string`): Local `YYYY-MM-DD`.
- `input` (`number`): Prompt tokens, cache excluded.
- `model` (`string`): The model id the usage names; `unknown` when none.
- `output` (`number`): Output tokens.
- `project` (`string`): The session's project root (`sessions.project_root`); `''` for a session without one.
- `turns` (`number`): Assistant turns (compaction summaries count none).

Source: [src/session/sqlite-usage.ts:17](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L17)

### `UsageBuckets`

Interface.

The three per-day aggregates of a sessions database, split by project
(`sessions.project_root`) so one scan serves every project's summary
and the global one (`summarizeUsage`'s `projectRoot`).

```ts
interface UsageBuckets
```

**Properties**

- `assistant` (`UsageAssistantDayRow[]`): Per day × model.
- `sessions` (`UsageSessionDayRow[]`): Per day.
- `user` (`UsageUserDayRow[]`): Per day × hour.

Source: [src/session/sqlite-usage.ts:65](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L65)

### `UsageSessionDayRow`

Interface.

Sessions created on one day.

```ts
interface UsageSessionDayRow
```

**Properties**

- `day` (`string`): Local `YYYY-MM-DD`.
- `project` (`string`): The project root they were created in; `''` without one.
- `sessions` (`number`): Sessions created that day.

Source: [src/session/sqlite-usage.ts:51](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L51)

### `UsageUserDayRow`

Interface.

Human messages in one hour of one day.

```ts
interface UsageUserDayRow
```

**Properties**

- `day` (`string`): Local `YYYY-MM-DD`.
- `hour` (`number`): Local hour, 0-23.
- `messages` (`number`): Parent-run user turns.
- `project` (`string`): The session's project root; `''` without one.

Source: [src/session/sqlite-usage.ts:39](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-usage.ts#L39)

## Types

### `AgentCompactResult`

Type.

Result of `Agent.compact`.

```ts
type AgentCompactResult =
  | { compacted: true; droppedCount: number; effectiveTokens: number; model: string; replacedCount: number; restoredFiles: number; restoredSkills: number; summaryTurnId: string; usage: TurnUsage }
  | { compacted: false; reason: 'nothing-to-compact' | 'no-session' | 'aborted' }
```

Source: [src/agent-types.ts:429](https://github.com/Tahul/zidane/blob/main/src/agent-types.ts#L429)

### `AutoCompact`

Type.

`AgentBehavior.autoCompact` value: `true` enables loop-native
auto-compaction with defaults, `false` / omitted disables it, and an
[`AutoCompactConfig`](https://zidane.si/docs/reference/index.md#AutoCompactConfig) enables it with overrides.

```ts
type AutoCompact = boolean | AutoCompactConfig
```

Source: [src/types.ts:549](https://github.com/Tahul/zidane/blob/main/src/types.ts#L549)

### `AutoCompactDecision`

Type.

Result of [`shouldAutoCompact`](https://zidane.si/docs/reference/index.md#shouldAutoCompact): `fire` with the usage figures, or `skip` with the reason.

```ts
type AutoCompactDecision =
  | { effectiveWindow: number; kind: 'fire'; usedFraction: number }
  | { kind: 'skip'; reason: 'disabled' | 'unknown-window' | 'invalid-threshold' | 'invalid-input-tokens' | 'under-threshold' | 'already-compacting' | 'cooldown' }
```

Source: [src/compact/policy.ts:118](https://github.com/Tahul/zidane/blob/main/src/compact/policy.ts#L118)

### `CacheTtl`

Type.

Prompt-cache entry lifetime. See `AgentBehavior.cacheTtl`.

```ts
type CacheTtl = '5m' | '1h'
```

Source: [src/types.ts:780](https://github.com/Tahul/zidane/blob/main/src/types.ts#L780)

### `ChildSpawnHookContext`

Type.

Payload of `child:spawn:before` / `child:spawn:error`: the spawned agent's
[`SpawnHookContext`](https://zidane.si/docs/reference/types.md#SpawnHookContext) plus [`ChildSpawnIdentity`](https://zidane.si/docs/reference/index.md#ChildSpawnIdentity), minus the
mutable `tracingContext` carrier. Trace propagation into a nested child
is owned by its spawner's own tracer (the one listening on the spawner's
bus, which knows the spawner's active span); a root tracer writing into
the carrier would re-parent the grandchild under the ROOT's ambient span
and race the spawner's injection — so the bubbled copy carries none.

```ts
type ChildSpawnHookContext = Omit<SpawnHookContext, 'tracingContext'> & ChildSpawnIdentity
```

Source: [src/types.ts:3956](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3956)

### `CompactDirection`

Type.

Identifier for the section of the conversation being summarized.

```ts
type CompactDirection = 'full' | 'tail' | 'from' | 'up_to'
```

Source: [src/compact/prompt.ts:18](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L18)

### `CompactEndEvent`

Type.

Payload for `CompactOptions.onEnd`: the result on success, or the thrown error with the elapsed time on failure.

```ts
type CompactEndEvent =
  | { durationMs: number; result: CompactResult; status: 'success' }
  | { durationMs: number; error: unknown; status: 'error' }
```

Source: [src/compact/compact.ts:195](https://github.com/Tahul/zidane/blob/main/src/compact/compact.ts#L195)

### `CompactEndHookContext`

Type.

Fired exactly once after a `compact:start`, on every outcome. `status`
discriminates success (carries the result counts + post-compact size
estimate hosts use to refresh their context indicator) from failure.

```ts
type CompactEndHookContext = CompactHookContext & ({ droppedCount: number; durationMs: number; effectiveTokens: number; replacedCount: number; restoredFiles: number; restoredSkills: number; status: 'success'; summaryModel: string } | { durationMs: number; error: unknown; status: 'error' })
```

Source: [src/types.ts:4116](https://github.com/Tahul/zidane/blob/main/src/types.ts#L4116)

### `CompactFunction`

Type.

Pluggable client-side context compactor — see
`AgentBehavior.compactStrategy`. The loop invokes this in place
of the built-in tail elision when `compactStrategy` is a function.

Contract:

- Operates on the wire-level message list — the post-alias / post-
  sanitize / post-`context:transform` view the provider will see.
  The framework treats the returned array as the new wire payload;
  `ctx.session` / `ctx.turns` are never modified.
- Must preserve `tool_use ↔ tool_result` adjacency. Stranding a
  `tool_use` without its matching `tool_result` (or vice versa) will
  trip the loop's pair-repair pass and either repair the violation
  or throw (`strictToolPairing`).
- The trailing user message must remain — providers reject
  assistant-tail wire payloads. If unsure, leave the last user turn
  intact and operate on the prefix only.
- May return the input verbatim (e.g. when the total stays under the
  host's threshold).
- Sync or async. The loop awaits the result, so a long-running LLM
  summarizer will block the next turn — keep latency in mind.

`ctx.threshold` and `ctx.keepTurns` are forwarded from
`behavior.compactThreshold` / `behavior.compactKeepTurns` so hosts
can reuse the same knobs the built-in tail mode uses.
`ctx.totalBytes` is the pre-compaction total — the same number the
tail mode uses to gate its threshold check, exposed so the function
can short-circuit on under-threshold inputs without recomputing.

```ts
type CompactFunction = (messages: SessionMessage[], ctx: { keepTurns: number; threshold: number; totalBytes: number }) => SessionMessage[] | Promise<SessionMessage[]>
```

Source: [src/types.ts:438](https://github.com/Tahul/zidane/blob/main/src/types.ts#L438)

### `CompactPromptBuilder`

Type.

Function shape for callers that want to swap in a domain-specific
summary prompt (security review handoff, support-ticket continuation,
etc.) without touching the runner. Default: [`buildCompactPrompt`](https://zidane.si/docs/reference/index.md#buildCompactPrompt).

```ts
type CompactPromptBuilder = (opts: CompactPromptOptions) => string
```

Source: [src/compact/prompt.ts:38](https://github.com/Tahul/zidane/blob/main/src/compact/prompt.ts#L38)

### `CompactScope`

Type.

What to summarize and what to preserve verbatim.

- `'full'`         — summarize everything, no preserved tail.
- `'tail'`         — summarize everything before the last `keepTurns` turns.
- `{ kind: 'from',  turnId }` — summarize from the anchor turn onward.
- `{ kind: 'up_to', turnId }` — summarize up to (and including) the anchor.

```ts
type CompactScope =
  | 'full'
  | 'tail'
  | { kind: 'from'; turnId: string }
  | { kind: 'up_to'; turnId: string }
```

Source: [src/compact/messages.ts:27](https://github.com/Tahul/zidane/blob/main/src/compact/messages.ts#L27)

### `CpuMemory`

Type.

CPU seconds per pid at the previous sample, for the rows' CPU.

```ts
type CpuMemory = Map<number, { at: number; cpuSeconds: number }>
```

Source: [src/perf/processes.ts:33](https://github.com/Tahul/zidane/blob/main/src/perf/processes.ts#L33)

### `DecisionAnswerFor`

Type.

Answer type for one question, refusal included.

```ts
type DecisionAnswerFor<Q extends DecisionQuestion> = 
  | (Q extends DecisionPredicateQuestion ? DecisionPredicateAnswer : Q extends DecisionChoiceQuestion ? DecisionChoiceAnswer<ChoiceValues<Q>> : DecisionScoreAnswer)
  | DecisionRefusalAnswer
```

**Type parameters**

- `Q` (`extends DecisionQuestion`)

Source: [src/decisions/types.ts:113](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L113)

### `DecisionInputKind`

Type.

Shape of a decision input as reported to hooks: plain text, a JSON object, or prompt parts.

```ts
type DecisionInputKind = 'text' | 'json' | 'parts'
```

Source: [src/decisions/types.ts:248](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L248)

### `DecisionScoreLevel`

Type.

One ordered level of a score rubric: a bare label, or a label with criteria.

```ts
type DecisionScoreLevel = string | { description?: string; label: string }
```

Source: [src/decisions/types.ts:37](https://github.com/Tahul/zidane/blob/main/src/decisions/types.ts#L37)

### `DedupHasher`

Type.

Per-tool argument hasher used by `AgentBehavior.dedupTools`.

Returning a non-empty string activates dedup with that string as the
cache key. Returning `undefined` (or `''` / non-string) opts THIS call
out — the tool runs normally and no state is recorded. See
`dedupTools` for the full contract.

```ts
type DedupHasher = (input: Record<string, unknown>) => string | undefined
```

Source: [src/types.ts:401](https://github.com/Tahul/zidane/blob/main/src/types.ts#L401)

### `DedupToolConfig`

Type.

Per-tool dedup configuration. Two equivalent forms:

- **Hasher only**: a bare function. The framework runs
  in `'replay'` mode — identical re-calls replay the prior result.
- **Config object**: explicit `hasher` plus a `mode`:
  - `'replay'` (default) — replay the cached result on identical re-
    calls. Cheap loop, but doesn't BREAK the loop — the model keeps
    seeing the same tool_result and keeps trying.
  - `'block-after'` — replay identical calls until the total count
    reaches `threshold`, then refuse with `Blocked: <reason>` via
    `tool:gate`. Designed to
    break tight loops where the model fixates on a single failing
    call. The block lands on the Nth identical call (i.e. once the
    total count reaches `threshold`); the cap is sticky — every
    subsequent identical call also blocks until a different input
    resets the counter.

`reason` is the model-visible refusal text. The framework formats the
final tool_result as `Blocked: <reason>` (see `tool:gate` docs).
Strings are used verbatim; the callback form receives the input and
the (now-blocking) repeat count so it can produce per-invocation
messaging like `Blocked: 4 identical "shell" calls — try a different
approach`. Default reason is generic but actionable.

```ts
type DedupToolConfig =
  | DedupHasher
  | { hasher: DedupHasher; mode?: 'replay' | 'block-after'; reason?: string | ((input: Record<string, unknown>, count: number) => string); scope?: 'session' | 'run'; threshold?: number }
```

Source: [src/types.ts:576](https://github.com/Tahul/zidane/blob/main/src/types.ts#L576)

### `GithubAnswer`

Type.

A request's outcome. `text` is the raw body.

```ts
type GithubAnswer =
  | { headers: Headers; kind: 'ok'; notModified: boolean; status: number; text: string }
  | { anonymous: boolean; kind: 'rateLimited'; retryAt?: number }
  | { kind: 'notFound' }
  | { kind: 'unauthorized' }
  | { kind: 'failed'; message?: string; status: number }
```

Source: [src/github/client.ts:46](https://github.com/Tahul/zidane/blob/main/src/github/client.ts#L46)

### `GithubPullRead`

Type.

Result of reading one pull request. Narrow on `kind`.

```ts
type GithubPullRead =
  | { kind: 'ok'; notModified: boolean; pull: GithubPull }
  | { kind: 'unchanged' }
  | { anonymous: boolean; kind: 'rateLimited'; last?: GithubPull; retryAt?: number }
  | { kind: 'unavailable' }
```

Source: [src/github/pulls.ts:92](https://github.com/Tahul/zidane/blob/main/src/github/pulls.ts#L92)

### `InferSchemaOutput`

Type.

Output type carried by a [`StandardSchemaLike`](https://zidane.si/docs/reference/index.md#StandardSchemaLike); `unknown` for plain JSON Schema.

```ts
type InferSchemaOutput<S> = S extends StandardSchemaLike<infer O> ? O : unknown
```

**Type parameters**

- `S`

Source: [src/zod.ts:36](https://github.com/Tahul/zidane/blob/main/src/zod.ts#L36)

### `InjectedTurnReason`

Type.

Why the agent loop injected a user turn (see `SessionTurn.injected`).

```ts
type InjectedTurnReason =
  | 'refusal-retry'
  | 'length-resume'
  | 'pause-resume'
  | 'tool-output-budget'
```

Source: [src/types.ts:3216](https://github.com/Tahul/zidane/blob/main/src/types.ts#L3216)

### `JsonValue`

Type.

Any value that survives `JSON.stringify` and `JSON.parse` unchanged.

```ts
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }
```

Source: [src/types.ts:2519](https://github.com/Tahul/zidane/blob/main/src/types.ts#L2519)

### `LogLevel`

Type.

Severity levels, from least to most severe.

```ts
type LogLevel = 'debug' | 'info' | 'warn' | 'error'
```

Source: [src/logger.ts:44](https://github.com/Tahul/zidane/blob/main/src/logger.ts#L44)

### `MetricAttributes`

Type.

Attributes attached to a measurement.

```ts
type MetricAttributes = Record<string, string | number | boolean | undefined>
```

Source: [src/metrics.ts:63](https://github.com/Tahul/zidane/blob/main/src/metrics.ts#L63)

### `PairingRepairMode`

Type.

Classification of a single repair the pairing pass performed. Surfaced via
`EnsureToolResultPairingOptions.onRepair` so consumers can wire
telemetry, debug logs, or strict-mode rejection without re-implementing the
walk.

Each entry corresponds to one of the corruption modes documented on
[`ensureToolResultPairing`](https://zidane.si/docs/reference/index.md#ensureToolResultPairing).

```ts
type PairingRepairMode =
  | 'orphan-tool-use-prepend'
  | 'orphan-tool-use-append'
  | 'orphan-tool-result-strip'
  | 'duplicate-tool-use-strip'
  | 'duplicate-tool-result-strip'
  | 'empty-assistant-marker'
  | 'duplicate-tool-use-remint'
```

Source: [src/session/messages-pairing.ts:50](https://github.com/Tahul/zidane/blob/main/src/session/messages-pairing.ts#L50)

### `PerfChannelDirection`

Type.

`invoke`: renderer → main request, timed to the answer; `send`: renderer → main message; `push`: main → renderer.

```ts
type PerfChannelDirection = 'invoke' | 'send' | 'push'
```

Source: [src/perf/types.ts:90](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L90)

### `PerfOrigin`

Type.

Whose cost a process is. `app`: Zidane's own (its processes, the daemon,
MCP and language servers, its helpers). `launched`: what a session's
shell tool, a background task or a terminal started, and everything under
it. The rule is in `./processes.ts`.

```ts
type PerfOrigin = 'app' | 'launched'
```

Source: [src/perf/types.ts:18](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L18)

### `PerfProcessKind`

Type.

What a process is to the app. `daemon`: a host process (the daemon, a server).

```ts
type PerfProcessKind =
  | 'main'
  | 'window'
  | 'page'
  | 'gpu'
  | 'utility'
  | 'daemon'
  | 'child'
  | 'other'
```

Source: [src/perf/types.ts:10](https://github.com/Tahul/zidane/blob/main/src/perf/types.ts#L10)

### `PersistOutcome`

Type.

Result of [`maybePersistToolResult`](https://zidane.si/docs/reference/index.md#maybePersistToolResult): a skip with its reason, a persisted blob with its stub, or a write failure.

```ts
type PersistOutcome =
  | { kind: 'skip'; reason: 'disabled' | 'excluded' | 'under-threshold' | 'unsupported-shape' | 'unsafe-call-id' | 'invalid-persist-dir' }
  | { evicted?: { bytes: number; files: number }; kind: 'persisted'; originalBytes: number; output: string; persistedPath: string }
  | { error: Error; kind: 'error'; originalBytes: number; output: string; reason: 'write-failed' }
```

Source: [src/loop-persistence.ts:513](https://github.com/Tahul/zidane/blob/main/src/loop-persistence.ts#L513)

### `ProviderLimitReason`

Type.

Why a provider turned a request away for capacity or account limits rather than for its content.

```ts
type ProviderLimitReason = 'rate_limit' | 'quota' | 'overloaded'
```

Source: [src/errors.ts:35](https://github.com/Tahul/zidane/blob/main/src/errors.ts#L35)

### `ReadonlySqliteSessionStore`

Type.

What [`createReadonlySqliteSessionStore`](https://zidane.si/docs/reference/index.md#createReadonlySqliteSessionStore) serves: reads only.

```ts
type ReadonlySqliteSessionStore = Pick<SessionStore, 'load'> & Required<Pick<SessionStore, 'getMeta' | 'getTurns' | 'close'>>
```

Source: [src/session/sqlite-readonly.ts:19](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-readonly.ts#L19)

### `ReasoningWireAction`

Type.

What a wire builder should do with a reasoning block for a given target.

```ts
type ReasoningWireAction = 'keep' | 'drop' | 'strip-signature'
```

Source: [src/session/messages.ts:411](https://github.com/Tahul/zidane/blob/main/src/session/messages.ts#L411)

### `ScheduleAction`

Type.

What a fire does.

```ts
type ScheduleAction =
  | { kind: 'prompt'; sessionId: string; text: string }
  | { kind: 'prompt'; newSession: ScheduleNewSession; text: string }
  | { extensionId: string; handler: string; kind: 'extension'; payload?: JsonValue }
```

Source: [src/schedules/types.ts:33](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L33)

### `ScheduleCatchUp`

Type.

What to do with the fires that a host missed while no host was running.

```ts
type ScheduleCatchUp = 'skip' | 'once'
```

Source: [src/schedules/types.ts:69](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L69)

### `ScheduleCreator`

Type.

Who made a schedule.

```ts
type ScheduleCreator =
  | { kind: 'user' }
  | { kind: 'agent'; sessionId: string }
  | { id: string; kind: 'extension' }
```

Source: [src/schedules/types.ts:63](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L63)

### `ScheduleFireOutcome`

Type.

How one fire went.

```ts
type ScheduleFireOutcome =
  | 'sent'
  | 'queued'
  | 'merged'
  | 'handled'
  | 'skipped'
  | 'failed'
```

Source: [src/schedules/types.ts:72](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L72)

### `ScheduleTrigger`

Type.

When a schedule fires.

```ts
type ScheduleTrigger =
  | { at: number; kind: 'at' }
  | { anchor: number; everyMs: number; kind: 'every' }
  | { expr: string; kind: 'cron'; tz: string }
```

Source: [src/schedules/types.ts:13](https://github.com/Tahul/zidane/blob/main/src/schedules/types.ts#L13)

### `SchemaInput`

Type.

A schema-accepting input: plain JSON Schema, or a Standard Schema (e.g. zod v4).

```ts
type SchemaInput = Record<string, unknown> | StandardSchemaLike
```

Source: [src/zod.ts:39](https://github.com/Tahul/zidane/blob/main/src/zod.ts#L39)

### `SectionChangeNote`

Type.

A note announcing one changed section, with the text the model reads.

```ts
type SectionChangeNote = SystemNote & { text: string }
```

Source: [src/system-freeze.ts:26](https://github.com/Tahul/zidane/blob/main/src/system-freeze.ts#L26)

### `SqlValue`

Type.

A value SQLite binds or returns.

```ts
type SqlValue = string | number | bigint | null | Uint8Array
```

Source: [src/session/sqlite-driver.ts:11](https://github.com/Tahul/zidane/blob/main/src/session/sqlite-driver.ts#L11)

### `StaleReadPolicy`

Type.

Strategy for handling reads made stale by a later mutation in the same run.
See `AgentBehavior.elideStaleReads` for full semantics and the measured
cache economics of each mode.

```ts
type StaleReadPolicy = 'stub' | 'notice'
```

Source: [src/types.ts:767](https://github.com/Tahul/zidane/blob/main/src/types.ts#L767)

### `StartSpan`

Type.

Function that opens a span. Caller-provided so we stay tracer-agnostic.

`parentContext` carries opaque trace metadata propagated from another
agent (typically a W3C `{ traceparent, tracestate }` carrier received on
`agent:start.tracingContext` after a parent agent's tracer injected it on
`spawn:before`). Implementations that integrate with OTel should extract
the carrier into a `Context` and use it as the parent when opening the
span; implementations that don't care about cross-agent linkage can
ignore the third argument entirely.

```ts
type StartSpan = (name: string, attrs?: Record<string, unknown>, parentContext?: Readonly<Record<string, string>>) => Span
```

Source: [src/tracing.ts:95](https://github.com/Tahul/zidane/blob/main/src/tracing.ts#L95)

### `ThinkingDecay`

Type.

Thinking-budget decay schedule. See `AgentBehavior.thinkingDecay` for
semantics and the measured prompt-cache cost of each form.

```ts
type ThinkingDecay =
  | GeometricThinkingDecay
  | StepThinkingDecay
  | ((runTurn: number, baseBudget: number) => number)
```

Source: [src/types.ts:822](https://github.com/Tahul/zidane/blob/main/src/types.ts#L822)

### `TracingConventions`

Type.

Gen-AI attribute convention set emitted on spans: `'sentry'`, `'otel'` or `'both'`.

```ts
type TracingConventions = 'sentry' | 'otel' | 'both'
```

Source: [src/tracing.ts:102](https://github.com/Tahul/zidane/blob/main/src/tracing.ts#L102)

### `TurnInterruptionState`

Type.

Classification of a session's tail state for resume purposes.

- `'clean'` — the trailing turn is a user message (the model would respond
  next), or the transcript is empty. Safe to resume by appending a fresh
  user prompt.
- `'interrupted'` — the trailing turn is an assistant message that has at
  least one `tool_call` block with no matching `tool_result` anywhere
  later. The run was almost certainly killed between persisting the
  assistant turn and persisting its tool-results turn. Hosts that want
  Claude-Code-style auto-resume can detect this and inject a
  `"Continue from where you left off."` user message before the next run.
- `'completed'` — the trailing turn is an assistant message with no
  orphan tool_calls. The model considers itself done. Hosts that want to
  resume must supply a new prompt; auto-continuation here would be a
  non-sequitur.

```ts
type TurnInterruptionState = 'clean' | 'interrupted' | 'completed'
```

Source: [src/session/messages.ts:821](https://github.com/Tahul/zidane/blob/main/src/session/messages.ts#L821)

## Re-exports

These names are documented on the entry point that owns them.

- [zidane/extensions](https://zidane.si/docs/reference/extensions.md): [`AccessScope`](https://zidane.si/docs/reference/extensions.md#AccessScope), [`ActionSetting`](https://zidane.si/docs/reference/extensions.md#ActionSetting), [`ActionSettingContext`](https://zidane.si/docs/reference/extensions.md#ActionSettingContext), [`ActionSettingResult`](https://zidane.si/docs/reference/extensions.md#ActionSettingResult), [`ActionSettingStatus`](https://zidane.si/docs/reference/extensions.md#ActionSettingStatus), [`ActionSettingStatusContext`](https://zidane.si/docs/reference/extensions.md#ActionSettingStatusContext), [`ActionSettingValue`](https://zidane.si/docs/reference/extensions.md#ActionSettingValue), [`AddFn`](https://zidane.si/docs/reference/extensions.md#AddFn), [`AgentEditor`](https://zidane.si/docs/reference/extensions.md#AgentEditor), [`AgentsDomain`](https://zidane.si/docs/reference/extensions.md#AgentsDomain), [`AppInfo`](https://zidane.si/docs/reference/extensions.md#AppInfo), [`artifactKindLabel`](https://zidane.si/docs/reference/extensions.md#artifactKindLabel), [`ArtifactResolveOptions`](https://zidane.si/docs/reference/extensions.md#ArtifactResolveOptions), [`ArtifactsDomain`](https://zidane.si/docs/reference/extensions.md#ArtifactsDomain), [`BadgeAction`](https://zidane.si/docs/reference/extensions.md#BadgeAction), [`BadgeActionEffect`](https://zidane.si/docs/reference/extensions.md#BadgeActionEffect), [`BadgeActionsMatch`](https://zidane.si/docs/reference/extensions.md#BadgeActionsMatch), [`BadgeActionSpec`](https://zidane.si/docs/reference/extensions.md#BadgeActionSpec), [`BadgeActionWire`](https://zidane.si/docs/reference/extensions.md#BadgeActionWire), [`badgeMenu`](https://zidane.si/docs/reference/extensions.md#badgeMenu), [`BadgeMenuItem`](https://zidane.si/docs/reference/extensions.md#BadgeMenuItem), [`BadgeTarget`](https://zidane.si/docs/reference/extensions.md#BadgeTarget), [`BadgeTargetKind`](https://zidane.si/docs/reference/extensions.md#BadgeTargetKind), [`Bindable`](https://zidane.si/docs/reference/extensions.md#Bindable), [`BooleanSetting`](https://zidane.si/docs/reference/extensions.md#BooleanSetting), [`buildExtensionPreset`](https://zidane.si/docs/reference/extensions.md#buildExtensionPreset), [`buildExtensionRegistry`](https://zidane.si/docs/reference/extensions.md#buildExtensionRegistry), [`BuildExtensionRegistryOptions`](https://zidane.si/docs/reference/extensions.md#BuildExtensionRegistryOptions), [`BUILTIN_ARTIFACT_KINDS`](https://zidane.si/docs/reference/extensions.md#BUILTIN_ARTIFACT_KINDS), [`CatalogDomain`](https://zidane.si/docs/reference/extensions.md#CatalogDomain), [`CatalogEditor`](https://zidane.si/docs/reference/extensions.md#CatalogEditor), [`clampExtensionConfigNumber`](https://zidane.si/docs/reference/extensions.md#clampExtensionConfigNumber), [`Cleanup`](https://zidane.si/docs/reference/extensions.md#Cleanup), [`coerceExtensionConfigInput`](https://zidane.si/docs/reference/extensions.md#coerceExtensionConfigInput), [`CommandListing`](https://zidane.si/docs/reference/extensions.md#CommandListing), [`CommandsDomain`](https://zidane.si/docs/reference/extensions.md#CommandsDomain), [`CommandSource`](https://zidane.si/docs/reference/extensions.md#CommandSource), [`CommandSpec`](https://zidane.si/docs/reference/extensions.md#CommandSpec), [`compileReferencePattern`](https://zidane.si/docs/reference/extensions.md#compileReferencePattern), [`COMPLETION_TIMEOUT_MS`](https://zidane.si/docs/reference/extensions.md#COMPLETION_TIMEOUT_MS), [`completionProviderSummaries`](https://zidane.si/docs/reference/extensions.md#completionProviderSummaries), [`CompletionRunner`](https://zidane.si/docs/reference/extensions.md#CompletionRunner), [`ComponentRef`](https://zidane.si/docs/reference/extensions.md#ComponentRef), [`ComponentWire`](https://zidane.si/docs/reference/extensions.md#ComponentWire), [`composeExtensionPreset`](https://zidane.si/docs/reference/extensions.md#composeExtensionPreset), [`ComposerDomain`](https://zidane.si/docs/reference/extensions.md#ComposerDomain), [`Connection`](https://zidane.si/docs/reference/extensions.md#Connection), [`ContextSection`](https://zidane.si/docs/reference/extensions.md#ContextSection), [`ContextSectionItem`](https://zidane.si/docs/reference/extensions.md#ContextSectionItem), [`ContextSectionWire`](https://zidane.si/docs/reference/extensions.md#ContextSectionWire), [`Contract`](https://zidane.si/docs/reference/extensions.md#Contract), [`ContractsDomain`](https://zidane.si/docs/reference/extensions.md#ContractsDomain), [`ContractToken`](https://zidane.si/docs/reference/extensions.md#ContractToken), [`createArtifactDetectHook`](https://zidane.si/docs/reference/extensions.md#createArtifactDetectHook), [`createArtifactsSurface`](https://zidane.si/docs/reference/extensions.md#createArtifactsSurface), [`createCompletionRunner`](https://zidane.si/docs/reference/extensions.md#createCompletionRunner), [`createExtensionHostRuntimeBridge`](https://zidane.si/docs/reference/extensions.md#createExtensionHostRuntimeBridge), [`createExtensionPromptBridge`](https://zidane.si/docs/reference/extensions.md#createExtensionPromptBridge), [`createReferenceResolver`](https://zidane.si/docs/reference/extensions.md#createReferenceResolver), [`createSharedWatches`](https://zidane.si/docs/reference/extensions.md#createSharedWatches), [`createWorkspaceSurface`](https://zidane.si/docs/reference/extensions.md#createWorkspaceSurface), [`Credential`](https://zidane.si/docs/reference/extensions.md#Credential), [`defaultExtensionScanPaths`](https://zidane.si/docs/reference/extensions.md#defaultExtensionScanPaths), [`defineExtension`](https://zidane.si/docs/reference/extensions.md#defineExtension), [`DesktopDomain`](https://zidane.si/docs/reference/extensions.md#DesktopDomain), [`DialogOptions`](https://zidane.si/docs/reference/extensions.md#DialogOptions), [`DialogRequest`](https://zidane.si/docs/reference/extensions.md#DialogRequest), [`DialogTimeoutError`](https://zidane.si/docs/reference/extensions.md#DialogTimeoutError), [`discoverAndBuildExtensionRegistry`](https://zidane.si/docs/reference/extensions.md#discoverAndBuildExtensionRegistry), [`DiscoverAndBuildExtensionRegistryOptions`](https://zidane.si/docs/reference/extensions.md#DiscoverAndBuildExtensionRegistryOptions), [`discoverExtensions`](https://zidane.si/docs/reference/extensions.md#discoverExtensions), [`Disposable`](https://zidane.si/docs/reference/extensions.md#Disposable), [`DisposedError`](https://zidane.si/docs/reference/extensions.md#DisposedError), [`disposeExtensionRegistry`](https://zidane.si/docs/reference/extensions.md#disposeExtensionRegistry), [`EMPTY_EXTENSION_REGISTRY`](https://zidane.si/docs/reference/extensions.md#EMPTY_EXTENSION_REGISTRY), [`ENTRY_CANDIDATES`](https://zidane.si/docs/reference/extensions.md#ENTRY_CANDIDATES), [`EnumSetting`](https://zidane.si/docs/reference/extensions.md#EnumSetting), [`EXTENSION_API_VERSION`](https://zidane.si/docs/reference/extensions.md#EXTENSION_API_VERSION), [`ExtensionActionRunResult`](https://zidane.si/docs/reference/extensions.md#ExtensionActionRunResult), [`ExtensionActionSummary`](https://zidane.si/docs/reference/extensions.md#ExtensionActionSummary), [`ExtensionApiVersion`](https://zidane.si/docs/reference/extensions.md#ExtensionApiVersion), [`ExtensionApprovalDecision`](https://zidane.si/docs/reference/extensions.md#ExtensionApprovalDecision), [`ExtensionArtifactDetection`](https://zidane.si/docs/reference/extensions.md#ExtensionArtifactDetection), [`ExtensionArtifactKindRegistration`](https://zidane.si/docs/reference/extensions.md#ExtensionArtifactKindRegistration), [`ExtensionArtifactQuery`](https://zidane.si/docs/reference/extensions.md#ExtensionArtifactQuery), [`ExtensionArtifactRow`](https://zidane.si/docs/reference/extensions.md#ExtensionArtifactRow), [`ExtensionArtifactRowFact`](https://zidane.si/docs/reference/extensions.md#ExtensionArtifactRowFact), [`ExtensionArtifactScope`](https://zidane.si/docs/reference/extensions.md#ExtensionArtifactScope), [`extensionBadgeActions`](https://zidane.si/docs/reference/extensions.md#extensionBadgeActions), [`ExtensionBadgeActions`](https://zidane.si/docs/reference/extensions.md#ExtensionBadgeActions), [`ExtensionBadgeColor`](https://zidane.si/docs/reference/extensions.md#ExtensionBadgeColor), [`ExtensionBadgeIcon`](https://zidane.si/docs/reference/extensions.md#ExtensionBadgeIcon), [`ExtensionBadgeTone`](https://zidane.si/docs/reference/extensions.md#ExtensionBadgeTone), [`ExtensionBehaviorTransform`](https://zidane.si/docs/reference/extensions.md#ExtensionBehaviorTransform), [`ExtensionCatalogPartition`](https://zidane.si/docs/reference/extensions.md#ExtensionCatalogPartition), [`ExtensionCompletionItemSummary`](https://zidane.si/docs/reference/extensions.md#ExtensionCompletionItemSummary), [`ExtensionCompletionProviderSummary`](https://zidane.si/docs/reference/extensions.md#ExtensionCompletionProviderSummary), [`ExtensionConfigActionItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigActionItem), [`ExtensionConfigActionResult`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigActionResult), [`ExtensionConfigActionStatus`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigActionStatus), [`ExtensionConfigBooleanItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigBooleanItem), [`ExtensionConfigCategory`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigCategory), [`ExtensionConfigChangeBehavior`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigChangeBehavior), [`ExtensionConfigEnumItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigEnumItem), [`ExtensionConfigItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigItem), [`ExtensionConfigItemBase`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigItemBase), [`ExtensionConfigModelItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigModelItem), [`ExtensionConfigNumberItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigNumberItem), [`ExtensionConfigScope`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigScope), [`ExtensionConfigStringItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigStringItem), [`ExtensionConfigValue`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigValue), [`ExtensionConfigValueItem`](https://zidane.si/docs/reference/extensions.md#ExtensionConfigValueItem), [`ExtensionContext`](https://zidane.si/docs/reference/extensions.md#ExtensionContext), [`ExtensionContextPanelSection`](https://zidane.si/docs/reference/extensions.md#ExtensionContextPanelSection), [`ExtensionContributions`](https://zidane.si/docs/reference/extensions.md#ExtensionContributions), [`ExtensionCreateSessionParams`](https://zidane.si/docs/reference/extensions.md#ExtensionCreateSessionParams), [`ExtensionDefinition`](https://zidane.si/docs/reference/extensions.md#ExtensionDefinition), [`ExtensionEventQuery`](https://zidane.si/docs/reference/extensions.md#ExtensionEventQuery), [`ExtensionFetchResult`](https://zidane.si/docs/reference/extensions.md#ExtensionFetchResult), [`ExtensionFooterHint`](https://zidane.si/docs/reference/extensions.md#ExtensionFooterHint), [`ExtensionHostKind`](https://zidane.si/docs/reference/extensions.md#ExtensionHostKind), [`ExtensionHostRuntimeBridge`](https://zidane.si/docs/reference/extensions.md#ExtensionHostRuntimeBridge), [`ExtensionHostRuntimeImpl`](https://zidane.si/docs/reference/extensions.md#ExtensionHostRuntimeImpl), [`ExtensionInfo`](https://zidane.si/docs/reference/extensions.md#ExtensionInfo), [`ExtensionInstallCandidate`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallCandidate), [`ExtensionInstallError`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallError), [`ExtensionInstallErrorCode`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallErrorCode), [`ExtensionInstallIo`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallIo), [`ExtensionInstallProvenance`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallProvenance), [`ExtensionInstallResult`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallResult), [`ExtensionInstallScope`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallScope), [`ExtensionInstallSource`](https://zidane.si/docs/reference/extensions.md#ExtensionInstallSource), [`ExtensionKeybinding`](https://zidane.si/docs/reference/extensions.md#ExtensionKeybinding), [`ExtensionKeybindingDispatchContext`](https://zidane.si/docs/reference/extensions.md#ExtensionKeybindingDispatchContext), [`ExtensionManifest`](https://zidane.si/docs/reference/extensions.md#ExtensionManifest), [`ExtensionMcpConfigTransform`](https://zidane.si/docs/reference/extensions.md#ExtensionMcpConfigTransform), [`ExtensionMcpHost`](https://zidane.si/docs/reference/extensions.md#ExtensionMcpHost), [`ExtensionMcpServerInfo`](https://zidane.si/docs/reference/extensions.md#ExtensionMcpServerInfo), [`ExtensionMcpToolResult`](https://zidane.si/docs/reference/extensions.md#ExtensionMcpToolResult), [`ExtensionModelEntry`](https://zidane.si/docs/reference/extensions.md#ExtensionModelEntry), [`ExtensionOrchestrationTool`](https://zidane.si/docs/reference/extensions.md#ExtensionOrchestrationTool), [`ExtensionOrderedContribution`](https://zidane.si/docs/reference/extensions.md#ExtensionOrderedContribution), [`ExtensionPaletteItem`](https://zidane.si/docs/reference/extensions.md#ExtensionPaletteItem), [`ExtensionPaletteProviderEntry`](https://zidane.si/docs/reference/extensions.md#ExtensionPaletteProviderEntry), [`ExtensionPaletteRunResult`](https://zidane.si/docs/reference/extensions.md#ExtensionPaletteRunResult), [`ExtensionPanel`](https://zidane.si/docs/reference/extensions.md#ExtensionPanel), [`ExtensionPanelEntry`](https://zidane.si/docs/reference/extensions.md#ExtensionPanelEntry), [`ExtensionPanelScope`](https://zidane.si/docs/reference/extensions.md#ExtensionPanelScope), [`ExtensionPaths`](https://zidane.si/docs/reference/extensions.md#ExtensionPaths), [`ExtensionPendingRequest`](https://zidane.si/docs/reference/extensions.md#ExtensionPendingRequest), [`ExtensionPromptBridge`](https://zidane.si/docs/reference/extensions.md#ExtensionPromptBridge), [`ExtensionPromptDelivery`](https://zidane.si/docs/reference/extensions.md#ExtensionPromptDelivery), [`ExtensionReferenceCard`](https://zidane.si/docs/reference/extensions.md#ExtensionReferenceCard), [`ExtensionReferenceCardFact`](https://zidane.si/docs/reference/extensions.md#ExtensionReferenceCardFact), [`ExtensionReferencePattern`](https://zidane.si/docs/reference/extensions.md#ExtensionReferencePattern), [`ExtensionReferenceProvider`](https://zidane.si/docs/reference/extensions.md#ExtensionReferenceProvider), [`ExtensionReferenceSurface`](https://zidane.si/docs/reference/extensions.md#ExtensionReferenceSurface), [`ExtensionReferenceView`](https://zidane.si/docs/reference/extensions.md#ExtensionReferenceView), [`ExtensionRegistry`](https://zidane.si/docs/reference/extensions.md#ExtensionRegistry), [`ExtensionRunSettledEvent`](https://zidane.si/docs/reference/extensions.md#ExtensionRunSettledEvent), [`ExtensionRunSettledHandler`](https://zidane.si/docs/reference/extensions.md#ExtensionRunSettledHandler), [`ExtensionRuntimeEnv`](https://zidane.si/docs/reference/extensions.md#ExtensionRuntimeEnv), [`ExtensionRuntimeSurface`](https://zidane.si/docs/reference/extensions.md#ExtensionRuntimeSurface), [`ExtensionRunTransform`](https://zidane.si/docs/reference/extensions.md#ExtensionRunTransform), [`ExtensionScanEntry`](https://zidane.si/docs/reference/extensions.md#ExtensionScanEntry), [`ExtensionSessionBadge`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionBadge), [`ExtensionSessionBadgeCardRow`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionBadgeCardRow), [`ExtensionSessionControl`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionControl), [`ExtensionSessionDetail`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionDetail), [`ExtensionSessionEvent`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionEvent), [`ExtensionSessionEventHandler`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionEventHandler), [`ExtensionSessionRow`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionRow), [`ExtensionSessionScope`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionScope), [`ExtensionSessionsSurface`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionsSurface), [`ExtensionSessionVerbs`](https://zidane.si/docs/reference/extensions.md#ExtensionSessionVerbs), [`ExtensionSkillPolicy`](https://zidane.si/docs/reference/extensions.md#ExtensionSkillPolicy), [`ExtensionSource`](https://zidane.si/docs/reference/extensions.md#ExtensionSource), [`ExtensionToolCatalogTransform`](https://zidane.si/docs/reference/extensions.md#ExtensionToolCatalogTransform), [`ExtensionToolResultMetadataRegistration`](https://zidane.si/docs/reference/extensions.md#ExtensionToolResultMetadataRegistration), [`ExtensionUiSurface`](https://zidane.si/docs/reference/extensions.md#ExtensionUiSurface), [`ExtensionWaitResult`](https://zidane.si/docs/reference/extensions.md#ExtensionWaitResult), [`ExtensionWorkspaceOps`](https://zidane.si/docs/reference/extensions.md#ExtensionWorkspaceOps), [`ExtensionWorkspacePair`](https://zidane.si/docs/reference/extensions.md#ExtensionWorkspacePair), [`ExtensionWorkspaceSurface`](https://zidane.si/docs/reference/extensions.md#ExtensionWorkspaceSurface), [`fetchExtensionSource`](https://zidane.si/docs/reference/extensions.md#fetchExtensionSource), [`fetchGithubPullRequest`](https://zidane.si/docs/reference/extensions.md#fetchGithubPullRequest), [`filterExtensionRegistry`](https://zidane.si/docs/reference/extensions.md#filterExtensionRegistry), [`findReferences`](https://zidane.si/docs/reference/extensions.md#findReferences), [`GeneratedImage`](https://zidane.si/docs/reference/extensions.md#GeneratedImage), [`GenerateDomain`](https://zidane.si/docs/reference/extensions.md#GenerateDomain), [`GenerateImageOptions`](https://zidane.si/docs/reference/extensions.md#GenerateImageOptions), [`GITHUB_ISSUE_PROVIDER_ID`](https://zidane.si/docs/reference/extensions.md#GITHUB_ISSUE_PROVIDER_ID), [`GITHUB_PULL_PROVIDER_ID`](https://zidane.si/docs/reference/extensions.md#GITHUB_PULL_PROVIDER_ID), [`githubIssueView`](https://zidane.si/docs/reference/extensions.md#githubIssueView), [`githubPullUrl`](https://zidane.si/docs/reference/extensions.md#githubPullUrl), [`githubPullView`](https://zidane.si/docs/reference/extensions.md#githubPullView), [`githubRateLimitText`](https://zidane.si/docs/reference/extensions.md#githubRateLimitText), [`Handle`](https://zidane.si/docs/reference/extensions.md#Handle), [`HookEvents`](https://zidane.si/docs/reference/extensions.md#HookEvents), [`HooksDomain`](https://zidane.si/docs/reference/extensions.md#HooksDomain), [`HttpRequestInput`](https://zidane.si/docs/reference/extensions.md#HttpRequestInput), [`HttpResponseInput`](https://zidane.si/docs/reference/extensions.md#HttpResponseInput), [`Infer`](https://zidane.si/docs/reference/extensions.md#Infer), [`inlineLoadedExtension`](https://zidane.si/docs/reference/extensions.md#inlineLoadedExtension), [`InstalledExtensionTargetOptions`](https://zidane.si/docs/reference/extensions.md#InstalledExtensionTargetOptions), [`installExtensionFromSpec`](https://zidane.si/docs/reference/extensions.md#installExtensionFromSpec), [`InstallExtensionFromSpecOptions`](https://zidane.si/docs/reference/extensions.md#InstallExtensionFromSpecOptions), [`InstructionsDomain`](https://zidane.si/docs/reference/extensions.md#InstructionsDomain), [`IntegrationCustomMethod`](https://zidane.si/docs/reference/extensions.md#IntegrationCustomMethod), [`IntegrationCustomResult`](https://zidane.si/docs/reference/extensions.md#IntegrationCustomResult), [`IntegrationFlowIO`](https://zidane.si/docs/reference/extensions.md#IntegrationFlowIO), [`IntegrationHandle`](https://zidane.si/docs/reference/extensions.md#IntegrationHandle), [`IntegrationMethod`](https://zidane.si/docs/reference/extensions.md#IntegrationMethod), [`integrationMethodFromOAuthProvider`](https://zidane.si/docs/reference/extensions.md#integrationMethodFromOAuthProvider), [`IntegrationsDomain`](https://zidane.si/docs/reference/extensions.md#IntegrationsDomain), [`IntegrationSpec`](https://zidane.si/docs/reference/extensions.md#IntegrationSpec), [`IntegrationSpecPatch`](https://zidane.si/docs/reference/extensions.md#IntegrationSpecPatch), [`InterceptOptions`](https://zidane.si/docs/reference/extensions.md#InterceptOptions), [`InterceptorHandler`](https://zidane.si/docs/reference/extensions.md#InterceptorHandler), [`Interceptors`](https://zidane.si/docs/reference/extensions.md#Interceptors), [`isBadgeColor`](https://zidane.si/docs/reference/extensions.md#isBadgeColor), [`isPullFresh`](https://zidane.si/docs/reference/extensions.md#isPullFresh), [`isValidExtensionConfigItem`](https://zidane.si/docs/reference/extensions.md#isValidExtensionConfigItem), [`isValidExtensionConfigValue`](https://zidane.si/docs/reference/extensions.md#isValidExtensionConfigValue), [`ItemOrigin`](https://zidane.si/docs/reference/extensions.md#ItemOrigin), [`Json`](https://zidane.si/docs/reference/extensions.md#Json), [`JsonSchema`](https://zidane.si/docs/reference/extensions.md#JsonSchema), [`KeymapDomain`](https://zidane.si/docs/reference/extensions.md#KeymapDomain), [`KeymapEntry`](https://zidane.si/docs/reference/extensions.md#KeymapEntry), [`KeyScope`](https://zidane.si/docs/reference/extensions.md#KeyScope), [`KeyValue`](https://zidane.si/docs/reference/extensions.md#KeyValue), [`LinkHandler`](https://zidane.si/docs/reference/extensions.md#LinkHandler), [`LinkHandlerItem`](https://zidane.si/docs/reference/extensions.md#LinkHandlerItem), [`LinkSource`](https://zidane.si/docs/reference/extensions.md#LinkSource), [`listActionSummaries`](https://zidane.si/docs/reference/extensions.md#listActionSummaries), [`listExtensionCandidates`](https://zidane.si/docs/reference/extensions.md#listExtensionCandidates), [`listExtensionPaletteItems`](https://zidane.si/docs/reference/extensions.md#listExtensionPaletteItems), [`Live`](https://zidane.si/docs/reference/extensions.md#Live), [`LiveAccessor`](https://zidane.si/docs/reference/extensions.md#LiveAccessor), [`loadableExtensionDirs`](https://zidane.si/docs/reference/extensions.md#loadableExtensionDirs), [`LoadedExtension`](https://zidane.si/docs/reference/extensions.md#LoadedExtension), [`LoadedExtensionSource`](https://zidane.si/docs/reference/extensions.md#LoadedExtensionSource), [`LoadedPluginRecord`](https://zidane.si/docs/reference/extensions.md#LoadedPluginRecord), [`loadExtensionPanel`](https://zidane.si/docs/reference/extensions.md#loadExtensionPanel), [`MAX_COMPLETION_ITEMS`](https://zidane.si/docs/reference/extensions.md#MAX_COMPLETION_ITEMS), [`MAX_COMPOSER_BADGES`](https://zidane.si/docs/reference/extensions.md#MAX_COMPOSER_BADGES), [`McpDomain`](https://zidane.si/docs/reference/extensions.md#McpDomain), [`McpServerStatus`](https://zidane.si/docs/reference/extensions.md#McpServerStatus), [`McpToolDescriptor`](https://zidane.si/docs/reference/extensions.md#McpToolDescriptor), [`Menu`](https://zidane.si/docs/reference/extensions.md#Menu), [`MenuItem`](https://zidane.si/docs/reference/extensions.md#MenuItem), [`MenuWire`](https://zidane.si/docs/reference/extensions.md#MenuWire), [`ModelEditor`](https://zidane.si/docs/reference/extensions.md#ModelEditor), [`ModelsDomain`](https://zidane.si/docs/reference/extensions.md#ModelsDomain), [`ModelSetting`](https://zidane.si/docs/reference/extensions.md#ModelSetting), [`NamedTool`](https://zidane.si/docs/reference/extensions.md#NamedTool), [`normalizeBadgeTarget`](https://zidane.si/docs/reference/extensions.md#normalizeBadgeTarget), [`NoUiError`](https://zidane.si/docs/reference/extensions.md#NoUiError), [`NumberSetting`](https://zidane.si/docs/reference/extensions.md#NumberSetting), [`OnOptions`](https://zidane.si/docs/reference/extensions.md#OnOptions), [`Owner`](https://zidane.si/docs/reference/extensions.md#Owner), [`PaletteProviderSpec`](https://zidane.si/docs/reference/extensions.md#PaletteProviderSpec), [`Panel`](https://zidane.si/docs/reference/extensions.md#Panel), [`PanelAction`](https://zidane.si/docs/reference/extensions.md#PanelAction), [`PanelBarsItem`](https://zidane.si/docs/reference/extensions.md#PanelBarsItem), [`PanelBarsPoint`](https://zidane.si/docs/reference/extensions.md#PanelBarsPoint), [`PanelBarsSeries`](https://zidane.si/docs/reference/extensions.md#PanelBarsSeries), [`PanelContent`](https://zidane.si/docs/reference/extensions.md#PanelContent), [`PanelContentItem`](https://zidane.si/docs/reference/extensions.md#PanelContentItem), [`PanelControl`](https://zidane.si/docs/reference/extensions.md#PanelControl), [`PanelControlOption`](https://zidane.si/docs/reference/extensions.md#PanelControlOption), [`PanelCustomItem`](https://zidane.si/docs/reference/extensions.md#PanelCustomItem), [`PanelFocus`](https://zidane.si/docs/reference/extensions.md#PanelFocus), [`PanelHeatmapDay`](https://zidane.si/docs/reference/extensions.md#PanelHeatmapDay), [`PanelHeatmapItem`](https://zidane.si/docs/reference/extensions.md#PanelHeatmapItem), [`PanelHomeLayout`](https://zidane.si/docs/reference/extensions.md#PanelHomeLayout), [`PanelHostDeps`](https://zidane.si/docs/reference/extensions.md#PanelHostDeps), [`panelHostRuntime`](https://zidane.si/docs/reference/extensions.md#panelHostRuntime), [`PanelIcon`](https://zidane.si/docs/reference/extensions.md#PanelIcon), [`PanelItem`](https://zidane.si/docs/reference/extensions.md#PanelItem), [`PanelKeyValueItem`](https://zidane.si/docs/reference/extensions.md#PanelKeyValueItem), [`PanelKeyValueRow`](https://zidane.si/docs/reference/extensions.md#PanelKeyValueRow), [`PanelLoadContext`](https://zidane.si/docs/reference/extensions.md#PanelLoadContext), [`PanelLoadContextInput`](https://zidane.si/docs/reference/extensions.md#PanelLoadContextInput), [`PanelLoadScope`](https://zidane.si/docs/reference/extensions.md#PanelLoadScope), [`PanelMarkdownItem`](https://zidane.si/docs/reference/extensions.md#PanelMarkdownItem), [`PanelMore`](https://zidane.si/docs/reference/extensions.md#PanelMore), [`PanelRowAction`](https://zidane.si/docs/reference/extensions.md#PanelRowAction), [`PanelRowItem`](https://zidane.si/docs/reference/extensions.md#PanelRowItem), [`PanelScopeDeps`](https://zidane.si/docs/reference/extensions.md#PanelScopeDeps), [`PanelSearch`](https://zidane.si/docs/reference/extensions.md#PanelSearch), [`PanelSection`](https://zidane.si/docs/reference/extensions.md#PanelSection), [`PanelStartSession`](https://zidane.si/docs/reference/extensions.md#PanelStartSession), [`PanelStat`](https://zidane.si/docs/reference/extensions.md#PanelStat), [`PanelStatsItem`](https://zidane.si/docs/reference/extensions.md#PanelStatsItem), [`panelSummaries`](https://zidane.si/docs/reference/extensions.md#panelSummaries), [`PanelSummary`](https://zidane.si/docs/reference/extensions.md#PanelSummary), [`PanelSurface`](https://zidane.si/docs/reference/extensions.md#PanelSurface), [`PanelView`](https://zidane.si/docs/reference/extensions.md#PanelView), [`panelViewValue`](https://zidane.si/docs/reference/extensions.md#panelViewValue), [`panelViewValues`](https://zidane.si/docs/reference/extensions.md#panelViewValues), [`PanelWire`](https://zidane.si/docs/reference/extensions.md#PanelWire), [`parseExtensionInstallSource`](https://zidane.si/docs/reference/extensions.md#parseExtensionInstallSource), [`parseExtensionScanPathEnv`](https://zidane.si/docs/reference/extensions.md#parseExtensionScanPathEnv), [`parseGithubRefKey`](https://zidane.si/docs/reference/extensions.md#parseGithubRefKey), [`partitionExtensionCatalog`](https://zidane.si/docs/reference/extensions.md#partitionExtensionCatalog), [`PluginsDomain`](https://zidane.si/docs/reference/extensions.md#PluginsDomain), [`precompileExtension`](https://zidane.si/docs/reference/extensions.md#precompileExtension), [`probeActionStatuses`](https://zidane.si/docs/reference/extensions.md#probeActionStatuses), [`PromptInput`](https://zidane.si/docs/reference/extensions.md#PromptInput), [`ProviderEditor`](https://zidane.si/docs/reference/extensions.md#ProviderEditor), [`ProvidersDomain`](https://zidane.si/docs/reference/extensions.md#ProvidersDomain), [`pruneExtensionCompileCache`](https://zidane.si/docs/reference/extensions.md#pruneExtensionCompileCache), [`pullFromMeta`](https://zidane.si/docs/reference/extensions.md#pullFromMeta), [`pullMeta`](https://zidane.si/docs/reference/extensions.md#pullMeta), [`Readable`](https://zidane.si/docs/reference/extensions.md#Readable), [`readExtensionInstallProvenance`](https://zidane.si/docs/reference/extensions.md#readExtensionInstallProvenance), [`Reference`](https://zidane.si/docs/reference/extensions.md#Reference), [`ReferenceMatch`](https://zidane.si/docs/reference/extensions.md#ReferenceMatch), [`ReferenceProviderWire`](https://zidane.si/docs/reference/extensions.md#ReferenceProviderWire), [`referenceProviderWires`](https://zidane.si/docs/reference/extensions.md#referenceProviderWires), [`ReferenceResolver`](https://zidane.si/docs/reference/extensions.md#ReferenceResolver), [`refreshArtifact`](https://zidane.si/docs/reference/extensions.md#refreshArtifact), [`registerExtensionApiHostModules`](https://zidane.si/docs/reference/extensions.md#registerExtensionApiHostModules), [`registerExtensionHostModules`](https://zidane.si/docs/reference/extensions.md#registerExtensionHostModules), [`Registry`](https://zidane.si/docs/reference/extensions.md#Registry), [`RegistryToken`](https://zidane.si/docs/reference/extensions.md#RegistryToken), [`removeInstalledExtension`](https://zidane.si/docs/reference/extensions.md#removeInstalledExtension), [`renderArtifactRow`](https://zidane.si/docs/reference/extensions.md#renderArtifactRow), [`Renderer`](https://zidane.si/docs/reference/extensions.md#Renderer), [`RendererItem`](https://zidane.si/docs/reference/extensions.md#RendererItem), [`RendererTarget`](https://zidane.si/docs/reference/extensions.md#RendererTarget), [`RendererWire`](https://zidane.si/docs/reference/extensions.md#RendererWire), [`resolveArtifactKind`](https://zidane.si/docs/reference/extensions.md#resolveArtifactKind), [`resolveExtensionCompletionSubmit`](https://zidane.si/docs/reference/extensions.md#resolveExtensionCompletionSubmit), [`resolveExtensionConfig`](https://zidane.si/docs/reference/extensions.md#resolveExtensionConfig), [`resolveExtensionConfigValue`](https://zidane.si/docs/reference/extensions.md#resolveExtensionConfigValue), [`Rpc`](https://zidane.si/docs/reference/extensions.md#Rpc), [`RpcCallContext`](https://zidane.si/docs/reference/extensions.md#RpcCallContext), [`RpcCallError`](https://zidane.si/docs/reference/extensions.md#RpcCallError), [`RpcClient`](https://zidane.si/docs/reference/extensions.md#RpcClient), [`RpcContract`](https://zidane.si/docs/reference/extensions.md#RpcContract), [`RpcDomain`](https://zidane.si/docs/reference/extensions.md#RpcDomain), [`RpcError`](https://zidane.si/docs/reference/extensions.md#RpcError), [`RpcEvent`](https://zidane.si/docs/reference/extensions.md#RpcEvent), [`RpcEvents`](https://zidane.si/docs/reference/extensions.md#RpcEvents), [`RpcEventSpec`](https://zidane.si/docs/reference/extensions.md#RpcEventSpec), [`RpcImplementation`](https://zidane.si/docs/reference/extensions.md#RpcImplementation), [`RpcMethodSpec`](https://zidane.si/docs/reference/extensions.md#RpcMethodSpec), [`RpcRegistration`](https://zidane.si/docs/reference/extensions.md#RpcRegistration), [`runBadgeAction`](https://zidane.si/docs/reference/extensions.md#runBadgeAction), [`runExtensionAction`](https://zidane.si/docs/reference/extensions.md#runExtensionAction), [`runExtensionPaletteItem`](https://zidane.si/docs/reference/extensions.md#runExtensionPaletteItem), [`runExtensionPanelAction`](https://zidane.si/docs/reference/extensions.md#runExtensionPanelAction), [`RunSettledEvent`](https://zidane.si/docs/reference/extensions.md#RunSettledEvent), [`sanitizeExtensionConfigActionPatch`](https://zidane.si/docs/reference/extensions.md#sanitizeExtensionConfigActionPatch), [`scanExtensionDirectories`](https://zidane.si/docs/reference/extensions.md#scanExtensionDirectories), [`ScheduleFireEvent`](https://zidane.si/docs/reference/extensions.md#ScheduleFireEvent), [`SchedulesDomain`](https://zidane.si/docs/reference/extensions.md#SchedulesDomain), [`Schema`](https://zidane.si/docs/reference/extensions.md#Schema), [`Screen`](https://zidane.si/docs/reference/extensions.md#Screen), [`ScreenItem`](https://zidane.si/docs/reference/extensions.md#ScreenItem), [`ScreenWire`](https://zidane.si/docs/reference/extensions.md#ScreenWire), [`SelectOption`](https://zidane.si/docs/reference/extensions.md#SelectOption), [`SessionBadgeEntry`](https://zidane.si/docs/reference/extensions.md#SessionBadgeEntry), [`sessionBadges`](https://zidane.si/docs/reference/extensions.md#sessionBadges), [`SessionEvent`](https://zidane.si/docs/reference/extensions.md#SessionEvent), [`SessionFacetsDomain`](https://zidane.si/docs/reference/extensions.md#SessionFacetsDomain), [`SessionFacetSpec`](https://zidane.si/docs/reference/extensions.md#SessionFacetSpec), [`SessionFacetTrigger`](https://zidane.si/docs/reference/extensions.md#SessionFacetTrigger), [`SessionFields`](https://zidane.si/docs/reference/extensions.md#SessionFields), [`SessionInfo`](https://zidane.si/docs/reference/extensions.md#SessionInfo), [`SessionListPage`](https://zidane.si/docs/reference/extensions.md#SessionListPage), [`SessionListQuery`](https://zidane.si/docs/reference/extensions.md#SessionListQuery), [`SessionListRow`](https://zidane.si/docs/reference/extensions.md#SessionListRow), [`SessionListStatus`](https://zidane.si/docs/reference/extensions.md#SessionListStatus), [`sessionsBadges`](https://zidane.si/docs/reference/extensions.md#sessionsBadges), [`SessionsDomain`](https://zidane.si/docs/reference/extensions.md#SessionsDomain), [`SessionSnapshot`](https://zidane.si/docs/reference/extensions.md#SessionSnapshot), [`Setting`](https://zidane.si/docs/reference/extensions.md#Setting), [`SettingApply`](https://zidane.si/docs/reference/extensions.md#SettingApply), [`SettingBase`](https://zidane.si/docs/reference/extensions.md#SettingBase), [`SettingsCategory`](https://zidane.si/docs/reference/extensions.md#SettingsCategory), [`SettingScope`](https://zidane.si/docs/reference/extensions.md#SettingScope), [`SettingsDomain`](https://zidane.si/docs/reference/extensions.md#SettingsDomain), [`SettingsPage`](https://zidane.si/docs/reference/extensions.md#SettingsPage), [`SettingsPageItem`](https://zidane.si/docs/reference/extensions.md#SettingsPageItem), [`SettingsPageSpec`](https://zidane.si/docs/reference/extensions.md#SettingsPageSpec), [`SettingsPageWire`](https://zidane.si/docs/reference/extensions.md#SettingsPageWire), [`SettingsSchema`](https://zidane.si/docs/reference/extensions.md#SettingsSchema), [`SettingValue`](https://zidane.si/docs/reference/extensions.md#SettingValue), [`SharedWatches`](https://zidane.si/docs/reference/extensions.md#SharedWatches), [`SidebarBadge`](https://zidane.si/docs/reference/extensions.md#SidebarBadge), [`SidebarChip`](https://zidane.si/docs/reference/extensions.md#SidebarChip), [`SidebarDecoration`](https://zidane.si/docs/reference/extensions.md#SidebarDecoration), [`SidebarDecorationItem`](https://zidane.si/docs/reference/extensions.md#SidebarDecorationItem), [`SidebarDecorationWire`](https://zidane.si/docs/reference/extensions.md#SidebarDecorationWire), [`SidebarFilter`](https://zidane.si/docs/reference/extensions.md#SidebarFilter), [`SidebarFilterItem`](https://zidane.si/docs/reference/extensions.md#SidebarFilterItem), [`SidebarFilterOption`](https://zidane.si/docs/reference/extensions.md#SidebarFilterOption), [`SidebarFilterWire`](https://zidane.si/docs/reference/extensions.md#SidebarFilterWire), [`SidebarGroup`](https://zidane.si/docs/reference/extensions.md#SidebarGroup), [`SidebarGroupItem`](https://zidane.si/docs/reference/extensions.md#SidebarGroupItem), [`SidebarGroupWire`](https://zidane.si/docs/reference/extensions.md#SidebarGroupWire), [`SidebarRow`](https://zidane.si/docs/reference/extensions.md#SidebarRow), [`SidebarRowAction`](https://zidane.si/docs/reference/extensions.md#SidebarRowAction), [`SidebarRowActionWire`](https://zidane.si/docs/reference/extensions.md#SidebarRowActionWire), [`SidebarRowItem`](https://zidane.si/docs/reference/extensions.md#SidebarRowItem), [`SidebarRowOpen`](https://zidane.si/docs/reference/extensions.md#SidebarRowOpen), [`SidebarRowStatus`](https://zidane.si/docs/reference/extensions.md#SidebarRowStatus), [`SidebarRowWire`](https://zidane.si/docs/reference/extensions.md#SidebarRowWire), [`SidebarSort`](https://zidane.si/docs/reference/extensions.md#SidebarSort), [`SidebarSortItem`](https://zidane.si/docs/reference/extensions.md#SidebarSortItem), [`SidebarSortWire`](https://zidane.si/docs/reference/extensions.md#SidebarSortWire), [`SidebarText`](https://zidane.si/docs/reference/extensions.md#SidebarText), [`SkillsDomain`](https://zidane.si/docs/reference/extensions.md#SkillsDomain), [`Slot`](https://zidane.si/docs/reference/extensions.md#Slot), [`SlotItem`](https://zidane.si/docs/reference/extensions.md#SlotItem), [`SlotName`](https://zidane.si/docs/reference/extensions.md#SlotName), [`SlotWire`](https://zidane.si/docs/reference/extensions.md#SlotWire), [`Space`](https://zidane.si/docs/reference/extensions.md#Space), [`SpaceItem`](https://zidane.si/docs/reference/extensions.md#SpaceItem), [`SpaceNewSession`](https://zidane.si/docs/reference/extensions.md#SpaceNewSession), [`SpaceWire`](https://zidane.si/docs/reference/extensions.md#SpaceWire), [`StorageDomain`](https://zidane.si/docs/reference/extensions.md#StorageDomain), [`StoragePathScope`](https://zidane.si/docs/reference/extensions.md#StoragePathScope), [`StorageScope`](https://zidane.si/docs/reference/extensions.md#StorageScope), [`Store`](https://zidane.si/docs/reference/extensions.md#Store), [`StoredExtensionConfigItem`](https://zidane.si/docs/reference/extensions.md#StoredExtensionConfigItem), [`StoreOptions`](https://zidane.si/docs/reference/extensions.md#StoreOptions), [`StringSetting`](https://zidane.si/docs/reference/extensions.md#StringSetting), [`subscribeExtensionPalette`](https://zidane.si/docs/reference/extensions.md#subscribeExtensionPalette), [`subscribeExtensionPanel`](https://zidane.si/docs/reference/extensions.md#subscribeExtensionPanel), [`suggestCompletionItems`](https://zidane.si/docs/reference/extensions.md#suggestCompletionItems), [`SyncInterceptorName`](https://zidane.si/docs/reference/extensions.md#SyncInterceptorName), [`ThemeToken`](https://zidane.si/docs/reference/extensions.md#ThemeToken), [`ToolCallDecision`](https://zidane.si/docs/reference/extensions.md#ToolCallDecision), [`ToolCallResult`](https://zidane.si/docs/reference/extensions.md#ToolCallResult), [`ToolEditor`](https://zidane.si/docs/reference/extensions.md#ToolEditor), [`ToolMetadataNamespace`](https://zidane.si/docs/reference/extensions.md#ToolMetadataNamespace), [`ToolResultDecision`](https://zidane.si/docs/reference/extensions.md#ToolResultDecision), [`ToolsDomain`](https://zidane.si/docs/reference/extensions.md#ToolsDomain), [`toWireConfigSchema`](https://zidane.si/docs/reference/extensions.md#toWireConfigSchema), [`Transform`](https://zidane.si/docs/reference/extensions.md#Transform), [`TuiContributions`](https://zidane.si/docs/reference/extensions.md#TuiContributions), [`UiDomain`](https://zidane.si/docs/reference/extensions.md#UiDomain), [`UiEntry`](https://zidane.si/docs/reference/extensions.md#UiEntry), [`UiToken`](https://zidane.si/docs/reference/extensions.md#UiToken), [`updateInstalledExtension`](https://zidane.si/docs/reference/extensions.md#updateInstalledExtension), [`usableCompletionProviders`](https://zidane.si/docs/reference/extensions.md#usableCompletionProviders), [`ValueKeys`](https://zidane.si/docs/reference/extensions.md#ValueKeys), [`viewForRead`](https://zidane.si/docs/reference/extensions.md#viewForRead), [`Webview`](https://zidane.si/docs/reference/extensions.md#Webview), [`WebviewItem`](https://zidane.si/docs/reference/extensions.md#WebviewItem), [`WebviewWire`](https://zidane.si/docs/reference/extensions.md#WebviewWire), [`WireExtensionConfigItem`](https://zidane.si/docs/reference/extensions.md#WireExtensionConfigItem), [`WireExtensionConfigSchema`](https://zidane.si/docs/reference/extensions.md#WireExtensionConfigSchema), [`WireSettings`](https://zidane.si/docs/reference/extensions.md#WireSettings), [`WireSettingsExtension`](https://zidane.si/docs/reference/extensions.md#WireSettingsExtension), [`WorkspaceDomain`](https://zidane.si/docs/reference/extensions.md#WorkspaceDomain)
- [zidane/skills](https://zidane.si/docs/reference/skills.md): [`ActivationVia`](https://zidane.si/docs/reference/skills.md#ActivationVia), [`ActiveSkill`](https://zidane.si/docs/reference/skills.md#ActiveSkill), [`buildCatalog`](https://zidane.si/docs/reference/skills.md#buildCatalog), [`createSkillActivationState`](https://zidane.si/docs/reference/skills.md#createSkillActivationState), [`DeactivationReason`](https://zidane.si/docs/reference/skills.md#DeactivationReason), [`defineSkill`](https://zidane.si/docs/reference/skills.md#defineSkill), [`discoverSkills`](https://zidane.si/docs/reference/skills.md#discoverSkills), [`IMPLICITLY_ALLOWED_SKILL_TOOLS`](https://zidane.si/docs/reference/skills.md#IMPLICITLY_ALLOWED_SKILL_TOOLS), [`installAllowedToolsGate`](https://zidane.si/docs/reference/skills.md#installAllowedToolsGate), [`installSkillFromSpec`](https://zidane.si/docs/reference/skills.md#installSkillFromSpec), [`interpolateShellCommands`](https://zidane.si/docs/reference/skills.md#interpolateShellCommands), [`InterpolateShellCommandsOptions`](https://zidane.si/docs/reference/skills.md#InterpolateShellCommandsOptions), [`isToolAllowedByUnion`](https://zidane.si/docs/reference/skills.md#isToolAllowedByUnion), [`listSkillCandidates`](https://zidane.si/docs/reference/skills.md#listSkillCandidates), [`matchesAllowedTool`](https://zidane.si/docs/reference/skills.md#matchesAllowedTool), [`parseAllowedToolPattern`](https://zidane.si/docs/reference/skills.md#parseAllowedToolPattern), [`parseSkillFile`](https://zidane.si/docs/reference/skills.md#parseSkillFile), [`parseSkillInstallSpec`](https://zidane.si/docs/reference/skills.md#parseSkillInstallSpec), [`readSkillProvenance`](https://zidane.si/docs/reference/skills.md#readSkillProvenance), [`resolveSkills`](https://zidane.si/docs/reference/skills.md#resolveSkills), [`ShellInterpolationApproval`](https://zidane.si/docs/reference/skills.md#ShellInterpolationApproval), [`SkillActivationState`](https://zidane.si/docs/reference/skills.md#SkillActivationState), [`SkillActivationStateOptions`](https://zidane.si/docs/reference/skills.md#SkillActivationStateOptions), [`SkillConfig`](https://zidane.si/docs/reference/skills.md#SkillConfig), [`SkillDiagnostic`](https://zidane.si/docs/reference/skills.md#SkillDiagnostic), [`SkillInstallCandidate`](https://zidane.si/docs/reference/skills.md#SkillInstallCandidate), [`SkillInstallError`](https://zidane.si/docs/reference/skills.md#SkillInstallError), [`SkillInstallErrorCode`](https://zidane.si/docs/reference/skills.md#SkillInstallErrorCode), [`SkillInstallOptions`](https://zidane.si/docs/reference/skills.md#SkillInstallOptions), [`SkillInstallResult`](https://zidane.si/docs/reference/skills.md#SkillInstallResult), [`SkillInstallSpec`](https://zidane.si/docs/reference/skills.md#SkillInstallSpec), [`SkillResource`](https://zidane.si/docs/reference/skills.md#SkillResource), [`SkillsConfig`](https://zidane.si/docs/reference/skills.md#SkillsConfig), [`SkillSource`](https://zidane.si/docs/reference/skills.md#SkillSource), [`SkillValidationIssue`](https://zidane.si/docs/reference/skills.md#SkillValidationIssue), [`SkillValidationResult`](https://zidane.si/docs/reference/skills.md#SkillValidationResult), [`SourcedScanPath`](https://zidane.si/docs/reference/skills.md#SourcedScanPath), [`stripShellInterpolations`](https://zidane.si/docs/reference/skills.md#stripShellInterpolations), [`validateResourcePath`](https://zidane.si/docs/reference/skills.md#validateResourcePath), [`validateResourcePathReal`](https://zidane.si/docs/reference/skills.md#validateResourcePathReal), [`validateSkillForWrite`](https://zidane.si/docs/reference/skills.md#validateSkillForWrite), [`validateSkillName`](https://zidane.si/docs/reference/skills.md#validateSkillName), [`writeSkillsToDisk`](https://zidane.si/docs/reference/skills.md#writeSkillsToDisk), [`writeSkillToDisk`](https://zidane.si/docs/reference/skills.md#writeSkillToDisk)
- [zidane/agent](https://zidane.si/docs/reference/agent.md): [`Agent`](https://zidane.si/docs/reference/agent.md#Agent), [`AgentHookMap`](https://zidane.si/docs/reference/agent.md#AgentHookMap), [`AgentHooks`](https://zidane.si/docs/reference/agent.md#AgentHooks), [`AgentOptions`](https://zidane.si/docs/reference/agent.md#AgentOptions), [`CacheBreakInfo`](https://zidane.si/docs/reference/agent.md#CacheBreakInfo), [`CacheBreakLoggerOptions`](https://zidane.si/docs/reference/agent.md#CacheBreakLoggerOptions), [`CacheDimensionDiff`](https://zidane.si/docs/reference/agent.md#CacheDimensionDiff), [`CacheDimensionName`](https://zidane.si/docs/reference/agent.md#CacheDimensionName), [`CacheDimensionSnapshot`](https://zidane.si/docs/reference/agent.md#CacheDimensionSnapshot), [`CacheDriftInfo`](https://zidane.si/docs/reference/agent.md#CacheDriftInfo), [`CachePromptSections`](https://zidane.si/docs/reference/agent.md#CachePromptSections), [`CacheSystemSection`](https://zidane.si/docs/reference/agent.md#CacheSystemSection), [`createAgent`](https://zidane.si/docs/reference/agent.md#createAgent), [`createRunSummaryCollector`](https://zidane.si/docs/reference/agent.md#createRunSummaryCollector), [`diffCacheDimensions`](https://zidane.si/docs/reference/agent.md#diffCacheDimensions), [`fnv1a32`](https://zidane.si/docs/reference/agent.md#fnv1a32), [`hashMessages`](https://zidane.si/docs/reference/agent.md#hashMessages), [`installCacheBreakLogger`](https://zidane.si/docs/reference/agent.md#installCacheBreakLogger), [`McpConnector`](https://zidane.si/docs/reference/agent.md#McpConnector), [`McpToolMeta`](https://zidane.si/docs/reference/agent.md#McpToolMeta), [`McpToolWrap`](https://zidane.si/docs/reference/agent.md#McpToolWrap), [`RunSummary`](https://zidane.si/docs/reference/agent.md#RunSummary), [`RunSummaryBlock`](https://zidane.si/docs/reference/agent.md#RunSummaryBlock), [`RunSummaryBudget`](https://zidane.si/docs/reference/agent.md#RunSummaryBudget), [`RunSummaryByModel`](https://zidane.si/docs/reference/agent.md#RunSummaryByModel), [`RunSummaryCollector`](https://zidane.si/docs/reference/agent.md#RunSummaryCollector), [`RunSummaryCollectorOptions`](https://zidane.si/docs/reference/agent.md#RunSummaryCollectorOptions), [`RunSummaryError`](https://zidane.si/docs/reference/agent.md#RunSummaryError), [`RunSummaryRepeatGuard`](https://zidane.si/docs/reference/agent.md#RunSummaryRepeatGuard), [`RunSummaryTokens`](https://zidane.si/docs/reference/agent.md#RunSummaryTokens), [`RunSummaryValidation`](https://zidane.si/docs/reference/agent.md#RunSummaryValidation), [`snapshotCacheDimensions`](https://zidane.si/docs/reference/agent.md#snapshotCacheDimensions)
- [zidane/errors](https://zidane.si/docs/reference/errors.md): [`AgentAbortedError`](https://zidane.si/docs/reference/errors.md#AgentAbortedError), [`AgentAuthError`](https://zidane.si/docs/reference/errors.md#AgentAuthError), [`AgentBudgetExceededError`](https://zidane.si/docs/reference/errors.md#AgentBudgetExceededError), [`AgentContextExceededError`](https://zidane.si/docs/reference/errors.md#AgentContextExceededError), [`AgentProviderError`](https://zidane.si/docs/reference/errors.md#AgentProviderError), [`AgentToolNotAllowedError`](https://zidane.si/docs/reference/errors.md#AgentToolNotAllowedError), [`AgentToolPairingError`](https://zidane.si/docs/reference/errors.md#AgentToolPairingError), [`AuthFailure`](https://zidane.si/docs/reference/errors.md#AuthFailure), [`AuthFailureKind`](https://zidane.si/docs/reference/errors.md#AuthFailureKind), [`ClassifiedError`](https://zidane.si/docs/reference/errors.md#ClassifiedError), [`ClassifiedErrorKind`](https://zidane.si/docs/reference/errors.md#ClassifiedErrorKind), [`CONTEXT_EXCEEDED_MESSAGE_PATTERNS`](https://zidane.si/docs/reference/errors.md#CONTEXT_EXCEEDED_MESSAGE_PATTERNS), [`errorMessage`](https://zidane.si/docs/reference/errors.md#errorMessage), [`matchesContextExceeded`](https://zidane.si/docs/reference/errors.md#matchesContextExceeded), [`OperationTimeoutError`](https://zidane.si/docs/reference/errors.md#OperationTimeoutError), [`toTypedError`](https://zidane.si/docs/reference/errors.md#toTypedError)
- [zidane/types](https://zidane.si/docs/reference/types.md): [`AgentBehavior`](https://zidane.si/docs/reference/types.md#AgentBehavior), [`AgentDecide`](https://zidane.si/docs/reference/types.md#AgentDecide), [`AgentDecisionsOptions`](https://zidane.si/docs/reference/types.md#AgentDecisionsOptions), [`AgentHookBus`](https://zidane.si/docs/reference/types.md#AgentHookBus), [`AgentHookHandlers`](https://zidane.si/docs/reference/types.md#AgentHookHandlers), [`AgentRunOptions`](https://zidane.si/docs/reference/types.md#AgentRunOptions), [`AgentStats`](https://zidane.si/docs/reference/types.md#AgentStats), [`AgentToolState`](https://zidane.si/docs/reference/types.md#AgentToolState), [`DecideHookContext`](https://zidane.si/docs/reference/types.md#DecideHookContext), [`DecisionAnswer`](https://zidane.si/docs/reference/types.md#DecisionAnswer), [`DecisionAnswers`](https://zidane.si/docs/reference/types.md#DecisionAnswers), [`DecisionEndHookContext`](https://zidane.si/docs/reference/types.md#DecisionEndHookContext), [`DecisionFailure`](https://zidane.si/docs/reference/types.md#DecisionFailure), [`DecisionFailureReason`](https://zidane.si/docs/reference/types.md#DecisionFailureReason), [`DecisionInput`](https://zidane.si/docs/reference/types.md#DecisionInput), [`DecisionOutcome`](https://zidane.si/docs/reference/types.md#DecisionOutcome), [`DecisionQuestion`](https://zidane.si/docs/reference/types.md#DecisionQuestion), [`DecisionQuestions`](https://zidane.si/docs/reference/types.md#DecisionQuestions), [`DecisionRequest`](https://zidane.si/docs/reference/types.md#DecisionRequest), [`DecisionStartHookContext`](https://zidane.si/docs/reference/types.md#DecisionStartHookContext), [`DecisionSuccess`](https://zidane.si/docs/reference/types.md#DecisionSuccess), [`DecisionUsage`](https://zidane.si/docs/reference/types.md#DecisionUsage), [`flattenTurns`](https://zidane.si/docs/reference/types.md#flattenTurns), [`McpServerConfig`](https://zidane.si/docs/reference/types.md#McpServerConfig), [`McpToolHookContext`](https://zidane.si/docs/reference/types.md#McpToolHookContext), [`ModelUsage`](https://zidane.si/docs/reference/types.md#ModelUsage), [`MutationValidationBatch`](https://zidane.si/docs/reference/types.md#MutationValidationBatch), [`MutationValidationFailure`](https://zidane.si/docs/reference/types.md#MutationValidationFailure), [`MutationValidationHooksOptions`](https://zidane.si/docs/reference/types.md#MutationValidationHooksOptions), [`MutationValidationMutation`](https://zidane.si/docs/reference/types.md#MutationValidationMutation), [`MutationValidationResult`](https://zidane.si/docs/reference/types.md#MutationValidationResult), [`OAuthRefreshHookContext`](https://zidane.si/docs/reference/types.md#OAuthRefreshHookContext), [`ProgressNudgeKind`](https://zidane.si/docs/reference/types.md#ProgressNudgeKind), [`ProgressNudgeMessage`](https://zidane.si/docs/reference/types.md#ProgressNudgeMessage), [`PromptAudioPart`](https://zidane.si/docs/reference/types.md#PromptAudioPart), [`PromptDocumentPart`](https://zidane.si/docs/reference/types.md#PromptDocumentPart), [`PromptImagePart`](https://zidane.si/docs/reference/types.md#PromptImagePart), [`PromptPart`](https://zidane.si/docs/reference/types.md#PromptPart), [`PromptTextPart`](https://zidane.si/docs/reference/types.md#PromptTextPart), [`PromptVideoPart`](https://zidane.si/docs/reference/types.md#PromptVideoPart), [`QueuedMessageOptions`](https://zidane.si/docs/reference/types.md#QueuedMessageOptions), [`QueuedUserMessage`](https://zidane.si/docs/reference/types.md#QueuedUserMessage), [`RepeatGuardConfig`](https://zidane.si/docs/reference/types.md#RepeatGuardConfig), [`RepeatGuardToolMatcher`](https://zidane.si/docs/reference/types.md#RepeatGuardToolMatcher), [`ResolveContentRef`](https://zidane.si/docs/reference/types.md#ResolveContentRef), [`ResolveContentRefBlock`](https://zidane.si/docs/reference/types.md#ResolveContentRefBlock), [`RetryConfig`](https://zidane.si/docs/reference/types.md#RetryConfig), [`RunHookMap`](https://zidane.si/docs/reference/types.md#RunHookMap), [`SessionContentBlock`](https://zidane.si/docs/reference/types.md#SessionContentBlock), [`SessionEndStatus`](https://zidane.si/docs/reference/types.md#SessionEndStatus), [`SessionHookContext`](https://zidane.si/docs/reference/types.md#SessionHookContext), [`SessionMessage`](https://zidane.si/docs/reference/types.md#SessionMessage), [`SessionTurn`](https://zidane.si/docs/reference/types.md#SessionTurn), [`SpawnHookContext`](https://zidane.si/docs/reference/types.md#SpawnHookContext), [`StagedToolState`](https://zidane.si/docs/reference/types.md#StagedToolState), [`statsByModel`](https://zidane.si/docs/reference/types.md#statsByModel), [`StreamHookContext`](https://zidane.si/docs/reference/types.md#StreamHookContext), [`SuccessfulMutationOutcome`](https://zidane.si/docs/reference/types.md#SuccessfulMutationOutcome), [`ThinkingLevel`](https://zidane.si/docs/reference/types.md#ThinkingLevel), [`ToolHookContext`](https://zidane.si/docs/reference/types.md#ToolHookContext), [`ToolOutcome`](https://zidane.si/docs/reference/types.md#ToolOutcome), [`toolOutputBudgetByteLength`](https://zidane.si/docs/reference/types.md#toolOutputBudgetByteLength), [`toolOutputByteLength`](https://zidane.si/docs/reference/types.md#toolOutputByteLength), [`ToolResultAudioContent`](https://zidane.si/docs/reference/types.md#ToolResultAudioContent), [`ToolResultContent`](https://zidane.si/docs/reference/types.md#ToolResultContent), [`ToolResultDocumentContent`](https://zidane.si/docs/reference/types.md#ToolResultDocumentContent), [`ToolResultDocumentRefContent`](https://zidane.si/docs/reference/types.md#ToolResultDocumentRefContent), [`ToolResultImageContent`](https://zidane.si/docs/reference/types.md#ToolResultImageContent), [`ToolResultImageRefContent`](https://zidane.si/docs/reference/types.md#ToolResultImageRefContent), [`ToolResultMetadata`](https://zidane.si/docs/reference/types.md#ToolResultMetadata), [`ToolResultTextContent`](https://zidane.si/docs/reference/types.md#ToolResultTextContent), [`toolResultToText`](https://zidane.si/docs/reference/types.md#toolResultToText), [`ToolResultVideoContent`](https://zidane.si/docs/reference/types.md#ToolResultVideoContent), [`ToolStateController`](https://zidane.si/docs/reference/types.md#ToolStateController), [`ToolStateOp`](https://zidane.si/docs/reference/types.md#ToolStateOp), [`ToolStateStore`](https://zidane.si/docs/reference/types.md#ToolStateStore), [`ToolStateView`](https://zidane.si/docs/reference/types.md#ToolStateView), [`TurnFinishReason`](https://zidane.si/docs/reference/types.md#TurnFinishReason), [`TurnUsage`](https://zidane.si/docs/reference/types.md#TurnUsage)
- [zidane/plugins](https://zidane.si/docs/reference/plugins.md): [`agentPluginsSchemaId`](https://zidane.si/docs/reference/plugins.md#agentPluginsSchemaId), [`AgentPluginsVersion`](https://zidane.si/docs/reference/plugins.md#AgentPluginsVersion), [`defaultPluginDataRoot`](https://zidane.si/docs/reference/plugins.md#defaultPluginDataRoot), [`expandPluginVars`](https://zidane.si/docs/reference/plugins.md#expandPluginVars), [`isSupportedAgentPluginsVersion`](https://zidane.si/docs/reference/plugins.md#isSupportedAgentPluginsVersion), [`loadAgentPlugin`](https://zidane.si/docs/reference/plugins.md#loadAgentPlugin), [`LoadAgentPluginOptions`](https://zidane.si/docs/reference/plugins.md#LoadAgentPluginOptions), [`LoadedPlugin`](https://zidane.si/docs/reference/plugins.md#LoadedPlugin), [`ManifestValidation`](https://zidane.si/docs/reference/plugins.md#ManifestValidation), [`parsePluginManifest`](https://zidane.si/docs/reference/plugins.md#parsePluginManifest), [`parseSchemaId`](https://zidane.si/docs/reference/plugins.md#parseSchemaId), [`PLUGIN_MANIFEST_FILE`](https://zidane.si/docs/reference/plugins.md#PLUGIN_MANIFEST_FILE), [`PLUGIN_MCP_FILE`](https://zidane.si/docs/reference/plugins.md#PLUGIN_MCP_FILE), [`PLUGIN_SKILLS_DIR`](https://zidane.si/docs/reference/plugins.md#PLUGIN_SKILLS_DIR), [`PluginAuthor`](https://zidane.si/docs/reference/plugins.md#PluginAuthor), [`PluginComponentStatus`](https://zidane.si/docs/reference/plugins.md#PluginComponentStatus), [`PluginDiagnostic`](https://zidane.si/docs/reference/plugins.md#PluginDiagnostic), [`PluginManifest`](https://zidane.si/docs/reference/plugins.md#PluginManifest), [`PluginSchemaKind`](https://zidane.si/docs/reference/plugins.md#PluginSchemaKind), [`SUPPORTED_AGENT_PLUGINS_VERSIONS`](https://zidane.si/docs/reference/plugins.md#SUPPORTED_AGENT_PLUGINS_VERSIONS), [`validatePluginManifest`](https://zidane.si/docs/reference/plugins.md#validatePluginManifest)
- [zidane/chat](https://zidane.si/docs/reference/chat.md): [`AgentProfile`](https://zidane.si/docs/reference/chat.md#AgentProfile), [`AnswerValue`](https://zidane.si/docs/reference/chat.md#AnswerValue), [`CommandAgentResult`](https://zidane.si/docs/reference/chat.md#CommandAgentResult), [`CommandAttachment`](https://zidane.si/docs/reference/chat.md#CommandAttachment), [`CommandExecution`](https://zidane.si/docs/reference/chat.md#CommandExecution), [`CommandInteraction`](https://zidane.si/docs/reference/chat.md#CommandInteraction), [`CommandOutputBlock`](https://zidane.si/docs/reference/chat.md#CommandOutputBlock), [`CommandSpawnResult`](https://zidane.si/docs/reference/chat.md#CommandSpawnResult), [`CommandSpawnTask`](https://zidane.si/docs/reference/chat.md#CommandSpawnTask), [`CommandStep`](https://zidane.si/docs/reference/chat.md#CommandStep), [`CommandStepContext`](https://zidane.si/docs/reference/chat.md#CommandStepContext), [`CommandStepFn`](https://zidane.si/docs/reference/chat.md#CommandStepFn), [`CommandStepResult`](https://zidane.si/docs/reference/chat.md#CommandStepResult), [`commandSteps`](https://zidane.si/docs/reference/chat.md#commandSteps), [`ConfirmQuestion`](https://zidane.si/docs/reference/chat.md#ConfirmQuestion), [`createPathAutocompleteProvider`](https://zidane.si/docs/reference/chat.md#createPathAutocompleteProvider), [`CustomField`](https://zidane.si/docs/reference/chat.md#CustomField), [`executeCommand`](https://zidane.si/docs/reference/chat.md#executeCommand), [`generateStructuredData`](https://zidane.si/docs/reference/chat.md#generateStructuredData), [`GenerateStructuredDataOptions`](https://zidane.si/docs/reference/chat.md#GenerateStructuredDataOptions), [`InlineAutocompleteContext`](https://zidane.si/docs/reference/chat.md#InlineAutocompleteContext), [`InlineAutocompleteProvider`](https://zidane.si/docs/reference/chat.md#InlineAutocompleteProvider), [`InteractionResponse`](https://zidane.si/docs/reference/chat.md#InteractionResponse), [`ModelInfo`](https://zidane.si/docs/reference/chat.md#ModelInfo), [`ModelOption`](https://zidane.si/docs/reference/chat.md#ModelOption), [`PlanDecision`](https://zidane.si/docs/reference/chat.md#PlanDecision), [`PlanProposal`](https://zidane.si/docs/reference/chat.md#PlanProposal), [`PlanProposalStep`](https://zidane.si/docs/reference/chat.md#PlanProposalStep), [`PlanResponse`](https://zidane.si/docs/reference/chat.md#PlanResponse), [`ProviderDescriptor`](https://zidane.si/docs/reference/chat.md#ProviderDescriptor), [`ProviderFactoryOptions`](https://zidane.si/docs/reference/chat.md#ProviderFactoryOptions), [`ProviderUsageProbe`](https://zidane.si/docs/reference/chat.md#ProviderUsageProbe), [`ProviderUsageReport`](https://zidane.si/docs/reference/chat.md#ProviderUsageReport), [`Question`](https://zidane.si/docs/reference/chat.md#Question), [`QuestionChoice`](https://zidane.si/docs/reference/chat.md#QuestionChoice), [`QuestionPayload`](https://zidane.si/docs/reference/chat.md#QuestionPayload), [`QuestionResponse`](https://zidane.si/docs/reference/chat.md#QuestionResponse), [`QuestionType`](https://zidane.si/docs/reference/chat.md#QuestionType), [`resolveInlineSuggestion`](https://zidane.si/docs/reference/chat.md#resolveInlineSuggestion), [`SelectQuestion`](https://zidane.si/docs/reference/chat.md#SelectQuestion), [`TextQuestion`](https://zidane.si/docs/reference/chat.md#TextQuestion)
- [zidane/providers/anthropic](https://zidane.si/docs/reference/providers-anthropic.md): [`anthropic`](https://zidane.si/docs/reference/providers-anthropic.md#anthropic), [`AnthropicParams`](https://zidane.si/docs/reference/providers-anthropic.md#AnthropicParams), [`applyAnthropicCacheBreakpoints`](https://zidane.si/docs/reference/providers-anthropic.md#applyAnthropicCacheBreakpoints)
- [zidane/prompt](https://zidane.si/docs/reference/prompt.md): [`appendDynamicSection`](https://zidane.si/docs/reference/prompt.md#appendDynamicSection), [`appendStaticSection`](https://zidane.si/docs/reference/prompt.md#appendStaticSection), [`hasSystemPromptBoundary`](https://zidane.si/docs/reference/prompt.md#hasSystemPromptBoundary), [`joinSystemPrompt`](https://zidane.si/docs/reference/prompt.md#joinSystemPrompt), [`renderSystemForWire`](https://zidane.si/docs/reference/prompt.md#renderSystemForWire), [`replaceDynamicSection`](https://zidane.si/docs/reference/prompt.md#replaceDynamicSection), [`splitSystemPrompt`](https://zidane.si/docs/reference/prompt.md#splitSystemPrompt), [`SYSTEM_PROMPT_BOUNDARY`](https://zidane.si/docs/reference/prompt.md#SYSTEM_PROMPT_BOUNDARY), [`SystemPromptParts`](https://zidane.si/docs/reference/prompt.md#SystemPromptParts)
- [zidane/session](https://zidane.si/docs/reference/session.md): [`AppendTurnsOptions`](https://zidane.si/docs/reference/session.md#AppendTurnsOptions), [`ARTIFACT_KINDS`](https://zidane.si/docs/reference/session.md#ARTIFACT_KINDS), [`ArtifactFilter`](https://zidane.si/docs/reference/session.md#ArtifactFilter), [`ARTIFACTS_METADATA_KEY`](https://zidane.si/docs/reference/session.md#ARTIFACTS_METADATA_KEY), [`ARTIFACTS_PER_SESSION_CAP`](https://zidane.si/docs/reference/session.md#ARTIFACTS_PER_SESSION_CAP), [`autoDetectAndConvert`](https://zidane.si/docs/reference/session.md#autoDetectAndConvert), [`createFileMapStore`](https://zidane.si/docs/reference/session.md#createFileMapStore), [`createMemoryStore`](https://zidane.si/docs/reference/session.md#createMemoryStore), [`createRemoteStore`](https://zidane.si/docs/reference/session.md#createRemoteStore), [`createSession`](https://zidane.si/docs/reference/session.md#createSession), [`CreateSessionOptions`](https://zidane.si/docs/reference/session.md#CreateSessionOptions), [`dropInvalidToolPairings`](https://zidane.si/docs/reference/session.md#dropInvalidToolPairings), [`FileMapAdapter`](https://zidane.si/docs/reference/session.md#FileMapAdapter), [`FileMapStoreOptions`](https://zidane.si/docs/reference/session.md#FileMapStoreOptions), [`fromAnthropic`](https://zidane.si/docs/reference/session.md#fromAnthropic), [`fromOpenAI`](https://zidane.si/docs/reference/session.md#fromOpenAI), [`loadSession`](https://zidane.si/docs/reference/session.md#loadSession), [`LoadSessionOptions`](https://zidane.si/docs/reference/session.md#LoadSessionOptions), [`matchesArtifactFilter`](https://zidane.si/docs/reference/session.md#matchesArtifactFilter), [`mergeArtifact`](https://zidane.si/docs/reference/session.md#mergeArtifact), [`mergeSessionMetadata`](https://zidane.si/docs/reference/session.md#mergeSessionMetadata), [`normalizeArtifactInput`](https://zidane.si/docs/reference/session.md#normalizeArtifactInput), [`PairingDrop`](https://zidane.si/docs/reference/session.md#PairingDrop), [`PairingDropKind`](https://zidane.si/docs/reference/session.md#PairingDropKind), [`RemoteStoreOptions`](https://zidane.si/docs/reference/session.md#RemoteStoreOptions), [`RunEstimate`](https://zidane.si/docs/reference/session.md#RunEstimate), [`RunEstimateFailure`](https://zidane.si/docs/reference/session.md#RunEstimateFailure), [`RunUserWait`](https://zidane.si/docs/reference/session.md#RunUserWait), [`SaveMetaOptions`](https://zidane.si/docs/reference/session.md#SaveMetaOptions), [`selectArtifactEvictions`](https://zidane.si/docs/reference/session.md#selectArtifactEvictions), [`Session`](https://zidane.si/docs/reference/session.md#Session), [`SessionArtifact`](https://zidane.si/docs/reference/session.md#SessionArtifact), [`SessionArtifactInput`](https://zidane.si/docs/reference/session.md#SessionArtifactInput), [`SessionData`](https://zidane.si/docs/reference/session.md#SessionData), [`SessionHistory`](https://zidane.si/docs/reference/session.md#SessionHistory), [`SessionMetaRow`](https://zidane.si/docs/reference/session.md#SessionMetaRow), [`SessionRun`](https://zidane.si/docs/reference/session.md#SessionRun), [`SessionRunAgent`](https://zidane.si/docs/reference/session.md#SessionRunAgent), [`SessionStore`](https://zidane.si/docs/reference/session.md#SessionStore), [`sortArtifacts`](https://zidane.si/docs/reference/session.md#sortArtifacts), [`StoredRunOptions`](https://zidane.si/docs/reference/session.md#StoredRunOptions), [`toAnthropic`](https://zidane.si/docs/reference/session.md#toAnthropic), [`toOpenAI`](https://zidane.si/docs/reference/session.md#toOpenAI), [`toWireMessages`](https://zidane.si/docs/reference/session.md#toWireMessages), [`ToWireMessagesOptions`](https://zidane.si/docs/reference/session.md#ToWireMessagesOptions), [`UpdateRunOptions`](https://zidane.si/docs/reference/session.md#UpdateRunOptions)
- [zidane/providers/arcee](https://zidane.si/docs/reference/providers-arcee.md): [`arcee`](https://zidane.si/docs/reference/providers-arcee.md#arcee), [`ArceeParams`](https://zidane.si/docs/reference/providers-arcee.md#ArceeParams)
- [zidane/eval](https://zidane.si/docs/reference/eval.md): [`artifactPath`](https://zidane.si/docs/reference/eval.md#artifactPath), [`buildEvalRunSummary`](https://zidane.si/docs/reference/eval.md#buildEvalRunSummary), [`buildRegisteredEvals`](https://zidane.si/docs/reference/eval.md#buildRegisteredEvals), [`buildTrajectory`](https://zidane.si/docs/reference/eval.md#buildTrajectory), [`clearRegisteredEvals`](https://zidane.si/docs/reference/eval.md#clearRegisteredEvals), [`computeEvalTagScores`](https://zidane.si/docs/reference/eval.md#computeEvalTagScores), [`createEvalAgent`](https://zidane.si/docs/reference/eval.md#createEvalAgent), [`CreateEvalAgentOptions`](https://zidane.si/docs/reference/eval.md#CreateEvalAgentOptions), [`createEvalRunReporter`](https://zidane.si/docs/reference/eval.md#createEvalRunReporter), [`createReusableExecutionContext`](https://zidane.si/docs/reference/eval.md#createReusableExecutionContext), [`defineEval`](https://zidane.si/docs/reference/eval.md#defineEval), [`defineMetrics`](https://zidane.si/docs/reference/eval.md#defineMetrics), [`EFFICIENCY_METRICS`](https://zidane.si/docs/reference/eval.md#EFFICIENCY_METRICS), [`efficiencyMetricValues`](https://zidane.si/docs/reference/eval.md#efficiencyMetricValues), [`emitEfficiencyMetrics`](https://zidane.si/docs/reference/eval.md#emitEfficiencyMetrics), [`EvalAgent`](https://zidane.si/docs/reference/eval.md#EvalAgent), [`EvalAgentMcpServers`](https://zidane.si/docs/reference/eval.md#EvalAgentMcpServers), [`EvalAgentRunOptions`](https://zidane.si/docs/reference/eval.md#EvalAgentRunOptions), [`EvalAgentRunResult`](https://zidane.si/docs/reference/eval.md#EvalAgentRunResult), [`EvalAgentRunStats`](https://zidane.si/docs/reference/eval.md#EvalAgentRunStats), [`EvalAgentStats`](https://zidane.si/docs/reference/eval.md#EvalAgentStats), [`EvalArtifacts`](https://zidane.si/docs/reference/eval.md#EvalArtifacts), [`EvalCaseOptions`](https://zidane.si/docs/reference/eval.md#EvalCaseOptions), [`EvalCaseResult`](https://zidane.si/docs/reference/eval.md#EvalCaseResult), [`EvalDefinition`](https://zidane.si/docs/reference/eval.md#EvalDefinition), [`EvalDefinitionContext`](https://zidane.si/docs/reference/eval.md#EvalDefinitionContext), [`EvalMetric`](https://zidane.si/docs/reference/eval.md#EvalMetric), [`EvalMetricError`](https://zidane.si/docs/reference/eval.md#EvalMetricError), [`EvalRunMetricAggregate`](https://zidane.si/docs/reference/eval.md#EvalRunMetricAggregate), [`EvalRunReporter`](https://zidane.si/docs/reference/eval.md#EvalRunReporter), [`EvalRunReporterOptions`](https://zidane.si/docs/reference/eval.md#EvalRunReporterOptions), [`EvalRunSummary`](https://zidane.si/docs/reference/eval.md#EvalRunSummary), [`EvalRunSummaryCase`](https://zidane.si/docs/reference/eval.md#EvalRunSummaryCase), [`EvalRunUsage`](https://zidane.si/docs/reference/eval.md#EvalRunUsage), [`EvalScore`](https://zidane.si/docs/reference/eval.md#EvalScore), [`EvalScorer`](https://zidane.si/docs/reference/eval.md#EvalScorer), [`EvalScorerContext`](https://zidane.si/docs/reference/eval.md#EvalScorerContext), [`EvalTestRunner`](https://zidane.si/docs/reference/eval.md#EvalTestRunner), [`EvalVariantSummary`](https://zidane.si/docs/reference/eval.md#EvalVariantSummary), [`EvalWorkspaceFile`](https://zidane.si/docs/reference/eval.md#EvalWorkspaceFile), [`EvalWorkspaceOptions`](https://zidane.si/docs/reference/eval.md#EvalWorkspaceOptions), [`EvalWorkspaceSnapshot`](https://zidane.si/docs/reference/eval.md#EvalWorkspaceSnapshot), [`fileContains`](https://zidane.si/docs/reference/eval.md#fileContains), [`fileContentQuality`](https://zidane.si/docs/reference/eval.md#fileContentQuality), [`fileExists`](https://zidane.si/docs/reference/eval.md#fileExists), [`fileExistsOneOf`](https://zidane.si/docs/reference/eval.md#fileExistsOneOf), [`finalizeEvalMetrics`](https://zidane.si/docs/reference/eval.md#finalizeEvalMetrics), [`formatEvalCaseSummary`](https://zidane.si/docs/reference/eval.md#formatEvalCaseSummary), [`formatEvalRunSummary`](https://zidane.si/docs/reference/eval.md#formatEvalRunSummary), [`formatTrajectoryLine`](https://zidane.si/docs/reference/eval.md#formatTrajectoryLine), [`functionalityMetric`](https://zidane.si/docs/reference/eval.md#functionalityMetric), [`llmJudge`](https://zidane.si/docs/reference/eval.md#llmJudge), [`LlmJudgeOptions`](https://zidane.si/docs/reference/eval.md#LlmJudgeOptions), [`MetricDirection`](https://zidane.si/docs/reference/eval.md#MetricDirection), [`MetricEmitter`](https://zidane.si/docs/reference/eval.md#MetricEmitter), [`MetricSpec`](https://zidane.si/docs/reference/eval.md#MetricSpec), [`MetricSpecMap`](https://zidane.si/docs/reference/eval.md#MetricSpecMap), [`MetricStats`](https://zidane.si/docs/reference/eval.md#MetricStats), [`normalizeMetric`](https://zidane.si/docs/reference/eval.md#normalizeMetric), [`registerEvalTests`](https://zidane.si/docs/reference/eval.md#registerEvalTests), [`RegisterEvalTestsOptions`](https://zidane.si/docs/reference/eval.md#RegisterEvalTestsOptions), [`relativeArtifactPath`](https://zidane.si/docs/reference/eval.md#relativeArtifactPath), [`ReusableExecutionContext`](https://zidane.si/docs/reference/eval.md#ReusableExecutionContext), [`runEvalCase`](https://zidane.si/docs/reference/eval.md#runEvalCase), [`statusCompleted`](https://zidane.si/docs/reference/eval.md#statusCompleted), [`Trajectory`](https://zidane.si/docs/reference/eval.md#Trajectory), [`TrajectoryStep`](https://zidane.si/docs/reference/eval.md#TrajectoryStep), [`TrajectoryStepKind`](https://zidane.si/docs/reference/eval.md#TrajectoryStepKind)
- [zidane/presets](https://zidane.si/docs/reference/presets.md): [`artifactsPreset`](https://zidane.si/docs/reference/presets.md#artifacts), [`basic`](https://zidane.si/docs/reference/presets.md#basic), [`basicTools`](https://zidane.si/docs/reference/presets.md#basicTools), [`composePresets`](https://zidane.si/docs/reference/presets.md#composePresets), [`definePreset`](https://zidane.si/docs/reference/presets.md#definePreset), [`Preset`](https://zidane.si/docs/reference/presets.md#Preset)
- [zidane/contexts](https://zidane.si/docs/reference/contexts.md): [`BackgroundTaskStatus`](https://zidane.si/docs/reference/contexts.md#BackgroundTaskStatus), [`ContextCapabilities`](https://zidane.si/docs/reference/contexts.md#ContextCapabilities), [`ContextHardening`](https://zidane.si/docs/reference/contexts.md#ContextHardening), [`ContextMount`](https://zidane.si/docs/reference/contexts.md#ContextMount), [`ContextType`](https://zidane.si/docs/reference/contexts.md#ContextType), [`createProcessContext`](https://zidane.si/docs/reference/contexts.md#createProcessContext), [`DetachedTasksCapability`](https://zidane.si/docs/reference/contexts.md#DetachedTasksCapability), [`ExecResult`](https://zidane.si/docs/reference/contexts.md#ExecResult), [`ExecutionContext`](https://zidane.si/docs/reference/contexts.md#ExecutionContext), [`ExecutionHandle`](https://zidane.si/docs/reference/contexts.md#ExecutionHandle), [`isolationAvailability`](https://zidane.si/docs/reference/contexts.md#isolationAvailability), [`IsolationBackend`](https://zidane.si/docs/reference/contexts.md#IsolationBackend), [`IsolationPolicy`](https://zidane.si/docs/reference/contexts.md#IsolationPolicy), [`ListFileMetadata`](https://zidane.si/docs/reference/contexts.md#ListFileMetadata), [`ListFilesEntry`](https://zidane.si/docs/reference/contexts.md#ListFilesEntry), [`ListFilesOptions`](https://zidane.si/docs/reference/contexts.md#ListFilesOptions), [`listOwnedProcesses`](https://zidane.si/docs/reference/contexts.md#listOwnedProcesses), [`listSessionProcesses`](https://zidane.si/docs/reference/contexts.md#listSessionProcesses), [`OwnedProcess`](https://zidane.si/docs/reference/contexts.md#OwnedProcess), [`OwnedProcessRole`](https://zidane.si/docs/reference/contexts.md#OwnedProcessRole), [`parseAllowWriteSetting`](https://zidane.si/docs/reference/contexts.md#parseAllowWriteSetting), [`registerSessionProcess`](https://zidane.si/docs/reference/contexts.md#registerSessionProcess), [`resolveDetachedTasksCapability`](https://zidane.si/docs/reference/contexts.md#resolveDetachedTasksCapability), [`resolveWritableRoots`](https://zidane.si/docs/reference/contexts.md#resolveWritableRoots), [`resolveWritableRootsAsync`](https://zidane.si/docs/reference/contexts.md#resolveWritableRootsAsync), [`SessionProcess`](https://zidane.si/docs/reference/contexts.md#SessionProcess), [`SpawnConfig`](https://zidane.si/docs/reference/contexts.md#SpawnConfig), [`StreamHandle`](https://zidane.si/docs/reference/contexts.md#StreamHandle), [`TaskEntry`](https://zidane.si/docs/reference/contexts.md#TaskEntry), [`TaskExitInfo`](https://zidane.si/docs/reference/contexts.md#TaskExitInfo), [`TaskHandle`](https://zidane.si/docs/reference/contexts.md#TaskHandle), [`TaskStallInfo`](https://zidane.si/docs/reference/contexts.md#TaskStallInfo)
- [zidane/providers/baseten](https://zidane.si/docs/reference/providers-baseten.md): [`baseten`](https://zidane.si/docs/reference/providers-baseten.md#baseten), [`BasetenParams`](https://zidane.si/docs/reference/providers-baseten.md#BasetenParams)
- [zidane/providers/cerebras](https://zidane.si/docs/reference/providers-cerebras.md): [`cerebras`](https://zidane.si/docs/reference/providers-cerebras.md#cerebras), [`CerebrasParams`](https://zidane.si/docs/reference/providers-cerebras.md#CerebrasParams)
- [zidane/tools](https://zidane.si/docs/reference/tools.md): [`ChildAgent`](https://zidane.si/docs/reference/tools.md#ChildAgent), [`createGenerateImageTool`](https://zidane.si/docs/reference/tools.md#createGenerateImageTool), [`createInteractionTool`](https://zidane.si/docs/reference/tools.md#createInteractionTool), [`createModelSearchTool`](https://zidane.si/docs/reference/tools.md#createModelSearchTool), [`createShellTool`](https://zidane.si/docs/reference/tools.md#createShellTool), [`CreateShellToolOptions`](https://zidane.si/docs/reference/tools.md#CreateShellToolOptions), [`createSkillsReadTool`](https://zidane.si/docs/reference/tools.md#createSkillsReadTool), [`createSkillsRunScriptTool`](https://zidane.si/docs/reference/tools.md#createSkillsRunScriptTool), [`createSkillsUseTool`](https://zidane.si/docs/reference/tools.md#createSkillsUseTool), [`createSpawnTool`](https://zidane.si/docs/reference/tools.md#createSpawnTool), [`edit`](https://zidane.si/docs/reference/tools.md#edit), [`ExtensionSubagentDef`](https://zidane.si/docs/reference/tools.md#ExtensionSubagentDef), [`formatModelLine`](https://zidane.si/docs/reference/tools.md#formatModelLine), [`GenerateImageToolOptions`](https://zidane.si/docs/reference/tools.md#GenerateImageToolOptions), [`getReadState`](https://zidane.si/docs/reference/tools.md#getReadState), [`glob`](https://zidane.si/docs/reference/tools.md#glob), [`grep`](https://zidane.si/docs/reference/tools.md#grep), [`hashContent`](https://zidane.si/docs/reference/tools.md#hashContent), [`hydrateReadStateFromSession`](https://zidane.si/docs/reference/tools.md#hydrateReadStateFromSession), [`hydrateReadStateFromSessionAsync`](https://zidane.si/docs/reference/tools.md#hydrateReadStateFromSessionAsync), [`HydrateReadStateOptions`](https://zidane.si/docs/reference/tools.md#HydrateReadStateOptions), [`ImageModelSource`](https://zidane.si/docs/reference/tools.md#ImageModelSource), [`InteractionToolOptions`](https://zidane.si/docs/reference/tools.md#InteractionToolOptions), [`isSpawnTool`](https://zidane.si/docs/reference/tools.md#isSpawnTool), [`matchModelEntries`](https://zidane.si/docs/reference/tools.md#matchModelEntries), [`multiEdit`](https://zidane.si/docs/reference/tools.md#multiEdit), [`ReadStateEntry`](https://zidane.si/docs/reference/tools.md#ReadStateEntry), [`readStateKey`](https://zidane.si/docs/reference/tools.md#readStateKey), [`ReadStateMap`](https://zidane.si/docs/reference/tools.md#ReadStateMap), [`resolveReadStateMap`](https://zidane.si/docs/reference/tools.md#resolveReadStateMap), [`SkillsReadToolOptions`](https://zidane.si/docs/reference/tools.md#SkillsReadToolOptions), [`SkillsRunScriptToolOptions`](https://zidane.si/docs/reference/tools.md#SkillsRunScriptToolOptions), [`SkillsUseToolOptions`](https://zidane.si/docs/reference/tools.md#SkillsUseToolOptions), [`SpawnModelEntry`](https://zidane.si/docs/reference/tools.md#SpawnModelEntry), [`SpawnTaskInput`](https://zidane.si/docs/reference/tools.md#SpawnTaskInput), [`SpawnTaskOutcome`](https://zidane.si/docs/reference/tools.md#SpawnTaskOutcome), [`SpawnTool`](https://zidane.si/docs/reference/tools.md#SpawnTool), [`SpawnToolOptions`](https://zidane.si/docs/reference/tools.md#SpawnToolOptions), [`SpawnToolState`](https://zidane.si/docs/reference/tools.md#SpawnToolState), [`SubagentDef`](https://zidane.si/docs/reference/tools.md#SubagentDef), [`SubagentOverride`](https://zidane.si/docs/reference/tools.md#SubagentOverride), [`SubagentRegistry`](https://zidane.si/docs/reference/tools.md#SubagentRegistry), [`ToolContext`](https://zidane.si/docs/reference/tools.md#ToolContext), [`ToolDef`](https://zidane.si/docs/reference/tools.md#ToolDef), [`ToolDescriptionOverride`](https://zidane.si/docs/reference/tools.md#ToolDescriptionOverride), [`ToolDescriptions`](https://zidane.si/docs/reference/tools.md#ToolDescriptions), [`ToolDescriptionTarget`](https://zidane.si/docs/reference/tools.md#ToolDescriptionTarget), [`ToolMap`](https://zidane.si/docs/reference/tools.md#ToolMap), [`validateToolArgs`](https://zidane.si/docs/reference/tools.md#validateToolArgs), [`ValidationResult`](https://zidane.si/docs/reference/tools.md#ValidationResult), [`waitTask`](https://zidane.si/docs/reference/tools.md#waitTask), [`withIsolatedSpawnTool`](https://zidane.si/docs/reference/tools.md#withIsolatedSpawnTool)
- [zidane/providers/google](https://zidane.si/docs/reference/providers-google.md): [`classifyGoogleError`](https://zidane.si/docs/reference/providers-google.md#classifyGoogleError), [`GeminiContent`](https://zidane.si/docs/reference/providers-google.md#GeminiContent), [`GeminiPart`](https://zidane.si/docs/reference/providers-google.md#GeminiPart), [`GeminiRequest`](https://zidane.si/docs/reference/providers-google.md#GeminiRequest), [`GeminiResponseChunk`](https://zidane.si/docs/reference/providers-google.md#GeminiResponseChunk), [`google`](https://zidane.si/docs/reference/providers-google.md#google), [`googleCompatible`](https://zidane.si/docs/reference/providers-google.md#googleCompatible), [`GoogleCompatibleRoute`](https://zidane.si/docs/reference/providers-google.md#GoogleCompatibleRoute), [`GoogleParams`](https://zidane.si/docs/reference/providers-google.md#GoogleParams), [`GoogleTurnRequest`](https://zidane.si/docs/reference/providers-google.md#GoogleTurnRequest), [`googleVertex`](https://zidane.si/docs/reference/providers-google.md#googleVertex), [`GoogleVertexParams`](https://zidane.si/docs/reference/providers-google.md#GoogleVertexParams), [`GoogleWireModel`](https://zidane.si/docs/reference/providers-google.md#GoogleWireModel)
- [zidane/providers/openai-compat](https://zidane.si/docs/reference/providers-openai-compat.md): [`classifyOpenAICompatError`](https://zidane.si/docs/reference/providers-openai-compat.md#classifyOpenAICompatError), [`mapOAIFinishReason`](https://zidane.si/docs/reference/providers-openai-compat.md#mapOAIFinishReason), [`openaiCompat`](https://zidane.si/docs/reference/providers-openai-compat.md#openaiCompat), [`OpenAICompatAuthHeader`](https://zidane.si/docs/reference/providers-openai-compat.md#OpenAICompatAuthHeader), [`OpenAICompatHttpError`](https://zidane.si/docs/reference/providers-openai-compat.md#OpenAICompatHttpError), [`OpenAICompatParams`](https://zidane.si/docs/reference/providers-openai-compat.md#OpenAICompatParams)
- [zidane/chat/pure](https://zidane.si/docs/reference/chat-pure.md): [`Command`](https://zidane.si/docs/reference/chat-pure.md#Command), [`CommandArgSuggestion`](https://zidane.si/docs/reference/chat-pure.md#CommandArgSuggestion), [`CommandInvocation`](https://zidane.si/docs/reference/chat-pure.md#CommandInvocation), [`compileQuery`](https://zidane.si/docs/reference/chat-pure.md#compileQuery), [`CompletionContext`](https://zidane.si/docs/reference/chat-pure.md#CompletionContext), [`CompletionItem`](https://zidane.si/docs/reference/chat-pure.md#CompletionItem), [`CompletionProvider`](https://zidane.si/docs/reference/chat-pure.md#CompletionProvider), [`CompletionReference`](https://zidane.si/docs/reference/chat-pure.md#CompletionReference), [`ContextBreakdown`](https://zidane.si/docs/reference/chat-pure.md#ContextBreakdown), [`ContextBreakdownContributionContext`](https://zidane.si/docs/reference/chat-pure.md#ContextBreakdownContributionContext), [`ContextBreakdownContributor`](https://zidane.si/docs/reference/chat-pure.md#ContextBreakdownContributor), [`ContextBreakdownOptions`](https://zidane.si/docs/reference/chat-pure.md#ContextBreakdownOptions), [`ContextCategory`](https://zidane.si/docs/reference/chat-pure.md#ContextCategory), [`ContextCategoryId`](https://zidane.si/docs/reference/chat-pure.md#ContextCategoryId), [`ContextExactCounts`](https://zidane.si/docs/reference/chat-pure.md#ContextExactCounts), [`ContextExtensionRow`](https://zidane.si/docs/reference/chat-pure.md#ContextExtensionRow), [`ContextExtensionSection`](https://zidane.si/docs/reference/chat-pure.md#ContextExtensionSection), [`ContextItem`](https://zidane.si/docs/reference/chat-pure.md#ContextItem), [`ContextMcpGroup`](https://zidane.si/docs/reference/chat-pure.md#ContextMcpGroup), [`ContextSegment`](https://zidane.si/docs/reference/chat-pure.md#ContextSegment), [`ContextSegmentFile`](https://zidane.si/docs/reference/chat-pure.md#ContextSegmentFile), [`ContextSegmentOrigin`](https://zidane.si/docs/reference/chat-pure.md#ContextSegmentOrigin), [`ContextSegmentsInput`](https://zidane.si/docs/reference/chat-pure.md#ContextSegmentsInput), [`ContextSnapshot`](https://zidane.si/docs/reference/chat-pure.md#ContextSnapshot), [`ContextUsageSplit`](https://zidane.si/docs/reference/chat-pure.md#ContextUsageSplit), [`escapeTemplate`](https://zidane.si/docs/reference/chat-pure.md#escapeTemplate), [`FacetPath`](https://zidane.si/docs/reference/chat-pure.md#FacetPath), [`formatLogLine`](https://zidane.si/docs/reference/chat-pure.md#formatLogLine), [`InlineGhost`](https://zidane.si/docs/reference/chat-pure.md#InlineGhost), [`parseCommandInvocation`](https://zidane.si/docs/reference/chat-pure.md#parseCommandInvocation), [`patchInlineGhost`](https://zidane.si/docs/reference/chat-pure.md#patchInlineGhost), [`QueryBound`](https://zidane.si/docs/reference/chat-pure.md#QueryBound), [`querySessions`](https://zidane.si/docs/reference/chat-pure.md#querySessions), [`QueryValue`](https://zidane.si/docs/reference/chat-pure.md#QueryValue), [`SessionCondition`](https://zidane.si/docs/reference/chat-pure.md#SessionCondition), [`SessionFieldName`](https://zidane.si/docs/reference/chat-pure.md#SessionFieldName), [`SessionFieldPath`](https://zidane.si/docs/reference/chat-pure.md#SessionFieldPath), [`SessionGroupBy`](https://zidane.si/docs/reference/chat-pure.md#SessionGroupBy), [`SessionGroupOrder`](https://zidane.si/docs/reference/chat-pure.md#SessionGroupOrder), [`SessionQuery`](https://zidane.si/docs/reference/chat-pure.md#SessionQuery), [`SessionQueryAll`](https://zidane.si/docs/reference/chat-pure.md#SessionQueryAll), [`SessionQueryAny`](https://zidane.si/docs/reference/chat-pure.md#SessionQueryAny), [`SessionQueryEnvironment`](https://zidane.si/docs/reference/chat-pure.md#SessionQueryEnvironment), [`SessionQueryError`](https://zidane.si/docs/reference/chat-pure.md#SessionQueryError), [`SessionQueryIssue`](https://zidane.si/docs/reference/chat-pure.md#SessionQueryIssue), [`SessionQueryNot`](https://zidane.si/docs/reference/chat-pure.md#SessionQueryNot), [`SessionSort`](https://zidane.si/docs/reference/chat-pure.md#SessionSort)
- [zidane/mcp](https://zidane.si/docs/reference/mcp.md): [`connectMcpServers`](https://zidane.si/docs/reference/mcp.md#connectMcpServers), [`ConnectMcpServersOptions`](https://zidane.si/docs/reference/mcp.md#ConnectMcpServersOptions), [`expandEnvPlaceholders`](https://zidane.si/docs/reference/mcp.md#expandEnvPlaceholders), [`expandMcpConfigEnv`](https://zidane.si/docs/reference/mcp.md#expandMcpConfigEnv), [`McpConnection`](https://zidane.si/docs/reference/mcp.md#McpConnection), [`McpExecutionBinding`](https://zidane.si/docs/reference/mcp.md#McpExecutionBinding), [`normalizeMcpBlocks`](https://zidane.si/docs/reference/mcp.md#normalizeMcpBlocks), [`normalizeMcpServers`](https://zidane.si/docs/reference/mcp.md#normalizeMcpServers), [`originPinnedFetch`](https://zidane.si/docs/reference/mcp.md#originPinnedFetch), [`resolveTransportConfig`](https://zidane.si/docs/reference/mcp.md#resolveTransportConfig), [`resultToString`](https://zidane.si/docs/reference/mcp.md#resultToString)
- [zidane/contexts/sandbox](https://zidane.si/docs/reference/contexts-sandbox.md): [`createSandboxContext`](https://zidane.si/docs/reference/contexts-sandbox.md#createSandboxContext), [`SandboxProvider`](https://zidane.si/docs/reference/contexts-sandbox.md#SandboxProvider)
- [zidane/providers](https://zidane.si/docs/reference/providers.md): [`credentialsFilePath`](https://zidane.si/docs/reference/providers.md#credentialsFilePath), [`credentialsFromParams`](https://zidane.si/docs/reference/providers.md#credentialsFromParams), [`extractRuntimeCredentials`](https://zidane.si/docs/reference/providers.md#extractRuntimeCredentials), [`getModelCatalog`](https://zidane.si/docs/reference/providers.md#getModelCatalog), [`getOAuthApiKey`](https://zidane.si/docs/reference/providers.md#getOAuthApiKey), [`getOAuthProvider`](https://zidane.si/docs/reference/providers.md#getOAuthProvider), [`HistoryRepair`](https://zidane.si/docs/reference/providers.md#HistoryRepair), [`ImageAspectRatio`](https://zidane.si/docs/reference/providers.md#ImageAspectRatio), [`ImageData`](https://zidane.si/docs/reference/providers.md#ImageData), [`ImageModelInfo`](https://zidane.si/docs/reference/providers.md#ImageModelInfo), [`isOAuthAccessToken`](https://zidane.si/docs/reference/providers.md#isOAuthAccessToken), [`mistral`](https://zidane.si/docs/reference/providers.md#mistral), [`MistralParams`](https://zidane.si/docs/reference/providers.md#MistralParams), [`ModelCatalog`](https://zidane.si/docs/reference/providers.md#ModelCatalog), [`ModelCatalogEntry`](https://zidane.si/docs/reference/providers.md#ModelCatalogEntry), [`ModelCatalogSource`](https://zidane.si/docs/reference/providers.md#ModelCatalogSource), [`OAuthParams`](https://zidane.si/docs/reference/providers.md#OAuthParams), [`OAuthProviderInterface`](https://zidane.si/docs/reference/providers.md#OAuthProviderInterface), [`pinnedAccountMissingError`](https://zidane.si/docs/reference/providers.md#pinnedAccountMissingError), [`Provider`](https://zidane.si/docs/reference/providers.md#Provider), [`ProviderCapabilities`](https://zidane.si/docs/reference/providers.md#ProviderCapabilities), [`ProviderDecisionAvailability`](https://zidane.si/docs/reference/providers.md#ProviderDecisionAvailability), [`ProviderDecisionRequest`](https://zidane.si/docs/reference/providers.md#ProviderDecisionRequest), [`ProviderDecisionResponse`](https://zidane.si/docs/reference/providers.md#ProviderDecisionResponse), [`ProviderDecisions`](https://zidane.si/docs/reference/providers.md#ProviderDecisions), [`ProviderImageAvailability`](https://zidane.si/docs/reference/providers.md#ProviderImageAvailability), [`ProviderImageRequest`](https://zidane.si/docs/reference/providers.md#ProviderImageRequest), [`ProviderImageResponse`](https://zidane.si/docs/reference/providers.md#ProviderImageResponse), [`ProviderImages`](https://zidane.si/docs/reference/providers.md#ProviderImages), [`ProviderMeta`](https://zidane.si/docs/reference/providers.md#ProviderMeta), [`readAccountOAuthCredential`](https://zidane.si/docs/reference/providers.md#readAccountOAuthCredential), [`readOAuthCredentials`](https://zidane.si/docs/reference/providers.md#readOAuthCredentials), [`refreshAnthropicToken`](https://zidane.si/docs/reference/providers.md#refreshAnthropicToken), [`refreshOpenAICodexToken`](https://zidane.si/docs/reference/providers.md#refreshOpenAICodexToken), [`registerCustomOAuthProvider`](https://zidane.si/docs/reference/providers.md#registerCustomOAuthProvider), [`registerOAuthProvider`](https://zidane.si/docs/reference/providers.md#registerOAuthProvider), [`resolveOAuthApiKey`](https://zidane.si/docs/reference/providers.md#resolveOAuthApiKey), [`ResolveOAuthApiKeyOptions`](https://zidane.si/docs/reference/providers.md#ResolveOAuthApiKeyOptions), [`sanitizeToolSchema`](https://zidane.si/docs/reference/providers.md#sanitizeToolSchema), [`sanitizeToolSpecs`](https://zidane.si/docs/reference/providers.md#sanitizeToolSpecs), [`SchemaSanitizeOptions`](https://zidane.si/docs/reference/providers.md#SchemaSanitizeOptions), [`SchemaSanitizeProfile`](https://zidane.si/docs/reference/providers.md#SchemaSanitizeProfile), [`SchemaSanitizeResult`](https://zidane.si/docs/reference/providers.md#SchemaSanitizeResult), [`setModelCatalog`](https://zidane.si/docs/reference/providers.md#setModelCatalog), [`StreamCallbacks`](https://zidane.si/docs/reference/providers.md#StreamCallbacks), [`StreamOptions`](https://zidane.si/docs/reference/providers.md#StreamOptions), [`ToolCall`](https://zidane.si/docs/reference/providers.md#ToolCall), [`ToolResult`](https://zidane.si/docs/reference/providers.md#ToolResult), [`ToolSpec`](https://zidane.si/docs/reference/providers.md#ToolSpec), [`TurnResult`](https://zidane.si/docs/reference/providers.md#TurnResult), [`writeOAuthCredentials`](https://zidane.si/docs/reference/providers.md#writeOAuthCredentials)
- [zidane/headless](https://zidane.si/docs/reference/headless.md): [`HeadlessErrorInfo`](https://zidane.si/docs/reference/headless.md#HeadlessErrorInfo), [`HeadlessEvent`](https://zidane.si/docs/reference/headless.md#HeadlessEvent), [`headlessEventToJsonl`](https://zidane.si/docs/reference/headless.md#headlessEventToJsonl), [`HeadlessOptions`](https://zidane.si/docs/reference/headless.md#HeadlessOptions), [`HeadlessResult`](https://zidane.si/docs/reference/headless.md#HeadlessResult), [`HeadlessStatus`](https://zidane.si/docs/reference/headless.md#HeadlessStatus), [`HeadlessUsage`](https://zidane.si/docs/reference/headless.md#HeadlessUsage), [`OpenAIChatMessage`](https://zidane.si/docs/reference/headless.md#OpenAIChatMessage), [`runHeadless`](https://zidane.si/docs/reference/headless.md#runHeadless), [`transcriptToOpenAIMessages`](https://zidane.si/docs/reference/headless.md#transcriptToOpenAIMessages)
- [zidane/providers/local](https://zidane.si/docs/reference/providers-local.md): [`local`](https://zidane.si/docs/reference/providers-local.md#local), [`LocalParams`](https://zidane.si/docs/reference/providers-local.md#LocalParams)
- [zidane/providers/openai](https://zidane.si/docs/reference/providers-openai.md): [`openai`](https://zidane.si/docs/reference/providers-openai.md#openai), [`OpenAIParams`](https://zidane.si/docs/reference/providers-openai.md#OpenAIParams)
- [zidane/providers/openrouter](https://zidane.si/docs/reference/providers-openrouter.md): [`openrouter`](https://zidane.si/docs/reference/providers-openrouter.md#openrouter), [`OpenRouterParams`](https://zidane.si/docs/reference/providers-openrouter.md#OpenRouterParams)
- [zidane/tools/prompts](https://zidane.si/docs/reference/tools-prompts.md): [`toolPrompts`](https://zidane.si/docs/reference/tools-prompts.md#toolPrompts), [`ToolPrompts`](https://zidane.si/docs/reference/tools-prompts.md#ToolPrompts)
- [zidane/providers/xai](https://zidane.si/docs/reference/providers-xai.md): [`xai`](https://zidane.si/docs/reference/providers-xai.md#xai), [`XaiParams`](https://zidane.si/docs/reference/providers-xai.md#XaiParams)
