UNPKG

@code-yeongyu/senpi

Version:

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

146 lines • 7.23 kB
/** * The evidence `host gc` needs before it may remove an endpoint: whether anything still runs behind * it, and whether anything still answers on it. Each answer errs toward "alive" - a record that * cannot be proven dead, a probe that neither connects nor is refused, a claim whose owner cannot be * read - because the cost of keeping a dead directory is disk, and the cost of removing a live one * is every session its host holds. * * Reading only: nothing here writes, unlinks or signals. */ import { lstat, readdir } from "node:fs/promises"; import { createConnection } from "node:net"; import { basename, dirname, join } from "node:path"; import { ProcessIdentityUnreadableError, parseDaemonPidFile, processMatchesPidFile, } from "../../utils/process-identity.js"; import { generationPaths } from "./host-daemon-paths.js"; import { parseJson, readFileOrUndefined } from "./host-daemon-state.js"; import { claimOwnerIsLive, readSessionPathClaims } from "./host-reservations.js"; import { hostChildAlive } from "./host-stalled-evidence.js"; import { BIND_SCRATCH_INFIX, isBindScratchName } from "./socket-ownership.js"; import { readSocketSecret, resolveSocketTransportAddress, socketSecretPath } from "./socket-transport.js"; /** A connect that neither succeeds nor fails within this budget counts as an answer. */ const SOCKET_PROBE_TIMEOUT_MS = 2_000; /** * The three-part test, in the order its answers are reported: (a) no generation pidfile names a live * process - the pointer's generation included, since its record lives under `generations/` too - (b) no * session-path claim has a live owner, (c) the public socket - and every `.next-*` successor bind beside * it - refuses the connection or does not exist. */ export async function endpointInUse(paths, socket) { if (await anyGenerationLive(paths)) return { inUse: "live_generation" }; for (const claim of await readSessionPathClaims(paths.reservationsDir)) { if (await claimOwnerIsLive(claim.owner)) return { inUse: "live_claim" }; } const silence = await socketSilence(socket); if (silence === "credential_unavailable") return { inUse: silence }; if (silence === undefined) return { inUse: "reachable" }; // A successor mid-handoff listens on `<socket>.next-<gen>` before it registers anywhere. const successors = (await socketSiblings(socket)).filter((name) => name.startsWith(`${basename(socket)}.next-`) && !isBindScratchName(name)); for (const successor of successors) { const successorSilence = await socketSilence(join(dirname(socket), successor)); if (successorSilence === "credential_unavailable") return { inUse: successorSilence }; if (successorSilence === undefined) return { inUse: "reachable" }; } return { inUse: undefined, silence }; } /** * Every entry beside `socket` that belongs to it: `<name>.next-*` successor binds, `<name>.shield-*`, and the * `<name>.bind-*` directory a bind crashed out of (`host-socket-bind.ts`). */ export async function socketSiblings(socket) { const name = basename(socket); const entries = await readdir(dirname(socket)).catch(() => []); return entries.filter((entry) => entry.startsWith(`${name}.next-`) || entry.startsWith(`${name}.shield-`) || entry.startsWith(`${name}${BIND_SCRATCH_INFIX}`)); } /** * EVERY generation, not only the pointer's: a predecessor draining after a handoff is still serving. * Also the "dead" half of `classifyEndpointLiveness`, so the verdict and gc never disagree about it. */ export async function anyGenerationLive(paths) { for (const instanceId of await readdir(paths.generationsDir).catch(() => [])) { if (await hostChildAlive(generationPaths(paths, instanceId))) return true; const record = generationRecord(await readFileOrUndefined(generationPaths(paths, instanceId).pidFile)); if (record !== undefined && (await recordIsLive(record))) return true; } return false; } /** * A pidfile's process, or nothing when it names none. A record whose identity guard does not parse * still names a pid, and is read as unguarded rather than as absent: its process may be running. */ function generationRecord(text) { if (text === undefined) return undefined; const record = parseDaemonPidFile(text); if (record !== undefined) return record; const pid = parseJson(text)?.pid; return typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? { pid, processStartTime: null } : undefined; } /** Live and still the recorded process; a live pid whose identity cannot be read counts as live. */ async function recordIsLive(record) { try { return await processMatchesPidFile(record); } catch (error) { if (error instanceof ProcessIdentityUnreadableError) return true; throw error; } } /** * How the socket proved silent, or `undefined` when it did not: only ECONNREFUSED and ENOENT prove * nobody listens. A connect that succeeds, times out or fails any other way is treated as an answer. * ECONNREFUSED counts only when the entry IS a socket: Linux refuses a connect to a regular file the * same way it refuses a dead socket, and a file named where the socket should be is not ours to unlink. */ async function socketSilence(socket) { let secret; if (process.platform === "win32") { // The pipe name includes the secret, so without a readable one nothing proves the pipe silent: a // live host may still serve it under the key whose file was lost (sisyphuslabs/omo-desktop-app#4199). secret = await readSocketSecret(socketSecretPath(socket)).catch(() => undefined); if (secret === undefined) return "credential_unavailable"; } return new Promise((resolveProbe) => { const connection = createConnection(resolveSocketTransportAddress(socket, process.platform, secret)); const finish = (value) => { clearTimeout(timeout); connection.destroy(); resolveProbe(value); }; const timeout = setTimeout(() => finish(undefined), SOCKET_PROBE_TIMEOUT_MS); connection.once("connect", () => finish(undefined)); connection.once("error", (error) => { if (error.code === "ECONNREFUSED") void refusedBySocket(socket).then(finish); else if (error.code === "ENOENT") finish("socket_absent"); else finish(undefined); }); }); } /** A refusal proves silence only from a socket entry; an entry of any other type is an answer. */ async function refusedBySocket(socket) { // Named pipes and abstract sockets have no filesystem entry to be of the wrong type. if (process.platform === "win32" || socket.startsWith("\0")) return "socket_refused"; try { return (await lstat(socket)).isSocket() ? "socket_refused" : undefined; } catch (error) { return error instanceof Error && "code" in error && error.code === "ENOENT" ? "socket_absent" : undefined; } } //# sourceMappingURL=host-gc-evidence.js.map