From e1f68197a416a142884ce1d1e6de0ee8c7b8c3c0 Mon Sep 17 00:00:00 2001 From: Rui Luo Date: Fri, 23 Oct 2026 10:50:31 +0800 Subject: [PATCH 1/8] fix(agent): enforce the piped-input deadline on the host Signed-off-by: Rui Luo --- docs/reference/commands.mdx | 5 +- .../agent/passthrough-dispatch.test.ts | 123 ++++++++++++++++++ .../sandbox/agent/passthrough-dispatch.ts | 110 +++++++++++++++- .../adapters/openshell/sandbox-command-cli.ts | 23 +++- src/lib/adapters/openshell/sandbox-session.ts | 3 +- src/lib/core/process-capture.test.ts | 22 ++++ src/lib/core/process-capture.ts | 25 +++- 7 files changed, 292 insertions(+), 19 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index ae8e74c98b5..87e3c42d3d3 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1494,9 +1494,10 @@ Nonempty `--message-file` arguments and calls without a recognized inline messag The sandbox resolves message-file paths, including symlinks to stdin. For example, the wrapper preserves redirected input for `printf 'ping' | $$nemoclaw my-assistant agent --agent main`. The producer must close standard input after writing the message. -The managed OpenClaw parser waits up to 30 seconds for piped input, including `--message-file /dev/stdin` and symlinks to stdin. +OpenShell starts the sandbox command only after standard input ends, so without an inline message NemoClaw reads piped input on the host first. +It waits up to 30 seconds for the input to end, including for `--message-file /dev/stdin` and symlinks to stdin. A positive `--timeout ` sets this input wait as well as the agent turn timeout. -If the input deadline expires, the command exits nonzero with guidance to close the producer or provide an inline message. +If the input deadline expires, or the input exceeds 4 MiB, the command exits nonzero without starting the turn and prints guidance to close the producer or provide an inline message. When the top-level OpenClaw `--json` output flag is present, the wrapper uses a captured no-TTY path with a `64 MiB` buffer so `stdout` stays parseable JSON. Raw `stderr`, including structured JSON diagnostics, is forwarded unchanged. NemoClaw appends failed-tool or untrusted-child provenance only from the `stdout` JSON. The wrapper reads completion markers only from the final matching OpenClaw response envelope: a local `{ payloads, meta }` response or a gateway `{ status, result: { payloads, meta } }` response. It ignores earlier JSON progress or log records. It exits with status `1` when that metadata contains `error.kind: "incomplete_turn"`, `livenessState: "abandoned"`, or a `timeoutPhase` value, even when the envelope reports success. `replayInvalid: true` means replaying the turn may repeat side effects. The wrapper accepts it only with evidence of a completed run, a successful tool summary, and final assistant text matching the reply payload. Otherwise it exits with status `1` and the existing inspect-before-retry guidance. Marker-shaped values inside tool results, tool-call arguments, or other descendants do not change the exit status. A turn can run every tool successfully and still become abandoned before it produces a reply. The wrapper writes the unchanged JSON trace to `stdout` before it reports the incomplete turn, so the partial tool trace remains available. The wrapper writes the verdict, the detected markers, and verify-before-retry guidance to `stderr`. A `timeoutPhase` value names the phase the deadline fired in, so the wrapper writes deadline guidance in place of the generic incomplete-turn text. Tool calls in a partial trace may have already applied side effects, so verify what the turn changed before you retry it. The wrapper passes through an upstream non-zero exit status unchanged. Literal `--json` values consumed by flags such as `-m` or `--reply-channel`, or arguments after `--`, stay on the normal passthrough path. Documented value flags written as `--flag=value`, such as `--session-id=s1`, are recognized the same way as separated value flags. If an unrecognized OpenClaw option appears before `--json`, NemoClaw also keeps the command on the normal passthrough path so OpenClaw remains the argv source of truth. diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts index a17e6e4f2ad..8faed9216e1 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts @@ -3,10 +3,15 @@ import { describe, expect, it, vi } from "vitest"; import { EventEmitter } from "node:events"; +import { PassThrough } from "node:stream"; import type { CapturedProcessChild } from "../../../core/process-capture"; import type { ProcessSessionSignals } from "../../../core/process-session"; import { createCliOpenShellSandboxSessionExecutor } from "../../../adapters/openshell/sandbox-command-cli"; +import type { OpenShellSandboxSessionRequest } from "../../../adapters/openshell/sandbox-session"; import { + AGENT_STDIN_MAX_BYTES, + dispatchWithAgentStdinDeadline, + readAgentStdinWithinDeadline, runAgentDispatch, canCloseAgentStdin, hasOpenClawAgentSelector, @@ -383,3 +388,121 @@ describe("agent dispatch execution deadline", () => { } }); }); + +describe("agent piped-input deadline (#13621)", () => { + const request: OpenShellSandboxSessionRequest = { + kind: "command", + sandboxName: "alpha", + target: { kind: "selected" }, + command: ["openclaw", "agent", "--agent", "main"], + tty: false, + output: "capture", + }; + const delivered = { + outcome: { kind: "exited" as const, exitCode: 0 }, + stdout: "PONG\n", + stderr: "", + }; + const runner = () => vi.fn(async (_request: OpenShellSandboxSessionRequest) => delivered); + + it("hands piped input that reached EOF to OpenShell", async () => { + const run = runner(); + const readStdin = vi.fn(async () => ({ kind: "eof" as const, data: Buffer.from("ping\n") })); + + const result = await dispatchWithAgentStdinDeadline(request, 30, run, { + stdinIsTty: () => false, + readStdin, + }); + + expect(result).toEqual(delivered); + expect(readStdin).toHaveBeenCalledWith(30_000); + expect(run).toHaveBeenCalledWith({ ...request, stdin: Buffer.from("ping\n") }); + }); + + it.each([ + [ + { kind: "deadline" as const }, + "Timed out after 1 second(s) waiting for the piped message to end.", + ], + [{ kind: "too-large" as const }, `The piped message exceeds ${AGENT_STDIN_MAX_BYTES} bytes.`], + ])("fails before dispatch when piped input does not end in time %#", async (read, problem) => { + const run = runner(); + + const result = await dispatchWithAgentStdinDeadline(request, 1, run, { + stdinIsTty: () => false, + readStdin: async () => read, + }); + + expect(run).not.toHaveBeenCalled(); + expect(result).toMatchObject({ outcome: { kind: "exited", exitCode: 1 }, stdout: "" }); + expect(result.stderr).toContain(problem); + expect(result.stderr).toContain("provide --message, or set --timeout "); + }); + + it.each([ + ["closed stdin", { ...request, stdin: false }, false], + ["interactive terminal", request, true], + ])("keeps the %s posture without reading input", async (_name, prepared, terminal) => { + const run = runner(); + const readStdin = vi.fn(); + + await dispatchWithAgentStdinDeadline(prepared as OpenShellSandboxSessionRequest, 30, run, { + stdinIsTty: () => terminal, + readStdin, + }); + + expect(readStdin).not.toHaveBeenCalled(); + expect(run).toHaveBeenCalledWith(prepared); + }); + + it.each([ + [["--timeout", "1"], 1_000], + [[], 30_000], + ])("uses a positive --timeout, else 30 seconds, as the input deadline %#", async (flags, ms) => { + const readStdin = vi.fn(async () => ({ kind: "deadline" as const })); + + const result = await runOpenClawAgentDispatch( + "alpha", + ["openclaw", "agent", "--agent", "main", ...flags], + { getGatewayName: () => null, stdinIsTty: () => false, readStdin }, + ); + + expect(readStdin).toHaveBeenCalledWith(ms); + expect(result.outcome).toEqual({ kind: "exited", exitCode: 1 }); + }); + + it("reads piped input to EOF", async () => { + const source = new PassThrough(); + const pending = readAgentStdinWithinDeadline(source, 1_000); + + source.end("ping\n"); + + await expect(pending).resolves.toEqual({ kind: "eof", data: Buffer.from("ping\n") }); + }); + + it("stops at the deadline while the producer keeps the pipe open", async () => { + vi.useFakeTimers(); + try { + const source = new PassThrough(); + const pending = readAgentStdinWithinDeadline(source, 1_000); + source.write("ping\n"); + + await vi.advanceTimersByTimeAsync(1_000); + + await expect(pending).resolves.toEqual({ kind: "deadline" }); + expect(source.destroyed).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + + it("stops at the size limit", async () => { + const source = new PassThrough(); + const pending = readAgentStdinWithinDeadline(source, 1_000, 4); + + source.write("12345"); + + await expect(pending).resolves.toEqual({ kind: "too-large" }); + expect(source.destroyed).toBe(true); + }); +}); diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts index f5fb5333939..04eeaae1bd8 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts @@ -42,6 +42,12 @@ // an explicit message retain the existing piped-input behavior. // - Removal condition: drop the TTY carve-out if `openclaw agent` gains a // documented interactive stdin mode reachable through this wrapper. +// - Input deadline (#13621): because OpenShell starts the remote command +// only at EOF, the in-sandbox parser's piped-input deadline cannot fire +// while a producer keeps the pipe open. The host therefore reads piped +// input itself within the same budget (positive `--timeout`, else 30 +// seconds) and the same size limit, then hands the bytes to OpenShell. +// Removal condition: OpenShell dispatches before stdin reaches EOF. // // 8. Host interruption propagation. // @@ -87,6 +93,8 @@ import type { OpenShellSandboxSessionExecutor, } from "../../../adapters/openshell/sandbox-session"; +import { isStdinTty } from "../../../core/stdin"; +import { MAX_TIMER_DELAY_MS } from "../../../core/timer"; import { getKnownSandboxTargetGatewayName } from "../gateway-target"; import { wrapOpenClawAgentCommandWithRuntimeEnv } from "../runtime-env"; @@ -111,11 +119,91 @@ export async function runAgentDispatch( return { outcome: result.outcome, stdout: result.stdout, stderr: result.stderr }; } -export type OpenClawAgentDispatchDeps = { +/** The in-sandbox OpenClaw parser uses the same default wait and size limit. */ +export const AGENT_STDIN_DEFAULT_DEADLINE_SECONDS = 30; +export const AGENT_STDIN_MAX_BYTES = 4 * 1024 * 1024; + +export type AgentStdinRead = + | { kind: "eof"; data: Buffer } + | { kind: "deadline" } + | { kind: "too-large" }; + +/** Read piped input to EOF, or stop at the deadline or size limit. */ +export function readAgentStdinWithinDeadline( + source: Pick & { destroy(): unknown }, + deadlineMs: number, + maxBytes: number = AGENT_STDIN_MAX_BYTES, +): Promise { + return new Promise((resolve) => { + const chunks: Buffer[] = []; + let size = 0; + const onData = (chunk: Buffer | string) => { + const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + size += data.byteLength; + if (size > maxBytes) return finish({ kind: "too-large" }, true); + chunks.push(data); + }; + // An unreadable descriptor carries no message; dispatch what was read. + const onEnd = () => finish({ kind: "eof", data: Buffer.concat(chunks) }, false); + const finish = (result: AgentStdinRead, release: boolean) => { + clearTimeout(timer); + source.off("data", onData); + source.off("end", onEnd); + source.off("error", onEnd); + if (release) source.destroy(); + resolve(result); + }; + const timer = setTimeout(() => finish({ kind: "deadline" }, true), deadlineMs); + source.on("data", onData); + source.on("end", onEnd); + source.on("error", onEnd); + }); +} + +function agentStdinFailure(read: Exclude, seconds: number) { + const problem = + read.kind === "deadline" + ? `Timed out after ${seconds} second(s) waiting for the piped message to end` + : `The piped message exceeds ${AGENT_STDIN_MAX_BYTES} bytes`; + return ` ${problem}. Close the producer after it writes the message, provide --message, or set --timeout .\n`; +} + +export type AgentStdinDispatchDeps = { + stdinIsTty?: () => boolean; + readStdin?: (deadlineMs: number) => Promise; +}; + +/** + * Give OpenShell piped input that already reached EOF, so the input deadline + * applies before dispatch. A closed or interactive stdin keeps its posture. + */ +export async function dispatchWithAgentStdinDeadline( + request: OpenShellSandboxSessionRequest, + deadlineSeconds: number, + run: AgentDispatchRunner, + deps: AgentStdinDispatchDeps = {}, +): Promise { + if ( + request.kind !== "command" || + request.stdin !== undefined || + (deps.stdinIsTty ?? isStdinTty)() + ) + return run(request); + const read = await ( + deps.readStdin ?? ((deadlineMs) => readAgentStdinWithinDeadline(process.stdin, deadlineMs)) + )(Math.min(deadlineSeconds * 1000, MAX_TIMER_DELAY_MS)); + if (read.kind === "eof") return run({ ...request, stdin: read.data }); + return { + outcome: { kind: "exited", exitCode: 1 }, + stdout: "", + stderr: agentStdinFailure(read, deadlineSeconds), + }; +} + +export type OpenClawAgentDispatchDeps = AgentStdinDispatchDeps & { getOpenshellBinary?: () => string; getGatewayName?: (sandboxName: string) => string | null; runDispatch?: AgentDispatchRunner; - stdinIsTty?: () => boolean; }; /** Both output formats use the same argv, owning gateway, deadline, and stdin policy. */ @@ -125,15 +213,23 @@ export function runOpenClawAgentDispatch( deps: OpenClawAgentDispatchDeps = {}, ): Promise { const gatewayName = (deps.getGatewayName ?? getKnownSandboxTargetGatewayName)(sandboxName); + const inputDeadlineSeconds = + requestedAgentTimeoutSeconds(command) ?? AGENT_STDIN_DEFAULT_DEADLINE_SECONDS; const runDispatch: AgentDispatchRunner = deps.runDispatch ?? ((request) => - runAgentDispatch( + dispatchWithAgentStdinDeadline( request, - createCliOpenShellSandboxSessionExecutor({ - resolveBinary: deps.getOpenshellBinary, - stdinIsTty: deps.stdinIsTty, - }), + inputDeadlineSeconds, + (prepared) => + runAgentDispatch( + prepared, + createCliOpenShellSandboxSessionExecutor({ + resolveBinary: deps.getOpenshellBinary, + stdinIsTty: deps.stdinIsTty, + }), + ), + deps, )); return runDispatch({ kind: "command", diff --git a/src/lib/adapters/openshell/sandbox-command-cli.ts b/src/lib/adapters/openshell/sandbox-command-cli.ts index 293cdc1f328..7d566e7fc98 100644 --- a/src/lib/adapters/openshell/sandbox-command-cli.ts +++ b/src/lib/adapters/openshell/sandbox-command-cli.ts @@ -37,7 +37,11 @@ import { export { assertCliOpenShellSandboxName, assertCliOpenShellTarget } from "./target-validation"; -import { runCapturedProcess, type CapturedProcessChild } from "../../core/process-capture"; +import { + feedCapturedProcessStdin, + runCapturedProcess, + type CapturedProcessChild, +} from "../../core/process-capture"; import type { OpenShellSandboxSessionExecutor, OpenShellSandboxSessionOutcome, @@ -376,6 +380,11 @@ export function createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor }; } +function sessionStdinMode(input: boolean | Buffer | undefined): "pipe" | "ignore" | "inherit" { + if (Buffer.isBuffer(input)) return "pipe"; + return input === false ? "ignore" : "inherit"; +} + export type CliOpenShellSessionChild = CapturedProcessChild; export type CliOpenShellSessionSpawner = ( binary: string, @@ -521,12 +530,16 @@ export function createCliOpenShellSandboxSessionExecutor( { spawnChild: spawnSession, signalSource: deps.signalSource }, ) : superviseProcessSession( - () => - spawnSession(binary, args, [ - request.kind === "command" && request.stdin === false ? "ignore" : "inherit", + () => { + const input = request.kind === "command" ? request.stdin : undefined; + const session = spawnSession(binary, args, [ + sessionStdinMode(input), "inherit", "inherit", - ]), + ]); + if (Buffer.isBuffer(input)) feedCapturedProcessStdin(session, input); + return session; + }, deps.signalSource, { forwardSigint: !stdinIsTty }, ); diff --git a/src/lib/adapters/openshell/sandbox-session.ts b/src/lib/adapters/openshell/sandbox-session.ts index 2e9080bbfcf..5d309009900 100644 --- a/src/lib/adapters/openshell/sandbox-session.ts +++ b/src/lib/adapters/openshell/sandbox-session.ts @@ -16,7 +16,8 @@ export type OpenShellSandboxSessionRequest = Readonly<{ tty?: boolean | null; timeoutSeconds?: number; output: "inherit" | "capture"; - stdin?: boolean; + /** `false` closes fd 0; bytes are written to a pipe and then closed. */ + stdin?: boolean | Buffer; outputLimitBytes?: number; }> ); diff --git a/src/lib/core/process-capture.test.ts b/src/lib/core/process-capture.test.ts index 078b499b43d..4fd23726b66 100644 --- a/src/lib/core/process-capture.test.ts +++ b/src/lib/core/process-capture.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { StdioOptions } from "node:child_process"; import { EventEmitter } from "node:events"; import { describe, expect, it, vi } from "vitest"; import { @@ -124,6 +125,27 @@ describe("runCapturedProcess", () => { expect(result.stdout).toBe("1234"); expect(result.stderr).toBe(""); }); + + it("writes supplied input to a piped fd 0 and closes it (#13621)", async () => { + const harness = dispatchHarness(); + const end = vi.fn(); + harness.child.stdin = { on: vi.fn(), end }; + const spawnChild = vi.fn( + (_binary: string, _args: readonly string[], _stdio: StdioOptions) => harness.child, + ); + const pending = runCapturedProcess( + "openshell", + ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "agent"], + { stdinIsTty: false, stdin: Buffer.from("ping\n") }, + { signalSource: harness.signalSource, spawnChild }, + ); + + harness.childEvents.emit("close", 0, null); + + expect(await pending).toMatchObject({ status: 0 }); + expect(spawnChild.mock.calls[0]?.[2]).toEqual(["pipe", "pipe", "pipe"]); + expect(end).toHaveBeenCalledWith(Buffer.from("ping\n")); + }); }); describe("capturedProcessStdio", () => { it("closes an idle input pipe when stdin is disabled (#11371)", () => { diff --git a/src/lib/core/process-capture.ts b/src/lib/core/process-capture.ts index 7b4b5217e32..b47e55821d4 100644 --- a/src/lib/core/process-capture.ts +++ b/src/lib/core/process-capture.ts @@ -30,11 +30,26 @@ type CaptureBudget = { overflowed: boolean; }; +type CapturedProcessWritable = { + on(event: "error", listener: (error: Error) => void): unknown; + end(chunk: Buffer): unknown; +}; + export type CapturedProcessChild = ProcessSessionChild & { stderr: CapturedProcessReadable | null; stdout: CapturedProcessReadable | null; + stdin?: CapturedProcessWritable | null; }; +/** + * Write caller-supplied input to a child spawned with a piped fd 0, then close it. + * The child can exit before it reads everything, so a write error is not a result. + */ +export function feedCapturedProcessStdin(child: CapturedProcessChild, input: Buffer): void { + child.stdin?.on("error", () => {}); + child.stdin?.end(input); +} + export type CapturedProcessSpawner = ( binary: string, args: readonly string[], @@ -89,7 +104,7 @@ export async function runCapturedProcess( options: { maxBufferBytes?: number; stdinIsTty?: boolean; - stdin?: boolean; + stdin?: boolean | Buffer; } = {}, deps: CapturedProcessRunDeps = {}, ): Promise { @@ -103,6 +118,7 @@ export async function runCapturedProcess( const result = await superviseProcessSession( () => { const child = spawnChild(binary, args, capturedProcessStdio(stdinIsTty, options.stdin)); + if (Buffer.isBuffer(options.stdin)) feedCapturedProcessStdin(child, options.stdin); const setOverflowError = (error: Error) => { overflowError ??= error; }; @@ -142,12 +158,13 @@ export async function runCapturedProcess( /** * Stdio for a non-interactive agent dispatch. An interactive terminal is - * withheld from fd 0. Callers can close unused input explicitly; other pipes - * and redirects retain their original bytes. + * withheld from fd 0. Callers can close unused input explicitly or supply the + * bytes they already read; other pipes and redirects retain their original bytes. */ export function capturedProcessStdio( stdinIsTty: boolean = isStdinTty(), - stdin = true, + stdin: boolean | Buffer = true, ): StdioOptions { + if (Buffer.isBuffer(stdin)) return ["pipe", "pipe", "pipe"]; return [stdinIsTty || !stdin ? "ignore" : "inherit", "pipe", "pipe"]; } From 4f13cb318d3bc2a0c5872d6d9ddf44d7c5631b9d Mon Sep 17 00:00:00 2001 From: Rui Luo Date: Fri, 23 Oct 2026 11:09:04 +0800 Subject: [PATCH 2/8] fix(agent): fail before dispatch when piped input cannot be read Signed-off-by: Rui Luo --- .../agent/passthrough-dispatch.test.ts | 13 ++++++++++++- .../sandbox/agent/passthrough-dispatch.ts | 19 +++++++++++-------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts index 8faed9216e1..a118eed1b8e 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts @@ -425,7 +425,8 @@ describe("agent piped-input deadline (#13621)", () => { "Timed out after 1 second(s) waiting for the piped message to end.", ], [{ kind: "too-large" as const }, `The piped message exceeds ${AGENT_STDIN_MAX_BYTES} bytes.`], - ])("fails before dispatch when piped input does not end in time %#", async (read, problem) => { + [{ kind: "read-error" as const }, "Could not read the piped message from stdin."], + ])("fails before dispatch when piped input does not end cleanly %#", async (read, problem) => { const run = runner(); const result = await dispatchWithAgentStdinDeadline(request, 1, run, { @@ -496,6 +497,16 @@ describe("agent piped-input deadline (#13621)", () => { } }); + it("reports a read error after partial input instead of a truncated message", async () => { + const source = new PassThrough(); + const pending = readAgentStdinWithinDeadline(source, 1_000); + + source.write("pi"); + source.destroy(new Error("EIO")); + + await expect(pending).resolves.toEqual({ kind: "read-error" }); + }); + it("stops at the size limit", async () => { const source = new PassThrough(); const pending = readAgentStdinWithinDeadline(source, 1_000, 4); diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts index 04eeaae1bd8..fccf671c215 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts @@ -126,7 +126,8 @@ export const AGENT_STDIN_MAX_BYTES = 4 * 1024 * 1024; export type AgentStdinRead = | { kind: "eof"; data: Buffer } | { kind: "deadline" } - | { kind: "too-large" }; + | { kind: "too-large" } + | { kind: "read-error" }; /** Read piped input to EOF, or stop at the deadline or size limit. */ export function readAgentStdinWithinDeadline( @@ -143,28 +144,30 @@ export function readAgentStdinWithinDeadline( if (size > maxBytes) return finish({ kind: "too-large" }, true); chunks.push(data); }; - // An unreadable descriptor carries no message; dispatch what was read. const onEnd = () => finish({ kind: "eof", data: Buffer.concat(chunks) }, false); + // A read error can follow partial input; never dispatch a truncated message. + const onError = () => finish({ kind: "read-error" }, true); const finish = (result: AgentStdinRead, release: boolean) => { clearTimeout(timer); source.off("data", onData); source.off("end", onEnd); - source.off("error", onEnd); + source.off("error", onError); if (release) source.destroy(); resolve(result); }; const timer = setTimeout(() => finish({ kind: "deadline" }, true), deadlineMs); source.on("data", onData); source.on("end", onEnd); - source.on("error", onEnd); + source.on("error", onError); }); } function agentStdinFailure(read: Exclude, seconds: number) { - const problem = - read.kind === "deadline" - ? `Timed out after ${seconds} second(s) waiting for the piped message to end` - : `The piped message exceeds ${AGENT_STDIN_MAX_BYTES} bytes`; + const problem = { + deadline: `Timed out after ${seconds} second(s) waiting for the piped message to end`, + "too-large": `The piped message exceeds ${AGENT_STDIN_MAX_BYTES} bytes`, + "read-error": "Could not read the piped message from stdin", + }[read.kind]; return ` ${problem}. Close the producer after it writes the message, provide --message, or set --timeout .\n`; } From 746f32a826f1f04637affea65bbff78c20ab488d Mon Sep 17 00:00:00 2001 From: Rui Luo Date: Fri, 23 Oct 2026 12:28:23 +0800 Subject: [PATCH 3/8] test(agent): cover buffered stdin handoff to the OpenShell child Signed-off-by: Rui Luo --- docs/reference/commands.mdx | 4 ++-- .../openshell/sandbox-session-cli.test.ts | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 87e3c42d3d3..1f3d201d3cf 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1496,8 +1496,8 @@ For example, the wrapper preserves redirected input for `printf 'ping' | $$nemoc The producer must close standard input after writing the message. OpenShell starts the sandbox command only after standard input ends, so without an inline message NemoClaw reads piped input on the host first. It waits up to 30 seconds for the input to end, including for `--message-file /dev/stdin` and symlinks to stdin. -A positive `--timeout ` sets this input wait as well as the agent turn timeout. -If the input deadline expires, or the input exceeds 4 MiB, the command exits nonzero without starting the turn and prints guidance to close the producer or provide an inline message. +A positive whole-number `--timeout ` sets this input wait as well as the agent turn timeout; any other value keeps the 30-second wait. +If the input deadline expires, the input exceeds 4 MiB, or standard input cannot be read, the command exits nonzero without starting the turn and prints guidance to close the producer or provide an inline message. When the top-level OpenClaw `--json` output flag is present, the wrapper uses a captured no-TTY path with a `64 MiB` buffer so `stdout` stays parseable JSON. Raw `stderr`, including structured JSON diagnostics, is forwarded unchanged. NemoClaw appends failed-tool or untrusted-child provenance only from the `stdout` JSON. The wrapper reads completion markers only from the final matching OpenClaw response envelope: a local `{ payloads, meta }` response or a gateway `{ status, result: { payloads, meta } }` response. It ignores earlier JSON progress or log records. It exits with status `1` when that metadata contains `error.kind: "incomplete_turn"`, `livenessState: "abandoned"`, or a `timeoutPhase` value, even when the envelope reports success. `replayInvalid: true` means replaying the turn may repeat side effects. The wrapper accepts it only with evidence of a completed run, a successful tool summary, and final assistant text matching the reply payload. Otherwise it exits with status `1` and the existing inspect-before-retry guidance. Marker-shaped values inside tool results, tool-call arguments, or other descendants do not change the exit status. A turn can run every tool successfully and still become abandoned before it produces a reply. The wrapper writes the unchanged JSON trace to `stdout` before it reports the incomplete turn, so the partial tool trace remains available. The wrapper writes the verdict, the detected markers, and verify-before-retry guidance to `stderr`. A `timeoutPhase` value names the phase the deadline fired in, so the wrapper writes deadline guidance in place of the generic incomplete-turn text. Tool calls in a partial trace may have already applied side effects, so verify what the turn changed before you retry it. The wrapper passes through an upstream non-zero exit status unchanged. Literal `--json` values consumed by flags such as `-m` or `--reply-channel`, or arguments after `--`, stay on the normal passthrough path. Documented value flags written as `--flag=value`, such as `--session-id=s1`, are recognized the same way as separated value flags. If an unrecognized OpenClaw option appears before `--json`, NemoClaw also keeps the command on the normal passthrough path so OpenClaw remains the argv source of truth. diff --git a/src/lib/adapters/openshell/sandbox-session-cli.test.ts b/src/lib/adapters/openshell/sandbox-session-cli.test.ts index 1232aeccf11..decc8d9fe43 100644 --- a/src/lib/adapters/openshell/sandbox-session-cli.test.ts +++ b/src/lib/adapters/openshell/sandbox-session-cli.test.ts @@ -131,6 +131,27 @@ describe("OpenShell sessions", () => { }, ); + it.each(["capture", "inherit"] as const)( + "writes buffered stdin to a closed piped fd 0 with %s output (#13621)", + async (output) => { + const f = sessionHarness(false); + const end = vi.fn(); + f.child.stdin = { on: vi.fn(), end }; + const session = f.executor.start({ ...command, output, stdin: Buffer.from("ping\n") }); + + expect(f.spawnChild.mock.calls[0]?.[2].stdio).toEqual([ + "pipe", + output === "capture" ? "pipe" : "inherit", + output === "capture" ? "pipe" : "inherit", + ]); + expect(end).toHaveBeenCalledWith(Buffer.from("ping\n")); + f.events.emit("close", 0, null); + const completed = await session.completion; + expect(completed.outcome).toEqual({ kind: "exited", exitCode: 0 }); + completed.release(); + }, + ); + it("captures a gateway-scoped command and withholds terminal stdin", async () => { const f = sessionHarness(); const session = f.executor.start(command); From 89a0879cbd93043efc952fc19ad561eed6cfedbc Mon Sep 17 00:00:00 2001 From: Rui Luo Date: Fri, 23 Oct 2026 13:42:25 +0800 Subject: [PATCH 4/8] test(agent): cover the default dispatch stdin handoff Signed-off-by: Rui Luo --- .../agent/passthrough-dispatch.test.ts | 33 +++++++++++++++++++ .../sandbox/agent/passthrough-dispatch.ts | 7 +++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts index a118eed1b8e..1b8a543277c 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { StdioOptions } from "node:child_process"; import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; import type { CapturedProcessChild } from "../../../core/process-capture"; @@ -472,6 +473,38 @@ describe("agent piped-input deadline (#13621)", () => { expect(result.outcome).toEqual({ kind: "exited", exitCode: 1 }); }); + it("hands EOF-delimited input from the default dispatch to OpenShell fd 0", async () => { + const harness = dispatchHarness(); + const end = vi.fn(); + harness.child.stdin = { on: vi.fn(), end }; + const spawnChild = vi.fn( + (_binary: string, _args: readonly string[], _options: { stdio: StdioOptions }) => { + queueMicrotask(() => { + harness.stdout.emit("data", "PONG\n"); + harness.child.exitCode = 0; + harness.childEvents.emit("close", 0, null); + }); + return harness.child; + }, + ); + + const result = await runOpenClawAgentDispatch( + "alpha", + ["openclaw", "agent", "--agent", "main"], + { + getGatewayName: () => null, + getOpenshellBinary: () => "openshell", + stdinIsTty: () => false, + readStdin: async () => ({ kind: "eof", data: Buffer.from("ping\n") }), + spawnChild, + }, + ); + + expect(spawnChild.mock.calls[0]?.[2].stdio).toEqual(["pipe", "pipe", "pipe"]); + expect(end).toHaveBeenCalledWith(Buffer.from("ping\n")); + expect(result).toMatchObject({ outcome: { kind: "exited", exitCode: 0 }, stdout: "PONG\n" }); + }); + it("reads piped input to EOF", async () => { const source = new PassThrough(); const pending = readAgentStdinWithinDeadline(source, 1_000); diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts index fccf671c215..90d96e5d78d 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts @@ -86,7 +86,10 @@ // CLI session and core capture tests own the process lifecycle. // `passthrough-help.test.ts` owns the diagnostic text. -import { createCliOpenShellSandboxSessionExecutor } from "../../../adapters/openshell/sandbox-command-cli"; +import { + createCliOpenShellSandboxSessionExecutor, + type CliOpenShellSessionSpawner, +} from "../../../adapters/openshell/sandbox-command-cli"; import type { OpenShellSandboxSessionCompletion, OpenShellSandboxSessionRequest, @@ -207,6 +210,7 @@ export type OpenClawAgentDispatchDeps = AgentStdinDispatchDeps & { getOpenshellBinary?: () => string; getGatewayName?: (sandboxName: string) => string | null; runDispatch?: AgentDispatchRunner; + spawnChild?: CliOpenShellSessionSpawner; }; /** Both output formats use the same argv, owning gateway, deadline, and stdin policy. */ @@ -230,6 +234,7 @@ export function runOpenClawAgentDispatch( createCliOpenShellSandboxSessionExecutor({ resolveBinary: deps.getOpenshellBinary, stdinIsTty: deps.stdinIsTty, + spawnChild: deps.spawnChild, }), ), deps, From f86d0d2af8b32929ca933b89455a5f09ae88fbc9 Mon Sep 17 00:00:00 2001 From: Rui Luo Date: Fri, 23 Oct 2026 14:16:58 +0800 Subject: [PATCH 5/8] docs(agent): state which --timeout values set the piped-input wait Signed-off-by: Rui Luo --- docs/reference/commands.mdx | 3 +- .../agent/passthrough-dispatch.test.ts | 30 +++++++++++-------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 1f3d201d3cf..59d2b9669a1 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1496,7 +1496,8 @@ For example, the wrapper preserves redirected input for `printf 'ping' | $$nemoc The producer must close standard input after writing the message. OpenShell starts the sandbox command only after standard input ends, so without an inline message NemoClaw reads piped input on the host first. It waits up to 30 seconds for the input to end, including for `--message-file /dev/stdin` and symlinks to stdin. -A positive whole-number `--timeout ` sets this input wait as well as the agent turn timeout; any other value keeps the 30-second wait. +A `--timeout ` that bounds the OpenShell wait above also sets this input wait. +Each case in the preceding list instead keeps the 30-second input wait, including a `--timeout` after an unrecognized option or after `--`. If the input deadline expires, the input exceeds 4 MiB, or standard input cannot be read, the command exits nonzero without starting the turn and prints guidance to close the producer or provide an inline message. When the top-level OpenClaw `--json` output flag is present, the wrapper uses a captured no-TTY path with a `64 MiB` buffer so `stdout` stays parseable JSON. Raw `stderr`, including structured JSON diagnostics, is forwarded unchanged. NemoClaw appends failed-tool or untrusted-child provenance only from the `stdout` JSON. The wrapper reads completion markers only from the final matching OpenClaw response envelope: a local `{ payloads, meta }` response or a gateway `{ status, result: { payloads, meta } }` response. It ignores earlier JSON progress or log records. It exits with status `1` when that metadata contains `error.kind: "incomplete_turn"`, `livenessState: "abandoned"`, or a `timeoutPhase` value, even when the envelope reports success. `replayInvalid: true` means replaying the turn may repeat side effects. The wrapper accepts it only with evidence of a completed run, a successful tool summary, and final assistant text matching the reply payload. Otherwise it exits with status `1` and the existing inspect-before-retry guidance. Marker-shaped values inside tool results, tool-call arguments, or other descendants do not change the exit status. A turn can run every tool successfully and still become abandoned before it produces a reply. The wrapper writes the unchanged JSON trace to `stdout` before it reports the incomplete turn, so the partial tool trace remains available. The wrapper writes the verdict, the detected markers, and verify-before-retry guidance to `stderr`. A `timeoutPhase` value names the phase the deadline fired in, so the wrapper writes deadline guidance in place of the generic incomplete-turn text. Tool calls in a partial trace may have already applied side effects, so verify what the turn changed before you retry it. The wrapper passes through an upstream non-zero exit status unchanged. Literal `--json` values consumed by flags such as `-m` or `--reply-channel`, or arguments after `--`, stay on the normal passthrough path. Documented value flags written as `--flag=value`, such as `--session-id=s1`, are recognized the same way as separated value flags. If an unrecognized OpenClaw option appears before `--json`, NemoClaw also keeps the command on the normal passthrough path so OpenClaw remains the argv source of truth. diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts index 1b8a543277c..d69570505b3 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts @@ -460,18 +460,24 @@ describe("agent piped-input deadline (#13621)", () => { it.each([ [["--timeout", "1"], 1_000], [[], 30_000], - ])("uses a positive --timeout, else 30 seconds, as the input deadline %#", async (flags, ms) => { - const readStdin = vi.fn(async () => ({ kind: "deadline" as const })); - - const result = await runOpenClawAgentDispatch( - "alpha", - ["openclaw", "agent", "--agent", "main", ...flags], - { getGatewayName: () => null, stdinIsTty: () => false, readStdin }, - ); - - expect(readStdin).toHaveBeenCalledWith(ms); - expect(result.outcome).toEqual({ kind: "exited", exitCode: 1 }); - }); + [["--timeout", "1.5"], 30_000], + [["--unknown-flag", "--timeout", "1"], 30_000], + [["--", "--timeout", "1"], 30_000], + ])( + "uses a recognized --timeout, else 30 seconds, as the input deadline %#", + async (flags, ms) => { + const readStdin = vi.fn(async () => ({ kind: "deadline" as const })); + + const result = await runOpenClawAgentDispatch( + "alpha", + ["openclaw", "agent", "--agent", "main", ...flags], + { getGatewayName: () => null, stdinIsTty: () => false, readStdin }, + ); + + expect(readStdin).toHaveBeenCalledWith(ms); + expect(result.outcome).toEqual({ kind: "exited", exitCode: 1 }); + }, + ); it("hands EOF-delimited input from the default dispatch to OpenShell fd 0", async () => { const harness = dispatchHarness(); From 0d02b916425daa671107c5c2361f643c0c5d3752 Mon Sep 17 00:00:00 2001 From: Rui Luo Date: Fri, 23 Oct 2026 14:59:31 +0800 Subject: [PATCH 6/8] test(agent): prove a real child reads the buffered piped message Signed-off-by: Rui Luo --- test/cli/agent-dispatch-stdin.test.ts | 75 +++++++++++++++++++++++---- 1 file changed, 65 insertions(+), 10 deletions(-) diff --git a/test/cli/agent-dispatch-stdin.test.ts b/test/cli/agent-dispatch-stdin.test.ts index a89e383fea6..f3179c7bd63 100644 --- a/test/cli/agent-dispatch-stdin.test.ts +++ b/test/cli/agent-dispatch-stdin.test.ts @@ -9,6 +9,7 @@ import { EventEmitter } from "node:events"; import { describe, expect, it } from "vitest"; import { + readAgentStdinWithinDeadline, runAgentDispatch, runOpenClawAgentDispatch, type AgentDispatchRunner, @@ -26,6 +27,19 @@ const messageParser = patchAgentMessageInput( ), ).replace(/^import .*;\n/u, ""); +// A real child that resolves its message with the patched OpenClaw parser. +function parserChildScript(options: Record): string { + return `const fs = require('node:fs/promises'); +const nemoclawStdinStat = () => require('node:fs').fstatSync(0); +const readFileDescriptorBounded = async (fd) => require('node:fs').readFileSync(fd); +const MESSAGE_FILE_DECODER = new TextDecoder('utf-8', {fatal: true}); +const formatCliCommand = (command) => command; +${messageParser} +resolveAgentMessageOpts(${JSON.stringify(options)}).then(({message: input}) => { +console.log(JSON.stringify({payloads: [{text: JSON.stringify({input, args: process.argv.slice(2)})}]})); +}).catch((error) => { console.error(error.message); process.exitCode = 1; });`; +} + function openPipe(inputPath: string): number { expect(spawnSync("mkfifo", [inputPath]).status).toBe(0); return fs.openSync(inputPath, fs.constants.O_RDWR); @@ -120,19 +134,11 @@ describe.skipIf(process.platform === "win32")("agent dispatch stdin", () => { getGatewayName: () => "nemoclaw-8081", runDispatch: childDispatch( inputFd, - `const fs = require('node:fs/promises'); -const nemoclawStdinStat = () => require('node:fs').fstatSync(0); -const readFileDescriptorBounded = async (fd) => require('node:fs').readFileSync(fd); -const MESSAGE_FILE_DECODER = new TextDecoder('utf-8', {fatal: true}); -const formatCliCommand = (command) => command; -${messageParser} -resolveAgentMessageOpts(${JSON.stringify({ + parserChildScript({ ...(input === "inline" ? { message: "ARG_MESSAGE" } : {}), ...(messageFile ? { messageFile } : {}), json, - })}).then(({message: input}) => { -console.log(JSON.stringify({payloads: [{text: JSON.stringify({input, args: process.argv.slice(2)})}]})); -}).catch((error) => { console.error(error.message); process.exitCode = 1; });`, + }), { messageFile }, ), }), @@ -153,6 +159,55 @@ console.log(JSON.stringify({payloads: [{text: JSON.stringify({input, args: proce } }); + it.each([false, true])( + "hands closed piped input from the default dispatch to a real child (JSON: %s) (#13621)", + async (json) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-agent-buffered-")); + const inputPath = path.join(root, "input"); + fs.writeFileSync(inputPath, "PIPED_INPUT"); + const stdout: string[] = []; + const stderr: string[] = []; + const fdZero: unknown[] = []; + const command = ["openclaw", "agent", "--agent", "main", ...(json ? ["--json"] : [])]; + try { + const invoke = json ? runAgentJsonPassthrough : runAgentNonJsonPassthrough; + await expect( + invoke( + "alpha", + command, + { + exit(code: number): never { + throw new Error(`exit:${code}`); + }, + stdout: { write: (value: string) => stdout.push(value) }, + stderr: { write: (value: string) => stderr.push(value) }, + }, + { + getGatewayName: () => "nemoclaw-8081", + getOpenshellBinary: () => process.execPath, + stdinIsTty: () => false, + readStdin: (deadlineMs) => + readAgentStdinWithinDeadline(fs.createReadStream(inputPath), deadlineMs), + spawnChild: (_binary, args, { stdio }) => { + fdZero.push(Array.isArray(stdio) ? stdio[0] : stdio); + return spawn( + process.execPath, + ["-e", parserChildScript({ json }), "--", "/dev/stdin", ...args], + { stdio }, + ); + }, + }, + ), + ).rejects.toThrow("exit:0"); + expect(fdZero).toEqual(["pipe"]); + expect(JSON.parse(JSON.parse(stdout.join("")).payloads[0].text).input).toBe("PIPED_INPUT"); + expect(stderr.join("")).toBe(""); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }, + ); + it.each([ { signal: "SIGTERM" as const, code: 143 }, { signal: "SIGINT" as const, code: 130 }, From 3fecfb210d1546493079901d4822c3f77659cce2 Mon Sep 17 00:00:00 2001 From: Rui Luo Date: Fri, 23 Oct 2026 15:43:20 +0800 Subject: [PATCH 7/8] fix(agent): use the 30-second input wait when --timeout cannot bound dispatch Signed-off-by: Rui Luo --- src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts | 1 + src/lib/actions/sandbox/agent/passthrough-dispatch.ts | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts index d69570505b3..76a091fa80b 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts @@ -463,6 +463,7 @@ describe("agent piped-input deadline (#13621)", () => { [["--timeout", "1.5"], 30_000], [["--unknown-flag", "--timeout", "1"], 30_000], [["--", "--timeout", "1"], 30_000], + [["--timeout", String(Number.MAX_SAFE_INTEGER)], 30_000], ])( "uses a recognized --timeout, else 30 seconds, as the input deadline %#", async (flags, ms) => { diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts index 90d96e5d78d..c9065462c49 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts @@ -220,8 +220,12 @@ export function runOpenClawAgentDispatch( deps: OpenClawAgentDispatchDeps = {}, ): Promise { const gatewayName = (deps.getGatewayName ?? getKnownSandboxTargetGatewayName)(sandboxName); + // Only a timeout that also bounds the OpenShell wait sets the input wait. + const requestedSeconds = requestedAgentTimeoutSeconds(command); const inputDeadlineSeconds = - requestedAgentTimeoutSeconds(command) ?? AGENT_STDIN_DEFAULT_DEADLINE_SECONDS; + requestedSeconds !== null && agentDispatchDeadlineSeconds(command) !== undefined + ? requestedSeconds + : AGENT_STDIN_DEFAULT_DEADLINE_SECONDS; const runDispatch: AgentDispatchRunner = deps.runDispatch ?? ((request) => From 44ef9f74e0f64af45a29dfead6abf3128fd913e0 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter Date: Mon, 26 Oct 2026 14:14:24 -0700 Subject: [PATCH 8/8] fix(cli): report buffered agent stdin write failures Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../adapters/openshell/sandbox-command-cli.ts | 11 ++++++++-- .../openshell/sandbox-session-cli.test.ts | 17 +++++++++++++++ src/lib/core/process-capture.test.ts | 17 +++++++++++++++ src/lib/core/process-capture.ts | 21 ++++++++++++++----- 4 files changed, 59 insertions(+), 7 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-command-cli.ts b/src/lib/adapters/openshell/sandbox-command-cli.ts index 7d566e7fc98..fb565037d7f 100644 --- a/src/lib/adapters/openshell/sandbox-command-cli.ts +++ b/src/lib/adapters/openshell/sandbox-command-cli.ts @@ -510,6 +510,7 @@ export function createCliOpenShellSandboxSessionExecutor( const stdinIsTty = (deps.stdinIsTty ?? (() => Boolean(process.stdin.isTTY)))(); let cancelled = false; let finished = false; + let stdinError: Error | undefined; let child: CliOpenShellSessionChild | undefined; const spawnSession = (executable: string, argv: readonly string[], stdio: StdioOptions) => { const spawnChild: CliOpenShellSessionSpawner = @@ -537,7 +538,10 @@ export function createCliOpenShellSandboxSessionExecutor( "inherit", "inherit", ]); - if (Buffer.isBuffer(input)) feedCapturedProcessStdin(session, input); + if (Buffer.isBuffer(input)) + feedCapturedProcessStdin(session, input, (error) => { + stdinError ??= error; + }); return session; }, deps.signalSource, @@ -553,7 +557,10 @@ export function createCliOpenShellSandboxSessionExecutor( } } return { - outcome: sessionOutcome(result, cancelled), + outcome: sessionOutcome( + stdinError ? { ...result, error: result.error ?? stdinError } : result, + cancelled, + ), stdout: result.stdout ?? "", stderr: result.stderr ?? "", release: result.releaseSignals ?? (() => {}), diff --git a/src/lib/adapters/openshell/sandbox-session-cli.test.ts b/src/lib/adapters/openshell/sandbox-session-cli.test.ts index decc8d9fe43..97edd800320 100644 --- a/src/lib/adapters/openshell/sandbox-session-cli.test.ts +++ b/src/lib/adapters/openshell/sandbox-session-cli.test.ts @@ -152,6 +152,23 @@ describe("OpenShell sessions", () => { }, ); + it.each(["capture", "inherit"] as const)( + "fails a %s session when buffered stdin cannot be delivered (#13621)", + async (output) => { + const f = sessionHarness(false); + const stdin = new EventEmitter(); + f.child.stdin = { on: stdin.on.bind(stdin), end: vi.fn() }; + const session = f.executor.start({ ...command, output, stdin: Buffer.from("ping\n") }); + + stdin.emit("error", Object.assign(new Error("stdin closed early"), { code: "EPIPE" })); + f.events.emit("close", 0, null); + + const completed = await session.completion; + expect(completed.outcome).toMatchObject({ kind: "failed", reason: "invocation" }); + completed.release(); + }, + ); + it("captures a gateway-scoped command and withholds terminal stdin", async () => { const f = sessionHarness(); const session = f.executor.start(command); diff --git a/src/lib/core/process-capture.test.ts b/src/lib/core/process-capture.test.ts index 4fd23726b66..6edd3f0808f 100644 --- a/src/lib/core/process-capture.test.ts +++ b/src/lib/core/process-capture.test.ts @@ -146,6 +146,23 @@ describe("runCapturedProcess", () => { expect(spawnChild.mock.calls[0]?.[2]).toEqual(["pipe", "pipe", "pipe"]); expect(end).toHaveBeenCalledWith(Buffer.from("ping\n")); }); + + it("reports a buffered stdin write failure even when the child exits successfully (#13621)", async () => { + const harness = dispatchHarness(); + const stdin = new EventEmitter(); + harness.child.stdin = { on: stdin.on.bind(stdin), end: vi.fn() }; + const pending = runCapturedProcess( + "openshell", + ["sandbox", "exec"], + { stdinIsTty: false, stdin: Buffer.from("ping\n") }, + { signalSource: harness.signalSource, spawnChild: () => harness.child }, + ); + + stdin.emit("error", Object.assign(new Error("stdin closed early"), { code: "EPIPE" })); + harness.childEvents.emit("close", 0, null); + + expect(await pending).toMatchObject({ status: 0, error: { code: "EPIPE" } }); + }); }); describe("capturedProcessStdio", () => { it("closes an idle input pipe when stdin is disabled (#11371)", () => { diff --git a/src/lib/core/process-capture.ts b/src/lib/core/process-capture.ts index b47e55821d4..142f3adc8d4 100644 --- a/src/lib/core/process-capture.ts +++ b/src/lib/core/process-capture.ts @@ -43,10 +43,15 @@ export type CapturedProcessChild = ProcessSessionChild & { /** * Write caller-supplied input to a child spawned with a piped fd 0, then close it. - * The child can exit before it reads everything, so a write error is not a result. + * Report write failures so a child that exits successfully without reading + * its input cannot make the caller report a successful agent turn. */ -export function feedCapturedProcessStdin(child: CapturedProcessChild, input: Buffer): void { - child.stdin?.on("error", () => {}); +export function feedCapturedProcessStdin( + child: CapturedProcessChild, + input: Buffer, + onError: (error: Error) => void, +): void { + child.stdin?.on("error", onError); child.stdin?.end(input); } @@ -112,13 +117,17 @@ export async function runCapturedProcess( const stdoutChunks: Buffer[] = []; const captureBudget: CaptureBudget = { bytes: 0, overflowed: false }; let overflowError: Error | undefined; + let stdinError: Error | undefined; const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_CAPTURE_LIMIT_BYTES; const spawnChild = deps.spawnChild ?? defaultCapturedProcessSpawner; const stdinIsTty = options.stdinIsTty ?? isStdinTty(); const result = await superviseProcessSession( () => { const child = spawnChild(binary, args, capturedProcessStdio(stdinIsTty, options.stdin)); - if (Buffer.isBuffer(options.stdin)) feedCapturedProcessStdin(child, options.stdin); + if (Buffer.isBuffer(options.stdin)) + feedCapturedProcessStdin(child, options.stdin, (error) => { + stdinError ??= error; + }); const setOverflowError = (error: Error) => { overflowError ??= error; }; @@ -147,7 +156,9 @@ export async function runCapturedProcess( return { status: result.status, signal: result.signal, - ...(result.error || overflowError ? { error: result.error ?? overflowError } : {}), + ...(result.error || overflowError || stdinError + ? { error: result.error ?? overflowError ?? stdinError } + : {}), stderr: Buffer.concat(stderrChunks).toString("utf-8"), stdout: Buffer.concat(stdoutChunks).toString("utf-8"), };