@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
297 lines • 13.6 kB
JavaScript
/**
* WHAT the lifecycle supervisor is launched with and WHAT it launches: its hidden argv route, the
* argv it parses, and the host child it spawns. Split out of `host-lifecycle.ts`, which keeps the
* supervisor's orchestration; every name stays re-exported there for existing importers.
*/
import childProcess from "node:child_process";
import { spawnWithPrivateFds } from "../../private-fd-spawn.js";
import { Socket } from "node:net";
import { extname } from "node:path";
import { isBunBinary } from "../../config.js";
import { runtimeExecArgv } from "../../utils/runtime-exec-argv.js";
import { resolveCliMainPath } from "./host-cli-entry.js";
import { HOST_DAEMON_DIR_ENV } from "./host-daemon-paths.js";
import { HOST_INSTANCE_ID_ENV, HOST_STARTUP_EVENTS_ENV, INTERNAL_KEY_STDIN_ENV } from "./host-identity-env.js";
import { hostChildStartupHandOff } from "./host-startup-beacon.js";
import { hostChildStdio } from "./host-lifecycle-startup.js";
import { releaseStartupFillers } from "../../private-fd-startup-fillers.js";
import { HOST_CLEANUP_PATHS_ENV, HOST_PUBLIC_SOCKET_ENV, HOST_SCRATCH_DIR_ENV, HOST_WATCH_FD_ENV, HOST_WATCH_LIFETIME_FIFO_ENV, HOST_WATCH_PPID_ENV, HOST_WATCH_PSTART_ENV, HOST_WATCH_PSTART_TICKS_ENV, } from "./host-watchdog.js";
import { parseSocketIdentity } from "./socket-ownership.js";
import { SOCKET_SECRET_FILE_ENV } from "./socket-transport.js";
export { resolveCliMainPath } from "./host-cli-entry.js";
/** Hidden internal launch route: wire-invisible, never advertised by the public CLI surface. */
export const INTERNAL_SUPERVISOR_FLAG = "--internal-rpc-host-supervisor";
/**
* Engine-global flags a rebranded wrapper may legitimately prepend when it
* re-dispatches this binary. `packages/omo-native` injects `--extension <dir>`
* for every non-early command, which pushed the sentinel off argv[0].
*/
const INJECTABLE_PREFIX_FLAGS = new Set(["--extension"]);
/**
* Returns the internal supervisor payload when argv selects that route.
*
* The route dispatches when the sentinel is argv[0] OR is preceded only by
* known injectable prefix flags and their values - the one perturbation
* wrappers legitimately perform. Everything else disqualifies it: a positional
* operand, `--`, or an unknown flag before the sentinel all return undefined,
* so a user-supplied value that happens to equal the sentinel can never reach
* the supervisor.
*
* The skipped prefix is deliberately NOT forwarded to the host: a wrapper
* re-injects its own prefix on every re-entry, so the host child receives it
* from the wrapper rather than twice from here.
*/
export function findInternalSupervisorArgs(argv) {
for (let index = 0; index < argv.length; index++) {
const arg = argv[index];
if (arg === INTERNAL_SUPERVISOR_FLAG)
return argv.slice(index + 1);
// A prefix flag only counts when its value is actually present.
if (!INJECTABLE_PREFIX_FLAGS.has(arg) || index + 1 >= argv.length)
return undefined;
index++;
}
return undefined;
}
/** `--socket <path>` selects the public socket; every other argument is forwarded to the host CLI. */
export function parseSupervisorArgs(argv) {
const hostArgs = [];
let socket;
let childCommand;
let childArgs;
let agentDir;
let ownerFd;
let presenterBootstrapFd;
let bindSocket;
let replaceIdentity;
let replaceOwner;
for (let index = 0; index < argv.length; index++) {
const arg = argv[index];
if (arg === "--mcp-presenter-fd" && argv[index + 1] === "4") {
presenterBootstrapFd = 4;
index++;
continue;
}
if (arg === "--owner-fd" && index + 1 < argv.length) {
ownerFd = Number(argv[++index]);
if (!Number.isSafeInteger(ownerFd) || ownerFd < 3)
return undefined;
continue;
}
if (arg === "--socket" && index + 1 < argv.length) {
socket = argv[++index];
continue;
}
if (arg === "--child-command" && index + 1 < argv.length) {
childCommand = argv[++index];
continue;
}
if (arg === "--child-args" && index + 1 < argv.length) {
try {
const parsed = JSON.parse(argv[++index]);
if (Array.isArray(parsed) && parsed.every((value) => typeof value === "string"))
childArgs = parsed;
}
catch {
return undefined;
}
continue;
}
if (arg === "--agent-dir" && index + 1 < argv.length) {
agentDir = argv[++index];
continue;
}
if (arg === "--bind" && index + 1 < argv.length) {
bindSocket = argv[++index];
continue;
}
if (arg === "--replace" && index + 1 < argv.length) {
replaceIdentity = parseSocketIdentity(argv[++index]);
continue;
}
if (arg === "--replace-owner" && index + 1 < argv.length) {
replaceOwner = argv[++index];
continue;
}
hostArgs.push(arg);
}
return socket === undefined
? undefined
: ownerFd === presenterBootstrapFd && ownerFd !== undefined
? undefined
: {
socket,
hostArgs,
childCommand,
childArgs,
agentDir,
ownerFd,
bindSocket,
replaceIdentity,
replaceOwner,
presenterBootstrapFd,
};
}
export const OWNER_WATCH_FD = 3;
// Strongly retain the write end until that supervisor exits, but never keep the caller alive.
const ownerPipes = new Set();
export function keepOwnerPipe(child) {
const pipe = child.stdio[OWNER_WATCH_FD];
if (!(pipe instanceof Socket))
throw new Error("RPC owner pipe was not inherited");
ownerPipes.add(pipe);
pipe.on("error", () => { });
pipe.unref();
child.once("exit", () => {
ownerPipes.delete(pipe);
pipe.destroy();
});
}
/**
* Resolves the host child spawn. Explicit child commands (desktop launchers)
* are forwarded untouched. The default re-enters the committed CLI entry
* through the runtime, except in compiled standalone binaries, which always
* boot their embedded entrypoint and would parse a script path as CLI
* arguments - there the executable itself is the CLI, so the mode flags are
* passed directly. Exported for tests.
*/
export function resolveHostChildLaunch(launch, internalSocket, compiled = isBunBinary) {
if (launch.childCommand) {
return {
command: launch.childCommand,
args: [...(launch.childArgs ?? []), "--listen", `unix://${internalSocket}`],
};
}
return {
command: process.execPath,
args: [
...(compiled ? [] : [...runtimeExecArgv(), resolveCliMainPath()]),
"--mode",
"rpc",
"--multi-session",
"--listen",
`unix://${internalSocket}`,
...launch.hostArgs,
],
};
}
/** Mirrors cross-spawn: survives cmd.exe parsing and `CommandLineToArgvW`. */
function quoteWindowsShellArg(value) {
const escaped = value
.replace(/(\\*)"/g, '$1$1\\"')
.replace(/(\\*)$/, "$1$1")
.replace(/([()%!^"<>&|;,])/g, "^$1");
return `"${escaped}"`;
}
/**
* Windows refuses to spawn a `.cmd`/`.bat` without a shell, and Node's
* `shell: true` concatenates argv without escaping it. Escape each original
* value before adding the surrounding quotes so `.cmd`/`.bat` launchers survive
* cmd.exe parsing without double-escaping.
* Exported for tests.
*/
export function spawnableChildLaunch(launch, platform = process.platform) {
const extension = extname(launch.command).toLowerCase();
if (platform !== "win32" || (extension !== ".cmd" && extension !== ".bat")) {
return { ...launch, shell: false };
}
return {
command: quoteWindowsShellArg(launch.command),
args: launch.args.map(quoteWindowsShellArg),
shell: true,
};
}
/**
* Child stdio slot carrying the supervisor-lifetime pipe. The supervisor holds
* the write end open and never writes; the kernel closes it when the supervisor
* dies for ANY reason (SIGKILL, OOM kill, crash), so the host sees EOF on this
* fd and shuts itself down. Catchable-signal cleanup alone cannot do this.
*/
export const HOST_CHILD_WATCH_FD = 3;
/**
* The same hand-off an initial daemon or successor spawn carries (`adoptedEngineTrustHandOff`). Both modules load
* lazily, keeping the marker writer and its zod schema out of the supervisor's startup graph
* (`test/supervisor-import-graph.test.ts`): only a supervisor that adopted a generation loads the writer.
*/
export async function loadHostChildTrustHandOff() {
const { adoptedEngineTrust } = await import("../../engine-trust/adopted.js");
if (adoptedEngineTrust() === undefined)
return {};
const { adoptedEngineTrustHandOff } = await import("../../engine-trust/hand-off.js");
return adoptedEngineTrustHandOff();
}
/**
* The variables that bind the host child to this supervisor and its generation. The public socket is
* passed on every platform: the child stamps it as its sessions' `host_socket`, and a host session
* without one cannot register a control endpoint, so nothing would drain its gateway deliveries
* (omo#12486). Exported for tests.
*/
export function hostChildEnvironment(options, startupHandOff, platform = process.platform) {
const { launch, internal, internalSecret } = options;
return {
...process.env,
...options.trustHandOff,
...(launch.agentDir ? { SENPI_CODING_AGENT_DIR: launch.agentDir } : {}),
// The child binds a PRIVATE socket, so it cannot derive this endpoint's daemon directory
// from what it listens on: it is told, and it claims its session paths there.
[HOST_DAEMON_DIR_ENV]: options.daemonDir,
[HOST_INSTANCE_ID_ENV]: options.instanceId,
[HOST_WATCH_FD_ENV]: String(HOST_CHILD_WATCH_FD),
[HOST_WATCH_PPID_ENV]: String(process.pid),
[HOST_WATCH_PSTART_ENV]: options.supervisorStart?.time,
[HOST_WATCH_PSTART_TICKS_ENV]: options.supervisorStart?.ticks,
[HOST_WATCH_LIFETIME_FIFO_ENV]: options.lifetimeFifo,
...(internal.dir ? { [HOST_SCRATCH_DIR_ENV]: internal.dir } : {}),
[SOCKET_SECRET_FILE_ENV]: platform === "win32" && internalSecret ? internal.secretPath : undefined,
[INTERNAL_KEY_STDIN_ENV]: options.internalKey ? "1" : undefined,
[HOST_CLEANUP_PATHS_ENV]: options.cleanupPaths.join("\n"),
[HOST_PUBLIC_SOCKET_ENV]: options.publicSocket,
[HOST_STARTUP_EVENTS_ENV]: startupHandOff,
};
}
/** Spawns the host child with the environment that binds it to this supervisor and its generation. */
export function spawnHostChild(options) {
const { launch, internalSocket } = options;
const childLaunch = spawnableChildLaunch(resolveHostChildLaunch(launch, internalSocket));
// A shell wrapper cannot prove preservation of the private inherited handle.
const bootstrap = launch.presenterBootstrapFd !== undefined && !childLaunch.shell;
if (bootstrap)
childLaunch.args.push("--mcp-presenter-fd", "4");
// Property access also preserves OS-level instrumentation on runtimes with captured builtin exports.
const startupStdio = hostChildStdio(bootstrap, options.reportsStartup === true);
const child = spawnWithPrivateFds((command, args, options) => childProcess.spawn(command, args, options), childLaunch.command, childLaunch.args, {
env: hostChildEnvironment(options, options.reportsStartup ? hostChildStartupHandOff(startupStdio.fillers) : undefined),
// Slot 3 is the lifetime pipe: "pipe" gives the child a read end it can
// wait on and keeps the write end owned by this process alone.
shell: childLaunch.shell,
stdio: startupStdio.stdio,
// The supervisor is spawned detached, so on win32 it owns no console. A
// console-subsystem child started from it would allocate a fresh one,
// which Windows Terminal renders as an empty window that takes focus.
// CREATE_NO_WINDOW gives the child a console with no window instead.
windowsHide: true,
},
// The engine ends the private descriptor chain: a host it starts later never inherits them.
{ final: true });
releaseStartupFillers(child, startupStdio.fillers);
if (launch.presenterBootstrapFd !== undefined) {
const fd = launch.presenterBootstrapFd;
// The opt-in helper stays outside the supervisor's fixed startup import budget.
void import("./mcp-presenter-bootstrap.js")
.then(({ presenterBootstrapStream, relayPresenterBootstrap }) => {
const upstream = presenterBootstrapStream(fd);
if (upstream && bootstrap)
return relayPresenterBootstrap(upstream, child);
upstream?.destroy();
child.stdio[4]?.destroy();
})
.catch(() => child.stdio[4]?.destroy());
}
if (options.internalKey) {
child.stdin?.on("error", () => { });
// One write only. Keep its write end alive until this supervisor exits.
child.stdin?.write(options.internalKey);
}
return child;
}
//# sourceMappingURL=host-lifecycle-launch.js.map