UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

526 lines (525 loc) • 27.3 kB
import { existsSync } from "node:fs"; import { readFileSync, readdirSync, unlinkSync } from "./descriptor-seat.js"; import { basename, join } from "node:path"; import { conjoinSessionRuleRows, judgeSessionRulesWrite, readMountedToolNames, readSessionRulesShape, SessionPolicyError, sessionRulesPrincipalOf, } from "../../core/session-policy-store.js"; import { atomicWriteFile, ensureDir, sanitizeScope } from "./fs-atomic.js"; import { guardCorruptSink } from "./corrupt-read-sink.js"; import { assertAdoptionBootGate, readRootAdoptionFile } from "./adoption/marker.js"; import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js"; import { HolderLatch } from "../../core/holder-latch.js"; import { eraseStepOf, judgePrincipalRekey, readPrincipalRekeyInput, } from "../../core/identity-rekey.js"; const FILE_SESSION_POLICY_STORE_OPTION_KEYS = optionKeys()({ mountedToolNames: 0, onCorruptRead: 0 }); export const SESSION_POLICY_MARK_SUFFIX = ".hwm.json"; const MARK_SUFFIX = SESSION_POLICY_MARK_SUFFIX; function isArrivalRecord(v) { const isStamp = (s) => { if (s === null || typeof s !== "object") return false; const { rev, gen } = s; return typeof rev === "number" && Number.isFinite(rev) && typeof gen === "number" && Number.isInteger(gen) && gen >= 0; }; if (v === null || typeof v !== "object" || Array.isArray(v)) return false; const r = v; return typeof r.to === "string" && (r.from === "unreadable" || isStamp(r.from)) && isStamp(r.at); } export function readSessionPolicyMark(path) { let raw; try { raw = readFileSync(path, "utf8"); } catch (err) { if (err.code === "ENOENT") return { mark: null }; throw err; } const corrupt = (reason) => ({ corrupt: { reason } }); let parsed; try { parsed = JSON.parse(raw); } catch { return corrupt("is unparseable"); } if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return corrupt("is not a JSON object"); const mark = parsed; if (typeof mark.__hwm !== "number" || !Number.isFinite(mark.__hwm)) return corrupt("carries no numeric value"); if (mark.__gen !== undefined && (typeof mark.__gen !== "number" || !Number.isInteger(mark.__gen) || mark.__gen < 0)) return corrupt("carries a lineage that is not a whole number"); if (mark.__arrival !== undefined && !isArrivalRecord(mark.__arrival)) return corrupt("carries an arrival record that is not one"); return { mark }; } export function judgeSessionPolicyRowObject(raw) { let parsed; try { parsed = JSON.parse(raw); } catch { return { corrupt: { grade: "unparseable", reason: "unparseable JSON (torn/zero-byte write?)" } }; } if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { return { corrupt: { grade: "malformed", reason: "not a JSON object" } }; } return { row: parsed }; } export function judgeSessionPolicyRowShape(row) { const bad = (reason) => ({ corrupt: { grade: "malformed", reason } }); if (typeof row.rev !== "number" || !Number.isFinite(row.rev) || row.rev < 1) return bad("rev is not a positive number"); if (row.gen !== undefined && (typeof row.gen !== "number" || !Number.isInteger(row.gen) || row.gen < 0)) return bad("gen is not a whole number"); const { __sid: _sid, __principal: _principal, ...clean } = row; void _sid; void _principal; const shaped = readSessionRulesShape(clean); if ("fault" in shaped) return bad(shaped.sentence); return { rules: clean }; } export function attributeSessionPolicyRow(dir, file, row) { const spell = (p) => (typeof p === "string" || p === null ? p : undefined); if (row !== undefined && typeof row.__sid === "string") return { owner: { sessionId: row.__sid, principal: spell(row.__principal) } }; const markRead = readSessionPolicyMark(join(dir, `${file.slice(0, -".json".length)}${MARK_SUFFIX}`)); const mark = "corrupt" in markRead ? null : markRead.mark; return { owner: mark !== null && typeof mark.__sid === "string" ? { sessionId: mark.__sid, principal: spell(mark.__principal) } : undefined, markRead }; } function effectivePrincipalOf(principal, alias) { return principal ?? alias ?? null; } function sessionPolicyStemFor(sessionId, principal, alias) { return sanitizeScope(JSON.stringify([sessionId, effectivePrincipalOf(principal, alias)])); } function refuseRekey(path, what, reason) { throw new SessionPolicyError("corrupt", `session rules re-key: ${what} ${reason}: ${path} — refusing rather than guess whose rules it holds or restart a key's rev from zero. Repair or remove that file (removing a mark gives up the number it held), then run the step again.`); } const errnoOf = (err) => err.code ?? err.name; function rekeyMarkAt(path) { let read; try { read = readSessionPolicyMark(path); } catch (err) { return refuseRekey(path, "a high-water mark", `could not be read (${errnoOf(err)})`); } return "corrupt" in read ? refuseRekey(path, "a high-water mark", read.corrupt.reason) : read.mark; } function rekeyRowAt(path) { let raw; try { raw = readFileSync(path, "utf8"); } catch (err) { if (err.code === "ENOENT") return null; return refuseRekey(path, "a rules row", `could not be read (${errnoOf(err)})`); } return { raw, judged: judgeSessionPolicyRowObject(raw) }; } function rekeyKeyFiles(dir, stem) { const rowPath = join(dir, `${stem}.json`); const markPath = join(dir, `${stem}${MARK_SUFFIX}`); return { rowPath, markPath, row: rekeyRowAt(rowPath), mark: rekeyMarkAt(markPath) }; } function rekeyRowStampOf(row) { if (row === null) return null; if ("corrupt" in row.judged) return { readable: false, rev: 0, gen: 0 }; const shaped = judgeSessionPolicyRowShape(row.judged.row); if ("rules" in shaped) return { readable: true, rev: shaped.rules.rev, gen: shaped.rules.gen ?? 0 }; const { rev, gen } = row.judged.row; return { readable: false, rev: typeof rev === "number" && Number.isFinite(rev) ? rev : 0, gen: typeof gen === "number" && Number.isInteger(gen) && gen >= 0 ? gen : 0 }; } function rekeyMarkReadingOf(mark) { if (mark === null) return null; return { stamp: { rev: mark.__hwm, gen: mark.__gen ?? 0 }, lineageLost: mark.__lineage === "lost", ...(mark.__arrival !== undefined ? { arrival: mark.__arrival } : {}) }; } function writeRekeyMark(dir, path, stamp, sessionId, principal, arrival) { const mark = { __hwm: stamp.rev, __gen: stamp.gen, __sid: sessionId, __principal: principal, ...(arrival !== undefined ? { __arrival: arrival } : {}) }; atomicWriteFile(join(dir, "tmp"), path, JSON.stringify(mark)); } export function rekeySessionPolicyDirectory(dir, input, alias) { const { from, toPrincipal, mode } = input; const fromName = from.kind === "principal" ? from.principal : undefined; const source = effectivePrincipalOf(fromName, alias); const sessions = new Set(); if (source !== toPrincipal) { let entries; try { entries = readdirSync(dir); } catch (err) { if (err.code !== "ENOENT") refuseRekey(dir, "the session rules directory", `could not be read (${errnoOf(err)})`); entries = []; } for (const file of entries) { if (!file.endsWith(MARK_SUFFIX)) continue; const mark = rekeyMarkAt(join(dir, file)); if (mark !== null && mark.__principal === source && typeof mark.__sid === "string") sessions.add(mark.__sid); } for (const file of entries) { if (file.endsWith(MARK_SUFFIX) || !file.endsWith(".json")) continue; const row = rekeyRowAt(join(dir, file)); if (row === null) continue; let owner; try { owner = attributeSessionPolicyRow(dir, file, "row" in row.judged ? row.judged.row : undefined).owner; } catch (err) { return refuseRekey(join(dir, `${file.slice(0, -".json".length)}${MARK_SUFFIX}`), "a rules row's high-water mark", `could not be read (${errnoOf(err)})`); } if (owner !== undefined && owner.principal === source) sessions.add(owner.sessionId); } } const keys = [...sessions].sort().map((sessionId) => ({ sessionId, source: rekeyKeyFiles(dir, sessionPolicyStemFor(sessionId, fromName, alias)), target: rekeyKeyFiles(dir, sessionPolicyStemFor(sessionId, toPrincipal, alias)), })); const { answer, writes } = judgePrincipalRekey(mode, toPrincipal, keys.map((k) => ({ sourceRow: rekeyRowStampOf(k.source.row), sourceMark: rekeyMarkReadingOf(k.source.mark), targetRow: rekeyRowStampOf(k.target.row), targetMark: rekeyMarkReadingOf(k.target.mark), }))); writes.forEach((write, i) => { if (write === undefined) return; const { sessionId, source: a, target: b } = keys[i]; switch (write.kind) { case "arrive": { const at = write.record.at; if (write.sourceMark !== null) writeRekeyMark(dir, a.markPath, write.sourceMark, sessionId, source, write.record); writeRekeyMark(dir, b.markPath, at, sessionId, toPrincipal); atomicWriteFile(join(dir, "tmp"), b.rowPath, arrivingBytesOf(a.row, at, sessionId, toPrincipal)); return; } case "merge-marks": writeRekeyMark(dir, b.markPath, write.mark, sessionId, toPrincipal); return; case "leave": writeRekeyMark(dir, a.markPath, write.mark, sessionId, source, write.record); unlinkIfPresent(a.rowPath); return; case "withdraw": if (write.targetMark !== undefined) { writeRekeyMark(dir, b.markPath, write.targetMark, sessionId, toPrincipal); unlinkIfPresent(b.rowPath); } writeRekeyMark(dir, a.markPath, write.sourceMark, sessionId, source); return; default: { const unhandled = write; return unhandled; } } }); return answer; } function arrivingBytesOf(row, at, sessionId, toPrincipal) { if (row === null) throw new Error("a re-key arrival needs its source row"); if ("corrupt" in row.judged) return row.raw; const shaped = judgeSessionPolicyRowShape(row.judged.row); if ("corrupt" in shaped) return JSON.stringify({ ...row.judged.row, __principal: toPrincipal }); return JSON.stringify({ ...shaped.rules, rev: at.rev, gen: at.gen, __sid: sessionId, __principal: toPrincipal }); } export class FileSessionPolicyStore { dir; onCorruptRead; mountedToolNames; anonymousAlias; latch = new HolderLatch(this); constructor(root, options) { const opts = receiveOptions(options, "FileSessionPolicyStore", FILE_SESSION_POLICY_STORE_OPTION_KEYS); assertAdoptionBootGate(root, "FileSessionPolicyStore"); this.mountedToolNames = readMountedToolNames(opts?.mountedToolNames); this.dir = join(root, "session-policy"); ensureDir(this.dir); this.onCorruptRead = guardCorruptSink(opts?.onCorruptRead); const adoption = readRootAdoptionFile(root); this.anonymousAlias = adoption !== undefined && "adopted" in adoption && adoption.adopted.from.kind === "local-owner" ? adoption.adopted.toPrincipal : undefined; } disclose(info) { this.onCorruptRead?.({ kind: "file", ...info }); } refuseDamaged(sessionId, principal, path, grade, reason) { this.disclose({ sessionId, ...(principal !== undefined ? { principal } : {}), path, reason }); throw new SessionPolicyError("corrupt", `session rules file for ${JSON.stringify(sessionId)} is ${grade} (${reason}) — refusing rather than read the rules it held as none (session rules only tighten). Repair it: fix the file, or delete it (deleting it = explicitly no rules, and gives up the rules it held). The file's location is reported to the store's corrupt-read disclosure (onCorruptRead), not in this message.`); } refuseDamagedMark(sessionId, principal, reason) { this.disclose({ sessionId, ...(principal !== undefined ? { principal } : {}), path: this.markPathFor(sessionId, principal), reason: `high-water mark ${reason}` }); throw new SessionPolicyError("corrupt", `session rules high-water mark for ${JSON.stringify(sessionId)} ${reason} — refusing rather than restart this key's rev from zero. Repair it: fix the mark file, or delete it (deleting it gives up the number it was holding). The file's location is reported to the store's corrupt-read disclosure (onCorruptRead), not in this message.`); } refuseUnreadable(sessionId, path, what, err) { const reason = `${what} could not be read (${err.code ?? err.name})`; this.disclose({ sessionId, path, reason }); throw new SessionPolicyError("corrupt", `session rules for ${JSON.stringify(sessionId)}: ${reason} — refusing rather than guess whose rules it holds. Retry; if it persists, repair access to the file. The file's location is reported to the store's corrupt-read disclosure (onCorruptRead), not in this message.`); } ownerOf(sessionId, file, row) { try { return attributeSessionPolicyRow(this.dir, file, row); } catch (err) { return this.refuseUnreadable(sessionId, join(this.dir, `${file.slice(0, -".json".length)}${MARK_SUFFIX}`), "a rules row's high-water mark", err); } } sweepMark(sessionId, markPath) { try { return readSessionPolicyMark(markPath); } catch (err) { return this.refuseUnreadable(sessionId, markPath, "a rules row's high-water mark", err); } } sweepEntries(sessionId) { try { return readdirSync(this.dir); } catch (err) { if (err.code === "ENOENT") return []; return this.refuseUnreadable(sessionId, this.dir, "the session rules directory", err); } } readMark(sessionId, principal) { let judged; try { judged = readSessionPolicyMark(this.markPathFor(sessionId, principal)); } catch (err) { return this.refuseDamagedMark(sessionId, principal, `could not be read (${err.code ?? err.name})`); } if ("corrupt" in judged) return this.refuseDamagedMark(sessionId, principal, judged.corrupt.reason); return judged.mark; } pathFor(sessionId, principal) { return join(this.dir, `${this.basenameFor(sessionId, principal)}.json`); } basenameFor(sessionId, principal) { return sessionPolicyStemFor(sessionId, principal, this.anonymousAlias); } markPathFor(sessionId, principal) { return join(this.dir, `${this.basenameFor(sessionId, principal)}${MARK_SUFFIX}`); } writeMarkFile(path, rev, sessionId, principal, gen) { this.writeMark(path, { __hwm: rev, __gen: gen, __sid: sessionId, __principal: principal }); } writeMark(path, mark) { atomicWriteFile(join(this.dir, "tmp"), path, JSON.stringify(mark)); } read(sessionId, principal) { if (principal === undefined || principal === this.anonymousAlias) { const closedRead = this.foldEmptyPrincipalKey(sessionId); if (closedRead !== undefined) return closedRead.unmoved; } return this.servedRow(sessionId, principal, this.pathFor(sessionId, principal)); } servedRow(sessionId, principal, path) { const judged = this.readRowFile(path); if (judged === null) return null; if ("corrupt" in judged) return this.refuseDamaged(sessionId, principal, path, judged.corrupt.grade, judged.corrupt.reason); const shaped = judgeSessionPolicyRowShape(judged.row); if ("corrupt" in shaped) return this.refuseDamaged(sessionId, principal, path, shaped.corrupt.grade, shaped.corrupt.reason); return shaped.rules; } readRowFile(path) { let raw; try { raw = readFileSync(path, "utf8"); } catch (err) { if (err.code === "ENOENT") return null; return { corrupt: { grade: "unreadable", reason: `read failed (${err.code ?? err.name})` } }; } return judgeSessionPolicyRowObject(raw); } foldEmptyPrincipalKey(sessionId) { const stem = sessionPolicyStemFor(sessionId, "", undefined); const fromRow = join(this.dir, `${stem}.json`); const fromMark = join(this.dir, `${stem}${MARK_SUFFIX}`); if (!existsSync(fromRow) && !existsSync(fromMark)) return undefined; const moved = this.servedRow(sessionId, "", fromRow); const movedMark = this.readMark(sessionId, ""); const held = this.servedRow(sessionId, undefined, this.pathFor(sessionId, undefined)); const heldMark = this.readMark(sessionId, undefined); let row = null; const gen = Math.max(moved?.gen ?? 0, held?.gen ?? 0, heldMark?.__gen ?? 0, movedMark?.__gen ?? 0); const wearing = (r) => (r.gen !== undefined || gen > 0 ? { gen } : {}); if (moved !== null && held === null) row = { ...moved, rev: Math.max(moved.rev, (heldMark?.__hwm ?? 0) + 1), ...wearing(moved) }; if (held !== null) { const both = moved === null ? held : conjoinSessionRuleRows(held, moved); if (both === undefined) { this.disclose({ sessionId, path: fromRow, reason: "a row an earlier release filed under the empty-string principal, in another rule grammar than the session-wide row" }); throw new SessionPolicyError("corrupt", `session rules for ${JSON.stringify(sessionId)}: an earlier release filed rules for this session under the principal "" (the empty string), which now reads as no principal, and the session-wide rules are written in another rule grammar, so the two cannot be held as one row without reading one row's entries differently — refusing rather than drop either. Repair it: delete the file the disclosure names and write its entries into the session's rules again without a principal. The file's location is reported to the store's corrupt-read disclosure (onCorruptRead), not in this message.`); } if (!sameRuleContent(both, held) || gen > (held.gen ?? 0)) { row = { ...both, rev: Math.max(held.rev, moved?.rev ?? 0, heldMark?.__hwm ?? 0, movedMark?.__hwm ?? 0) + 1, ...wearing(held) }; } } if (this.latch.closed) return { unmoved: row ?? held }; const attributed = this.anonymousAlias ?? null; const mark = { __hwm: Math.max(row?.rev ?? 0, heldMark?.__hwm ?? 0, movedMark?.__hwm ?? 0), __gen: Math.max(row?.gen ?? 0, gen), __sid: sessionId, __principal: attributed, ...(heldMark?.__lineage === "lost" || movedMark?.__lineage === "lost" ? { __lineage: "lost" } : {}), ...(row === null && heldMark?.__arrival !== undefined ? { __arrival: heldMark.__arrival } : {}), }; this.writeMark(this.markPathFor(sessionId, undefined), mark); if (row !== null) atomicWriteFile(join(this.dir, "tmp"), this.pathFor(sessionId, undefined), JSON.stringify({ ...row, __sid: sessionId, __principal: attributed })); unlinkIfPresent(fromRow); unlinkIfPresent(fromMark); return undefined; } async getRules(sessionId, principal) { return this.read(sessionId, sessionRulesPrincipalOf(principal, "getRules")); } async putRules(sessionId, given, rules, opts) { this.latch.refuse("FileSessionPolicyStore.putRules"); const principal = sessionRulesPrincipalOf(given, "putRules"); const prior = this.read(sessionId, principal); const clean = judgeSessionRulesWrite(prior, rules, opts, this.mountedToolNames); const mark = this.readMark(sessionId, principal); if (mark?.__lineage === "lost") { throw new SessionPolicyError("corrupt", `session rules for ${JSON.stringify(sessionId)} have no lineage evidence (the erase left a lost-lineage mark) — refusing to restart the key's lineage by guessing; delete the mark to restart it`); } const floor = Math.max(prior?.rev ?? 0, mark?.__hwm ?? 0); const gen = prior !== null ? (prior.gen ?? 0) : (mark?.__gen ?? 0); const next = { ...clean, rev: floor + 1, gen }; const attributedPrincipal = (principal ?? this.anonymousAlias) ?? null; this.writeMarkFile(this.markPathFor(sessionId, principal), next.rev, sessionId, attributedPrincipal, Math.max(gen, mark?.__gen ?? 0)); atomicWriteFile(join(this.dir, "tmp"), this.pathFor(sessionId, principal), JSON.stringify({ ...next, __sid: sessionId, __principal: attributedPrincipal })); return next; } async listBySession(sessionId) { const closedRead = this.foldEmptyPrincipalKey(sessionId); const folded = closedRead === undefined ? undefined : new Set([`${sessionPolicyStemFor(sessionId, "", undefined)}.json`, basename(this.pathFor(sessionId, undefined))]); const files = this.sweepEntries(sessionId); const out = []; if (closedRead !== undefined && closedRead.unmoved !== null) out.push({ principal: this.anonymousAlias ?? undefined, rules: closedRead.unmoved }); for (const file of files) { if (file.endsWith(MARK_SUFFIX)) continue; if (!file.endsWith(".json")) continue; if (folded?.has(file) === true) continue; const full = join(this.dir, file); const judged = this.readRowFile(full); if (judged === null) continue; const { owner } = this.ownerOf(sessionId, file, "row" in judged ? judged.row : undefined); if (owner === undefined) { this.disclose({ sessionId, path: full, reason: "corrupt" in judged ? judged.corrupt.reason : "session metadata is not a string" }); continue; } if (owner.sessionId !== sessionId) continue; if ("corrupt" in judged) this.refuseDamaged(sessionId, undefined, full, judged.corrupt.grade, judged.corrupt.reason); if (typeof judged.row.__sid !== "string") this.refuseDamaged(sessionId, undefined, full, "malformed", "session metadata is not a string"); const shaped = judgeSessionPolicyRowShape(judged.row); if ("corrupt" in shaped) this.refuseDamaged(sessionId, undefined, full, shaped.corrupt.grade, shaped.corrupt.reason); const attributed = judged.row.__principal; if (attributed !== undefined && attributed !== null && typeof attributed !== "string") { this.refuseDamaged(sessionId, undefined, full, "malformed", "principal metadata is not a string"); } out.push({ principal: attributed ?? undefined, rules: shaped.rules }); } return out; } async deleteBySession(sessionId) { this.latch.refuse("FileSessionPolicyStore.deleteBySession"); for (const file of this.sweepEntries(sessionId)) { if (file.endsWith(MARK_SUFFIX)) continue; if (!file.endsWith(".json")) continue; const full = join(this.dir, file); const judged = this.readRowFile(full); if (judged === null) continue; const row = "row" in judged ? judged.row : undefined; const markPath = join(this.dir, `${file.slice(0, -".json".length)}${MARK_SUFFIX}`); const { owner, markRead } = this.ownerOf(sessionId, file, row); if (owner !== undefined) { if (owner.sessionId === sessionId) this.eraseRow(full, markPath, sessionId, owner.principal ?? null, row, markRead); continue; } if (!("corrupt" in judged) || judged.corrupt.grade !== "unparseable") continue; const tornRead = markRead ?? this.sweepMark(sessionId, markPath); if ("corrupt" in tornRead) { this.disclose({ sessionId, path: markPath, reason: `erase purged a torn row whose high-water mark is corrupt (it ${tornRead.corrupt.reason}); the mark is left for the operator` }); } else if (tornRead.mark === null) { this.writeMark(markPath, { __hwm: 0, __gen: 0, __lineage: "lost" }); this.disclose({ sessionId, path: full, reason: "erase purged a torn row that had no high-water mark: the key's lineage is lost, writes are refused until the mark is deleted" }); } else { const { __arrival, ...found } = tornRead.mark; this.writeMark(markPath, { ...found, __gen: (found.__gen ?? 0) + 1 }); } unlinkIfPresent(full); } } eraseRow(full, markPath, sessionId, principal, row, observed) { const markRead = observed ?? this.sweepMark(sessionId, markPath); if (!("corrupt" in markRead)) { const rowRev = typeof row?.rev === "number" && Number.isFinite(row.rev) ? row.rev : 0; const rowGen = typeof row?.gen === "number" && Number.isInteger(row.gen) && row.gen >= 0 ? row.gen : 0; const next = eraseStepOf(markRead.mark === null ? null : { rev: markRead.mark.__hwm, gen: markRead.mark.__gen ?? 0 }, { rev: rowRev, gen: rowGen }); this.writeMarkFile(markPath, next.rev, sessionId, principal, next.gen); } unlinkIfPresent(full); } async rekeyPrincipal(input) { this.latch.refuse("FileSessionPolicyStore.rekeyPrincipal"); return rekeySessionPolicyDirectory(this.dir, readPrincipalRekeyInput("SessionPolicyStore.rekeyPrincipal", input), this.anonymousAlias); } } function sameRuleContent(a, b) { const canonical = (r) => JSON.stringify({ toolAllow: r.toolAllow, toolDeny: r.toolDeny, allowDirs: r.allowDirs, grammar: r.grammar, operatorRules: r.operatorRules }, (_k, v) => v !== null && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))) : v); return canonical(a) === canonical(b); } function unlinkIfPresent(path) { try { unlinkSync(path); } catch (err) { if (err.code !== "ENOENT") throw err; } }