UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

554 lines (553 loc) • 22.5 kB
import { existsSync, statSync } from "node:fs"; import { mkdirSync, readFileSync, readdirSync, unlinkSync } from "./descriptor-seat.js"; import { createHash } from "node:crypto"; import { basename, join } from "node:path"; import { callKeyOrdinal, readWorkflowJournalEntry, launchRecordToKeepOrThrow, readLaunchRecordVerdict, assertLaunchRecordFits, sameLaunchRecord, WorkflowLaunchConflictError, WorkflowLaunchUnreadableError, WorkflowJournalIncompatibleError, resumeClaimRemainingMember, } from "../../core/workflow-journal-store.js"; import { processCensus, processFingerprint } from "../../core/process-identity.js"; import { callerText } from "../../core/caller-text.js"; import { AppendLog, readJsonlRecords } from "./fs-atomic.js"; import { guardCorruptSink } from "./corrupt-read-sink.js"; import { assertWellFormedKey, atomicWriteFile, BootLock, canonicalStoreKey, FileStoreLockError, sanitizePathComponent, writeThenLink } from "./fs-atomic.js"; import { assertAdoptionBootGate } from "./adoption/marker.js"; import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js"; import { assertJournalEntryFits } from "../../core/workflow-journal-store.js"; import { HolderLatch } from "../../core/holder-latch.js"; const TOMBSTONE_CLAIM_HOLDER = "workflow:stopped"; function holderProcessOf(v) { if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined; const r = v; const measure = (m) => (m === null ? null : typeof m === "number" && Number.isFinite(m) ? m : undefined); const startedAtMs = measure(r.startedAtMs); const startedSinceBootMs = measure(r.startedSinceBootMs); if (typeof r.pid !== "number" || !Number.isSafeInteger(r.pid) || r.pid <= 0 || typeof r.host !== "string" || r.host === "") return undefined; if (startedAtMs === undefined || startedSinceBootMs === undefined) return undefined; if (r.pidNs !== undefined && (typeof r.pidNs !== "string" || r.pidNs === "")) return undefined; return { pid: r.pid, startedAtMs, startedSinceBootMs, host: r.host, ...(typeof r.pidNs === "string" ? { pidNs: r.pidNs } : {}) }; } function claimBinds(claim, now) { if (claim.stopped !== undefined) return true; if (claim.rec.expiresAt <= now) return false; return claim.process === undefined || processCensus().verdict(claim.process).state !== "gone"; } function heldHere(claim, newRunId) { if (claim.stopped !== undefined || claim.rec.holder !== newRunId || claim.process === undefined) return false; const me = processFingerprint(); return claim.process.pid === me.pid && claim.process.host === me.host && claim.process.pidNs === me.pidNs; } export const RESUME_CLAIM_TTL_MS = 60 * 60 * 1000; export const RESUME_CLAIM_RELEASE_GRACE_MS = 5_000; export const RESUME_CLAIM_SWEEP_INTERVAL_MS = 60_000; export const RESUME_CLAIM_REAP_GRACE_MS = 5 * 60_000; const sharedJournalDirs = new Map(); function isJournalLine(r) { const rec = r; return typeof rec.scope === "string" && Number.isFinite(rec.ordinal); } const FILE_WORKFLOW_JOURNAL_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0 }); export class FileWorkflowJournalStore { fsyncEnabled; dir; claimsDir; shared; sharedKey; latch = new HolderLatch(this); lastClaimSweepAt = 0; get logs() { return this.shared.logs; } get scopes() { return this.shared.scopes; } discloseCorrupt; constructor(root, fsyncEnabled = true, options) { this.fsyncEnabled = fsyncEnabled; const opts = receiveOptions(options, "FileWorkflowJournalStore", FILE_WORKFLOW_JOURNAL_STORE_OPTION_KEYS); this.discloseCorrupt = guardCorruptSink(opts?.onCorruptRead); assertAdoptionBootGate(root, "FileWorkflowJournalStore"); this.dir = join(root, "workflow-journal"); mkdirSync(this.dir, { recursive: true, mode: 0o700 }); this.claimsDir = join(this.dir, "claims"); this.sharedKey = canonicalStoreKey(this.dir); const existing = sharedJournalDirs.get(this.sharedKey); if (existing !== undefined) { existing.refs += 1; this.shared = existing; } else { this.shared = { logs: new Map(), scopes: new Map(), refs: 1 }; sharedJournalDirs.set(this.sharedKey, this.shared); } } pathFor(runId) { return join(this.dir, `${sanitizePathComponent(runId)}.jsonl`); } locator(runId) { try { return this.pathFor(runId); } catch { return undefined; } } replay(runId) { let path; try { path = this.pathFor(runId); } catch { return undefined; } if (!existsSync(path)) return undefined; let scope; const byOrdinal = new Map(); const judge = { accepts: (r) => { if (!isJournalLine(r)) return false; scope ??= r.scope; return r.scope === scope; }, what: "a journal line carries no scope/ordinal pair, or a scope other than its run's first line", }; const notRecords = []; const onCorrupt = (info) => { if (info.kind === "record") notRecords.push(info); this.discloseCorrupt?.(info); }; for (const rec of readJsonlRecords(path, onCorrupt, judge)) byOrdinal.set(rec.ordinal, rec); return { scope, byOrdinal, notRecords }; } launchPathFor(runId) { return join(this.dir, "launches", `${sanitizePathComponent(runId)}.json`); } readLaunch(runId) { let path; try { path = this.launchPathFor(runId); } catch { return undefined; } let raw; try { raw = readFileSync(path, "utf-8"); } catch (err) { if (err.code === "ENOENT") return undefined; throw err; } let kept; try { kept = JSON.parse(raw); } catch { return "unreadable"; } if (kept === null || typeof kept !== "object" || Array.isArray(kept)) return "unreadable"; const scope = Reflect.get(kept, "scope"); return typeof scope === "string" ? { scope, launch: Reflect.get(kept, "launch") } : "unreadable"; } async recordLaunch(runId, scope, launch) { this.latch.refuse("FileWorkflowJournalStore.recordLaunch"); const read = launchRecordToKeepOrThrow(runId, launch); assertLaunchRecordFits(read); const path = this.launchPathFor(runId); mkdirSync(join(this.dir, "launches"), { recursive: true, mode: 0o700 }); try { writeThenLink(path, JSON.stringify({ scope, launch: read })); } catch (err) { if (err.code !== "EEXIST") throw err; const kept = this.readLaunch(runId); const keptVerdict = kept === undefined || kept === "unreadable" ? undefined : readLaunchRecordVerdict(kept.launch); if (keptVerdict !== undefined && "record" in keptVerdict && kept !== undefined && kept !== "unreadable" && kept.scope === scope && sameLaunchRecord(keptVerdict.record, read)) return; throw new WorkflowLaunchConflictError(runId); } } async loadLaunch(runId, scope) { const kept = this.readLaunch(runId); if (kept === "unreadable") throw new WorkflowLaunchUnreadableError(runId, undefined); if (kept === undefined || kept.scope !== scope) return undefined; const v = readLaunchRecordVerdict(kept.launch); if ("defect" in v) throw new WorkflowLaunchUnreadableError(runId, kept.launch); return v.record; } async deleteRun(runId, scope) { this.latch.refuse("FileWorkflowJournalStore.deleteRun"); let fault; let erased = false; for (const erase of [() => this.eraseLaunch(runId, scope), () => this.eraseLedger(runId, scope)]) { try { if (erase()) erased = true; } catch (err) { fault ??= { err }; } } if (fault !== undefined) throw fault.err; return erased; } eraseLaunch(runId, scope) { const launch = this.readLaunch(runId); if (launch === "unreadable") { this.discloseCorrupt?.({ kind: "file", path: this.launchPathFor(runId), reason: `the launch file of run ${JSON.stringify(runId)} is not a JSON object naming a scope, so whose it is cannot be told — deleteRun left it as stored (remove it by hand once it is known to be this scope's)` }); return false; } if (launch === undefined || launch.scope !== scope) return false; try { unlinkSync(this.launchPathFor(runId)); } catch (err) { if (err.code !== "ENOENT") throw err; } return true; } eraseLedger(runId, scope) { const rec = this.replay(runId); if (rec === undefined || rec.scope !== scope) return false; const log = this.logs.get(runId); this.logs.delete(runId); log?.close(); this.scopes.delete(runId); try { unlinkSync(this.pathFor(runId)); } catch (err) { if (err.code !== "ENOENT") throw err; } return true; } async append(runId, scope, entry) { this.latch.refuse("FileWorkflowJournalStore.append"); assertJournalEntryFits(entry); const committed = this.scopes.get(runId) ?? this.replay(runId)?.scope; if (committed !== undefined && committed !== scope) { throw new Error(`workflow journal: runId ${runId} already recorded under a different scope`); } this.scopes.set(runId, committed ?? scope); let log = this.logs.get(runId); if (log === undefined) { log = new AppendLog(this.pathFor(runId)); this.logs.set(runId, log); } const head = { scope, ordinal: callKeyOrdinal(entry.callKey), callKey: entry.callKey }; const line = entry.parked !== undefined ? { ...head, parked: entry.parked } : entry.stopped !== undefined ? { ...head, stopped: entry.stopped } : { ...head, result: entry.result }; log.append(line, this.fsyncEnabled); } async load(runId, scope) { const rec = this.replay(runId); if (!rec || (rec.scope !== undefined && rec.scope !== scope)) return []; const lost = rec.notRecords[0]; if (lost !== undefined) { this.discloseCorrupt?.({ kind: "file", path: this.pathFor(runId), reason: `${lost.form}: ledger line ${lost.line} is not one of the run's records (the run's journal is refused)` }); throw WorkflowJournalIncompatibleError.ledgerLine(runId, lost.line, lost.form); } const out = []; for (const [ordinal, line] of [...rec.byOrdinal.entries()].sort((a, b) => a[0] - b[0])) { const read = readWorkflowJournalEntry(line); if ("corrupt" in read) { this.discloseCorrupt?.({ kind: "file", path: this.pathFor(runId), reason: `${read.corrupt}: journal entry #${ordinal} ${read.why} (the run's journal is refused)` }); throw new WorkflowJournalIncompatibleError(runId, ordinal, line); } out.push(read.entry); } return out; } claimPathFor(sourceRunId, scope) { if (typeof sourceRunId !== "string") throw new TypeError(`workflow journal: a resume claim key must be a string (got ${callerText(sourceRunId)})`); assertWellFormedKey(scope, "workflow journal: the resume claim's scope"); const scopeTag = createHash("sha256").update(scope).digest("hex").slice(0, 16); let name; try { name = sanitizePathComponent(sourceRunId); } catch { name = undefined; } if (name === undefined || /[A-Z]/.test(name)) { name = `%${createHash("sha256").update(JSON.stringify(sourceRunId), "utf8").digest("hex").slice(0, 32)}`; } return join(this.claimsDir, `${name}.${scopeTag}.json`); } readClaimAt(path) { let raw; try { raw = readFileSync(path, "utf8"); } catch (err) { if (err.code === "ENOENT") return undefined; throw err; } try { const rec = JSON.parse(raw); if (typeof rec.holder !== "string" || typeof rec.expiresAt !== "number" || !Number.isFinite(rec.expiresAt)) { return { raw, claim: undefined }; } const stopped = typeof rec.stoppedBy === "string" && rec.stoppedBy.length > 0 ? { by: rec.stoppedBy } : undefined; return { raw, claim: { rec, process: holderProcessOf(rec.holderProcess), stopped } }; } catch { return { raw, claim: undefined }; } } removeIfUnchanged(path, judged, holder = false) { const unlinkIfJudged = () => { let now; try { now = readFileSync(path, "utf8"); } catch { return "done"; } if (now === judged) unlinkSync(path); return "done"; }; const gate = this.gateAt(path, judged); try { gate.acquire(); } catch (err) { if (err instanceof FileStoreLockError && (err.code === "store.dir_in_use" || err.code === "store.dir_claiming")) return "contended"; if (holder) return unlinkIfJudged(); throw err; } try { return unlinkIfJudged(); } finally { gate.release(); } } replaceIfUnchanged(path, judged, payload) { const gate = this.gateAt(path, judged); try { gate.acquire(); } catch (err) { if (err instanceof FileStoreLockError && (err.code === "store.dir_in_use" || err.code === "store.dir_claiming")) return "contended"; throw err; } try { let now; try { now = readFileSync(path, "utf8"); } catch (err) { if (err.code === "ENOENT") return "changed"; throw err; } if (now !== judged) return "changed"; atomicWriteFile(this.claimsDir, path, payload); return "replaced"; } finally { gate.release(); } } gateAt(path, judged) { const gatePath = judged === undefined ? path : join(this.claimsDir, `${createHash("sha256").update(`${basename(path)}\n${judged}`).digest("hex").slice(0, 32)}.takeover`); return new BootLock(gatePath, RESUME_CLAIM_TTL_MS); } sweepExpiredClaims() { const now = Date.now(); if (now - this.lastClaimSweepAt < RESUME_CLAIM_SWEEP_INTERVAL_MS) return; this.lastClaimSweepAt = now; let names; try { names = readdirSync(this.claimsDir); } catch { return; } for (const name of names) { const path = join(this.claimsDir, name); try { if (name.endsWith(".json")) { const read = this.readClaimAt(path); if (read === undefined) continue; if (read.claim !== undefined ? read.claim.stopped !== undefined || read.claim.rec.expiresAt + RESUME_CLAIM_REAP_GRACE_MS > now : now - statSync(path).mtimeMs <= RESUME_CLAIM_TTL_MS) { continue; } this.removeIfUnchanged(path, read.raw); } else if (name.endsWith(".tmp")) { if (now - statSync(path).mtimeMs > RESUME_CLAIM_TTL_MS) unlinkSync(path); } else { if (now - statSync(path).mtimeMs <= RESUME_CLAIM_TTL_MS) continue; const gate = this.gateAt(path); gate.acquire(); gate.release(); } } catch { } } } async resumeClaim(input) { this.latch.refuse("FileWorkflowJournalStore.resumeClaim"); const { sourceRunId, newRunId, scope } = input; const path = this.claimPathFor(sourceRunId, scope); mkdirSync(this.claimsDir, { recursive: true, mode: 0o700 }); this.sweepExpiredClaims(); const record = { sourceRunId, holder: newRunId, expiresAt: Date.now() + RESUME_CLAIM_TTL_MS, holderProcess: processFingerprint() }; const payload = JSON.stringify(record); for (let attempt = 0; attempt < 2; attempt++) { try { writeThenLink(path, payload); return { granted: true, ...resumeClaimRemainingMember(record.expiresAt, Date.now()) }; } catch (err) { if (err.code !== "EEXIST") throw err; } const read = this.readClaimAt(path); if (read === undefined) continue; const existing = read.claim; if (existing !== undefined && existing.stopped !== undefined) { return { granted: false, stopped: existing.stopped }; } const now = Date.now(); if (existing !== undefined && claimBinds(existing, now)) { const left = resumeClaimRemainingMember(existing.rec.expiresAt, now); if (heldHere(existing, newRunId)) return { granted: true, ...left }; return { granted: false, holder: existing.rec.holder, ...left }; } this.removeIfUnchanged(path, read.raw); } const winner = this.readClaimAt(path)?.claim; if (winner !== undefined && winner.stopped !== undefined) { return { granted: false, stopped: winner.stopped }; } const lastLook = Date.now(); const bound = winner !== undefined && claimBinds(winner, lastLook) ? winner : undefined; if (bound !== undefined && heldHere(bound, newRunId)) return { granted: true, ...resumeClaimRemainingMember(bound.rec.expiresAt, lastLook) }; return { granted: false, ...(bound !== undefined ? { holder: bound.rec.holder, ...resumeClaimRemainingMember(bound.rec.expiresAt, lastLook) } : {}) }; } async releaseResumeClaim(input) { this.latch.refuse("FileWorkflowJournalStore.releaseResumeClaim"); const path = this.claimPathFor(input.sourceRunId, input.scope); let read; try { read = this.readClaimAt(path); } catch { return; } const existing = read?.claim; if (read === undefined || existing === undefined || existing.stopped !== undefined || !heldHere(existing, input.newRunId)) return; if (existing.rec.expiresAt - Date.now() <= RESUME_CLAIM_RELEASE_GRACE_MS) return; try { this.removeIfUnchanged(path, read.raw, true); } catch { } } async stopResumeClaim(input) { this.latch.refuse("FileWorkflowJournalStore.stopResumeClaim"); if (typeof input.stoppedBy !== "string" || input.stoppedBy === "") { throw new TypeError("workflow journal: stopResumeClaim requires a non-empty stoppedBy string"); } const { sourceRunId, scope, stoppedBy, holder } = input; const path = this.claimPathFor(sourceRunId, scope); mkdirSync(this.claimsDir, { recursive: true, mode: 0o700 }); const record = { sourceRunId, holder: TOMBSTONE_CLAIM_HOLDER, expiresAt: Number.MAX_SAFE_INTEGER, stoppedBy, stoppedAt: Date.now(), }; const payload = JSON.stringify(record); for (let attempt = 0; attempt < 2; attempt++) { try { writeThenLink(path, payload); return { stopped: true }; } catch (err) { if (err.code !== "EEXIST") throw err; } const read = this.readClaimAt(path); if (read === undefined) continue; const existing = read.claim; if (existing !== undefined && existing.stopped !== undefined) { return { stopped: true }; } const now = Date.now(); const binds = existing !== undefined && claimBinds(existing, now); if (binds && (holder === undefined || existing.rec.holder !== holder)) { return { stopped: false, holder: existing.rec.holder }; } const replaced = this.replaceIfUnchanged(path, read.raw, payload); if (replaced === "replaced") return { stopped: true }; } const winner = this.readClaimAt(path)?.claim; if (winner !== undefined && winner.stopped !== undefined) return { stopped: true }; const lastLook = Date.now(); const bound = winner !== undefined && claimBinds(winner, lastLook) ? winner : undefined; return { stopped: false, ...(bound !== undefined ? { holder: bound.rec.holder } : {}) }; } dispose() { if (!this.latch.close()) return; this.shared.refs -= 1; if (this.shared.refs > 0) return; for (const log of this.shared.logs.values()) { try { log.close(); } catch { } } this.shared.logs.clear(); this.shared.scopes.clear(); sharedJournalDirs.delete(this.sharedKey); } }