@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
166 lines • 9.93 kB
JavaScript
/**
* What a client does when it finds - or does not find - a host on the shared RPC socket.
*
* One machine-wide host serves several client surfaces, so the process on the socket is
* usually NOT this process's child. Two invariants follow, and this module is where they
* are decided once instead of in every client:
*
* I1 - never terminate, signal or replace a host you did not start. The only sanctioned
* replacement is the drain-based generation handoff, which ends no running work.
* I2 - compatibility is `protocolVersion` + capabilities, NEVER a version-string compare,
* and "is my build newer?" is `compareEngineOrdinal`, never `serverVersion`. An
* ordinal that cannot be compared (a build without git metadata, a host that reports
* none, an ordinal outside senpi CalVer such as a compiled omo's `[5, 1, 78]`, senpi#7040) is
* EQUAL, and since a handoff needs STRICTLY greater, such a pair attaches.
*
* The profile rule is the third guard: a handoff additionally requires the candidate's
* extension set to be a SUPERSET of the running host's. Handing off to a narrower generation
* would silently drop whatever the running host loaded (an editor plugin, a member bundle)
* from every session that reopens in the new generation - so a narrower candidate attaches
* and says so instead.
*/
import { compareEngineOrdinal, engineIdentityOf, } from "../../core/engine-build-identity.js";
import { EXTENSION_EVENTS_CAPABILITY, SESSION_CONTEXT_CAPABILITY, SESSION_KIND_CAPABILITY, } from "./custom-capability.js";
import { describeHostHolder } from "./host-holder.js";
export { parseHostProtocolInfo } from "./host-protocol-info.js";
/** The wire protocol this build speaks. A host answering with any other number is refused, not replaced. */
export const HOST_PROTOCOL_VERSION = 1;
/**
* HOST capability: this host drains into a successor generation on SIGUSR1 instead of dying with
* its sessions. A host without it is attach-only - it is never renamed, signalled or upgraded.
*/
export const GENERATION_HANDOFF_CAPABILITY = "generation_handoff";
/**
* HOST capability (senpi#4602): every rename or remove this host makes on its public socket entry runs under the
* endpoint's mutation fence and re-reads the endpoint owner token. Only a predecessor that advertises it is handed
* off with the owner-token guard; an older one gets today's handoff and its late-rename race.
*/
export const ENDPOINT_OWNER_FENCE_CAPABILITY = "endpoint_owner_fence";
/** What a daemon session needs from a host before any client may attach to it. */
export const REQUIRED_HOST_CAPABILITIES = [
"multi_session",
EXTENSION_EVENTS_CAPABILITY,
SESSION_CONTEXT_CAPABILITY,
SESSION_KIND_CAPABILITY,
];
/**
* An ensure that found an unusable host and refused to act on it. A refusal is FINAL by design:
* this process may not signal a host it did not start (I1), and starting a second host on an
* endpoint another process already owns is exactly the failure the refusal exists to prevent.
*/
export class HostEnsureRefusedError extends Error {
constructor(socket, reason, host, detail, holder) {
const heldBy = holder ? ` (held by ${describeHostHolder(holder)})` : "";
super(`RPC socket ${socket} refused: ${reason} - ${refusalDetail(reason, host)}${detail ? `: ${detail}` : ""}${heldBy}`);
this.name = "HostEnsureRefusedError";
this.socket = socket;
this.reason = reason;
this.detail = detail;
this.holder = holder;
}
}
function refusalDetail(reason, host) {
switch (reason) {
case "protocol":
return `the running host speaks protocol version ${host?.protocolVersion ?? "unknown"}, this build speaks ${HOST_PROTOCOL_VERSION}`;
case "capability": {
const missing = REQUIRED_HOST_CAPABILITIES.filter((capability) => !host?.capabilities.includes(capability));
return `the running host is missing ${JSON.stringify(missing)}; it owns the socket, so no second host is started`;
}
case "foreign_writer":
return "another process registered the host on this socket; it accepts connections but did not answer as a host, and this one may not signal it - stop that host explicitly (host stop --force), then ensure again";
case "legacy_host":
return "a host from before the per-socket daemon directory is still running; it is drained and replaced only while it holds no session, and no second host is started beside it";
case "host_busy":
return "its socket accepts connections but did not answer inside the probe budget: a live host under load, which is never ended to make room for a replacement";
case "host_stopping":
return "this generation is stopping; wait for its exit before launching a successor";
case "endpoint_occupied":
return "another process accepts connections on this socket but does not answer as a host, and no host registration names it; it is never removed while it listens, so quit the process holding it and ensure again";
case "host_stalled":
return "nothing reaches its socket, but its process is alive and its own loop-lag watchdog measured a recent stall: a stalled host is still serving its sessions, so it is neither stopped nor replaced";
default:
return assertNever(reason);
}
}
export function decideHostAction(client, host, policy) {
if (host === undefined) {
return { action: "start", reason: client.startedByUs ? "restart_own_host" : "no_host", upgradeable: false };
}
if (host.lifecycle === "stopping")
return { action: "refuse", reason: "host_stopping", upgradeable: false };
if (host.protocolVersion !== client.protocolVersion) {
return { action: "refuse", reason: "protocol", upgradeable: false };
}
if (!client.requiredCapabilities.every((capability) => host.capabilities.includes(capability))) {
// A host that cannot serve this client still OWNS the socket: starting a second one would
// bind over an endpoint another process is serving. Refuse, or fall back to no host at all.
if (policy === "fallback")
return { action: "fallback", reason: "capability", upgradeable: false };
return { action: "refuse", reason: "capability", upgradeable: false };
}
const upgradeable = client.platform !== "win32" && host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY);
if (policy === "fallback" && host.engineVersion !== client.identity.text) {
return { action: "fallback", reason: "engine_mismatch", upgradeable };
}
const warning = profileWarning(client, host);
if (client.platform === "win32") {
return { action: "reuse", reason: "win32_attach_only", upgradeable: false, ...(warning && { warning }) };
}
if (!upgradeable) {
return { action: "reuse", reason: "handoff_unsupported", upgradeable: false, ...(warning && { warning }) };
}
if (policy === "upgrade" && client.launchProfile && host.launch_profile && supersedes(client, host)) {
return {
action: "handoff",
reason: sameRelease(client.identity.ordinal, host.engineOrdinal) ? "profile" : "newer_engine",
upgradeable: true,
};
}
return { action: "reuse", reason: "compatible", upgradeable, ...(warning && { warning }) };
}
/** A strictly newer build whose extensions cover everything the host loads - the only handoff candidate. */
function supersedes(client, host) {
if (host.engineOrdinal === undefined)
return false;
if (compareEngineOrdinal(client.identity, engineIdentityOf(host.engineVersion ?? "", host.engineOrdinal)) <= 0)
return false;
return covers(client.launchProfile, host.launch_profile);
}
function profileWarning(client, host) {
if (client.launchProfile === undefined || host.launch_profile === undefined)
return "profile_mismatch_attached";
if (client.launchProfile.profile_id === host.launch_profile.profile_id)
return undefined;
const clientCoversHost = covers(client.launchProfile, host.launch_profile);
// The same plugin set installed under another root differs only in path: nothing to warn about.
if (clientCoversHost && covers(host.launch_profile, client.launchProfile))
return undefined;
return clientCoversHost ? "profile_mismatch_attached" : "profile_narrower_attached";
}
/**
* The role of a launch-profile extension: the engine plugin's files are identified from the last
* `plugin` path segment on (`plugin`, `plugin/extensions/<name>.js`), so two installs of the same
* plugin set under different roots (a runtime directory per build) name the same roles. Every other
* extension keeps its whole path: only the plugin's location is build-specific.
*/
function extensionRole(extension) {
const segments = extension.split(/[\\/]+/);
const pluginAt = segments.lastIndexOf("plugin");
return pluginAt < 0 ? extension : segments.slice(pluginAt).join("/");
}
/** Profile compatibility only: runtime identity (`runtimeBuildId`, the engine ordinal) is decided elsewhere. */
function covers(candidate, running) {
if (candidate === undefined || running === undefined)
return false;
const candidateRoles = new Set(candidate.core.extensions.map(extensionRole));
return running.core.extensions.every((extension) => candidateRoles.has(extensionRole(extension)));
}
/** True when both builds are the same released version and only their build epoch differs. */
function sameRelease(candidate, running) {
return running !== undefined && candidate.slice(0, 4).every((part, index) => part === running[index]);
}
function assertNever(value) {
throw new Error(`unreachable host decision: ${JSON.stringify(value)}`);
}
//# sourceMappingURL=host-decision.js.map