UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

566 lines (565 loc) • 26.8 kB
import type { EngineStorageBackend } from "./engine-storage-backend.js"; import type { WorkflowRunStore } from "./workflow-run-store.js"; import type { WorkflowScriptStore } from "../orchestration/workflow-script-store.js"; import type { TaskListStore } from "../tools/task-list.js"; import type { PeerTaskStore } from "./peer-task-store.js"; /** A store's retention declaration: `"managed"` = this store's rows are deleted on schedule by the * deployment; `"none"` = nothing deletes them on schedule. Absent ⇒ read fail-closed as `"none"`. */ export type RetentionDeclaration = "managed" | "none"; /** The declaration face a storage implementation carries (structural — every store interface's * optional `retention` field conforms). The word is the deployment's statement about this store's * rows (see {@link RetentionDeclaration}), given by the party that runs the sweep when it constructs * the store: the bundled stores take it as their `retention` option and default to `"none"`. */ export interface RetentionDeclaring { readonly retention?: RetentionDeclaration; } /** * The one reader of a retention declaration word — the startup validation's and every bundled store's * constructor option's. `undefined` reads as `"none"`; anything but the two words is refused * (`config.retention_capability`), so a typo'd declaration never silently means anything. * * @param name the deployment-facing name of where the word was read (a store seat, an option). */ export declare function readRetentionDeclaration(name: string, value: unknown): RetentionDeclaration; /** * The deployment's managed-retention policy ({@link import("./types.js").RunnerDeps.retentionPolicy}). * Core consumes it ONLY for the startup capability validation (and exposes it to the deployment's * scheduler); the engine never deletes data on the task path. Administrative locking rides the * locked-config plane (key `"retentionPolicy"`), not a field here — one lock mechanism, not two. */ export interface RetentionPolicy { /** Retention horizon in days. Fail-loud validated: non-finite or negative refuses the deployment * (`config.retention_policy`); `0` is absurd-but-evaluable (delete-eligible immediately) and legal. */ maxAgeDays: number; } /** * The executor that deletes the rows of the stores declaring `retention: "managed"` — a backend's * `retention` member (contract TYPE — core ships no implementation; the server half consumes this. * The legs it calls, store by store and in order, are {@link RETENTION_CASCADE}). A deployment * that declares a store managed runs one over that store's rows. Every method is expected to be: * - **tenant-domain scoped**: work is enumerated and executed per retention domain (tenant/scope), * never as one global sweep; * - **idempotent**: a retried invocation after a crash re-converges (already-deleted rows are * counted, not errors); * - **tombstoned**: deletions leave tombstones so replicas/backups converge instead of resurrecting; * - **audited**: every destructive call is recorded append-only. The IDENTITY of that record — * which occurrence, which of the three operations, at what wall clock — belongs to the side that * WRITES the row, not to the receipt: an implementation makes it durable no later than the rows it * witnesses are gone (for a session, as its deletion record: {@link ManagedRetentionCapability.deleteExpiredSessions}; * recording after the delete would leave an unwitnessed delete on a crash), and it is * the only side that knows its own op, sweep round, and policy generation. The receipt below is * therefore the CALL's three counts, deliberately not an audit row. Where the deletion and the * sweep's context live on two sides — a SQL backend writes the deletion, the deployment holds the op — * the deployment writes the audit row through the backend's `audit` transaction hook, inside the * deleting transaction, from the receipt it is handed there; * - **bounded by its call**: each call carries its own `cutoffMs`, computed by the party that runs the * sweep (from its own horizon, e.g. a host's cleanup period in days) — an executor never reads * {@link RetentionPolicy.maxAgeDays}, which is the startup check's to judge. */ export interface ManagedRetentionCapability { /** Enumerate the retention domains (tenant/scope keys) this store holds data for. */ listRetentionDomains(): Promise<readonly string[]>; /** CAS-fenced checkpoint expiry for one domain: `pending → expired` strictly by deadline, exactly * one winner per row across replicas, AND release the associated session pins (the reap/unpin * split is the documented gap this contract closes). */ expireCheckpoints(input: { domain: string; cutoffMs: number; }): Promise<RetentionReceipt>; /** Lineage-aware transcript/session deletion: a session tree is deleted only when no live * reference still points into it — the table's legs name each one (`liveReference`) — and the * references are re-checked as below, never assumed from a prior scan; an * exempt row of {@link RETENTION_CASCADE} is never deleted with one. What one session's deletion * erases, and in which order, is {@link RETENTION_CASCADE}'s session-tree legs. * * @contract retention.session_deletion_recorded_first — one session's deletion is witnessed no later than it happens, and a * crash part-way through it is finished by a replay. Under an exclusion on the session that every write able to point into it takes too (a fork of it, a * background agent of it, a checkpoint it parks), the executor re-checks the session's live references and, with none standing, * runs the legs in {@link RETENTION_SESSION_TREE_STEPS}' order under a deletion record — its intent (the domain, the session, * the call's cutoff), its audit row and its tombstones: no row the record witnesses is gone while the record is not yet written * and synced, and the record is marked done after the session row's leg. A record not marked done keeps its session's exclusion * across a crash: the executor's next start replays it from the first step before any other write takes that exclusion, and a * replay is idempotent — a row already gone counts 0, and the record's audit row and tombstones are not written again. */ deleteExpiredSessions(input: { domain: string; cutoffMs: number; }): Promise<RetentionReceipt>; /** Delete the offloaded tool results stored with no owner record that are older than the call's * cutoff ({@link RETENTION_CASCADE}'s orphan leg). Nothing here reads a transcript: a fork's copied * log keeps its source's refs, and once the source's entries are gone (its deletion, or this sweep) * the fork keeps each result's preview, never the full output. */ deleteOrphanToolResults(input: { domain: string; cutoffMs: number; }): Promise<RetentionReceipt>; } /** * The session a session-tree leg's verb deletes for, judged at the verb's door: a non-empty string, else refused * (`config.invalid_argument`) before any row is read — a verb handed no session must not read "no session filter" (every row of * the scope) or "rows that name no session" as its selection. */ export declare function assertDeletionSessionId(sessionId: unknown, verb: string): asserts sessionId is string; /** The executor operation a cascade leg belongs to: `"checkpoints"` = `expireCheckpoints`, `"session-trees"` = * `deleteExpiredSessions`, `"orphan-tool-results"` = `deleteOrphanToolResults`. */ export type RetentionCascadeDomain = "checkpoints" | "session-trees" | "orphan-tool-results"; /** The stores {@link RETENTION_CASCADE} covers, by seat name: every store member of {@link EngineStorageBackend}, the three a * deployment constructs and hands the engine itself — the workflow-run store, the workflow script store * (`RunnerDeps.workflowScriptStore`), and the task list it mounts under the session's id (`task_list.partition_is_root_session`; * a deployment that mounts one list per root session binds this seat to that session's list) — and the deployment's peer task * store (its own table, or `InMemoryPeerTaskStore`; a deployment that keeps no peer task rows binds a store whose * `deleteBySession` answers `[]`). */ export type RetentionCascadeStores = Omit<EngineStorageBackend, "retention" | "dispose"> & { readonly workflowRunStore: WorkflowRunStore; readonly workflowScriptStore: WorkflowScriptStore; readonly taskListStore: TaskListStore; readonly peerTaskStore: PeerTaskStore; }; /** One leg of a store's row: the store method a domain's operation calls on it. */ export interface RetentionCascadeLeg<S = { readonly [verb: string]: unknown; }> { readonly domain: RetentionCascadeDomain; /** The store's method — a member of its interface (checked by the table's type). */ readonly verb: Extract<keyof S, string>; /** What the call is given and what it removes. */ readonly selects: string; /** A session-tree leg's place in one session's erasure (ascending; unique across the table). Present on a * `"session-trees"` leg, absent on the other two domains' legs, whose operations each call one leg. */ readonly step?: number; /** A fence the leg's store runs before the session's first step, where the store carries it (absent there ⇒ no fence). */ readonly fence?: Extract<keyof S, string>; /** What, on this leg's side, still points into the session and keeps its tree from being deleted by the executor. */ readonly liveReference?: string; /** What the leg leaves of the session's bytes in its store on purpose, and why — never session content (absent ⇒ it leaves none). */ readonly keeps?: string; /** The store's method that takes this leg's place for a session whose head cannot be read (`SessionStore.deleteUnreadable`'s * deletion — an operator's, where no owner guard can hold); absent ⇒ the leg runs as it is for that session too. A store that does * not carry the method refuses that session's deletion before its first destructive call ({@link RETENTION_CASCADE}). */ readonly unreadable?: Extract<keyof S, string>; } /** A row's fork column: how a fork of the session carries the rows (`"at-fork"` — copied when the fork is made; * `"first-prepare"` — carried on the fork's first prepare, keyed on `SessionMetadata.forkedFrom`; `"not-carried"` — the * fork starts without them), and why, as a sentence. */ export interface RetentionCascadeFork { readonly carry: "at-fork" | "first-prepare" | "not-carried"; readonly why: string; } /** A row of {@link RETENTION_CASCADE}: the legs that erase a store's rows, or why none do — a store seat's exemption, or a * governance record the memory engine's control plane holds (`heldBy`) — and the row's fork column. */ export type RetentionCascadeRow<S = { readonly [verb: string]: unknown; }> = { readonly legs: readonly RetentionCascadeLeg<S>[]; readonly fork: RetentionCascadeFork; } | { readonly exempt: string; readonly heldBy?: "memory-control-plane"; readonly fork: RetentionCascadeFork; }; /** * @contract retention.cascade_table — what deleting a session erases, as one table: every store seat has exactly one row (typed * complete against {@link RetentionCascadeStores}), and so has each governance document and each control-object kind the memory * engine's governance store keeps beside them (typed complete against both closed sets). A store's row is either the legs that erase its rows or an exemption naming why its rows are not session data; a leg names * its executor domain (every leg belongs to exactly one of the three, and each domain has a leg), its verb, what the verb selects, * for a session-tree leg its step, what on its side still points into the session (`liveReference`), what it leaves of the session's * bytes on purpose and why (`keeps` — never session content), and the verb that takes its place for a session whose head cannot be * read (`unreadable`). A governance record's row (`heldBy: "memory-control-plane"`) is always an exemption, naming the content it * is a fact about — a memory entry, a contribution, a held write, an import, a session's standing pollution mark or capture opt-out * — which outlives the session, so deleting the record with its session would make a one-way record revocable. Every row has a fork column: whether a fork of the session * carries the rows when it is made, on its first prepare, or not at all, and why. A session tree is erased child sessions first; * within one session every leg's fence runs before the first step, then the steps ascend and the session row's leg is last — a leg * that fails leaves the row, so a retry runs the cascade again from its first step and converges. A leg that finds what it erases * through another store's rows runs before that store's leg (the journals and scripts before the runs, the background agents' boxes * before their rows, the forks' file-history carry before the session's history), so a retry still finds them. A session whose head * cannot be read is deleted by the same legs, each leg that names an `unreadable` verb calling it instead — an operator's act, since * no owner guard can hold for a row that names no owner: `SessionStore.deleteUnreadable` is that session's row leg as * `SessionStore.delete` is a readable one's, and neither alone deletes more than the row and its log. Those verbs are optional store * members, so such a deletion first checks that every store whose leg names one carries it: a store without it refuses the deletion * there, before the first destructive call, naming the store and the verb — nothing is deleted, nothing is left half-deleted. The session row's own * verb, `SessionStore.delete`, is optional too (a store whose repo lacks the placement read has none), so a coordinator checks it before its first * deletion just the same: found missing at the row's own step it has already run every other leg, and no retry cures that. A workflow run started in a deleted * session goes with it, journal and script included: a later resume of that run from another session is refused * `workflow.park_truth_unreadable` with `detail.reason: "record_missing"`, the word an absent prior record already answers. The run * store is what indexes runs by session, so a deployment that wires a journal or script store without one leaves them out of reach. * A run deleted by retention goes the same way: {@link import("./workflow-run-store.js").reapWorkflowRuns} erases its journal and its * script (these two rows' `deleteRun`, in this order) before its row, so nothing keyed by a run id outlives the row it is found through. * A host's coordinator is checked against the table by {@link import("./store-contracts/session-deletion-cascade-contract.js").sessionDeletionCascadeContract}. * A row the session store deletes on its own — a release under `evict: "delete"`, an idle sweep, a placed row's release — is this table's * session-row leg alone: a deployment erases that session by running the legs before it in the store's `beforeSessionDelete` hook, while * the row stands; once the row is gone, the checkpoint and file-history legs, which read its head, can no longer name the deleted occupant. */ export declare const RETENTION_CASCADE: { lineage: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; challenges: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; settlements: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; "session-accounts": { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; announcements: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; holds: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; "origin-clearances": { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; pollution: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; "import-receipt": { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; quarantine: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; hold: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; "clearance-custody": { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; capture: { exempt: string; heldBy: "memory-control-plane"; fork: { carry: "not-carried"; why: string; }; }; workflowJournalStore: { legs: { domain: "session-trees"; step: number; verb: "deleteRun"; selects: string; liveReference: string; }[]; fork: { carry: "not-carried"; why: string; }; }; workflowScriptStore: { legs: { domain: "session-trees"; step: number; verb: "deleteRun"; selects: string; liveReference: string; }[]; fork: { carry: "not-carried"; why: string; }; }; workflowRunStore: { legs: { domain: "session-trees"; step: number; verb: "deleteBySession"; selects: string; liveReference: string; }[]; fork: { carry: "not-carried"; why: string; }; }; backgroundAgentStore: { legs: { domain: "session-trees"; step: number; verb: "deleteBySession"; selects: string; liveReference: string; }[]; fork: { carry: "not-carried"; why: string; }; }; rosterStore: { legs: { domain: "session-trees"; step: number; verb: "releaseAgent"; selects: string; }[]; fork: { carry: "not-carried"; why: string; }; }; checkpointStore: { legs: ({ domain: "session-trees"; step: number; verb: "deleteSessionCheckpoints"; unreadable: "deleteUnreadableSessionCheckpoints"; selects: string; liveReference: string; } | { domain: "checkpoints"; verb: "reap"; selects: string; step?: undefined; unreadable?: undefined; liveReference?: undefined; })[]; fork: { carry: "not-carried"; why: string; }; }; toolResultStore: { legs: ({ domain: "session-trees"; step: number; verb: "deleteBySession"; selects: string; } | { domain: "orphan-tool-results"; verb: "deleteUnattributable"; selects: string; step?: undefined; })[]; fork: { carry: "not-carried"; why: string; }; }; sessionPolicyStore: { legs: { domain: "session-trees"; step: number; verb: "deleteBySession"; selects: string; keeps: string; }[]; fork: { carry: "not-carried"; why: string; }; }; fileHistoryStore: { legs: ({ domain: "session-trees"; step: number; verb: "adoptScope"; selects: string; unreadable?: undefined; } | { domain: "session-trees"; step: number; verb: "deleteBySession"; unreadable: "deleteUnreadableSessionHistory"; selects: string; })[]; fork: { carry: "first-prepare"; why: string; }; }; mailboxStore: { legs: ({ domain: "session-trees"; step: number; verb: "drop"; selects: string; keeps: string; fence?: undefined; } | { domain: "session-trees"; step: number; verb: "drop"; fence: "retireRecipient"; selects: string; keeps: string; })[]; fork: { carry: "not-carried"; why: string; }; }; taskListStore: { legs: { domain: "session-trees"; step: number; verb: "drop"; selects: string; }[]; fork: { carry: "not-carried"; why: string; }; }; peerTaskStore: { legs: { domain: "session-trees"; step: number; verb: "deleteBySession"; selects: string; }[]; fork: { carry: "not-carried"; why: string; }; }; /** * @contract retention.image_bytes_live_in_the_session_store — a transcript's image bytes have one holder, the engine's session store: * they ride the session's log entries, so the session row's leg deletes them. A host that keeps a transcript of its own keeps a * reference to them (session id, entry id, block index), never a second copy. */ sessionStore: { legs: ({ domain: "session-trees"; step: number; verb: "delete"; unreadable: "deleteUnreadable"; selects: string; liveReference: string; } | { domain: "checkpoints"; verb: "unpin"; selects: string; step?: undefined; unreadable?: undefined; liveReference?: undefined; })[]; fork: { carry: "at-fork"; why: string; }; }; usageWindowStore: { exempt: string; fork: { carry: "not-carried"; why: string; }; }; }; /** One session's erasure in order — {@link RETENTION_CASCADE}'s session-tree legs, ascending by step (the one reading of the order). */ export declare const RETENTION_SESSION_TREE_STEPS: readonly (RetentionCascadeLeg & { readonly store: keyof RetentionCascadeStores; })[]; /** * The three counts one destructive retention call produced. NOT an audit row and deliberately * identity-free (see the capability's `audited` clause): a scheduler that needs to tell two * same-shaped calls apart reads its store's audit records, which the implementation writes with its * own occurrence id, operation, and timestamp, durable no later than the deletion it witnesses. Adding those here * would ask a return value to know its own call context. */ export interface RetentionReceipt { domain: string; /** Rows destroyed by THIS call (idempotent retries count already-gone rows as 0, not errors). */ deleted: number; /** Rows intentionally skipped (live lineage references, legal-hold marks — hold semantics are the * scheduler's: when a hold mark exists for a domain, the scheduler skips the domain entirely and * records the skip; this field carries the per-row remainder). */ skipped: number; /** Tombstones written for the deleted rows. */ tombstones: number; } /** The stores whose words are judged, and the policy that judges them. */ interface RetentionWords { policy: RetentionPolicy | undefined; /** Whether locked-config locks the `retentionPolicy` key (locked-config.ts `LockedKey`). */ locked: boolean; /** The wired stores to check, each with its deployment-facing name for the refusal message. * Accepts any store object (interfaces that predate the declaration conform structurally with * no declaration ⇒ read fail-closed as `"none"`); the declaration read is the one narrow. */ stores: ReadonlyArray<{ name: string; store: object | undefined; }>; } /** * The declaration half of the check — all a caller that holds no executor can judge: the policy value, every * wired store's word, and, with the retention policy LOCKED and configured, every store declaring * `retention: "managed"` — a locked policy over a store that cannot delete is refused * (`config.retention_capability`), never silently accepted. The task-prepare preflight runs it on every leg; * a deployment's own startup calls {@link assertRetentionCapability}, which runs it too. */ export declare function assertRetentionWords(input: RetentionWords): void; /** * Startup validation, the deployment's call: the declaration half ({@link assertRetentionWords}) and the * declaration held to the executor the deployment runs. `executor` is required — the * {@link ManagedRetentionCapability} the deployment runs over these stores' rows (a backend's `retention` member), * or `null` when it runs none; `undefined` is refused (`config.retention_capability`), so a backend's absent * member is never read as "judge the words alone". Locked or not, a store saying `"managed"` (its rows are deleted * on schedule) beside `executor: null` is refused, and so is an executor that is not one. A `"none"` store beside * an executor is not refused — a deployment may hold the executor and not run it on a store, and a locked policy * refuses that store by its word. */ export declare function assertRetentionCapability(input: RetentionWords & { executor: ManagedRetentionCapability | null; }): void; export {};