English | 中文
The in-memory, event-sourced model of dsh-session. A Session is an append-only log of typed SessionEvents — the single source of truth for an agent's whole interaction history. The LLM message history is derived from the log, never stored separately; replay is re-derivation from the same events. How the log is made durable (the persistence seam, backends, crash recovery) is the sibling concern on persistence.md.
Source: packages/core/session/src/types.ts
SessionEventMap — the event vocabularyThe append-only event types. Merge-extensible: a plugin declares extra event types via declaration merging — e.g. the compaction seam adds compaction/start / compaction/summary / compaction/end, and @deepseek-ai/dsh-hook-protocol adds log-only hook/invoked / hook/result records for a hook bridge. Like compaction/*, these are NOT SurfaceEventTypes (no surfaceOp). The generated persistence log event catalog enumerates every member — core and merged — with its payload, surface badge, and declaration site.
/** A user-role specialization of the one shared message representation. */
interface UserMessage extends Message {
readonly role: 'user'
}
/**
* The merge-extensible, append-only source of truth for an agent interaction.
* Message history is derived from this log. Every event is lossless JSON and
* sequence numbers stay contiguous. Assistant attempt events embed their exact
* compact raw streams so persistence stores one durable settlement per attempt.
*/
interface SessionEventMap {
/**
* Opens turn `turn` before the loop claims queued input or runs pre-step.
* Rejection, empty input, cancellation, or failure may close it with no
* step; otherwise the following identified `user/message` event or batch
* records the messages entering the step.
*/
'turn/start': { turn: number }
/**
* Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn
* with no entered step has no `step/start` or `step/end`. The loop does not await a
* flush at turn boundaries: `dsh-session-checkpoint-policy` owns the
* per-request durability checkpoint, and consumers that read storage after
* `whenIdle()` flush themselves. Success commits the turn; rejection is
* reported live and does not prevent later work.
*/
'turn/end': { turn: number; reason: TurnEndReason }
/** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */
'step/start': { turn: number; step: number }
/** Closes step `step` of turn `turn`. */
'step/end': { turn: number; step: number }
/**
* A user-role message on the model-visible surface: a direct human prompt
* (the queued message claimed for this turn), a synthetic `agent.inject()`
* context (file-change notices, subdir AGENTS.md, skill content, cron
* notifications, …), or an entered goal continuation round. All three
* project their `content` verbatim; `source` tells them apart.
*/
'user/message': UserMessage
/**
* Assembled assistant message for one step (derived history uses this).
* Carries the step's `usage` when the adapter reported token accounting, so
* the model output and its accounting travel together (there is no separate
* usage record). `usage` is absent when the adapter reported none. A turn
* cancelled mid-stream finalizes its delivered text/reasoning prefix as this
* event with `interrupted: true`; undispatched tool calls are absent. The
* marker distinguishes that prefix without re-deriving interruption from turn
* boundaries. An aborted turn with no such event streamed no visible content.
*/
'assistant/message': {
turn: number
step: number
message: AssistantMessage
/** Exact timed model stream, compacted without joining delta boundaries. */
stream: AssistantStreamRecord[]
usage?: TokenUsage
interrupted?: true
}
/**
* One model attempt that committed no surface message. The embedded stream
* preserves a failed, retried, cancelled, or stream-error attempt that
* reached settlement without fabricating model-visible history.
*/
'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] }
/**
* The model requested one tool invocation: `name` with the raw `arguments`
* JSON string exactly as the model produced it (unparsed). `callId` pairs the
* call with its `tool/result`.
*/
'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string }
/**
* A completed tool call's model-facing result, optional internal failure
* identity, and optional tool-private `meta` presentation payload. `meta` is
* opaque to the core (the producing tool owns its shape and reads it back in
* `presentResult`) but MUST be JSON-serializable: `Session.append`
* runtime-validates all event data with `isJsonValue`, so a non-serializable
* `meta` is rejected at the source, and the durable log reproduces the
* identical card on replay. Absent
* unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time
* contextual diff here).
*/
'tool/result': {
turn: number
step: number
message: ToolResultMessage
error?: { name: string; code: string }
meta?: JsonValue
}
/**
* Full header for the next request, appended inside its step before dispatch.
* It is log-only; the latest snapshot reconstructs the request header.
*/
'request/header': {
header: EpochHeader
reason: RequestHeaderReason
/** A changed header also begins a distinct model-message series. */
startsSeries?: true
}
/**
* Route metadata for the next request, logged only when the route or capacity
* changes. It does not participate in request reconstruction or header equality.
*/
'request/context': RequestContext
/**
* Marks the end of a constructor seed. Events before it have smaller seq
* values and came from the seed (resume, fork, or replay); this lifecycle
* produced none of them. This log-only event is the durable projection of
* {@link Session.firstLiveSeq}.
*
* A fresh fork child owns one `{ inherited: true }` marker at its exact
* inherited-prefix cut, even when that prefix ends in an ancestor marker.
* The last tagged marker is the current Session's cut; untagged markers keep
* ordinary restore and replay lifecycle boundaries.
*
* `Session`'s constructor is the only legitimate writer. The invariant
* companion deliberately constrains nothing here, so a plugin appending one
* would silently classify every live bracket before it as seed history.
*
* An owner of a standalone open/close bracket (`compaction/start` …
* `compaction/end`) reads it because seed history and live work are otherwise
* byte-identical: an unmatched opening marker before this event belongs to
* an ended lifecycle, whatever ended it. NOT a liveness signal about other
* writers — a concurrently live session holds its own boundary elsewhere,
* so tolerating concurrent writers needs a signal beyond the log.
*/
'session/end-seed': { inherited?: true }
}
UserMessage is the identified, frozen user-role value shared by ordinary prompts, injected context, steering, and live inbox events. Event wrappers add only event-local position or outcome facts; the loop adds only driver-owned routing state while an item remains pending.
request/headerThe request envelope — the EpochHeader (call config + markers for adapter-supplied defaults + rendered system prompt + assembled tool schemas) — is logged session state, so every conversation request is a pure function of the log (the reconstructability Agent Note). A full request/header snapshot with reason 'initial' or 'resume' records each loop-instance boundary; a changed request appends a snapshot with reason 'change'; and an unchanged envelope beginning an explicitly declared message series or following a surface replacement appends a snapshot with reason 'series'. A changed snapshot carries startsSeries: true when that request also begins a series. Ordinary append-only later Turns, further Steps, and retries in the same model-message series inherit the latest snapshot. foldRequestHeader(events) reconstructs the header by selecting the latest snapshot. The event is not a SurfaceEventType: it produces no LLM message.
/**
* Logged request state outside derived history: call config, system prompt, and
* tools. The latest full `request/header` snapshot reconstructs it; canonical
* empty optional fields are absent.
*/
interface EpochHeader {
/** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */
config: LlmCallConfig
/** Effective config fields materialized from the exact adapter rather than proposed by a caller. */
adapterDefaults?: LlmCallConfigAdapterDefaults
/** Rendered system prompt text; absent for a system-less request. */
system?: string
/** Assembled tool schemas; absent for a tool-less request. */
tools?: ToolSchema[]
}
Canonical form represents an empty system prompt or tool list as an absent field, matching how requests are built. Legacy v0 logs containing the legacy request/header-delta event or its full-snapshot fallback reason are rejected at seed, append, and persistence-load boundaries rather than replayed incompletely.
request/contextThe context metadata of the route a request resolved to is separate logged state, appended beside request/header inside the same step and only when the provider, model, or capacity differs from the previous record. It stays outside EpochHeader because that type is the reconstruction contract compared field-wise by headerEquals: capacity describes a route, not a request input, so folding it in would let a capacity change register as a request-envelope change and would pull adapter metadata into the loop's reconstruction invariant. Like request/header, it is not a SurfaceEventType and produces no LLM message. session.requestContext() folds the latest record incrementally. A route whose adapter advertises no capacity is recorded with contextWindow absent, so the new record clears an older route's capacity.
/** Registration-bound metadata for one resolved model route. */
interface RequestContext {
/** Registered provider route the metadata belongs to. */
provider: string
/** Provider-owned model id the metadata belongs to. */
model: string
/** Maximum combined request and response context in tokens, when advertised. */
contextWindow?: number
}
SessionEvent<T> — one log entryA proper discriminated union over type (not independent type/data unions), so switch (event.type) narrows event.data without casts. seq is the monotonic position in the log (seq = log.length); time is epoch ms.
/** Sequence number of one existing event in a Session log. */
type SessionSeq = BrandedNumber<'SessionSeq'>
/** A Session log gap, prefix length, or read offset, which may equal the event count. */
type SessionLogOffset = BrandedNumber<'SessionLogOffset'>
/** Inclusive Session event watermark, or `-1` before any event exists. */
type SessionSeqCursor = SessionSeq | -1
/** One existing Session event position, or explicit absence. */
type OptionalSessionSeq = SessionSeq | null
SessionSeq(value) and SessionLogOffset(value) admit only non-negative safe integers and reject negative zero. They add compile-time brands without changing the serialized number; arithmetic returns an ordinary number that callers must admit again through the constructor for its intended role.
/**
* One immutable entry in the session log.
*
* A proper discriminated union over `type` (not independent `type`/`data`
* unions), so `switch (event.type)` narrows `event.data` without casts.
*
* The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
* they only exist on {@link SurfaceEventType} variants (`user/message`,
* `assistant/message`, `tool/result`).
* Non-surface events (boundary markers, attempts, errors) never carry
* surface metadata — the compiler enforces this at `Session.append()`
* call sites.
*/
type SessionEvent<T extends SessionEventType = SessionEventType> = {
[K in SessionEventType]: {
type: K
/** Monotonic sequence number within the session. */
seq: SessionSeq
/** Unix epoch milliseconds. */
time: number
data: SessionEventMap[K]
/**
* Marks an event a reader may safely skip when it does not recognize
* `type`. Absent means required: a reader meeting an unrecognized type
* without this marker MUST refuse to reconstruct the session instead of
* silently dropping the event, because an unrecognized required event may
* change how the rest of the log is interpreted. A writer sets `true` only
* on purely informational records whose loss cannot affect reconstruction;
* defaulting to required means a forgotten marker over-refuses (an
* inconvenience) rather than silently resuming a gutted session.
*/
ignorable?: true
} & (K extends SurfaceEventType ? {
/**
* Seq numbers of earlier events that this event cites as sources, such as
* the surface nodes shadowed by a compaction replacement. A v2
* `assistant/message` embeds its provider stream and cannot carry this field.
*/
sourceEventSeqs?: SessionSeq[]
/** How this event entered the surface; absent for non-surface events. */
surfaceOp?: SurfaceOp
} : object)
}[T]
SessionEventType = keyof SessionEventMap. Because SessionEventMap is merge-extensible, switches over SessionEvent must NOT use assertNever — a plugin-added variant is a valid unknown value; handle the known cases and fall through default.
V2 assistant/message embeds its provider stream and cannot carry sourceEventSeqs. User and tool surface events may cite a complete non-empty set of unique earlier events when their provenance or replacement operation requires it.
The three message-producing types (SurfaceEventType — user/message, assistant/message, tool/result) carry surface metadata declaring how they join the ordered derived surface. See the session surface Agent Note.
SurfaceEventType — the message-producing subset of event types/**
* The subset of {@link SessionEventType} values whose events produce LLM
* messages and are eligible to appear on the ordered surface. Only these
* event types may carry {@link SurfaceOp}; user and tool events may also cite
* earlier sources through {@link SessionEvent.sourceEventSeqs}.
*/
type SurfaceEventType =
| 'user/message'
| 'assistant/message'
| 'tool/result'
SurfaceOp — how an event entered the surface/**
* How a session event entered the ordered surface. Only valid on
* {@link SurfaceEventType} events.
*
* - `'append'`: added to the tail — normal path for user/assistant/tool
* messages.
* - `{ op: 'replace', start, end }`: replaces surface nodes from `start`
* (inclusive) through `end` (inclusive) with this node. Both must exist as
* surface nodes in the current surface. `start === end` replaces a single
* node. The node's {@link SessionEvent.sourceEventSeqs} must include every
* shadowed surface node. Used by compaction; any surface-replacing producer
* may use it.
*/
type SurfaceOp =
| 'append'
| { op: 'replace'; start: SessionSeq; end: SessionSeq }
'append' is the normal tail-append path. replace shadows surface entries from start through end inclusive (both must be valid surface seqs; start === end replaces a single entry) and inserts the new event in their place.
SurfaceIntent — the parameter to session.append()/**
* Surface placement and cited source-event seqs for {@link Session.append}. Required on
* message-producing events and forbidden on log-only events.
*/
type SurfaceIntent<T extends SurfaceEventType = SurfaceEventType> = {
surfaceOp: SurfaceOp
} & (T extends 'assistant/message' ? {
/** V2 Assistant messages embed their provider stream instead of citing source events. */
sourceEventSeqs?: never
} : {
/** Complete non-empty set of known earlier source-event seqs. */
sourceEventSeqs?: SessionSeq[]
})
Required for SurfaceEventType events — every message-producing event must declare how it joins the surface, the sole source of derived model history. A human-facing transcript is the other projection and reads the log's append-origin events instead, because the surface deliberately shadows the ranges a replacement summarizes (isAppendSurfaceEvent in dsh-session). Non-surface types reject it at compile time.
assistant/message cannot carry sourceEventSeqs; its stream owns exact provider evidence. Other surface events omit the field when they cite no earlier event and use a complete non-empty list when they do.
SessionSurface — the live readonly surface projectionSession.surface returns the session's stable SessionSurface view. The same incremental manager validates append candidates before commit and advances this projection from committed events; callers can observe membership and replacement generation but cannot invoke validation.
SurfaceManager(log, baseSeq?) can instead fold a contiguous loaded window whose first event has the absolute sequence baseSeq. Every event remains contiguous in that absolute sequence space, and a replacement that crosses the window head fails because its declared range is absent.
/** Readonly live projection of the message-producing session events. */
interface SessionSurface {
/** Current surface event sequences in model-visible order. */
readonly nodes: readonly SessionSeq[]
/** Monotonic count of committed positional replacements. */
readonly replaceGeneration: number
}
SurfaceFoldReplacement and SurfaceFoldResult — a complete surface replayfoldSurface(events) returns detached current event sequences together with the actual sequences shadowed by each declared replacement range. The live manager uses the same transitions without retaining replacement history. Its replaceGeneration increments for each committed replacement so incremental consumers can distinguish pure tail growth from a rewrite.
/** One replacement operation observed while folding a session surface. */
interface SurfaceFoldReplacement {
/** Seq of the event that replaced the prior surface range. */
seq: SessionSeq
/** Declared inclusive start seq of the replaced surface range. */
start: SessionSeq
/** Declared inclusive end seq of the replaced surface range. */
end: SessionSeq
/** Actual surface entries removed by the operation, in surface order. */
shadowedSeqs: SessionSeq[]
}
/** Complete result of replaying the surface operations in a session log. */
interface SurfaceFoldResult {
/** Current surface event sequences in model-visible order. */
nodes: SessionSeq[]
/** Replacement operations in event order. */
replacements: SurfaceFoldReplacement[]
}
Session public APIThe body-stripped declaration keeps the plain class's detached factory, state accessors, append method, and history projections synchronized with source. Store operations remain in the generated ctx.sessions section.
/**
* An event-sourced session: an append-only log of {@link SessionEvent}s.
*
* Plain class (not a Service) — create live instances via
* `ctx.sessions.create()` and detached instances via {@link create}.
* Seeding with an existing event log replays/forks a session.
* @typert object
*/
declare class Session {
/** The ordered surface over this session's event log. */
get surface(): SessionSurface;
/**
* Detached, deep-frozen creation metadata (format version, cwd, lineage,
* and whether fork history exists). Supplied by the store via `ctx.sessions.create()`. When a
* `Session` is created without a store-owned header, a minimal header is
* synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
* `session.header` is always present. Kept out of the event log — it is a
* storage concern, not replayable conversation state.
*/
readonly header: SessionHeader;
/** Number of leading events inherited from this Session's fork parent. */
readonly inheritedEventCount: SessionLogOffset;
/** The session identity, derived from its durable header's single copy. */
get id(): SessionId;
/**
* The first seq appended IN THIS PROCESS: the length of the constructor
* seed (0 without one). Events with smaller seq values entered through
* construction — replay, fork, or resume — and were never published on the
* `session/event` firehose (constructor seeds do not emit). This offset marks
* the constructor-input boundary for lifecycle ownership and persistence
* adoption; consumers that need complete canonical history still start at
* seq 0. Distinct from {@link inheritedEventCount}, the DURABLE
* fork-lineage cut: a resumed session's constructor seed is its full stored
* log, while the inherited count keeps the original fork value — this field is the
* in-process construction fact.
*
* Not persisted itself: a seeded session projects it into the log as the
* `session/end-seed` event, which is what a consumer reading STORED history
* reads. Locate the LAST such event, not necessarily one at this seq — a
* seed already ending in one is not re-marked, so reopening an untouched
* session leaves that event at a smaller seq than `firstLiveSeq`. Prefer
* this field in-process: it is exact before the marker reaches storage.
*
* When this lifecycle appends the marker, it occupies this seq before the
* store attaches and therefore does not publish either. Otherwise this seq
* holds an ordinary published write.
*/
readonly firstLiveSeq: SessionLogOffset;
/**
* Create a detached session by validating and snapshotting borrowed seed
* events and storage metadata.
* @param id - session identity.
* @param seed - optional borrowed replay or fork events.
* @param header - optional borrowed storage metadata.
* @param inheritedEventCount - exact fork-inherited prefix length for a seeded header.
* @returns a detached session.
*/
static create(
id: SessionId,
seed?: readonly SessionEvent[],
header?: SessionHeader,
inheritedEventCount?: SessionLogOffset,
): Session;
/**
* Restore a detached session by taking ownership of fresh persistence values.
* The storage format, event envelopes, sequence continuity, surface transitions,
* and header fields are validated before the restored objects are frozen.
* @param id - restored session identity.
* @param seed - fresh detached events whose ownership is transferred.
* @param header - fresh detached metadata whose ownership is transferred.
* @param inheritedEventCount - exact fork-inherited prefix length decoded from storage.
* @returns a restored detached session.
*/
static fromRestore(
id: SessionId,
seed: readonly SessionEvent[],
header: SessionHeader,
inheritedEventCount: SessionLogOffset,
): Session;
/**
* Return the immutable event stored at one exact sequence number.
* @param seq - event sequence number.
* @returns the accepted event, or undefined when the log does not contain it.
*/
eventAt(seq: SessionSeq): SessionEvent | undefined;
/**
* Materialize an immutable snapshot of a half-open event sequence range.
* A full current snapshot is reused until the next append; every previously
* returned snapshot remains stable after later appends.
* @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
* @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
* @returns a frozen array of the selected deeply frozen events.
*/
snapshotEvents(
fromSeq: SessionLogOffset = SessionLogOffset(0),
toSeqExclusive: SessionLogOffset = this.seq,
): readonly SessionEvent[];
/**
* Return this Session's events after its fork-inherited prefix.
* @returns a fresh array containing child-owned events in log order.
*/
ownEvents(): readonly SessionEvent[];
/**
* Whether one existing event position is outside the fork-inherited prefix.
* @param seq - event position in this Session.
* @returns true when the event belongs to this Session rather than its parent.
*/
isOwnSeq(seq: SessionSeq): boolean;
/** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
get seq(): SessionLogOffset;
/**
* Append one typed event to the log and synchronously notify observers via
* the store-owned, module-private publication hooks. The hot path never blocks
* on I/O — persistence plugins buffer asynchronously. Once the event enters
* the log, the append is committed: observer failures are logged and
* contained per listener, so they do not change the return value or prevent
* later listeners from observing the same accepted event.
*
* @param type - The event type (key of {@link SessionEventMap}).
* @param data - The event payload; must be JSON-serializable.
* @param opts - Surface metadata: `surfaceOp` controls how the event enters
* the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
* events this one derives from. REQUIRED for
* {@link SurfaceEventType} events (every message-producing event must
* declare how it joins the surface, the sole source of derived model
* history) and
* rejected by the compiler for non-surface types like `turn/start` or
* `assistant/attempt`. Assistant messages embed their exact provider
* stream and cannot cite top-level source events.
* @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
* `data` that entered the log, so reading `event.data` back sees the logged
* value, never the caller's still-mutable input.
* @throws if `data` or surface metadata is not losslessly JSON-serializable
* (BigInt, function, symbol, undefined, negative zero, non-finite number,
* circular reference, sparse array, or an exotic object such as
* Map/Set/Date/class instance), or when the candidate violates the
* canonical surface contract (marker shape and eligibility, unique
* earlier source-event references, positional replacement validity, and complete
* shadowed-node coverage). One iterative pass reads, validates, and
* copies each nested value once, so a stateful getter cannot supply one value
* to validation and another to storage. The event log is the durable source
* of truth, so a bad event fails at the append site rather than later during
* a backend flush. A synchronous internal dispatch validation failure or an
* append reentered while this acceptance/publication boundary is open also
* rejects before the log changes.
*/
append<T extends SessionEventType>(
type: T,
data: SessionEventMap[T],
...opts: T extends SurfaceEventType ? [opts: SurfaceIntent<T>] : []
): SessionEvent<T>;
/**
* The {@link EpochHeader} in force after the log's last header event — the
* header the NEXT request will be compared against — or undefined before
* the first `request/header` snapshot. The live, incrementally-maintained
* form of `foldRequestHeader(session.snapshotEvents())`: each header event is folded
* once, when first seen, so a per-step read costs O(new events).
* @returns the folded header, or undefined when no header event exists yet.
*/
requestHeader(): EpochHeader | undefined;
/**
* Return the latest resolved route metadata, or `undefined` before the first
* `request/context` event. Each event is folded once.
* @returns the latest immutable route metadata.
*/
requestContext(): RequestContext | undefined;
/**
* Derive the LLM message history by walking the ordered sequences of
* message-producing events maintained by `surfaceOp` markers. The
* surface is the single source of derived history: every message-producing
* append records its `surfaceOp`, so a raw event with no marker (a chunk, a
* turn boundary) is correctly absent, and a compaction `replace` deletes the
* shadowed nodes from the derivation. The projection rules are
* {@link deriveEventMessage}, folded per node.
*
* CACHED: each surface node is projected exactly once, when first seen — a
* call costs O(new nodes), and a surface rewrite (a `replace`;
* {@link SessionSurface.replaceGeneration}) rebuilds. The returned array is
* a fresh snapshot per call (later appends never grow an array a caller
* already holds); the `Message` objects in it are SHARED and **deep-frozen**.
* Their content reuses the already frozen durable event data, so the cache
* needs no second deep clone and consumers still cannot mutate the log.
* @returns a fresh array of the shared, frozen derived history.
*/
deriveMessages(): Message[];
/**
* Instance face of the pure per-node `deriveEventMessage` export from
* `surface.ts`.
* @param event - the event to project.
* @returns the derived message, or null when the event produces none.
*/
deriveEventMessage(event: SessionEvent): Message | null;
}
deriveMessages() and deriveEventMessage()Session.deriveMessages() projects the event log into the Message[] the model sees — cached (each surface node projected once, when first seen; a surface rewrite rebuilds) and frozen (a fresh array per call over shared, deep-frozen messages, so mutating logged history through a projection is unrepresentable). deriveEventMessage(event) is the per-node pure function the fold applies — public so external reconstructors and the dev invariant project a log prefix with exactly the same rules and cannot disagree with the cache. The projection rules:
user/message → a user message carrying exact content; an optional envelope remains log-only display metadata.assistant/message → an assistant message with the provider and model that produced it plus optional adapter-private replay state. Its embedded compact stream is replay, usage, and UI evidence rather than a second message. An empty-content assistant/message is also skipped — a max-tokens step cut off with no content still records an assistant/message to hold its stream, usage, provider, and model, but a content-less assistant turn must not enter the provider transcript.tool/result → a user message carrying a tool-result block.user/message (injected context, i.e. non-user source) → a user-role message carrying its content verbatim at its chronological position; its typed source names the producer and carries any producer-specific data.Everything else (turn/*, step/*, assistant/attempt, plugin-owned llm/retry) is structural and does not project into a message. Token accounting expands the embedded stream on each assistant/message or assistant/attempt, while the message's top-level usage remains the committed-message authority when present. A failed model-request attempt therefore retains its provider usage without fabricating an assistant message. Current logical validation rejects request headers and assistant messages that omit provider/model instead of guessing a route; supported historical representations are normalized and validated by their adjacent format edge before a current Session exists.
ctx.sessions.create(id, { seed, meta }) is the low-level replay/fork primitive. For ordinary live-session forks, SessionStore exposes one policy API:
fork(source, boundary?, childSessionId?) accepts a live Session object or live SessionId, selects source events through the inclusive SessionSeq boundary (default: current last event), requires the selected prefix to end outside an open turn, then creates a live child session with deep-cloned seed events, parentSession, isSeeded: true, the exact inheritedEventCount, and inherited cwd.An explicit boundary lets callers fork from any stable between-turn position, including a previous turn/end or a later standalone log-only event, even if the source has newer events or an open current turn. The API rejects a prefix that ends inside an open turn instead of clipping silently. Broader execution-relation sanity stays in the existing dsh-invariants plugin and persistence repair path rather than being duplicated in fork(). dsh-subagent-fork-in-process keeps its completed-prefix clipping because tool-time delegation usually starts while the parent turn is open; ordinary session branching should make the requested boundary explicit.
TurnEndReasonMapturn/start has no trigger field. The entered user/message batch records what entered each step, llm/retry records request recovery, and idle injection remains pending until a waking delivery reaches a later pre-step. Live turns retain the typed AgentCancelCause that stopped the driver; persistence uses the additional { kind: 'legacy' } cause only when importing a supported coarse cancellation record that did not store its caller.
/** Durable cancellation cause, including imports whose original coarse record carried no cause. */
type TurnEndCancelCause = AgentCancelCause | { readonly kind: 'legacy' }
/**
* Why a turn ended. Merge-extensible sum type.
*/
interface TurnEndReasonMap {
completed: { kind: 'completed' }
/** A cancellation request interrupted the live turn. */
aborted: { kind: 'aborted'; reason: TurnEndCancelCause }
blocked: { kind: 'blocked' }
/**
* The turn failed. `error` is always a structured failure: the `LlmError`
* facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }`
* flattened from any other error.
*/
error: { kind: 'error'; error: LlmFailure }
/** At least one step reached its output-token ceiling, even if a plugin continued the turn. */
'max-tokens': { kind: 'max-tokens' }
/**
* A crash-orphaned turn was closed after the fact: agent-loop resume appends
* this closer for a stored log whose last turn never ended, and session-query
* synthesizes it on cold reads. The loop never emits this marker live, and
* the events recorded before the crash remain intact.
*/
interrupted: { kind: 'interrupted' }
}
max-tokens mirrors the model-call FinishReason of the same name: any max-tokens step in a turn makes the whole turn end max-tokens rather than completed (the cut-short fact wins over a later continuation), so a consumer can tell a clean stop from a truncated one. Cancellation and errors remain distinct outcomes. interrupted is the one reason no loop emits—it is synthesized by crash recovery (see persistence.md). The map is merge-extensible.
A turn encloses one model-loop execution, not the whole session log. AgentLoop records injected user/message events only from entering pre-step batches inside a turn; plugin-owned log-only events may still appear between turn/end and the next turn/start, consuming event seqs without incrementing turn numbers. Persistence admits every contiguous accepted event into a bounded durable batch, while crash repair closes only a genuinely open trailing turn. A producer that needs an immediate durability barrier explicitly awaits ctx.sessions.flush(session).
The optional dsh-session/invariant companion enforces the relations owned by core: turn and step numbering, execution-event enclosure, and same-step tool call/result pairing. Merge-extensible event relations belong to the plugin that declares them, so core does not reject an unknown event merely because no turn is open. See the standalone-event decision.
session/end-seedA fresh fork constructor requires its seed to equal the inherited prefix and appends session/end-seed { inherited: true } at the exact durable cut. A restore retains that tagged marker and appends an ordinary session/end-seed {} only when its complete stored seed does not already end in a marker. Both forms are log-only and produce no message; Session's constructor is the only legitimate writer.
For fork lineage, locate the LAST marker whose payload carries inherited: true; v2 decoding requires it exactly when SessionHeader.isSeeded is true and derives inheritedEventCount from its seq. For lifecycle ownership, locate the last session/end-seed of either form. Reopening a seed that already ends in any marker does not append another ordinary marker.
It exists because seed history and live work are otherwise byte-identical, which defeats any plugin owning a standalone open/close bracket: an unmatched compaction/start reads the same whether the writer crashed mid-compaction or is compacting right now. An opening marker before session/end-seed came from the constructor seed and belongs to an ended lifecycle, whatever ended it (a crash, a succeeding process, or a fork out of a still-running parent), so its owner may treat it as dead. That covers only brackets this session inherited: a concurrently live session holding an open bracket over the same history has its own boundary elsewhere, so tolerating concurrent writers needs a liveness signal beyond the log. Core writes the boundary and reads nothing from it — a bracket's vocabulary stays with its owning plugin, which is why crash repair closes turn/step/tool boundaries and never compaction/*.
Consumers that order Sessions by human activity exclude this boundary: picking a Session up is not work, so ordering by the log tail would float every opened Session to the top.
A plugin may declaration-merge extra SessionEventMap types. These are log-only: NOT SurfaceEventTypes (they carry no surfaceOp and contribute nothing to derived history). Their owner decides whether they belong to an open execution turn or may stand between turns, and enforces any relation in its own invariant companion. The generated persistence log event catalog enumerates every core and plugin-contributed event; the compaction seam's compaction/* semantics are discussed on compaction.md.
When several events in one plugin-owned family assemble into one Web Client Conversation Node, every start, update, result, resource, or interruption event in that family carries or independently derives the same stable business id. This requirement applies to correlated Node families, not to every Session event; it lets the client group each event without guessing from adjacency or scanning history. See the Conversation subsystem.
The hook bridges' hook/invoked / hook/result pairs (from @deepseek-ai/dsh-hook-protocol) correlate by handlerId. UserPromptSubmit, PreToolUse, PostToolUse, and Stop fire inside the loop's open turn, so their hook/* records are turn-enclosed by construction. SessionStart gets no hook/* record because it runs before turn 1; its context remains pending in the inbox until a waking delivery opens a turn (see the hook-bridges Agent Note).
What a persistence backend relies on: the durable log persists every event losslessly, and every Assistant attempt is one assistant/message or assistant/attempt whose embedded compact stream preserves the original timed chunks. seq stays contiguous across these settlements and all interleaved events. A backend may choose its own storage framing for an event batch as long as a handle's read() returns the exact appended events; current JSONL v2 writes one row per event (see persistence.md). All event.data must be JSON-serializable; Session.append enforces this at the source (throwing on non-serializable data), so a bad event never enters the log and session.snapshotEvents() always equals what a backend can persist. Adding an event type that carries non-serializable data, corrupts core execution nesting, or violates its owner's declared relation is a breaking change to the on-disk format.
The backends that consume this contract are on persistence.md.
ModelCatalog is the Host-generation model directory returned by session/modelCatalog: it carries the deployment default, routable provider ids, successful provider groups, and isolated provider failures. It is not derived from one Session and remains separate from Session projections.
SessionOpenWorkspacePathRequest carries an absolute or workspace-resolved path. SessionOpenWorkspacePathValue confirms that the Host accepted the native handoff. A Session-aware Client resolves relative paths against its current Session cwd when known; the controller hands the path to the opener unchanged and reports invalid requests, cancellation, and opener failures through the Session Remote error vocabulary.
Generated from source by scripts/gen-cordis-catalog.ts (verified fresh by pnpm run verify-cordis-catalog in doc-sync; regenerate with pnpm run gen-cordis-catalog) — the language sides differ only in locale-specific paired document paths. Signature blocks use a ts cordis-catalog fence and keep the original source JSDoc; dispatch modes are defined in the primer, and the framework-inherited ctx API lives in cordis-api/inherited.md.
ctx.sessionController — SessionControllerHost service backing the generated ctx.remote.session namespace.
/**
* Resolve or resume one ordinary Session for another Host API domain.
* @param sessionId - Session identity whose Agent owns the operation.
* @returns the live Agent or the stable Session-domain failure.
*/
resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult>
/**
* Inspect one attached or persisted Session without activating its Agent.
* @param sessionId - durable Session identity.
* @param signal - optional caller cancellation for persistence reads.
* @returns the current attached state or persisted header and event prefix.
*/
inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise<SessionInspection>
/**
* Read all visible Session rows without resuming an Agent.
* @param _request - reserved empty list request.
* @param signal - cancellation for persistence reads.
* @returns visible Session summaries ordered by activity.
*/
@Remote('list') async list(_request: SessionListRequest, signal: AbortSignal): Promise<SessionListValue>
/**
* Search visible Session content without resuming an Agent.
* @param request - literal message-content query.
* @param signal - cancellation for list and search reads.
* @returns authorized bounded Session search results.
*/
@Remote('search') search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue>
/**
* Create or idempotently adopt one ordinary Session.
* @param request - requested identity, location, and Agent preset.
* @returns the Session identity and resolved preset when configured.
*/
@Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
/**
* Select one Session-local model after explicitly resuming the Session.
* @param request - Session identity and requested model selection.
* @returns the normalized selection installed for the Session.
*/
@Remote('selectModel') selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue>
/**
* Describe every currently routable model for Host-generation selectors.
* @returns provider-grouped models, the deployment default, and isolated provider failures.
*/
@Remote('modelCatalog') modelCatalog(): Promise<ModelCatalog>
/**
* Report whether this deployment can hand a Session workspace path to a native desktop.
* @returns true when the matching open operation is available.
*/
@Remote canOpenWorkspacePath(): boolean
/**
* Open one path prepared by a Session-aware caller on the Host desktop.
* @param request - path after best-effort Session workspace resolution.
* @param signal - caller lifetime; abort terminates the native command.
* @returns confirmation after the native opener accepts the path.
* @throws RemoteError when the request is invalid, cancelled, or the opener fails.
*/
@Remote('openWorkspacePath') async openWorkspacePath( request: SessionOpenWorkspacePathRequest, signal: AbortSignal, ): Promise<SessionOpenWorkspacePathValue>
/**
* Rename one Session after explicitly resuming it.
* @param request - Session identity and proposed title.
* @returns the accepted title and durable event sequence.
*/
@Remote('rename') rename(request: SessionRenameRequest): Promise<SessionRenameValue>
/**
* Fork one cold-readable completed-turn prefix into a new Session.
* @param request - source Session and optional event anchor.
* @returns the new Session identity.
*/
@Remote('fork') fork(request: SessionForkRequest): Promise<SessionForkValue>
/**
* Admit one prompt after explicitly resuming its Session.
* @param request - Session identity, prompt content, source metadata, and delivery mode.
* @param signal - caller cancellation before prompt admission begins.
* @returns acknowledgement that the Agent accepted the prompt.
*/
@Remote('prompt') prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue>
/**
* Read one image proven reachable from the addressed Session log.
* @param request - Session and attachment identities used for authorization.
* @returns the durable attachment reference and base64-encoded bytes.
*/
@Remote('attachment') attachment(request: SessionAttachmentRequest): Promise<SessionAttachmentValue>
/**
* Mutate one still-pending queue occurrence on a live Agent.
* @param request - Session, queue item, and requested mutation.
* @returns acknowledgement that the queue mutation was applied.
*/
@Remote('updateQueue') updateQueue(request: SessionUpdateQueueRequest): SessionUpdateQueueValue
/**
* Cancel one active Agent turn without dropping its pending inbox.
* @param request - Session whose active Agent turn is cancelled.
* @returns acknowledgement that cancellation was requested.
*/
@Remote('cancel') cancel(request: SessionCancelRequest): SessionCancelValue
/**
* Read one cold-safe, message-aligned Session history page.
* @param request - durable address, backward cursor, and page budget.
* @param signal - cancellation for persistence reads.
* @returns one chronological page.
*/
@Remote('page') page(request: SessionPageRequest, signal: AbortSignal): Promise<SessionPage>
/**
* Follow one Session log from its opening or resume cursor.
* @param request - durable address and last committed sequence already held by the caller.
* @param signal - cancellation owned by the Remote stream carrier.
* @returns a complete opening snapshot followed by gap-free durable event
* frames and optional cursorless assistant-stream frames.
*/
@Remote({ mode: 'stream' }) follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame>
/**
* Stream a complete live-control baseline followed by replacement frames.
* @param signal - cancellation owned by the Remote stream carrier.
* @returns one complete baseline followed by live replacement frames.
*/
@Remote({ mode: 'stream' }) control(signal: AbortSignal): AsyncIterable<SessionControlFrame>
Types: SessionId · SessionInspection · SessionSearchRequest
Source: packages/api/session-controller/src/index.ts
ctx.sessions — SessionStoreIn-memory session store (ctx.sessions).
Persistence is intentionally not implemented here — the agent lifecycle attaches a session-log writer to each published session's write handle; a session published outside that lifecycle persists nothing.
/**
* Create a session owned by the calling fiber: disposing that fiber stops
* event notification and removes the session from the store. `options.seed`
* populates the session with a copy of those events (replay/fork);
* `options.meta` attaches creation metadata (validated absolute `cwd`, seed
* and parent lineage, and delegation depth) as the immutable
* {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
*
* For an agent whose session must be torn down IN ORDER with its loop (so the
* loop's final events are published before the store attachment ends), do NOT use this
* — fold the session lifecycle into the agent's own effect via
* {@link prepare} + {@link enter} + {@link announce} (see
* `dsh-agent-loop`'s creation transaction).
*
* @param id - the session id; omitted, the store mints `session-<n>`.
* @param options - seed events and/or creation metadata for the header.
* @returns the live session, already entered and announced.
* @throws if a session with `id` already exists, metadata is not a plain
* lossless-JSON record with valid scalar fields, or `meta.cwd` is a
* non-absolute path (storage backends key directories off it).
*/
create(id?: SessionId, options?: CreateSessionOptions): Session
/**
* Build a session WITHOUT entering it into the store — validate the id/cwd and
* construct the {@link Session} (with its immutable {@link SessionHeader}).
* Pairs with {@link enter} + {@link announce}: a caller that owns a composite
* `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
* effect so a fiber unload tears the session + agent down as a single ORDERED
* chain rather than as racing sibling effects — which would remove the publication hooks
* before the driver's closing events commit, dropping them.
*
* @param id - the session id; omitted, the store mints `session-<n>`.
* @param options - seed events and/or creation metadata for the header. With
* `seedSource: 'persistence'`, metadata and events must be fresh detached
* graphs whose ownership transfers to this call: they are validated and
* frozen in place through {@link Session.fromRestore}, so the caller must
* retain no mutable aliases.
* @returns the constructed session, NOT yet in the store.
* @throws if a session with `id` already exists, metadata is not a plain
* lossless-JSON record with valid scalar fields, or `meta.cwd` is a
* non-absolute path.
*/
prepare(id?: SessionId, options?: PrepareSessionOptions): Session
/**
* Enter a {@link prepare}d session into the store: install the module-private
* append publication hooks and add it to the store. Returns the DETACH
* disposer (hooks + store removal). Does NOT emit `session/created` —
* the caller yields this disposer inside its effect and THEN calls
* {@link announce}, so a throwing `session/created` listener rolls the attach
* back instead of leaking it.
*
* Re-checks the id for a duplicate: `prepare` and `enter` are public
* cross-package primitives and a caller may interleave arbitrary work (or
* another create) between them, so a stale prepared session must NOT overwrite
* a live store entry of the same id — its detach disposer would later delete
* the REAL session. The {@link create} convenience and the agent factory call
* the two back-to-back so they never trip this, but the public API cannot
* assume that.
*
* @param session - a {@link prepare}d session not yet in the store.
* @returns the detach disposer (publication hooks + store removal). When called from
* a synchronous `session/created` listener, removal and disposal wait until
* that creation dispatch unwinds.
* @throws if a session with this id is already in the store.
*/
enter(session: Session): () => void
/** Emit `session/created` exactly once for an {@link enter}ed session (with
* the carrier {@link enter} captured). Separate from {@link enter} so the
* caller can yield the detach disposer first (rollback safety — see
* {@link enter}).
* @param session - the entered session to announce to listeners.
* @throws if the session is not live or its announcement already began,
* including a reentrant call from a creation listener. */
announce(session: Session): void
/**
* Dispatch the awaited `session/flush` durability checkpoint for `session`,
* with the carrier captured at {@link enter}. THE flush entry point: the
* store owns the carrier, so callers (the checkpoint policy's per-request
* barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers
* that flush themselves before reading storage) must come through here
* rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner,
* one spelling, and the scoped-dispatch invariant can pin it.
* @param session - the session whose buffered events must reach durable storage.
* @returns whether at least one durability listener participated, after every
* listener has settled successfully.
* @throws the first registered listener failure after every listener settles.
*/
async flush(session: Session): Promise<boolean>
/**
* Look up a live session.
* @param id - the session id to look up.
* @returns the session, or undefined when no live session has that id.
*/
get(id: SessionId): Session | undefined
/**
* All live sessions, in creation order.
* @returns a fresh array; mutating it does not affect the store.
*/
list(): Session[]
/**
* Create a live child session from a stable prefix of a live source.
* `boundary` is an inclusive source event seq; omitted means the source's
* current last event. The selected slice may end with a between-turn event
* but must not end inside an open turn.
*
* @param source - Live source session object or id.
* @param boundary - Inclusive source event seq to fork through; omitted means
* the source's current last event, and omitted on an empty source forks an
* empty child.
* @param childSessionId - Optional child session id; omitted delegates to
* `SessionStore`'s id policy.
* @returns The created live child session.
*/
fork(source: SessionForkSource, boundary?: SessionSeq, childSessionId?: SessionId): Session
Types: CreateSessionOptions · PrepareSessionOptions · SessionId
Source: packages/core/session/src/index.ts
api-session/* eventsapi-session/activity — emitOne user-authored durable message advanced Session list activity.
/**
* One user-authored durable message advanced Session list activity.
* @mode emit
* @param sessionId - addressed Session identity.
* @param updatedAt - durable message time used for list ordering.
*/
'api-session/activity'(sessionId: SessionId, updatedAt: number): void
Types: SessionId
Source: packages/api/session-controller/src/types.ts
api-session/added — emitA Session became visible to Session list consumers.
/**
* A Session became visible to Session list consumers.
* @mode emit
* @param summary - initial list row for the Session.
*/
'api-session/added'(summary: SessionSummary): void
Source: packages/api/session-controller/src/types.ts
api-session/error — emitOne Agent failed outside a durable turn position.
/**
* One Agent failed outside a durable turn position.
* @mode emit
* @param sessionId - Agent and Session identity.
* @param message - user-safe failure chain.
*/
'api-session/error'(sessionId: SessionId, message: string): void
Types: SessionId
Source: packages/api/session-controller/src/types.ts
api-session/removed — emitA Session left the live Host registry.
/**
* A Session left the live Host registry.
* @mode emit
* @param sessionId - removed Session identity.
*/
'api-session/removed'(sessionId: SessionId): void
Types: SessionId
Source: packages/api/session-controller/src/types.ts
api-session/status — emitOne Agent changed running state.
/**
* One Agent changed running state.
* @mode emit
* @param sessionId - Agent and Session identity.
* @param running - whether the Agent is running.
*/
'api-session/status'(sessionId: SessionId, running: boolean): void
Types: SessionId
Source: packages/api/session-controller/src/types.ts
session/* eventssession/created — emitCreation announcement during session publication. A synchronous throw vetoes and rolls back with a paired disposal; detach requested during dispatch is deferred. A returned-promise rejection is logged but cannot retroactively veto this synchronous boundary. Scope-filtered dispatch (@deepseek-ai/dsh-scope): agent-scoped listeners receive only sessions entered through that agent's context.
/**
* Creation announcement during session publication. A synchronous throw vetoes and rolls
* back with a paired disposal; detach requested during dispatch is deferred.
* A returned-promise rejection is logged but cannot retroactively veto this
* synchronous boundary.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
* receive only sessions entered through that agent's context.
* @param session - the session just entered and announced.
* @dshScopeScan unsupported
* @mode emit
*/
'session/created'(this: Scoped<Session>, session: Session): void
Types: Scoped
Source: packages/core/session/src/index.ts
session/disposed — emitEmitted once when an announced session leaves the store, including publication rollback, but never for an entry whose creation announcement did not begin. Listener failures are logged and contained. Scope-filtered dispatch (@deepseek-ai/dsh-scope) reuses the owner scope.
/**
* Emitted once when an announced session leaves the store, including
* publication rollback, but never for an entry whose creation announcement
* did not begin. Listener failures are logged and contained.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
* @param session - the session that is no longer live in the store.
* @dshScopeScan unsupported
* @mode emit
*/
'session/disposed'(this: Scoped<Session>, session: Session): void
Types: Scoped
Source: packages/core/session/src/index.ts
session/event — emitPost-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Scope-filtered dispatch (@deepseek-ai/dsh-scope): agent-scoped listeners receive only events from sessions entered through that agent's context.
/**
* Post-commit, fire-and-forget append feed. The listener snapshot resolves
* before the log push, but callbacks run after it; observer failures are
* logged and contained without making the committed append fail.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
* receive only events from sessions entered through that agent's context.
* @param session - the session whose log grew.
* @param event - the appended event, exactly as recorded.
* @dshScopeScan unsupported
* @mode emit
*/
'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void
Types: Scoped
Source: packages/core/session/src/index.ts
session/flush — parallelAwaited parallel durability checkpoint: every listener runs and the caller awaits all of them, with no waterfall veto. Scope-filtered dispatch (@deepseek-ai/dsh-scope) reuses the session's owner scope.
/**
* Awaited parallel durability checkpoint: every listener runs and the
* caller awaits all of them, with no waterfall veto. Scope-filtered dispatch
* (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
* @param session - the session whose buffered events must reach durable storage.
* @dshScopeScan unsupported
* @mode parallel
*/
'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void
Types: Scoped