UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

257 lines (256 loc) • 11.9 kB
import { existsSync } from "node:fs"; import { BACKGROUND_AGENT_ROW_SHAPE, BackgroundAgentStoreError, admitBackgroundAgent, backgroundAgentReapCandidates, backgroundAgentSessionRows, isBackgroundAgentSettledStatus, nextBackgroundAgentOnUpdate, readScopeRekeyPlan, receiveBackgroundAgentReapOptions, queryBackgroundAgents, readStoredBackgroundAgent, staleRunningFlip, scopeRekeyWritesOf, } from "../../core/background-agent-store.js"; import { readScopeRekeyInput } from "../../core/identity-rekey.js"; import { ledgerPathsOf, SharedLedgerTable } from "./shared-ledger.js"; import { guardCorruptSink } from "./corrupt-read-sink.js"; import { assertAdoptionBootGate } from "./adoption/marker.js"; import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js"; import { LEDGER_COMPACT_EVERY_DEFAULTS, readLedgerTuning } from "./ledger-tuning.js"; import { HolderLatch } from "../../core/holder-latch.js"; const FILE_BACKGROUND_AGENT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, fsync: 0, compactEvery: 0 }); const isAgentRow = (x) => BACKGROUND_AGENT_ROW_SHAPE.rowKey(x); const agentLedgerModel = { label: "background-agent ledger", keyOf: (r) => FileBackgroundAgentStore.key(r.handle, r.scope), apply: (rows, ev) => { if (ev.t === "delete") { rows.delete(ev.k); return; } rows.set(ev.k, ev.r); }, judgeRow: isAgentRow, judgeEvent: (x) => { const ev = x; if (typeof ev.k !== "string") return false; return ev.t === "delete" ? true : isAgentRow(ev.r); }, eventKey: (ev) => ev.k, settles: (ev) => (ev.t === "delete" ? null : ev.r), nameOf: (r) => `background agent ${r.handle}`, }; const agentLedgers = new SharedLedgerTable(agentLedgerModel); export const BACKGROUND_AGENT_LEDGER = Object.freeze({ name: "background-agents", ledgerFile: "agents.jsonl", snapshotFile: "agents.snapshot.jsonl", model: agentLedgerModel, table: agentLedgers, }); const readAgentRekeyInput = (input) => readScopeRekeyInput("BackgroundAgentStore.rekeyScope", input); function rekeyAgentLedgerScope(ledger, read, commit, disclose) { const rows = ledger.rows; const keyOf = FileBackgroundAgentStore.key; if (read.fromScope === read.toScope) return Promise.resolve(readScopeRekeyPlan(rows, keyOf, read).answer); const filedUnder = keyOf("", read.fromScope); const taken = new Set([...rows.keys()].filter((k) => k.startsWith(filedUnder))); const keys = [...new Set([...taken].flatMap((k) => [k, keyOf(k.slice(filedUnder.length), read.toScope)]))].sort(); const underAll = (i) => i < keys.length ? ledger.withLock(keys[i], () => underAll(i + 1)) : Promise.resolve().then(() => { const plan = readScopeRekeyPlan(rows, keyOf, read, { only: taken, ...(disclose !== undefined ? { disclose } : {}) }); const { puts, deletes } = scopeRekeyWritesOf(read.mode, plan, read.toScope, keyOf); for (const p of puts) commit({ t: "put", k: p.key, r: p.row }); for (const d of deletes) if (rows.get(d.key)?.rev === d.rev) commit({ t: "delete", k: d.key }); return plan.answer; }); return underAll(0); } export function lookBackgroundAgentDirectory(root) { const paths = ledgerPathsOf(root, BACKGROUND_AGENT_LEDGER); if (existsSync(paths.dir)) agentLedgers.acquire(paths).release(); } export async function rekeyBackgroundAgentDirectory(root, input) { const read = readAgentRekeyInput(input); const paths = ledgerPathsOf(root, BACKGROUND_AGENT_LEDGER); if (!existsSync(paths.dir)) return readScopeRekeyPlan(new Map(), FileBackgroundAgentStore.key, read).answer; const ledger = agentLedgers.acquire(paths); try { return await rekeyAgentLedgerScope(ledger, read, (ev) => ledger.commit(ev, true, LEDGER_COMPACT_EVERY_DEFAULTS.FileBackgroundAgentStore), undefined); } finally { ledger.release(); } } export class FileBackgroundAgentStore { fsyncEnabled; compactEvery; ledger; latch = new HolderLatch(this); disclose; get rows() { return this.ledger.rows; } constructor(root, options) { const opts = receiveOptions(options, "FileBackgroundAgentStore", FILE_BACKGROUND_AGENT_STORE_OPTION_KEYS); assertAdoptionBootGate(root, "FileBackgroundAgentStore"); const tuning = readLedgerTuning(opts, "FileBackgroundAgentStore", "FileBackgroundAgentStore options"); this.fsyncEnabled = tuning.fsync; this.compactEvery = tuning.compactEvery; const paths = ledgerPathsOf(root, BACKGROUND_AGENT_LEDGER); const sink = guardCorruptSink(opts.onCorruptRead); this.disclose = sink === undefined ? undefined : (reason) => sink({ kind: "file", path: paths.ledgerPath, reason }); this.ledger = agentLedgers.acquire({ ...paths, ...(sink !== undefined ? { onCorruptRead: sink } : {}) }); } static key(handle, scope) { return `${scope}\u0000${handle}`; } withLock(key, fn) { return this.ledger.withLock(key, fn); } commit(ev) { this.ledger.commit(ev, this.fsyncEnabled, this.compactEvery); } async put(record) { this.latch.refuse("FileBackgroundAgentStore.put"); const stored = structuredClone(record); stored.rev = record.rev ?? 0; const k = FileBackgroundAgentStore.key(record.handle, record.scope); const admitted = admitBackgroundAgent(stored, { key: k }); return this.withLock(k, () => { if (this.rows.has(k)) { throw new BackgroundAgentStoreError("agent_record.already_exists", "agent record already exists"); } this.commit({ t: "put", k, r: admitted }); }); } async get(handle, scope) { const k = FileBackgroundAgentStore.key(handle, scope); const row = this.rows.get(k); return row ? structuredClone(readStoredBackgroundAgent(row, { key: k }, this.disclose)) : null; } async update(handle, scope, record, expect) { return this.updateIf(handle, scope, record, { rev: expect.rev }); } async updateIf(handle, scope, record, expect) { this.latch.refuse("FileBackgroundAgentStore.updateIf"); const k = FileBackgroundAgentStore.key(handle, scope); return this.withLock(k, async () => { const next = nextBackgroundAgentOnUpdate(this.rows.get(k), k, handle, scope, record, expect, this.disclose); if (next === null) return false; this.commit({ t: "update", k, r: next }); return true; }); } async listBySession(scope, sessionId, opts) { return queryBackgroundAgents(this.rows.values(), { scope, sessionId, status: opts?.status, limit: opts?.limit }, this.disclose); } async listByScope(scope, opts) { return queryBackgroundAgents(this.rows.values(), { scope, status: opts?.status, limit: opts?.limit }, this.disclose); } async listByRoot(rootSessionId, opts) { return queryBackgroundAgents(this.rows.values(), { root: rootSessionId, status: opts?.status, limit: opts?.limit }); } async listScopes() { return [...new Set([...this.rows.values()].map((r) => r.scope))].sort(); } async delete(handle, scope, expect) { this.latch.refuse("FileBackgroundAgentStore.delete"); const k = FileBackgroundAgentStore.key(handle, scope); return this.withLock(k, () => { const live = this.rows.get(k); const gone = live !== undefined && (expect === undefined || live.rev === expect.rev); if (gone) this.ledger.commit({ t: "delete", k }, this.fsyncEnabled, Number.POSITIVE_INFINITY); return gone; }); } async settleErasure() { this.latch.refuse("FileBackgroundAgentStore.settleErasure"); this.ledger.settleErasure(); } async deleteBySession(scope, sessionId) { this.latch.refuse("FileBackgroundAgentStore.deleteBySession"); const deleted = []; for (const handle of backgroundAgentSessionRows(this.rows.values(), scope, sessionId, this.disclose)) { const k = FileBackgroundAgentStore.key(handle, scope); const gone = await this.withLock(k, () => { const live = this.rows.get(k); if (live === undefined || backgroundAgentSessionRows([live], scope, sessionId).length === 0) return false; this.ledger.commit({ t: "delete", k }, this.fsyncEnabled, Number.POSITIVE_INFINITY); return true; }); if (gone) deleted.push(handle); } this.ledger.settleErasure(); return deleted; } async rekeyScope(input) { this.latch.refuse("FileBackgroundAgentStore.rekeyScope"); return rekeyAgentLedgerScope(this.ledger, readAgentRekeyInput(input), (ev) => this.commit(ev), this.disclose); } async reap(scope, now, opts) { this.latch.refuse("FileBackgroundAgentStore.reap"); const policy = receiveBackgroundAgentReapOptions(opts); if (policy.maxAgeMs === undefined && policy.keep === undefined && policy.staleRunningMaxAgeMs === undefined) return 0; const changed = new Set(); if (policy.staleRunningMaxAgeMs !== undefined) { const staleMs = policy.staleRunningMaxAgeMs; const staleCandidates = [...this.rows.entries()].filter(([k, r]) => staleRunningFlip(r, k, scope, now, staleMs, this.disclose) !== undefined).map(([k]) => k); for (const k of staleCandidates) { const flipped = await this.withLock(k, () => { const next = staleRunningFlip(this.rows.get(k), k, scope, now, staleMs); if (next === undefined) return false; this.commit({ t: "update", k, r: next }); return true; }); if (flipped) changed.add(k); } } const terminal = backgroundAgentReapCandidates(this.rows.entries(), scope, this.disclose); const doomed = new Map(); if (policy.maxAgeMs !== undefined) { for (const r of terminal) { if (r.age < now - policy.maxAgeMs) doomed.set(r.key, { byAge: true }); } } if (policy.keep !== undefined) { for (const r of terminal.slice(Math.max(0, policy.keep))) { if (!doomed.has(r.key)) doomed.set(r.key, { byAge: false }); } } for (const [k, why] of doomed) { const deleted = await this.withLock(k, () => { const live = this.rows.get(k); if (!live || live.scope !== scope || !isBackgroundAgentSettledStatus(live.status)) return false; if (why.byAge && policy.maxAgeMs !== undefined && (live.settledAt ?? live.spawnedAt) >= now - policy.maxAgeMs) return false; this.ledger.commit({ t: "delete", k }, this.fsyncEnabled, Number.POSITIVE_INFINITY); return true; }); if (deleted) changed.add(k); } if (policy.maxAgeMs !== undefined || policy.keep !== undefined) this.ledger.settleErasure(); return changed.size; } compactNow() { this.latch.refuse("FileBackgroundAgentStore.compactNow"); this.ledger.compact(); } get size() { return this.rows.size; } close() { if (!this.latch.close()) return; this.ledger.release(); } }