UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

464 lines (463 loc) • 23.5 kB
import { randomBytes, timingSafeEqual } from "node:crypto"; import { redactThenCut } from "../core/untrusted-egress.js"; import { createServer, Socket } from "node:net"; import { chmod, lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path"; import { CrossSessionCodecError, decodeCcPeerFrame } from "./cross-session-envelope.js"; import { peerSendVerdictSeverity } from "./cross-session-judge.js"; import { peerAxisToken, peerWireHopToken, resolvePeerLaneConfig } from "./peer-admission.js"; import { judgePeerRecordFile, peerSessionBoxHandle, vetPeerRegistryDirectory } from "./peer-directory.js"; import { defaultCcProcessProbe } from "./cc-peer-directory.js"; import { CC_PEER_FIRST_LINE_DEADLINE_MS, CC_PEER_KEY_FILE_MAX_BYTES, CC_PEER_KEY_FILE_RE, CC_PEER_LINE_MAX_CHARS, CC_PEER_SEND_TIMEOUT_MS, CC_PEER_SOCKET_PATH_MAX_BYTES, CC_PEER_TOKEN_RE, ccPeerAddress, ccPeerKeyFileName, ccPeerSocketDigest, ccRegistrationRow, encodeCcAuthLine, encodeCcNudgeLine, encodeCcUserLine, parseCcPeerLine, } from "./cc-peer-wire.js"; export class CcPeerChannelError extends Error { code; path; constructor(code, message, path) { super(message); this.name = "CcPeerChannelError"; this.code = code; if (path !== undefined) this.path = path; } } const LISTENING_SLOTS = new Set(); const NUDGE_TIMEOUT_MS = 1_000; const STALE_PROBE_MS = 250; function errCode(e) { const c = e?.code; return typeof c === "string" ? c : undefined; } async function writeFileAtomic0600(path, text) { const tmp = `${path}.tmp.${randomBytes(6).toString("hex")}`; try { await writeFile(tmp, text, { mode: 0o600, flag: "wx" }); await rename(tmp, path); } catch (e) { await unlink(tmp).catch(() => undefined); throw e; } } function probeSocket(path, ms) { return new Promise((resolve) => { const s = new Socket(); const done = (answer) => { s.destroy(); resolve(answer); }; s.setTimeout(ms, () => done("unknown")); s.once("connect", () => done("live")); s.once("error", (e) => done(errCode(e) === "ECONNREFUSED" ? "stale" : "unknown")); s.connect({ path }); }); } export function createCcUdsPeerChannel(opts) { const platform = opts.platform ?? process.platform; const pid = opts.pid ?? process.pid; const probe = opts.probe ?? defaultCcProcessProbe; const now = opts.now ?? Date.now; const uid = opts.uid ?? (typeof process.getuid === "function" ? process.getuid() : undefined); const vetOpts = { ...(uid !== undefined ? { uid } : {}), platform }; let listening; const ensureVettedDir = async (dir) => { try { await lstat(dir); } catch (e) { if (errCode(e) !== "ENOENT") throw e; await mkdir(dir, { recursive: true, mode: 0o700 }); } const verdict = await vetPeerRegistryDirectory(dir, vetOpts); if (!verdict.ok) throw new CcPeerChannelError(verdict.code, `the directory ${verdict.path} is not one this engine can trust (${verdict.code}) — the socket lane was not opened`, verdict.path); }; const vetPeerSocket = async (address) => { if (platform === "win32") return { ok: false, code: "peer_send.not_reachable", text: "the reference agent's socket lane is not available on this platform" }; if (!isAbsolute(address) || Buffer.byteLength(address) > CC_PEER_SOCKET_PATH_MAX_BYTES) return { ok: false, code: "peer_send.invalid_target", text: `${JSON.stringify(address.slice(0, 120))} is not a usable local socket address` }; const verdict = await vetPeerRegistryDirectory(dirname(address), vetOpts); if (!verdict.ok) return { ok: false, code: "peer_send.invalid_target", text: `the peer's socket directory is not one this engine trusts (${verdict.code}: ${verdict.path})` }; let st; try { st = await lstat(address); } catch { return { ok: false, code: "peer_send.not_reachable", text: "no socket exists at that address (the session is gone)" }; } if (st.isSymbolicLink()) return { ok: false, code: "peer_send.invalid_target", text: "the peer's socket address is a link" }; if (!st.isSocket()) return { ok: false, code: "peer_send.invalid_target", text: "the peer's address is not a socket" }; return { ok: true }; }; const readPeerToken = async (address) => { const digest = ccPeerSocketDigest(address); let names; try { names = await readdir(opts.registryDir); } catch { return undefined; } const candidates = names .map((n) => ({ n, m: CC_PEER_KEY_FILE_RE.exec(n) })) .filter((c) => c.m !== null && c.m[2] === digest) .map((c) => ({ file: c.n, pid: Number.parseInt(c.m[1], 10) })) .sort((a, b) => Number(probe.processExists(b.pid)) - Number(probe.processExists(a.pid))); for (const c of candidates) { const path = join(opts.registryDir, c.file); try { const st = await lstat(path); if (!judgePeerRecordFile({ uid: st.uid, mode: st.mode, isFile: st.isFile(), size: st.size }, uid, platform).ok || st.size > CC_PEER_KEY_FILE_MAX_BYTES) continue; const parsed = JSON.parse(await readFile(path, "utf8")); const token = parsed !== null && typeof parsed === "object" ? parsed["peerToken"] : undefined; if (typeof token === "string" && CC_PEER_TOKEN_RE.test(token)) return token; } catch { } } return undefined; }; const send = (address, payload, timeoutMs) => new Promise((resolve) => { const sock = new Socket(); let written = false; let settled = false; const settle = (v) => { if (settled) return; settled = true; sock.destroy(); resolve(v); }; sock.setTimeout(timeoutMs, () => settle(written ? { ok: false, code: "peer_send.send_uncertain", text: "the frame was written but the connection did not close in time — it may have arrived" } : { ok: false, code: "peer_send.timeout", text: `the peer did not accept the connection within ${timeoutMs} ms` })); sock.once("error", (e) => { const c = errCode(e); if (written) return settle({ ok: false, code: "peer_send.send_uncertain", text: `the frame was written, then the connection failed (${c ?? "error"}) — it may have arrived` }); if (c === "ENOENT") return settle({ ok: false, code: "peer_send.not_reachable", text: "no socket exists at that address (the session is gone)" }); if (c === "ECONNREFUSED") return settle({ ok: false, code: "peer_send.stale_socket", text: "the socket file is there but nothing is listening on it (the session ended)" }); if (c === "EAGAIN" || c === "EBUSY") return settle({ ok: false, code: "peer_send.socket_busy", text: "the peer's socket is momentarily busy — retry shortly" }); return settle({ ok: false, code: "peer_send.other", text: `the connection failed (${c ?? "error"})` }); }); sock.once("connect", () => { sock.write(payload, () => { written = true; sock.end(); }); }); sock.once("close", (hadError) => { if (!hadError) settle(written ? { ok: true } : { ok: false, code: "peer_send.send_uncertain", text: "the connection closed before the frame was confirmed written" }); }); sock.connect({ path: address }); }); const prepareSocketPath = async (socketPath) => { await ensureVettedDir(dirname(socketPath)); await ensureVettedDir(opts.registryDir); let existing; try { existing = await lstat(socketPath); } catch (e) { if (errCode(e) !== "ENOENT") throw e; } if (existing === undefined) return; const inUse = (why) => new CcPeerChannelError("address_in_use", `${socketPath} is in use (${why}) — the socket lane was not opened`, socketPath); if (!existing.isSocket()) throw inUse("it is not a socket"); if (uid !== undefined && existing.uid !== uid) throw inUse("another user's socket"); const state = await probeSocket(socketPath, STALE_PROBE_MS); if (state !== "stale") throw inUse(state === "live" ? "a process listens there" : "it could not be proven stale"); const again = await lstat(socketPath).catch(() => undefined); if (again === undefined) return; if (again.ino !== existing.ino || again.dev !== existing.dev) throw inUse("it changed while it was probed"); await unlink(socketPath); }; const refusal = (code, text) => ({ ok: false, code, severity: peerSendVerdictSeverity(code), message: text }); return { async listen(self) { if (platform === "win32") throw new CcPeerChannelError("unsupported_platform", "the reference agent's socket lane (its named-pipe arm) is not implemented on this platform — the socket lane was not opened"); if (listening !== undefined) throw new CcPeerChannelError("already_listening", `this channel already listens at ${listening.address}`); if (self.occupant !== null && (typeof self.occupant !== "string" || self.occupant === "")) { throw new TypeError("PeerChannel.listen: self.occupant must be the session row's occupant (its SessionMetadata.incarnation, a non-empty string) or null when the row carries no token"); } const socketPath = opts.socketPath; if (!isAbsolute(socketPath) || Buffer.byteLength(socketPath) > CC_PEER_SOCKET_PATH_MAX_BYTES) { throw new CcPeerChannelError("socket_path_too_long", `the socket path must be absolute and at most ${CC_PEER_SOCKET_PATH_MAX_BYTES} bytes (got ${Buffer.byteLength(socketPath)})`, socketPath); } const box = peerSessionBoxHandle(self.sessionId); const laneConfig = resolvePeerLaneConfig(opts.lane); const slot = `${pid}\u0000${resolvePath(opts.registryDir)}`; if (LISTENING_SLOTS.has(slot)) throw new CcPeerChannelError("already_listening", `this process already listens through ${opts.registryDir} (its key file and registry row are named by the pid)`); LISTENING_SLOTS.add(slot); const release = (e) => { LISTENING_SLOTS.delete(slot); throw e; }; await prepareSocketPath(socketPath).catch(release); const token = randomBytes(16).toString("hex"); const tokenBytes = Buffer.from(token, "utf8"); const tokenMatches = (t) => { if (t === undefined) return false; const b = Buffer.from(t, "utf8"); return b.length === tokenBytes.length && timingSafeEqual(b, tokenBytes); }; const emit = (event) => { try { self.onEvent?.(event); } catch { } }; const drop = (reason, detail) => emit({ kind: "dropped", reason, ...(detail !== undefined ? { detail } : {}) }); let chain = Promise.resolve(); let pending = 0; const enqueue = (work) => { if (pending >= laneConfig.maxQueuedPeerMessages) return drop("box_full", `${pending} frames already waiting for the box`); pending++; chain = chain .then(work) .catch((e) => drop("append_failed", e instanceof Error ? redactThenCut(e.message, 200) : "error")) .then(() => { pending--; }); }; const appendUser = async (line) => { if (line.toSession !== undefined && line.toSession !== self.sessionId) return drop("session_mismatch"); if (line.attachments) return drop("unhandled_frame", "file_attachments"); let queued = 0; try { queued = await opts.mailbox.peekCount(self.scope, box); } catch { } if (queued >= laneConfig.maxQueuedPeerMessages) return drop("box_full", `${queued} queued`); const decoded = decodeCcPeerFrame(line.content); const fields = decoded.ok ? decoded.fields : {}; const body = decoded.ok ? decoded.body : line.content; const peerMeta = { ...(fields.fromSession !== undefined ? { fromSession: fields.fromSession, senderKey: peerAxisToken(self.scope, "s", fields.fromSession) } : {}), ...(fields.fromMode !== undefined ? { fromMode: fields.fromMode } : {}), kind: "peer_message", ...(self.occupant !== null ? { occupant: self.occupant } : {}), }; const from = fields.fromName ?? line.from; const seq = await opts.mailbox.append(self.scope, box, { ...(from !== undefined ? { from } : {}), content: body, sentAt: now(), hopChain: fields.hopChain !== undefined ? [...fields.hopChain] : [], peerMeta }); emit({ kind: "appended", seq }); }; const connections = new Set(); const deadlineMs = opts.firstLineDeadlineMs ?? CC_PEER_FIRST_LINE_DEADLINE_MS; const server = createServer({ allowHalfOpen: true }, (sock) => { connections.add(sock); sock.setEncoding("utf8"); let timer = setTimeout(() => { timer = undefined; drop("first_line_deadline"); sock.destroy(); }, deadlineMs); timer.unref(); const clear = () => { if (timer !== undefined) clearTimeout(timer); timer = undefined; }; let authed = false; let buf = ""; const handle = (raw) => { if (raw.trim() === "") { if (authed) return true; drop("unauthenticated", "a blank line"); return false; } const line = parseCcPeerLine(raw); if (!authed) { if (line.kind !== "auth") { drop("unauthenticated", line.kind === "malformed" ? line.why : `a '${line.kind}' line`); return false; } if (!tokenMatches(line.token)) { drop("bad_token"); return false; } authed = true; return true; } switch (line.kind) { case "auth": return true; case "malformed": drop("malformed_line", line.why); return true; case "unhandled": drop("unhandled_frame", line.action !== undefined ? `${line.type}:${line.action}` : line.type); return true; case "nudge": enqueue(async () => { emit({ kind: "nudged" }); try { self.onNudge?.(); } catch { } }); return true; case "user": enqueue(() => appendUser(line)); return true; } }; sock.on("data", (chunk) => { buf += chunk; if (buf.length > CC_PEER_LINE_MAX_CHARS) { drop("line_too_long"); buf = ""; sock.destroy(); return; } for (let nl = buf.indexOf("\n"); nl !== -1; nl = buf.indexOf("\n")) { const raw = buf.slice(0, nl); buf = buf.slice(nl + 1); clear(); if (!handle(raw)) { buf = ""; sock.destroy(); return; } } }); sock.on("end", () => { if (buf.trim() !== "" && !sock.destroyed) { clear(); handle(buf); } buf = ""; sock.end(); }); sock.on("error", () => undefined); sock.on("close", () => { clear(); connections.delete(sock); }); }); server.on("error", () => undefined); await new Promise((resolve, reject) => { const onError = (e) => reject(errCode(e) === "EADDRINUSE" ? new CcPeerChannelError("address_in_use", `another process listens at ${socketPath}`, socketPath) : e); server.once("error", onError); server.listen(socketPath, () => { server.removeListener("error", onError); resolve(); }); }).catch(release); server.unref(); const keyPath = join(opts.registryDir, ccPeerKeyFileName(pid, socketPath)); const rowPath = join(opts.registryDir, `${pid}.json`); let closed = false; const close = async () => { if (closed) return; closed = true; listening = undefined; LISTENING_SLOTS.delete(slot); for (const s of connections) s.destroy(); connections.clear(); await new Promise((resolve) => server.close(() => resolve())); await unlink(socketPath).catch(() => undefined); await unlink(keyPath).catch(() => undefined); await unlink(rowPath).catch(() => undefined); await chain.catch(() => undefined); }; try { await chmod(socketPath, 0o600); const procStart = await probe.processStartToken(pid); await writeFileAtomic0600(keyPath, JSON.stringify({ peerToken: token, ...(procStart !== undefined ? { procStart } : {}) })); const at = now(); const reg = opts.registration ?? {}; await writeFileAtomic0600(rowPath, JSON.stringify(ccRegistrationRow({ pid, sessionId: self.sessionId, socketPath, startedAt: reg.startedAt ?? at, updatedAt: at, ...(reg.cwd !== undefined ? { cwd: reg.cwd } : {}), ...(reg.name !== undefined ? { name: reg.name } : {}), ...(reg.entrypoint !== undefined ? { entrypoint: reg.entrypoint } : {}), ...(procStart !== undefined ? { procStart } : {}), ...(typeof opts.mailbox.identity === "string" && opts.mailbox.identity !== "" ? { storeIdentity: opts.mailbox.identity } : {}), occupant: self.occupant, }))); } catch (e) { await close(); throw new CcPeerChannelError("publish_failed", `the socket was bound but its key file or registry row could not be published (${errCode(e) ?? (e instanceof Error ? e.message : "error")}) — no peer could authenticate or find it, so the socket lane was closed`, opts.registryDir); } listening = { address: socketPath, sessionId: self.sessionId }; return { address: socketPath, close }; }, async dial(address, message) { const vetted = await vetPeerSocket(address); if (!vetted.ok) return refusal(vetted.code, vetted.text); let line; try { const from = listening !== undefined && message.fromSession === listening.sessionId ? ccPeerAddress(listening.address) : undefined; line = encodeCcUserLine({ fields: { ...(from !== undefined ? { from } : {}), ...(message.fromSession !== undefined ? { fromSession: message.fromSession } : {}), hopChain: message.hopChain.map(peerWireHopToken), ...(message.fromName !== undefined ? { fromName: message.fromName } : {}), ...(message.fromMode !== undefined ? { fromMode: message.fromMode } : {}), }, body: message.body, ...(from !== undefined ? { from } : {}), }); } catch (e) { if (e instanceof CrossSessionCodecError) return refusal("peer_send.other", `the frame could not be spelled (${e.code})`); throw e; } if (encodeCcAuthLine("0".repeat(32)).length + line.length > CC_PEER_LINE_MAX_CHARS) return refusal("peer_send.too_large", `the frame is ${line.length} characters; the peer's line wall is ${CC_PEER_LINE_MAX_CHARS}`); const token = await readPeerToken(address); const sent = await send(address, `${token !== undefined ? encodeCcAuthLine(token) : ""}${line}`, opts.sendTimeoutMs ?? CC_PEER_SEND_TIMEOUT_MS); return sent.ok ? { ok: true, disposition: "delivered", via: "uds" } : refusal(sent.code, sent.text); }, async nudge(address) { try { if (!(await vetPeerSocket(address)).ok) return false; const token = await readPeerToken(address); const sent = await send(address, `${token !== undefined ? encodeCcAuthLine(token) : ""}${encodeCcNudgeLine()}`, opts.nudgeTimeoutMs ?? NUDGE_TIMEOUT_MS); return sent.ok; } catch { return false; } }, }; }