UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

253 lines (252 loc) • 11.4 kB
import { randomBytes } from "node:crypto"; import { readdirSync, readFileSync } from "./descriptor-seat.js"; import { dirname, join, sep } from "node:path"; import { physicalPathOf } from "../../core/physical-path.js"; import { processCensus, processFingerprint, uncheckableProcessText } from "../../core/process-identity.js"; import { receiptRefusal } from "../../core/own-property-receipt.js"; import { describeRejectedValue } from "../../core/tool-search-setting.js"; import { ANCHOR_DIR, nonLocalFilesystemOf, readAnchor, readAnchorMember } from "./process-anchor.js"; export const STORE_LOCK_NAMES = Object.freeze(["LOCK", "ADOPTION-LOCK", "PERMISSION-RULES-WRITER-LOCK"]); const RECLAIM_GATE_NAME = /^(?:LOCK|ADOPTION-LOCK|PERMISSION-RULES-WRITER-LOCK)(?:\.claim\.[1-9][0-9]*)+$/; export const LOCK_RECORD_VERSION = 2; export function serializeLockRecord(anchor) { const fp = processFingerprint(); const nonce = randomBytes(16).toString("hex"); mintedNonces.add(nonce); return JSON.stringify({ v: LOCK_RECORD_VERSION, pid: fp.pid, startedAtMs: fp.startedAtMs, startedSinceBootMs: fp.startedSinceBootMs, host: fp.host, ...(fp.pidNs !== undefined ? { pidNs: fp.pidNs } : {}), ...(anchor !== undefined ? { anchor } : {}), nonce, }); } const mintedNonces = new Set(); export function publishedHere(record) { return record.nonce !== undefined && mintedNonces.has(record.nonce); } function parseLockRecord(raw) { if (/^[1-9][0-9]*$/.test(raw)) { const pid = Number.parseInt(raw, 10); return Number.isSafeInteger(pid) ? { record: { pid, startedAtMs: null, startedSinceBootMs: null, host: null, pidNs: null } } : { unread: "bytes" }; } if (!raw.startsWith("{")) return { unread: "bytes" }; let parsed; try { parsed = JSON.parse(raw); } catch { return { unread: "bytes" }; } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { unread: "bytes" }; const rec = parsed; const pid = typeof rec.pid === "number" && Number.isSafeInteger(rec.pid) && rec.pid > 0 ? rec.pid : undefined; if (rec.v !== LOCK_RECORD_VERSION) return pid !== undefined ? { unread: "version", pid } : { unread: "version" }; const wrong = () => (pid !== undefined ? { unread: "member_type", pid } : { unread: "member_type" }); if (pid === undefined) return wrong(); const measure = (key) => { const v = rec[key]; if (v === undefined || v === null) return null; return typeof v === "number" && Number.isFinite(v) ? v : "wrong"; }; const text = (key) => { const v = rec[key]; if (v === undefined || v === null) return null; return typeof v === "string" ? (v === "" ? null : v) : "wrong"; }; const startedAtMs = measure("startedAtMs"); const startedSinceBootMs = measure("startedSinceBootMs"); const host = text("host"); const pidNs = text("pidNs"); if (startedAtMs === "wrong" || startedSinceBootMs === "wrong" || host === "wrong" || pidNs === "wrong") return wrong(); let anchor; if (rec.anchor !== undefined) { anchor = readAnchorMember(rec.anchor); if (anchor === undefined) return wrong(); } const nonce = rec.nonce; if (nonce !== undefined && (typeof nonce !== "string" || !/^[0-9a-f]{32}$/.test(nonce))) return wrong(); return { record: { pid, startedAtMs, startedSinceBootMs, host, pidNs, ...(anchor !== undefined ? { anchor } : {}), ...(nonce !== undefined ? { nonce } : {}) } }; } const singleProcessTableRoots = new Set(); export function holdSingleProcessTableRoot(physicalRoot) { singleProcessTableRoots.add(physicalRoot); } function singleProcessTableRootOf(lockPath) { if (singleProcessTableRoots.size === 0) return undefined; let dir; try { dir = physicalPathOf(dirname(lockPath)); } catch { return undefined; } for (const root of singleProcessTableRoots) { if (dir === root || dir.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)) return root; } return undefined; } export function readLockBytes(lockPath) { let raw; try { raw = readFileSync(lockPath, "utf8").trim(); } catch (err) { if (err.code === "ENOENT") return { state: "absent" }; return { state: "present", raw: "", parsed: { unread: "bytes" } }; } return { state: "present", raw, parsed: parseLockRecord(raw) }; } export function lockRecordOf(bytes) { return bytes.state === "present" && "record" in bytes.parsed ? bytes.parsed.record : undefined; } export function judgeLockBytes(lockPath, bytes, census) { const remove = Object.freeze({ kind: "remove_lock", path: lockPath }); if ("unread" in bytes.parsed) { const { unread, pid } = bytes.parsed; return { reading: reading(lockPath, pid !== undefined ? { state: "unread", pid, why: unread } : { state: "unread", why: unread }, [remove]) }; } const record = bytes.parsed.record; if (publishedHere(record)) return { reading: reading(lockPath, { state: "this_process" }, []) }; let verdict = census.verdict(record); let declaredRoot; if (verdict.state === "uncheckable" && verdict.why === "pid_namespace_unrecorded") { declaredRoot = singleProcessTableRootOf(lockPath); if (declaredRoot !== undefined) verdict = processCensus({ singleProcessTable: true }).verdict(record); } if (verdict.state === "running") { return { reading: reading(lockPath, { state: "running", pid: record.pid, by: "process_table" }, []) }; } const anchor = record.anchor === undefined ? "absent" : readAnchor(dirname(lockPath), record.anchor, record.host); if (anchor === "open") return { reading: reading(lockPath, { state: "running", pid: record.pid, by: "anchor", ...(record.host !== null ? { host: record.host } : {}) }, []) }; if (verdict.state === "gone") { const by = declaredRoot !== undefined ? "declaration" : "process_table"; return { reading: reading(lockPath, { state: "gone", by }, []), ...(declaredRoot !== undefined ? { declaredRoot } : {}) }; } const fsType = record.anchor === undefined ? nonLocalFilesystemOf(dirname(lockPath)) : undefined; const holder = { state: "uncheckable", pid: record.pid, why: verdict.why, anchor, ...(fsType !== undefined ? { fsType } : {}) }; const declarable = verdict.why === "pid_namespace_unrecorded" && declaredRoot === undefined && processCensus({ singleProcessTable: true }).verdict(record).state === "gone"; return { reading: reading(lockPath, holder, declarable ? [remove, Object.freeze({ kind: "declare_single_process_table", root: dirname(lockPath) })] : [remove]) }; } function reading(path, holder, remedies) { return Object.freeze({ path, form: "file", holder: Object.freeze(holder), remedies: Object.freeze([...remedies]) }); } export function readLockAt(lockPath, census = processCensus()) { const bytes = readLockBytes(lockPath); return bytes.state === "absent" ? undefined : judgeLockBytes(lockPath, bytes, census).reading; } export function anchorNamesReferencedIn(dir) { const names = new Set(); for (const name of STORE_LOCK_NAMES) { const record = lockRecordOf(readLockBytes(join(dir, name))); if (record?.anchor !== undefined) names.add(record.anchor.name); } return names; } const UNREAD_TEXT = Object.freeze({ bytes: "its bytes are not a lock record", version: "it was written by a later engine version", member_type: "a member of its record has the wrong type", }); const ANCHOR_TEXT = Object.freeze({ kernel_unknown: "names no boot", kernel_differs: "is from another boot", host_unknown: "cannot be checked (this host has no name)", host_differs: "is from another host", filesystem_unknown: "is on a disk that cannot be read", filesystem_not_local: "is not on a local disk", filesystem_differs: "was made on another disk type", anchor_missing: "is missing", anchor_unreadable: "cannot be read", anchor_not_fifo: "is not a pipe", anchor_replaced: "was replaced", probe_refused: "could not be probed", }); export function lockRefusalClause(reading, where) { const h = reading.holder; let said; if (h === undefined) said = `${where} is held`; else if (h.state === "this_process") said = `${where} is already held by this process`; else if (h.state === "running") said = h.by === "anchor" ? `${where} is held by a live process (pid ${h.pid} in its own process table${h.host !== undefined ? `, on host ${JSON.stringify(h.host)}` : ""})` : `${where} is held by a live process (pid ${h.pid})`; else if (h.state === "gone") said = `${where} was left by a process that is gone`; else if (h.state === "unread") said = `${where} cannot be read: ${UNREAD_TEXT[h.why]}`; else { said = `${where} names pid ${h.pid}, not checkable here: ${uncheckableProcessText(h.why)}`; if (h.anchor === "closed") said += "; its anchor is held by no process"; else if (h.anchor !== "absent" && h.anchor !== "open") said += `; its anchor ${ANCHOR_TEXT[h.anchor]}`; if (h.fsType !== undefined) said += `; on ${h.fsType}, no anchor is made`; } const advice = []; for (const r of reading.remedies) { if (r.kind === "remove_lock") advice.push("if no process uses it, remove it"); else advice.push("declare one process table for its directory"); } return advice.length === 0 ? said : `${said}; ${advice.join(", or ")}`; } const MAX_LOCK_LISTING_DEPTH = 4; export function readDataRootLocks(root) { if (typeof root !== "string" || root === "") { throw receiptRefusal(`readDataRootLocks: the data root must be a non-empty path (got ${describeRejectedValue(root)})`); } const census = processCensus(); const locks = []; const unwalked = []; const walk = (dir, depth) => { let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch (err) { unwalked.push(Object.freeze({ path: dir, code: err.code ?? "unknown" })); return; } entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); for (const entry of entries) { const path = join(dir, entry.name); if (entry.isSymbolicLink()) continue; if (STORE_LOCK_NAMES.includes(entry.name) || RECLAIM_GATE_NAME.test(entry.name)) { const bytes = readLockBytes(path); if (bytes.state === "present") locks.push(judgeLockBytes(path, bytes, census).reading); continue; } if (entry.isDirectory() && entry.name !== ANCHOR_DIR && depth < MAX_LOCK_LISTING_DEPTH) walk(path, depth + 1); } }; walk(root, 0); return Object.freeze({ root, locks: Object.freeze(locks), unwalked: Object.freeze(unwalked) }); }