@sema-agent/core
Version:
Stateless, task-oriented AI agent core
252 lines (251 loc) • 14.6 kB
JavaScript
import { join } from "node:path";
import { types } from "node:util";
import { STORE_HOOK_KEYS, TtlSessionStore } from "../../core/session-store.js";
import { BootLock, resolveDataRoot } from "./fs-atomic.js";
import { assertAdoptionBootGate } from "./adoption/marker.js";
import { FileCheckpointStore } from "./checkpoint-store.js";
import { readLedgerTuning } from "./ledger-tuning.js";
import { FileSessionRepo, readRowPlacement, sessionsDirOf } from "./session-store.js";
import { FileToolResultStore } from "./tool-result-store.js";
import { FileSessionPolicyStore } from "./session-policy-store.js";
import { FileWorkflowJournalStore } from "./workflow-journal-store.js";
import { FileUsageWindowStore } from "./usage-window-store.js";
import { FileBackgroundAgentStore } from "./background-agent-store.js";
import { FileMailboxStore } from "./mailbox-store.js";
import { FileRosterStore } from "../../agents/roster-store.js";
import { FileFileHistoryStore } from "./file-history-store.js";
import { readMountedToolNames } from "../../core/session-policy-store.js";
import { optionKeys, receiptRefusal, receiveMembers, receiveOptions, refuseStrayMembers } from "../../core/own-property-receipt.js";
import { describeRejectedValue } from "../../core/tool-search-setting.js";
import { deliverEngineNotice } from "../../core/engine-notice.js";
import { receiveFileHistoryRetention } from "../../core/file-history-retention.js";
import { readRetentionDeclaration } from "../../core/retention.js";
import { readHolderJudge } from "../../core/checkpoint-generation.js";
import { HolderLatch, builtUnder } from "../../core/holder-latch.js";
function nestedOptions(value, member, keys) {
return value === undefined ? undefined : receiveMembers(value, { subject: `FileStorageBackendOptions.${member}`, unit: "option", moment: "at new FileStorageBackend" }, keys);
}
export { FileCheckpointStore, CHECKPOINT_LEDGER_EVENT_KINDS, readCheckpointLedger, } from "./checkpoint-store.js";
export { FileSessionRepo } from "./session-store.js";
export { FileToolResultStore } from "./tool-result-store.js";
export { FileSessionPolicyStore } from "./session-policy-store.js";
export { FileFileHistoryStore } 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 } from "./usage-window-store.js";
export { resolveDataRoot, sanitizeScope, sanitizePathComponent } from "./fs-atomic.js";
export { dataRootLocation } from "../../core/data-root.js";
export { FileStoreLockError } from "./fs-atomic.js";
export { readDataRootLocks } from "./lock-reading.js";
export { FileLedgerDamagedError } from "./shared-ledger.js";
export { inspectFileLedgers, setAsideLedgerDamage } from "./ledger-damage.js";
export { atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog } from "./fs-atomic.js";
export { setAppendLogDescriptorBudget, appendLogDescriptorStats } from "./descriptor-seat.js";
export { processFingerprint, isProcessLive } from "./fs-atomic.js";
export { declareDataRoot } from "./data-root-declaration.js";
export { ADOPTION_ERROR_CODES, AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, } from "./adoption/marker.js";
export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, } from "./adoption/adopt.js";
const FILE_STORAGE_BACKEND_OPTION_KEYS = optionKeys()({ root: 0, anchor: 0, evict: 0, checkpoint: 0, holderIsCurrent: 0, retention: 0, fileHistory: 0, sessionPolicy: 0, onCorruptRead: 0, sessions: 0, admit: 0 });
function refuseNestedHolderJudge(record) {
let nested;
try {
nested = record !== null && typeof record === "object" && Object.prototype.hasOwnProperty.call(record, "holderIsCurrent");
}
catch {
return;
}
if (nested) {
throw receiptRefusal("FileStorageBackendOptions.checkpoint.holderIsCurrent is retired: the grant judge is the backend's one, handed to the session store and the checkpoint store alike — pass it as FileStorageBackendOptions.holderIsCurrent");
}
}
function readSessionHooks(face, evict) {
let hook;
if (face !== undefined) {
if (typeof face !== "object" || face === null)
throw receiptRefusal(`FileStorageBackendOptions.sessions must be an object when given, got ${face === null ? "null" : typeof face}`);
hook = receiveMembers(face, { subject: "FileStorageBackendOptions.sessions", unit: "hook", moment: "at new FileStorageBackend" }, STORE_HOOK_KEYS)["beforeSessionDelete"];
if (hook !== undefined && typeof hook !== "function")
throw receiptRefusal(`FileStorageBackendOptions.sessions.beforeSessionDelete must be a function when given, got ${hook === null ? "null" : typeof hook}`);
}
if (typeof hook !== "function") {
if (evict === "delete") {
throw receiptRefusal(`FileStorageBackendOptions.evict "delete" deletes a session's row and log on the store's own motion (a release, an idle eviction) and leaves ` +
`the session's rows in every other store, which no later deletion can tell from a new occupant's: give ` +
`FileStorageBackendOptions.sessions.beforeSessionDelete — it runs before each such deletion while the row still stands, where the ` +
`deployment runs RETENTION_CASCADE's legs before the session row's — or a beforeSessionDelete that does nothing to state that nothing is erased`);
}
return undefined;
}
const run = hook;
return { beforeSessionDelete: (sessionId) => Reflect.apply(run, face, [sessionId]) };
}
function readAdmit(value) {
if (value === undefined || typeof value === "function")
return value;
throw receiptRefusal(`FileStorageBackendOptions.admit must be a function when given (got ${describeRejectedValue(value)})`);
}
function admitRoot(admit, root) {
const sessionsDir = sessionsDirOf(root);
let open = true;
const admission = Object.freeze({
isPlaced(sessionId) {
if (!open) {
throw receiptRefusal("FileStorageBackendOptions.admit: admission.isPlaced may only be called while the admit callback is running");
}
return readRowPlacement(sessionsDir, sessionId) !== undefined;
},
});
let answer;
try {
answer = Reflect.apply(admit, undefined, [root, admission]);
}
finally {
open = false;
}
if (answer !== undefined) {
if (types.isPromise(answer)) {
try {
Promise.prototype.then.call(answer, undefined, () => {
});
}
catch {
}
}
throw receiptRefusal(`file store: the data root ${root} is refused — FileStorageBackendOptions.admit returned ${describeRejectedValue(answer)}, but it admits by ` +
`returning nothing and refuses by throwing, and this open is synchronous, so a returned value (a promise included) is not an admission`);
}
}
const NESTED_FILE_HISTORY_OPTION_KEYS = optionKeys()({ retention: 0, maxBlobBytes: 0 });
const NESTED_SESSION_POLICY_OPTION_KEYS = optionKeys()({ mountedToolNames: 0 });
const NESTED_CHECKPOINT_OPTION_KEYS = optionKeys()({ fsync: 0, compactEvery: 0 });
export class FileStorageBackend {
root;
sessionStore;
checkpointStore;
toolResultStore;
sessionPolicyStore;
workflowJournalStore;
usageWindowStore;
backgroundAgentStore;
mailboxStore;
rosterStore;
fileHistoryStore;
lock;
latch = new HolderLatch();
fileAgentRows;
fileMailbox;
fileCheckpoints;
ttl;
fileSessions;
fileWorkflowJournal;
constructor(options) {
const opts = receiveOptions(options, "FileStorageBackend", FILE_STORAGE_BACKEND_OPTION_KEYS);
const retention = readRetentionDeclaration("FileStorageBackendOptions.retention", opts.retention);
const holderIsCurrent = readHolderJudge("FileStorageBackendOptions.holderIsCurrent", opts.holderIsCurrent);
const judge = holderIsCurrent !== undefined ? { holderIsCurrent } : undefined;
refuseNestedHolderJudge(opts.checkpoint);
const checkpointRecord = nestedOptions(opts.checkpoint, "checkpoint", NESTED_CHECKPOINT_OPTION_KEYS);
const checkpointOptions = checkpointRecord === undefined ? undefined : { ...checkpointRecord, ...readLedgerTuning(checkpointRecord, "FileCheckpointStore", "FileStorageBackendOptions.checkpoint") };
const sessionPolicyRecord = nestedOptions(opts.sessionPolicy, "sessionPolicy", NESTED_SESSION_POLICY_OPTION_KEYS);
const sessionPolicyOptions = sessionPolicyRecord?.mountedToolNames === undefined ? sessionPolicyRecord : { ...sessionPolicyRecord, mountedToolNames: readMountedToolNames(sessionPolicyRecord.mountedToolNames) };
const fileHistoryRecord = nestedOptions(opts.fileHistory, "fileHistory", NESTED_FILE_HISTORY_OPTION_KEYS);
const fileHistoryOptions = fileHistoryRecord === undefined ? undefined : { ...fileHistoryRecord, retention: receiveFileHistoryRetention("FileStorageBackendOptions.fileHistory", fileHistoryRecord.retention) };
if (opts.sessions !== undefined)
refuseStrayMembers(opts.sessions, { subject: "FileStorageBackendOptions.sessions", unit: "hook", moment: "at new FileStorageBackend" }, STORE_HOOK_KEYS);
const admit = readAdmit(opts.admit);
this.root = resolveDataRoot(opts.root, opts.anchor);
assertAdoptionBootGate(this.root, "FileStorageBackend");
this.lock = BootLock.fence(this.root, "LOCK");
this.lock.acquire();
const built = [];
const ours = (store) => builtUnder(store, this.latch);
try {
if (admit !== undefined)
admitRoot(admit, this.root);
const sessionHooks = readSessionHooks(opts.sessions, opts.evict);
const corruptRead = opts.onCorruptRead !== undefined ? { onCorruptRead: opts.onCorruptRead } : undefined;
const repo = ours(new FileSessionRepo(this.root, { ...corruptRead, ...judge }));
this.fileSessions = repo;
this.ttl = ours(new TtlSessionStore({ repo, evict: opts.evict ?? "forget", durability: "durable", placements: { subagent: { durability: "durable" } }, retention, ...(sessionHooks !== undefined ? { hooks: sessionHooks } : {}) }));
this.sessionStore = this.ttl;
const sessionHeadOf = this.ttl.headOf;
this.fileCheckpoints = ours(new FileCheckpointStore(this.root, { ...checkpointOptions, ...corruptRead, ...judge, retention, ...(sessionHeadOf !== undefined ? { sessionHeadOf } : {}) }));
built.push(() => this.fileCheckpoints.close());
this.checkpointStore = this.fileCheckpoints;
this.toolResultStore = ours(new FileToolResultStore(this.root, { ...corruptRead, retention }));
this.sessionPolicyStore = ours(new FileSessionPolicyStore(this.root, { ...sessionPolicyOptions, ...corruptRead }));
this.fileWorkflowJournal = ours(new FileWorkflowJournalStore(this.root, true, corruptRead));
built.push(() => this.fileWorkflowJournal.dispose());
this.workflowJournalStore = this.fileWorkflowJournal;
this.usageWindowStore = ours(new FileUsageWindowStore(this.root, corruptRead));
this.fileAgentRows = ours(new FileBackgroundAgentStore(this.root, corruptRead ?? {}));
built.push(() => this.fileAgentRows.close());
this.backgroundAgentStore = this.fileAgentRows;
this.fileMailbox = ours(new FileMailboxStore(this.root, corruptRead ?? {}));
built.push(() => this.fileMailbox.close());
this.mailboxStore = this.fileMailbox;
this.rosterStore = ours(new FileRosterStore(join(this.root, "roster.json"), corruptRead ?? {}));
this.fileHistoryStore = ours(new FileFileHistoryStore(this.root, { ...fileHistoryOptions, ...(corruptRead ?? {}) }));
}
catch (err) {
for (const undo of built.reverse()) {
try {
undo();
}
catch {
}
}
if (!this.lock.release())
this.discloseRetainedBootLock();
throw err;
}
}
discloseRetainedBootLock() {
const lockPath = join(this.root, "LOCK");
deliverEngineNotice(undefined, {
code: "store.lock_retained",
message: `[sema] file store: this backend could not hand back its boot lock at ${lockPath} — the ` +
`removal could not be proven, so a lock file naming this live process (pid ${process.pid}) may still be ` +
`there. While it is, another process opening this data root is refused by name; a later open of this root ` +
`in THIS process finishes the cleanup or refuses by name. After this process exits the file is reclaimed ` +
`as a stale lock ONLY if it is readable and its directory writable — otherwise it has to be removed by hand.`,
detail: { lock: "boot", path: lockPath, pid: process.pid },
});
}
async dispose() {
this.latch.close();
const failures = [];
try {
await this.ttl.dispose();
}
catch (err) {
failures.push(err);
}
try {
await this.fileSessions.dispose();
}
catch (err) {
failures.push(err);
}
const closing = (close) => {
try {
close();
}
catch (err) {
failures.push(err);
}
};
closing(() => this.fileCheckpoints.close());
closing(() => this.fileWorkflowJournal.dispose());
closing(() => this.fileAgentRows.close());
closing(() => this.fileMailbox.close());
const released = this.lock.release();
if (!released)
this.discloseRetainedBootLock();
if (failures.length === 1)
throw failures[0];
if (failures.length > 1) {
throw new AggregateError(failures, `FileStorageBackend.dispose: ${failures.length} stores failed to close (every store was closed in turn, then the boot lock was ${released ? "released" : "NOT handed back — see store.lock_retained"})`);
}
}
}