UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

393 lines (392 loc) • 12.9 kB
import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, readlinkSync, renameSync, rmdirSync, statfsSync, unlinkSync } from "node:fs"; import { openSyncUnguarded as openSync, readdirSync, readFileSync } from "./descriptor-seat.js"; import { execFileSync } from "node:child_process"; import { randomBytes } from "node:crypto"; import { hostname } from "node:os"; import { basename, dirname, isAbsolute, join, resolve as resolvePath, sep } from "node:path"; import { inheritedHostEnv } from "../../core/secret-env.js"; import { physicalPathOfExisting } from "../../core/physical-path.js"; import { deliverEngineNotice } from "../../core/engine-notice.js"; export const ANCHOR_DIR = ".anchors"; const LOCAL_FILESYSTEMS = new Map([ [0xef53, "ext4"], [0x1021994, "tmpfs"], [0x58465342, "xfs"], [0x9123683e, "btrfs"], ]); const NAMED_FILESYSTEMS = new Map([ [0x6969, "nfs"], [0xfe534d42, "smb2"], [0xff534d42, "cifs"], [0xc36400, "ceph"], [0x65735546, "fuse"], [0x1021997, "9p"], [0x6a656a63, "virtiofs"], [0x794c7630, "overlay"], ]); const ANCHOR_NAME = /^p\.[0-9a-f]{32}$/; const DECIMAL = /^(0|[1-9][0-9]*)$/; const BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"; const UNFINISHED_ANCHOR_TTL_MS = 60 * 60 * 1000; const ANCHOR_CHECK_INTERVAL_MS = 30_000; export function readAnchorMember(value) { if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined; const a = value; if (typeof a.name !== "string" || !ANCHOR_NAME.test(a.name)) return undefined; if (typeof a.dev !== "string" || !DECIMAL.test(a.dev) || typeof a.ino !== "string" || !DECIMAL.test(a.ino)) return undefined; if (typeof a.fsType !== "number" || !Number.isSafeInteger(a.fsType)) return undefined; if (a.bootId !== null && (typeof a.bootId !== "string" || a.bootId === "")) return undefined; return { name: a.name, dev: a.dev, ino: a.ino, fsType: a.fsType, bootId: a.bootId }; } function filesystemTypeOf(path) { if (typeof statfsSync !== "function") return undefined; try { return Number(statfsSync(path).type); } catch { return undefined; } } export function nonLocalFilesystemOf(dir) { if (process.platform !== "linux") return undefined; const type = filesystemTypeOf(dir); if (type === undefined || LOCAL_FILESYSTEMS.has(type)) return undefined; return NAMED_FILESYSTEMS.get(type) ?? `0x${type.toString(16)}`; } let cachedBootId; function ownBootId() { if (cachedBootId === undefined) { try { const id = readFileSync(BOOT_ID_PATH, "utf8").trim(); cachedBootId = id === "" ? null : id; } catch { cachedBootId = null; } } return cachedBootId; } function anchorIdentityAt(path) { let st; try { st = lstatSync(path, { bigint: true }); } catch (err) { return err.code === "ENOENT" ? "anchor_missing" : "anchor_unreadable"; } return st.isFIFO() ? { dev: st.dev, ino: st.ino } : "anchor_not_fifo"; } function someoneHoldsOpen(path, expect) { let fd; try { fd = openSync(path, constants.O_WRONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0)); } catch (err) { return err.code === "ENXIO" ? "closed" : "probe_refused"; } try { const st = fstatSync(fd, { bigint: true }); return st.isFIFO() && st.dev === expect.dev && st.ino === expect.ino ? "open" : "anchor_replaced"; } catch { return "anchor_replaced"; } finally { try { closeSync(fd); } catch { } } } export function readAnchor(lockDir, anchor, recordHost) { const path = join(lockDir, ANCHOR_DIR, anchor.name); const expect = { dev: BigInt(anchor.dev), ino: BigInt(anchor.ino) }; const sameIdentity = () => { const id = anchorIdentityAt(path); if (typeof id === "string") return id; return id.dev === expect.dev && id.ino === expect.ino ? true : "anchor_replaced"; }; const first = sameIdentity(); if (first !== true) return first; const probed = someoneHoldsOpen(path, expect); if (probed !== "closed") return probed; const boot = ownBootId(); if (boot === null || anchor.bootId === null) return "kernel_unknown"; if (boot !== anchor.bootId) return "kernel_differs"; const host = hostname(); if (host === "") return "host_unknown"; if (recordHost !== host) return "host_differs"; const type = filesystemTypeOf(path); if (type === undefined) return "filesystem_unknown"; if (!LOCAL_FILESYSTEMS.has(type)) return "filesystem_not_local"; if (type !== anchor.fsType) return "filesystem_differs"; const again = sameIdentity(); return again === true ? "closed" : again; } const heldAnchors = new Map(); let checkTimer; let unavailableSaid = false; function announceUnavailable(dir, reason) { if (unavailableSaid) return; unavailableSaid = true; deliverEngineNotice(undefined, { code: "store.process_anchor_unavailable", message: `[sema] file store: no process anchor could be made for the locks this process takes (${reason}, first at ${dir}); its locks are ` + `judged by the process table alone, so a lock it leaves behind in another container's view stays refused until removed by hand.`, detail: { path: dir, reason }, }); } function announceLost(entry, reason) { deliverEngineNotice(undefined, { code: "store.process_anchor_lost", message: `[sema] file store: this process's anchor for the locks in ${entry.dir} is no longer the pipe it opened (${reason}); it treats ` + `those locks as lost and refuses every later write under them (store.lock_lost) — restart the process.`, detail: { path: entry.path, reason }, }); } function verify(entry) { if (entry.lost) return false; let reason; try { const st = fstatSync(entry.fd, { bigint: true }); if (st.dev !== entry.dev || st.ino !== entry.ino) reason = "replaced"; } catch { reason = "closed"; } if (reason === undefined) return true; entry.lost = true; announceLost(entry, reason); return false; } function syncTimer() { if (heldAnchors.size > 0 && checkTimer === undefined) { checkTimer = setInterval(() => { for (const entry of heldAnchors.values()) verify(entry); }, ANCHOR_CHECK_INTERVAL_MS); checkTimer.unref?.(); } else if (heldAnchors.size === 0 && checkTimer !== undefined) { clearInterval(checkTimer); checkTimer = undefined; } } function placeUnfinishedPipe(anchors, unfinished) { try { mkdirSync(anchors, { recursive: true, mode: 0o700 }); } catch { return "filesystem_unknown"; } const type = filesystemTypeOf(anchors); if (type === undefined) return "filesystem_unknown"; if (!LOCAL_FILESYSTEMS.has(type)) return "filesystem_not_local"; try { execFileSync("mkfifo", ["-m", "600", unfinished], { stdio: ["ignore", "ignore", "ignore"], timeout: 2_000, env: { ...inheritedHostEnv("scrub"), LC_ALL: "C", LANG: "C" }, }); } catch { return "mkfifo"; } return type; } function removeIfEmpty(anchors) { try { rmdirSync(anchors); } catch { } } function makeAnchor(dir) { const dirType = filesystemTypeOf(dir); if (dirType === undefined || !LOCAL_FILESYSTEMS.has(dirType)) { announceUnavailable(dir, dirType === undefined ? "filesystem_unknown" : "filesystem_not_local"); return undefined; } const anchors = join(dir, ANCHOR_DIR); const id = randomBytes(16).toString("hex"); const unfinished = join(anchors, `t.${id}`); const path = join(anchors, `p.${id}`); let placed = placeUnfinishedPipe(anchors, unfinished); if (typeof placed === "string" && placed !== "filesystem_not_local" && !existsSync(anchors)) placed = placeUnfinishedPipe(anchors, unfinished); if (typeof placed === "string") { removeIfEmpty(anchors); announceUnavailable(dir, placed); return undefined; } const type = placed; let fd; try { fd = openSync(unfinished, constants.O_RDWR | constants.O_NONBLOCK); } catch { try { unlinkSync(unfinished); } catch { } removeIfEmpty(anchors); announceUnavailable(dir, "open"); return undefined; } try { const st = fstatSync(fd, { bigint: true }); renameSync(unfinished, path); const record = { name: `p.${id}`, dev: st.dev.toString(), ino: st.ino.toString(), fsType: type, bootId: ownBootId() }; return { dir, path, fd, dev: st.dev, ino: st.ino, record, locks: new Set(), refs: 0, lost: false }; } catch { try { closeSync(fd); } catch { } try { unlinkSync(unfinished); } catch { } removeIfEmpty(anchors); announceUnavailable(dir, "rename"); return undefined; } } function dropAnchor(entry) { heldAnchors.delete(entry.dir); syncTimer(); if (!entry.lost) { try { closeSync(entry.fd); } catch { } } const id = anchorIdentityAt(entry.path); if (typeof id !== "string" && id.dev === entry.dev && id.ino === entry.ino) { try { unlinkSync(entry.path); } catch { } } removeIfEmpty(join(entry.dir, ANCHOR_DIR)); } export function holdAnchor(lockPath, lockDir) { if (process.platform !== "linux") return undefined; const dir = physicalPathOfExisting(lockDir); let entry = heldAnchors.get(dir); const fresh = entry === undefined; if (entry === undefined) { entry = makeAnchor(dir); if (entry === undefined) return undefined; heldAnchors.set(dir, entry); syncTimer(); } const held = entry; held.refs += 1; held.locks.add(resolvePath(lockPath)); let released = false; return { record: held.record, fresh, release: () => { if (released) return; released = true; held.locks.delete(resolvePath(lockPath)); held.refs -= 1; if (held.refs <= 0 && heldAnchors.get(held.dir) === held) dropAnchor(held); }, }; } export function lostLockCovering(target) { if (heldAnchors.size === 0) return undefined; const places = [join(physicalPathOfExisting(dirname(target)), basename(target)), physicalPathOfExisting(target)]; let leadsTo; try { if (lstatSync(target).isSymbolicLink()) leadsTo = readlinkSync(target); } catch { } if (leadsTo !== undefined) places.push(physicalPathOfExisting(isAbsolute(leadsTo) ? leadsTo : `${dirname(target)}${sep}${leadsTo}`)); for (const entry of heldAnchors.values()) { const under = entry.dir.endsWith(sep) ? entry.dir : `${entry.dir}${sep}`; if (!places.some((at) => at === entry.dir || at.startsWith(under))) continue; if (!verify(entry)) return [...entry.locks][0] ?? join(entry.dir, "LOCK"); } return undefined; } export function sweepLeftoverAnchors(lockDir, referenced) { const anchors = join(lockDir, ANCHOR_DIR); const own = heldAnchors.get(physicalPathOfExisting(lockDir))?.record.name; let names; try { names = readdirSync(anchors); } catch { return; } for (const name of names) { const path = join(anchors, name); try { const finished = ANCHOR_NAME.test(name); if (!finished && !/^t\.[0-9a-f]{32}$/.test(name)) continue; if (name === own) continue; if (!finished && Date.now() - Number(lstatSync(path).mtimeMs) <= UNFINISHED_ANCHOR_TTL_MS) continue; const id = anchorIdentityAt(path); if (typeof id === "string") continue; if (someoneHoldsOpen(path, id) !== "closed") continue; if (finished && referenced().has(name)) continue; const again = anchorIdentityAt(path); if (typeof again !== "string" && again.dev === id.dev && again.ino === id.ino) unlinkSync(path); } catch { } } removeIfEmpty(anchors); }