Skip to content
Merged
8 changes: 5 additions & 3 deletions docs/reference/commands.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <seconds>` 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 <seconds>` 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.

Expand Down
174 changes: 174 additions & 0 deletions src/lib/actions/sandbox/agent/passthrough-dispatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 <seconds>");
});

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);
});
});
124 changes: 116 additions & 8 deletions src/lib/actions/sandbox/agent/passthrough-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand Down Expand Up @@ -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";

Expand All @@ -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<NodeJS.ReadableStream, "on" | "off"> & { destroy(): unknown },
deadlineMs: number,
maxBytes: number = AGENT_STDIN_MAX_BYTES,
): Promise<AgentStdinRead> {
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<AgentStdinRead, { kind: "eof" }>, 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 <seconds>.\n`;
}

export type AgentStdinDispatchDeps = {
stdinIsTty?: () => boolean;
readStdin?: (deadlineMs: number) => Promise<AgentStdinRead>;
};

/**
* 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<AgentDispatchResult> {
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. */
Expand All @@ -125,15 +220,28 @@ export function runOpenClawAgentDispatch(
deps: OpenClawAgentDispatchDeps = {},
): Promise<AgentDispatchResult> {
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",
Expand Down
Loading
Loading