diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 29a91086c24..07cfab1fc32 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1497,9 +1497,11 @@ 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. -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. +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 `--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 a17e6e4f2ad..76a091fa80b 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts @@ -2,11 +2,17 @@ // 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"; 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 +389,171 @@ 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.`], + [{ 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, { + 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], + [["--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) => { + 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(); + 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); + + 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("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); + + 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..c9065462c49 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. // @@ -80,13 +86,18 @@ // 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, 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 +122,95 @@ 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" } + | { kind: "read-error" }; + +/** 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); + }; + 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", 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", onError); + }); +} + +function agentStdinFailure(read: Exclude, seconds: number) { + 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`; +} + +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; + spawnChild?: CliOpenShellSessionSpawner; }; /** Both output formats use the same argv, owning gateway, deadline, and stdin policy. */ @@ -125,15 +220,28 @@ 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 = + requestedSeconds !== null && agentDispatchDeadlineSeconds(command) !== undefined + ? requestedSeconds + : 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, + spawnChild: deps.spawnChild, + }), + ), + 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..fb565037d7f 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, @@ -501,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 = @@ -521,12 +531,19 @@ 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, (error) => { + stdinError ??= error; + }); + return session; + }, deps.signalSource, { forwardSigint: !stdinIsTty }, ); @@ -540,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 1232aeccf11..97edd800320 100644 --- a/src/lib/adapters/openshell/sandbox-session-cli.test.ts +++ b/src/lib/adapters/openshell/sandbox-session-cli.test.ts @@ -131,6 +131,44 @@ 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.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/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..6edd3f0808f 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,44 @@ 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")); + }); + + 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 7b4b5217e32..142f3adc8d4 100644 --- a/src/lib/core/process-capture.ts +++ b/src/lib/core/process-capture.ts @@ -30,11 +30,31 @@ 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. + * 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, + onError: (error: Error) => void, +): void { + child.stdin?.on("error", onError); + child.stdin?.end(input); +} + export type CapturedProcessSpawner = ( binary: string, args: readonly string[], @@ -89,7 +109,7 @@ export async function runCapturedProcess( options: { maxBufferBytes?: number; stdinIsTty?: boolean; - stdin?: boolean; + stdin?: boolean | Buffer; } = {}, deps: CapturedProcessRunDeps = {}, ): Promise { @@ -97,12 +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, (error) => { + stdinError ??= error; + }); const setOverflowError = (error: Error) => { overflowError ??= error; }; @@ -131,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"), }; @@ -142,12 +169,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"]; } 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 },