@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
129 lines • 6.2 kB
JavaScript
import { Readable } from "node:stream";
import { HOST_PROTOCOL_VERSION, REQUIRED_HOST_CAPABILITIES } from "./host-decision.js";
import { HOST_STARTUP_EVENTS_ENV } from "./host-identity-env.js";
import { pollProtocolInfo } from "./host-readiness.js";
import { attachStartupEvents } from "./host-startup-events.js";
import { STARTUP_DECISION_BUDGET_MS, startStartupController, } from "./host-startup-policy.js";
import { releaseStartupFillers, withStartupPipe } from "../../private-fd-startup-fillers.js";
import { encodeStartupHandOff, STARTUP_EVENT_FD } from "./host-startup-wire.js";
/** The launcher's monotonic clock: never the wall clock, never another process's timestamps. */
export function monotonicStartupClock() {
return {
now: () => performance.now(),
scheduleAt: (at, fire) => setTimeout(fire, Math.max(0, at - performance.now())),
cancel: (handle) => clearTimeout(handle),
};
}
/** Created immediately BEFORE the spawn: the controller's creation instant is the attempt's origin. */
export function beginStartupAttempt(options) {
const successor = options.successorOf !== undefined;
const launchKind = !options.coordinated ? "legacy" : successor ? "successor" : "initial";
const budgetMs = options.decisionBudgetMs ?? STARTUP_DECISION_BUDGET_MS;
const binding = {
attempt: options.attempt,
endpoint: options.socket,
instanceId: options.instanceId,
generation: options.generation,
launchKind: successor ? "successor" : "initial",
predecessor: options.successorOf ?? null,
};
const controller = startStartupController({
launchKind,
clock: options.clock ?? monotonicStartupClock(),
decisionBudgetMs: budgetMs,
});
const coordinated = options.coordinated;
let fillers = [];
return {
controller,
binding,
coordinated,
get env() {
if (!coordinated)
return {};
return { [HOST_STARTUP_EVENTS_ENV]: encodeStartupHandOff({ binding, role: "supervisor", budgetMs, fillers }) };
},
stdio(base) {
if (!coordinated)
return [...base];
const filled = withStartupPipe(base);
fillers = filled.fillers;
return filled.stdio;
},
attach(child, childExit) {
releaseStartupFillers(child, fillers);
const stream = child.stdio[STARTUP_EVENT_FD];
if (coordinated && stream instanceof Readable)
attachStartupEvents(stream, controller, binding);
// Before public verification a supervisor exit ends the attempt; during it, the in-flight probe decides.
void childExit.then((exit) => {
if (!controller.terminal && controller.phase !== "public_verified")
controller.fail(new Error(exitMessage(exit)));
});
},
};
}
export function exitMessage(exit) {
return `RPC socket host exited with ${exitStatus(exit)} before answering get_protocol_info`;
}
function exitStatus(exit) {
return `code ${exit.code ?? "null"}${exit.signal ? ` (${exit.signal})` : ""}`;
}
/** The reply a host gave instead of READY. A stopping host is not a protocol mismatch (senpi#6017). */
function answerMessage(protocol, exited) {
if (protocol.lifecycle !== "stopping")
return incompatibleMessage(protocol);
const exit = exited ? `, and then exited with ${exitStatus(exited)}` : "";
return `RPC socket host answered get_protocol_info with lifecycle "stopping": it began stopping before this start verified it${exit}`;
}
function incompatibleMessage(protocol) {
return `RPC socket host answered get_protocol_info with protocolVersion ${protocol.protocolVersion}, serverVersion ${protocol.serverVersion} and capabilities ${JSON.stringify(protocol.capabilities)}, but is incompatible with protocol version ${HOST_PROTOCOL_VERSION} and required capabilities ${JSON.stringify(REQUIRED_HOST_CAPABILITIES)}`;
}
export async function driveStartupToReady(options) {
const { controller } = options.attempt;
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 (options.attempt.coordinated) {
if (!(await controller.whenPhase("presenter_resolved")))
return failure();
const presenter = await Promise.race([
(options.presenterEnrollment ?? Promise.resolve()).then(() => "resolved"),
controller.settled().then(() => "terminal"),
]);
if (presenter === "terminal" || controller.complete("presenter_resolved") !== "accepted")
return failure();
}
const result = await pollProtocolInfo(options.socket, Math.max(1, controller.remainingMs()), options.isCompatible, options.childExit);
if (result.ready) {
if (controller.complete("public_verified") !== "accepted") {
result.hold.release();
return failure();
}
// A legacy launch keeps today's order: the presenter result after the public answer.
if (!options.attempt.coordinated)
await options.presenterEnrollment;
return { ready: true, hold: result.hold };
}
// An answer the host did give, or its exit, is an explicit cause: it is never relabelled as the timeout the
// poll ran into while it kept retrying that incompatible answer (A-amended section 6).
const explicit = result.protocol
? new Error(answerMessage(result.protocol, result.exited))
: result.exited
? new Error(exitMessage(result.exited))
: undefined;
if (!explicit)
return failure();
controller.fail(explicit);
const settled = await controller.settled();
return {
ready: false,
outcome: settled.kind === "failed"
? settled
: { kind: "failed", phase: "public_verified", cause: explicit, elapsedMs: settled.elapsedMs },
};
}
//# sourceMappingURL=host-startup-run.js.map