Skip to content

zidane/core

The agent, tools, hooks, sessions and the fetch-based providers, with no Node built-in in the import graph, for browsers, Workers and edge functions.

import { … } from 'zidane/core'src/core-entry.ts

Use zidane/core where there is no Node: a page, a Worker, or Deno with only --allow-env (Supabase and Netlify Edge Functions). Its createAgent() makes the same agent as zidane/agent, without the host's capabilities:

  • An agent without execution runs in createNoneContext(): no files and no commands.
  • Images are sent as they are, without being shrunk.
  • mcpServers needs an mcpConnector. skills, behavior.views and behavior.codemode refuse to start, and name the Node entry that has them.
  • anthropic() takes its key from apiKey, access or ANTHROPIC_API_KEY, never reads the credentials file and never refreshes a token.
  • openrouter() has no image generation and no stored settings.

On Node, zidane and zidane/agent create the agent with every capability.

TypeScript
import { anthropic, createAgent, createMemoryStore, createSession } from 'zidane/core'

const session = await createSession({ store: createMemoryStore() })
const agent = createAgent({
  // A site proxy that adds the key: the page holds none.
  provider: anthropic({ baseURL: '/api/anthropic', allowBrowser: true, betas: false }),
  session,
})
await agent.run({ prompt: 'Say hello.' })

Functions#

anthropicFunction#

The Anthropic provider without the credentials file: its key comes from apiKey, access or ANTHROPIC_API_KEY, never refreshed, and account or credentialsPath throw. zidane/providers/anthropic has the rest.

TypeScript
function anthropic(params?: AnthropicParams): Provider
Parameters
NameTypeDescription
params?AnthropicParams

API key, default model, base URL, headers and beta flags.

Provider

The provider.

src/core-entry.ts:55

createAgentFunction#

Creates an agent with no host capabilities (see the module comment).

TypeScript
function createAgent(options: AgentOptions): Agent
Parameters
NameTypeDescription
optionsAgentOptions

Agent options. Only provider is required.

src/core-entry.ts:43

createMemoryStoreFunction#

Creates an in-memory SessionStore. Nothing is persisted.

TypeScript
function createMemoryStore(): SessionStore
Example
import { createMemoryStore, createSession } from 'zidane/session'

const session = await createSession({ store: createMemoryStore() })

src/session/memory.ts:36

createNoneContextFunction#

A context that spawns a handle and nothing else (see the module comment).

TypeScript
function createNoneContext(): ExecutionContext

src/contexts/none.ts:14

createRemoteStoreFunction#

Creates a SessionStore that talks to a REST session API over HTTP. See the module comment for the endpoints it calls.

TypeScript
function createRemoteStore(options: RemoteStoreOptions): SessionStore
Parameters
NameTypeDescription
optionsRemoteStoreOptions

API base URL, headers and timeout.

Example
import { createRemoteStore, createSession } from 'zidane/session'

const store = createRemoteStore({ url: 'https://api.example.com', headers: { authorization: 'Bearer token' } })
const session = await createSession({ store })

src/session/remote.ts:57

createSessionFunction#

Create a new session. Async so stores that generate IDs server-side (e.g. a database) can be supported.

TypeScript
function createSession(options?: CreateSessionOptions): Promise<Session>
Parameters
NameTypeDefaultDescription
options?CreateSessionOptions{}

Session identity, metadata and store. See CreateSessionOptions.

Promise<Session>
Example
import { createMemoryStore, createSession } from 'zidane/session'

const session = await createSession({ agentId: 'reviewer', store: createMemoryStore() })
console.log(session.id, session.turns.length)

src/session/index.ts:1373

fnv1a32Function#

FNV-1a, 32 bits, over the UTF-16 code units of value: a tiny, dependency-free, deterministic, non-cryptographic hash for change detection, cache keys and seeds. The full code unit goes into the mix (not its low byte), so non-ASCII changes are seen. Every rendering (base36, hex, a seed) is built on this one.

TypeScript
function fnv1a32(value: string, seed?: number): number
Parameters
NameTypeDefaultDescription
valuestring

String to hash.

seed?numberFNV1A32_OFFSET

A running hash to continue (another fnv1a32 or fnv1aMix), so a hash is built in parts without joining strings. Default: the offset basis.

number

The hash, an unsigned 32-bit integer.

src/base/hash.ts:17

hasAsyncContextFunction#

Whether a scope follows awaits on this runtime.

TypeScript
function hasAsyncContext(): boolean
boolean

src/async-scope.ts:42

loadSessionFunction#

Load an existing session from a store.

TypeScript
function loadSession(
  store: SessionStore,
  sessionId: string,
  options?: LoadSessionOptions,
): Promise<Session | null>
Parameters
NameTypeDefaultDescription
storeSessionStore

Store to load from.

sessionIdstring

Id of the session to load.

options?LoadSessionOptions{}

Load options. See LoadSessionOptions.

Promise<Session | null>

The session, or null when the store has no session with that id.

src/session/index.ts:1691

openrouterFunction#

The OpenRouter provider without image generation (pi-ai's catalog) or the host's stored settings: its key comes from apiKey or OPENROUTER_API_KEY. zidane/providers/openrouter has the rest.

TypeScript
function openrouter(params?: OpenRouterParams): Provider
Parameters
NameTypeDescription
params?OpenRouterParams

API key, base URL, headers, default model and capabilities.

Provider

The provider.

src/core-entry.ts:67

Interfaces#

AgentRunOptionsInterface#

Options for one Agent.run call.

TypeScript
interface AgentRunOptions
AgentRunOptions properties
NameTypeDefaultDescription
behavior?AgentBehavior

Behavior overrides for this run (overrides agent defaults)

by?Actor

Who the run works for: the person whose message started it. Lands on every ToolContext.by and ToolHookContext.by of the run, and on the artifacts the run records (SessionArtifact.by). The built-in spawn tool passes it to each child. Absent: nobody named (the local user).

clock?AgentClock

Override the time + UUID source for this run only. Per-run wins over agent-level (AgentOptions.clock); both fall back to DEFAULT_AGENT_CLOCK. See AgentClock.

contextSections?{ rulesBlock?: string; rulesFiles?: { path: string; source: string }[] }

Optional metadata describing which named sections the host baked into system (e.g. the rendered AGENTS.md/CLAUDE.md "Rules" block). Purely informational — used by agent.getContextBreakdown() to attribute system- prompt tokens to a "Rules" bucket the agent can't otherwise isolate from the opaque base string. Does not affect what's sent to the model.

depth?number

Zero-based subagent depth. 0 = top-level agent.run(), 1 = first-level child spawned by a parent agent, and so on. Used by the spawn tool to enforce maxDepth and to stamp child:* forwarded hook payloads.

hooks?RunHookMap

Per-run hook registrations. Each hook is attached before the run starts and detached in a finally block so handlers never leak across runs.

Accepts either a single handler or an array (all handlers register).

leaseRenewMs?number

How often a top-level checkpoint run (zidane/durable) renews its session's lease, in ms. Default 60 s. Shorter: a run another process took over notices sooner, and stops showing output its new owner now shows (a channel run, whose reply lives in a shared conversation).

metadata?Readonly<Record<string, JsonValue>>

Host data about this run's prompt (an extension prompt interceptor's metadata). The agent never reads it: run interceptors see it on the options they receive. Not persisted.

model?string | (string | ModelTargetSpec)[]

Model selection for this run.

  • string — a model id. With a single provider the id runs on that provider; with multiple providers the id is tried on EVERY provider in order (fallback chain).
  • Array<string | ModelTargetSpec> — an ordered fallback list. Object entries pin a model to one provider by name; bare strings (and object entries without provider) fan out across all providers.
  • omitted — each provider's meta.defaultModel, in provider order.

The run starts on the first resolved target and advances down the list when a stream fails terminally (see the model:fallback hook). Once advanced, the run stays on that target (run-sticky); the next run() starts from the primary again.

modelOptions?Record<string, boolean>

Enabled model-specific options for this run, keyed by option id (e.g. { fast: true } for Anthropic's fast mode). Options the active model doesn't declare are silently ignored by the provider. Overrides AgentBehavior.modelOptions when both are set.

parentCallId?string

Tool-call id of the spawn call that created this run. The built-in spawn tool populates it from its own ToolContext.callId for every child it starts — no persist / shared session needed, unlike parentRunId. Hosts that roll their own subagent (calling agent.run with depth set from inside a tool) must pass it themselves; nothing derives it, so depth >= 1 alone does not imply it is set.

Lands on every ToolContext / ToolHookContext / McpToolHookContext of the run, so a host can attribute a subagent's tool call to the spawn call that owns it — see ToolHookContext.parentCallId. Recorded on the run (SessionRun.parentCallId), so a replay pairs the child with its spawn call exactly.

parentRunId?string

Parent run id. Populated automatically by the spawn tool when the child shares the parent's session; recorded on the resulting SessionRun so the parent↔child run tree can be reconstructed from a persisted session.

pauseSignal?AbortSignal

Pause signal: when triggered, the run stops at the next turn boundary (after the model call in flight and its tool results are saved), never mid-turn, and returns with stats.paused. A later run on the same session continues from those turns. A host uses it to restart (an update) without losing work.

prompt?string | PromptPart[]

User prompt. Optional when resuming a session with existing turns.

Accepts either a plain string (single text part) or an array of PromptParts for multimodal inputs (text, images, documents). See PromptPart.

promptOrigin?TextOrigin

Where the prompt came from (a channel, a schedule, a worker), set on the prompt's own text blocks in the seeded turn (not on drained notifications or AgentRunOptions.systemNotes), so the turn's first save already carries it. Ignored when the run seeds no prompt turn.

promptSkillGroups?SkillGroupUse[]

The skill groups the prompt named, saved on the seeded prompt turn (SessionTurn.skillGroups). Ignored when the run seeds no prompt turn.

promptTurnId?string

Id of the prompt turn this run seeds, minted by the caller beforehand (Session.generateTurnId) so it can show the prompt under its saved id before the run starts. Default: an id minted when the turn is seeded. Ignored when the run seeds no prompt turn.

requestId?string

The client request this run answers. RestateDurable.run sets it, to its requestId. Under AgentOptions.toolStateScope: 'request', the tool state lives across the runs of one request id.

resumeRunId?string

Resume a prior run's conversation: seed this run's turns from the session turns tagged with this runId (filtered through filterUnresolvedToolUses so a run killed mid-tool doesn't resume with an orphan tool_use). Used by the spawn tool to continue a stopped/failed subagent — the new run gets its own runId, with resumedFromRunId recorded on the resulting SessionRun so the chain stays reconstructible. Requires a session and a prompt (the continuation instruction); throws when the referenced run has no persisted turns.

runAgent?SessionRunAgent

The host's agent profile this run runs as, persisted onto the resulting SessionRun.agent so a transcript can name it per run.

runLabel?string

Host-assigned display label persisted onto the resulting SessionRun (SessionRun.label). The spawn tool passes its reserved child-N label here so label → run resolution (spawn resume) and transcript numbering read a stored fact instead of deriving it positionally.

runModel?string

The model id the run was announced on, persisted onto the resulting SessionRun.model. The spawn tool passes the one its spawn:before names, so a reloaded start marker shows the model the live one did.

signal?AbortSignal

Abort signal — when triggered, the run aborts the same way agent.abort() does

system?string

System prompt for this run. Falls back to AgentOptions.system, then to 'You are a helpful assistant.'.

systemFreeze?SystemFreezeOptions

Keep the conversation's system prompt byte-stable across runs and agent rebuilds, so provider prompt caches and replayed thinking stay valid. The run composes its fresh prompt as usual (base, skills catalog, searchable-tools catalog, MCP instructions), then:

  • with system set, sends that string instead and appends the notes notes(fresh, sections) returns to this run's prompt turn, ahead of AgentRunOptions.systemNotes;
  • otherwise sends the fresh prompt and hands it to onCapture, for the host to persist as the conversation's frozen prompt.

Both callbacks also get the sections the SDK appended (FrozenPromptSections); the zidane root exports helpers (systemSnapshotTurn, latestSystemSnapshot, catalogChangeNotes…) to store snapshots and announce those sections' changes. system:transform hooks still run per turn on top. Omitted: every run sends its fresh prompt.

systemNotes?readonly (SystemNote & { text: string })[]

Notes for the model, appended to this run's prompt turn after the prompt as text blocks marked with SystemNote. Use them to announce a change (mode, environment, instructions, effort) without editing the system prompt. Ignored when the run seeds no prompt turn.

thinking?'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'adaptive''off'

Thinking effort for this run. See ThinkingLevel.

tools?Record<string, ToolDef>

Tool overrides for this run. Pass {} for no tools. Omit to use agent tools.

tracingContext?Readonly<Record<string, string>>

Opaque trace-context carrier propagated from the parent agent's tracer (typically a W3C { traceparent, tracestate } map). The child's agent.run() re-emits it on the agent:start hook so the child's tracer can stitch its root span as a continuation of the parent's spawn span. Empty / absent on top-level runs.

Set automatically by the spawn tool when a parent's tracer wrote into SpawnHookContext.tracingContext on spawn:before. SDK consumers that drive subagents manually can populate this directly.

src/types.ts:3609

AgentStatsInterface#

Token, cost and timing totals returned by Agent.run.

TypeScript
interface AgentStats
AgentStats properties
NameTypeDescription
children?ChildRunStats[]

Stats from child agents spawned during this run, in completion order. Recursive.

cost?number

Cumulative cost in USD — parent loop plus every recursively-spawned sub-agent. Sums per-turn TurnUsage.cost reported by the provider. Absent when neither parent nor any descendant reported a non-zero cost.

elapsednumber

Wall-clock duration of the top-level agent.run() call, in milliseconds. Children run during parent tool calls so this naturally subsumes child wall time — sequential children inflate it, parallel children compress into the parent's window.

output?Record<string, unknown>

Structured output from schema enforcement (only present when behavior.schema is set)

paused?boolean

The run stopped at a turn boundary on pauseSignal, with work left: continue it with another run.

suspended?boolean

Agent.suspend stopped the run: on a checkpoint runtime it stays resumable (Agent.resume).

timeTillFirstTokenMs?number

Milliseconds from the start of agent.run() to the first observable signal from the provider (first stream:text, stream:thinking, or tool:before event).

Absent when the run produced no observable signals (e.g. aborted before any stream event).

totalCacheCreationnumber

Cumulative cache-creation tokens across the parent agent loop and every recursively-spawned sub-agent. Same rationale as AgentStats.totalCacheRead — separate Anthropic billing rate. Always 0 for providers that don't report cache usage.

totalCacheReadnumber

Cumulative cache-read tokens across the parent agent loop and every recursively-spawned sub-agent. Surfaced at the top level (rather than only per-TurnUsage) because Anthropic prices cache reads at a separate line-item rate from regular input — billing-correct cost computation needs this number directly. Always 0 for providers that don't report cache usage.

totalInnumber

Cumulative input tokens across the parent agent loop and every recursively-spawned sub-agent. Use this for billing / token-ledger consumption.

totalOutnumber

Cumulative output tokens. Same semantics as AgentStats.totalIn.

turnsnumber

Number of parent agent-loop turns. Children's turn counts live under children[].stats.turns and are NOT folded in here — a single "turns" number for the whole tree would conflate two different measures (parent-loop iterations vs. tree-wide tool-call rounds).

Tree-wide turn count: flattenTurns(stats).length.

turnUsage?TurnUsage[]

Per-turn usage breakdown for the parent loop only. Children's per-turn usages live under children[].stats.turnUsage. Use flattenTurns to walk the full tree.

waitedMs?number

Wall time the run spent waiting on the outside world, in ms (tools flagged ToolDef.excludeFromWallClock, a sub-agent's own waits), across resumes. Part of elapsed, left out of behavior.maxWallMs: work time is elapsed - waitedMs. Absent when the run waited none.

src/types.ts:3928

CreateSessionOptionsInterface#

Options for createSession.

TypeScript
interface CreateSessionOptions
CreateSessionOptions properties
NameTypeDescription
_data?SessionData

@internal: restore from existing data (bypasses id/agentId/metadata options). The session ALIASES this object for its lifetime — every mutation (appendTurns, run records, updatedAt) writes through to it, and the load-time pairing heal may replace its turns array in place before the session is returned. Callers must not retain independent ownership expectations.

agentId?string

Agent ID label

id?string

Session ID. If omitted and store provides generateSessionId, that is used.

metadata?Record<string, unknown>

Initial metadata

onPairingDrop?(drop: PairingDrop) => void

Observability hook for the load-time pairing heal: fired once per block or turn dropInvalidToolPairings deleted while restoring _data. Deletions are permanent once the session is saved, so hosts that alert on wire-time pairing:repair events should wire this to the same sink. Only fires on the _data restore path; fresh sessions never heal.

projectRoot?string

Project tag — see SessionData.projectRoot. Stamped once on creation; ignored when _data is set (restoring an existing session preserves whatever was already persisted there). The chat layer's session factory stamps projectRootOf(cwd) so sessions started from the same repo — any subdir, any linked worktree — share one tag.

store?SessionStore

Storage backend (optional, enables save/load)

src/session/index.ts:1127

LoadSessionOptionsInterface#

Options for loadSession.

TypeScript
interface LoadSessionOptions
LoadSessionOptions properties
NameTypeDescription
clock?Pick<AgentClock, 'now'>

Time source for the stale 'running' check. Default: Date.now. Pass a replay-stable clock inside a replaying run (Restate: { now: () => ctx.date.now() }) so a replay takes the same branch.

onPairingDrop?(drop: PairingDrop) => void

Forwarded to createSession — see CreateSessionOptions.onPairingDrop.

persistHeal?boolean

Write a load-time pairing heal back to the store (default true). Pass false from READERS — a window mirroring a session another process runs (daemon mode) — because the persist is a bulk turn overwrite and the owner's next load heals and persists it anyway.

No load closes interrupted tool calls: the process holding the run may still be running the tool. A run does that once it owns the session, through Session.healInterruptedToolCalls.

src/session/index.ts:1662

RemoteStoreOptionsInterface#

Options for createRemoteStore.

TypeScript
interface RemoteStoreOptions
RemoteStoreOptions properties
NameTypeDescription
headers?Record<string, string>

Optional headers (e.g. for authentication)

timeoutMs?number

Per-request timeout in ms. Default 30s — bounds a hung backend.

urlstring

Base URL of the session API

src/session/remote.ts:23

SessionInterface#

A live session: the turn history and run records of one conversation, with an optional store that persists them.

TypeScript
interface Session
Session properties
NameTypeDescription
abortRun(runId: string, stats?: { cost?: number; tokensIn: number; tokensOut: number; turns: number; turnUsage?: TurnUsage[] }) => void

Mark a run as aborted. Optional stats lets the agent backfill the run's token totals when the abort happened after the loop accumulated meaningful usage — common when the user presses esc mid-streaming. Without it, the run record reads 0 in / 0 out on reload regardless of how much was spent before the abort. Same shape as completeRun's stats so the persisted totalUsage aggregate stays consistent across paths.

addArtifact(input: SessionArtifactInput, origin?: { by?: Actor; runId?: string; turnId?: string }) => Promise<SessionArtifact | undefined>

Record an artifact this session produced. Fills id, timestamps and defaults projectRoot to the session's own; origin ties it to the producing run/turn for transcript anchoring, and names who that run works for (by, ToolContext.by). Resolves to the stored row, or undefined when there is no store or the store doesn't implement artifacts (never throws for that case — emission is best-effort by contract).

agentId?readonlystring

Agent ID (optional label)

appendTurns(turns: SessionTurn[], options?: AppendTurnsOptions) => Promise<HistoryWrite | undefined>

Appends turns to in-memory history and persists them via store.appendTurns when a store is present. Resolves to the store's history write, or undefined without a store.

completeRun(runId: string, stats: { cost?: number; tokensIn: number; tokensOut: number; turns: number; turnUsage?: TurnUsage[] }) => void

Mark a run as completed

createdAtreadonlynumber

Creation time as epoch milliseconds.

errorRun(runId: string, error: string, stats?: { cost?: number; tokensIn: number; tokensOut: number; turns: number; turnUsage?: TurnUsage[] }, detail?: RunErrorDetail) => void

Mark a run as errored. Optional stats — same rationale as abortRun.stats.

generateTurnId() => string | Promise<string>

Generate a session-managed turn ID using store.generateTurnId if available, else crypto.randomUUID()

healInterruptedToolCalls() => Promise<boolean>

Close every tool call whose result was never persisted (the process died mid-tool) with a synthetic error result saying the tool may have partially run. Call it only once this process OWNS the session's next run (after the run claim, or where a single owner is guaranteed): while another process still runs the tool, its real result would land after the synthetic one and be dropped as an orphan. loadSession never does this.

Persists through store.mutateHistory when available (re-derived from the stored turns, so turns appended by another writer survive), else a store.save guarded by a turn re-count. Best-effort: a failed persist keeps the in-memory heal, and never arms a bulk overwrite on the next save(). Resolves true when anything was closed in memory.

idreadonlystring

Session ID

isEmptyreadonlyboolean

True when this session has no turns yet.

Use this as a first-prompt signal when setting up a run — e.g. writing initial configuration only on fresh sessions. Equivalent to turns.length === 0.

listArtifacts(filter?: Pick<ArtifactFilter, 'kind' | 'since' | 'limit'>) => Promise<SessionArtifact[]>

This session's artifacts, newest first. Empty when unsupported.

metadatareadonlyRecord<string, unknown>

Arbitrary metadata

onMeta(listener: SessionMetaListener) => () => void

Call listener after each setMeta write, synchronously, in subscription order. Returns the unsubscribe.

onSaved(listener: SessionSavedListener) => () => void

Call listener after each successful save(). Listeners run one after another in subscription order and save() awaits them; a rejection rejects save() and skips the later listeners. Returns the unsubscribe.

projectRoot?readonlystring

Project this session was created under — see SessionData.projectRoot. Set once on creation; surfaces here for read-only inspection.

runsreadonlySessionRun[]

All runs in this session

save() => Promise<void>

Persist the session to the store. When the store implements saveMeta, this writes the header, the changed metadata keys and the runs, and leaves turns alone, unless setTurns or setRuns replaced them. In every other case it overwrites the whole document through store.save. Throws when the session has no store.

On a journaled store (SessionStore.journaled), a call made inside a tool step writes nothing: the changes stay pending, and the loop writes them after the step (savePending). Only metadata changes are kept pending: a header or run change with no metadata change waits for the next save that writes, since a replay could not rebuild it.

saveMetaKeys?(keys: readonly string[]) => Promise<void>

Persist only these metadata keys (and the header and runs saveMeta carries), never the turns, even after setTurns replaced them: a small state change mid-run (a plan update) must not pay for a full rewrite. Falls back to save() on a store without saveMeta. Throws when the session has no store. Optional so hand-built sessions need not provide it. Held back inside a tool step on a journaled store, like save.

savePending?() => Promise<void>

Write the metadata changed since the last save, if any (a save() when keys are pending, nothing otherwise). The loop calls it after each tool batch and when a run ends, outside any step, to land what a tool body changed on a journaled store. Optional so hand-built sessions need not provide it.

setAgentId(agentId: string) => void

Re-label the session's agent profile (in memory; persisted by the next save()). Sessions remember their profile — pickers restore it on activation; the host that saves it tells the other windows.

setMeta(key: string, value: unknown, options?: { touch?: boolean }) => void

Set metadata key. touch: false keeps updatedAt (a rename or a favorite is not activity).

setRuns(runs: SessionRun[]) => void

Replace all runs in-memory (does not persist — use save() for that). Mirrors setTurns for the fork / restore case: callers that bootstrap a session from an externally-derived snapshot (e.g. onForkTurn copying parent runs into a child session) need this so the cloned runs land in data.runs before the first save(). Production agent runs continue to mutate runs via startRun / completeRun / updateRun; this is the bulk-replace escape hatch.

setTurns(turns: SessionTurn[]) => void

Replace all turns in-memory (does not persist — use save() for that)

startRun(runId: string, prompt?: string, extras?: { agent?: SessionRunAgent; depth?: number; label?: string; model?: string; parentCallId?: string; parentRunId?: string; resumedFromRunId?: string }) => void

Start tracking a new run. extras.parentRunId + extras.depth are populated by the spawn tool when a child agent shares its parent's session; regular top-level agent.run() calls omit them.

statusreadonly'error' | 'running' | 'completed' | 'idle'

Top-level session status

store?readonlySessionStore

The backing store, when one was provided. Exposed so hosts can call its optional close() on teardown (e.g. release the SQLite handle).

toJSON() => SessionData

Serialize to SessionData

toMessages(options?: ToWireMessagesOptions) => Promise<SessionMessage[]>

Project the session's persisted turns into wire-ready messages safe to hand to any provider.

The canonical answer to "I need to send these turns to Anthropic / OpenAI from outside agent.run()" (sub-agent classifier, side-channel summarizer, replay worker, …). Runs the same defensive pairing repair the agent loop applies just-in-time at wire-send time (ensureToolResultPairing), so orphan tool_use blocks and dangling tool_results never reach the provider as the 400 "tool_result must be preceded by a tool_call with the same toolCallId".

Pass provider to also enforce the user-tail invariant (ensureEndsWithUserMessage) — required for opus 4.7 / o-series style models that reject assistant-prefill.

Pure + idempotent. Resolves content refs only in the returned messages and does NOT mutate session.turns. Do not write the result back via setTurns / appendTurns — synthetic placeholders or resolved payloads will contaminate persisted history.

turnsreadonlySessionTurn[]

Raw persisted turn history — kept pristine for fidelity (the model's reasoning chain stays intact across reloads).

DO NOT pass this directly to a provider request. Mid-pair persistence (interrupted runs, partial-result writes, compaction boundaries) leaves orphan tool_use / tool_result blocks here that every provider 400s on (tool_result must be preceded by a tool_call with the same toolCallId). The agent's own loop repairs these just-in-time at wire-send time and never writes the repair back to turns.

For provider requests built outside agent.run(), use Session.toMessages — it applies the same defensive pairing repair and resolves to a guaranteed-safe SessionMessage[].

updatedAtreadonlynumber

Last update time as epoch milliseconds.

updateRun(run: SessionRun) => Promise<void>

Persist an updated run record via store.updateRun (if store present)

updateStatus(status: 'error' | 'running' | 'completed' | 'idle') => Promise<void>

Update the session status in memory AND via store.updateStatus (if store present)

src/session/index.ts:898

SessionMessageInterface#

One message of a session conversation, as sent to the provider.

TypeScript
interface SessionMessage
SessionMessage properties
NameTypeDescription
contentSessionContentBlock[]

Content blocks of the message, in order.

role'user' | 'assistant'

Author of the message.

src/types.ts:3423

SessionStoreInterface#

Storage backend for sessions. Implement it to persist sessions somewhere else, or use a bundled store: memory, SQLite, remote or file map.

TypeScript
interface SessionStore
SessionStore properties
NameTypeDescription
appendTurns(sessionId: string, turns: SessionTurn[], options?: AppendTurnsOptions) => Promise<HistoryWrite>

Append new turns to a session (incremental, avoids full re-save). options is for the store of a checkpoint durable runtime (zidane/durable); other stores ignore it.

Resolves to the append's position, computed inside the write (an append of no turns keeps the position).

blobs?readonlyBlobStore

Optional: media bytes by content hash (./blob-store.ts). With it, a turn's images and binary documents are stored, and held by the agent, in blob-ref form (../media/blob-media.ts); the wire resolves them here. Without it, media stay inline.

claimRun?(sessionId: string, options: { owner?: RunOwner; staleAt: number }) => Promise<{ claimed: boolean; previous?: 'error' | 'running' | 'completed' | 'idle' }>

Optional: claim the session for a run in ONE atomic step — set status to 'running' (and stamp updatedAt) unless the stored status already is 'running' and its owner still holds it: written after options.staleAt by an owner not known dead (see isRunOwnerDead), or by an owner on this host that still runs (isRunOwnerHolding, up to RUN_OWNER_HOLD_MS of quiet). The claim records options.owner (default: this process) as the run owner. An unknown id is claimed without writing a row. previous is the status the claim replaced, for undoing a claim whose run never started. Callers without it fall back to a read-then-write check, which two processes can both pass. A marker only: a durable runtime's lease (DurableLease) is what fences writes.

close?() => void

Optional: release backend resources (e.g. close the SQLite handle). Hosts should call this on teardown when present; stores backed by memory or remote HTTP have nothing to release and may omit it.

delete(sessionId: string) => Promise<void>

Delete a session.

deleteArtifact?(sessionId: string, artifactId: string) => Promise<void>

Optional: remove one artifact. Unknown ids are a no-op.

findTurns?(sessionId: string, query: FindTurnsQuery) => Promise<SessionTurn[]>

Optional: the turns of one role and/or one run, or the last last of them, oldest first, without reading the others. Callers fall back to load() and filter.

generateSessionId?() => string | Promise<string>

Optional: generate a session ID server-side (e.g. a database-issued UUID).

generateTurnId?() => string | Promise<string>

Optional: generate a turn ID server-side for session-managed user turns.

Provider-loop assistant and tool-result turns use AgentClock.randomUUID() instead, so durable-execution adapters can keep those IDs replay-stable.

getHeader?(sessionId: string) => Promise<SessionHeaderData | null>

Optional: one session's header fields alone (no turn, no run, no count). The cheapest read of a session: hot paths that need its metadata, cwd or status read this. Callers fall back to getMeta or load().

getMeta?(sessionId: string) => Promise<SessionMetaRow | null>

Optional: one session's header row WITHOUT materializing turns. Hot-path reads (the cross-process run guard checks status + updatedAt on every prompt send) must not pay a multi-MB turn parse on long sessions. Callers fall back to load() when absent.

getRuns?(sessionId: string) => Promise<SessionRun[]>

Optional: one session's run records alone. Callers fall back to load().

getTurnById?(sessionId: string, turnId: string) => Promise<SessionTurn | null>

Optional: the first turn (in order) with id turnId, without reading the others. Callers fall back to load().

getTurns(sessionId: string, from?: number, limit?: number) => Promise<SessionTurn[]>

Return a slice of turns for a session.

historyPosition?(sessionId: string) => Promise<HistoryPosition | null>

Optional. The session's history position alone, or null for an unknown session. If the store has no getMeta (which carries the position), readers call it around a read to name the position the rows are at.

journaled?readonlytrue

Set when the store's writes are entries of a journal (a kernel session store on a journaled host: Restate). A re-run that skips the tool's body does not make a write made inside a tool step again, so a Session over this store holds such writes back (Session.save) and the loop saves them after the step (Session.savePending). Unset: writes land at once.

list(filter?: { agentId?: string; limit?: number; projectRoot?: string | null }) => Promise<string[]>

List session IDs, optionally filtered. projectRoot restricts to sessions whose SessionData.projectRoot matches exactly — untagged (legacy) sessions are NOT returned under that filter; pass null explicitly to ask for untagged ones, or omit the field to ignore the axis entirely. agentId filters by recorded agent; the two conditions AND together when both are set.

listArtifacts?(filter?: ArtifactFilter) => Promise<SessionArtifact[]>

Optional: list artifacts, newest updatedAt first. filter.sessionId scopes to one session; filter.projectRoot follows the tri-state contract of list; omit both for every artifact in the store.

listMeta?(filter?: { agentId?: string; limit?: number; projectRoot?: string | null }) => Promise<SessionMetaRow[]>

Optional: list session summaries without materializing full sessions.

The generic fallback (listSessionMeta in zidane/chat) is list()

  • load() per id — O(every turn in the store) because each load parses the full turn history just to count rows and derive a title. Stores that can answer from an index (SQL aggregates, a denormalized header) should implement this; the sqlite store turns a multi-hundred- ms TUI boot cost into a single query.

Same filter contract and ordering (most recently updated first) as list.

load(sessionId: string) => Promise<SessionData | null>

Load a session by ID. Returns null if not found.

mutateHistory?(sessionId: string, mutate: (history: SessionHistory) => SessionHistory | null) => Promise<'no-session' | HistoryWrite | 'unchanged'>

Optional: rewrite a session's history as ONE atomic read-modify-write, so turns appended between the read and the write can't be erased (a load() + save() pair can). mutate gets the current turns and runs and returns the next ones, or null to leave them untouched; a throw inside it aborts without writing. Runs are written only when it returns a different runs array. History edits (delete / edit a turn, rewind) use it when present and fall back to load() + save().

Resolves to the history write (a rewrite, or an append when mutate only added turns at the end), 'unchanged' when the turns stay as they were (runs mutate returned are still written), or 'no-session'.

mutateTurns?deprecated(sessionId: string, mutate: (turns: SessionTurn[]) => SessionTurn[] | null) => Promise<'no-session' | HistoryWrite | 'unchanged'>

Optional: the turns-only form of SessionStore.mutateHistory. When mutateHistory is absent, edits that leave the runs alone (delete or edit a turn) use it; a rewind falls back to load() + save().

Deprecated. Implement mutateHistory instead.

patchMeta?(sessionId: string, patch: Record<string, unknown>) => Promise<void>

Optional: merge patch into the stored metadata (an undefined value removes the key) without touching any other header column — status and updatedAt stay as they are, so the write can't undo a concurrent run marker. Unknown ids are a no-op.

save(session: SessionData) => Promise<HistoryWrite | null>

Save a session (create or update, full document). Bulk overwrite: turns and runs on disk are replaced by the caller's snapshot, so a stale snapshot silently discards anything another writer appended. Session.save() only routes here when the turn list was explicitly replaced (setTurns / setRuns / load-time heal); everything else goes through saveMeta.

Neither save nor saveMeta moves status into running: only updateStatus and claimRun do, and record the run owner. A snapshot's running keeps the stored status (idle for a new row) and the stored owner; a settled status is written as given.

Resolves to the history write it made, classified against the stored turns inside the same write: null when the turns are unchanged (no bump), an append when the stored turns are an unchanged prefix of the snapshot's (same ids and content), else a rewrite.

saveMeta?(session: SessionData, options?: SaveMetaOptions) => Promise<void>

Optional: persist header fields only (agentId, projectRoot, status, metadata, timestamps) plus an UPSERT of the runs present in the snapshot — never deletes turns or runs. This is what metadata writes (title, model, todos, extension state) need.

Scope of the guarantee: TURNS appended by a concurrent process survive. The header itself is still last-writer-wins — agentId and a settled status are written wholesale from the caller's snapshot (a snapshot's running is not, see save), and so is metadata unless options.metaKeys names the changed keys (Session.save() always does; stores merge them with mergeSessionMetadata), and every run in the snapshot is upserted as-is (a reader that loaded through loadSession carries the in-memory stale-running demotion, so it can write idle / aborted over a live owner's marker until the owner's next write). Readers that only need one key should prefer a keyed patch (the host's patchSessionMeta) over save(). Stores that omit it fall back to save, keeping the historical bulk semantics.

updatedAt never moves back in the bundled memory, sqlite and file-map stores: they keep the later of their own and the snapshot's. A write the store stamped itself (updateStatus, updateRun, another copy's save) is newer than a live session's copy, and its later save that is not activity (setMeta with touch: false) keeps the session's recency.

searchTurns?(lowerTerms: readonly string[], sessionIds: readonly string[]) => Promise<ContentIndexHits | null>

Optional: the turns of sessionIds whose searchable text holds every term (lowercased; a quoted phrase is one term), from a content index, without reading a turn. null when the index can't answer (the store keeps none, or a term is shorter than what it indexes). A cross-session search asks it once instead of reading each session.

turnsAfter(sessionId: string, afterPos: number, historyId: string, options?: TurnsAfterOptions) => Promise<TurnsAfter | 'gap' | null>

The turns appended after history position afterPos of numbering historyId, in order, with the current position. null for an unknown session; 'gap' when the store cannot say exactly (another historyId, afterPos < floor or afterPos > pos). With options.limit, reads at most limit + 1 turns (TurnsAfterOptions).

updateRun(sessionId: string, run: SessionRun) => Promise<void>

Persist a run record (called at run start with status: 'running', and after completeRun / abortRun / errorRun).

Upsert semantics required. The agent's run lifecycle calls session.startRun() to register a new run in IN-MEMORY state and then updateRun(). The store doesn't see the run before the first updateRun() — appendTurns persists turns but not runs. An update-only implementation would silently drop every newly-created run record, leaving the on-disk runs[] missing entries that the persisted turns reference (which eventsFromTurns then mis-classifies via ancestryOf → broken depth, broken child-N labels, broken userPrompts history).

Implementations MUST insert when the id doesn't exist and update when it does. The bundled sqlite / memory / file-map stores all follow this contract; remote stores using HTTP PUT get upsert for free via REST semantics.

updateStatus(sessionId: string, status: 'error' | 'running' | 'completed' | 'idle', options?: { owner?: RunOwner; preserveUpdatedAt?: boolean }) => Promise<void>

Update the top-level status of a session.

preserveUpdatedAt (default false) writes the status WITHOUT touching updatedAt — for pure-read heals (loadSession's stale 'running' demotion) that must not reorder recency-sorted session lists. Best-effort contract: stores that don't manage updatedAt themselves (memory, file-map, remote) may ignore the option; the sqlite store honors it.

'running' records options.owner (default: this process) as SessionData.runOwner; any other status clears it.

upsertArtifact?(artifact: SessionArtifact) => Promise<SessionArtifact | null>

Optional: record an artifact (see ./artifacts.ts). Upsert on (sessionId, kind, uri) — an existing row keeps its id / runId / turnId / createdAt and refreshes label / meta / updatedAt (mergeArtifact). Resolves to the canonical stored row. Unknown session ids are a no-op returning null (no ghost headers; same posture as updateRun). Implementations enforce ARTIFACTS_PER_SESSION_CAP via selectArtifactEvictions.

Every artifact method is optional: stores that don't implement them (file-map, remote, third-party) keep working — Session.addArtifact degrades to a no-op and listings come back empty.

src/session/index.ts:595

SessionTurnInterface#

One persisted turn of a session: a user prompt, an assistant response, or a system or command entry.

TypeScript
interface SessionTurn
SessionTurn properties
NameTypeDescription
aborted?true

On a role: 'assistant' turn: model output a process death cut off, rebuilt when its durable run resumed. Shown in the transcript, left out of the model context; the request is sent again.

contentSessionContentBlock[]

Content blocks of the turn, in order.

createdAtnumber

Unix timestamp (Date.now()) when the turn was created

display?string

Display-only replacement for transcript rendering — the full content still reaches the model unchanged. Set by command context notes (ctx.appendContext) so a replayed session renders the same one-line marker the live path showed (with the full note as a collapsed detail) instead of duplicating bulky note bodies as a wall of user text. Mirrors SessionRun.origin.display, at turn granularity, for turns that belong to no run.

idstring

Unique turn id. Provider-loop turns are minted from AgentClock.randomUUID().

injected?InjectedTurnReason

Set on a role: 'user' turn the agent loop injected rather than the user typed (a refusal retry, an output-limit or pause "Please continue.", a tool-output-budget or turn-limit warning, a nudge, a run:beforeEnd follow-up). The content still reaches the model; hosts use the marker to keep the turn out of everything that treats user turns as prompts (transcript bubbles, prompt matching, usage counts).

role'system' | 'user' | 'assistant' | 'command'

Conversational role, plus 'command' — a display-only turn emitted by a / command's local output. 'command' turns are persisted + rendered but excluded from every model-message builder (they never reach the LLM), mirroring how 'system' turns are filtered from the wire.

runId?string

Run that produced this turn (e.g. 'run_1')

skillGroups?SkillGroupUse[]

On a role: 'user' prompt turn: the skill groups its / picks named and the skills each one turned on (docs/SKILL.md, Skill groups). Display only: the model never reads it.

systemSnapshot?SystemPromptSnapshot

On a role: 'system' turn: the conversation's frozen system prompt, which content holds as one text block. The latest snapshot for a prompt key wins. Recorded by hosts that pass AgentRunOptions.systemFreeze.

usage?TurnUsage

Token usage — only present on assistant turns

src/types.ts:3431

Types#

SessionContentBlockType#

Content block of a session message: text, media, a tool call, a tool result, or thinking.

text, tool_call and thinking blocks can carry a signature: opaque state the producing API wants back with that block (a Gemini thought signature, an Anthropic thinking HMAC, OpenAI encrypted reasoning), tagged with its SignatureProducer. Only that provider's wire builder reads it; the others map blocks field by field and never send it.

TypeScript
type SessionContentBlock =
  | { origin?: TextOrigin; signature?: string; signatureProducer?: GeminiSignatureScope; systemNote?: SystemNote; text: string; type: 'text' }
  | { data: string; mediaType: string; name?: string; ref?: never; type: 'image' }
  | { data?: never; edge?: number; mediaType: string; name?: string; ref: string; size?: number; type: 'image' }
  | { data: string; mediaType: string; name?: string; type: 'audio' }
  | { data: string; mediaType: string; name?: string; type: 'video' }
  | { data: string; encoding: 'base64' | 'text'; mediaType: string; name?: string; ref?: never; type: 'document' }
  | { data?: never; encoding: 'base64' | 'text'; mediaType: string; name?: string; ref: string; size?: number; type: 'document' }
  | { id: string; input: Record<string, unknown>; name: string; signature?: string; signatureProducer?: GeminiSignatureScope; type: 'tool_call' }
  | { callId: string; calls?: NestedToolCallRecord[]; details?: ToolResultDetails; durationMs?: number; isError?: boolean; metadata?: ToolResultMetadata; outcome?: ToolOutcome; output: string | ToolResultContent[]; settledOrder?: number; type: 'tool_result' }
  | { signature?: string; signatureProducer?: SignatureProducer; text: string; type: 'thinking' }
  | { data: string; type: 'redacted_thinking' }
  | { details: unknown[]; model?: string; producer: 'openrouter'; type: 'provider_reasoning' }
  | { model?: string; producer: 'vllm'; reasoningText: string; type: 'provider_reasoning' }
  | { id: string; input: Record<string, unknown>; name: string; producer: 'anthropic'; type: 'server_tool_use' }
  | { content: unknown; producer: 'anthropic'; toolName: string; toolUseId: string; type: 'server_tool_result' }
  | { compactedAt: number; model: string; replacesTurnIds: readonly string[]; summary: string; type: 'compact-summary'; usage: TurnUsage }

src/types.ts:3248

ThinkingLevelType#

One of the THINKING_LEVELS strings: how much the model reasons before it answers.

TypeScript
type ThinkingLevel = typeof THINKING_LEVELS[number]

src/thinking-levels.ts:16

Re-exports#

These names are documented on the entry point that owns them.