UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

288 lines (287 loc) • 23 kB
import { describeRejectedValue } from "./tool-search-setting.js"; import { thrownText } from "./thrown-value.js"; import { CONFIG_RECEIPT_MODE, DECLARATION_RECEIPT_MODE, receiptRefusal, receiveOwnProperties } from "./own-property-receipt.js"; import { describeFault, receive } from "./mods/kernel/receive.js"; export function readRetentionDeclaration(name, value) { if (value === undefined || value === "none") return "none"; if (value === "managed") return "managed"; throw codedError("config.retention_capability", `store "${name}" declares an unparseable retention value ${describeRejectedValue(value)} — expected "managed" or "none".`); } export function assertDeletionSessionId(sessionId, verb) { if (typeof sessionId !== "string" || sessionId === "") { throw receiptRefusal(`${verb}: the session to delete for must be a non-empty string, got ${describeRejectedValue(sessionId)} — nothing is deleted`); } } function deepFreeze(value) { if (typeof value === "object" && value !== null) { for (const member of Object.values(value)) deepFreeze(member); Object.freeze(value); } return value; } const DROPPED_BOX_KEEPS = "in the file twin, the box's file stays, empty, under the box's handle (a session's box handle names the session's id): no record is left, and a process that still holds the box replays it empty"; const STORE_ROWS = { workflowJournalStore: { legs: [{ domain: "session-trees", step: 1, verb: "deleteRun", selects: "the journal of each terminal workflow run the session started, found through the run store's listByScope session filter while the run rows still exist", liveReference: "a running workflow run the session started" }], fork: { carry: "not-carried", why: "a run's journal stays keyed by the run the session started; a fork, like any other session, resumes that run only while the source's rows exist" }, }, workflowScriptStore: { legs: [{ domain: "session-trees", step: 2, verb: "deleteRun", selects: "the script persisted for each terminal workflow run the session started, in the run's scope, found through the run store's listByScope session filter while the run rows still exist; the saved-name registry is no run's and is not touched", liveReference: "a running workflow run the session started" }], fork: { carry: "not-carried", why: "a run's script stays keyed by the run the session started; a fork, like any other session, reads it only while the source's rows exist" }, }, workflowRunStore: { legs: [{ domain: "session-trees", step: 3, verb: "deleteBySession", selects: "the session's terminal workflow runs in its scope; answers the run ids it deleted", liveReference: "a running workflow run the session started" }], fork: { carry: "not-carried", why: "a run row stays keyed by the session that started it; a fork starts with none of its own" }, }, backgroundAgentStore: { legs: [{ domain: "session-trees", step: 5, verb: "deleteBySession", selects: "the session's terminal rows in its scope — those listBySession names for the session; answers the handles it deleted", liveReference: "a running or parked background agent of the session" }], fork: { carry: "not-carried", why: "a background agent works for the session that started it; a fork starts with none" }, }, rosterStore: { legs: [{ domain: "session-trees", step: 6, verb: "releaseAgent", selects: "every agent whose roster entry names the session as its session or as its root session (the host session of the tree the agent was spawned under — the only session a plain background agent's entry names)" }], fork: { carry: "not-carried", why: "a roster entry names the session its agent was registered for, and the root of the tree it was spawned under; a fork registers its own" }, }, checkpointStore: { legs: [ { domain: "session-trees", step: 7, verb: "deleteSessionCheckpoints", unreadable: "deleteUnreadableSessionCheckpoints", selects: "the session's checkpoint rows in any status, guarded by the session row's owner (so it runs while the row exists); for a session whose head cannot be read, the same rows, admitted by that refused read", liveReference: "a pending checkpoint of the session" }, { domain: "checkpoints", verb: "reap", selects: "the scope's pending rows whose deadline is before the call's cutoff, flipped to expired (no row is deleted)" }, ], fork: { carry: "not-carried", why: "a checkpoint is a pause of the session that parked; a fork starts with none pending" }, }, toolResultStore: { legs: [ { domain: "session-trees", step: 8, verb: "deleteBySession", selects: "the entries whose owner record names the session — offloaded text and the bytes a tool result kept alike" }, { domain: "orphan-tool-results", verb: "deleteUnattributable", selects: "the entries stored with no owner record, older than the call's cutoff" }, ], fork: { carry: "not-carried", why: "the fork's copied log keeps the source's refs, not the entries: once the source's session-tree legs ran, the fork keeps each offloaded result's preview, never the full output" }, }, sessionPolicyStore: { legs: [ { domain: "session-trees", step: 9, verb: "deleteBySession", selects: "the session's permission rules", keeps: "each of the session's keys' high-water mark — the largest rev the key carried and its generation, filed under the session id and principal it is keyed by, no rule (session_policy.rev_survives_delete): a later write on the key stamps above every rev it carried and starts a new generation, so a tighten-only write cannot slip under a floor a reader already enforced", }, ], fork: { carry: "not-carried", why: "no seat copies a session's rules into its fork; the fork's rules start empty" }, }, fileHistoryStore: { legs: [ { domain: "session-trees", step: 10, verb: "adoptScope", selects: "for each fork of the session whose row records the source occupant it was cut from (a session row whose forkedFrom names the session, with a forkedFromIncarnation) and whose source address fileHistoryScopeOf(forkedFrom, forkedFromIncarnation) is a scope step 11 deletes, that scope adopted into the fork's own (fileHistoryScopeOf(fork id, fork incarnation)) — `conflict` (already carried, or grown its own) counts as done, any other failure fails the leg, so the session's history is never deleted under a fork that has not received it; a fork row recording no source occupant is not carried into, and nothing is carried from a session whose row fileHistoryScopeOf refuses; for a session whose head cannot be read every scope under its id is deleted, so each fork recording a source occupant is carried from the address its own row records" }, { domain: "session-trees", step: 11, verb: "deleteBySession", unreadable: "deleteUnreadableSessionHistory", selects: "the session's whole history scope, fileHistoryScopeOf(session id, the row's incarnation read by headOf) and no other (a row the function refuses has none: nothing is deleted for it): boundaries, version records, pristine baselines, and the blobs no other scope references; for a session whose head cannot be read (its incarnation cannot be read, so its address cannot be named), every scope the store holds under the session id, each read back by readFileHistoryScope — the bare id and each occupant's address, never an id the session id is a prefix of" }, ], fork: { carry: "first-prepare", why: "the engine adopts the source's scope (the address the fork row records) into the fork's on the fork's first prepare; a deletion runs that carry first (its step precedes the history's), so a fork that has not prepared yet keeps its pre-fork history" }, }, mailboxStore: { legs: [ { domain: "session-trees", step: 4, verb: "drop", selects: "the box of each terminal background-agent row backgroundAgentStore.listBySession names for the session (the row's scope and handle), found through those rows while they still exist", keeps: DROPPED_BOX_KEEPS, }, { domain: "session-trees", step: 12, verb: "drop", fence: "retireRecipient", selects: "the session's box (its peer session handle) in the session owner's scope; the fence is the optional retireRecipient pair's — run first, it refuses deliveries from then on, and a store without the pair (the bundled two) keeps no recipient lifecycle and has its box dropped", keeps: DROPPED_BOX_KEEPS, }, ], fork: { carry: "not-carried", why: "a box belongs to the handle it was opened for; a fork gets its own" }, }, taskListStore: { legs: [{ domain: "session-trees", step: 13, verb: "drop", selects: "the whole list mounted under the session's id — every entry and its id high-water (task_list.partition_is_root_session: a delegation tree's root session; a child of a tree, or a session of a deployment that mounts one list per team, has none under its id)" }], fork: { carry: "not-carried", why: "a list is mounted under its tree's root session; a fork is a session of its own and starts with its own list" }, }, peerTaskStore: { legs: [{ domain: "session-trees", step: 14, verb: "deleteBySession", selects: "every readable peer-task row in the session's scope that the session sent (its own anchor: owner for a session-scoped row, parentSessionId for a task-scoped one), in any status — a running row and a settled row with an open overdue tail included; a row naming the session only as its delegation root is left (it goes with the session that sent it); nothing is sent to the peer, which may still be working; answers the task ids it deleted" }], fork: { carry: "not-carried", why: "a peer task was sent by the session that called the peer; a fork starts with none" }, }, sessionStore: { legs: [ { domain: "session-trees", step: 15, verb: "delete", unreadable: "deleteUnreadable", selects: "the session's row and its whole log (a placed subagent row is its agent row's joint reap: release after a winning delete); for a session whose head cannot be read, the row and its log as that refused read finds them, placed or not", liveReference: "a fork of the session (a session row whose forkedFrom names it)" }, { domain: "checkpoints", verb: "unpin", selects: "the session each expired checkpoint pinned" }, ], fork: { carry: "at-fork", why: "the fork copies the session's log (whole, or up to the fork point) and its row cells when it is made; deleting the source leaves the copy" }, }, usageWindowStore: { exempt: "a usage-governance ledger keyed by principal: token and cost counts, no session content, bounded by the deployment's live window set", fork: { carry: "not-carried", why: "keyed by principal, not by session: a fork's usage counts in the same principal's window" }, }, }; const GOVERNANCE_ROWS = { lineage: { exempt: "the harvest lineage ledger: which sessions contributed each memory entry, one ledger per control plane, read by the sweeps that trace a memory back to its sessions", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "one ledger per control plane, not per session: a fork's harvests add contributions under the fork's id" }, }, challenges: { exempt: "the challenge ledger: per memory entry, the challenge generations opened and resolved on it (an automatic one names the polluted session that raised it) — a fact about an entry that exists, read by every later retrieval of it", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "keyed by memory entry, not by session: a fork's pollution raises challenges of its own" }, }, settlements: { exempt: "the delegation-settlement ledger: each delegation a session launched and how it settled — the record by which a later external settlement challenges that session's committed memory contributions, so it lasts as long as they do", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "a delegation is the launching session's; a fork's launches write rows of their own" }, }, "session-accounts": { exempt: "the session-account ledger: the memory scope a session wrote, the process that held its leg, and the residue it left unattributed — an account still open marks that residue for every other session's harvest, which a deletion must not lift; a closed one keeps the scope, the process fingerprint, the times and the names of the memory files it left unattributed (no session content), and the ledger has no verb that removes it", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "an account is opened by the session's own materialize; a fork's opens its own" }, }, announcements: { exempt: "the memory announcement queue: notices about a memory scope, filed under the scope and drained by the next session that mounts it, bounded per scope — the producing session, where one is named, labels the notice; the notice is about the memory", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "filed per scope, not per session: whichever session mounts the scope next drains it" }, }, holds: { exempt: "the instruction-hold ledger: memory writes a harvest held until the writer's delegations settle, each naming its writer as the author lineage records on release — memory content pending, which the ledger releases or disposes", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "a hold is the writing session's harvest's; a fork's harvests hold their own writes" }, }, "origin-clearances": { exempt: "the origin-clearance account: per memory entry, which host request cleared its origin marker, why and when — an audit kept beside the entry, keyed by entry, whose rows outlive even the entry's erasure (that erasure takes their custody text, not the record of who vouched)", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "keyed by memory entry, not by session" }, }, pollution: { exempt: "the pollution markers: a session's record that its content carried untrusted or injected material — a fact about content that exists, not session data", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "read for the session id it names; a fork's harvest reads the fork's own marker" }, }, "import-receipt": { exempt: "a bundle import's completion receipt, one per bundle hash — a fact about an import into memory, no session's", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "keyed by bundle hash, not by session" }, }, quarantine: { exempt: "memory bytes a gate refused (or a hold's disposal moved aside), kept under the quarantine's own name — evidence about memory content, which the gate's notices and the operator read", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "named by the quarantine, not by a session" }, }, hold: { exempt: "a held memory write's captured bytes, named by its hold-ledger row — memory content pending, released into memory or moved to quarantine with that row", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "named by its hold, not by a session" }, }, "clearance-custody": { exempt: "an origin clearance's custody: the cleared memory entry's full text, kept beside the account row that names it, so a clearance a crash interrupted can still be resumed — deleted by the entry's erasure, which is the memory's to run", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "named by its clearance, not by a session" }, }, capture: { exempt: "the capture opt-out records: a person's standing withdrawal of a session from memory capture — a fact about content that exists, not session data", heldBy: "memory-control-plane", fork: { carry: "not-carried", why: "the fork reads its source's record through SessionMetadata.forkedFrom at prepare and on every harvest, so the source's standing opt-out governs the copied transcript; nothing is copied" }, }, }; export const RETENTION_CASCADE = deepFreeze({ ...STORE_ROWS, ...GOVERNANCE_ROWS }); export const RETENTION_SESSION_TREE_STEPS = deepFreeze(Object.entries(STORE_ROWS) .flatMap(([store, row]) => ("legs" in row ? row.legs.filter((leg) => leg.domain === "session-trees").map((leg) => ({ store, ...leg })) : [])) .sort((a, b) => (a.step ?? 0) - (b.step ?? 0))); function codedError(code, message) { const e = new Error(message); e.code = code; return e; } const RETENTION_EXECUTOR_MEMBERS = Object.keys({ listRetentionDomains: true, expireCheckpoints: true, deleteExpiredSessions: true, deleteOrphanToolResults: true, }); function faceMember(face, member, owner, refusal) { try { return face[member]; } catch (cause) { throw codedError("config.retention_capability", `${owner}'s ${member} could not be read (${thrownText(cause)}) — ${refusal}.`); } } function assertRetentionExecutor(executor) { if ((typeof executor !== "object" && typeof executor !== "function") || executor === null) { throw codedError("config.retention_capability", `the retention executor must be an object implementing ManagedRetentionCapability, or null when the deployment runs none (got ${describeRejectedValue(executor)}).`); } for (const member of RETENTION_EXECUTOR_MEMBERS) { const value = faceMember(executor, member, "the retention executor", "it is not a ManagedRetentionCapability"); if (typeof value !== "function") { throw codedError("config.retention_capability", `the retention executor's ${member} is ${describeRejectedValue(value)}, not a function — it is not a ManagedRetentionCapability.`); } } } function receiveRetentionInput(input, owner) { const top = receiveOwnProperties(input, { subject: `${owner}'s input`, unit: "member", moment: `at ${owner}` }); let policy = top["policy"]; if (typeof policy === "object" && policy !== null) { const got = receive(policy, DECLARATION_RECEIPT_MODE); if (!got.ok) throw codedError("config.retention_policy", `retentionPolicy could not be read as plain data — ${describeFault(got.fault)}.`); policy = got.value; } const list = receive(top["stores"], CONFIG_RECEIPT_MODE); if (!list.ok) throw receiptRefusal(`${owner}'s stores could not be read — ${describeFault(list.fault)}`); if (!Array.isArray(list.value)) throw receiptRefusal(`${owner}'s stores must be a list of { name, store } (got ${describeRejectedValue(list.value)})`); const stores = list.value.map((item, i) => { const got = receiveOwnProperties(item, { subject: `${owner}'s stores[${i}]`, unit: "member", moment: `at ${owner}` }); return { name: got.name, store: got.store }; }); return { policy: policy, locked: top["locked"], stores, ...(Object.hasOwn(top, "executor") ? { executor: top["executor"] } : {}) }; } function readRetentionWords({ policy, stores }) { const declared = policy; if (declared !== undefined && (typeof declared !== "object" || declared === null || Array.isArray(declared))) { throw codedError("config.retention_policy", `retentionPolicy must be an object carrying maxAgeDays (got ${declared === null ? "null" : Array.isArray(declared) ? "an array" : typeof declared}).`); } const maxAgeDays = policy?.maxAgeDays; if (policy !== undefined && (typeof maxAgeDays !== "number" || !Number.isFinite(maxAgeDays) || maxAgeDays < 0)) { throw codedError("config.retention_policy", `retentionPolicy.maxAgeDays must be a finite non-negative number of days (got ${describeRejectedValue(maxAgeDays)}).`); } return stores .filter((s) => s.store !== undefined && s.store !== null) .map(({ name, store }) => ({ name, retention: readRetentionDeclaration(name, faceMember(store, "retention", `store "${name}"`, "its retention declaration is unreadable")) })); } export function assertRetentionWords(input) { const { policy, locked, stores } = receiveRetentionInput(input, "assertRetentionWords"); const words = { policy, locked, stores }; refuseLockedOverNone(words, readRetentionWords(words)); } export function assertRetentionCapability(input) { const { policy, locked, stores, executor } = receiveRetentionInput(input, "assertRetentionCapability"); const words = { policy, locked, stores }; if (executor === undefined) { throw codedError("config.retention_capability", `executor is required — the managed-retention executor the deployment runs over these stores' rows (a backend's \`retention\` member), or null when it runs none (got undefined).`); } const declarations = readRetentionWords(words); if (executor !== null) assertRetentionExecutor(executor); else { const unexecuted = declarations.filter(({ retention }) => retention === "managed"); if (unexecuted.length > 0) { throw codedError("config.retention_capability", `${unexecuted.map((s) => s.name).join(", ")} declare${unexecuted.length === 1 ? "s" : ""} retention "managed" — rows deleted on schedule by the deployment — ` + `but the deployment runs no retention executor: nothing would delete them. Declare those stores "none", or wire the executor that deletes their rows.`); } } refuseLockedOverNone(words, declarations); } function refuseLockedOverNone({ policy, locked }, declarations) { if (!locked || policy === undefined) return; const incapable = declarations.filter(({ retention }) => retention !== "managed"); if (incapable.length > 0) { throw codedError("config.retention_capability", `retention policy is LOCKED but ${incapable.map((s) => s.name).join(", ")} ` + `declare${incapable.length === 1 ? "s" : ""} retention "none" (or no declaration — read fail-closed as "none"): ` + `a locked retention policy over stores that cannot delete would be "policy locked, data immortal". ` + `Wire managed-retention stores, or unlock/remove the retention policy.`); } }