@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
243 lines • 15 kB
JavaScript
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { getAgentDir } from "../../config.js";
import { processIsLive, readProcessStartTime } from "../../utils/process-identity.js";
import { createDaemonDirectories, createHostDaemonPaths, ensureEndpointIdentity, generationPaths, sameEndpoint, } from "./host-daemon-paths.js";
import { clearHostRegistration, readHostRegistration, writtenByThisProcess, } from "./host-daemon-registration.js";
import { claimHostOwner } from "./host-daemon-state.js";
import { HostEnsureRefusedError } from "./host-decision.js";
import { decideEnsureAction as decide } from "./host-ensure-client.js";
import { refuseIfForeignHeld, refuseIfStalled, unregisteredEndpointHeld } from "./host-ensure-liveness.js";
import { hostEnsureLockOptions, hostEnsureLockTarget } from "./host-ensure-lock.js";
import { appendStderr, DEFAULT_STOP_TIMEOUT_MS, startHost } from "./host-ensure-start.js";
import { delay, ensureSender, matchesPidFileOrUnknown, resolvePidFileOwnership, STOP_WAIT_BUDGET_MS, stopManagedHost, } from "./host-ensure-stop.js";
import { scheduleOpportunisticHostGc } from "./host-gc-pass.js";
import { handoffHostLocked } from "./host-handoff.js";
import { reapOrphanedBindAliases } from "./host-bind-alias-reaper.js";
import { reapOrphanedInternalHostDirs } from "./host-internal-dir-reaper.js";
import { retireIdleLegacyHost } from "./host-legacy.js";
import { holdProtocolInfo, probeSocketReachable } from "./host-probe.js";
import { childStalledStopMaxMs, hostChildAlive } from "./host-stalled-evidence.js";
import { ensureLockWaitDetail, startupEnvelope } from "./host-startup-policy.js";
import { acquireOwnershipSafeLock, isBusy } from "./ownership-safe-lock.js";
import { rpcKeyRoot, withRpcKeyRoot } from "./rpc-auth-client.js";
export { createHostDaemonPaths, daemonDirectoryName, HostDaemonStateError, } from "./host-daemon-paths.js";
export { hostEnsureLockTarget } from "./host-ensure-lock.js";
export { defaultHostLaunch, PINNED_HOST_CLIENT_CAPABILITIES } from "./host-launch.js";
export { probeHost } from "./host-probe.js";
const EXISTING_HOST_PROBE_TIMEOUT_MS = 10_000;
export async function ensureHost(options) {
return withRpcKeyRoot(rpcKeyRoot(options, options.agentDir), () => ensureHostInKeyRoot(options));
}
async function ensureHostInKeyRoot(options) {
const socket = normalizeSocketPath(options.socket);
const paths = createHostDaemonPaths({ socket, ...(options.agentDir ? { agentDir: options.agentDir } : {}) });
await createDaemonDirectories(paths);
// The public socket is the shared resource; agent directories are not a
// sufficient lock scope when two installations target the same endpoint.
const lockTarget = hostEnsureLockTarget(socket);
await mkdir(dirname(lockTarget), { recursive: true });
await writeFile(lockTarget, "", { flag: "a", mode: 0o600 });
// Opportunistic GC of other installs' leftovers stays OUTSIDE the endpoint lock.
// Its cost scales with the whole tmpdir and, on win32, adds a ~1s process probe per
// candidate; inside the critical section that inflated the hold for every concurrent
// ensureHost until a waiter exhausted its budget and surfaced a raw "database is
// locked". Its own guards (60s age, dead owner pid) already make it safe unlocked; so do the bind-alias
// reaper's (60s age, this user's 0700 directory, its bind directory gone).
await Promise.all([reapOrphanedInternalHostDirs(), reapOrphanedBindAliases()]);
// A lock waiter must outlast the longest critical section one compliant holder can run: W, derived from
// the resolved child-stall setting once per operation (senpi#4602, `startupEnvelope`). Each SQLite busy
// wait stays short because it blocks the event loop; W is the cumulative budget. Exhausting it is
// reported as the ensure-lock expiry, never as a raw "database is locked", and starts nothing.
const { lockWait } = startupEnvelope(childStalledStopMaxMs());
const release = await acquireOwnershipSafeLock(`${lockTarget}.lock`, hostEnsureLockOptions(lockWait)).catch((error) => {
throw isBusy(error) ? new Error(ensureLockWaitDetail(lockWait), { cause: error }) : error;
});
let ensured;
try {
await options._test?.afterLockAcquired?.();
ensured = await ensureHostLocked(paths, socket, options);
}
finally {
await release();
}
// Off the awaited path and outside the lock: the caller gets its host first, then dead endpoint
// records under this agent dir are reaped in the background on `host gc`'s own evidence.
scheduleOpportunisticHostGc({ agentDir: options.agentDir ?? getAgentDir(), exclude: socket });
return ensured;
}
async function ensureHostLocked(paths, socket, options, stopDeadline = Date.now() + Math.min(options.stoppingTimeoutMs ?? STOP_WAIT_BUDGET_MS, STOP_WAIT_BUDGET_MS)) {
// Under the lock, so a torn or foreign `endpoint.json` is repaired rather than left unaddressable.
await ensureEndpointIdentity(paths, socket, { repair: true });
const testOptions = options._test;
const registered = await readHostRegistration(paths);
// A record naming ANOTHER endpoint is not about this ensure's host. The per-socket directory
// makes that structural, and the field stays as the second guard for a directory that was
// somehow reused: a second socket must never read the first socket's daemon as its own.
const registeredHere = registersSocket(registered, socket);
if (registeredHere &&
registered &&
!processIsLive(registered.record.pid) &&
(await hostChildAlive(generationPaths(paths, registered.instanceId))))
throw new HostEnsureRefusedError(socket, "host_stalled", undefined);
// A reusable host is held from the connection that proved it compatible, never re-probed later.
const held = await holdProtocolInfo(socket, testOptions?.existingHostProbeTimeoutMs ?? EXISTING_HOST_PROBE_TIMEOUT_MS);
const protocol = held?.info;
if (protocol?.lifecycle === "stopping") {
held?.hold.release();
// A typed stop is not permission to signal or overwrite a foreign generation.
// Wait for BOTH identities to be gone, then re-run discovery under this lock.
if (!registeredHere || !registered || registered.instanceId !== protocol.instanceId)
throw new HostEnsureRefusedError(socket, "host_stopping", protocol, "no matching registered generation");
const generation = generationPaths(paths, registered.instanceId);
for (;;) {
if ((await resolvePidFileOwnership(registered.record, testOptions?.readProcessStartTime)) === "gone" &&
!(await hostChildAlive(generation)))
return ensureHostLocked(paths, socket, options, stopDeadline);
const remaining = stopDeadline - Date.now();
if (remaining <= 0)
throw new HostEnsureRefusedError(socket, "host_stopping", protocol, "generation exit exceeded stop budget");
await delay(Math.min(50, remaining));
}
}
const startedByUs = registeredHere && (await writtenByThisProcess(registered?.writer, testOptions?.readProcessStartTime));
const attachedPid = registeredHere ? (registered?.record.pid ?? 0) : 0;
const decision = decide(options, startedByUs, protocol);
if (options.owner && held && (decision.action === "reuse" || decision.action === "handoff")) {
try {
if (!registeredHere || !registered || registered.instanceId !== held.info.instanceId)
throw new Error("RPC host has no matching registered owner-lifetime generation");
await claimHostOwner(generationPaths(paths, registered.instanceId).dir);
}
catch (cause) {
held.hold.release();
throw cause;
}
}
if (decision.action === "reuse" && held) {
// A compatible socket is attachable even when another client surface
// started it. Only hosts we spawned are eligible for lifecycle management.
return { pid: attachedPid, socket, reused: true, release: held.hold.release };
}
held?.hold.release();
switch (decision.action) {
case "reuse":
throw new Error(`host at ${socket} was reused without answering its probe`);
case "refuse":
throw new HostEnsureRefusedError(socket, decision.reason, protocol);
case "handoff":
try {
return await upgradeGeneration(paths, socket, options, attachedPid);
}
catch (cause) {
if (cause instanceof HostEnsureRefusedError && cause.reason === "host_stopping")
return ensureHostLocked(paths, socket, options, stopDeadline);
throw cause;
}
case "start":
break;
default:
return assertNever(decision);
}
const probe = testOptions?.readProcessStartTime ?? readProcessStartTime;
const pidMatches = registeredHere && registered ? await matchesPidFileOrUnknown(registered.record, probe) : false;
// The generation this start leaves RUNNING beside the new one, when there is one.
let stranded;
if (registered && pidMatches) {
if (!startedByUs) {
// I1: the socket is silent, but the process behind it is alive. Only the process that WROTE
// this record may end it - anyone else refuses rather than signalling somebody else's host.
await refuseIfForeignHeld(paths, registered, socket, protocol);
await refuseIfStalled(paths, registered.instanceId, socket, protocol);
// A foreign record whose public endpoint accepts NOTHING names a generation nobody can reach:
// its entry was replaced (so it is already draining, #1893) or removed, or a dead listener
// left the entry behind. Refusing here locked every client out until that process happened
// to exit (#1936). Binding a fresh generation there signals nothing, so that is what happens -
// the stranded one keeps its record.
stranded = registered;
}
else {
// Silent is not the same as gone. A host serving many sessions can miss a probe budget
// while its event loop is busy; its socket still ACCEPTS the connection. Ending it then
// would destroy every live session to replace a host that was never broken, so a
// reachable socket is refused instead of signalled - the caller retries or falls back.
if (await probeSocketReachable(socket, EXISTING_HOST_PROBE_TIMEOUT_MS)) {
throw new HostEnsureRefusedError(socket, "host_busy", protocol);
}
await refuseIfStalled(paths, registered.instanceId, socket, protocol);
await stopManagedHost(registered.record, testOptions?.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS, {
daemonDir: paths.dir,
generation: generationPaths(paths, registered.instanceId),
instanceId: registered.instanceId,
sender: ensureSender(),
reason: "replace_unreachable",
}, probe);
}
}
// A host from before this layout registered itself in the FLAT directory. Its files are another
// process's state: never read as ours, never removed. While it is alive this ensure never starts
// beside it: an idle one is drained and waited out (#2423), a busy or unprovable one is refused.
const legacyRefusal = await retireIdleLegacyHost(paths, probe, testOptions?.stopTimeoutMs);
if (legacyRefusal !== undefined)
throw new HostEnsureRefusedError(socket, "legacy_host", protocol, legacyRefusal);
if (stranded !== undefined)
return startHost(paths, socket, options, stranded.generation + 1);
// Something no registration names still ACCEPTS at the public path and did not answer the probe.
// A start can only lose the bind ("address already in use") and exit without a reason, and the
// holder is not ours to remove (I1): refuse with the reason instead. A stale entry nobody listens
// behind reads as free here, so the start below still replaces it.
if (await unregisteredEndpointHeld(socket))
throw new HostEnsureRefusedError(socket, "endpoint_occupied", protocol, "no host registration names this socket and its listener did not answer get_protocol_info");
if (registeredHere)
await clearHostRegistration(paths);
return startHost(paths, socket, options);
}
/**
* The upgrade, when the decision allows one: a new generation takes the socket and the running
* host drains. A refused handoff ATTACHES - an upgrade that cannot happen must never become a stop.
*/
async function upgradeGeneration(paths, socket, options, attachedPid) {
const result = await handoffHostLocked({
socket,
agentDir: options.agentDir ?? getAgentDir(),
hostArgs: options.hostArgs ?? [],
presenterBootstrap: options.presenterBootstrap,
mcpPresenterEnforcement: options.mcpPresenterEnforcement,
...(options.env ? { env: options.env } : {}),
...(options.policy ? { policy: options.policy } : {}),
_test: {
...(options._test?.launch ? { launch: options._test.launch } : {}),
...(options._test?.readinessTimeoutMs ? { readinessTimeoutMs: options._test.readinessTimeoutMs } : {}),
},
});
if (result.action === "handoff")
return { pid: result.pid, socket, reused: false, release: await holdEnsured(socket) };
await appendStderr(paths, `generation handoff refused: ${result.reason}${result.detail ? ` (${result.detail})` : ""}`);
return { pid: attachedPid, socket, reused: true, release: await holdEnsured(socket) };
}
/** The attach hold for a host another step already proved ready (a handoff successor, a refused handoff). */
async function holdEnsured(socket) {
const held = await holdProtocolInfo(socket, EXISTING_HOST_PROBE_TIMEOUT_MS);
if (!held)
throw new Error(`RPC socket host at ${socket} stopped answering before this ensure could hold it`);
if (held.info.lifecycle === "stopping") {
held.hold.release();
throw new HostEnsureRefusedError(socket, "host_stopping", held.info);
}
return held.hold.release;
}
/** Whether a registration is about this endpoint. A record written before the field existed is. */
function registersSocket(registered, socket) {
if (registered === undefined)
return false;
return registered.socket === undefined || sameEndpoint(registered.socket, socket);
}
function normalizeSocketPath(value) {
if (value.startsWith("unix://"))
return value.slice("unix://".length);
return value;
}
function assertNever(value) {
throw new Error(`unreachable host decision: ${JSON.stringify(value)}`);
}
//# sourceMappingURL=host-ensure.js.map