UNPKG

@code-yeongyu/senpi

Version:

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

318 lines • 16.9 kB
#!/usr/bin/env node var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { env.stack.push({ async: true }); } return value; }; var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { return function (env) { function fail(e) { env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } var r, s = 0; function next() { while (r = env.stack.pop()) { try { if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); if (r.dispose) { var result = r.dispose.call(r.value); if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); } else s |= 1; } catch (e) { fail(e); } } if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); }; })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }); // First: report the coordinated start before the lifecycle graph loads (senpi#4602). import "./host-startup-beacon.js"; import "../../private-fds.js"; import { randomUUID } from "node:crypto"; import { mkdir, rm } from "node:fs/promises"; import { join } from "node:path"; import { getAgentDir, isBundledNode, VERSION } from "../../config.js"; import { HostAdmission } from "./host-admission.js"; import { classifyChildExit, noteChildExit } from "./host-child-exit.js"; import { hostCrashCleanupPaths } from "./host-cleanup-paths.js"; import { isCliModuleEntry } from "./host-cli-entry.js"; import { createGenerationDirectory, createHostDaemonPaths, generationPaths, HostDaemonStateError, } from "./host-daemon-paths.js"; import { HOST_INSTANCE_ID_ENV } from "./host-identity-env.js"; import { SupervisorActivity, SupervisorOwner } from "./host-lifecycle-activity.js"; import { drainOnPublicSocketLoss, recordDrainOverdue, SupervisorDrain, watchWin32ChildIdentity, } from "./host-lifecycle-drain.js"; import { prepareInternalHop } from "./host-lifecycle-internal-key.js"; import { HOST_CHILD_WATCH_FD, loadHostChildTrustHandOff, parseSupervisorArgs, spawnHostChild, } from "./host-lifecycle-launch.js"; import { resolveHostPolicy } from "./host-lifecycle-policy.js"; import { awaitInternalStartup, declareHostChild, hostChildReportsStartup, hostChildSpawned, publishSupervisorEndpoint, supervisorPublished, } from "./host-lifecycle-startup.js"; import { createPublicProxy, ensurePublicSocketSecret } from "./host-lifecycle-proxy.js"; import { readSettingsFile, recordChildPid } from "./host-lifecycle-scratch.js"; import { performShutdown, registerSupervisorSignals, supervisorSender, } from "./host-lifecycle-shutdown.js"; import { startSupervisorTicker } from "./host-lifecycle-ticker.js"; import { errorMessage, writeHostReady, writeStderrLine } from "./host-supervisor-log.js"; import { RpcPublicEndpoint } from "./rpc-public-key.js"; import { PUBLIC_SOCKET_IDENTITY_FILE, statSocketIdentity, writeSocketIdentityFile } from "./socket-ownership.js"; // The exit verdict, the launch surface and the cold-start/idle-exit policy live in their own modules // (host-child-exit.ts, host-lifecycle-launch.ts, host-lifecycle-policy.ts); they stay exported from // here so every existing importer keeps resolving them at their original home. export { classifyChildExit } from "./host-child-exit.js"; export { findInternalSupervisorArgs, INTERNAL_SUPERVISOR_FLAG, parseSupervisorArgs, resolveCliMainPath, resolveHostChildLaunch, spawnableChildLaunch, } from "./host-lifecycle-launch.js"; export { DEFAULT_HANDOFF_GRACE_MS, DEFAULT_HOST_IDLE_EXIT_MS, HANDOFF_GRACE_MS_ENV, HOST_COLD_START_ENV, HOST_IDLE_EXIT_MS_ENV, IdleExitDecider, parseColdStart, parseIdleExitMs, resolveHostPolicy, } from "./host-lifecycle-policy.js"; export { createInternalSocketPath } from "./host-lifecycle-scratch.js"; export { HOST_CHILD_LISTEN_MS } from "./host-lifecycle-startup.js"; export async function runHostSupervisor(launch) { const env_1 = { stack: [], error: void 0, hasError: false }; try { const paths = createHostDaemonPaths({ socket: launch.socket, agentDir: launch.agentDir ?? getAgentDir() }); // Which generation this supervisor is: the ensure that spawned it says so, and a DIRECT launch // (the hidden supervisor route, with no ensure behind it) names itself so its child agrees. const told = process.env[HOST_INSTANCE_ID_ENV]; const instanceId = told !== undefined && told.trim() !== "" ? told : randomUUID(); const generation = generationPaths(paths, instanceId); const created = await mkdir(generation.dir, { recursive: true, mode: 0o700 }).catch((cause) => { throw new HostDaemonStateError(generation.dir, cause); }); let startupRegistered = false; const _generationStartup = __addDisposableResource(env_1, { async [Symbol.asyncDispose]() { // An ensured directory is not ours to discard. Until shutdown owns a new one, // every failed startup must remove it, including failures after child spawn. if (created !== undefined && !startupRegistered) { await rm(generation.dir, { recursive: true, force: true }); } }, }, true); // A direct launch has no ensure to provision its records before the child can write them. await createGenerationDirectory(generation); const settings = await readSettingsFile(paths.settingsFile); const policy = resolveHostPolicy(settings, process.env); const publicSocket = launch.socket; const publicEndpoint = process.platform === "win32" ? undefined : new RpcPublicEndpoint(launch.agentDir ?? getAgentDir(), publicSocket); // A successor generation binds its own name and adopts the public one by rename; an ordinary // start binds the public name directly. Everything downstream - the child's environment, the // ownership token, the teardown - is expressed in terms of the PUBLIC path either way. // Direct-launch contract: the supervisor owns the public secret. ensureHost() // writes it before spawning, but the hidden --internal-rpc-host-supervisor route // has no such caller, so a fresh profile would otherwise die reading it (#1370). // It is provisioned BEFORE the internal hop and the child so a provisioning // failure leaves no scratch directory and no host process behind. const publicSecret = process.platform === "win32" ? await ensurePublicSocketSecret(publicSocket) : undefined; const hop = await prepareInternalHop(paths.dir); const { internal, internalSocket, internalSecret, internalKey } = hop; const state = { shuttingDown: false, shutdownReason: undefined, childExitRecorded: Promise.resolve(), startupComplete: Promise.resolve(), publicSocketOwned: false, publicSocketIdentity: undefined, endpointReplaced: false, }; const owner = new SupervisorOwner(generation.dir); const activity = new SupervisorActivity({ idleExitMs: policy.coldStart === "persistent" ? Number.POSITIVE_INFINITY : policy.idleExitMs, internalSocket, ...hop.transport, instanceId, settled: () => state.shuttingDown, onActivity: () => owner.activity(), }); const watchers = []; declareHostChild(launch.childCommand); const child = spawnHostChild({ launch, reportsStartup: hostChildReportsStartup(launch.childCommand), trustHandOff: await loadHostChildTrustHandOff(), internalSocket, internal, ...hop.transport, supervisorStart: hop.supervisorStart, lifetimeFifo: hop.lifetimeFifo, daemonDir: paths.dir, instanceId, cleanupPaths: hostCrashCleanupPaths({ pointerFile: paths.pointerFile, generationPidFile: generation.pidFile, settingsFile: paths.settingsFile, publicSocket, successor: launch.bindSocket !== undefined, platform: process.platform, }), publicSocket, }); const childStartedAt = Date.now(); await hostChildSpawned(child, generation.dir, hop.supervisorStart?.time); // Nothing is ever written; the pipe exists purely so its EOF is a reliable // death notification. Errors on it must not crash the supervisor. child.stdio[HOST_CHILD_WATCH_FD]?.on("error", () => { }); // The CHILD's own identity, so a reader can tell "supervisor gone, child still running" apart. if (child.pid !== undefined) void recordChildPid(generation.childPidFile, child.pid, () => child.exitCode === null && child.signalCode === null); child.once("exit", (code, signal) => { // Recorded BEFORE any shutdown it triggers: `shutdown` ends in `process.exit`. A stop the // supervisor is performing itself is recorded too, as the engine stop it is. const reason = state.shutdownReason; state.childExitRecorded = noteChildExit({ daemonDir: paths.dir, generation, instanceId, code, signal, childStartedAt, ...(state.shuttingDown && reason !== undefined ? { shutdown: { reason, supervisor: supervisorSender(instanceId) } } : {}), }); if (state.shuttingDown) return; const verdict = classifyChildExit(code, signal); void state.childExitRecorded.then(() => shutdown(verdict.reason, verdict.exitCode)); }); const admission = new HostAdmission({ protocolVersion: 1, serverVersion: VERSION, capabilities: [], instanceId }); const drain = new SupervisorDrain(child, () => state.shuttingDown, () => admission.stop(), { file: generation.childDrainRequestFile, sender: supervisorSender(instanceId) }, (drainingForMs) => recordDrainOverdue(paths.dir, instanceId, drainingForMs)); const server = createPublicProxy({ internalSocket, ...hop.transport, ...(publicSecret ? { publicSecret } : {}), ...(publicEndpoint ? { publicEndpoint } : {}), clients: activity.clients, admission, onDetach: () => activity.refresh(), onAdmit: () => owner.activity(), }); server.once("error", (cause) => { if (!state.shuttingDown) void shutdown(`public socket listener failed: ${errorMessage(cause)}`, 1); }); watchers.push(startSupervisorTicker({ idleExitMs: policy.idleExitMs, activity, owner, draining: () => drain.active, shuttingDown: () => state.shuttingDown, shutdown, })); const teardown = { paths, generation, instanceId, publicSocket, server, internalDir: internal.dir, child, activity, drain, admission, state, ...(publicEndpoint ? { publicEndpoint } : {}), stopWatchers: () => { for (const stop of watchers.splice(0)) stop(); }, }; let shutdownPromise; // Single-flight: concurrent triggers (listener error, child exit, signals) must not process.exit // mid-cleanup. Late callers park on this promise while the first shutdown finishes and exits. function shutdown(reason, exitCode) { shutdownPromise ??= performShutdown(teardown, reason, exitCode); return shutdownPromise; } // Registered before the startup handshake, not after it: the private internal directory already // exists, so a SIGTERM arriving during host startup must run the same cleanup instead of Node's // default kill, which would leave that directory behind. registerSupervisorSignals(shutdown, () => drain.drain()); startupRegistered = true; try { // Direct supervisor launches predate owner records and may have no generation settings. // Ensured starts create it before spawning and always carry an explicit owner/null record. if (launch.ownerFd !== undefined || (await readSettingsFile(generation.settingsFile))) { await owner.start(launch.ownerFd); } await awaitInternalStartup({ internalSocket, internalSecret, internalKey, openObserver: () => activity.openObserver(), }); if (state.shuttingDown) return; // Shutdown stops the child immediately, but joins these writes before removing their directories. state.startupComplete = (async () => { await publishSupervisorEndpoint({ launch, server, publicSecret, publicEndpoint, generationDir: generation.dir, instanceId, settings, state, }); state.publicSocketIdentity = await statSocketIdentity(publicSocket); // The child's crash cleanup compares the public entry against this generation's private token. if (state.publicSocketIdentity && internal.dir) { await writeSocketIdentityFile(join(internal.dir, PUBLIC_SOCKET_IDENTITY_FILE), state.publicSocketIdentity); } watchers.push(drainOnPublicSocketLoss(publicSocket, state.publicSocketIdentity, () => state.shuttingDown || drain.active, drain, () => { state.endpointReplaced = true; }, { file: paths.pointerFile, instanceId })); watchers.push(await drain.acceptRequests(generation)); })(); await state.startupComplete; supervisorPublished(); } catch (cause) { await shutdown(`startup failed: ${errorMessage(cause)}`, 1); } if (state.shuttingDown) return; if (process.platform === "win32") { watchers.push(await watchWin32ChildIdentity(child, () => state.shuttingDown, () => void shutdown("rpc host child exit observed by identity watchdog", 0))); } writeHostReady(publicSocket, policy.coldStart, policy.idleExitMs); await new Promise(() => { }); } catch (e_1) { env_1.error = e_1; env_1.hasError = true; } finally { const result_1 = __disposeResources(env_1); if (result_1) await result_1; } } if (!isBundledNode && isCliModuleEntry(import.meta.url)) { const launch = parseSupervisorArgs(process.argv.slice(2)); if (!launch) { writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"); process.exit(2); } void runHostSupervisor(launch); } //# sourceMappingURL=host-lifecycle.js.map