Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

[RSI] fix(coding-agent): guard stdin reads in non-interactive mode (#2285)

Seth Karten4535c87e5112
diff --git a/packages/coding-agent/.changes/noninteractive-stdin-guard.md b/packages/coding-agent/.changes/noninteractive-stdin-guard.md
new file mode 100644
index 0000000000..f8b829791f
--- /dev/null
+++ b/packages/coding-agent/.changes/noninteractive-stdin-guard.md
@@ -0,0 +1 @@
+- Non-interactive CLI boots no longer hang on stdin: the boot-time piped-stdin read gives up after a short idle window (PI_STDIN_TIMEOUT_MS, default 250ms) instead of waiting forever on a pipe a daemon worker, agent harness, or CI runner holds open without ever writing or closing it, `--resume` of a session from another project fails fast without a TTY instead of blocking on a fork confirmation, `daemon attach` without a TTY reports an error instead of waiting for terminal input, and the deprecation-warning keypress wait is skipped without a TTY.
diff --git a/packages/coding-agent/src/cli/daemon-command.ts b/packages/coding-agent/src/cli/daemon-command.ts
index 0154275727..e0073ab519 100644
--- a/packages/coding-agent/src/cli/daemon-command.ts
+++ b/packages/coding-agent/src/cli/daemon-command.ts
@@ -295,6 +295,11 @@ async function runOpen(parsed: ParsedDaemonClientCommand): Promise<void> {
if (!isLiveSessionSummary(data)) {
throw new Error("Daemon returned an invalid create response");
}
+ if (parsed.json) {
+ // Machine-readable open has no terminal to attach; match create's --json shape.
+ printJson(data);
+ return;
+ }
await runAttach(client, data.activeSessionId);
} finally {
client.close();
@@ -797,6 +802,10 @@ async function runCreate(client: DaemonClient, args: string[], json: boolean): P
}
async function runAttach(client: DaemonClient, activeSessionId: string): Promise<void> {
+ if (!process.stdin.isTTY) {
+ // The attach terminal reads stdin; without a TTY it would hang forever.
+ throw new Error("attach requires an interactive terminal (pass --json for machine-readable attach)");
+ }
const terminal = new DaemonAttachTerminal(client, activeSessionId);
await terminal.run();
}
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 34f39e4a03..dec3295dc4 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -122,29 +122,7 @@ import { shouldRunOnboarding } from "./modes/interactive/onboarding.js";
import { initTheme, preloadCodeHighlighter, stopThemeWatcher } from "./modes/interactive/theme/theme.js";
import { handleConfigCommand } from "./package-manager-cli.js";
import { isLocalPath } from "./utils/paths.js";
-
-/**
- * Read all content from piped stdin.
- * Returns undefined if stdin is a TTY (interactive terminal).
- */
-async function readPipedStdin(): Promise<string | undefined> {
- // If stdin is a TTY, we're running interactively - don't read stdin
- if (process.stdin.isTTY) {
- return undefined;
- }
-
- return new Promise((resolve) => {
- let data = "";
- process.stdin.setEncoding("utf8");
- process.stdin.on("data", (chunk) => {
- data += chunk;
- });
- process.stdin.on("end", () => {
- resolve(data.trim() || undefined);
- });
- process.stdin.resume();
- });
-}
+import { readPipedStdin } from "./utils/piped-stdin.js";
function collectSettingsDiagnostics(
settingsManager: SettingsManager,
@@ -506,6 +484,15 @@ export async function createSessionManager(
: SessionManager.open(resolved.path, sessionDir, explicitCwdOverride);
case "global": {
+ if (!process.stdin.isTTY) {
+ // The fork confirm reads stdin; without a TTY it would hang boot forever.
+ console.error(
+ chalk.red(
+ `Error: session ${resumeSelector} belongs to a different project (${resolved.cwd}). Pass --fork ${resumeSelector} to use it here, or run from that project's directory.`,
+ ),
+ );
+ process.exit(1);
+ }
console.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));
const shouldFork = await promptConfirm("Fork this session into current directory?");
if (!shouldFork) {
diff --git a/packages/coding-agent/src/migrations.ts b/packages/coding-agent/src/migrations.ts
index 5e9f45d915..3fa258285a 100644
--- a/packages/coding-agent/src/migrations.ts
+++ b/packages/coding-agent/src/migrations.ts
@@ -418,6 +418,11 @@ export async function showDeprecationWarnings(warnings: string[]): Promise<void>
console.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`));
console.log(chalk.dim(`\nPress any key to continue...`));
+ if (!process.stdin.isTTY) {
+ // A non-interactive parent never delivers the keypress; don't hang waiting for it.
+ console.log();
+ return;
+ }
await new Promise<void>((resolve) => {
process.stdin.setRawMode?.(true);
process.stdin.resume();
diff --git a/packages/coding-agent/src/utils/piped-stdin.ts b/packages/coding-agent/src/utils/piped-stdin.ts
new file mode 100644
index 0000000000..b78c0c11ab
--- /dev/null
+++ b/packages/coding-agent/src/utils/piped-stdin.ts
@@ -0,0 +1,115 @@
+import type { Readable } from "node:stream";
+
+/**
+ * Env override for the no-input window of a non-interactive stdin read, in
+ * milliseconds. `0` skips the read entirely; values above the cap are clamped.
+ */
+export const STDIN_IDLE_TIMEOUT_MS_ENV = "PI_STDIN_TIMEOUT_MS";
+
+const DEFAULT_STDIN_IDLE_TIMEOUT_MS = 250;
+const MAX_STDIN_IDLE_TIMEOUT_MS = 30_000;
+
+export function resolveStdinIdleTimeoutMs(environment: NodeJS.ProcessEnv = process.env): number {
+ const raw = environment[STDIN_IDLE_TIMEOUT_MS_ENV];
+ if (raw === undefined || raw === "") {
+ return DEFAULT_STDIN_IDLE_TIMEOUT_MS;
+ }
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value < 0) {
+ return DEFAULT_STDIN_IDLE_TIMEOUT_MS;
+ }
+ return Math.min(Math.floor(value), MAX_STDIN_IDLE_TIMEOUT_MS);
+}
+
+/** Readable stdin shape: real stdin also reports whether it is a TTY. */
+export type StdinLike = Readable & { isTTY?: boolean };
+
+export interface ReadPipedStdinOptions {
+ /** Stream to read; defaults to process.stdin. */
+ input?: StdinLike;
+ /** No-input window before the read gives up. Defaults to resolveStdinIdleTimeoutMs(). */
+ idleTimeoutMs?: number;
+}
+
+/**
+ * Read all content from piped stdin without ever hanging a non-interactive boot.
+ *
+ * Returns undefined for TTY stdin (interactive terminal: nothing is piped), for
+ * streams that already ended, and when a non-TTY stdin stays silent past the
+ * idle window. Daemon workers, agent harnesses, and CI runners spawn this CLI
+ * with a stdin pipe they never write to and never close; `end` then never
+ * fires, so an unbounded read would hang boot forever. A short idle window is
+ * enough for real pipes: a producer that has already written delivers its
+ * buffered bytes the moment the listeners attach, and a live producer resets
+ * the window on every chunk. On give-up the stream is paused with all listeners
+ * detached, so bytes that arrive later stay buffered for a future reader and
+ * stdin cannot keep the process alive.
+ */
+export async function readPipedStdin(options: ReadPipedStdinOptions = {}): Promise<string | undefined> {
+ const input = options.input ?? (process.stdin as StdinLike);
+ const idleTimeoutMs = options.idleTimeoutMs ?? resolveStdinIdleTimeoutMs();
+ if (input.isTTY || input.destroyed || input.readableEnded || idleTimeoutMs === 0) {
+ return undefined;
+ }
+
+ return new Promise((resolve) => {
+ let data = "";
+ let settled = false;
+ let idleTimer: NodeJS.Timeout | undefined;
+
+ const finish = (value: string | undefined, pauseInput: boolean): void => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ if (idleTimer !== undefined) {
+ clearTimeout(idleTimer);
+ idleTimer = undefined;
+ }
+ input.off("data", onData);
+ input.off("end", onEnd);
+ input.off("error", onError);
+ input.off("close", onClose);
+ if (pauseInput) {
+ input.pause();
+ }
+ resolve(value);
+ };
+ const scheduleIdleTimeout = (): void => {
+ if (idleTimer !== undefined) {
+ clearTimeout(idleTimer);
+ }
+ idleTimer = setTimeout(() => {
+ console.error(
+ `stdin did not close within ${idleTimeoutMs}ms; continuing without waiting for more piped input`,
+ );
+ finish(data.trim() || undefined, true);
+ }, idleTimeoutMs);
+ idleTimer.unref?.();
+ };
+ const onData = (chunk: string): void => {
+ // A live producer keeps the read open; only silence gives up.
+ data += chunk;
+ scheduleIdleTimeout();
+ };
+ const onEnd = (): void => {
+ finish(data.trim() || undefined, false);
+ };
+ const onError = (error: Error): void => {
+ console.error(`stdin read failed (${error.message}); continuing without piped input`);
+ finish(undefined, true);
+ };
+ const onClose = (): void => {
+ // Covers a stream destroyed before `end` could fire.
+ finish(data.trim() || undefined, false);
+ };
+
+ input.setEncoding("utf8");
+ input.on("data", onData);
+ input.on("end", onEnd);
+ input.on("error", onError);
+ input.on("close", onClose);
+ scheduleIdleTimeout();
+ input.resume();
+ });
+}
diff --git a/packages/coding-agent/test/daemon-command.test.ts b/packages/coding-agent/test/daemon-command.test.ts
index 65866521c9..84e271e261 100644
--- a/packages/coding-agent/test/daemon-command.test.ts
+++ b/packages/coding-agent/test/daemon-command.test.ts
@@ -31,6 +31,8 @@ const daemonClientMock = vi.hoisted(() => {
emitStaleAgentEndOnAttach: false,
connectFails: false,
sessions: [] as Array<Record<string, unknown>>,
+ /** Optional live-session summary returned by the mocked create request. */
+ createdSession: undefined as Record<string, unknown> | undefined,
};
class MockDaemonClient {
@@ -53,6 +55,9 @@ const daemonClientMock = vi.hoisted(() => {
if (command.type === "list") {
return { type: "response", command: command.type, success: true, data: { sessions: behavior.sessions } };
}
+ if (command.type === "create" && behavior.createdSession !== undefined) {
+ return { type: "response", command: command.type, success: true, data: behavior.createdSession };
+ }
if (command.type === "attach" && behavior.emitStaleAgentEndOnAttach) {
this.emitMessage({ type: "session_event", activeSessionId: "active-1", event: { type: "agent_end" } });
}
@@ -138,6 +143,7 @@ describe("daemon command", () => {
daemonClientMock.behavior.emitStaleAgentEndOnAttach = false;
daemonClientMock.behavior.connectFails = false;
daemonClientMock.behavior.sessions = [];
+ daemonClientMock.behavior.createdSession = undefined;
consoleErrorMessages = [];
vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null | undefined) => {
throw new Error(`exit ${code}`);
@@ -522,6 +528,35 @@ describe("daemon command", () => {
const secondConfig = daemonClientMock.instances.at(-1)?.requests[0]?.config;
expect(secondConfig?.initialGoal).toBeUndefined();
});
+
+ it("errors on non-interactive daemon attach with the json remediation instead of hanging", async () => {
+ // The test runner's stdin is not a TTY, so the attach terminal guard must
+ // fail fast rather than block on a readline that can never be answered.
+ await expect(
+ handleDaemonCommand(["daemon", "--socket", "/tmp/prime-agent.sock", "attach", "active-1"]),
+ ).resolves.toBe(true);
+
+ expect(process.exitCode).toBe(1);
+ expect(consoleErrorMessages.join(" ")).toContain("attach requires an interactive terminal");
+ });
+
+ it("prints the created session for non-interactive --json open instead of attaching", async () => {
+ daemonClientMock.behavior.createdSession = makeSessionSummary("active-open-1", "session-open-1", "open-1");
+ const logCalls: unknown[][] = [];
+ vi.spyOn(console, "log").mockImplementation((...messages: unknown[]) => {
+ logCalls.push(messages);
+ });
+
+ await expect(handleDaemonCommand(["daemon", "--socket", "/tmp/prime-agent.sock", "--json"])).resolves.toBe(true);
+
+ // No attach-guard error: the machine-readable path prints the summary and exits.
+ expect(process.exitCode).toBeUndefined();
+ expect(consoleErrorMessages).toEqual([]);
+ const client = daemonClientMock.instances.at(-1);
+ expect(client?.requests.some((request) => request.type === "attach")).toBe(false);
+ expect(logCalls.length).toBe(1);
+ expect(() => JSON.parse(String(logCalls[0]?.[0]))).not.toThrow();
+ });
});
function makeSessionSummary(activeSessionId: string, sessionId: string, sessionName: string): Record<string, unknown> {
diff --git a/packages/coding-agent/test/piped-stdin.test.ts b/packages/coding-agent/test/piped-stdin.test.ts
new file mode 100644
index 0000000000..bc32fb3a8b
--- /dev/null
+++ b/packages/coding-agent/test/piped-stdin.test.ts
@@ -0,0 +1,108 @@
+import { PassThrough } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { readPipedStdin, resolveStdinIdleTimeoutMs, STDIN_IDLE_TIMEOUT_MS_ENV } from "../src/utils/piped-stdin.js";
+
+function ttyStream(): PassThrough {
+ const stream = new PassThrough();
+ (stream as unknown as { isTTY: boolean }).isTTY = true;
+ return stream;
+}
+
+afterEach(() => {
+ delete process.env[STDIN_IDLE_TIMEOUT_MS_ENV];
+ vi.restoreAllMocks();
+});
+
+describe("resolveStdinIdleTimeoutMs", () => {
+ it("defaults to a short non-interactive window", () => {
+ expect(resolveStdinIdleTimeoutMs({})).toBe(250);
+ });
+
+ it("honors a clean env override", () => {
+ expect(resolveStdinIdleTimeoutMs({ [STDIN_IDLE_TIMEOUT_MS_ENV]: "5000" })).toBe(5000);
+ });
+
+ it("allows zero to skip the read entirely", () => {
+ expect(resolveStdinIdleTimeoutMs({ [STDIN_IDLE_TIMEOUT_MS_ENV]: "0" })).toBe(0);
+ });
+
+ it("falls back to the default on invalid input and clamps the maximum", () => {
+ for (const bad of ["abc", "-3", ""]) {
+ expect(resolveStdinIdleTimeoutMs({ [STDIN_IDLE_TIMEOUT_MS_ENV]: bad })).toBe(250);
+ }
+ // Fractional requests floor to whole milliseconds.
+ expect(resolveStdinIdleTimeoutMs({ [STDIN_IDLE_TIMEOUT_MS_ENV]: "4.9" })).toBe(4);
+ expect(resolveStdinIdleTimeoutMs({ [STDIN_IDLE_TIMEOUT_MS_ENV]: "999999" })).toBe(30_000);
+ });
+});
+
+describe("readPipedStdin", () => {
+ it("returns undefined for a TTY without reading it", async () => {
+ const input = ttyStream();
+ await expect(readPipedStdin({ input, idleTimeoutMs: 25 })).resolves.toBeUndefined();
+ });
+
+ it("returns undefined when stdin was already consumed to end", async () => {
+ const input = new PassThrough();
+ input.end("already consumed");
+ input.resume();
+ await new Promise((resolve) => input.once("end", resolve));
+ expect(input.readableEnded).toBe(true);
+ await expect(readPipedStdin({ input, idleTimeoutMs: 1000 })).resolves.toBeUndefined();
+ });
+
+ it("skips the read entirely with a zero idle timeout", async () => {
+ const input = new PassThrough();
+ await expect(readPipedStdin({ input, idleTimeoutMs: 0 })).resolves.toBeUndefined();
+ expect(input.readableFlowing).not.toBe(true);
+ });
+
+ it("collects piped content until end", async () => {
+ const input = new PassThrough();
+ const promise = readPipedStdin({ input, idleTimeoutMs: 1000 });
+ input.write("hello\n");
+ input.write("world");
+ input.end();
+ await expect(promise).resolves.toBe("hello\nworld");
+ });
+
+ it("resolves undefined when stdin errors", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const input = new PassThrough();
+ const promise = readPipedStdin({ input, idleTimeoutMs: 1000 });
+ setTimeout(() => input.destroy(new Error("boom")), 5);
+ await expect(promise).resolves.toBeUndefined();
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("gives up on a held-open silent pipe instead of hanging", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const input = new PassThrough();
+ const promise = readPipedStdin({ input, idleTimeoutMs: 25 });
+ await expect(promise).resolves.toBeUndefined();
+ // The stream is paused with listeners detached: later bytes stay buffered
+ // for a future reader, and stdin cannot keep the process alive.
+ expect(input.isPaused()).toBe(true);
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps reading a live producer past the idle window", async () => {
+ const input = new PassThrough();
+ const promise = readPipedStdin({ input, idleTimeoutMs: 50 });
+ input.write("chunk-1;");
+ for (let index = 2; index <= 5; index++) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ input.write(`chunk-${index};`);
+ }
+ input.end("done");
+ await expect(promise).resolves.toBe("chunk-1;chunk-2;chunk-3;chunk-4;chunk-5;done");
+ });
+
+ it("returns partial content when the producer goes silent mid-stream", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const input = new PassThrough();
+ const promise = readPipedStdin({ input, idleTimeoutMs: 25 });
+ input.write("partial");
+ await expect(promise).resolves.toBe("partial");
+ });
+});
diff --git a/packages/coding-agent/test/stdin-guard-cold-cli.test.ts b/packages/coding-agent/test/stdin-guard-cold-cli.test.ts
new file mode 100644
index 0000000000..297b38d316
--- /dev/null
+++ b/packages/coding-agent/test/stdin-guard-cold-cli.test.ts
@@ -0,0 +1,182 @@
+import { type ChildProcess, spawn } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { ENV_AGENT_DIR } from "../src/config.js";
+
+/**
+ * Cold real-CLI stdin guard coverage.
+ *
+ * Non-interactive parents (daemon workers, agent harnesses, CI runners) spawn
+ * this CLI with a stdin pipe they never write to and never close. The boot-time
+ * piped-stdin read must give up on that pipe instead of hanging the process
+ * forever — a bug that previously left daemons "starting" for minutes while the
+ * client sat in readPipedStdin().
+ *
+ * Every spawn here keeps the child's stdin write end open and silent for the
+ * whole run, and every wait has an explicit deadline: a hang surfaces as a
+ * SIGKILL exit and a test failure, never a stuck test process.
+ */
+
+const cliPath = resolve(__dirname, "../src/cli.ts");
+const tsxPath = resolve(__dirname, "../../../node_modules/tsx/dist/cli.mjs");
+const tsconfigPath = resolve(__dirname, "../../../tsconfig.json");
+
+interface ColdRun {
+ code: number | null;
+ signal: NodeJS.Signals | null;
+ stdout: string;
+ stderr: string;
+ elapsedMs: number;
+}
+
+const tempRoots: string[] = [];
+const cleanupBoundMs = 30_000;
+
+function makeEnv(agentDir: string, extra?: Record<string, string>): NodeJS.ProcessEnv {
+ return {
+ ...process.env,
+ [ENV_AGENT_DIR]: agentDir,
+ HOME: agentDir,
+ TSX_TSCONFIG_PATH: tsconfigPath,
+ // Keep the guard's give-up window short and deterministic.
+ PI_STDIN_TIMEOUT_MS: "300",
+ ...extra,
+ };
+}
+
+function newTempRoot(): { tempRoot: string; agentDir: string } {
+ const tempRoot = mkdtempSync(join(tmpdir(), "pa-stdin-guard-"));
+ tempRoots.push(tempRoot);
+ const agentDir = join(tempRoot, "agent");
+ mkdirSync(agentDir, { recursive: true });
+ return { tempRoot, agentDir };
+}
+
+function killTree(child: ChildProcess): void {
+ if (child.pid === undefined) return;
+ try {
+ process.kill(-child.pid, "SIGKILL");
+ } catch {
+ child.kill("SIGKILL");
+ }
+}
+
+/** Run the real CLI non-interactively with a held-open, silent stdin pipe. */
+function runColdCli(
+ args: string[],
+ options: { timeoutMs: number; ipc?: boolean; extraEnv?: Record<string, string> },
+): Promise<ColdRun> {
+ const { tempRoot, agentDir } = newTempRoot();
+ return new Promise((resolveRun, rejectRun) => {
+ const startedAt = Date.now();
+ const child = spawn(process.execPath, [tsxPath, cliPath, ...args], {
+ cwd: tempRoot,
+ env: makeEnv(agentDir, options.extraEnv),
+ stdio: options.ipc ? ["pipe", "pipe", "pipe", "ipc"] : ["pipe", "pipe", "pipe"],
+ detached: true,
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout?.on("data", (chunk) => {
+ stdout += chunk.toString();
+ });
+ child.stderr?.on("data", (chunk) => {
+ stderr += chunk.toString();
+ });
+ // Deliberately never write to and never close child.stdin: this is the
+ // held-open pipe shape a non-interactive parent produces.
+ const killTimer = setTimeout(() => killTree(child), options.timeoutMs);
+ child.once("error", (error) => {
+ clearTimeout(killTimer);
+ rejectRun(error);
+ });
+ child.once("close", (code, signal) => {
+ clearTimeout(killTimer);
+ resolveRun({ code, signal, stdout, stderr, elapsedMs: Date.now() - startedAt });
+ });
+ });
+}
+
+/** Stop a daemon this test spawned on an isolated socket. Bounded. */
+async function shutdownDaemon(socketPath: string, agentDir: string, tempRoot: string): Promise<void> {
+ await new Promise<void>((resolveShutdown) => {
+ const child = spawn(
+ process.execPath,
+ [tsxPath, cliPath, "daemon", "shutdown", "--force", "--socket", socketPath],
+ {
+ cwd: tempRoot,
+ env: makeEnv(agentDir),
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ const killTimer = setTimeout(() => child.kill("SIGKILL"), cleanupBoundMs);
+ child.once("close", () => {
+ clearTimeout(killTimer);
+ resolveShutdown();
+ });
+ child.once("error", () => {
+ clearTimeout(killTimer);
+ resolveShutdown();
+ });
+ });
+}
+
+const daemonSockets: { socketPath: string; agentDir: string; tempRoot: string }[] = [];
+
+afterEach(async () => {
+ for (const target of daemonSockets.splice(0)) {
+ await shutdownDaemon(target.socketPath, target.agentDir, target.tempRoot);
+ }
+ for (const dir of tempRoots.splice(0)) {
+ // The CLI's daemon/kernel children may still be flushing caches under this
+ // dir when the child exits; retry the ENOTEMPTY/EBUSY window instead of failing cleanup.
+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ }
+});
+
+describe("cold CLI stdin guard", () => {
+ it("exits --version cleanly without reading a held-open stdin", async () => {
+ const result = await runColdCli(["--version"], { timeoutMs: 20_000 });
+ expect(result.signal).toBeNull();
+ expect(result.code).toBe(0);
+ // Non-interactive mode takes over stdout, so console output lands on stderr.
+ expect(`${result.stdout}${result.stderr}`).toMatch(/\d+\.\d+\.\d+/);
+ expect(result.elapsedMs).toBeLessThan(20_000);
+ }, 30_000);
+
+ it("does not hang a non-interactive owned-worker print boot on a held-open stdin pipe", async () => {
+ // The owned-worker shape boots the in-process runtime (no daemon) and
+ // still runs the boot-time piped-stdin read; the ipc channel satisfies
+ // the owner watch this role installs.
+ const result = await runColdCli(["--print", "--offline", "--no-session", "Say hi"], {
+ timeoutMs: 30_000,
+ ipc: true,
+ extraEnv: { PRIME_AGENT_INTERNAL_OWNED_WORKER: "1" },
+ });
+ // The old behavior hung here forever: the child never exits and the
+ // bound SIGKILLs it (signal SIGKILL, code null).
+ expect(result.signal).toBeNull();
+ expect(result.code).not.toBe(0);
+ expect(result.stderr).toContain("stdin did not close within 300ms");
+ expect(result.elapsedMs).toBeLessThan(30_000);
+ }, 45_000);
+
+ it("does not hang a daemon-client print boot on a held-open stdin pipe", async () => {
+ // The daemon-client shape is the reported bug: the early daemon spawn
+ // succeeds, the daemon worker boots, but the client sits in the
+ // boot-time stdin read and never reaches daemon readiness.
+ const { tempRoot, agentDir } = newTempRoot();
+ const socketPath = join(tempRoot, "daemon.sock");
+ daemonSockets.push({ socketPath, agentDir, tempRoot });
+ const result = await runColdCli(
+ ["--print", "--offline", "--no-session", "--daemon-socket", socketPath, "Say hi"],
+ { timeoutMs: 90_000 },
+ );
+ expect(result.signal).toBeNull();
+ expect(result.code).not.toBe(0);
+ expect(result.stderr).toContain("stdin did not close within 300ms");
+ expect(result.elapsedMs).toBeLessThan(90_000);
+ }, 150_000);
+});