UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

420 lines (419 loc) • 35.8 kB
import { type ForkPoint, type Session, type SessionHead, type SessionPlacementRecord, type SessionRepo, type SessionRowExpectation, type SessionRowRead } from "../internal/harness.js"; import { type AcquiredSession, type PlacedSessionRow, type SessionListQuery, type SessionLogTransfer, type SessionPlacement, type SessionStore, type SessionStoreHooks, type SessionStoreSummary } from "./session.js"; import type { StoreDurability } from "./checkpoint-store.js"; import { type StoreHolderFence } from "./checkpoint-generation.js"; import { type RetentionDeclaration } from "./retention.js"; /** Test seam: the notice is said once per process, so a test asserting it must be able to clear that. Never called by production code. */ export declare function __resetSessionDeleteWithheldNotice(): void; import { SESSION_DEFAULT_TTL_DAYS } from "../config/defaults.js"; export { SESSION_DEFAULT_TTL_DAYS }; /** What idle-eviction and `release` do to the underlying repo. */ export type EvictPolicy = "delete" | "forget"; export interface TtlSessionStoreOptions { /** Idle TTL before a cached session is evicted. Default 7 days. */ defaultTtlDays?: number; /** Optional background sweep interval: a whole number of milliseconds from 1 to 2147483647 (the longest a timer takes; any other * value is refused, `config.invalid_argument`). Omit it for no background sweep (sweeps opportunistically on acquire). */ sweepIntervalMs?: number; /** * Backing session repo. Default `InMemorySessionRepo` (process-only, lost on restart). Supply a * **durable** repo (e.g. a TiDB-backed `SessionRepo`, or the vendored file repo) to persist * sessions: `acquire` then **resumes** an existing session via `repo.open`, so any stateless * runner instance — even after a restart or on another replica — continues the same conversation. */ repo?: SessionRepo; /** * The deployment's grant judge (`HolderJudge`) for the store's OWN default repo: the store builds its `InMemorySessionRepo` with it, * so every session write carrying a holder is judged and the store declares `fence = { holder: "writes" }` — the defaults that come * with the default repo (`evict: "delete"`, `durability: "process-local"`) stay. A store given a `repo` takes the judge from that repo * (`new InMemorySessionRepo({ holderIsCurrent })`, `FileSessionRepo(root, { holderIsCurrent })`): both together are refused * (`config.invalid_argument`) — the judge has one place. A value that is not a function is refused too. */ holderIsCurrent?: import("./checkpoint-generation.js").HolderJudge; /** * What idle-eviction and `release` do to the repo: * - `"delete"` — remove the session from the repo too (correct for the throwaway in-memory repo): its row and log only, the session * row's leg of `RETENTION_CASCADE` — the session's rows in other stores stay unless {@link hooks}' `beforeSessionDelete` erases them, * but for the durable row of a background agent of its tree that this process is still writing: that row's writer removes it at its * next write (`durableAgentWriteLane`). * - `"forget"` — only drop the in-memory cache; the **durable** backend keeps the history so it can * be resumed later (the backend runs its own retention/GC). * * Defaults to `"delete"` for the built-in in-memory repo and `"forget"` when a custom `repo` is * supplied — so a durable store never silently deletes history on an idle timer. */ evict?: EvictPolicy; /** * design/173 §2.3 — the store's {@link StoreDurability} declaration. This cache layer cannot * inspect whether the injected {@link repo} persists across processes, so the DEPLOYMENT that * wired the repo states the fact (e.g. `FileStorageBackend` passes `"durable"`). Defaults: * without a custom `repo` the truth is knowable — `"process-local"` is declared; with a custom * `repo` and no explicit value the store declares NOTHING, which the wiring manifest reads * fail-closed as process-local (under-promise, never over-promise). */ durability?: StoreDurability; /** * Subagent transcript persistence — the store's per-placement durability declaration (see * {@link SessionStore.placements}). Same declaration rule as {@link durability}: this cache layer * cannot inspect whether the injected repo persists placed sessions, so the DEPLOYMENT that wired * the repo states the fact (`FileStorageBackend` passes `{subagent:{durability:"durable"}}`). * Declaring it also arms the cache-layer placement obligations (list exclusion, claim refusal, * release-is-deletion, sweep-never-deletes) — they key on the repo-persisted tuple, which a repo * that ignores `placement` never mints, so declaring over such a repo is the deployment lying to * itself (declaration-制, wiring-manifest posture). */ placements?: { subagent?: { durability: StoreDurability; }; }; /** * The store's managed-retention declaration ({@link RetentionDeclaration}): `"managed"` says this store's rows are deleted * on schedule by the deployment. Same declaration rule as {@link durability}: this cache layer runs no sweep and cannot see * one, so the party that runs the sweep over the repo's rows states it. Default `"none"`. A word other than the two is refused * at construction (`config.retention_capability`). */ retention?: RetentionDeclaration; /** The deployment's hooks on this store's row deletions ({@link SessionStoreHooks}): `beforeSessionDelete` runs, awaited, before * every row this store deletes — an owner's `delete`, a placed `release`, an `evict: "delete"` release or idle sweep. A hook that is * not a function, or a member this store does not run, is refused at construction. */ hooks?: SessionStoreHooks; } /** * The one placement admission of a session store's `acquire` — every backend that declares the placement partition * judges each resolved session through it (this module's {@link TtlSessionStore} on its four resolution paths: cache * hit, pending-promise inherit, open, idempotent re-create), so no backend writes the two directions a second time. * * Placement obligation 6 (claim closure): an EXISTING placed session refuses the claim-form * acquire — no `requireExisting` (the read/revive form, obligation 5) and no creation placement * (the trusted-internals form; the creating call and its dedup/retry re-acquires stay legal, and * placement immutability means the argument can never REWRITE anything — the persisted tuple wins). * * …and the MIRROR direction (the pre-claim SQUAT race): the child session id is * published on the spawn frame BEFORE the child's prepare creates the session, so a concurrent * claim-form acquire could win first creation and hand the trusted placement caller an ORDINARY * session — host-listable, never really-deleted, the declared full tier falsified in silence. On * a store that DECLARES the partition (`capability.subagentPlacement`; an ignoring store legally drops * placements), an acquire carrying a placement must therefore come back with a PERSISTED tuple whose * join identity matches the declaration — a missing or foreign tuple refuses loudly. A placed `fork` is judged by the * same direction on the row it created (no squat can win a fork's fresh id, but a repo that drops the tuple can). * * @param persisted the tuple the backend holds for `sessionId` as resolved (`undefined`: an unplaced session). * @param request the `acquire` options the caller passed (a placed `fork`: its placement). * @param capability whether the store declares the subagent placement partition. `subagentPlacement` is read once, * and only when the mirror direction is judged (a placement request that is not the read form, after `request`'s * members are read), so a store may pass a getter over its live declaration. * @throws SessionError `placement_refused` on either direction; returns nothing when admitted. */ export declare function admitSessionPlacement(sessionId: string, persisted: SessionPlacementRecord | undefined, request: { requireExisting?: boolean; placement?: SessionPlacement; }, capability: { subagentPlacement: boolean; }): void; /** The hooks {@link TtlSessionStore} runs — a member of `hooks` outside it is refused by name. */ export declare const STORE_HOOK_KEYS: import("./own-property-receipt.js").OptionKeys<SessionStoreHooks>; /** * TTL-cached {@link SessionStore} over a pluggable {@link SessionRepo}. * * Sessions are cached in process memory and evicted after `defaultTtlDays` of inactivity. With the * default in-memory repo they live only in this process (lost on restart). Supply a **durable** repo * and the same caching/concurrency logic becomes a "session center": on `acquire`, a session not in * the live cache is **resumed from the repo** (`repo.open`) rather than recreated — so a stateless * runner resumes a conversation after a restart or across replicas. The optimistic-lock seam * (`SessionWriteOptions.expectedLeafId` → `SessionError("conflict")`) keeps two replicas writing the * same session safe; the Runner reconciles a lost CAS and retries. * * See `design/10-会话持久化与会话中心.md` for the durable-backend (TiDB) contract. */ export declare class TtlSessionStore implements SessionStore { /** Managed-retention declaration (retention.ts): whether this store's rows are deleted on schedule by the deployment — given * by the party that runs the sweep ({@link TtlSessionStoreOptions.retention}), `"none"` when none is given. This layer deletes * nothing on schedule itself: with a custom repo the default evict policy is `forget` (cache eviction only, the durable rows * live on), so a locked retention policy refuses this store at the default. (The `SessionStore` interface * itself is declaration-agnostic; the retention face is the structural `RetentionDeclaring` shape.) */ readonly retention: RetentionDeclaration; /** design/173 §2.3 — see {@link TtlSessionStoreOptions.durability} for the declaration rules. */ readonly durability?: StoreDurability; /** Subagent transcript persistence — see {@link TtlSessionStoreOptions.placements}. */ readonly placements?: { subagent?: { durability: StoreDurability; }; }; /** The grant-holder declaration ({@link SessionStore.fence}): the repo's own ({@link SessionRepo.fence}), mirrored as the repo answers * it when this store is built, as {@link headOf} is — the writes are the repo's storages', so only the repo can say they judge. * Absent when the repo declares none. */ readonly fence?: StoreHolderFence; /** The repo's transcript directory, relayed as the repo answers it ({@link SessionStore.transcriptDirectory}); absent when it has none. */ readonly transcriptDirectory?: string; /** Placed-partition enumeration, present only when the backing repo can enumerate placements * (see {@link SessionStore.listPlaced} — absence means the partition-GC leg is unavailable). */ readonly listPlaced?: (kind: "subagent", opts?: { olderThanMs?: number; scope?: string; }) => Promise<PlacedSessionRow[]>; /** The by-id head read ({@link SessionStore.headOf}): the repo's own, verbatim — the row is the repo's, never this cache's, and a read * racing a delete answers either generation (it never waits on one). Present only when the backing repo answers it (absence means no * by-id head read, and so no ownership pair for an authorizer). */ readonly headOf?: (sessionId: string) => Promise<SessionHead | undefined>; /** The repo's head read as this store's own decisions read the row through it (the cache check, the existence check), held * privately so the store's reading of its rows is the repo's whatever a host does with the face. */ private readonly repoHead?; /** The row read ({@link SessionStore.readRow}): the repo's own, verbatim — no sweep, no activity, nothing cached. Present only when the * repo has a head read and a row read. */ readonly readRow?: (sessionId: string) => Promise<SessionRowRead | undefined>; /** The storage half of a cross-backend move ({@link SessionStore.logTransfer}), over the repo's row read and its conditional import: * present only when the repo has both and a head read. A staging lives in this process; a commit holds the id as a release does, and * the import it ends with is conditional on the row the commit read. */ readonly logTransfer?: SessionLogTransfer; /** The owner-guarded delete ({@link SessionStore.delete}): present only when the repo has a head read (the owner it guards on), the * row read (so its removal is conditional on the row it judged) and a header-only placement read ({@link SessionRepo.placementOf}: a * deletion is judged on the head, never on the log). A repo with the first two and not the third is said once * (`config.session_delete_withheld`). */ readonly delete?: (sessionId: string, guard: { readonly owner: string | null; } | { readonly row: NonNullable<SessionRowExpectation["row"]>; }) => Promise<boolean>; /** The operator's removal of a row whose head cannot be read ({@link SessionStore.deleteUnreadable}): present only when the repo has a * head read and its own unreadable-row removal ({@link SessionRepo.deleteUnreadable}), which re-reads the head in the step that removes. */ readonly deleteUnreadable?: (sessionId: string) => Promise<boolean>; /** The claim of a row that records no owner ({@link SessionStore.recordOwner}): present only when the repo has a head read and its own * conditional owner write ({@link SessionRepo.recordOwner}), which judges and writes the row in one step; this store holds the id as a * register does (a release in flight settles first). */ readonly recordOwner?: (sessionId: string, owner: string, expect: SessionRowExpectation) => Promise<SessionHead | undefined>; /** Whether the repo judges the expectation of the writes this store hands it (`SessionRepo.delete` / `importEntries` with `expect`): * a repo with a head read and the row read ({@link SessionRepo.readRow}). Over any other repo a deletion is of the id it judged. */ private readonly judgesRows; /** {@link TtlSessionStoreOptions.hooks}' deletion hook, read once at construction. */ private readonly beforeRowDelete?; private repo; /** The session cache's {@link HolderLatch}, handed the backend's when a backend built it: once that backend is disposed a write verb * that begins is refused `log_closed` and writes nothing (`acquire` reads the row first, as a read may). Its own {@link dispose} only * stops the sweep timer: the cache works on after it. */ private readonly latch; private entries; /** In-flight acquisitions keyed by id, so concurrent acquire(sameId) share one session. */ private pending; /** Subagent transcript persistence — placed ids whose durable deletion FAILED. Not a reading of placement: the row is that * (see `rowIsPlaced`). It makes a later cold `release` read the row whatever the repo or the store's declaration, and it is never * believed in the row's place: a read that faults deletes nothing. No cache entry is retained instead, because the repo may have torn down the shared session * authority before its removal failed (the File repo closes the append fd pre-rmSync): a retained entry would serve a closed log. */ private pendingPlacedDeletes; /** Releases (and idle-sweep deletes) IN FLIGHT that may delete the row: acquire and register — the two that resolve or write the row — * await the settlement, because the repo's delete tears down the shared session authority mid-flight — an acquire racing the await window could capture (or rebuild * and then lose) an authority the delete is about to close, and the caller would hold a session whose first append answers * log_closed while the file still exists. The gate is per-id and bounded by the release's own settlement (both outcomes release it). */ private releasing; /** Resolutions of an id in flight (`openOrCreate`), each marked when a hold of the id starts while it reads the row. */ private readonly resolutions; /** Sessions pinned by a design/45 checkpoint — skipped by idle sweep until unpinned (B6/§5). */ private pinned; private defaultTtlMs; private evictPolicy; private sweepTimer?; constructor(options?: TtlSessionStoreOptions); /** Get an existing session by id (resuming from the repo if needed), or create one — a created row records `opts.owner` (absent ⇒ * `null`) and `opts.placement` in its one creating write; a resolved existing row is left exactly as it is, whatever they carry. */ acquire(sessionId?: string, opts?: { requireExisting?: boolean; placement?: SessionPlacement; owner?: string | null; }): Promise<AcquiredSession>; /** The one judgement of "does this cached view still stand for this row": `shown` is the view's session metadata and `row` the row as * a read of it answered (a listed row, or the repo's head; `undefined` = no row, or no read of one). A row naming another occupant * (`compareOccupants` — the same token, or no token on either side, is one occupant) does not stand for it; neither does a row * naming a different owner — the owner is recorded once, by the write that creates the row, so another owner's row is another row * whatever it names; any other row does. With no row to judge (unknown) the answer is the repo's: over one with a head read the row * can always be read again, so the view is dropped and the id resolved from the row; over one with no head read the cached view is * the only evidence of the occupant, and it stands. */ private viewStandsFor; /** Whether a cached view is still the occupant the row holds ({@link viewStandsFor}, over the row's head read in one read), still * the log it holds — the row's leaf is the view's: a log replaced under the same occupant (a cross-backend move's commit, through * another instance or the repo) is another log — and still the row by its backend's own judgment (`SessionStorage.isViewOf`, the * one the repo joins a live authority by: a File view whose file was replaced under it, even by a byte-identical copy, is not). A * view that does not stand is dropped and the id resolved from the row. Answers the head that read gave when the view stands — the * row a deletion through the view expects (`SessionRepo.delete`'s expectation) — and `undefined` when it does not; a backend that * cannot tell rejects, and the view is kept. Over a repo with no head read there is no row to read: the judge's answer for no row * there is "stands" (`null`: no head to expect), given without reading the view. */ private standingRow; /** The placement admission ({@link admitSessionPlacement}) for this store, judged on every resolution path. The * partition declaration is a getter over this store's live field, so it is read where the admission judges the * mirror direction (after the request's own members, and only then) — never captured at construction. */ private assertPlacementAdmission; /** Resume an existing session from the repo, or create it if the backend has no such id (unless * `requireExisting`, in which case a genuinely-missing id fails loud instead — design/114 Phase3). A resolution that a hold of the id * (a commit, a delete, a release) overtook while it read the row is withdrawn and made again after the hold: the view it read may be of * a log the hold replaced, and it is never left published. */ private openOrCreate; /** One resolution of {@link openOrCreate}: open the row, or create it on a miss. */ private resolveRow; private createAndStore; /** Refresh the idle timer for a session, and record the activity on its row through the repo ({@link SessionRepo.touch}, where the repo * has it) — the time {@link list} orders by. A fault recording it rejects. */ touch(sessionId: string): Promise<void>; /** Record the most recent task run on a cached session (the `/resume` `lastRunId`); also bumps the idle * timer. Best-effort — a no-op if the session isn't cached here (the run will still be re-attachable via * its checkpoint). */ noteTaskRun(sessionId: string, taskId: string, runId?: string): void; /** * One page of the repo's sessions ({@link SessionStore.list}): the rows the repo lists — what a restart still finds, not this * cache — each projected from the row and ordered by the activity the repo RECORDS for it (its writes, and the touches this store * records through it): never by what this process saw, so a dropped cache, a restart or another replica pages the same order, and a * cursor is never overtaken by a row whose time moved back. The cached view adds only what it alone holds — the run it recorded * (`lastTaskId` / `lastTaskRunId`; after a restart, or once the view is evicted, a row lists without them) — and only while the view * stands for the listed row ({@link viewStandsFor}, the judgement `acquire` serves the cached session by). Every row is read to order the page; the repo's listing cost is its own (the File repo: one header * read per session). */ list(query?: SessionListQuery): Promise<SessionStoreSummary[]>; /** A listed row's projection: the row's own cells, and the cached view's run while the view stands for the row * ({@link viewStandsFor} — the row is read here, so a view of an occupant it names otherwise lends nothing). A row's activity is the * repo's recorded time for it, else its creation — the view's own time is never read, so a repo that records none lists by creation; * one whose times are both unreadable lists at 0 — at the end, never left out. */ private summaryOf; /** * design/110 (F3) — FORK a session: copy `sourceId`'s committed history into a NEW session and return its id * (or `null` when the source doesn't exist). Delegates to the backing repo's `fork`, so a durable repo persists the * branch; the in-memory repo holds it in-process. Registering the result in this cache makes `acquire(forkedId)` * hit immediately — the synchronous child run that `Agent(subagent_type:"fork")` launches resumes the fork without a repo round-trip. * * Adding this method is what makes {@link hasSessionFork} true for a `TtlSessionStore` wrapping ANY repo, so the * fork capability mounts (it was INERT before — the durable repo had `fork` but the store never exposed it). * * `opts.placement` forks INTO the placement partition ({@link SessionStore.fork}): the tuple rides the repo's fork verbatim, as a * placed create's does, and the cache entry carries the persisted tuple so the obligations arm at cache speed. On a store that * declares the partition the created row is judged by the placement admission's mirror direction; a refusal removes the row * first (the repo created it), so a dropped tuple leaves no ordinary copy of the source's history behind. * * `opts.id` is the id the fork lands on ({@link SessionStore.fork}; absent ⇒ a fresh one): handed to the repo's fork, which refuses an * id a row stands on `SessionError("conflict")` with nothing written. */ fork(sourceId: string, owner?: string | null, opts?: { placement?: SessionPlacement; id?: string; }): Promise<string | null>; /** Drop a session from the live set. With a durable repo (`evict: "forget"`) the history is kept. A release that rejects leaves the * session where it was: the store keeps no view of it and retries nothing on its own, and a placed row is found again by the * partition-GC leg's `listPlaced`. A row whose header cannot be read is no release's: every release of it rejects * (`corrupt_session`); it is removed by the operator's {@link deleteUnreadable}. */ release(sessionId: string): Promise<void>; /** Run a release that may delete the row while it holds the id: the gate is set before the first await, after any release already in * flight for the id, and `acquire` / `register` answer after it settles — no caller captures an authority the delete is about to tear * down (the repo closes the shared authority before its removal can fail), or writes the row mid-decision. */ /** Resolves once the hold of the id in flight when the caller arrived settles (either outcome). A hold queued behind it is the next * resolution's concern: `openOrCreate` resolves again after any hold that overtakes it. */ private settledHolds; private holdingId; /** The deciding half of {@link release}, under its gate. A delete goes through the cached view only while the row still stands for it * (`standingRow`); with no view, or a view of an occupant the row no longer holds (another writer deleted the row, or deleted and * created it again), the row decides — its head read first, then its placement read cold ({@link rowIsPlaced}) — and an unplaced row * nobody here holds is left as it is. Placement obligation 4: a placed row's release is a REAL deletion whatever the evict policy (the * joint reap deletes the agent row first and then calls this to end the transcript; a forget would strand it). A delete runs only on a * read that answered — the head read with the view still standing, or the row's own placement: a read that faults deletes nothing, and * the release rejects with it. A placed release that fails (a read or the delete) leaves the tombstone, so the retry reads the row * again — never a retained cache entry, which could serve a closed log; an unplaced view's release under `evict: "delete"` leaves * nothing, so its retry after a failed read resolves and deletes nothing. What the deletion expects of the row is what was judged: * a placed transcript's deletion is owed to its occupant, so it expects the occupant only; an unplaced view's eviction judged its log * idle, so it expects the view's occupant and the view's log as it stands after the hook ({@link idleViewExpectation}). A cold release * expects the head it read before the placement (no row read ⇒ it expects no row, and so deletes none): the deletion lands only on * that generation, and a row once replaced never comes back, so the placement read after it was of that same row. */ private releaseRow; /** What the deletion of a view judged idle (an `evict: "delete"` release or sweep) expects of the row, read after the hook: the occupant * the view stood for and the view's log as it stands then — an append through the view itself while the hook ran is still the view's * log; a write through anyone else is not, and the row is not deleted. Over a repo that does not judge rows, none (the id judged). */ private idleViewExpectation; /** Every row deletion this store makes, after its caller judged the row: the deployment's {@link TtlSessionStoreOptions.hooks} deletion * hook first, awaited — when it rejects the row is not deleted and the deletion rejects with it — then the repo's delete, conditional * on the row the caller judged (`expect`, read after the hook and judged by the repo in the step that removes the row: the hook ran in * another writer's time, which may have deleted the row, created another under the id, or written it). Answers whether it deleted: a * missed expectation (`conflict`) deletes nothing and answers `false`. With no expectation (a repo that does not judge rows) the * deletion is of the id judged. */ private deleteRow; /** The one order of every deletion this store makes: the deletion hook first, awaited — a rejection removes nothing and the deletion * rejects with it — then `remove`, which judges the row again in the repo's own step and answers whether it removed it. */ private removeAfterHook; /** * The operator's removal of an unreadable row ({@link SessionStore.deleteUnreadable}), holding the id as every deletion here does: the * head read first — only a row it reads as unreadable goes on (a readable row or no row answers `false` and the hook does not run; * another fault rejects with it) — then the hook, then the repo's removal, which reads the head again in the step that removes the row * (a row repaired or replaced while the hook ran is not removed: `false`). The placement is not read. A removed row leaves no cached * view, no pin and no tombstone of a failed placed deletion. */ private deleteUnreadableRow; /** * The owner-guarded delete ({@link SessionStore.delete}), holding the id as a release does: the row's head decides — no row, an * owner other than `guard.owner` (null-safe), or, for the occupant form, a head `sessionRowMatches` does not take for `guard.row`, * deletes nothing — and a placed row (read off the header alone) is left to `release` (the joint reap). The log is never read, so a * log whose open is refused `corrupt_session` is deleted like any other row. A deleted row leaves no cached view and no pin: the id * answers nothing afterwards, and a later create under it is a new occupant. */ private deleteOwned; /** The row's metadata as the repo holds it, its placement included; `undefined` = no row. A read fault rejects. */ private rowMetadata; /** The row's placement: the repo's placement probe where it has one, else the row's own metadata; `undefined` = no row or an unplaced * one. A read fault rejects. */ private readPlacement; /** The repo's header-only placement read ({@link SessionRepo.placementOf}), where it has one. */ private placementProbe; /** Whether an uncached id's row is worth reading for its placement: through the probe on a store that declares placements, and by * either means for an id whose placed deletion failed here. */ private rowReadMatters; /** Whether the row standing under `sessionId` is placed: the repo's placement probe where it has one, else the row's own metadata, * read where {@link rowReadMatters}. Its answer retires the tombstone. A read that FAULTS answers nothing: it rejects (the release * deletes nothing and fails with it), and the tombstone stays for the next release to read the row again. */ private rowIsPlaced; /** Drop only the cached view — the repo keeps the session regardless of `evictPolicy`, so a re-acquire * re-opens the SAME history (B-17: the reconcile retry / prepare-throw paths must never delete). Cost * on the default in-memory repo: ONE retained session object **per forgotten id** until process end * (invisible to `size`/`sweep`, which track the cache) — accumulation across many distinct forgotten * ids is the accepted trade-off vs silent history loss; deployments with churn use a durable repo, * where retention is the backend's normal job. A pinned id stays pinned (a forget must never expose a * suspended task's session to sweep eviction). */ forget(sessionId: string): void; /** Pin a session so idle sweep can't evict it while a design/45 checkpoint awaits resume (§5). */ pin(sessionId: string): void; /** Release a design/45 pin (on resume or checkpoint expiry); the session resumes normal idle eviction. */ unpin(sessionId: string): void; /** The owner write of the ownership pair (see the SessionStore contract): an id with no row gets one — an ordinary row recording * `owner` in its creating write, through the repo's create (the repo makes the creation first-write-wins); an id whose row exists is * left exactly as it is, whatever this call carries. Makes no authorization decision — the authorizer re-reads {@link headOf}. The * row is not cached here: it is resolved like any other row on the next `acquire`. */ register(sessionId: string, owner: string | null): Promise<void>; /** Whether the repo holds a row for `sessionId` — its head read where it has one (no replay of the row's history), else an open. A * fault rejects; it is not an answer. */ private hasRow; /** Evict idle-expired sessions from the cache. Deletes durable history only when `evict: "delete"`. */ sweep(now?: number): void; get size(): number; /** Stop the sweep timer. It does not close the store: the rows' holder is the repo (a host reuses this cache after its dispose); the * store refuses writes once the backend that built it is disposed ({@link latch}). */ dispose(): void; } /** * design/110 (F4) — pick the fork point so a child does NOT inherit an in-flight (uncommitted) tool call. * * The agent loop commits the assistant turn (`message_end` → `appendMessage`) BEFORE it executes that turn's tool * calls. So while the Fork tool's own `execute` runs, the source session's LEAF is the assistant message that carries * the Fork tool-call (and any sibling parallel calls) with NO tool results behind it yet. Forking the whole log would * copy that orphan call into the child, and the child's wake-time `reconcileInterruptedSession` would inject an * `[INTERRUPTED]` result for it — polluting the inherited context ("I called Fork → it was interrupted"). * * Detection: the latest assistant `message` on the leaf's chain (past the tool results behind it) has a `toolCall` block * (the message shape — there is NO `toolCalls` field; tool calls are content blocks) that no tool result behind it answers — * the loop's own reading of an open batch (`findUnansweredToolBatch`). When so, fork at the turn's PARENT (`position:"at"` * includes the parent, excludes the assistant turn) — the correct fork semantics: "inherit my context up to, but not * including, the spawn call". A settled leaf (a text-only turn, or a tool turn every call of which is answered), or an * unsettled assistant that is somehow a root (no `parentId`, fail-safe), forks the whole log (`{}`). * * The records a leg writes at its own close ({@link isLegCloseRecord}: the announced snapshot, the date anchor, the git * mirror, the member ledger) are climbed like tool results: a leg parked on a durable approval writes them after its open * batch, and they are that leg's. Any other entry that is not a message (a bookmark, a session name, …) ends the walk and * forks the whole log. * * Exported at the package root: the bundled store's `fork` and any other store's `fork` are the same question and must give the same * answer — a backend reads the source session (`SessionRepo.open`), asks this, and hands the answer to `SessionRepo.fork` with the id * and owner it mints. Forking the whole log instead copies the in-flight turn. The walk is one of the parent-chain walks, so it takes the * shared guard: a leaf on a loop of tool-result messages is refused `corrupt_session` (the sentence of `getPathToRoot`) instead of followed. */ export declare function settledForkOptions(source: Session): Promise<ForkPoint>;