@sema-agent/core
Version:
Stateless, task-oriented AI agent core
666 lines • 56.1 kB
TypeScript
export { StoredSession } from "../internal/harness.js";
export type { Session } from "../internal/harness.js";
export { InMemorySessionRepo, InMemorySessionStorage, uuidv7, validateEntriesForImport, StreamingImportValidator, } from "../internal/harness.js";
export { BaseSessionStorage, leafIdAfterEntry, } from "../internal/harness.js";
export type { SessionStorage, SessionRepo, SessionRepoRowCells, SessionRow, SessionMetadata, SessionTreeEntry, } from "../internal/harness.js";
export { SessionError } from "../internal/harness.js";
export type { SessionWriteOptions } from "../internal/harness.js";
export { CORRUPT_SESSION_DELETE_DOORS, CORRUPT_SESSION_FORMS, CORRUPT_SESSION_WAYS, CORRUPT_SESSION_WAYS_OUT, corruptSessionWayOutSentence, isCorruptSessionForm } from "../internal/harness.js";
export type { CorruptSessionDeleteDoor, CorruptSessionDetail, CorruptSessionForm, CorruptSessionWay, CorruptSessionWayOut } from "../internal/harness.js";
import type { CorruptSessionForm } from "../internal/harness.js";
import type { Session } from "../internal/harness.js";
import type { SessionHead, SessionRowExpectation, SessionRowRead, SessionTreeEntry } from "../internal/harness.js";
export type { SessionPlacementRecord } from "../internal/harness.js";
export type { SessionHead, SessionLogMark, SessionRowExpectation, SessionRowRead } from "../internal/harness.js";
/** True when `err` is a session optimistic-lock conflict (a concurrent writer won the branch leaf). Both
* halves read what a HOST `SessionStorage` threw, so both are guarded — unreadable is not a conflict,
* never a raise inside the classify-and-rethrow guard. The class test is KEPT: widening the verdict to
* any value carrying the word would arm the CAS retry loop on a foreign error (KL-942b). */
export declare function isSessionConflict(err: unknown): boolean;
/** True when `err` is a by-id head read's refusal of a row it cannot read (`corrupt_session`): the row stands, and no owner,
* occupant or placement can be named from it. That refusal is the only reading of "unreadable" — a head never carries a third owner
* value — and a `storage` fault (an I/O error) is never unreadable: it does not say whether the row stands. Same form as
* {@link isSessionConflict} (the class test, then one guarded read of `code`), and like it, it reads what a host's store threw. */
export declare function isRowUnreadable(err: unknown): boolean;
/**
* The form of a `corrupt_session` ({@link CORRUPT_SESSION_FORMS}) a thrown value states, or `undefined`: not a session error, not that code,
* or the code with no form (a store outside this package that mints it without one, which reads as "not stated" — the sentence is never
* parsed for it). Same form as {@link isRowUnreadable}: the class test, then guarded reads. What a person can do about a form is
* `CORRUPT_SESSION_WAYS_OUT[form]` and `corruptSessionWayOutSentence(form, store)`.
*/
export declare function corruptSessionFormOf(err: unknown): CorruptSessionForm | undefined;
/** Is the row unreadable now, by ONE synchronous head read: refused {@link isRowUnreadable} ⇒ `true`; a head or no row ⇒ `false`; any
* other fault rethrown. What a repo's unreadable-row removal decides by, in the step that removes the row. */
export declare function rowUnreadableNow(readHead: () => unknown): boolean;
/** {@link rowUnreadableNow} over an awaited head read — what a store's operator entry reads before it runs the deletion hook. */
export declare function rowUnreadableAt(readHead: () => Promise<unknown>): Promise<boolean>;
/** The operator deletion entries' one reading of the id they are handed: a session id is a non-empty string, and anything else is refused
* (`config.invalid_argument`) before any row is read — a number or an empty string never names a row by coercion. */
export declare function readUnreadableDeleteId(face: string, sessionId: unknown): string;
/**
* Subagent transcript persistence — the ACQUIRE-form placement declaration a trusted spawner passes
* when it creates a subagent's transcript session: the session is created INTO the store's subagent
* partition instead of the host lane. The minter reports the fact; the store never guesses residency
* from call shape. `placedAt` is stamped by the store at creation (see
* {@link SessionPlacementRecord}). Reaches stores ONLY through the engine's trusted internals chain
* (never a public TaskSpec key — a public key would let any caller push arbitrary sessions into the
* partition and poison store-side retention/enumeration).
*
* The tuple says WHERE the row lives, never whose it is: the row's owner is the creating write's own owner — the `owner` of the
* {@link SessionStore.acquire} that creates the row, the owner argument of a {@link SessionStore.fork} — exactly as for a row
* that is not placed.
*/
export interface SessionPlacement {
kind: "subagent";
/** Tenant key, same source as the durable agent row's `scope`. */
scope?: string;
/** The spawning host session (retrieval/partition metadata; authorization stays on the row predicate). */
parentSessionId?: string;
/** The delegation tree's root host session (fixed point). */
rootSessionId?: string;
/** The durable agent row key (`a…`) — the store-side join key for orphan GC. */
handle?: string;
}
/**
* One row of {@link SessionStore.listPlaced}. The row-store join key is the FULL `(scope, handle)`
* tuple — a listing that cannot supply both returns the discriminated `tupleIncomplete` variant
* instead (consumers fail closed on it: never age-reaped, reported honestly).
*/
export type PlacedSessionRow = {
sessionId: string;
placedAt: number;
} & ({
scope: string;
handle: string;
} | {
tupleIncomplete: true;
});
/** A session handed back by a {@link SessionStore}: the harness `Session` plus its resolved id. */
export interface AcquiredSession {
session: Session;
sessionId: string;
}
/**
* A lightweight, read-only projection of one session for a `/resume` list (shell K-5 — re-attach without an
* N+1 walk). Returned in pages by {@link SessionStore.list}, newest-first by `(lastActiveAt, sessionId)`.
* `lastTaskId` is the engine's term for what the service/wire surfaces as the session's **`lastRunId`** — the
* most recent task run on this session, so a shell re-attaches in ONE hop.
*
* Named `*StoreSummary` (not the bare `SessionSummary` an earlier version used) because that name collided
* with an unrelated, differently-shaped `SessionSummary` downstream (the SDK's wire GET /v1/sessions row) —
* same name, two shapes, the exact "同名异形" pattern a cross-repo cleanup was independently eradicating
* elsewhere. This type is this store interface's own projection, never itself
* serialized onto the wire — a service backend re-projects/renames its fields (`lastTaskId` → `lastRunId`)
* when building the actual wire response.
*/
export interface SessionStoreSummary {
/** The session id. */
sessionId: string;
/** When the session was created ({@link SessionMetadata.createdAt}, ISO string); absent when the backend's
* cache view doesn't carry it. */
createdAt?: string;
/** Epoch ms of the session's newest activity the store RECORDS — its writes and its {@link SessionStore.touch}es (the Runner touches
* a session as each run ends) — the newest-first sort key for "recent sessions". Recorded, never what one process saw: a restart,
* another replica or a dropped cache reads the same time, and only a later activity moves it. An acquire that writes nothing is not
* activity. */
lastActiveAt: number;
/** The most recent task run on this session (core's `taskId` — on a ledger run, the host's if it gave one other than the session id, the id the parked row recorded on a resume, otherwise the minted `rl-…` one; the service projects it as `lastRunId`).
* Absent until a task has run on the session (recorded via {@link SessionStore.noteTaskRun}). */
lastTaskId?: string;
/**
* An ENGINE-minted run identity for this session ({@link import("./types.js").TaskResult.runId}),
* recorded by the most recent {@link SessionStore.noteTaskRun} write to LAND.
* {@link lastTaskId} above is the leg's task id (a background row's id; on a ledger run, the host's if it gave one
* other than the session id, the id the parked row recorded on a resume, otherwise the minted `rl-…` one; else the
* declared one or the session id), so on the ordinary deployment that supplies no
* host task id it answers the SESSION's own id: a "last run" handle that names the session it hangs off
* cannot say WHICH run it means. This one names a specific run — read the ORDERING clause below for
* exactly how strong "most recent" is here, which is weaker than the sibling field's wording implies.
*
* Named `lastTaskRunId`, NOT `lastRunId`: the paragraph above this interface records that a service
* backend renames `lastTaskId` → the WIRE field `lastRunId`, so a store field spelled `lastRunId` would
* be the same name carrying a different identity one hop apart — a mixed-version mapper (or an object
* spread) could then publish either value under the one wire name with no type error. Same
* collision-avoidance as {@link import("../orchestration/workflow-types.js").WorkflowAgentRun.taskRunId}.
*
* ORDERING (honest limit): the Runner records this fire-and-forget, exactly as it always has for
* `lastTaskId`, so on a store whose write is asynchronous two runs of one session race and the loser's
* id can land last. That race was invisible while both runs wrote the same `lastTaskId`; it is
* observable here. Read this as "an id of a recent run", and take strict ordering from the runs'
* own results, not from this projection.
*
* Additive and optional: absent on a store that predates it, absent until a task has run, and absent
* whenever the recording caller had no run id (see {@link SessionStore.noteTaskRun}).
*/
lastTaskRunId?: string;
/** F7 fork-GC seam: the parent session this one was forked from ({@link SessionMetadata.forkedFrom}).
* Lets a consumer render/reap fork lineage; absent on non-forked sessions and on cache views that
* predate the fork. The durable source of truth is the repo's persisted metadata. */
forkedFrom?: string;
/** The row's occupant cell ({@link SessionMetadata.incarnation}), `null` when the row has none — read in the same row read as
* {@link forkedFrom}. With the session id it names the row's file-history scope (`fileHistoryScopeOf`), which a deletion cascade
* computes for each fork it carries history into. Store-interface material only: a service never puts it on the wire. */
incarnation: string | null;
/** The occupant of {@link forkedFrom} the fork was cut from ({@link SessionMetadata.forkedFromIncarnation}), `null` when the row
* records none (not a fork, or a fork cut before rows named their occupants) — read in the same row read as {@link forkedFrom}. With
* `forkedFrom` it names the source's history address the fork carries from. Store-interface material only, never on the wire. */
forkedFromIncarnation: string | null;
}
/** The page bounds of {@link SessionStore.list}: a query without `limit` reads `default` rows; an explicit `limit` is an integer in
* 1..`max`. */
export declare const SESSION_LIST_LIMITS: Readonly<{
readonly default: 50;
readonly max: 1000;
}>;
/**
* What {@link SessionStore.list} is asked for. No query, or `{}`, is the unfiltered list — every owner's rows, unowned ones included —
* read from its first page, at most {@link SESSION_LIST_LIMITS}`.default` rows; a caller that wants every row pages with `after`.
* A store may define extension filters of its own (members beside these, e.g. a text search); a filter applies before the page is
* cut, so `after` and `limit` page the filtered list. A store refuses a member it does not read — an unread filter would list rows the
* caller asked to exclude.
*/
export interface SessionListQuery {
/** Only the rows this owner owns (exact match; a principal name, so a blank string is refused, never an owner of its own). Absent = no owner filter. */
owner?: string;
/** With `owner`: the unowned rows (owner `null`) too. A member of the owner filter only — given without `owner` it is refused, so a
* query that lost its owner never widens into every owner's list. */
includeUnowned?: boolean;
/** The keyset cursor — the `lastActiveAt` and `sessionId` of the last row of the previous page: only rows after it in the list's
* order are read (a smaller `lastActiveAt`, or the same one with a smaller `sessionId`). */
after?: {
lastActiveAt: number;
sessionId: string;
};
/** At most this many rows, an integer in 1..{@link SESSION_LIST_LIMITS}`.max`; absent = the default. Ask for one more than a page
* shows to learn whether another page exists. */
limit?: number;
}
/** {@link readSessionListQuery}'s answer: the query's members as read, the defaults filled in. */
export interface SessionListQueryReading {
readonly owner?: string;
readonly includeUnowned: boolean;
readonly after?: {
readonly lastActiveAt: number;
readonly sessionId: string;
};
readonly limit: number;
/** The values of the extension members the reading store declared and the query carries. */
readonly extensions: Readonly<Record<string, unknown>>;
}
/**
* The one reading of a {@link SessionListQuery}, for every store that implements {@link SessionStore.list}: `raw` read by the
* engine's receipt law (a plain object, each member read once), each member judged, the default limit filled in. `extensions` names
* the extension members the calling store reads (none for a store without extension filters); any other member is refused. A bad
* value is refused, never mapped to a default: `config.invalid_argument`.
*/
export declare function readSessionListQuery(raw: unknown, extensions?: readonly string[]): SessionListQueryReading;
/**
* The session lifecycle/caching layer the {@link Runner} depends on.
*
* `TtlSessionStore` is the default (in-memory, 7-day idle TTL). Provide a custom implementation
* to back sessions with durable, external storage (the "Session center"): `acquire` reconstructs
* a session from the persisted event log so any stateless runner instance can resume it.
*
* Implementations must be safe under concurrent `acquire` of the same id (return one session).
*
* `S` / `Q` are the store's list projection and query: a backend whose list carries more per row (or filters by more) extends
* {@link SessionStoreSummary} / {@link SessionListQuery} and implements `SessionStore<Its summary, Its query>` — still assignable
* wherever a `SessionStore` is taken.
*/
export interface SessionStore<S extends SessionStoreSummary = SessionStoreSummary, Q extends SessionListQuery = SessionListQuery> {
/**
* design/173 §2.3 — durability declaration (see
* {@link import("./checkpoint-store.js").StoreDurability}): whether sessions this store accepts
* SURVIVE A PROCESS RESTART. That is the whole claim of this axis — multi-replica
* coordination/concurrency is a separate backend property this field does not license (review
* fold r1-F2/r2-F3; a single-instance file-backed store declares `"durable"` honestly).
* Declaration, never duck-typing (the wiring manifest relays it verbatim — it never sniffs class
* names); ABSENT is read fail-closed as `"process-local"` (under-promise, never over-promise).
* `TtlSessionStore` over a durable {@link SessionRepo} declares via its `durability` option — the
* store cannot inspect the repo's persistence, so the DEPLOYMENT that wired the repo states the
* fact.
*/
readonly durability?: import("./checkpoint-store.js").StoreDurability;
/**
* The grant-holder declaration — ONE per store, the same shape and meaning as `CheckpointStore.fence`
* ({@link import("./checkpoint-generation.js").StoreHolderFence}): `{ holder: "writes" }` = every storage this store hands out judges
* {@link import("../engine/harness/types.js").SessionWriteOptions.holder} on each append and leaf move that carries one, first and in
* the write's own atomic step, by the deployment's one judge — a holder not current throws `holder.superseded` with nothing written.
* `requireHolder: true` asks the engine's run and verb doors to refuse a run or verb the HOST starts without a holder (a leg the engine
* starts — a delegated child, a workflow member, an observer — is exempt); the store itself never refuses a write for carrying none.
* ABSENT ⇒ judges no holder, and a run carrying one over this store is refused at its seat (`config.invalid_session_store`); the
* retired `{ holder: true }` and every other form are refused there too. `TtlSessionStore` mirrors its repo's
* ({@link import("../engine/harness/types.js").SessionRepo.fence}); a host's own store declares it directly; a wrapper forwards it
* (and the holder of every write it forwards); a routing store declares only when every store it routes to judges. The engine reads
* it at the door and never calls the judge itself; a store declaring it without judging is caught by the contract kit
* (`sessionStoreContract` with `composed` and `grants`), not at startup.
*/
readonly fence?: import("./checkpoint-generation.js").StoreHolderFence;
/** A routing store's word in place of {@link fence} (the same one shape): "every storage I hand out answers for itself"
* ({@link import("../engine/harness/types.js").SessionStorage.getResidence}). Read only for a leg an engine lane started that carries a
* tree holder over a store with no `fence`; the storage's answer then decides (judges ⇒ the writes carry the holder; process-local and
* judging nothing ⇒ they carry none; no answer ⇒ the leg is refused). A store that declares it hands out only storages that answer. */
readonly durableFence?: import("./checkpoint-generation.js").StoreHolderFence;
/**
* The directory this store writes its sessions' transcripts into, absolute — present only where they are files there
* (`TtlSessionStore` relays its repo's {@link import("../engine/harness/types.js").SessionRepo.transcriptDirectory}; a file
* backend's store answers its `<root>/sessions`). The Runner's transcript gate guards exactly this directory; ABSENT ⇒ there is no
* transcript directory to guard (a store in memory, a database's), and the gate guards none — it never falls back to a directory
* computed from `AGENT_DATA_DIR`, which may not be where this store writes.
*/
readonly transcriptDirectory?: string;
/**
* Subagent transcript persistence — the store's PER-PLACEMENT durability declaration: "this store
* understands and honors placement semantics (partitioning + the obligations below), and sessions
* placed into the `subagent` partition have THIS durability". Declaration, never duck-typing (the
* wiring manifest relays it verbatim). The store-level {@link durability} continues to describe
* only UN-placed sessions — a routing/composite store whose transient host lane and durable
* subagent partition differ can therefore be honest on both axes. ABSENT = the store does not
* understand placement: an `acquire` carrying one is legally IGNORED (the session is then an
* ordinary one, and the deployment's delegation-durability tier reads as rows-only).
*
* Declaring this commits the store to the placement obligations:
* 1. a placed session enjoys the declared durability (`acquire(id, {requireExisting:true})`
* reaches it after a restart when `"durable"`);
* 2. placed sessions do NOT appear on host enumeration faces (`list` and every deployment
* listing path — restart-stable);
* 3. acquire semantics for sessions WITHOUT a placement are byte-unchanged;
* 4. `release(placedId)` is a REAL deletion (durable history included) — the joint reap's
* "row and session both gone" depends on it;
* 5. placement is FIRST-WRITE IMMUTABLE — a re-open (`requireExisting`, with or without a
* placement argument) returns the same session and never rewrites the tuple;
* 6. a placed id cannot be CLAIMED: a later claim-form acquire (no `requireExisting`, no
* creation placement) of an existing placed id refuses loudly
* (`SessionError("placement_refused")`) instead of attaching;
* 7. a placed row's owner cell is recorded as every created row's is — the creating acquire's `owner` (no owner of its own
* derived, none read off the tuple) — and the store answers {@link headOf} for every session it holds — with the row's
* `incarnation`, the same token the acquired session's metadata carries for a row this store created (a revived child reads
* its tree's owner off its own row through it).
*/
readonly placements?: {
subagent?: {
durability: "durable" | "process-local";
};
};
/** Get an existing session by id, or create one (optionally with a caller-supplied id). design/114 Phase3:
* `opts.requireExisting` ⇒ a store MUST fail loud (throw a `not_found` {@link SessionError}) on a genuinely
* missing id rather than create-on-miss — so a reuse-style warm-resume of a gone session errors instead of
* silently starting a fresh empty run. A store that cannot honor it MUST still not silently create (either
* implement the check or reject the option).
* `opts.placement` (subagent transcript persistence): CREATE the session into the named placement
* partition (see {@link SessionPlacement} — trusted-internals channel only). Ignored by stores
* that do not declare {@link placements}; on a store that does, the creating call is exempt from
* obligation 6 above and idempotent re-acquire by the same trusted chain stays legal.
* `opts.owner`: the owner the CREATING write records in the row's owner cell — a principal name, or `null` for anonymous;
* absent ⇒ `null` (the same cell reading every create applies). It is the one owner channel of a row an acquire creates, placed
* or not, as the owner argument is a fork's and register's. An acquire that resolves an EXISTING row records nothing and changes
* nothing, whatever `owner` it carries (a row's owner is recorded once, by the write that creates it); the engine, which names an
* owner on the create-capable acquire of every leg it delegates, reads the row back through {@link headOf} and refuses a row
* that does not record that owner. Read only on the create-capable form (a `requireExisting` acquire creates nothing). */
acquire(sessionId?: string, opts?: {
requireExisting?: boolean;
placement?: SessionPlacement;
owner?: string | null;
}): Promise<AcquiredSession>;
/** Mark a session recently active: resets the idle TTL where applicable, and is activity the {@link list} order records. May be
* async for durable stores. */
touch(sessionId: string): void | Promise<void>;
/** Drop a session from the live set (e.g. a throwaway task). Durable history may be retained by the backend. A release that deletes the
* row (a placed row's, or any under `evict: "delete"`) deletes the row and its log only, as {@link delete} does — never the session's rows
* in other stores; a deployment that erases them does it in {@link SessionStoreHooks.beforeSessionDelete}, while the row still stands. */
release(sessionId: string): Promise<void>;
/**
* Drop only the CACHED view of a session — **never** deletes history (unlike `release`, which with the
* in-memory `TtlSessionStore`'s default `evict: "delete"` policy removes the session from the repo too).
* The Runner uses this where the intent is "discard a stale view and re-wake", and on a prepare-phase
* throw after acquire (audit B-17 + the 1.93.0 throw-cleanup contract gap: calling `release` there
* silently DELETED an existing session's whole history on the default store — the re-acquire then
* continued on an empty same-id session). **Optional, but custom stores SHOULD implement it**: when
* absent the Runner performs NO fallback (it never substitutes `release`, whose contract permits
* deletion — B-17 council) — the cached view is simply not dropped, so a persistent reconcile conflict
* exhausts its retry budget and propagates instead of risking history. A store whose `release` is
* already history-safe can implement `forget = release`.
*/
forget?(sessionId: string): void | Promise<void>;
/**
* Protect a session from idle eviction while a design/45 checkpoint references it (a suspended task
* must still be resumable). `pin` before suspend, `unpin` on resume/expiry. **Optional**: a durable
* backend that never idle-GCs sessions (service's `tidb-session-store`) implements both as no-ops and
* is still safe; only the in-memory `TtlSessionStore` needs a real pin (its `sweep` skips pinned ids).
* See design/45 §5 / M3.
*/
pin?(sessionId: string): void | Promise<void>;
unpin?(sessionId: string): void | Promise<void>;
/**
* Record that a task run STARTED on a session (the Runner calls this at task start, when both ids are
* known) so the store can surface it as {@link SessionStoreSummary.lastTaskId} — letting a `/resume` list
* re-attach to the most recent run, even one still in-flight or suspended. **Optional + best-effort**: a
* store that surfaces no session list may ignore it; it MUST NOT throw. The engine's `taskId` is the
* service's `lastRunId`.
*
* `runId` (#499, additive third parameter — an existing implementation keeps typechecking and keeps
* working): the engine's own identity for THIS run, for {@link SessionStoreSummary.lastTaskRunId}. It
* is supplied because `taskId` cannot answer "which run": with no host task id it IS the session id (on a run that keeps no
* member ledger; one that keeps one records the task id the engine minted for it, `rl-…`, the same on every run of that task).
*
* The two seats describe ONE run and MUST move together: a call that omits `runId` records the new
* `lastTaskId` and CLEARS `lastTaskRunId`. Keeping the previous run's id beside a newer task id would
* assert that an id belonging to an older run identifies the latest one — absence is the honest answer
* to "which run was last" when the caller does not know.
*/
noteTaskRun?(sessionId: string, taskId: string, runId?: string): void | Promise<void>;
/**
* One page of the store's sessions as lightweight {@link SessionStoreSummary} projections, so a shell's `/resume` lists sessions +
* their last run in ONE call: every session ROW the store holds — what a restart still finds, not only what this process has
* cached — that the query admits, newest-first by `(lastActiveAt, sessionId)` (both descending; equal times order by id), at most
* `limit` rows after the `after` cursor (see {@link SessionListQuery}; read it with {@link readSessionListQuery}, whose refusals are
* this face's). Placed sessions are never listed (placement obligation 2). Reading the list is not activity, and a row's time only
* moves forward, so paging with `after` never reads a row twice — a row written or touched between two pages moves ahead of the
* cursor, where later pages do not read it (a fresh first page shows it). **Optional**: a store that cannot enumerate omits this (the
* shell then has no session-list affordance — honest degrade).
*/
list?(query?: Q): Promise<S[]>;
/**
* Subagent transcript persistence — enumerate the PLACED partition (the input to the joint reap's
* partition leg: sessions whose owning agent row is gone are the orphan shape it collects).
* **Optional**: absent = the partition-GC leg is simply unavailable on this store (documented,
* fail-closed — placed sessions then age out only through the row-joined reap path). `olderThanMs`
* filters by session AGE (last activity where knowable, else `placedAt`); `scope` narrows to one
* tenant. Rows return the FULL `(scope, handle)` join tuple or the honest `tupleIncomplete`
* variant (see {@link PlacedSessionRow}) — consumers must skip incomplete tuples, never guess.
*/
listPlaced?(kind: "subagent", opts?: {
olderThanMs?: number;
scope?: string;
}): Promise<PlacedSessionRow[]>;
/**
* design/110 — FORK a session: copy `sourceId`'s durable history (root→leaf) into a NEW session and return its
* id (or `null` if the source doesn't exist). The forked session is independent (writes to it don't touch the
* source). Backs CC `/fork` (continue with the parent's full context) AND the inheriting-context subagent fork
* (run a child on the fork so it inherits the parent context + shares the prompt-cache prefix). **Optional**:
* a store implements it only if it can replay history. `TtlSessionStore` DOES — it delegates to its
* {@link SessionRepo} (so {@link hasSessionFork} is true) — BUT the fork is only as durable as that repo:
* an in-memory repo forks IN-PROCESS yet loses the copy on restart, while a durable repo (file/pg) makes the
* fork survive restart/replica. **Capability presence ≠ durability** — a cross-replica consumer (design/114
* warm-resume) MUST wire a durable repo; core cannot verify durability, only fail-loud on a missing source at
* fork time (returns `null`). The fork is a new row whose owner cell is recorded in the write that creates it — a fork
* COPIES the source's history, so the copy is never weaker than the original: with no `owner` argument, or an
* EXPLICIT `null`, the fork records the SOURCE row's owner ("anonymous" on a copy of an OWNED source would admit
* every principal to that history — a downgrade this face exists to prevent); an owner string (a principal name — a blank
* string is refused, with no row left behind) records that owner.
* MUST copy the COMMITTED leaf (an in-flight uncommitted turn of an active source is not included — a fork is a
* snapshot at the fork point). The fork point is `settledForkOptions`' answer: a turn whose tool batch is still open — in flight,
* or left open by a durable park under the records its leg wrote at its close — is cut away with everything after it.
*
* `opts.placement` (subagent transcript persistence): fork INTO the placement partition — the fork's creating write lays the
* tuple down exactly as a placed `acquire` does (first-write immutable, `placedAt` stamped by the store), so the forked row owes
* every placement obligation above and the row's placement reads back that tuple. The row's owner cell is the `owner`
* argument's, by the rule above (a background fork records its delegation tree's owner, which is its source row's), as a placed
* acquire's is its own `owner`. Trusted-internals channel only, as for `acquire`. On a store that declares {@link placements}, a fork whose
* row comes back without the declared tuple (a repo that dropped it) is refused `SessionError("placement_refused")` and the row
* is removed — the same mirror judgement a placed `acquire` takes.
*
* `opts.id`: the id the fork lands on (absent ⇒ a fresh one). A fork lays down a NEW row, so an id under which a row already stands is
* refused `SessionError("conflict")` and nothing is written — that row keeps every cell and its log; the source's own id stays
* `invalid_fork_target`. Replacing a row is two explicit steps: delete it (expecting the row meant), then fork. A value that is not a
* non-empty string is refused `config.invalid_argument` before anything is read.
*/
fork?(sourceId: string, owner?: string | null, opts?: {
placement?: SessionPlacement;
id?: string;
}): Promise<string | null>;
/**
* The row's {@link SessionHead} for `sessionId` — owner, occupant and active leaf — in ONE read of the row, never assembled from
* separate reads (a delete and re-create of the id between two reads would pair one generation's owner with the next one's
* occupant). `undefined` = no row for this id. A rejection is a read fault, not an answer.
*
* The BY-ID read, for a reader that did not acquire the session (hosts, a deployment's authorizer). A store that has it hands out,
* from `acquire`, only a session of the occupant it names — a cached view of an occupant the row no longer holds (the row deleted,
* or deleted and created again, through another writer — on the File lane a writer in another process too) is not served — so its `incarnation` and the acquired session's metadata agree (the kit pins both); a run's own memory seat reads the session it ACQUIRED instead, never this lookup. The owner is a cell of the row: `null` = anonymous (admitted to every principal) — a row created
* with no owner (the creating write names none), or a row written before the cell existed; a principal name = owned (a cell holding a blank string
* names nobody and is a read fault, never an owner). Every row the engine creates for a leg it delegates — placed or not, a workflow's
* agent, a synchronous or background child, an observer — carries the owner of its delegation tree: the creating acquire names it
* (`opts.owner`, read by the engine from the tree root's row as the root run read it, and carried unchanged down the tree; a fork
* names it through its owner argument), and no store derives an owner of its own; the child's owner VALUE is its root's (`null` when
* the root is anonymous). A row created before its engine named owners records what its creating write recorded (`null` on the bundled
* stores — placed rows before 7.62.0, every other delegated row before 7.69.0) until a leg of a tree with an owner first runs on it
* (reading it records nothing): the engine then records that owner through {@link recordOwner}, and from then on every other
* principal's tree is refused it.
* **Optional**: absent ⇒ no by-id read, and a deployment's authorizer, which needs this and {@link register} together, takes its
* fail-closed arm.
*/
headOf?(sessionId: string): Promise<SessionHead | undefined>;
/**
* The row as it stands, for a reader that does not run on it: its metadata, its head and its whole log oldest-first, all of one row
* generation ({@link SessionRowRead}). Four rules, the same on every store:
* · **It writes nothing** — no row, entry, owner cell, file or cached view is created or changed by it, an id with no row included.
* · **It sweeps nothing** — no session, the one read or any other, is evicted from a cache or deleted because of this read.
* · **It is no activity** — no idle clock moves (the read session stays exactly as near its idle eviction as it was), nor the time
* {@link list} orders by.
* · **No row and a failed read are two answers** — an id with no row RESOLVES `undefined`: a definite "there is no such row". A row
* that is there and cannot be read REJECTS with a coded error, never `undefined`: on the bundled stores a `SessionError` with code
* `corrupt_session` for a row whose header the store cannot read, and a backend's own coded fault for a read that did not complete.
* **Optional**: absent ⇒ an entry that reads a session without running on it (`Runner.previewInstructions`) refuses a named session
* (`config.invalid_session_store`) rather than open it through {@link acquire}, which sweeps and records activity.
*/
readRow?(sessionId: string): Promise<SessionRowRead | undefined>;
/**
* The owner write of the ownership pair ({@link headOf} + this). On an id with NO row it creates the row — an ordinary row, no
* placement — recording `owner` in the creating write, first-write-wins and atomic: of two concurrent first registers, both
* callers' re-reads see the same winner (durable implementations need a real uniqueness guarantee, not read-then-write). On an id
* whose row EXISTS it does nothing, whatever it carries — an owned row, an anonymous row, a row `acquire` created (which
* records the owner it named, `null` when it named none), or a placed row (likewise) stays as it is: a row's owner is recorded by the write that
* creates it and `register` never changes it; the one write that records an owner on an existing row is {@link recordOwner}, and only on a
* row that records none. A FIRST write whose `owner` is neither a principal
* name (`PRINCIPAL_NAME_SPELLING`) nor `null` is refused loudly and leaves no row; a later call stays a silent no-op
* whatever it carries. Deliberately makes NO
* authorization decision — the caller re-reads {@link headOf} and judges there. The owner lives and dies with its row.
*/
register?(sessionId: string, owner: string | null): Promise<void>;
/**
* The claim of a row that records no owner — the one write that records an owner on a row that exists. In ONE step, against every writer
* of the row: only while the row records no owner (`null`) and is the row `expect` names ({@link SessionRowExpectation}: `row.owner`
* `null` and the occupant cell its caller read, judged by `sessionRowMatches`) it records `owner`; nothing else of the row changes (its
* occupant, placement, lineage and log stay), and a session this store handed out for the row before the write keeps writing to it and
* answers the recorded owner. Answers the row's head after that step: the head the write committed; on a row that already records a name,
* the row as read, nothing written (a claim never changes an owner, and never makes a row anonymous again). The row `expect` does not name
* (another occupant, another owner than `null`) is refused `SessionError("conflict")`, nothing written; no row ⇒ `undefined`; an `owner`
* that is not a principal name (`PRINCIPAL_NAME_SPELLING`) is refused `config.invalid_argument` before the row is read. Of two concurrent
* claims of one row, exactly one records its owner and both answers name it. Makes NO authorization decision: the engine reads the
* answered head and judges there (a leg of a tree with an owner claims a row that records none the first time it runs on it; an entry
* that only opens or reads such a row records nothing). **Optional**: absent ⇒ a leg of a tree with an owner is refused every row that
* records none (the refusal names this member); reading such a row, and an anonymous tree, are not affected. `TtlSessionStore` offers it over a repo that has `SessionRepo.recordOwner`.
*/
recordOwner?(sessionId: string, owner: string, expect: SessionRowExpectation): Promise<SessionHead | undefined>;
/**
* The storage half of moving a session's log between backends (session-sync): read it out ({@link SessionLogTransfer.listEntryIds},
* {@link SessionLogTransfer.exportStream}) and replace it whole through a staging the readers never see
* ({@link SessionLogTransfer.beginReplace}). One write law for every store: a commit onto an existing row keeps that row's occupant and
* owner and lands only on a row that is already the committer's (compared null-safe; another owner's row is refused `conflict`, a placed
* row `placement_refused`, nothing written); onto an absent id it creates the row recording the committer and a fresh occupant; every
* entry passes the engine's import gate ({@link StreamingImportValidator}); and the owner check, the relation the committer judges, the
* write and the head the commit answers are one step — against every writer of the row, not only this instance's: the commit reads the
* row once (owner, log and head of one generation), `decide` weighs that log, and the write lands only while the row is still that
* generation with that log (a write through another instance or the repo since then refuses the commit `conflict`, nothing written);
* the head answered is the one the write committed (on `"keep"`, the one read: a `"keep"` writes nothing, so it answers the row as the
* commit read it — an id deleted and created again while `decide` weighed it is another row, and an expectation naming the answered
* head misses that row). A commit naming the row it expects ({@link SessionLogCommit.expect}) lands only on
* that row, judged on the same read after the owner: a miss refuses it `conflict` before `decide` is asked. A refusal, or a throw from
* `decide`, writes nothing.
* **Optional**: absent = this store does not take part in a cross-backend move.
*/
readonly logTransfer?: SessionLogTransfer;
/**
* Delete ONE session row and its log — the row primitive, and the last leg of the session-deletion cascade
* ({@link import("./retention.js").RETENTION_CASCADE}). It reads no reference and touches no other store: the session's checkpoints,
* offloaded tool results, session rules, file history and the rest outlive it until the cascade's executor removes them, so a host that
* offers "delete a session" runs the cascade, not this call alone. The guard names the row it is for in one of two forms:
* `{ owner }` — the row whose owner equals `guard.owner`, whichever occupant it holds (null-safe:
* `null` deletes only an anonymous row; the owner is read as a stored name is — `recordedPrincipalNameOf` — so the owner of a row an
* earlier release wrote under a name the rule now refuses as ill-formed deletes it by that same string) — or the occupant a read of the
* row answered, `{ row: { owner, incarnation } }` (#4746: the expectation the out-of-run verbs take, read by the same reader —
* `row: null`, a `log` mark and a key besides `row` are refused — and judged by `sessionRowMatches` on the head in the step that removes
* the row: a row deleted and created again under the id since that read, by the same owner too, is another occupant and is not deleted).
* A guard that is neither form, or both, is refused (`TypeError`) before anything is read. A placed row is not deleted here (its deletion is `release`'s, through the joint reap). `true`
* = this call deleted the row; `false` = there was no row, the guard did not hold, or the row is placed — nothing was deleted, so a
* repeat is harmless. The id answers nothing afterwards, and a later create under it is a new occupant. A store wired with
* {@link SessionStoreHooks.beforeSessionDelete} runs it first and deletes nothing when it rejects (the call rejects with it).
* The row is judged on its head (owner, occupant, placement), never on its log: a row whose head reads is taken by its owner's delete
* whatever its log holds — a log the open refuses `corrupt_session` included — and a head that cannot be read rejects, nothing deleted.
* **Optional**: absent = this store has no owner-guarded delete (`TtlSessionStore` offers it only over a repo with a head read, a row
* read and a header-only placement read, `SessionRepo.placementOf`).
*/
delete?(sessionId: string, guard: {
readonly owner: string | null;
} | {
readonly row: NonNullable<SessionRowExpectation["row"]>;
}): Promise<boolean>;
/**
* Delete a session whose head cannot be read — a deployment operator's act, never an owner's request: a row that cannot be read names
* no owner, so no owner-guarded door (`delete`, `release`, an import) ever takes it. The row's head is read again in the step that
* removes it: a read refused {@link isRowUnreadable} ⇒ the row and its whole log are deleted, `true`; a readable row (owned or
* anonymous) or no row ⇒ nothing deleted, `false`; any other fault of that read (a `storage` fault, an errno) rejects with it and
* deletes nothing. The row's placement is not read: a placed row is deleted alike, and a child still writing into it has its next
* write refused `log_closed` — the deletion does not wait for children. A store wired with {@link SessionStoreHooks.beforeSessionDelete}
* runs it first, only for a row it read as unreadable, and deletes nothing when it rejects (the call rejects with it). An id that is not
* a non-empty string is refused (`config.invalid_argument`) before anything is read. Nothing automatic calls it (idle sweep, release,
* retention). It is the session row's leg of {@link import("./retention.js").RETENTION_CASCADE} for such a session (the leg's `unreadable`
* verb) and, like {@link delete}, touches no other store: an operator who deletes the session runs the table's legs with it, not this
* call alone. **Optional**: absent = this store cannot remove an unreadable row (its repo cannot, or its rows cannot be unreadable).
*/
deleteUnreadable?(sessionId: string): Promise<boolean>;
/** Number of live/cached sessions (best-effort). */
readonly size: number;
/** Release resources (timers, connections). Best-effort; must not throw. */
dispose(): void | Promise<void>;
}
/** What {@link SessionLogTransfer.exportStream} reads: `afterSeq` resumes after that 0-based position of the oldest-first log (absent
* = from the first entry; an integer ≥ -1); `batchSize` is how many entries a store reads per page (an integer ≥ 1; absent = the store's
* own page) — a store holding the log whole reads it once whatever the page, the stream is the same. A bad value is refused. */
export interface SessionLogExportOptions {
afterSeq?: number;
batchSize?: number;
}
/** The read and replace halves of {@link SessionStore.logTransfer}. */
export interface SessionLogTransfer {
/** The ids of the session's whole log, oldest-first (no compaction floor applied); `null` = no such session. */
listEntryIds(sessionId: string): Promise<readonly string[] | null>;
/** The session's whole log, oldest-first, as a stream; `null` = no such session (see {@link SessionLogExportOptions}). */
exportStream(sessionId: string, opts?: SessionLogExportOptions): Promise<AsyncIterable<SessionTreeEntry> | null>;
/** Open a staging for a replacement of `sessionId`'s log: entries appended to it are invisible to every reader until its commit.
* `preserveActorAssertions` is the import gate's trusted-source declaration (see {@link StreamingImportValidator}), read here
* because the gate reads each batch as it is appended. */
beginReplace(sessionId: string, opts?: {
preserveActorAssertions?: boolean;
}): SessionLogReplace;
}
/** What a commit's `decide` sees, inside the commit's one step: the destination's entry ids as they stand now (`null` = no row) and the
* staged ids, and a read of either side's entries by id. */
export interface SessionLogCommitView {
readonly current: readonly string[] | null;
readonly staged: readonly string[];
read(side: "current" | "staged", ids: readonly string[]): Promise<SessionTreeEntry[]>;
}
/** A commit of a staged replacement. */
export interface SessionLogCommit {
/** The committing principal (`null` = anonymous) — the authenticated importer, never a value read from the staged log. */
owner: string | null;
/** The committer's judgement of the relation between the two logs, inside the commit's one step: `"replace"` writes the staged log,
* `"keep"` leaves the destination's log as it is (an identical push); a throw writes nothing and the commit rejects with it. */
decide(view: SessionLogCommitView): "replace" | "keep" | Promise<"replace" | "keep">;
/**
* The row the committer judged before it staged, as every conditional write of a session row names it ({@link SessionRowExpectation}):
* `{ row: head }` with the head its gate read ({@link SessionStore.headOf}, passed as it came — a row with no occupant token has no
* `incarnation` there, and none is expected), `{ row: null }` when that read found no row, and `log` when the gate judged the log too.
* Judged on the commit's one read, after the owner and before `decide`, by the one judge of a conditional row write (`sessionRowMatches`):
* a miss — the row deleted, created again under the id, created where none was, another owner's, or (with `log`) written since —
* refuses the commit `SessionError("conflict")` with nothing written and `decide` not asked; judge the row again. Absent = no
* expectation: the commit lands on whichever row the id holds now, as before this member existed. A value not of the shape — read by
* the root's strict reading of a caller's `expect` (`readRowExpectationMember`, the out-of-run verbs' own; the judge called directly
* still reads members): a plain data object at each level (the bundled stores' heads are), own keys of the type only (a head's
* `leafId` is taken), a log mark some log has, and `row: null` with no log but the empty one's mark — is refused
* `config.invalid_argument`. A store of its own reads the member through that function, and hands the judge the row's occupant cell
* decoded (`readIncarnationCell`: a cell holding no token — a SQL `NULL` — is absent, as its head says, with no `incarnation` key).
*/
expect?: SessionRowExpectation;
}
/** One staging opened by {@link SessionLogTransfer.beginReplace}. After its commit settles (either way) or its abort, it takes nothing more. */
export interface SessionLogReplace {
/** An opaque name of this staging. */
readonly stagingId: string;
/** Stage a batch, after the batches before it; each entry passes the import gate here, and a refused batch refuses the staging. */
append(entries: readonly SessionTreeEntry[]): Promise<void>;
/** The commit point: the write law of {@link SessionStore.logTransfer} (the expected row included, when named), then `decide`,
* then the write and the head the row holds after it, in one step. Before it settles, no reader sees the staged log; a refusal, or a
* throw from `decide`, writes nothing; a row written by anyone else since the commit read it refuses it `conflict` (read the row again
* and stage again). The first commit call ends the staging, whatever its outcome. */
commit(input: SessionLogCommit): Promise<{
outcome: "replaced" | "kept";
head: SessionHead;
}>;
/** Drop the staging; nothing is written. Idempotent. */
abort(): Promise<void>;
}
/**
* A deployment's hooks on a session store's row deletions — the cleanup of the deployment's own records keyed by session id (a title, a
* pin, an instruction baseline). `beforeSessionDelete` runs, and is awaited, before every deletion of a row the store makes (an owner's
* {@link SessionStore.delete}, a placed `release`, an `evict: "delete"` release or idle sweep); when it rejects the row is not deleted and
* the deletion fails with it — an owner's `delete` or a placed `release` called again runs both again, while an ordinary release has
* dropped its view and, like any failed ordinary release, has nothing more to delete. The deletion after the hook lands only on the row
* the store judged (the repo judges it in the step that removes the row — another writer may have deleted the row, created another under
* the id, or written it while the hook ran); a row that is no longer the one judged is not deleted. The row is still there while the hook
* runs, so no create under the same id can meet the deployment's records for the occupant being deleted. Called with the id only; it
* must be idempotent.
*
* It is also where a deployment erases a session the store deletes: the store's deletions delete the row and its log only, so the
* deployment runs `RETENTION_CASCADE`'s legs before the session row's here — the row still stands, so each leg reads the occupant being
* deleted (its owner, its history address) — and rejects to keep the row while a live reference stands; the row's own leg is the deletion
* that follows. A cascade run after the row is gone cannot name that occupant: the checkpoint and file-history legs read its head. The hook
* does not call the store's deletion of the same id itself: that waits for the deletion in flight, which waits for the hook.
*/
export interface SessionStoreHooks {
beforeSessionDelete?(sessionId: string): void | Promise<void>;
}
/** Structural detection: does this store expose the optional {@link SessionStore.fork}? Mounts the fork
* capability only when true (INERT otherwise — mirrors `hasScheduler`/`hasBackgroundShell`). */
export declare function hasSessionFork(store: SessionStore): store is SessionStore & {
fork: NonNullable<SessionStore["fork"]>;
};
/** Does this store declare the subagent placement partition ({@link SessionStore.placements})? The opt-in a placing write needs: the
* store that CREATES a row is handed a placement only when it declares, so no store holds tuples it never opted into. */
export declare function declaresSubagentPlacement(store: Pick<SessionStore, "placements">): boolean;
/**
* F3 bounded-wake recipe, packaged. Given the **path-ordered** entries of a branch
* (root→leaf, e.g. `await session.getBranch(leafId)` or a durable store's leaf-walk),
* returns the smallest self-contained tail a stateless runner needs to resume:
*
* - `floorEntryId` = the **latest** compaction's `firstKeptEntryId` (null if never compacted),
* - `tail` = entries from that floor to the leaf — i.e. the surviving compaction summary
* plus every message kept after it. Everything before the floor is already folded into
* that summary, so it can stay cold in durable storage.
*
* Hand the result straight to a floored storage:
* `new InMemorySessionStorage({ entries: tail, floorEntryId })` (or your durable equivalent).
* `buildContext()` on that is identical to waking from the full tree — see `session-floor.test.ts`.
*
* Pure and allocation-light: it scans for the last compaction and slices. If the tree was never
* compacted (or the floor isn't on this path — shouldn't happen for a real branch) it returns the
* full input unchanged with `floorEntryId: null`, so callers can always use the result verbatim.
*/
export declare function boundedTail(pathEntries: readonly SessionTreeEntry[]): {
tail: SessionTreeEntry[];
floorEntryId: string | null;
};
/**
* The ONE "has this session seen conversation?" predicate — the freshness question is asked three
* times in one prepare (project-memory phase, design/148 center adoption, the epoch-pin
* discriminator), and an entry-COUNT proxy at ANY of them re-creates the same lie: a host may write
* session_info / model_change / … rows before the first turn (naming a new chat, recording a model
* pick), and none of that is evidence of a prior session (the count proxy
* survived at the adoption arm after the pin arm was fixed, silently costing a pre-named session
* its published center prompt for life). Conversation content — and only that — is the evidence.
*/
export declare function hasConversationContent(branch: ReadonlyArray<{
type: string;
}>): boolean;