UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

312 lines • 17 kB
/** * Which session file each generation of the daemon currently holds open. * * Inside one host process the registry's own reservation set is the authority. Across * GENERATIONS it cannot be: during a handoff two hosts are alive at the same time, and the * successor must not open a session file the predecessor is still writing - two writers on * one JSONL interleave partial records and the transcript is silently corrupted. * * So every open publishes a small claim next to the daemon state, and every close removes it. * A claim is evidence, not a lock: it names the process that made it, so a claim whose owner is * gone (a SIGKILLed host, a reboot, a recycled pid with a different start time) is ignored * rather than trusted. The failure mode is therefore "a reopen waits ~2s for a live writer to * finish", never "a session file can never be opened again". * * Liveness alone was not enough evidence for an older claim. A generation that lost the socket stayed * alive holding retained sessions nobody was attached to, and its claims then refused every reopen of * those files for as long as the process existed (#1893). So a claim without the strict-transfer * contract counts while its owner is the generation the pointer names, or while the owner still has a * client attached to that session. * * Attachments are no evidence that a session is quiet: a retained lane runs its turns with no client * attached, and a drain parks every idle session at once, so what a draining generation still holds is * exactly what it is still writing (senpi#7098). A claim this host publishes therefore carries * `strict_transfer: true` and stands for as long as its owner runs; the owner removes it itself once * the session parks or closes. */ import { createHash } from "node:crypto"; import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { processIsLive, processIsRunning, processStartTimeMs, readProcessStartTime, sameProcessStartMs, } from "../../utils/process-identity.js"; import { createHostDaemonPaths, generationPaths, HOST_DAEMON_DIR_ENV, hostDaemonDirectoryPaths, } from "./host-daemon-paths.js"; import { parseJson, readFileOrUndefined } from "./host-daemon-state.js"; import { generationHeartbeatStopped } from "./host-stalled-evidence.js"; import { logUnknownHostIdentity } from "./host-supervisor-log.js"; /** How long a client should wait before retrying a path another generation still holds. */ export const SESSION_PATH_RETRY_AFTER_MS = 2_000; /** One claim per canonical session path, named by its hash so the file name is bounded. */ export function reservationFile(dir, sessionPath) { return join(dir, `${createHash("sha256").update(sessionPath, "utf8").digest("hex").slice(0, 16)}.json`); } /** * The claims of a host serving one ENDPOINT, or none when there is no endpoint to share. A * supervised host is TOLD its daemon directory, because the socket it binds is a private hop rather * than the public endpoint; a bare socket host derives it from what it listens on; a stdio host has * no daemon directory, no successor generation and therefore nothing to publish. */ export function createEndpointReservations(host) { const told = process.env[HOST_DAEMON_DIR_ENV]; const dir = told !== undefined && told.trim() !== "" ? told : host.socket === undefined ? undefined : createHostDaemonPaths({ socket: host.socket, agentDir: host.agentDir }).dir; if (dir === undefined) return undefined; return createSessionPathReservations({ daemonDir: dir, instanceId: host.instanceId, ...(host.publicSocket === undefined ? {} : { publicSocket: host.publicSocket }), ...(host.onFailure ? { onFailure: host.onFailure } : {}), }); } export function createSessionPathReservations(options) { const paths = hostDaemonDirectoryPaths(options.daemonDir); const dir = paths.reservationsDir; const pid = options.pid ?? process.pid; const startTime = readProcessStartTime(pid).then((value) => value ?? null, () => null); const held = new Set(); const updates = new Map(); const report = (message) => options.onFailure?.(message); const publish = async (sessionPath, attached, stillHeld) => { const owner = { instanceId: options.instanceId, ...(options.publicSocket === undefined ? {} : { host_socket: options.publicSocket }), pid, processStartTime: await startTime, sessionPath, attached, strict_transfer: true, }; const file = reservationFile(dir, sessionPath); await mkdir(dir, { recursive: true, mode: 0o700 }); // Written aside and renamed in: a reader never sees half a claim. const staging = `${file}.${pid}.tmp`; await writeFile(staging, `${JSON.stringify(owner)}\n`, { mode: 0o600 }); // A republish that raced the release of the same path must not resurrect the claim: this host // parks a session milliseconds after it detaches, and a loaded event loop can reorder the two. if (stillHeld?.() === false) { await rm(staging, { force: true }); return; } await rename(staging, file); }; return { async holderPids(observedStarts) { const candidates = (await readSessionPathClaims(dir)).map(({ owner }) => owner); const generations = await readdir(paths.generationsDir, { withFileTypes: true }).catch(() => []); for (const generation of generations) { if (!generation.isDirectory()) continue; const record = parseJson(await readFileOrUndefined(join(paths.generationsDir, generation.name, "host-child.pid"))); if (typeof record?.pid !== "number") continue; candidates.push({ pid: record.pid, processStartTime: typeof record.processStartTime === "string" ? record.processStartTime : null, instanceId: generation.name, sessionPath: "", }); } const byPid = new Map(); for (const owner of candidates) { if (owner.pid === process.pid) continue; const owners = byPid.get(owner.pid) ?? []; owners.push(owner); byPid.set(owner.pid, owners); } const live = await Promise.all([...byPid].map(async ([pid, owners]) => { if (!processIsLive(pid)) return undefined; if (observedStarts) { // Only foreign-looking holders need family classification. Their bounded OS // probes were already done by lease validation at this command's admission. if (!observedStarts.has(pid)) return undefined; const observed = observedStarts.get(pid); return owners.some((owner) => { if (owner.processStartTime === null) return false; return sameProcessStartMs(processStartTimeMs(owner.processStartTime), observed); }) ? pid : undefined; } const current = await readProcessStartTime(pid, process.platform, 1_000).catch(() => undefined); // Recorded identities may carry an explicit UTC tag (host-child.pid, #3054); the probe // reads in UTC too (senpi#3067 L1), and legacy local-format records still parse as // local time: compare the parsed instant, never the raw text. const observed = current === undefined ? undefined : processStartTimeMs(current); return observed !== undefined && owners.some((owner) => owner.processStartTime !== null && sameProcessStartMs(processStartTimeMs(owner.processStartTime), observed)) ? pid : undefined; })); return [...new Set(live.filter((value) => value !== undefined))]; }, async claim(sessionPath, attached = true) { const existing = await readOwner(reservationFile(dir, sessionPath)); if (existing && existing.pid !== pid) { const verdict = await standingOwner(existing, paths); if (verdict.kind === "stands") return verdict.owner; const fenced = verdict.kind === "released" || // Documented lazy boundary (AGENTS.md: inline dynamic imports only at documented lazy boundaries): the // lifecycle supervisor imports this module, and the fence module (whose writers read it synchronously) // must stay out of the supervisor's startup graph (test/supervisor-import-graph.test.ts). Only a takeover // of an unprovable claim reaches it. (await import("../../core/session-write-fence.js") .then(({ advanceSessionFence }) => advanceSessionFence(sessionPath)) .then(() => true, (cause) => { report(`session file ${sessionPath} could not be fenced for a takeover (${errorMessage(cause)})`); return false; })); if (!fenced) return { ...existing, current: false }; } try { await publish(sessionPath, attached); held.add(sessionPath); } catch (cause) { // A daemon directory that cannot be written is not a reason to refuse a session: the // in-process reservation still protects this host, and a handoff is the only thing // that loses its guard. Say so once rather than failing the open. report(`session path reservation for ${sessionPath} could not be written (${errorMessage(cause)})`); } return undefined; }, async release(sessionPath) { if (!held.delete(sessionPath)) return; await updates.get(sessionPath); updates.delete(sessionPath); await rm(reservationFile(dir, sessionPath), { force: true }).catch((cause) => { report(`session path reservation for ${sessionPath} could not be removed (${errorMessage(cause)})`); }); }, setAttached(sessionPath, attached) { if (!held.has(sessionPath)) return; const update = (updates.get(sessionPath) ?? Promise.resolve()) .then(() => publish(sessionPath, attached, () => held.has(sessionPath))) .catch((cause) => { report(`session path reservation for ${sessionPath} could not be updated (${errorMessage(cause)})`); }); updates.set(sessionPath, update); }, }; } /** Every claim published in one reservations directory, for a reader pruning or reporting them. */ export async function readSessionPathClaims(dir) { const entries = await readdir(dir).catch(() => []); const claims = []; for (const entry of entries) { if (!entry.endsWith(".json")) continue; const file = join(dir, entry); const owner = await readOwner(file); if (owner) claims.push({ file, owner }); } return claims; } /** * The claim that STANDS against a new open, or nothing when this path may be taken over. * * A strict-transfer claim is honored while its owner runs: its owner drops it when the session parks or * closes, so a claim still on disk is a session that owner is still running (senpi#7098). * * An older claim is honored while its owner is the generation serving the socket, or while that owner * still has a client attached to the session. A superseded older owner that published `attached: false` * is draining (or should be), so its claim is released rather than obeyed. A claim without the flag * predates it and is honored, so a running older generation is never reclaimed from. * * A superseded owner whose identity cannot be PROVEN - no start time was recorded, or none can be read * now - needs one more piece of evidence before it may block an open (#3652). On Windows a terminated * generation leaves its claim behind and the OS hands its pid to an unrelated process; without a * readable start time that stranger would hold the session file for as long as it runs. So such a * claim stands only while its generation still heartbeats: a heartbeat older than the stall-refusal * window is the same "died without cleaning up" verdict `hostLoopStalled` already reaches. A live * host whose probe is merely starved (#1609) keeps heartbeating and keeps its claim; a claim with no * heartbeat at all (an unsupervised or older host) keeps the previous benefit of the doubt. */ async function standingOwner(owner, paths) { const identity = await claimOwnerIdentity(owner); if (identity === "gone") return { kind: "released" }; const current = (await currentInstanceId(paths.pointerFile)) === owner.instanceId; if (!current && identity === "unproven" && (await heartbeatStopped(paths, owner.instanceId))) return { kind: "presumed_done" }; return current || owner.strict_transfer === true || owner.attached !== false ? { kind: "stands", owner: { ...owner, current } } : { kind: "released" }; } /** Whether the owner's generation left a heartbeat that is older than a stalled host could explain. */ async function heartbeatStopped(paths, instanceId) { // A claim file is untrusted input: an instance id that is not a plain directory name names no generation. if (instanceId === "" || instanceId === "." || instanceId === ".." || /[\\/]/.test(instanceId)) return false; return generationHeartbeatStopped(generationPaths(paths, instanceId)); } /** The generation the pointer names, or nothing when no pointer describes this endpoint. */ async function currentInstanceId(pointerFile) { const pointer = parseJson(await readFileOrUndefined(pointerFile).catch(() => undefined)); return typeof pointer?.instance_id === "string" ? pointer.instance_id : undefined; } async function readOwner(file) { let parsed; try { parsed = JSON.parse(await readFile(file, "utf8")); } catch { // Absent, unreadable or half-written: no claim that anyone could act on. return undefined; } if (typeof parsed !== "object" || parsed === null) return undefined; const { instanceId, pid, processStartTime, sessionPath, attached, host_socket, strict_transfer } = parsed; if (typeof instanceId !== "string" || typeof pid !== "number" || typeof sessionPath !== "string") return undefined; return { instanceId, pid, processStartTime: typeof processStartTime === "string" ? processStartTime : null, sessionPath, ...(typeof host_socket === "string" ? { host_socket } : {}), ...(typeof attached === "boolean" ? { attached } : {}), ...(strict_transfer === true ? { strict_transfer } : {}), }; } /** * A claim counts only while the process that made it is still running. The recorded start time is * what separates "that host is still writing" from "the OS handed its pid to something else". */ export async function claimOwnerIsLive(owner) { return (await claimOwnerIdentity(owner)) !== "gone"; } /** * `proven`: the pid runs and its start time matches the claim. `gone`: the pid is dead, or runs with a * different start time. `unproven`: the pid runs but no start time was recorded or none can be read. */ export async function claimOwnerIdentity(owner) { // An exited, unreaped owner (state Z) makes no more writes: the claim is gone (senpi#4119). if (!processIsRunning(owner.pid)) return "gone"; const recorded = owner.processStartTime === null ? undefined : processStartTimeMs(owner.processStartTime); if (recorded === undefined) { logUnknownHostIdentity("session-path-claim", owner.pid); return "unproven"; } const current = await readProcessStartTime(owner.pid).catch(() => undefined); const observed = current === undefined ? undefined : processStartTimeMs(current); if (observed === undefined) return "unproven"; return sameProcessStartMs(recorded, observed) ? "proven" : "gone"; } function errorMessage(cause) { return cause instanceof Error ? cause.message : String(cause); } //# sourceMappingURL=host-reservations.js.map