UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

165 lines • 7.66 kB
/** * The conditional idle handover, as the RUNNING host performs it. * * `senpi host handoff --when idle` names the generation it means (`ifInstanceId`, `ifGeneration`), * the runtime it wants serving (`targetRuntimeBuildId`) and one `operationId`. The host owns the * operation from then on, because only it can see its own turns and only it outlives the CLI call: * * 1. it checks, synchronously and before anything else, that it IS the named generation, and * refuses `stale_generation` otherwise; * 2. it stops admitting new input (`admits`): prompts, steering, follow-ups, user bash, * compaction, edits and wake deliveries are answered with a `handover_pending` error, while * every turn already running keeps running and keeps its control traffic; * 3. it waits for its next safe idle point - no open session busy, no request in flight. An idle * session that is merely retained is not work. The wait has NO deadline: a long turn delays the * handover, it is never aborted for it; * 4. it starts the successor through the ordinary generation handoff (successor proven on the * public socket, then this generation drains and parks its idle sessions for the successor to * reopen by path). A successor that does not come up leaves this generation serving and admits * input again (`handover_blocked { reason }`). * * A repeated `operationId` with the same terms answers with the operation that already exists, * whatever its state, so a caller that lost a reply can ask again without starting a second one; the * same id with other terms is refused (`operation_conflict`). Another id for the same target joins * the pending operation and is answered with ITS id; another target is refused * (`handover_in_progress`) until the pending operation ends. */ import { olderEngineDetail } from "../../core/engine-build-identity.js"; /** * Set on a successor launched by an idle handover: the runtime it must report. A successor that * computes another id exits before it listens, so the socket never moves to the wrong runtime. */ export const EXPECTED_RUNTIME_BUILD_ID_ENV = "SENPI_RPC_HOST_EXPECTED_RUNTIME_BUILD_ID"; /** Commands that would start, extend or queue model work. Everything else stays admitted. */ const NEW_WORK_COMMANDS = new Set([ "prompt", "steer", "follow_up", "send_custom_message", "continue_from_leaf", "resume_session", "append_user_message", "bash", "compact", "wake", "admit_external_message", "edit_assistant_message", "edit_user_message", ]); const DEFAULT_POLL_MS = 200; export class HostIdleHandover { constructor(options) { this.options = options; } /** The operation this host holds, for `get_protocol_info` and therefore `host status`. */ view() { return this.operation?.view; } /** False while a handover holds new work back; a blocked one admits again. */ admits(commandType) { const state = this.operation?.view.state; return state === undefined || state === "handover_blocked" || !NEW_WORK_COMMANDS.has(commandType); } async begin(request) { const current = this.operation; if (current !== undefined && current.view.operationId === request.operationId) { return sameTerms(current.request, request) ? answer(current) : { kind: "refused", reason: "operation_conflict", detail: "this operation id names other terms" }; } if (current !== undefined && current.view.state !== "handover_blocked") { return current.request.targetRuntimeBuildId === request.targetRuntimeBuildId && Boolean(current.request.mcpPresenterEnforcement) === Boolean(request.mcpPresenterEnforcement) ? answer(current) : { kind: "refused", reason: "handover_in_progress", detail: current.view.operationId }; } const self = this.options.identity(); if (self.instanceId !== request.ifInstanceId || self.generation !== request.ifGeneration) { return { kind: "refused", reason: "stale_generation", detail: `this host is ${self.instanceId} generation ${self.generation}`, }; } if (self.runtimeBuildId === request.targetRuntimeBuildId) { return { kind: "refused", reason: "already_current", detail: self.runtimeBuildId }; } const downgrade = downgradeDetail(request, self.engine); if (downgrade !== undefined) return { kind: "refused", reason: "older_engine", detail: downgrade }; const operation = { request, view: { operationId: request.operationId, state: "handover_pending", targetRuntimeBuildId: request.targetRuntimeBuildId, }, }; this.operation = operation; this.options.log?.(`handover ${request.operationId} pending: no new work is admitted`); if (this.idleNow()) { await this.switchOver(operation); return answer(operation); } this.timer = setInterval(() => this.observe(), this.options.pollMs ?? DEFAULT_POLL_MS); this.timer.unref?.(); return answer(operation); } /** Re-checks a pending operation; the host calls it whenever a request settles. */ observe() { const operation = this.operation; if (operation?.view.state === "handover_pending" && this.idleNow()) void this.switchOver(operation); } dispose() { this.stopTimer(); } idleNow() { try { return this.options.isIdle(); } catch (cause) { this.options.log?.(`handover idle check failed, waiting: ${String(cause)}`); return false; } } async switchOver(operation) { if (operation.view.state !== "handover_pending") return; this.stopTimer(); operation.view = { ...operation.view, state: "handover_switching" }; this.options.holdNewWork?.(); const outcome = await this.options .perform(operation.request) .catch((cause) => ({ ok: false, reason: `successor_unavailable: ${String(cause)}` })); operation.view = outcome.ok ? { ...operation.view, state: "handover_completed", successor: outcome.successor } : { ...operation.view, state: "handover_blocked", reason: outcome.reason }; if (!outcome.ok) this.options.releaseNewWork?.(); this.options.log?.(`handover ${operation.view.operationId} ${operation.view.state}`); } stopTimer() { if (this.timer !== undefined) clearInterval(this.timer); this.timer = undefined; } } function sameTerms(a, b) { return (a.targetRuntimeBuildId === b.targetRuntimeBuildId && Boolean(a.mcpPresenterEnforcement) === Boolean(b.mcpPresenterEnforcement) && a.ifInstanceId === b.ifInstanceId && a.ifGeneration === b.ifGeneration); } function downgradeDetail(request, engine) { if (request.allowDowngrade === true || engine === undefined) return undefined; if (request.targetEngine === undefined) { return `the requesting CLI did not state its engine, so it predates the downgrade guard and is older than this host's ${engine.text}`; } return olderEngineDetail(request.targetEngine, engine); } function answer(operation) { return { kind: "operation", view: operation.view }; } //# sourceMappingURL=host-idle-handover.js.map