@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
107 lines • 5.12 kB
JavaScript
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { ENDPOINT_OWNER_FENCE_CAPABILITY } from "./host-decision.js";
import { startupTimeoutDetail } from "./host-startup-policy.js";
import { ADOPTION_GRANT_FILE, STARTUP_EVENT_FD, startupGrantLine } from "./host-startup-wire.js";
import { MCP_PRESENTER_BOOTSTRAP_FD, relayPresenterBootstrap, } from "./mcp-presenter-bootstrap.js";
export async function driveSuccessorStartup(options) {
const { controller, coordinated } = options.attempt;
const terminal = controller.settled().then(() => "terminal");
const failure = async () => {
const outcome = await controller.settled();
if (outcome.kind === "ready")
throw new Error("startup controller reported READY on a failure path");
return { ready: false, outcome };
};
if (coordinated) {
if (!(await controller.whenPhase("presenter_resolved")))
return failure();
if (options.presenter) {
const result = await Promise.race([options.presenter(), terminal]);
// LEAD ruling 10-31 (b): a channel that closes without enrolling passes P7 as "not enrolled" - preserves #4254's
// tested behaviour (a refused enrollment never blocks the handoff). Only P7's own expiry fails the candidate.
if (result === "terminal")
return failure();
}
if (controller.complete("presenter_resolved") !== "accepted")
return failure();
try {
await options.attempt.grant();
}
catch (cause) {
controller.fail(cause instanceof Error ? cause : new Error(String(cause)));
return failure();
}
if (!(await controller.whenPhase("public_verified")))
return failure();
}
const answer = await Promise.race([options.awaitAnswer(Math.max(1, controller.remainingMs())), terminal]);
if (answer !== "terminal" && answer !== undefined && controller.complete("public_verified") === "accepted")
return { ready: true, answer };
if (!controller.terminal)
controller.fail(new Error("the successor never answered on the public socket"));
return failure();
}
/**
* The presenter exchange of one successor. A coordinated successor whose owner channel is DEFERRED (a running
* host's idle handover) asks for the fresh permit only when called, at its P7. An eager owner channel, and every
* channel of an uncoordinated launch, is relayed from the spawn as before; calling the result joins that relay.
*/
export function successorPresenter(bootstrap, child, predecessor, coordinated) {
if (bootstrap === undefined)
return undefined;
const relay = async () => {
const stream = typeof bootstrap === "function" ? await bootstrap() : bootstrap;
if (stream)
return relayPresenterBootstrap(stream, child, {
kind: "replacement",
predecessorHostInstance: predecessor.instanceId,
});
const channel = child.stdio[MCP_PRESENTER_BOOTSTRAP_FD];
if (typeof channel === "object" &&
channel !== null &&
"destroy" in channel &&
typeof channel.destroy === "function")
channel.destroy();
return "closed";
};
if (typeof bootstrap !== "function" || !coordinated) {
const started = relay();
return () => started;
}
let started;
return () => {
started ??= relay();
return started;
};
}
/** The refusal detail of a failed successor attempt, in the same machine-readable form an initial start reports. */
export function failureDetail(outcome, cleanupFailure) {
return outcome.kind === "timeout"
? startupTimeoutDetail(outcome, cleanupFailure ? "incomplete" : "completed")
: outcome.cause.message;
}
/** The grant for one attempt: authority in the candidate's own generation directory, wake-up on its startup pipe. */
export function adoptionGrant(attempt, generationDir, child) {
const file = join(generationDir, ADOPTION_GRANT_FILE);
return {
async grant() {
await writeFile(file, `${JSON.stringify({ attempt })}\n`, { mode: 0o600 });
const pipe = child.stdio[STARTUP_EVENT_FD];
if (typeof pipe !== "object" || pipe === null || !("write" in pipe) || typeof pipe.write !== "function")
throw new Error("the successor's startup pipe is gone");
pipe.write(startupGrantLine(attempt));
},
revoke: () => rm(file, { force: true }),
};
}
/**
* Q1 (LEAD ruling, senpi#4602): the owner-token guard is claimed only against a predecessor that advertises it.
* Without the capability the successor adopts the way it always did, and the old host's late-rename race remains.
*/
export function predecessorOwnerArgs(host) {
return host.instanceId !== undefined && host.capabilities.includes(ENDPOINT_OWNER_FENCE_CAPABILITY)
? ["--replace-owner", host.instanceId]
: [];
}
//# sourceMappingURL=host-successor-startup.js.map