@sema-agent/core
Version:
Stateless, task-oriented AI agent core
142 lines (141 loc) • 6.2 kB
JavaScript
import { execFile } from "node:child_process";
import { lstat, readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { inheritedHostEnv } from "../core/secret-env.js";
import { ANONYMOUS_SCOPE } from "../core/isolation-scope.js";
import { CC_PEER_ROW_FILE_RE } from "./cc-peer-wire.js";
import { judgePeerRecordFile, PEER_SESSION_RECORD_SCHEMA_VERSION, peerRowFault, readPeerSessionRecord, vetPeerRegistryDirectory, } from "./peer-directory.js";
export const CC_UNNAMED_SESSION_NAME = "(unnamed session)";
export function ccProcessStartToken(pid) {
if (process.platform === "win32" || !Number.isInteger(pid) || pid <= 0)
return Promise.resolve(undefined);
return new Promise((resolve) => {
execFile("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 1_000, env: { ...inheritedHostEnv("scrub"), LC_ALL: "C", TZ: "UTC" } }, (err, stdout) => {
const token = err === null ? String(stdout).trim() : "";
resolve(token === "" ? undefined : token);
});
});
}
export const defaultCcProcessProbe = {
processExists(pid) {
try {
process.kill(pid, 0);
return true;
}
catch (e) {
return e.code === "EPERM";
}
},
processStartToken: ccProcessStartToken,
};
export class CcPeerDirectoryError extends Error {
code;
path;
constructor(code, path) {
super(`the reference agent's session registry is not a directory this engine can trust (${code}: ${path})`);
this.name = "CcPeerDirectoryError";
this.code = code;
this.path = path;
}
}
const FEATURE_RE = /^[a-z0-9_]{1,32}$/;
const MAX_FEATURES = 16;
export function createCcPeerDirectory(opts) {
const scope = opts.scope ?? ANONYMOUS_SCOPE;
const probe = opts.probe ?? defaultCcProcessProbe;
const selfUid = opts.uid ?? (typeof process.getuid === "function" ? process.getuid() : undefined);
const skip = (file, reason, detail) => {
try {
opts.onSkip?.(file, reason, detail);
}
catch {
}
};
const readRow = async (file, pid) => {
const path = join(opts.registryDir, file);
let text;
try {
const st = await lstat(path);
const judged = judgePeerRecordFile({ uid: st.uid, mode: st.mode, isFile: st.isFile(), size: st.size }, selfUid, opts.platform);
if (!judged.ok)
return void skip(file, judged.code);
text = await readFile(path, "utf8");
}
catch (e) {
return void skip(file, "unreadable", e.code);
}
let row;
try {
row = JSON.parse(text);
}
catch {
return void skip(file, "not_json");
}
if (row === null || typeof row !== "object" || Array.isArray(row))
return void skip(file, "invalid_row", "not an object");
const r = row;
const sockPath = r["messagingSocketPath"];
if (typeof sockPath !== "string" || sockPath === "")
return void skip(file, "no_socket");
if (!probe.processExists(pid))
return void skip(file, "not_live", "no such process");
const procStart = typeof r["procStart"] === "string" ? r["procStart"] : undefined;
if (procStart !== undefined) {
const now = await probe.processStartToken(pid);
if (now !== undefined && now !== procStart)
return void skip(file, "not_live", "the pid belongs to another process now");
}
const finite = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
const startedAt = finite(r["startedAt"]) ?? 0;
const name = typeof r["name"] === "string" ? r["name"] : CC_UNNAMED_SESSION_NAME;
const features = Array.isArray(r["peerFeatures"]) ? r["peerFeatures"].filter((f) => typeof f === "string" && FEATURE_RE.test(f)).slice(0, MAX_FEATURES) : undefined;
const tempo = r["tempo"];
const agent = typeof r["agent"] === "string" ? r["agent"] : undefined;
const raw = {
schemaVersion: PEER_SESSION_RECORD_SCHEMA_VERSION,
sessionId: r["sessionId"],
occupant: r["occupant"] === undefined ? null : r["occupant"],
scope,
name,
pid,
...(typeof r["cwd"] === "string" ? { cwd: r["cwd"] } : {}),
startedAt,
updatedAt: finite(r["updatedAt"]) ?? startedAt,
liveness: "live",
...(tempo === "active" || tempo === "idle" || tempo === "blocked" ? { tempo } : {}),
...(agent !== undefined ? { agent } : {}),
...(typeof r["entrypoint"] === "string" ? { entrypoint: r["entrypoint"] } : {}),
...(typeof r["peerProtocol"] === "number" ? { peerProtocol: r["peerProtocol"] } : {}),
...(features !== undefined ? { peerFeatures: features } : {}),
sockPath,
where: "this_machine",
};
const read = readPeerSessionRecord(raw);
if (!read.ok)
throw peerRowFault(raw, read);
return read.record;
};
return {
async listPeerSessions(access) {
if (access.scope !== scope)
return [];
const verdict = await vetPeerRegistryDirectory(opts.registryDir, { ...(selfUid !== undefined ? { uid: selfUid } : {}), ...(opts.platform !== undefined ? { platform: opts.platform } : {}) });
if (!verdict.ok)
throw new CcPeerDirectoryError(verdict.code, verdict.path);
const names = await readdir(opts.registryDir);
const rows = [];
for (const file of names.sort()) {
const m = CC_PEER_ROW_FILE_RE.exec(file);
if (m === null)
continue;
const pid = Number.parseInt(m[1], 10);
if (String(pid) !== m[1] || pid <= 0)
continue;
const record = await readRow(file, pid);
if (record !== undefined)
rows.push(record);
}
return rows;
},
};
}