@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
103 lines • 6.12 kB
JavaScript
/**
* Replacing a running daemon without ending the work it is doing.
*
* An upgrade cannot mean "kill the host and start a newer one": one machine-wide daemon
* holds every client's sessions, so that is a data-loss operation dressed as a version
* bump. A GENERATION HANDOFF replaces the process while the work continues:
*
* 1. the successor binds `<public>.next-<gen>` - never the live public path, which it
* has no right to unlink - and only renames its own entry over the public path once
* its host answers, and only while that path still holds the exact socket this
* handoff was decided against (`--replace <dev>:<ino>`);
* 2. the predecessor is then asked to DRAIN with SIGUSR1: it stops accepting, keeps
* every connection it is already proxying, parks each retained session as its turn
* settles, and exits through its ordinary idle path;
* 3. clients that arrive in between reach whichever generation owns the path at that
* instant - both are alive and serving.
*
* Two guards make this safe rather than merely clever. SIGUSR1 has a DEFAULT DISPOSITION OF
* TERMINATE, so a host that does not advertise `generation_handoff` is never signalled - it
* would die, taking its sessions with it. And a host whose pidfile identity cannot be proven
* is never signalled either (I1), because "the process at this pid" is not evidence.
*
* win32 has neither a renameable named pipe nor SIGUSR1, so every entry point here refuses
* with `upgrade_unsupported`; upgrades there apply after a drain-stop or an idle exit.
*
* A handoff changes who serves the socket, so it runs inside the endpoint's ENSURE lock, like an
* ensure and `host gc`: an ensure arriving meanwhile attaches to whichever generation the handoff
* left registered, and gc never judges the endpoint halfway through.
*/
import { getAgentDir } from "../../config.js";
import { engineBuildIdentity, engineIdentityOf, olderEngineDetail, } from "../../core/engine-build-identity.js";
import { createDaemonDirectories, createHostDaemonPaths } from "./host-daemon-paths.js";
import { provenOwner, readHostRegistration } from "./host-daemon-registration.js";
import { GENERATION_HANDOFF_CAPABILITY } from "./host-decision.js";
import { acquireHostEnsureLock } from "./host-ensure-lock.js";
import { foreignAgentDirRefusal } from "./host-handoff-agent-dir.js";
import { handoffUnregisteredHost } from "./host-handoff-unregistered.js";
import { electPointer } from "./host-pointer-election.js";
import { probeProtocolInfo } from "./host-probe.js";
import { childStalledStopMaxMs } from "./host-stalled-evidence.js";
import { startupEnvelope } from "./host-startup-policy.js";
import { startSuccessor } from "./host-successor.js";
const HANDOFF_PROBE_TIMEOUT_MS = 10_000;
/**
* Hands the socket to a new generation of this build. Forced by design: the caller decides
* whether an upgrade is warranted (`decideHostAction`); this performs the one it asked for, except
* a downgrade: a successor whose engine is older than the running host's is refused unless the caller
* says `allowDowngrade` (senpi#7018), so no caller can hand a newer host down by accident.
*/
export async function handoffHost(options) {
if (handoffUnsupported(options))
return { action: "refuse", reason: "upgrade_unsupported", upgradeable: false };
// W: the same bound an ensure waits, covering one compliant holder H (senpi#4602).
const release = await acquireHostEnsureLock(options.socket, startupEnvelope(childStalledStopMaxMs()).lockWait);
try {
return await handoffHostLocked(options);
}
finally {
await release();
}
}
/** The handoff itself, for a caller that already holds this socket's ensure lock: an ensure's upgrade. */
export async function handoffHostLocked(requested) {
if (handoffUnsupported(requested))
return { action: "refuse", reason: "upgrade_unsupported", upgradeable: false };
// One agent dir for the guard, the daemon paths and the successor's environment alike (an empty
// string keeps its pre-#3563 meaning: this process's default).
const options = { ...requested, agentDir: requested.agentDir || getAgentDir() };
const paths = createHostDaemonPaths({ socket: options.socket, agentDir: options.agentDir });
// Created before the agent-dir guard on purpose: realpath needs the caller's dir to exist, so a refused
// foreign caller may leave an empty daemon dir under its own agent dir (harmless).
await createDaemonDirectories(paths);
const host = await probeProtocolInfo(options.socket, HANDOFF_PROBE_TIMEOUT_MS);
if (!host)
return { action: "refuse", reason: "no_host", upgradeable: false };
if (!host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY)) {
return { action: "refuse", reason: "handoff_unsupported", upgradeable: false };
}
const downgrade = downgradeRefusal(options, host);
if (downgrade)
return downgrade;
const foreign = await foreignAgentDirRefusal(options.socket, options.agentDir, host);
if (foreign)
return foreign;
// A pointer an earlier prune dropped is given back to the one proven live generation (senpi#1911).
await electPointer(paths);
const registered = await readHostRegistration(paths);
const owner = await provenOwner(registered, options.socket);
if (!owner)
return handoffUnregisteredHost(options, paths, host);
return startSuccessor({ options, paths, host, owner });
}
function downgradeRefusal(options, host) {
if (options.allowDowngrade === true || host.engineOrdinal === undefined)
return undefined;
const running = engineIdentityOf(host.engineVersion ?? "", host.engineOrdinal);
const detail = olderEngineDetail(options.successorEngine ?? engineBuildIdentity(), running);
return detail === undefined ? undefined : { action: "refuse", reason: "older_engine", upgradeable: false, detail };
}
function handoffUnsupported(options) {
return (options._test?.platform ?? process.platform) === "win32";
}
//# sourceMappingURL=host-handoff.js.map