UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

267 lines (266 loc) • 21.9 kB
import type { CheckpointStore } from "../../core/checkpoint-store.js"; import type { ToolResultStore } from "../../core/tool-result-store.js"; import { type EvictPolicy } from "../../core/session-store.js"; import type { SessionStore, SessionStoreHooks } from "../../core/session.js"; import { type FileCheckpointStoreOptions } from "./checkpoint-store.js"; import { type FileSessionPolicyStoreOptions } from "./session-policy-store.js"; import { type FileFileHistoryStoreOptions } from "./file-history-store.js"; import type { CorruptReadInfo } from "./corrupt-read-sink.js"; import type { FileHistoryStore } from "../../core/file-history-store.js"; import type { BackgroundAgentStore } from "../../core/background-agent-store.js"; import type { MailboxStore } from "../../core/mailbox-store.js"; import type { RosterStore } from "../../agents/roster-store.js"; import { type SessionPolicyStore } from "../../core/session-policy-store.js"; import type { WorkflowJournalStore } from "../../core/workflow-journal-store.js"; import type { UsageWindowStore } from "../../core/usage-window-store.js"; import type { EngineStorageBackend } from "../../core/engine-storage-backend.js"; import { type RetentionDeclaration } from "../../core/retention.js"; import { type HolderJudge } from "../../core/checkpoint-generation.js"; export { FileCheckpointStore, CHECKPOINT_LEDGER_EVENT_KINDS, readCheckpointLedger, type CheckpointLedgerEventKind, type CheckpointLedgerReading, type FileCheckpointStoreOptions, type ReadCheckpointLedgerOptions, } from "./checkpoint-store.js"; export { FileSessionRepo, type FileSessionRepoOptions } from "./session-store.js"; export { FileToolResultStore } from "./tool-result-store.js"; export { FileSessionPolicyStore, type FileSessionPolicyStoreOptions, type SessionPolicyCorruptReadInfo } from "./session-policy-store.js"; export { FileFileHistoryStore, type FileFileHistoryStoreOptions } from "./file-history-store.js"; export { FileWorkflowJournalStore } from "./workflow-journal-store.js"; export { MAX_JOURNAL_RESULT_BYTES, oversizeJournalResult } from "../../core/workflow-journal-store.js"; export { FileUsageWindowStore, type FileUsageWindowStoreOptions } from "./usage-window-store.js"; export { resolveDataRoot, sanitizeScope, sanitizePathComponent } from "./fs-atomic.js"; export { dataRootLocation } from "../../core/data-root.js"; export { FileStoreLockError, type FileStoreLockErrorCode } from "./fs-atomic.js"; export { readDataRootLocks, type LockReading, type LockHolder, type LockRemedy, type AnchorReading } from "./lock-reading.js"; export { FileLedgerDamagedError, type LedgerDamagedLine } from "./shared-ledger.js"; export { inspectFileLedgers, setAsideLedgerDamage, type FileLedgerHealth, type FileLedgerName, type LedgerDamageSetAside } from "./ledger-damage.js"; export { atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog } from "./fs-atomic.js"; export { setAppendLogDescriptorBudget, appendLogDescriptorStats, type AppendLogDescriptorStats } from "./descriptor-seat.js"; export { processFingerprint, isProcessLive, type ProcessFingerprint } from "./fs-atomic.js"; export { declareDataRoot, type DataRootDeclaration } from "./data-root-declaration.js"; export { ADOPTION_ERROR_CODES, AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, type AdoptionErrorCode, type AdoptionReport, type AdoptionReceipt, type AdoptionLegReport, type AffectedDeploymentConfig, type RootAdoptionFile, } from "./adoption/marker.js"; export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, type AdoptionStatus, type AdoptLocalDataRootOptions, type AdoptLocalDataRootResult, type AdoptionCarriageLeg, type AdoptionCarriageLegContext, type AdoptionConfigWitnessReceipt, } from "./adoption/adopt.js"; /** * design/80 — the file-backed {@link EngineStorageBackend} for the local (TOC) single-user binary, selected * purely by what the embedder injects into `RunnerDeps` (no engine change). Construct one over a single data * root and pass its members into the `RunnerDeps` seats of the same names (every member of the contract is * one; the class's extra member `root` is not a seat): * * ```ts * const backend = new FileStorageBackend(); // ~/.ai-agent (or $AGENT_DATA_DIR) * const runner = new Runner({ * brain, * sessionStore: backend.sessionStore, * checkpointStore: backend.checkpointStore, * toolResultStore: backend.toolResultStore, * // …and the other seats the contract names (sessionPolicyStore, fileHistoryStore, …) * }); * // …on shutdown: * await backend.dispose(); * ``` * * **Single-instance-per-data-dir (§2.4 / §7 decision 4):** the constructor takes a coarse boot `flock` on * `root/LOCK`. A second `FileStorageBackend` over the same dir FAILS FAST ("another instance owns this data * dir"); a stale lock from a dead PID is pruned. The once-only checkpoint CAS is in-process (one event * loop), so there is still no per-operation lock. What this backend's lock does NOT cover — and never did, * despite what the store docs used to say — is a store constructed DIRECTLY off the root export (or one * this backend does not construct at all, like `FileWorkflowRunStore`); those now take their own * per-directory writer fence at construction ({@link import("./fs-atomic.js").acquireStoreDirLock}), so * the single-writer premise holds however the stores were assembled. Serving many writers CONCURRENTLY * (rather than refusing the second) is the Pg/TiDB backend's job, by design. */ /** * Read-only probe handed to {@link FileStorageBackendOptions.admit} while it runs under the root's lock, before any store is built. * Calling it after `admit` returns or throws is refused (`config.invalid_argument`). */ export interface FileDataRootAdmission { /** * Whether the session row for `sessionId` currently holds a placement header on disk — the file session repo's own header read * (`FileSessionRepo.placementOf`), returning `boolean` without creating `sessions/` or replaying the log. On one resolved * `sessions/` directory both doors answer and throw alike (on a symlinked root, native OS errors keep class and `code` while * `path`/`message` follow each door's resolved spelling). Each call reads disk at that moment (not a snapshot). Failures throw * for that call only (`isRowUnreadable` answers `true` for `SessionError("corrupt_session")` — `no_header` / `bad_cell` — and * `false` for native filesystem errors and uncoded header-cursor errors) and leave the probe usable; a non-string or empty id * is refused (`config.invalid_argument`). */ readonly isPlaced: (sessionId: string) => boolean; } export interface FileStorageBackendOptions { /** Data root. Default `$AGENT_DATA_DIR ?? ~/.ai-agent`, NFC-normalized + realpath-canonicalized. */ root?: string; /** The directory a relative {@link root} is placed under — another process's working directory, for a host that opens (and so * locks) the root that process will open; absent, this process's directory. Taken as given (only the root's own segment is NFC); * an absolute `root` is not moved by it. Not a non-empty absolute path, or given with no `root` ⇒ `config.invalid_argument` before * the root is touched. */ anchor?: string; /** `TtlSessionStore` idle-eviction policy. Default `"forget"` (§7 decision 5 — durable history is never * deleted by an idle timer). `"delete"`: a release and an idle eviction delete the session's row and log — the session row's leg of * `RETENTION_CASCADE`, not the session's erasure: its rows in every other store stay (but for the durable row of a background agent * of its tree this process is still writing, which that row's writer removes at its next write). It is refused (`config.invalid_argument`, after * {@link FileStorageBackendOptions.admit} and before any store is built, as an admission's refusal is) unless {@link FileStorageBackendOptions.sessions} carries a `beforeSessionDelete` function: the deployment's * erasure, or one that does nothing to state that nothing is erased. */ evict?: EvictPolicy; /** Checkpoint store tuning (fsync cadence for `put`/`setPendingSteer`, ledger compaction threshold). The corrupt-read sink, the * session head read and the grant judge are the backend's own — the sink is {@link FileStorageBackendOptions.onCorruptRead} (one * failure grammar, one sink), the head read is its session store's, and the judge is {@link FileStorageBackendOptions.holderIsCurrent} * (one grant table, one judge) — so none is accepted here; a `holderIsCurrent` here is refused, naming where it moved. */ checkpoint?: Omit<FileCheckpointStoreOptions, "onCorruptRead" | "sessionHeadOf" | "retention" | "holderIsCurrent">; /** * The deployment's grant judge ({@link HolderJudge}) — ONE for the backend, handed to both stores that judge a holder: the session * store's repo (every append and leaf move carrying one) and the checkpoint store (`put`, `setPendingSteer`, `expire`, `resolve`). With * it both declare `fence = { holder: "writes" }`; without it neither does, and a run carrying a holder over this backend is refused at * its store seats. A deployment has one grant table, so it has one judge; the same function object is what every other store it * builds over this data root must be given too (a judge built later is wired through one trampoline function). */ holderIsCurrent?: HolderJudge; /** * The managed-retention declaration of this backend's three declaring stores — {@link FileStorageBackend.sessionStore}, * {@link FileStorageBackend.checkpointStore} and {@link FileStorageBackend.toolResultStore} — stated by the party that runs the sweep * (`"managed"`: an executor deletes their rows on schedule; default `"none"`; a third word refused, `config.retention_capability`). * The backend carries no executor of its own: a deployment that says `"managed"` runs one over these stores (the legs it calls are * `RETENTION_CASCADE`'s) and hands it to `assertRetentionCapability` as `executor`, which refuses `"managed"` beside `executor: null`. * One word for the three, because one sweep covers them; it is not a per-store choice, so the `checkpoint` record does not take it. */ retention?: RetentionDeclaration; /** * design/381 §片2 — file-history tuning, today just the boundary RETENTION bound (omitted ⇒ the * engine default; `{ retention: { keep: "unbounded" } }` hands the GC schedule to the deployment). * The corrupt-read sink is deliberately NOT accepted here: it is wired from {@link * FileStorageBackendOptions.onCorruptRead} above, because one failure grammar takes one sink. */ fileHistory?: Omit<FileFileHistoryStoreOptions, "onCorruptRead">; /** The session-rules store's options — today the names this deployment mounts its own tools under * (`mountedToolNames`, the roster its write and loosening checks judge rule names against). The corrupt-read sink is * wired from {@link FileStorageBackendOptions.onCorruptRead}, as for {@link fileHistory}. */ sessionPolicy?: Omit<FileSessionPolicyStoreOptions, "onCorruptRead">; /** * Disclosure sink for a durable read this backend's stores treat as ABSENT because the bytes were * corrupt or unreadable (never fires on plain ENOENT — real absence). * * Why it lives on the BACKEND options and not only on the individual store: the fail-open it discloses * exists for the DEFAULT deployment (a corrupt policy file yields an apparently normal, UNCONSTRAINED * task), and the default deployment constructs its stores through this one-argument constructor — the * per-store constructor parameter was unreachable from here, so the disclosure was wired exactly * nowhere for the deployments that need it most. * * Reach TODAY: {@link FileStorageBackend.sessionPolicyStore} (an absent file ⇒ no rules; a present but * unreadable / unparseable / malformed file ⇒ refused, the disclosure delivered alongside the refusal) * and {@link FileStorageBackend.sessionStore}'s repo (a session listing that silently omits what it * could not read). The aggregated roster, mailbox and usage-window stores receive the same sink (the * usage-window ledger refuses a damaged record and discloses its location here). A store that * grows the seat later is wired here in the same constructor. * * The payload is the UNION shape ({@link FileStorageCorruptReadInfo}): `path` + `reason` always, * `sessionId` when the disclosure is about one session (the session store and the session-policy face), * `principal` when the read was keyed by one. One sink for one failure grammar — a host does not register three. */ onCorruptRead?: (info: FileStorageCorruptReadInfo) => void; /** The deployment's hooks on the session store's row deletions ({@link SessionStoreHooks}) — the File lane has no foreign keys, so a * deployment's own records keyed by session id are cleaned here, before each row the session store deletes, and so is the session's * erasure where the deployment wants one: `RETENTION_CASCADE`'s legs before the session row's, run while the row still stands. Required * with `evict: "delete"` ({@link FileStorageBackendOptions.evict}). */ sessions?: SessionStoreHooks; /** * The caller's admission of this data root: the one seat between "this process holds the root's lock" and "this backend has * written under it", for a host that must refuse a root it is not fit to serve while the refusal still leaves the root as found. * 1. Called exactly once, synchronously, after the boot lock on `<root>/LOCK` is held and before any store is constructed (the * checkpoint ledger's torn-tail repair included), with the resolved canonical root ({@link FileStorageBackend.root}) and a * read-only {@link FileDataRootAdmission} probe valid only until `admit` returns or throws. * 2. A throw refuses the root: the lock is released, no store of this backend has written under the root, and the thrown value * propagates as the same object, neither wrapped nor retyped (a host branches on its own class). Any return but `undefined` * refuses the same way (`config.invalid_argument`); a returned promise's later rejection is absorbed, never left unhandled. * A refused open leaves only what taking the lock did: a root that did not exist is created, a dead owner's stale lock is gone. * Not a function ⇒ `config.invalid_argument` before the root is touched. While it runs the root is locked to every other opener. */ admit?: (root: string, admission: FileDataRootAdmission) => void; } /** * The payload of {@link FileStorageBackendOptions.onCorruptRead} — the widest shape any store this * backend constructs can deliver, so ONE sink reaches all of them (a per-store payload type would make * the backend's forwarding contravariance-illegal, which is what kept the seat single-store). * `SessionPolicyCorruptReadInfo` is assignable to it; the two-field store seats are satisfied by it. * `path` (absolute) and `reason` ride every level; `kind` tells a skipped JSONL record (`"record"`) and * that replay's count (`"replay"`) from a disclosure about a file or directory as a whole (`"file"`). */ export type FileStorageCorruptReadInfo = CorruptReadInfo & { /** Present when the disclosure is about ONE session: the session-policy face's rows, and the session store's * log of that session (its skipped records and tally, or the log skipped from a listing). Absent on a * disclosure about a directory as a whole or about a store not keyed by session. */ sessionId?: string; /** Present only when the read was keyed by a principal. */ principal?: string; }; export declare class FileStorageBackend implements EngineStorageBackend { /** The resolved, canonical data root every store of this backend lives under. */ readonly root: string; readonly sessionStore: SessionStore; readonly checkpointStore: CheckpointStore; readonly toolResultStore: ToolResultStore; /** design/99 §E6 — file-backed per-session permission rules (E6). Wire into `RunnerDeps.sessionPolicyStore` * for a local deployment that needs session rules to survive a restart. */ readonly sessionPolicyStore: SessionPolicyStore; /** SVC-2 (onboarded per) — file-backed durable workflow resume journal. Wire into * `RunnerDeps.workflowJournalStore` so `resumeFromRunId` survives a process restart on a TOC box. */ readonly workflowJournalStore: WorkflowJournalStore; /** design/164 件五 — file-backed cross-task usage-governance ledger. Wire into * `RunnerDeps.usageWindowStore` so a deployment's `usageWindows` survive a restart (an in-memory * ledger silently re-grants every allowance on every boot). */ readonly usageWindowStore: UsageWindowStore; /** design/151 S1a / subagent transcript persistence — the durable background-agent execution * ledger over the same data root. Wire into BOTH `RunnerDeps.backgroundAgentStore` AND (for a * deployment-composed Agent tool) `SubagentToolOptions.background.agentStore` — SAME instance * (the RB-37 pairing discipline). Aggregated here so the TOC full-persistence assembly is one * constructor, the same reason the session/checkpoint/tool-result trio are. */ readonly backgroundAgentStore: BackgroundAgentStore; /** design/151 §7 S3c — the durable SendMessage mailbox (tier-3 parking lane), same data root. * Wire into `RunnerDeps.mailboxStore` (single-instance pairing, same as above). */ readonly mailboxStore: MailboxStore; /** design/147 S1c — the durable name→agent roster (layer 0.5 resolution), `root/roster.json`. * Wire into `RunnerDeps.rosterStore` so name-addressing survives a restart alongside the rows. */ readonly rosterStore: RosterStore; /** * design/381 slice 2 — the durable per-edited-file rewind history over the same data root * (`root/file-history/`). Wire into `RunnerDeps.fileHistoryStore` so `/rewind` survives a restart: * WIRING IS THE OPT-IN (DV-9), so a deployment that omits it runs with rewind off, exactly as * before this member existed. It replaces the retired whole-tree `fileSnapshotStore` member — * per-edited-file means no size gate, no exclusion table, no tree traversal, and files the agent * never edited are structurally out of reach of a restore. */ readonly fileHistoryStore: FileHistoryStore; private readonly lock; /** This backend's "closed" latch ({@link import("../../core/holder-latch.js").HolderLatch}): every store it builds joins it, so after * {@link dispose} a write verb that begins on any of them is refused and touches nothing. */ private readonly latch; private readonly fileAgentRows; private readonly fileMailbox; private readonly fileCheckpoints; private readonly ttl; /** RB-437 — kept so {@link dispose} can release the shared per-session authorities (and their append * descriptors) this backend joined; `TtlSessionStore.dispose()` only clears the sweep timer. */ private readonly fileSessions; private readonly fileWorkflowJournal; constructor(options?: FileStorageBackendOptions); /** * The data-dir boot lock could not be handed back — a root that turned read-only under a running * process, an unreadable lock file. Teardown here is best-effort by contract, but best-effort must not * mean SILENT: a lock file naming a LIVE pid refuses this data root to every other process, and only * somebody saying so out loud makes that operator-actionable. (The release's own answer is the seat for * this — a discarded boolean was the backend never learning that the fence it took at construction was * never given back.) * * The wording states what a FAILED release actually establishes and no more: the removal could not be * proven. A repeat teardown replays that same verdict without re-reading the directory (the release is * one-shot), so this must not assert the file's CURRENT contents — only the consequence while it is * there, and the ways out. In particular it must NOT promise that exiting clears it: the two conditions * that produce this verdict are an UNREADABLE lock (never pruned by anyone — a stale-lock reclaim has to * read the pid it is reclaiming) and a directory the removal cannot write; neither is undone by the * owner exiting, and "it will be cleaned up automatically" is the one sentence that turns a five-second * `chmod` into an outage. */ private discloseRetainedBootLock; /** * Release file handles + the boot lock. Call on shutdown so a successor can acquire. Every store is closed, each on its own — one * that throws does not keep the next from closing — and the boot lock is released LAST, whatever the closes did: a failed close never * leaves the data root locked by a process that is done with it (a release that cannot remove the lock file says so, * `store.lock_retained`). What the closes threw then reaches the caller (the one error as it was, several as an `AggregateError`), * after the release; nothing is swallowed. From its first step every store this backend built refuses a write verb that begins * (see {@link import("../../core/holder-latch.js")}). */ dispose(): Promise<void>; }