zidane
The root entry point, with the agent, providers, tools and presets re-exported alongside the runtime helpers that have no narrower entry.
import { … } from 'zidane'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.
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#
anchorPreviewForFunction#
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.
announcedDigestFunction#
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.
announcedResetMsFunction#
The wait a provider message announces (try again in …, resets in …),
every unit summed (2h30m14s), in ms; undefined when it names none.
applyCompactSummaryCutoffFunction#
Wire-level cutoff for 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:
- A marker turn never passes through verbatim (providers don't
know the
compact-summaryblock type). - 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.
- 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.
- 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 SessionTurns 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.
authFailureOfFunction#
The sign-in failure behind err: an AgentAuthError anywhere on its
cause chain, else a provider error that came back 401 (the credential
was sent and refused). undefined for anything else.
buildFromCompactPromptFunction#
Builds the summary prompt for summarizing from an anchor turn onward.
buildFullCompactPromptFunction#
Builds the summary prompt for summarizing the whole conversation.
buildPersistedStubFunction#
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_filethe persisted blob without scanning the preview. - Preview always shows the head — how
shellcuts 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.
buildPostCompactAttachmentsFunction#
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.
buildTailCompactPromptFunction#
Builds the summary prompt for summarizing everything before the preserved tail.
buildUpToCompactPromptFunction#
Builds the summary prompt for summarizing up to an anchor turn.
buildZidaneExtensionSkillFunction#
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.
buildZidaneSkillEditSkillFunction#
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.
catalogChangeNotesFunction#
Notes for each SDK-appended section whose live text differs from what the
model was last told (see 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.
classifyGithubAnswerFunction#
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.
classifyProviderLimitFunction#
The classification for a rate limit, spent quota or overload: the human
message from 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.
cleanupPersistedSessionFunction#
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.
clearGithubPullMemoryFunction#
Forget remembered PRs (tests).
clearMcpSignInFunction#
Sign out of name: drop tokens, registration and discovery, keep a
stored client secret (configuration, not session state).
collectNewlyStaleReadPathsFunction#
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.
commandBlocksToContentFunction#
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.
commandBlockToEventFunction#
Map ONE command-output block to its LIVE transcript event — the
in-memory mirror of 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.
commandLabelFunction#
A short name for a command line: the program, or the script an interpreter runs
(node …/typescript-language-server --stdio → typescript-language-server (node)).
compactConversationFunction#
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 when the inputs cannot be compacted, CompactPromptTooLongError when the retry budget runs out, and rethrows aborts from opts.signal unchanged.
configureGithubClientFunction#
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).
consoleSinkFunction#
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).
createExtensionFunction#
Scaffolds a new extension folder: index.ts, plus the optional files
input asks for. Throws when the name is invalid or the folder exists.
createFileGithubStateStoreFunction#
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.
createGithubClientFunction#
Creates a GitHub client with its own answer cache, request limit and rate-limit handling.
createGpuReaderFunction#
A GPU reader for a sampler: ioreg at most every everyMs (macOS only),
the last figure in between.
createHostPerfFunction#
Creates the host's monitor. Nothing runs until the first watch.
createLoggerFunction#
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.
createLoggingHooksFunction#
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).
createMainThreadMeterFunction#
Creates the meter.
createMemoryGithubStateStoreFunction#
State in this process only.
createMemoryMcpCredentialStoreFunction#
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).
createMetricsHooksFunction#
Build a set of metrics hook handlers that can be installed on an agent.
createMutationValidationHooksFunction#
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.
createOwnedProcessesFunction#
The owned-process reader a sampler calls once a tick: the local registries, and the other host's last answers.
createReadonlySqliteSessionStoreFunction#
Serves load, getMeta and getTurns from driver exactly as the
regular store does. close closes the driver.
createRingFunction#
Creates a ring.
createRingBufferSinkFunction#
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.
createSamplerFunction#
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.
createSqliteDriverFunction#
Wraps a bun:sqlite Database or a node:sqlite DatabaseSync as a
SqliteDriver: a bounded statement cache, get normalized to
undefined on no row (bun returns null), and a manual BEGIN IMMEDIATE.
createSqliteSessionStoreFunction#
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.
createSqliteWriteQueueFunction#
A SqliteWriteQueue; one per connection, shared by every writer on it.
createToolStateControllerFunction#
Creates the controller that owns an agent's tool state snapshot and per-call staging views.
createTracingHooksFunction#
Build a set of tracing hook handlers that can be installed on an agent.
defaultRepeatGuardNormalizeFunction#
Built-in normalizer used when the consumer doesn't supply one. Shell-shaped
tools get 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.
defaultRepeatGuardTrackedFunction#
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.
describeProviderLimitFunction#
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.
detectTurnInterruptionFunction#
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 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').
editSessionMetadataFunction#
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 / buildZidaneSkillEditSkill),
so the preset rides as real conversation context from turn one.
effectiveContextWindowFunction#
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.
ensureEndsWithUserMessageFunction#
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, soensureToolResultPairingdoesn't synthesize a user tail). context:transformhooks that strip the trailing user turn.
The pair-repair pass 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).
ensureToolResultPairingFunction#
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 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 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 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.
estimateTokensFunction#
Approximate token count for text: text.length (UTF-16 code units, not
bytes) divided by 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.
extensionDirForCwdFunction#
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.
extensionScaffoldFunction#
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.
fanoutSinkFunction#
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).
filterUnresolvedToolUsesFunction#
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 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.
formatTokenUsageFunction#
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.
githubApiBaseFunction#
REST root for a host (github.com or Enterprise).
githubClientFunction#
This process's client: one quota view and one answer cache for every GitHub reader.
githubPullConfirmedAtFunction#
When this process last confirmed a PR current with GitHub (epoch ms), if it did.
githubTokenFingerprintFunction#
sha256(host + token), 16 hex chars: safe for keys and files, never the token.
hasAuthorizationHeaderFunction#
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.
isGhRateLimitErrorFunction#
primary (the hourly quota is spent), secondary (too fast), or null.
isSqliteBusyErrorFunction#
True when err is SQLite reporting a held lock (SQLITE_BUSY, SQLITE_LOCKED).
isStandardSchemaFunction#
Checks whether value carries a Standard Schema ~standard marker with a string vendor.
isThinkingLevelFunction#
Type guard for canonical ThinkingLevel strings (e.g. metadata.effort read off a persisted session).
isToolStateOpsFunction#
Runtime guard for a journaled op list — adapters validate before restoring.
isValidCallbackPortFunction#
Unprivileged TCP port: the loopback listener can't bind below 1024 without root.
jsonSinkFunction#
One-JSON-object-per-line sink. Suitable for piping into log aggregators (Datadog Agent, Fluent Bit, Loki, Vector) that expect JSONL.
labelSessionsFunction#
Names each process's session as the reader does, and titles it, read once per session.
latestSystemSnapshotFunction#
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.
localReliabilityBehaviorFunction#
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.
loginMcpServerFunction#
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.
maybePersistToolResultFunction#
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.
mcpOAuthProviderForFunction#
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.
migrateSessionArtifactDirsFunction#
Fold older artifact layouts into the session-first one
(<userDir>/sessions/<sessionId>/<kind>/).
Two source layouts are folded in:
- pre-6.x
<userDir>/<sessionId>/{tasks,mcp-warnings}/— one top-level entry per session, so a few hundred sessions burycredentials.jsonunder noise. This is what is actually on users' disks. - 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 and 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.
normalizeGithubHostFunction#
Normalizes a host name to lowercase and maps api.github.com and www.github.com to github.com. Defaults to github.com.
normalizeProvidersFunction#
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.
normalizeShellCommandFunction#
Canonicalize a shell command so semantically-identical invocations collapse to one streak key:
- strip a leading
cd <path> &&(orcd <path>;) prefix — the model often re-prefixes the same command with acdinto 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.
originTotalsFunction#
CPU and memory summed per origin.
pinnedMcpRedirectUriFunction#
The loopback redirect a pinned oauth.callbackPort produces: the URL to
register with the provider. Pass the same callbackPath given to
loginMcpServer, if any.
queueGithubPullFunction#
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).
rateLimitResetFromJsonFunction#
The reset of a quota from gh api rate_limit output (epoch seconds in
resources.<name>.reset), as local epoch ms; undefined when unreadable.
readGithubPullFunction#
One PR.
readGithubPullsFunction#
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.
readOsThreadsFunction#
The OS threads of a process, busiest first.
readProcessTreeFunction#
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.
readSkillEditMarkerFunction#
Parse a persisted SkillEditMarker back out of session metadata.
Tolerant: anything that isn't { dir: string, name: string } → null
(older sessions, manual metadata edits, type drift).
reasoningWireActionFunction#
Single source of truth for whether a signature-bearing reasoning block
(thinking / redacted_thinking) may be forwarded to a provider. The
wire builders (toAnthropic, the OpenAI and Google message shapers)
and the host-facing 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).thinkingtaggedopenai,googleorgoogle-vertex→ drop (OpenAIencrypted_contentand Gemini thought signatures are not valid Anthropic HMACs; 400s).- unsigned
thinking→ drop (ThinkingBlockParamrequires 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
openaior a Gemini-wire scope (google,google-vertex, agoogleCompatibleroute's):redacted_thinking→ drop (Anthropic-only block type).thinkingtaggedanthropic→ drop (an Anthropic HMAC is valid nowhere else).thinkingsigned 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.
remintDuplicateToolCallIdsFunction#
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) 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.
renderStaleReadNoticeFunction#
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.
resolveCompletionSubmitFunction#
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.
resolveExtensionDocsDirFunction#
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).
resolveLegacyPersistDirFunction#
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). They keep resolving where they
are; this resolver exists so session delete still reclaims them. Same
positive id match, same reason.
resolveLegacySessionDirFunction#
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 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/.
resolveMcpWarningsDirFunction#
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.
resolveModelTargetsFunction#
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'smeta.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.
resolvePersistDirFunction#
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) 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).
resolveSchemaInputFunction#
Resolve a 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.
resolveSessionDirFunction#
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.
resolveTasksDirFunction#
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.
runUsageAggregatesFunction#
All three aggregates against one handle.
sanitizeHistoryForProviderFunction#
Host-facing history sanitizer — applies 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.
saveMcpClientSecretFunction#
Store (or, with an empty value, forget) the client secret a host UI
collected for name's pre-registered client.
sectionDigestFunction#
Short stable digest of a section's text.
sectionDigestsFunction#
Digest of every section present, by section kind.
selectFilesFromReadStateFunction#
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, which wraps
getReadState(session) + this function in one call so the host
doesn't have to reach into the tools layer.
selectFilesFromSessionFunction#
Session-aware convenience: extract recently-read files directly from
a 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:
const state = getReadState(session)
return state ? selectFilesFromReadState(state, cwd) : []
selectRecentFilesFunction#
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.
shouldAutoCompactFunction#
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.
sliceForCompactionFunction#
Partition turns into (toSummarize, preserved) according to scope.
Throws CompactInvalidInputError on degenerate inputs so the
caller doesn't pay for a doomed provider call:
- empty
turns scope: 'tail'withkeepTurns >= turns.length(nothing to summarize)scope: { from | up_to }with an anchor id that isn't inturns- the resulting
toSummarizeslice 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.
sqliteStoreFileFunction#
The database file a store from createSqliteSessionStore (or a
wrapper that called adoptSqliteStoreFile) works on; undefined
for any other store and for an in-memory database.
stableStringifyFunction#
Deterministic JSON with sorted keys so key order doesn't split a streak.
stagedToolStateFunction#
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.
startOAuthCallbackFunction#
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).
stripImagesFromTurnsFunction#
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.outputarray 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.
summaryToTurnFunction#
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:
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])
systemSnapshotTurnFunction#
The out-of-band role: 'system' turn recording a frozen prompt, or
clearing the one recorded for key (every key when omitted).
treeProcessesFunction#
One row per OS process of the tree, in the tree's order (listed ones left out).
truncateHeadForPtlRetryFunction#
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.
usageAssistantDailyFunction#
Usage per local day × model.
usageSessionDailyFunction#
Sessions created per local day.
usageUserDailyFunction#
Human messages per local day × hour.
utf8ByteLengthFunction#
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.
validateExtensionNameFunction#
Why a proposed extension name is refused, or null when it is fine.
withZidaneExtensionSkillFunction#
Inject the zidane-extension skill into an already-merged 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.
withZidaneSkillEditSkillFunction#
Inject the skill-edit preset skill into an already-merged SkillsConfig.
Same contract as withZidaneExtensionSkill — call on the FINAL merged
skills object.
zodToJsonSchemaFunction#
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.
Classes#
AgentLengthResumeExhaustedErrorClass#
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.
CompactInvalidInputErrorClass#
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 inturns- the resolved
toSummarizeslice has no text-bearing content
Synchronous — thrown from compactConversation() before the provider
call so the caller can recover without a network round-trip.
CompactPromptTooLongErrorClass#
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.
DecisionErrorClass#
Thrown by agent.decide(req, { throw: true }) when the decision failed.
DecisionHttpErrorClass#
Non-2xx response from a decisions endpoint.
DecisionInvalidResponseErrorClass#
The provider answered 2xx with a body that doesn't match the expected shape.
DecisionTimeoutErrorClass#
Abort reason of the decider's wall-clock cap.
DecisionUnsupportedErrorClass#
The input or questions can't be expressed on this provider's wire.
McpOAuthProviderClass#
OAuth client provider for one MCP server. Persists tokens and registration in a McpCredentialStore and never opens a browser by itself.
PerfProcessNotFoundErrorClass#
perf.threads asked for a process the host doesn't list.
Constants#
ANCHOR_PREVIEW_MAX_CHARSConstant#
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.
AUTO_COMPACT_MIN_GROWTH_FRACTIONConstant#
Hysteresis floor that chat hosts pass as minGrowthFraction to
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.
BASE_INSTRUCTIONSConstant#
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.
buildCompactPromptConstant#
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.
BYTES_PER_TOKENConstant#
Same constant Claude Code's CONTEXT_MANAGEMENT.md documents.
DEFAULT_DECISION_TIMEOUT_MSConstant#
Default wall-clock cap for one decision, in milliseconds.
DEFAULT_MAX_VALUE_BYTESConstant#
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.
EXTENSION_EDIT_METADATA_KEYConstant#
Session-metadata key marking an "edit / create extension" session. The value
is an 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).
FROZEN_PROMPT_SECTION_KINDSConstant#
The SDK-appended sections, in announcement order.
GEN_AI_ATTRIBUTESConstant#
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.
INTERRUPT_MESSAGE_FOR_TOOL_USEConstant#
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.
NO_TOOLS_PREAMBLEConstant#
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.
ORPHANED_TOOL_RESULT_MARKERConstant#
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 on the user side.
OUTPUT_RESERVE_TOKENSConstant#
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.
ownCommandsConstant#
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.
PERSISTED_STUB_PREFIXConstant#
Byte-stable prefix every 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).
PERSISTENCE_PREVIEW_BYTESConstant#
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.
SAMPLE_CAPACITYConstant#
Samples kept: 5 minutes at SAMPLE_INTERVAL_MS.
SAMPLE_INTERVAL_MSConstant#
Between two samples, ms.
SHELL_CASCADE_CANCEL_MESSAGEConstant#
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 (user-issued abort) and
TOOL_USE_SKIPPED_MESSAGE (steered) so consumers can split
the three causes by string-match.
SKILL_EDIT_METADATA_KEYConstant#
Session-metadata key marking an "edit skill" session — the skill-editing
counterpart of EXTENSION_EDIT_METADATA_KEY. The value is a
SkillEditMarker. Stamped at session creation by both hosts (via
editSessionMetadata); persisted metadata means it survives reload.
SYNTHETIC_TOOL_RESULT_PLACEHOLDERConstant#
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.
TOOL_USE_CANCELLED_MESSAGEConstant#
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 (run-wide user abort) and
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.
TOOL_USE_INTERRUPTED_MARKERConstant#
Replacement text for an assistant message whose every content block was
stripped during pairing repair (e.g. the only blocks were orphan
tool_calls). 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.
TOOL_USE_SKIPPED_MESSAGEConstant#
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 so consumers can split "user
cancelled" from "framework superseded".
TRAILERConstant#
Trailer prompting the model to begin. Same on every direction.
ZIDANE_EXTENSION_SKILL_NAMEConstant#
Name of the inline docs skill auto-activated in extension edit sessions.
ZIDANE_SKILL_EDIT_SKILL_NAMEConstant#
Name of the inline preset skill auto-activated in skill edit sessions.
Interfaces#
AgentCacheChangeInterface#
A change a host is about to make, passed to Agent.cacheImpact.
AgentCacheImpactInterface#
What a change would cost the prompt cache, from Agent.cacheImpact.
AgentCompactOptionsInterface#
Options for Agent.compact.
AutoCompactConfigInterface#
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.
AutoCompactInputInterface#
Inputs to 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.
ChildSpawnIdentityInterface#
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).
CommandGenerateDataOptionsInterface#
Options for ctx.generateData — a silent, schema-pinned model call.
CompactHookContextInterface#
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.
CompactionSliceInterface#
Result of sliceForCompaction: the turns to summarize and the turns to keep.
CompactOptionsInterface#
Options for compactConversation.
CompactPromptOptionsInterface#
Options passed to a CompactPromptBuilder.
CompactResultInterface#
Outcome of a successful compactConversation call.
CompactStartEventInterface#
Payload for CompactOptions.onStart.
CompactStartHookContextInterface#
Fired right before the summary call starts. See compact:start.
CompletionSubmitContextInterface#
Context passed to a provider's submit-time hooks.
ConsoleSinkOptionsInterface#
Options shared by consoleSink and jsonSink.
CounterInterface#
Instrument that only increases.
CreateExtensionDepsInterface#
Where createExtension writes.
CreateExtensionInputInterface#
A new extension to scaffold.
CreateExtensionResultInterface#
A scaffolded extension.
DecisionChoiceAnswerInterface#
Answer to a DecisionChoiceQuestion.
DecisionChoiceQuestionInterface#
Pick one of a fixed set of values. Keys are the values, entries describe when each applies.
DecisionPredicateAnswerInterface#
Answer to a DecisionPredicateQuestion.
DecisionPredicateQuestionInterface#
Is a condition true? Answered with a probability in [0, 1].
DecisionRefusalAnswerInterface#
The model declined to answer this question.
DecisionScoreAnswerInterface#
Answer to a DecisionScoreQuestion.
DecisionScoreQuestionInterface#
Rate the input against ordered levels (lowest first). Level indices start at 0.
EditSessionTargetInterface#
What an editing session targets. dir becomes the session's cwd; name
feeds the preset wording (and the skill marker).
EnsureToolResultPairingOptionsInterface#
Options for ensureToolResultPairing.
ExtensionEditMarkerInterface#
Per-edit-session marker persisted on session.metadata[EXTENSION_EDIT_METADATA_KEY].
FrozenPromptSectionsInterface#
The sections the SDK appended to a run's fresh system prompt, exactly as
appended; a section is undefined when the run had none.
FrozenSystemPromptInterface#
The newest snapshot for a prompt key, with its prompt text and the index of the turn holding it.
GeometricThinkingDecayInterface#
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 when
caching is on.
GithubClientInterface#
A GitHub API client that shares quota, pause and ETag state across its callers.
GithubClientOptionsInterface#
Options for createGithubClient.
GithubIdentityInterface#
Who a host's current token is, as far as the client knows.
GithubPullRefInterface#
Identifies one pull request.
GithubRequestInterface#
A request to the GitHub API sent through GithubClient.
GithubStateStoreInterface#
Storage for the shared GitHub quota, pause and account state.
HistogramInterface#
Instrument that records a distribution of values.
HostPerfInterface#
A host's performance monitor: what perf.watch, perf.history and perf.threads answer from.
HostPerfOptionsInterface#
What createHostPerf needs of its host.
InstrumentOptionsInterface#
Options passed to the meter when an instrument is created.
KnownGithubPullInterface#
What a caller already holds for a PR, so an unchanged one isn't read again.
LoggerInterface#
Structured logger that writes records to a LogSink.
LoggingHookSetInterface#
Value returned by createLoggingHooks.
LoggingHooksOptionsInterface#
Options for createLoggingHooks.
LoginMcpServerOptionsInterface#
Options for loginMcpServer.
LoginMcpServerResultInterface#
Outcome of a successful loginMcpServer flow.
LogRecordInterface#
One structured log entry.
LogSinkInterface#
Destination for log records.
MainThreadMeterInterface#
A host's main thread, measured: how busy it was, and (while on) how late its timers ran.
McpCredentialEntryInterface#
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.
McpCredentialStoreInterface#
Persistence for MCP OAuth credentials, keyed by server name.
McpOAuthClientConfigInterface#
McpServerConfig.oauth.
McpOAuthProviderOptionsInterface#
Options for McpOAuthProvider and mcpOAuthProviderFor.
McpStaticClientInterface#
A pre-registered OAuth client. With one set, the provider skips dynamic client registration.
MeterInterface#
Minimal Meter interface — structurally identical to OTel's Meter.
Hosts passing metrics.getMeter(name) (from @opentelemetry/api)
satisfy this without adaptation.
MetricsHookSetInterface#
Value returned by createMetricsHooks.
MetricsHooksOptionsInterface#
Options for createMetricsHooks.
ModelTargetInterface#
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.
ModelTargetSpecInterface#
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.
OAuthCallbackHandleInterface#
Handle to a running one-shot OAuth callback server.
OAuthCallbackOptionsInterface#
Options for startOAuthCallback.
OAuthCallbackResultInterface#
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).
OwnedInterface#
One tick's reading.
OwnedDaemonInterface#
Another host whose tree is sampled too (the desktop app's daemon), as far as this module needs it.
OwnedMcpInstanceInterface#
One MCP server process, as mcp.instances lists it.
OwnedPidInterface#
One owned process; the role is not read here.
PairingRepairInterface#
One repair made by ensureToolResultPairing.
PerfChannelInterface#
One IPC channel's counters since start or the last reset.
PerfGpuInterface#
Whole-GPU use (every app's: macOS has no per-process figure).
PerfLagInterface#
The host's event-loop delay over the last interval, ms.
PerfOsThreadInterface#
One OS thread of a process. macOS gives no names (label empty).
PerfProcessInterface#
One process of the app, a host, or a program either started.
PerfProcessMcpInterface#
The MCP server a process runs (mcp.instances).
PerfProcessSessionInterface#
The session a process runs for.
PerfSampleInterface#
One sample: every 2 s while someone watches.
PerfSlowFrameInterface#
Where long frames (over 50 ms) spent their time: one script and function, summed.
PerfThreadInterface#
A thread the app can name: a host's event loop, a worker, a window's main thread or worker.
PerfTotalsInterface#
CPU (percent of one core) and resident memory (bytes), summed.
PersistInputInterface#
Inputs to 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.
PostCompactAttachmentsInterface#
Envelope returned by buildPostCompactAttachments. The caller
spreads turns into session.appendTurns([summaryTurn, ...turns]).
Count fields drive UI banners ("restored 5 files + 2 skills").
PostCompactRestoreOptionsInterface#
Options for buildPostCompactAttachments.
ProviderLimitInterface#
A rate limit, spent quota or overload, as describeProviderLimit words it.
PsRowInterface#
One OS process, as ps reports it.
RecentFileInterface#
One file selected for restoration, with its last-read timestamp for ranking.
RemintResultInterface#
Result of remintDuplicateToolCallIds.
RingInterface#
A fixed-capacity list that drops its oldest item when full.
RingBufferSinkInterface#
Live handle over a createRingBufferSink — the read side the logs viewer consumes.
SamplerInterface#
A sampling loop that runs only while someone watches.
SamplerOptionsInterface#
What createSampler samples, and how often.
ScheduleInterface#
A stored schedule.
ScheduleFireInterface#
One fire of a schedule, newest first in schedules.fires.
ScheduleInputInterface#
What schedules.create takes.
ScheduleListFilterInterface#
What schedules.list filters on.
ScheduleNewSessionInterface#
The session a newSession prompt action creates on each fire.
SchedulePatchInterface#
What schedules.update takes: the fields to change. expiresAt: null keeps a schedule for good (you pinned it).
SessionArtifactDirMigrationInterface#
Outcome of one migrateSessionArtifactDirs sweep.
SessionPidInterface#
One process started for a session, as daemon.sessionProcesses lists it.
SkillEditMarkerInterface#
Per-edit-session marker persisted on session.metadata[SKILL_EDIT_METADATA_KEY].
SpanInterface#
Minimal span shape — any tracer that provides these methods is compatible.
SpawnQueuedContextInterface#
spawn:queued: a top-level spawn call waiting for a free slot.
SqliteDatabaseLikeInterface#
What createSqliteDriver wraps: a bun:sqlite Database or a node:sqlite DatabaseSync.
SqliteDriverInterface#
The connection surface the session store needs.
SqliteSessionStoreOptionsInterface#
Options for createSqliteSessionStore.
SqliteStatementInterface#
A prepared statement. get returns undefined when no row matches.
SqliteStoreFileInterface#
The file behind a SQLite store, for readers on their own connection (sqliteStoreFile).
SqliteWriteQueueInterface#
Serializes a connection's writes and retries SQLITE_BUSY on timers.
StandardSchemaLikeInterface#
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.
StepThinkingDecayInterface#
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 by the absence of factor.
StreamProgressHookContextInterface#
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.
StreamUsageSnapshotInterface#
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.
SummaryToTurnInputInterface#
Input shape for 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.
SystemFreezeOptionsInterface#
See AgentRunOptions.systemFreeze.
SystemPromptSnapshotInterface#
A frozen system prompt's bookkeeping, carried by a role: 'system' turn
(see SessionTurn.systemSnapshot).
TokenUsageLikeInterface#
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.
ToolGateResumeFieldsInterface#
What tool:gate carries for a call of a resumed checkpoint run. See AgentHooks['tool:gate'].
ToolProgressInterface#
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.
TracingHookSetInterface#
Value returned by createTracingHooks — install entrypoint.
TracingHooksOptionsInterface#
Options for createTracingHooks.
TreeInputInterface#
What treeProcesses turns into rows.
TreeRootInterface#
How a tree's root shows: a host process (the daemon, a server).
UpDownCounterInterface#
Instrument whose value can go up and down.
UsageAssistantDayRowInterface#
One model's usage on one day (assistant turns and compaction summaries).
UsageBucketsInterface#
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).
UsageSessionDayRowInterface#
Sessions created on one day.
UsageUserDayRowInterface#
Human messages in one hour of one day.
Types#
AgentCompactResultType#
Result of Agent.compact.
AutoCompactType#
AgentBehavior.autoCompact value: true enables loop-native
auto-compaction with defaults, false / omitted disables it, and an
AutoCompactConfig enables it with overrides.
AutoCompactDecisionType#
Result of shouldAutoCompact: fire with the usage figures, or skip with the reason.
CacheTtlType#
Prompt-cache entry lifetime. See AgentBehavior.cacheTtl.
ChildSpawnHookContextType#
Payload of child:spawn:before / child:spawn:error: the spawned agent's
SpawnHookContext plus 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.
CompactDirectionType#
Identifier for the section of the conversation being summarized.
CompactEndEventType#
Payload for CompactOptions.onEnd: the result on success, or the thrown error with the elapsed time on failure.
CompactEndHookContextType#
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.
CompactFunctionType#
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:transformview the provider will see. The framework treats the returned array as the new wire payload;ctx.session/ctx.turnsare never modified. - Must preserve
tool_use ↔ tool_resultadjacency. Stranding atool_usewithout its matchingtool_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.
CompactPromptBuilderType#
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.
CompactScopeType#
What to summarize and what to preserve verbatim.
'full'— summarize everything, no preserved tail.'tail'— summarize everything before the lastkeepTurnsturns.{ kind: 'from', turnId }— summarize from the anchor turn onward.{ kind: 'up_to', turnId }— summarize up to (and including) the anchor.
CpuMemoryType#
CPU seconds per pid at the previous sample, for the rows' CPU.
DecisionAnswerForType#
Answer type for one question, refusal included.
DecisionInputKindType#
Shape of a decision input as reported to hooks: plain text, a JSON object, or prompt parts.
DecisionScoreLevelType#
One ordered level of a score rubric: a bare label, or a label with criteria.
DedupHasherType#
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.
DedupToolConfigType#
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
hasherplus amode:'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 reachesthreshold, then refuse withBlocked: <reason>viatool: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 reachesthreshold); 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.
GithubAnswerType#
A request's outcome. text is the raw body.
GithubPullReadType#
Result of reading one pull request. Narrow on kind.
InferSchemaOutputType#
Output type carried by a StandardSchemaLike; unknown for plain JSON Schema.
InjectedTurnReasonType#
Why the agent loop injected a user turn (see SessionTurn.injected).
JsonValueType#
Any value that survives JSON.stringify and JSON.parse unchanged.
LogLevelType#
Severity levels, from least to most severe.
MetricAttributesType#
Attributes attached to a measurement.
PairingRepairModeType#
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.
PerfChannelDirectionType#
invoke: renderer → main request, timed to the answer; send: renderer → main message; push: main → renderer.
PerfOriginType#
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.
PerfProcessKindType#
What a process is to the app. daemon: a host process (the daemon, a server).
PersistOutcomeType#
Result of maybePersistToolResult: a skip with its reason, a persisted blob with its stub, or a write failure.
ProviderLimitReasonType#
Why a provider turned a request away for capacity or account limits rather than for its content.
ReadonlySqliteSessionStoreType#
What createReadonlySqliteSessionStore serves: reads only.
ReasoningWireActionType#
What a wire builder should do with a reasoning block for a given target.
ScheduleActionType#
What a fire does.
ScheduleCatchUpType#
What to do with the fires that a host missed while no host was running.
ScheduleCreatorType#
Who made a schedule.
ScheduleFireOutcomeType#
How one fire went.
ScheduleTriggerType#
When a schedule fires.
SchemaInputType#
A schema-accepting input: plain JSON Schema, or a Standard Schema (e.g. zod v4).
SectionChangeNoteType#
A note announcing one changed section, with the text the model reads.
SqlValueType#
A value SQLite binds or returns.
StaleReadPolicyType#
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.
StartSpanType#
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.
ThinkingDecayType#
Thinking-budget decay schedule. See AgentBehavior.thinkingDecay for
semantics and the measured prompt-cache cost of each form.
TracingConventionsType#
Gen-AI attribute convention set emitted on spans: 'sentry', 'otel' or 'both'.
TurnInterruptionStateType#
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 onetool_callblock with no matchingtool_resultanywhere 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.
Re-exports#
These names are documented on the entry point that owns them.
- AccessScope
- ActionSetting
- ActionSettingContext
- ActionSettingResult
- ActionSettingStatus
- ActionSettingStatusContext
- ActionSettingValue
- AddFn
- AgentEditor
- AgentsDomain
- AppInfo
- artifactKindLabel
- ArtifactResolveOptions
- ArtifactsDomain
- BadgeAction
- BadgeActionEffect
- BadgeActionsMatch
- BadgeActionSpec
- BadgeActionWire
- badgeMenu
- BadgeMenuItem
- BadgeTarget
- BadgeTargetKind
- Bindable
- BooleanSetting
- buildExtensionPreset
- buildExtensionRegistry
- BuildExtensionRegistryOptions
- BUILTIN_ARTIFACT_KINDS
- CatalogDomain
- CatalogEditor
- clampExtensionConfigNumber
- Cleanup
- coerceExtensionConfigInput
- CommandListing
- CommandsDomain
- CommandSource
- CommandSpec
- compileReferencePattern
- COMPLETION_TIMEOUT_MS
- completionProviderSummaries
- CompletionRunner
- ComponentRef
- ComponentWire
- composeExtensionPreset
- ComposerDomain
- Connection
- ContextSection
- ContextSectionItem
- ContextSectionWire
- Contract
- ContractsDomain
- ContractToken
- createArtifactDetectHook
- createArtifactsSurface
- createCompletionRunner
- createExtensionHostRuntimeBridge
- createExtensionPromptBridge
- createReferenceResolver
- createSharedWatches
- createWorkspaceSurface
- Credential
- defaultExtensionScanPaths
- defineExtension
- DesktopDomain
- DialogOptions
- DialogRequest
- DialogTimeoutError
- discoverAndBuildExtensionRegistry
- DiscoverAndBuildExtensionRegistryOptions
- discoverExtensions
- Disposable
- DisposedError
- disposeExtensionRegistry
- EMPTY_EXTENSION_REGISTRY
- ENTRY_CANDIDATES
- EnumSetting
- EXTENSION_API_VERSION
- ExtensionActionRunResult
- ExtensionActionSummary
- ExtensionApiVersion
- ExtensionApprovalDecision
- ExtensionArtifactDetection
- ExtensionArtifactKindRegistration
- ExtensionArtifactQuery
- ExtensionArtifactRow
- ExtensionArtifactRowFact
- ExtensionArtifactScope
- extensionBadgeActions
- ExtensionBadgeActions
- ExtensionBadgeColor
- ExtensionBadgeIcon
- ExtensionBadgeTone
- ExtensionBehaviorTransform
- ExtensionCatalogPartition
- ExtensionCompletionItemSummary
- ExtensionCompletionProviderSummary
- ExtensionConfigActionItem
- ExtensionConfigActionResult
- ExtensionConfigActionStatus
- ExtensionConfigBooleanItem
- ExtensionConfigCategory
- ExtensionConfigChangeBehavior
- ExtensionConfigEnumItem
- ExtensionConfigItem
- ExtensionConfigItemBase
- ExtensionConfigModelItem
- ExtensionConfigNumberItem
- ExtensionConfigScope
- ExtensionConfigStringItem
- ExtensionConfigValue
- ExtensionConfigValueItem
- ExtensionContext
- ExtensionContextPanelSection
- ExtensionContributions
- ExtensionCreateSessionParams
- ExtensionDefinition
- ExtensionEventQuery
- ExtensionFetchResult
- ExtensionFooterHint
- ExtensionHostKind
- ExtensionHostRuntimeBridge
- ExtensionHostRuntimeImpl
- ExtensionInfo
- ExtensionInstallCandidate
- ExtensionInstallError
- ExtensionInstallErrorCode
- ExtensionInstallIo
- ExtensionInstallProvenance
- ExtensionInstallResult
- ExtensionInstallScope
- ExtensionInstallSource
- ExtensionKeybinding
- ExtensionKeybindingDispatchContext
- ExtensionManifest
- ExtensionMcpConfigTransform
- ExtensionMcpHost
- ExtensionMcpServerInfo
- ExtensionMcpToolResult
- ExtensionModelEntry
- ExtensionOrchestrationTool
- ExtensionOrderedContribution
- ExtensionPaletteItem
- ExtensionPaletteProviderEntry
- ExtensionPaletteRunResult
- ExtensionPanel
- ExtensionPanelEntry
- ExtensionPanelScope
- ExtensionPaths
- ExtensionPendingRequest
- ExtensionPromptBridge
- ExtensionPromptDelivery
- ExtensionReferenceCard
- ExtensionReferenceCardFact
- ExtensionReferencePattern
- ExtensionReferenceProvider
- ExtensionReferenceSurface
- ExtensionReferenceView
- ExtensionRegistry
- ExtensionRunSettledEvent
- ExtensionRunSettledHandler
- ExtensionRuntimeEnv
- ExtensionRuntimeSurface
- ExtensionRunTransform
- ExtensionScanEntry
- ExtensionSessionBadge
- ExtensionSessionBadgeCardRow
- ExtensionSessionControl
- ExtensionSessionDetail
- ExtensionSessionEvent
- ExtensionSessionEventHandler
- ExtensionSessionRow
- ExtensionSessionScope
- ExtensionSessionsSurface
- ExtensionSessionVerbs
- ExtensionSkillPolicy
- ExtensionSource
- ExtensionToolCatalogTransform
- ExtensionToolResultMetadataRegistration
- ExtensionUiSurface
- ExtensionWaitResult
- ExtensionWorkspaceOps
- ExtensionWorkspacePair
- ExtensionWorkspaceSurface
- fetchExtensionSource
- fetchGithubPullRequest
- filterExtensionRegistry
- findReferences
- GeneratedImage
- GenerateDomain
- GenerateImageOptions
- GITHUB_ISSUE_PROVIDER_ID
- GITHUB_PULL_PROVIDER_ID
- githubIssueView
- githubPullUrl
- githubPullView
- githubRateLimitText
- Handle
- HookEvents
- HooksDomain
- HttpRequestInput
- HttpResponseInput
- Infer
- inlineLoadedExtension
- InstalledExtensionTargetOptions
- installExtensionFromSpec
- InstallExtensionFromSpecOptions
- InstructionsDomain
- IntegrationCustomMethod
- IntegrationCustomResult
- IntegrationFlowIO
- IntegrationHandle
- IntegrationMethod
- integrationMethodFromOAuthProvider
- IntegrationsDomain
- IntegrationSpec
- IntegrationSpecPatch
- InterceptOptions
- InterceptorHandler
- Interceptors
- isBadgeColor
- isPullFresh
- isValidExtensionConfigItem
- isValidExtensionConfigValue
- ItemOrigin
- Json
- JsonSchema
- KeymapDomain
- KeymapEntry
- KeyScope
- KeyValue
- LinkHandler
- LinkHandlerItem
- LinkSource
- listActionSummaries
- listExtensionCandidates
- listExtensionPaletteItems
- Live
- LiveAccessor
- loadableExtensionDirs
- LoadedExtension
- LoadedExtensionSource
- LoadedPluginRecord
- loadExtensionPanel
- MAX_COMPLETION_ITEMS
- MAX_COMPOSER_BADGES
- McpDomain
- McpServerStatus
- McpToolDescriptor
- Menu
- MenuItem
- MenuWire
- ModelEditor
- ModelsDomain
- ModelSetting
- NamedTool
- normalizeBadgeTarget
- NoUiError
- NumberSetting
- OnOptions
- Owner
- PaletteProviderSpec
- Panel
- PanelAction
- PanelBarsItem
- PanelBarsPoint
- PanelBarsSeries
- PanelContent
- PanelContentItem
- PanelControl
- PanelControlOption
- PanelCustomItem
- PanelFocus
- PanelHeatmapDay
- PanelHeatmapItem
- PanelHomeLayout
- PanelHostDeps
- panelHostRuntime
- PanelIcon
- PanelItem
- PanelKeyValueItem
- PanelKeyValueRow
- PanelLoadContext
- PanelLoadContextInput
- PanelLoadScope
- PanelMarkdownItem
- PanelMore
- PanelRowAction
- PanelRowItem
- PanelScopeDeps
- PanelSearch
- PanelSection
- PanelStartSession
- PanelStat
- PanelStatsItem
- panelSummaries
- PanelSummary
- PanelSurface
- PanelView
- panelViewValue
- panelViewValues
- PanelWire
- parseExtensionInstallSource
- parseExtensionScanPathEnv
- parseGithubRefKey
- partitionExtensionCatalog
- PluginsDomain
- precompileExtension
- probeActionStatuses
- PromptInput
- ProviderEditor
- ProvidersDomain
- pruneExtensionCompileCache
- pullFromMeta
- pullMeta
- Readable
- readExtensionInstallProvenance
- Reference
- ReferenceMatch
- ReferenceProviderWire
- referenceProviderWires
- ReferenceResolver
- refreshArtifact
- registerExtensionApiHostModules
- registerExtensionHostModules
- Registry
- RegistryToken
- removeInstalledExtension
- renderArtifactRow
- Renderer
- RendererItem
- RendererTarget
- RendererWire
- resolveArtifactKind
- resolveExtensionCompletionSubmit
- resolveExtensionConfig
- resolveExtensionConfigValue
- Rpc
- RpcCallContext
- RpcCallError
- RpcClient
- RpcContract
- RpcDomain
- RpcError
- RpcEvent
- RpcEvents
- RpcEventSpec
- RpcImplementation
- RpcMethodSpec
- RpcRegistration
- runBadgeAction
- runExtensionAction
- runExtensionPaletteItem
- runExtensionPanelAction
- RunSettledEvent
- sanitizeExtensionConfigActionPatch
- scanExtensionDirectories
- ScheduleFireEvent
- SchedulesDomain
- Schema
- Screen
- ScreenItem
- ScreenWire
- SelectOption
- SessionBadgeEntry
- sessionBadges
- SessionEvent
- SessionFacetsDomain
- SessionFacetSpec
- SessionFacetTrigger
- SessionFields
- SessionInfo
- SessionListPage
- SessionListQuery
- SessionListRow
- SessionListStatus
- sessionsBadges
- SessionsDomain
- SessionSnapshot
- Setting
- SettingApply
- SettingBase
- SettingsCategory
- SettingScope
- SettingsDomain
- SettingsPage
- SettingsPageItem
- SettingsPageSpec
- SettingsPageWire
- SettingsSchema
- SettingValue
- SharedWatches
- SidebarBadge
- SidebarChip
- SidebarDecoration
- SidebarDecorationItem
- SidebarDecorationWire
- SidebarFilter
- SidebarFilterItem
- SidebarFilterOption
- SidebarFilterWire
- SidebarGroup
- SidebarGroupItem
- SidebarGroupWire
- SidebarRow
- SidebarRowAction
- SidebarRowActionWire
- SidebarRowItem
- SidebarRowOpen
- SidebarRowStatus
- SidebarRowWire
- SidebarSort
- SidebarSortItem
- SidebarSortWire
- SidebarText
- SkillsDomain
- Slot
- SlotItem
- SlotName
- SlotWire
- Space
- SpaceItem
- SpaceNewSession
- SpaceWire
- StorageDomain
- StoragePathScope
- StorageScope
- Store
- StoredExtensionConfigItem
- StoreOptions
- StringSetting
- subscribeExtensionPalette
- subscribeExtensionPanel
- suggestCompletionItems
- SyncInterceptorName
- ThemeToken
- ToolCallDecision
- ToolCallResult
- ToolEditor
- ToolMetadataNamespace
- ToolResultDecision
- ToolsDomain
- toWireConfigSchema
- Transform
- TuiContributions
- UiDomain
- UiEntry
- UiToken
- updateInstalledExtension
- usableCompletionProviders
- ValueKeys
- viewForRead
- Webview
- WebviewItem
- WebviewWire
- WireExtensionConfigItem
- WireExtensionConfigSchema
- WireSettings
- WireSettingsExtension
- WorkspaceDomain
- ActivationVia
- ActiveSkill
- buildCatalog
- createSkillActivationState
- DeactivationReason
- defineSkill
- discoverSkills
- IMPLICITLY_ALLOWED_SKILL_TOOLS
- installAllowedToolsGate
- installSkillFromSpec
- interpolateShellCommands
- InterpolateShellCommandsOptions
- isToolAllowedByUnion
- listSkillCandidates
- matchesAllowedTool
- parseAllowedToolPattern
- parseSkillFile
- parseSkillInstallSpec
- readSkillProvenance
- resolveSkills
- ShellInterpolationApproval
- SkillActivationState
- SkillActivationStateOptions
- SkillConfig
- SkillDiagnostic
- SkillInstallCandidate
- SkillInstallError
- SkillInstallErrorCode
- SkillInstallOptions
- SkillInstallResult
- SkillInstallSpec
- SkillResource
- SkillsConfig
- SkillSource
- SkillValidationIssue
- SkillValidationResult
- SourcedScanPath
- stripShellInterpolations
- validateResourcePath
- validateResourcePathReal
- validateSkillForWrite
- validateSkillName
- writeSkillsToDisk
- writeSkillToDisk
- Agent
- AgentHookMap
- AgentHooks
- AgentOptions
- CacheBreakInfo
- CacheBreakLoggerOptions
- CacheDimensionDiff
- CacheDimensionName
- CacheDimensionSnapshot
- CacheDriftInfo
- CachePromptSections
- CacheSystemSection
- createAgent
- createRunSummaryCollector
- diffCacheDimensions
- fnv1a32
- hashMessages
- installCacheBreakLogger
- McpConnector
- McpToolMeta
- McpToolWrap
- RunSummary
- RunSummaryBlock
- RunSummaryBudget
- RunSummaryByModel
- RunSummaryCollector
- RunSummaryCollectorOptions
- RunSummaryError
- RunSummaryRepeatGuard
- RunSummaryTokens
- RunSummaryValidation
- snapshotCacheDimensions
- AgentAbortedError
- AgentAuthError
- AgentBudgetExceededError
- AgentContextExceededError
- AgentProviderError
- AgentToolNotAllowedError
- AgentToolPairingError
- AuthFailure
- AuthFailureKind
- ClassifiedError
- ClassifiedErrorKind
- CONTEXT_EXCEEDED_MESSAGE_PATTERNS
- errorMessage
- matchesContextExceeded
- OperationTimeoutError
- toTypedError
- AgentBehavior
- AgentDecide
- AgentDecisionsOptions
- AgentHookBus
- AgentHookHandlers
- AgentRunOptions
- AgentStats
- AgentToolState
- DecideHookContext
- DecisionAnswer
- DecisionAnswers
- DecisionEndHookContext
- DecisionFailure
- DecisionFailureReason
- DecisionInput
- DecisionOutcome
- DecisionQuestion
- DecisionQuestions
- DecisionRequest
- DecisionStartHookContext
- DecisionSuccess
- DecisionUsage
- flattenTurns
- McpServerConfig
- McpToolHookContext
- ModelUsage
- MutationValidationBatch
- MutationValidationFailure
- MutationValidationHooksOptions
- MutationValidationMutation
- MutationValidationResult
- OAuthRefreshHookContext
- ProgressNudgeKind
- ProgressNudgeMessage
- PromptAudioPart
- PromptDocumentPart
- PromptImagePart
- PromptPart
- PromptTextPart
- PromptVideoPart
- QueuedMessageOptions
- QueuedUserMessage
- RepeatGuardConfig
- RepeatGuardToolMatcher
- ResolveContentRef
- ResolveContentRefBlock
- RetryConfig
- RunHookMap
- SessionContentBlock
- SessionEndStatus
- SessionHookContext
- SessionMessage
- SessionTurn
- SpawnHookContext
- StagedToolState
- statsByModel
- StreamHookContext
- SuccessfulMutationOutcome
- ThinkingLevel
- ToolHookContext
- ToolOutcome
- toolOutputBudgetByteLength
- toolOutputByteLength
- ToolResultAudioContent
- ToolResultContent
- ToolResultDocumentContent
- ToolResultDocumentRefContent
- ToolResultImageContent
- ToolResultImageRefContent
- ToolResultMetadata
- ToolResultTextContent
- toolResultToText
- ToolResultVideoContent
- ToolStateController
- ToolStateOp
- ToolStateStore
- ToolStateView
- TurnFinishReason
- TurnUsage
- agentPluginsSchemaId
- AgentPluginsVersion
- defaultPluginDataRoot
- expandPluginVars
- isSupportedAgentPluginsVersion
- loadAgentPlugin
- LoadAgentPluginOptions
- LoadedPlugin
- ManifestValidation
- parsePluginManifest
- parseSchemaId
- PLUGIN_MANIFEST_FILE
- PLUGIN_MCP_FILE
- PLUGIN_SKILLS_DIR
- PluginAuthor
- PluginComponentStatus
- PluginDiagnostic
- PluginManifest
- PluginSchemaKind
- SUPPORTED_AGENT_PLUGINS_VERSIONS
- validatePluginManifest
- AgentProfile
- AnswerValue
- CommandAgentResult
- CommandAttachment
- CommandExecution
- CommandInteraction
- CommandOutputBlock
- CommandSpawnResult
- CommandSpawnTask
- CommandStep
- CommandStepContext
- CommandStepFn
- CommandStepResult
- commandSteps
- ConfirmQuestion
- createPathAutocompleteProvider
- CustomField
- executeCommand
- generateStructuredData
- GenerateStructuredDataOptions
- InlineAutocompleteContext
- InlineAutocompleteProvider
- InteractionResponse
- ModelInfo
- ModelOption
- PlanDecision
- PlanProposal
- PlanProposalStep
- PlanResponse
- ProviderDescriptor
- ProviderFactoryOptions
- ProviderUsageProbe
- ProviderUsageReport
- Question
- QuestionChoice
- QuestionPayload
- QuestionResponse
- QuestionType
- resolveInlineSuggestion
- SelectQuestion
- TextQuestion
- AppendTurnsOptions
- ARTIFACT_KINDS
- ArtifactFilter
- ARTIFACTS_METADATA_KEY
- ARTIFACTS_PER_SESSION_CAP
- autoDetectAndConvert
- createFileMapStore
- createMemoryStore
- createRemoteStore
- createSession
- CreateSessionOptions
- dropInvalidToolPairings
- FileMapAdapter
- FileMapStoreOptions
- fromAnthropic
- fromOpenAI
- loadSession
- LoadSessionOptions
- matchesArtifactFilter
- mergeArtifact
- mergeSessionMetadata
- normalizeArtifactInput
- PairingDrop
- PairingDropKind
- RemoteStoreOptions
- RunEstimate
- RunEstimateFailure
- RunUserWait
- SaveMetaOptions
- selectArtifactEvictions
- Session
- SessionArtifact
- SessionArtifactInput
- SessionData
- SessionHistory
- SessionMetaRow
- SessionRun
- SessionRunAgent
- SessionStore
- sortArtifacts
- StoredRunOptions
- toAnthropic
- toOpenAI
- toWireMessages
- ToWireMessagesOptions
- UpdateRunOptions
- artifactPath
- buildEvalRunSummary
- buildRegisteredEvals
- buildTrajectory
- clearRegisteredEvals
- computeEvalTagScores
- createEvalAgent
- CreateEvalAgentOptions
- createEvalRunReporter
- createReusableExecutionContext
- defineEval
- defineMetrics
- EFFICIENCY_METRICS
- efficiencyMetricValues
- emitEfficiencyMetrics
- EvalAgent
- EvalAgentMcpServers
- EvalAgentRunOptions
- EvalAgentRunResult
- EvalAgentRunStats
- EvalAgentStats
- EvalArtifacts
- EvalCaseOptions
- EvalCaseResult
- EvalDefinition
- EvalDefinitionContext
- EvalMetric
- EvalMetricError
- EvalRunMetricAggregate
- EvalRunReporter
- EvalRunReporterOptions
- EvalRunSummary
- EvalRunSummaryCase
- EvalRunUsage
- EvalScore
- EvalScorer
- EvalScorerContext
- EvalTestRunner
- EvalVariantSummary
- EvalWorkspaceFile
- EvalWorkspaceOptions
- EvalWorkspaceSnapshot
- fileContains
- fileContentQuality
- fileExists
- fileExistsOneOf
- finalizeEvalMetrics
- formatEvalCaseSummary
- formatEvalRunSummary
- formatTrajectoryLine
- functionalityMetric
- llmJudge
- LlmJudgeOptions
- MetricDirection
- MetricEmitter
- MetricSpec
- MetricSpecMap
- MetricStats
- normalizeMetric
- registerEvalTests
- RegisterEvalTestsOptions
- relativeArtifactPath
- ReusableExecutionContext
- runEvalCase
- statusCompleted
- Trajectory
- TrajectoryStep
- TrajectoryStepKind
- BackgroundTaskStatus
- ContextCapabilities
- ContextHardening
- ContextMount
- ContextType
- createProcessContext
- DetachedTasksCapability
- ExecResult
- ExecutionContext
- ExecutionHandle
- isolationAvailability
- IsolationBackend
- IsolationPolicy
- ListFileMetadata
- ListFilesEntry
- ListFilesOptions
- listOwnedProcesses
- listSessionProcesses
- OwnedProcess
- OwnedProcessRole
- parseAllowWriteSetting
- registerSessionProcess
- resolveDetachedTasksCapability
- resolveWritableRoots
- resolveWritableRootsAsync
- SessionProcess
- SpawnConfig
- StreamHandle
- TaskEntry
- TaskExitInfo
- TaskHandle
- TaskStallInfo
- ChildAgent
- createGenerateImageTool
- createInteractionTool
- createModelSearchTool
- createShellTool
- CreateShellToolOptions
- createSkillsReadTool
- createSkillsRunScriptTool
- createSkillsUseTool
- createSpawnTool
- edit
- ExtensionSubagentDef
- formatModelLine
- GenerateImageToolOptions
- getReadState
- glob
- grep
- hashContent
- hydrateReadStateFromSession
- hydrateReadStateFromSessionAsync
- HydrateReadStateOptions
- ImageModelSource
- InteractionToolOptions
- isSpawnTool
- matchModelEntries
- multiEdit
- ReadStateEntry
- readStateKey
- ReadStateMap
- resolveReadStateMap
- SkillsReadToolOptions
- SkillsRunScriptToolOptions
- SkillsUseToolOptions
- SpawnModelEntry
- SpawnTaskInput
- SpawnTaskOutcome
- SpawnTool
- SpawnToolOptions
- SpawnToolState
- SubagentDef
- SubagentOverride
- SubagentRegistry
- ToolContext
- ToolDef
- ToolDescriptionOverride
- ToolDescriptions
- ToolDescriptionTarget
- ToolMap
- validateToolArgs
- ValidationResult
- waitTask
- withIsolatedSpawnTool
- Command
- CommandArgSuggestion
- CommandInvocation
- compileQuery
- CompletionContext
- CompletionItem
- CompletionProvider
- CompletionReference
- ContextBreakdown
- ContextBreakdownContributionContext
- ContextBreakdownContributor
- ContextBreakdownOptions
- ContextCategory
- ContextCategoryId
- ContextExactCounts
- ContextExtensionRow
- ContextExtensionSection
- ContextItem
- ContextMcpGroup
- ContextSegment
- ContextSegmentFile
- ContextSegmentOrigin
- ContextSegmentsInput
- ContextSnapshot
- ContextUsageSplit
- escapeTemplate
- FacetPath
- formatLogLine
- InlineGhost
- parseCommandInvocation
- patchInlineGhost
- QueryBound
- querySessions
- QueryValue
- SessionCondition
- SessionFieldName
- SessionFieldPath
- SessionGroupBy
- SessionGroupOrder
- SessionQuery
- SessionQueryAll
- SessionQueryAny
- SessionQueryEnvironment
- SessionQueryError
- SessionQueryIssue
- SessionQueryNot
- SessionSort
- credentialsFilePath
- credentialsFromParams
- extractRuntimeCredentials
- getModelCatalog
- getOAuthApiKey
- getOAuthProvider
- HistoryRepair
- ImageAspectRatio
- ImageData
- ImageModelInfo
- isOAuthAccessToken
- mistral
- MistralParams
- ModelCatalog
- ModelCatalogEntry
- ModelCatalogSource
- OAuthParams
- OAuthProviderInterface
- pinnedAccountMissingError
- Provider
- ProviderCapabilities
- ProviderDecisionAvailability
- ProviderDecisionRequest
- ProviderDecisionResponse
- ProviderDecisions
- ProviderImageAvailability
- ProviderImageRequest
- ProviderImageResponse
- ProviderImages
- ProviderMeta
- readAccountOAuthCredential
- readOAuthCredentials
- refreshAnthropicToken
- refreshOpenAICodexToken
- registerCustomOAuthProvider
- registerOAuthProvider
- resolveOAuthApiKey
- ResolveOAuthApiKeyOptions
- sanitizeToolSchema
- sanitizeToolSpecs
- SchemaSanitizeOptions
- SchemaSanitizeProfile
- SchemaSanitizeResult
- setModelCatalog
- StreamCallbacks
- StreamOptions
- ToolCall
- ToolResult
- ToolSpec
- TurnResult
- writeOAuthCredentials