UNPKG

@code-yeongyu/senpi

Version:

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

726 lines • 39.5 kB
import { engineBuildIdentity } from "../../core/engine-build-identity.js"; import { reportStartupMilestone } from "./host-startup-beacon.js"; import { createServer } from "node:net"; import { rm } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; import { envValue } from "../../core/brand.js"; import { HostMcpRegistry } from "../../core/extensions/builtin/mcp/host-registry.js"; import { flushRawStdout, takeOverStdout, waitForRawStdoutBackpressure, writeRawStdout, } from "../../core/output-guard.js"; import { killTrackedDetachedChildren } from "../../utils/shell.js"; import { startHostChildReaper } from "./child-reaper.js"; import { warmAtBootForPrivateFds } from "./host-boot-extensions.js"; import { CommandAuthority, commandAuthority, takeRelayExec } from "./command-authority.js"; import { answerDelegation, relayExecRefusal } from "./delegated-answer.js"; import { parseClientCapabilities } from "./custom-capability.js"; import { ClientOccupancy } from "./host-client-occupancy.js"; import { HostCoreGate } from "./host-core-gate.js"; import { bindRegisteredEndpoint } from "./host-bare-endpoint-registration.js"; import { createHostDaemonPaths } from "./host-daemon-paths.js"; import { ENDPOINT_OWNER_FENCE_CAPABILITY, GENERATION_HANDOFF_CAPABILITY } from "./host-decision.js"; import { HandoffAnnouncement } from "./host-handoff-announcement.js"; import { reopenHandoverParkedSessions } from "./host-handover-reopen.js"; import { performIdleHandover } from "./host-handover-wire.js"; import { publishHostInstanceId } from "./host-identity-env.js"; import { listenForSuccessor } from "./predecessor-endpoint.js"; import { authRecord } from "./rpc-auth-proof.js"; import { EXPECTED_RUNTIME_BUILD_ID_ENV } from "./host-idle-handover.js"; import { RPC_CLOSE_GRACE_MS_ENV, resolveHostIdlePolicy } from "./host-idle-policy.js"; import { hostWatchdogBinding, internalHostTransport } from "./host-internal-transport.js"; import { parseIdleExitMs } from "./host-lifecycle.js"; import { prepareSocketPath } from "./host-lifecycle-proxy.js"; import { isHostOccupancyWatch } from "./host-observe-request.js"; import { createZeroSessionTrim, startHostObservers } from "./host-observers.js"; import { HostOccupancyWatch } from "./host-occupancy-watch.js"; import { closeHostConnections } from "./host-shutdown-connections.js"; import { runAsHostGenerationProcess } from "./host-process-role.js"; import { createEndpointReservations } from "./host-reservations.js"; import { hostChildDrainRequestFile, watchDrainRequest } from "./host-stop-intent.js"; import { armHostWatchdog } from "./host-watchdog.js"; import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from "./jsonl.js"; import { MachineOpHandler } from "./machine-op/handler.js"; import { withOpenRetention } from "./open-retention.js"; import { hostGeneration, hostInstanceId, protocolIdentity } from "./protocol-identity.js"; import { rpcCommandShapeError } from "./rpc-input-validation.js"; import { computeRuntimeBuildId, RUNTIME_IDENTITY_HANDOVER_CAPABILITY } from "./runtime-build-id.js"; import { SessionCommandRouter } from "./session-command-router.js"; import { SessionEventWriter } from "./session-event-writer.js"; import { canonicalSessionPath } from "./session-path-key.js"; import { RpcSessionRegistry, RpcSessionRegistryError } from "./session-registry.js"; import { PUBLIC_SOCKET_IDENTITY_FILE, readSocketIdentityFile, socketEntryReplaced, waitForSocketIdentityFile, } from "./socket-ownership.js"; import { closeShieldedEndpoint, unlinkOwnedEndpoint } from "./host-endpoint-owner.js"; import { formatSocketAddress, listen, resolveSocketPath } from "./host-socket-bind.js"; import { socketSink } from "./socket-sink.js"; import { ensureSocketSecret, SOCKET_SECRET_FILE_ENV, socketSecretPath } from "./socket-transport.js"; import { WorkerSessionRegistry } from "./worker-session-registry.js"; import { presenterBootstrapStream } from "./mcp-presenter-bootstrap.js"; import { startMcpPresenterControl } from "./mcp-presenter-control-start.js"; export { presenterPipePath } from "./mcp-presenter-control-start.js"; export { DEFAULT_HOST_EMPTY_EXIT_MS, DEFAULT_SESSION_IDLE_EVICTION_MS, RPC_HOST_EMPTY_EXIT_MS_ENV, RPC_SESSION_IDLE_EVICTION_MS_ENV, resolveHostIdlePolicy, } from "./host-idle-policy.js"; /** Win32 named-pipe close can leave libuv's server callback pending after handles are destroyed. */ const WINDOWS_SHUTDOWN_HARD_EXIT_MS = 2_000; /** * How long a win32 shutdown waits for its sessions to finish closing (#3652). A TerminateProcess'd * supervisor runs no stop of its own, its watchdog removes the pointer at once, and until the * connections detach this host's claims still read `attached: true` - so an unbounded dispose would * hold every session file it served for as long as one close stays wedged. */ const WINDOWS_SHUTDOWN_DISPOSE_BOUND_MS = 10_000; /** * Socket agent events are delivered only to connections attached to their * session, tagged with its routing sessionId. Content-free session lifecycle * events remain visible to every connection. Responses and extension UI * requests remain requester-only; foreign observation uses attach-on-open. */ export async function runMultiSessionHost(options) { return runAsHostGenerationProcess(() => options.listen === undefined || options.listen === "stdio://" ? runStdioHost(options) : runSocketHost(options, resolveSocketPath(options.listen, options.agentDir))); } export function createHostCore(options, writer, capabilities = parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")), idle = {}, hostContext, hooks = {}) { if (options.mcpPresenterEnforcement === true) writer.enableMcpPresenters(); const machineOwned = options.sessionOwner === "machine"; const policy = resolveHostIdlePolicy(process.env, machineOwned ? { ...idle, emptyExitMs: Number.POSITIVE_INFINITY } : idle); const endpointSocket = publicEndpointSocket(options); const pathReservations = createEndpointReservations({ agentDir: options.agentDir, socket: listenSocketPath(options), instanceId: hostInstanceId(), publicSocket: hostContext?.host_socket, onFailure: hostLog, }); const registry = options.workerConfiguration ? new WorkerSessionRegistry({ configuration: options.workerConfiguration, now: policy.now, closeGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000, pathReservations, }) : new RpcSessionRegistry({ agentDir: options.agentDir, createRuntime: options.createRuntime, mcpRegistry: new HostMcpRegistry(), now: policy.now, closeGraceMs: idle.closeGraceMs ?? parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV]) ?? 10_000, // Two generations of this daemon can be alive at once during a handoff; the claims // they publish here are what keeps them off one session file. ...(hooks.onSessionCountChange ? { onSizeChange: hooks.onSessionCountChange } : {}), pathReservations, }); const machineOps = new MachineOpHandler({ agentDir: options.agentDir }); const router = new SessionCommandRouter(registry, writer, hostContext ? { ...options, hostContext } : options, options.createBinding, { capabilities }, { now: policy.now, idleEvictionMs: policy.idleEvictionMs, emptyExitMs: policy.emptyExitMs, // Held in the same step as the exit decision: no machine op may start on a host that is ending (senpi#6752). onEmptyExit: idle.onEmptyExit === undefined ? undefined : () => { machineOps.hold(); idle.onEmptyExit?.(); }, onHandoffParked: idle.onHandoffParked, ...(endpointSocket === undefined ? {} : { handoverParkedDir: createHostDaemonPaths({ socket: endpointSocket, agentDir: options.agentDir, }).dir, }), // The host's own gate first, then machine work: an empty exit would end every relay-host terminal (senpi#6752). canExitWhenEmpty: () => (idle.canExitWhenEmpty?.() ?? true) && !machineOps.busy(), }); if (endpointSocket !== undefined) reopenHandoverParkedSessions(async (entry) => { const refused = await router.reopenParked(entry); if (refused?.success !== false) return; const detail = typeof refused.errorData === "object" && refused.errorData !== null && !Array.isArray(refused.errorData) ? Object.fromEntries(Object.entries(refused.errorData)) : undefined; throw refused.error === "session_path_in_use" ? new RpcSessionRegistryError("session_path_in_use", undefined, detail) : new RpcSessionRegistryError("open_failed", refused.error); }, options.agentDir, endpointSocket, { hostInstance: hostInstanceId(), hostSocket: endpointSocket, ...(hooks.shouldReopenParked !== undefined ? { shouldReopen: hooks.shouldReopenParked } : {}), onProgress: (state) => router.setInheritedHandover(state), }).catch((cause) => { router.setInheritedHandover(undefined); process.stderr.write(`senpi rpc successor reopen parked set failed: ${String(cause)}\n`); }); const gate = new HostCoreGate(registry, (command) => router.handle(command), { ...hooks, machineWork: machineOps, }); const handle = async (line) => { const connection = writer.currentConnection(); let parsed; try { parsed = JSON.parse(line); } catch { await writer.enqueueControl(writer.delegations.unparsable(connection, "Failed to parse command: invalid JSON")); return; } // omo-relay-daemon#307: a host-mode delegated line runs under one authority snapshot, its forwarder's `relayExec` // taken out of the record before anything else reads it. const delegation = writer.connectionContext.delegation; if (delegation?.mode !== "host") return handleParsed(connection, parsed); const exec = takeRelayExec(parsed); if (exec === "malformed") { await writer.enqueueControl(relayExecRefusal(parsed)); return; } return commandAuthority.run(new CommandAuthority(connection, delegation, exec), () => handleParsed(connection, parsed)); }; const handleParsed = async (connection, parsed) => { if (connection?.startsWith("generation-route-") && !router.admitsRoutedRecord(connection, parsed)) { const record = authRecord(parsed); await writer.enqueueControl({ type: "response", id: record?.id, command: record?.type, success: false, error: "host_draining", }); return; } // Before any await: a declaration takes effect for the very next line of its connection (senpi#5632). const delegation = writer.delegations.inspect(connection, parsed); if (delegation.kind === "machine_op") { await writer.enqueueControl(await machineOps.answer(delegation.command, parsed, delegation.id)); return; } if (delegation.kind !== "pass") { const declaration = authRecord(parsed); if (connection && declaration?.type === "declare_delegation" && delegation.kind === "reply" && delegation.response.success) await router.configureRoutes(connection, declaration); await answerDelegation(writer, delegation, parsed); return; } // A delegated connection ends with the viewer it forwards for, while the forwarder keeps serving what it opened to // the next one: every open on it is retained, whatever it asks, so its end detaches and never closes (senpi#5808). // Read at line receipt, so a connection that ends before the open is dispatched still counts as delegated. const delegated = writer.delegations.isDelegated(connection); if (writer.handleMcpForm(parsed)) return; if (await gate.intercept(parsed, (answer) => writer.enqueueControl(answer))) return; const shapeError = rpcCommandShapeError(parsed); if (shapeError) { await writer.enqueueControl(parseError(shapeError)); return; } const command = parsed; const response = await gate.dispatch(withOpenRetention(command, delegated, machineOwned)); if (connection && command.type === "set_client_info" && !command.sessionId && authRecord(response)?.success === true) await router.configureRoutes(connection, command); if (response) await writer.enqueueControl(response); writer.delegations.lineAnswered(connection); }; return { router, handle, /** senpi#6752: the host's `machine_op` handler; its terminals end at host shutdown. */ machineOps, handover: gate.handover, handoverAnswered: () => gate.answered(), /** The in-process registry's `warm`; the worker registry has none. */ warm: "warm" in registry ? registry.warm : undefined, /** * A session's live registry entry by its routing id. Only in-process test fixtures read it today, in place of * spying on the registry prototype (senpi#5802); the host itself never calls it. */ peekSession: (sessionId) => registry.peek(sessionId), }; } /** Plain-stdio host with no eagerly-created AgentSessionRuntime. */ async function runStdioHost(options) { takeOverStdout(); const sink = { writeRaw: writeRawStdout, waitForBackpressure: waitForRawStdoutBackpressure }; const writer = new SessionEventWriter(sink.writeRaw, sink.waitForBackpressure); // An empty host (no session ever opened, or all closed) must not stay resident // forever: exit through the normal shutdown path once the window elapses. const runtimeBuildId = await startupRuntimeBuildId(); const trim = createZeroSessionTrim(writer, () => router.sessionCount); const { router, handle, warm, machineOps } = createHostCore(options, writer, undefined, { onEmptyExit: () => void shutdown(0) }, undefined, { ...(runtimeBuildId === undefined ? {} : { runtimeBuildId }), onSessionCountChange: (size) => trim.observe(size), }); const observers = startHostObservers(router, writer, { trim }); let shuttingDown = false; const shutdown = async (exitCode = 0) => { if (shuttingDown) process.exit(exitCode); shuttingDown = true; observers.stop(); detach(); await router.dispose(); await machineOps.dispose(); await writer.flush(); await flushRawStdout(); process.exit(exitCode); }; const onEnd = () => void shutdown(); process.stdin.on("end", onEnd); const reportInputFailure = (cause) => { process.stderr.write(`senpi rpc stdio request failed: ${errorMessage(cause)}\n`); }; const detachReader = attachJsonlLineReader(process.stdin, (line) => void handle(line).catch(reportInputFailure), { maxLineLength: MAX_RPC_LINE_CHARACTERS, onOversizedLine: () => void writer.enqueueControl(parseError(oversizedLineError())).catch(reportInputFailure), }); const detach = () => { detachReader(); process.stdin.off("end", onEnd); }; registerShutdownSignals(shutdown); warmAtBootForPrivateFds(warm, { cwd: options.cwd }, hostLog); return new Promise(() => { }); } async function runSocketHost(options, socketPath) { await prepareSocketPath(socketPath); publishHostInstanceId(hostInstanceId()); const writer = new SessionEventWriter(() => { }); const connections = new Map(); // The supervisor's rule for which clients hold a host open (host-client-occupancy.ts): a // connection that has only sent observing reads (`status`) is not occupancy. const occupancy = new ClientOccupancy(() => { }, hostInstanceId()); let draining = false; let handoffAnnounced = false; const handoff = new HandoffAnnouncement(); const hostContext = hostSessionContext(socketPath); const runtimeBuildId = await startupRuntimeBuildId(); const expected = process.env[EXPECTED_RUNTIME_BUILD_ID_ENV]; if (expected !== undefined && expected !== runtimeBuildId) { // An idle handover started this host for a runtime it does not run (the files changed since the // request). Exiting before it listens leaves the predecessor serving, and the handover blocked. hostLog(`runtime ${runtimeBuildId ?? "unreadable"} is not the handover target ${expected}; exiting`); process.exit(1); } const canHandOver = runtimeBuildId !== undefined && process.platform !== "win32"; const trim = createZeroSessionTrim(writer, () => router.sessionCount); const { router, handle, handover, handoverAnswered, warm, machineOps } = createHostCore(options, writer, [ ...parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")), // A socket host installs the SIGUSR1 drain below, so it can be handed off to a newer // generation instead of being killed. A host that does not advertise this is never // signalled - SIGUSR1 would simply terminate it, sessions and all. GENERATION_HANDOFF_CAPABILITY, // Every rename/remove of its public entry runs under the endpoint fence (senpi#4602 Q1). ENDPOINT_OWNER_FENCE_CAPABILITY, // The host reports the runtime it loaded and can hand over at its next idle point. ...(canHandOver ? [RUNTIME_IDENTITY_HANDOVER_CAPABILITY] : []), ], // Supervised hosts idle-exit via the supervisor, but a socket host that // outlives its supervisor (or is started bare) still self-exits when empty. // A connected client counts as occupancy even with no session open: exiting // under it would drop its socket and read as a crash to the supervisor. Only an // OBSERVER does not - one whose every request so far was an `observe: true` read. // While DRAINING the opposite is true: the successor generation owns the socket, so a // sessionless connection must not hold this host open. { onEmptyExit: () => void shutdown(0), // A watching supervisor owns the idle exit: its observer link never ends this host from here. canExitWhenEmpty: () => draining || (occupancy.attachedCount === 0 && occupancy.unclassifiedCount === 0 && !occupancyWatch.watching), onHandoffParked: async (ids) => { await Promise.all(ids.map(async (id) => { await writer.flushConnection(id); await connections.get(id)?.close("host_handoff"); })); }, }, hostContext, { onSessionCountChange: (size) => { trim.observe(size); // A session the host closed itself (eviction, park) has left its owners' records by now. occupancyWatch.refresh(); }, // A draining predecessor parks its retained sessions for the successor and must not reopen // them into its own registry (senpi#3282). Gate the reopen watch on not draining. shouldReopenParked: () => !draining, ...(runtimeBuildId !== undefined && { runtimeBuildId }), ...(canHandOver && { endpoint: { agentDir: options.agentDir, socket: hostWatchdogBinding()?.publicSocket ?? socketPath, }, handover: { identity: () => ({ instanceId: hostInstanceId(), generation: hostGeneration(process.env), runtimeBuildId, engine: engineBuildIdentity(), }), perform: async (request) => performIdleHandover({ // Prepared only when the successor reaches its P7, never before it boots (senpi#4602). presenterBootstrap: presenterControl?.successorBootstrapProvider(), request, socket: hostWatchdogBinding()?.publicSocket ?? socketPath, agentDir: options.agentDir, }), log: hostLog, }, }), }); const occupancyWatch = new HostOccupancyWatch({ connections: () => connections.keys(), attached: (id) => { const socket = connections.get(id)?.socket; return socket !== undefined && occupancy.isAttached(socket); }, holdsSessions: (id) => router.holdsSessions(id), send: (id, record) => void writer .enqueueControl(record, id) .catch((cause) => hostLog(`host_occupancy to ${id} failed: ${errorMessage(cause)}`)), }); const presenter = await startMcpPresenterControl(writer, { enforcement: options.mcpPresenterEnforcement, bootstrap: options.presenterBootstrapFd === undefined ? undefined : presenterBootstrapStream(options.presenterBootstrapFd), account: options.presenterAccountAuthority, }); const presenterControl = presenter?.control; const presenterDir = presenter?.dir; const observers = startHostObservers(router, writer, { trim, // The shape #1893 measured: gigabytes resident with `sessions.total 0`. Say it once, and when // this generation no longer owns the endpoint, leave - nobody can reach it to ask. onIdlePressure: ({ footprintMb, measure, rssMb }) => { hostLog(`memory pressure with no sessions: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb}`); void endpointSuperseded().then((superseded) => { if (superseded) drainForHandoff(); }, noop); }, }); let nextConnection = 0; let shuttingDown = false; // omo-relay-daemon#307: a socket whose incarnations ran out is ended once its detach answer is flushed (engine_closed). writer.endExhaustedConnections((id) => connections.get(id)?.sink); const secret = process.platform === "win32" ? await ensureSocketSecret(process.env[SOCKET_SECRET_FILE_ENV] ?? socketSecretPath(socketPath)) : undefined; const transport = internalHostTransport(hostWatchdogBinding(), secret, { agentDir: options.agentDir, socket: socketPath, log: hostLog, }); const { watchdogConfig, admit } = transport; // This host's OWN copy of the crash-path cleanup list. A drain empties it: once a successor // generation is registered, the daemon state files under those paths describe the successor, // and a crash of this (already replaced) host must not take them with it. const crashCleanupPaths = [...(watchdogConfig?.cleanupPaths ?? [])]; // Crash-path ownership for the supervisor's PUBLIC socket: the supervisor // records the identity of the entry it bound (inside its private scratch // directory, which no replacement supervisor writes) right after its listen, // and this host removes that path only while the identity still matches. A // blind path removal here would unlink a newer host's freshly published // entry after a takeover - the startup path already refuses to touch a // socket owned by a live server; teardown follows the same rule. const supervisorPublicSocketPath = process.platform === "win32" || socketPath.startsWith("\0") ? undefined : watchdogConfig?.publicSocket; const supervisorPublicOwnerFile = supervisorPublicSocketPath && watchdogConfig?.scratchDir ? join(watchdogConfig.scratchDir, PUBLIC_SOCKET_IDENTITY_FILE) : undefined; let boundIdentity; let supervisorPublicIdentity; const serve = (socket, arrivedBeforeDrain, launchProof, routed = false) => { if (!routed && draining && !shuttingDown && handoff.deliverLate(socket, arrivedBeforeDrain)) return; if ((!routed && draining) || shuttingDown) { socket.destroy(); return; } const id = `${routed ? "generation-route" : "socket"}-${++nextConnection}`; const sink = socketSink(socket); writer.registerConnection(id, sink, launchProof === undefined ? {} : { launchProof }); occupancy.admit(socket); const detachReader = attachJsonlLineReader(socket, (line) => { if (isHostOccupancyWatch(line)) { occupancyWatch.watch(id); return; } // Do not serialize awaited commands: extension_ui_response and other // re-entrant frames must be able to resolve a command already awaiting them. occupancyWatch.begin(id); void writer .withConnection(id, () => handle(line)) .catch((cause) => { process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}\n`); }) .finally(() => occupancyWatch.end(id)); }, { maxLineLength: MAX_RPC_LINE_CHARACTERS, onOversizedLine: () => { void writer .withConnection(id, () => writer.enqueueControl(parseError(oversizedLineError()))) .catch((cause) => process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}\n`)); }, }); let detached = false; const detach = () => { if (detached) return; detached = true; detachReader(); writer.unregisterConnection(id); connections.delete(id); occupancy.release(socket); occupancyWatch.forget(id); // A socket that dies without close_session still owns its sessions' attachments // and path reservations. Release them on the command chain so this runs after any // in-flight command for this connection settles, otherwise the path stays pinned // by a runtime whose client is gone and later resumes attach to that orphan. void router.releaseConnection(id).catch((cause) => { process.stderr.write(`senpi rpc connection ${id} release failed: ${errorMessage(cause)}\n`); }); }; // An announced close half-closes so `socket_closing` is flushed first (SOCKET_CUT_GRACE_MS bounds it). const close = (code) => writer.closeConnection(id, code, (announced) => (announced ? sink.close?.() : socket.destroy())); connections.set(id, { id, sink, socket, detach, close }); socket.once("close", detach); socket.once("error", () => detach()); }; const server = createServer((socket) => { const arrivedBeforeDrain = !draining && !shuttingDown; admit(socket, (stream = socket, proof) => serve(stream, arrivedBeforeDrain, proof)); }); let stopRoute; server.on("error", (cause) => { if (!shuttingDown) process.stderr.write(`senpi rpc socket listener failed: ${errorMessage(cause)}\n`); }); // Long-lived hosts outlive many session workers, and a terminated worker thread // takes its children's exit watchers with it (measured: every spawn API leaks // that way). The reaper claims those abandoned children; it never touches one a // live thread could still be waiting for. const stopChildReaper = await startHostChildReaper(hostLog); const shutdown = async (exitCode = 0, watchdogCleanup) => { if (shuttingDown) process.exit(exitCode); shuttingDown = true; const startedAt = Date.now(); observers.stop(); handover?.dispose(); presenterControl?.dispose(); if (presenterDir) await rm(presenterDir, { recursive: true, force: true }); stopChildReaper(); // A handover that completed at once drains this host; its caller still gets the answer. await handoverAnswered(); // On Windows, destroying named-pipe sockets does not always make libuv's // server.close callback fire: connected pipe instances can remain in the // kernel after the JavaScript handles are destroyed. Keep the normal drain // path, but never let that platform-specific close stall orphan the host. try { // Dispose while connections are still registered so `session_closed` // `{ reason: "host_shutdown" }` reaches clients before the sockets die. await (process.platform === "win32" ? Promise.race([router.dispose(), delay(WINDOWS_SHUTDOWN_DISPOSE_BOUND_MS)]) : router.dispose()); await machineOps.dispose(); const open = [...connections.values()]; const cancelForce = await closeHostConnections(open, (id) => writer.flushConnection(id), startedAt, hostLog); // libuv unlinks the bound NAME when the listening handle closes - which // would delete a newer host's entry renamed over this path. Shield the // current entry for the close, then let the ownership check decide. await closeShieldedEndpoint(socketPath, () => process.platform === "win32" ? Promise.race([closeServer(server), delay(WINDOWS_SHUTDOWN_HARD_EXIT_MS)]) : closeServer(server)); cancelForce(); // Ownership-checked: unlink only the entry THIS process bound. After a // takeover renamed a newer host's socket over the same path, the // identity no longer matches and the replacement stays published. await unlinkOwnedEndpoint(socketPath, boundIdentity, hostInstanceId(), hostLog); if (supervisorPublicSocketPath) { await unlinkOwnedEndpoint(supervisorPublicSocketPath, supervisorPublicIdentity, hostInstanceId(), hostLog); } if (watchdogCleanup) await watchdogCleanup; } finally { await stopRoute?.(); await transport.dispose(); // Explicitly terminate after every shutdown trigger. Windows named-pipe // handles are not fully controllable from JS, and an unresolved cleanup // must not leave this daemon or its public endpoint alive. process.exit(exitCode); } }; /** * Announce through the record writer, never inside the supervisor's raw byte proxy. This * preserves JSONL framing and FIFO before parking, including when a record spans proxy reads. * Active turns/requests keep running; durable wake-source holds resume on reopen. */ const drainForHandoff = () => { if (shuttingDown) return; if (draining) { if (handoffAnnounced) router.beginDrain(); return; } draining = true; crashCleanupPaths.length = 0; hostLog("draining for a generation handoff"); const identity = { instanceId: hostInstanceId(), generation: hostGeneration(process.env) }; void handoff .begin(endpointSuperseded(), identity, supervisorPublicSocketPath ?? socketPath, hostLog) .then((announced) => announced && writer.broadcastHostRecord(announced)) // A failed announcement still drains: parking is what lets this generation exit (senpi#2285). .finally(() => { handoffAnnounced = true; router.beginDrain(); }); }; /** * Whether the endpoint this host serves is held by another socket entry now. A supervised host * answers for the PUBLIC path its supervisor bound - its own listener is a private hop nobody * replaces - and a bare host for the path it bound itself. */ const endpointSuperseded = () => supervisorPublicSocketPath === undefined ? socketEntryReplaced(socketPath, boundIdentity) : socketEntryReplaced(supervisorPublicSocketPath, supervisorPublicIdentity); registerShutdownSignals(shutdown); if (process.platform !== "win32") process.on("SIGUSR1", drainForHandoff); // The supervisor's signal-free relay, the drain channel every platform shares (#3653). const drainRequestFile = hostChildDrainRequestFile(); if (drainRequestFile !== undefined) watchDrainRequest(drainRequestFile, drainForHandoff); // Arm before listen: a supervisor death during the listen transition must // still close the child and clean its private endpoint. const watchdog = watchdogConfig && supervisorPublicOwnerFile ? { ...watchdogConfig, cleanupPaths: crashCleanupPaths, // The supervisor may die while this host is still waiting for the token // below; read it before the watchdog removes the scratch directory, or the // shutdown's ownership check has nothing to prove with and leaves the // public socket behind. beforeCleanup: async () => { supervisorPublicIdentity ??= await readSocketIdentityFile(supervisorPublicOwnerFile); }, } : watchdogConfig && { ...watchdogConfig, cleanupPaths: crashCleanupPaths }; armHostWatchdog(watchdog, (reason, cleanup) => { process.stderr.write(`senpi rpc host: ${reason}; shutting down\n`); // Enter shutdown before killing session-owned child processes. The Windows // tree killer is synchronous, while the shutdown fallback must be armed // before any such cleanup can delay the event loop. void shutdown(0, cleanup); setImmediate(killTrackedDetachedChildren); }); // Everything the internal listener needs is initialized: the runtime milestone of a coordinated start (senpi#4602). reportStartupMilestone("host_runtime"); const bind = () => listen(server, socketPath, secret); // A host binding its own public socket keeps its registry record; a supervised one's ensure keeps it. boundIdentity = await (hostWatchdogBinding() === undefined ? bindRegisteredEndpoint({ agentDir: options.agentDir, socket: socketPath, log: hostLog }, bind) : bind()); // A key record that cannot be published safely ends this host: held connections are refused, never served keyless. await transport.publish(() => shutdown(1)); const drainFile = hostChildDrainRequestFile(); if (watchdogConfig && drainFile && process.platform !== "win32") stopRoute = await listenForSuccessor(options.agentDir, socketPath, dirname(drainFile), (stream) => serve(stream, false, "in_band", true)); if (supervisorPublicOwnerFile) { // The supervisor publishes its public-socket token after this internal // listener is ready, so a short bounded wait keeps the lifecycles in step // without delaying unsupervised hosts. supervisorPublicIdentity = await waitForSocketIdentityFile(supervisorPublicOwnerFile); } process.stderr.write(`senpi rpc listening on ${formatSocketAddress(socketPath)}\n`); warmAtBootForPrivateFds(warm, { cwd: options.cwd, sessionContext: hostContext }, hostLog); // Opt-in only: set by the lifecycle supervisor so this host can never outlive // it, including when the supervisor is SIGKILLed and runs no handler at all. return new Promise(() => { }); } /** * The runtime this process loaded, digested once before it serves anything. A runtime that cannot * be read leaves the host unverified (no `runtimeBuildId`, no handover capability) instead of * keeping it from starting. */ async function startupRuntimeBuildId() { try { return await computeRuntimeBuildId({ profile: protocolIdentity().launch_profile.core }); } catch (cause) { hostLog(`runtime identity unreadable: ${errorMessage(cause)}`); return undefined; } } function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } function noop() { } function parseError(error) { return { type: "response", command: "parse", success: false, error }; } function oversizedLineError() { return `RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`; } function errorMessage(cause) { return cause instanceof Error ? cause.message : String(cause); } /** * The identity every session on this socket host carries in its context: `host_socket`, the PUBLIC * endpoint clients address (the supervisor's path for a supervised host, whose own listener is a * private hop; the bound path for a bare one), realpath-canonicalized so it compares equal however * the path was spelled; and `host_instance`, this generation. The endpoint is stable across handoffs, * the instance is not. The FIRST generation runs this before its supervisor has created the socket's * directory, a successor after, so the directory is canonicalized through its deepest existing * ancestor: both then stamp the same spelling. `host_socket` is omitted where no public path exists * (abstract sockets, a supervised host whose supervisor passed none). Exported for tests. */ export function hostSessionContext(socketPath, supervised = hostWatchdogBinding()) { const endpoint = supervised === undefined ? socketPath : supervised.publicSocket; if (endpoint === undefined || endpoint.startsWith("\0")) return { host_instance: hostInstanceId() }; const directory = canonicalSessionPath(dirname(endpoint)); return { host_socket: join(directory, basename(endpoint)), host_instance: hostInstanceId() }; } /** The endpoint this host listens on, or nothing when it speaks stdio and shares no socket. */ function listenSocketPath(options) { if (options.listen === undefined || options.listen === "stdio://") return undefined; return resolveSocketPath(options.listen, options.agentDir); } /** * The PUBLIC endpoint clients address, matching `hostSessionContext`: a supervised host's own * listener is a private hop, so the daemon-directory key must come from the supervisor's public * socket or every generation hashes a different directory (senpi#3282). Bare hosts bind the path. */ function publicEndpointSocket(options) { const supervised = hostWatchdogBinding(); if (supervised !== undefined) return supervised.publicSocket; return listenSocketPath(options); } function closeServer(server) { return new Promise((resolve, reject) => { server.close((cause) => (cause ? reject(cause) : resolve())); }); } function hostLog(message) { process.stderr.write(`senpi rpc host: ${message}\n`); } function registerShutdownSignals(shutdown) { for (const signal of process.platform === "win32" ? ["SIGTERM"] : ["SIGTERM", "SIGHUP"]) { process.on(signal, () => { killTrackedDetachedChildren(); void shutdown(signal === "SIGHUP" ? 129 : 143); }); } } //# sourceMappingURL=multi-session-host.js.map