diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index c3fdd39cec3..0f60d3464f9 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -432,6 +432,23 @@ The exit code is the remote command's exit code. | `--tty` / `--no-tty` | Allocate a pseudo-terminal; defaults to auto-detection (on when stdin and stdout are terminals) | | `--timeout ` | Timeout in seconds (`0` means no timeout) | +### `nemohermes agent` + +Run one OpenClaw agent turn non-interactively in a running sandbox. +This command forwards every argument verbatim to `openclaw agent ...` inside the sandbox via `openshell sandbox exec`, with `HOME=/sandbox` so the addressed agent profile resolves the same way as `connect`. +Use this when driving the sandbox programmatically from another process (CI job, multi-agent platform, evaluation harness) rather than from an interactive terminal. + +Only OpenClaw sandboxes support the `agent` wrapper today; Hermes sandboxes already expose an OpenAI-compatible HTTP API on port `8642` inside the sandbox, so non-interactive use does not need a wrapper command. + +Forward the port and POST chat completions directly: + +```bash +openshell forward start --background 8642 my-hermes +curl -sN http://127.0.0.1:8642/v1/chat/completions \ + -H 'Content-Type: application/json' \ + -d '{"model":"","messages":[{"role":"user","content":"What is 2+2?"}],"stream":true}' +``` + ### Advanced Sandbox Maintenance Commands The following commands are available for targeted host-side maintenance, but they are not part of the top-level public command list. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index ee29b93ae2d..268a2d55714 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -530,6 +530,43 @@ The exit code is the remote command's exit code. | `--tty` / `--no-tty` | Allocate a pseudo-terminal; defaults to auto-detection (on when stdin and stdout are terminals) | | `--timeout ` | Timeout in seconds (`0` means no timeout) | +### `$$nemoclaw agent` + +Run one OpenClaw agent turn non-interactively in a running sandbox. +This command forwards every argument verbatim to `openclaw agent ...` inside the sandbox via `openshell sandbox exec`, with `HOME=/sandbox` so the addressed agent profile resolves the same way as `connect`. +Use this when driving the sandbox programmatically from another process (CI job, multi-agent platform, evaluation harness) rather than from an interactive terminal. + + + +All flags accepted by the in-sandbox OpenClaw CLI are forwarded verbatim, so the upstream surface stays the single source of truth. + +```bash +$$nemoclaw my-assistant agent -m "Summarise README.md" +$$nemoclaw my-assistant agent --agent work -m "Status update?" +$$nemoclaw my-assistant agent --session-id review-42 -m "Any new findings?" +$$nemoclaw my-assistant agent --json -m 'ping' +``` + +The wrapper inherits the remote command's exit code, so host-side pipelines can branch on it. Streaming forwards whatever `openclaw agent` already emits on `stdout`; the wrapper adds no buffering. + +Common upstream flags include `-m `, `--session-id `, `--agent `, `--model `, `--thinking `, `--json`, `--deliver`, `--reply-channel `, and `--timeout `. Run `$$nemoclaw agent --help` for the wrapper-level summary, or invoke `$$nemoclaw exec -- openclaw agent --help` to view the upstream OpenClaw help text directly. + + + + +Only OpenClaw sandboxes support the `agent` wrapper today; Hermes sandboxes already expose an OpenAI-compatible HTTP API on port `8642` inside the sandbox, so non-interactive use does not need a wrapper command. + +Forward the port and POST chat completions directly: + +```bash +openshell forward start --background 8642 my-hermes +curl -sN http://127.0.0.1:8642/v1/chat/completions \ + -H 'Content-Type: application/json' \ + -d '{"model":"","messages":[{"role":"user","content":"What is 2+2?"}],"stream":true}' +``` + + + ### Advanced Sandbox Maintenance Commands The following commands are available for targeted host-side maintenance, but they are not part of the top-level public command list. diff --git a/src/commands/sandbox/agent.test.ts b/src/commands/sandbox/agent.test.ts new file mode 100644 index 00000000000..5731ab9a2af --- /dev/null +++ b/src/commands/sandbox/agent.test.ts @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const runAgentPassthroughMock = vi.hoisted(() => vi.fn(async () => {})); +vi.mock("../../lib/actions/sandbox/agent/passthrough", () => ({ + runAgentPassthrough: runAgentPassthroughMock, +})); + +import SandboxAgentCommand from "./agent"; + +const rootDir = process.cwd(); + +describe("SandboxAgentCommand oclif parse path", () => { + let logSpy: ReturnType; + + beforeEach(() => { + runAgentPassthroughMock.mockReset(); + logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); + }); + + afterEach(() => { + logSpy.mockRestore(); + }); + + it("forwards the OpenClaw argv verbatim to runAgentPassthrough", async () => { + await SandboxAgentCommand.run(["alpha", "--agent", "work", "-m", "hi"], rootDir); + expect(runAgentPassthroughMock).toHaveBeenCalledWith("alpha", { + extraArgs: ["--agent", "work", "-m", "hi"], + }); + }); + + it("does not call runAgentPassthrough when --help follows the sandbox name", async () => { + await SandboxAgentCommand.run(["alpha", "--help"], rootDir); + expect(runAgentPassthroughMock).not.toHaveBeenCalled(); + const help = logSpy.mock.calls.map((c: unknown[]) => String(c[0])).join("\n"); + expect(help).toMatch(/openclaw agent/); + }); + + it("does not call runAgentPassthrough when no sandbox name is supplied", async () => { + await SandboxAgentCommand.run([], rootDir); + expect(runAgentPassthroughMock).not.toHaveBeenCalled(); + const help = logSpy.mock.calls.map((c: unknown[]) => String(c[0])).join("\n"); + expect(help).toMatch(/Pass-through to/); + }); + + it("treats sandbox name '--help' as a help request, not a name", async () => { + await SandboxAgentCommand.run(["--help"], rootDir); + expect(runAgentPassthroughMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/commands/sandbox/agent.ts b/src/commands/sandbox/agent.ts new file mode 100644 index 00000000000..89a4bcc349a --- /dev/null +++ b/src/commands/sandbox/agent.ts @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + hasAgentPassthroughHelpToken, + printAgentPassthroughHelp, +} from "../../lib/actions/sandbox/agent/passthrough-help"; +import { runAgentPassthrough } from "../../lib/actions/sandbox/agent/passthrough"; +import { NemoClawCommand } from "../../lib/cli/nemoclaw-oclif-command"; + +export default class SandboxAgentCommand extends NemoClawCommand { + static id = "sandbox:agent"; + static strict = false; + static summary = "Run one OpenClaw agent turn non-interactively in a sandbox"; + static description = + "Pass through to `openclaw agent` inside the sandbox via `openshell sandbox exec`. Stream the agent's response back to stdout without owning a TTY; useful for driving the sandbox from another process (CI job, multi-agent platform, evaluation harness). All flags accepted by the in-sandbox OpenClaw CLI are forwarded verbatim, including `-m `, `--session-id `, `--agent `, `--json`, `--thinking `, `--deliver`, and `--reply-channel`. Currently supported on OpenClaw sandboxes only; Hermes sandboxes exit non-zero with a redirect to the OpenAI-compatible API on port 8642 inside the sandbox."; + static usage = [" [openclaw-agent-flags...]"]; + static examples = [ + '<%= config.bin %> sandbox agent alpha -m "Summarise README.md"', + '<%= config.bin %> sandbox agent alpha --agent work -m "Status update?"', + '<%= config.bin %> sandbox agent alpha --session-id review-42 -m "Any new findings?"', + "<%= config.bin %> sandbox agent alpha --json -m 'ping'", + ]; + + public async run(): Promise { + this.parsed = true; + const [sandboxName, ...extraArgs] = this.argv; + if ( + !sandboxName || + sandboxName.trim() === "" || + sandboxName === "--help" || + sandboxName === "-h" + ) { + printAgentPassthroughHelp(); + return; + } + if (hasAgentPassthroughHelpToken(extraArgs)) { + printAgentPassthroughHelp(); + return; + } + await runAgentPassthrough(sandboxName, { extraArgs }); + } +} diff --git a/src/lib/actions/sandbox/agent/passthrough-help.test.ts b/src/lib/actions/sandbox/agent/passthrough-help.test.ts new file mode 100644 index 00000000000..80b26719ddd --- /dev/null +++ b/src/lib/actions/sandbox/agent/passthrough-help.test.ts @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { hasAgentPassthroughHelpToken } from "./passthrough-help"; + +describe("hasAgentPassthroughHelpToken", () => { + it("returns true for --help before the OpenClaw argv separator", () => { + expect(hasAgentPassthroughHelpToken(["--help"])).toBe(true); + expect(hasAgentPassthroughHelpToken(["-h", "-m", "hi"])).toBe(true); + }); + + it("ignores --help that appears after the OpenClaw argv separator", () => { + expect(hasAgentPassthroughHelpToken(["--", "--help"])).toBe(false); + }); + + it("returns false for unrelated flags", () => { + expect(hasAgentPassthroughHelpToken(["-m", "hi"])).toBe(false); + expect(hasAgentPassthroughHelpToken([])).toBe(false); + }); +}); diff --git a/src/lib/actions/sandbox/agent/passthrough-help.ts b/src/lib/actions/sandbox/agent/passthrough-help.ts new file mode 100644 index 00000000000..bc97dc76ead --- /dev/null +++ b/src/lib/actions/sandbox/agent/passthrough-help.ts @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { CLI_NAME } from "../../../cli/branding"; + +export function hasAgentPassthroughHelpToken(args: readonly string[]): boolean { + for (const arg of args) { + if (arg === "--") break; + if (arg === "--help" || arg === "-h") return true; + } + return false; +} + +export function printAgentPassthroughHelp(): void { + console.log(""); + console.log(` Usage: ${CLI_NAME} agent [openclaw-agent-flags...]`); + console.log(""); + console.log( + " Pass-through to `openclaw agent ...` inside the sandbox via `openshell sandbox exec`.", + ); + console.log(" All flags accepted by the in-sandbox OpenClaw CLI are forwarded verbatim."); + console.log( + " Common flags: -m , --session-id , --agent , --json, --thinking .", + ); + console.log(""); + console.log( + " Currently supported on OpenClaw sandboxes only; Hermes sandboxes are rejected with a", + ); + console.log(" redirect to the OpenAI-compatible API on port 8642 inside the sandbox."); + console.log(""); +} diff --git a/src/lib/actions/sandbox/agent/passthrough.test.ts b/src/lib/actions/sandbox/agent/passthrough.test.ts new file mode 100644 index 00000000000..af2169408ef --- /dev/null +++ b/src/lib/actions/sandbox/agent/passthrough.test.ts @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +const execMock = vi.hoisted(() => vi.fn(async () => {})); +const ensureLiveMock = vi.hoisted(() => vi.fn(async () => ({}))); +const getSandboxMock = vi.hoisted(() => vi.fn(() => null as { agent?: string } | null)); + +vi.mock("../exec", () => ({ execSandbox: execMock })); +vi.mock("../gateway-state", () => ({ ensureLiveSandboxOrExit: ensureLiveMock })); +vi.mock("../../../state/registry", () => ({ getSandbox: getSandboxMock })); + +import { runAgentPassthrough } from "./passthrough"; + +describe("runAgentPassthrough", () => { + function makeProcMock() { + const writes: string[] = []; + const exit = vi.fn((code: number) => { + throw new Error(`__exit:${code}`); + }); + return { + writes, + exit, + proc: { + exit: exit as unknown as (code: number) => never, + stderr: { write: (s: string) => writes.push(s) }, + }, + }; + } + + it("rejects Hermes sandboxes with a redirect to the OpenAI-compatible API", async () => { + execMock.mockClear(); + ensureLiveMock.mockClear(); + getSandboxMock.mockReturnValueOnce({ agent: "hermes" }); + const { writes, exit, proc } = makeProcMock(); + await expect( + runAgentPassthrough("alpha", { extraArgs: ["-m", "hi"] }, { process: proc }), + ).rejects.toThrow("__exit:2"); + expect(execMock).not.toHaveBeenCalled(); + expect(ensureLiveMock).not.toHaveBeenCalled(); + expect(exit).toHaveBeenCalledWith(2); + expect(writes.join("")).toMatch( + /Only OpenClaw sandboxes support the `sandbox agent` wrapper today \(sandbox 'alpha' runs 'hermes'\)/, + ); + expect(writes.join("")).toMatch(/port 8642/); + }); + + it("forwards extraArgs verbatim to `openclaw agent` for OpenClaw sandboxes with --no-tty enforced", async () => { + execMock.mockClear(); + ensureLiveMock.mockClear(); + getSandboxMock.mockReturnValueOnce({ agent: "openclaw" }); + await runAgentPassthrough("alpha", { + extraArgs: ["--agent", "work", "--session-id", "s-1", "-m", "ping", "--json"], + }); + expect(ensureLiveMock).toHaveBeenCalledWith("alpha", { allowNonReadyPhase: true }); + expect(execMock).toHaveBeenCalledWith( + "alpha", + ["openclaw", "agent", "--agent", "work", "--session-id", "s-1", "-m", "ping", "--json"], + { tty: false }, + ); + }); + + it("treats a clean registry miss as OpenClaw (preserves bootstrap and recovery paths)", async () => { + execMock.mockClear(); + getSandboxMock.mockReturnValueOnce(null); + await runAgentPassthrough("ghost", { extraArgs: ["-m", "hi"] }); + expect(execMock).toHaveBeenCalledWith("ghost", ["openclaw", "agent", "-m", "hi"], { + tty: false, + }); + }); + + it("fails closed when the registry read throws and never spawns OpenShell exec", async () => { + execMock.mockClear(); + ensureLiveMock.mockClear(); + getSandboxMock.mockImplementationOnce(() => { + throw new Error("EACCES: permission denied, open '~/.config/nemoclaw/sandboxes.json'"); + }); + const { writes, exit, proc } = makeProcMock(); + await expect( + runAgentPassthrough("alpha", { extraArgs: ["-m", "hi"] }, { process: proc }), + ).rejects.toThrow("__exit:2"); + expect(execMock).not.toHaveBeenCalled(); + expect(ensureLiveMock).not.toHaveBeenCalled(); + expect(exit).toHaveBeenCalledWith(2); + const all = writes.join(""); + expect(all).toMatch(/Could not read the local sandbox registry/); + expect(all).toMatch(/Refusing to forward/); + expect(all).toMatch(/EACCES/); + }); + + it("works with no extraArgs and still enforces --no-tty", async () => { + execMock.mockClear(); + getSandboxMock.mockReturnValueOnce({ agent: "openclaw" }); + await runAgentPassthrough("alpha"); + expect(execMock).toHaveBeenCalledWith("alpha", ["openclaw", "agent"], { tty: false }); + }); +}); diff --git a/src/lib/actions/sandbox/agent/passthrough.ts b/src/lib/actions/sandbox/agent/passthrough.ts new file mode 100644 index 00000000000..80a17dcbbc8 --- /dev/null +++ b/src/lib/actions/sandbox/agent/passthrough.ts @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Source-of-truth boundary for the `nemoclaw agent` passthrough: +// +// - Invalid state: the local registry is the source of truth for which agent a +// sandbox runs (openclaw vs hermes vs future variants). Forwarding to +// `openclaw agent` against a non-OpenClaw sandbox triggers an in-sandbox +// binary that does not exist (or exists with incompatible flags), and would +// silently bypass the host-side guard intended to redirect Hermes callers to +// the OpenAI-compatible API on port 8642. +// +// - Source boundary: this wrapper owns the host-side guard only; the in-sandbox +// agent invocation, its argv contract, and its streaming behaviour are owned +// by upstream OpenClaw. NemoClaw does not rewrite OpenClaw flags here; it +// forwards them verbatim. +// +// - Source-fix constraint: NemoClaw cannot prove agent type from anywhere +// except the registry, because the OpenShell exec transport has no +// pre-execution probe that reveals the sandbox's configured agent. A +// registry read failure therefore has to fail closed — silently degrading +// to OpenClaw-as-default would let a Hermes-onboarded sandbox dispatch the +// wrong binary on transient I/O errors. +// +// - Regression tests: `passthrough.test.ts` covers the Hermes redirect, the +// forwarded argv, the registry-miss fallback to OpenClaw, the registry-error +// fail-closed path, and the enforced `--no-tty` argv shape. +// +// - Removal condition: when OpenShell exposes a metadata endpoint that returns +// the sandbox's configured agent, drop the registry read and consult that +// endpoint directly. The fail-closed branch can then be retired in favour of +// the live source. + +import * as registry from "../../../state/registry"; +import { execSandbox } from "../exec"; +import { ensureLiveSandboxOrExit } from "../gateway-state"; + +export { + hasAgentPassthroughHelpToken, + printAgentPassthroughHelp, +} from "./passthrough-help"; + +export interface AgentPassthroughOptions { + extraArgs?: readonly string[]; +} + +export interface AgentPassthroughDeps { + getSandbox?: typeof registry.getSandbox; + ensureLive?: typeof ensureLiveSandboxOrExit; + exec?: typeof execSandbox; + process?: { + exit(code: number): never; + stderr: { write(s: string): unknown }; + }; +} + +type RegistryReadResult = + | { kind: "missing" } + | { kind: "agent"; agent: string | null } + | { kind: "error"; message: string }; + +function readSandboxAgentFromRegistry( + sandboxName: string, + getSandbox: typeof registry.getSandbox = registry.getSandbox, +): RegistryReadResult { + try { + const sandbox = getSandbox(sandboxName); + if (!sandbox) return { kind: "missing" }; + return { kind: "agent", agent: sandbox.agent ?? null }; + } catch (error) { + return { kind: "error", message: (error as Error).message ?? String(error) }; + } +} + +function rejectNonOpenclawAgent( + sandboxName: string, + agent: string, + proc: NonNullable, +): never { + proc.stderr.write( + ` Only OpenClaw sandboxes support the \`sandbox agent\` wrapper today (sandbox '${sandboxName}' runs '${agent}').\n`, + ); + proc.stderr.write(" Hermes exposes an OpenAI-compatible API on port 8642 inside the sandbox;\n"); + proc.stderr.write( + ` forward it with 'openshell forward start --background 8642 ${sandboxName}'\n`, + ); + proc.stderr.write(" and POST to http://127.0.0.1:8642/v1/chat/completions instead.\n"); + return proc.exit(2); +} + +function rejectRegistryReadError( + sandboxName: string, + message: string, + proc: NonNullable, +): never { + proc.stderr.write( + ` Could not read the local sandbox registry to confirm agent type for '${sandboxName}'.\n`, + ); + proc.stderr.write(` Registry read error: ${message}\n`); + proc.stderr.write( + " Refusing to forward to `openclaw agent` because the agent guard cannot fail closed.\n", + ); + return proc.exit(2); +} + +export async function runAgentPassthrough( + sandboxName: string, + { extraArgs = [] }: AgentPassthroughOptions = {}, + deps: AgentPassthroughDeps = {}, +): Promise { + const proc = deps.process ?? process; + const lookup = readSandboxAgentFromRegistry(sandboxName, deps.getSandbox); + if (lookup.kind === "error") { + rejectRegistryReadError(sandboxName, lookup.message, proc); + } + if (lookup.kind === "agent" && lookup.agent && lookup.agent !== "openclaw") { + rejectNonOpenclawAgent(sandboxName, lookup.agent, proc); + } + const ensureLive = deps.ensureLive ?? ensureLiveSandboxOrExit; + await ensureLive(sandboxName, { allowNonReadyPhase: true }); + const command = ["openclaw", "agent", ...extraArgs]; + const exec = deps.exec ?? execSandbox; + await exec(sandboxName, command, { tty: false }); +} diff --git a/src/lib/cli/command-registry.test.ts b/src/lib/cli/command-registry.test.ts index 708dd33a7e3..d756f82bd50 100644 --- a/src/lib/cli/command-registry.test.ts +++ b/src/lib/cli/command-registry.test.ts @@ -55,12 +55,13 @@ describe("command-registry", () => { }); describe("sandboxCommands()", () => { - it("should return exactly 47 entries", () => { - // 41 visible + 6 hidden (shields×3 + config get/set/rotate-token). - // 41 visible includes the sessions group (root + list + reset + delete + - // export), the agents trio (add + delete + list), and the download + + it("should return exactly 48 entries", () => { + // 42 visible + 6 hidden (shields×3 + config get/set/rotate-token). + // 42 visible includes the sessions group (root + list + reset + delete + + // export), the agents trio (add + delete + list), the singular `agent` + // passthrough that forwards to `openclaw agent`, and the download + // upload host-side openshell wrappers. - expect(sandboxCommands()).toHaveLength(47); + expect(sandboxCommands()).toHaveLength(48); }); it("every entry has scope sandbox", () => { @@ -214,11 +215,12 @@ describe("command-registry", () => { }); describe("sandboxActionTokens()", () => { - it("returns exactly 28 unique action tokens including empty string", () => { + it("returns exactly 29 unique action tokens including empty string", () => { const tokens = sandboxActionTokens(); - expect(tokens).toHaveLength(28); + expect(tokens).toHaveLength(29); // Must contain every first-level sandbox action plus the empty default action. const expected = new Set([ + "agent", "agents", "connect", "dashboard-url", diff --git a/src/lib/cli/public-display-defaults.ts b/src/lib/cli/public-display-defaults.ts index 33632c7ef19..626ef47c9a4 100644 --- a/src/lib/cli/public-display-defaults.ts +++ b/src/lib/cli/public-display-defaults.ts @@ -250,6 +250,13 @@ const PUBLIC_DISPLAY_LAYOUT: Record = { flags: "[--workdir ] [--tty|--no-tty] [--timeout ] -- [args...]", }, ], + "sandbox:agent": [ + { + group: "Sandbox Management", + order: 4.55, + flags: "[openclaw-agent-flags...]", + }, + ], "sandbox:upload": [ { group: "Sandbox Management",