From ae141630c850bb97a3ce102749465ab3d24f0fe4 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:02:09 -0700 Subject: [PATCH 01/16] feat(openshell): route session reads over gRPC Signed-off-by: Aaron Erickson --- docs/reference/commands.mdx | 6 +- .../sandbox/sessions/passthrough.test.ts | 148 ++++++++++-------- .../actions/sandbox/sessions/passthrough.ts | 14 +- .../openshell/sandbox-control-routing.test.ts | 111 +++++++++++++ .../openshell/sandbox-control-routing.ts | 60 +++++++ 5 files changed, 266 insertions(+), 73 deletions(-) create mode 100644 src/lib/adapters/openshell/sandbox-control-routing.test.ts create mode 100644 src/lib/adapters/openshell/sandbox-control-routing.ts diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index dd9d9b50cd1..0a43fe93d86 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2195,7 +2195,11 @@ Pass `-f` / `--file ` to point at the manifest; `--yes` confirms th List OpenClaw conversation sessions in the sandbox. With no subcommand the in-sandbox CLI lists stored sessions for the configured default agent. -NemoClaw invokes `openclaw sessions` via `openshell sandbox exec` and forwards OpenClaw flags verbatim, but filters default list output so internal `nemoclaw-onboard-warmup-*` sessions created during onboarding are hidden from user-facing output. +NemoClaw invokes the read-only `openclaw sessions` command through the sandbox's named OpenShell gateway and forwards OpenClaw flags verbatim. +It prefers the direct gRPC sandbox execution API. +If gateway configuration or the gRPC transport fails before NemoClaw receives a command result, it retries this read-only list operation through the OpenShell CLI. +A completed command, including a nonzero result, is never replayed during fallback. +NemoClaw filters default list output so internal `nemoclaw-onboard-warmup-*` sessions created during onboarding are hidden from user-facing output. ```bash $$nemoclaw my-assistant sessions diff --git a/src/lib/actions/sandbox/sessions/passthrough.test.ts b/src/lib/actions/sandbox/sessions/passthrough.test.ts index 127c957c1ea..b59787c6724 100644 --- a/src/lib/actions/sandbox/sessions/passthrough.test.ts +++ b/src/lib/actions/sandbox/sessions/passthrough.test.ts @@ -3,13 +3,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const captureMock = vi.hoisted(() => vi.fn()); +const readOnlyExecMock = vi.hoisted(() => vi.fn()); 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("../../../adapters/openshell/runtime", () => ({ - captureOpenshell: captureMock, +const getSandboxMock = vi.hoisted(() => + vi.fn( + () => + null as { + agent?: string; + gatewayName?: string; + gatewayPort?: number; + } | null, + ), +); + +vi.mock("../../../adapters/openshell/sandbox-control-routing", () => ({ + execSandboxReadOnlyWithGrpcFallback: readOnlyExecMock, })); vi.mock("../exec", async () => { const actual = await vi.importActual("../exec"); @@ -217,7 +226,7 @@ describe("runSessionsPassthrough", () => { let consoleErrorSpy: ReturnType; beforeEach(() => { - captureMock.mockReset(); + readOnlyExecMock.mockReset(); execMock.mockClear(); ensureLiveMock.mockClear(); getSandboxMock.mockReset(); @@ -234,13 +243,14 @@ describe("runSessionsPassthrough", () => { }); it("captures and filters `sessions list --json` instead of streaming warm-up entries", async () => { - captureMock.mockReturnValueOnce({ + readOnlyExecMock.mockResolvedValueOnce({ status: 0, - output: JSON.stringify({ + stdout: JSON.stringify({ count: 1, totalCount: 1, sessions: [{ key: "agent:main:explicit:warm", sessionId: `${WARMUP_SESSION_ID_PREFIX}1` }], }), + stderr: "", }); await runSessionsPassthrough("alpha", { @@ -250,22 +260,11 @@ describe("runSessionsPassthrough", () => { expect(ensureLiveMock).toHaveBeenCalledWith("alpha", { allowNonReadyPhase: true }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - [ - "sandbox", - "exec", - "--name", - "alpha", - "--", - "openclaw", - "sessions", - "list", - "--agent", - "main", - "--json", - ], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw", { + sandboxName: "alpha", + command: ["openclaw", "sessions", "list", "--agent", "main", "--json"], + maxOutputBytes: 64 * 1024 * 1024, + }); expect(JSON.parse(String(stdoutSpy.mock.calls[0]?.[0]))).toEqual({ count: 0, totalCount: 0, @@ -274,40 +273,38 @@ describe("runSessionsPassthrough", () => { }); it("captures and filters text `sessions list` output", async () => { - captureMock.mockReturnValueOnce({ + readOnlyExecMock.mockResolvedValueOnce({ status: 0, stdout: [ "Sessions listed: 1", `direct agent:main:expli... 1m ago model id:${WARMUP_SESSION_ID_PREFIX}1`, ].join("\n"), stderr: "warning: noisy but non-fatal\n", - output: [ - "Sessions listed: 1", - `direct agent:main:expli... 1m ago model id:${WARMUP_SESSION_ID_PREFIX}1`, - ].join("\n"), }); await runSessionsPassthrough("alpha", { verb: "list", extraArgs: ["--agent", "main"] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalled(); + expect(readOnlyExecMock).toHaveBeenCalled(); expect(String(stdoutSpy.mock.calls[0]?.[0])).toBe("Sessions listed: 0\n"); expect(String(stderrSpy.mock.calls[0]?.[0])).toBe("warning: noisy but non-fatal\n"); }); it("also filters the parent `sessions` list shorthand", async () => { - captureMock.mockReturnValueOnce({ + readOnlyExecMock.mockResolvedValueOnce({ status: 0, - output: `Sessions listed: 1\nid:${WARMUP_SESSION_ID_PREFIX}1`, + stdout: `Sessions listed: 1\nid:${WARMUP_SESSION_ID_PREFIX}1`, + stderr: "", }); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw", { + sandboxName: "alpha", + command: ["openclaw", "sessions"], + maxOutputBytes: 64 * 1024 * 1024, + }); expect(String(stdoutSpy.mock.calls[0]?.[0])).toBe("Sessions listed: 0\n"); }); @@ -317,11 +314,12 @@ describe("runSessionsPassthrough", () => { ) => { throw new Error(`process.exit:${code}`); }) as never); - captureMock.mockReturnValueOnce({ + readOnlyExecMock.mockResolvedValueOnce({ status: 0, - output: JSON.stringify({ + stdout: JSON.stringify({ records: [{ sid: `${WARMUP_SESSION_ID_PREFIX}1` }], }), + stderr: "", }); try { @@ -338,9 +336,10 @@ describe("runSessionsPassthrough", () => { it("passes through unrecognised JSON when it cannot leak a warm-up session", async () => { const raw = JSON.stringify({ records: [{ key: "agent:main:main", sessionId: "sid-real" }] }); - captureMock.mockReturnValueOnce({ + readOnlyExecMock.mockResolvedValueOnce({ status: 0, - output: raw, + stdout: raw, + stderr: "", }); await runSessionsPassthrough("alpha", { verb: "list", extraArgs: ["--json"] }); @@ -355,9 +354,8 @@ describe("runSessionsPassthrough", () => { ) => { throw new Error(`process.exit:${code}`); }) as never); - captureMock.mockReturnValueOnce({ + readOnlyExecMock.mockResolvedValueOnce({ status: null, - output: "", stdout: "", stderr: "", error: Object.assign(new Error("spawnSync openshell ENOBUFS"), { code: "ENOBUFS" }), @@ -371,10 +369,10 @@ describe("runSessionsPassthrough", () => { exitSpy.mockRestore(); } - expect(captureMock).toHaveBeenCalledWith(expect.any(Array), { - ignoreError: true, - includeStreams: true, - maxBuffer: 64 * 1024 * 1024, + expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw", { + sandboxName: "alpha", + command: ["openclaw", "sessions", "list", "--all-agents", "--json"], + maxOutputBytes: 64 * 1024 * 1024, }); expect(consoleErrorSpy).toHaveBeenCalledWith( expect.stringContaining("output exceeded NemoClaw's 64 MiB filtering buffer"), @@ -388,21 +386,30 @@ describe("runSessionsPassthrough", () => { await runSessionsPassthrough("hermes", { extraArgs: [] }); - expect(captureMock).not.toHaveBeenCalled(); + expect(readOnlyExecMock).not.toHaveBeenCalled(); expect(execMock).toHaveBeenCalledWith("hermes", ["hermes", "sessions", "list"]); }); it("uses openclaw binary for openclaw-agent sandboxes (#6247)", async () => { - getSandboxMock.mockReturnValue({ agent: "openclaw" }); - captureMock.mockReturnValueOnce({ status: 0, output: "Sessions listed: 0\n" }); + getSandboxMock.mockReturnValue({ + agent: "openclaw", + gatewayName: "nemoclaw-9090", + gatewayPort: 9090, + }); + readOnlyExecMock.mockResolvedValueOnce({ + status: 0, + stdout: "Sessions listed: 0\n", + stderr: "", + }); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw-9090", { + sandboxName: "alpha", + command: ["openclaw", "sessions"], + maxOutputBytes: 64 * 1024 * 1024, + }); }); it("routes hermes `sessions list` with forwarded flags via execSandbox (#6247)", async () => { @@ -413,34 +420,44 @@ describe("runSessionsPassthrough", () => { extraArgs: ["--limit", "5"], }); - expect(captureMock).not.toHaveBeenCalled(); + expect(readOnlyExecMock).not.toHaveBeenCalled(); expect(execMock).toHaveBeenCalledWith("hermes", ["hermes", "sessions", "list", "--limit", "5"]); }); it("defaults to the openclaw binary + filter path when the registry has no entry (#6247)", async () => { getSandboxMock.mockReturnValue(null); - captureMock.mockReturnValueOnce({ status: 0, output: "Sessions listed: 0\n" }); + readOnlyExecMock.mockResolvedValueOnce({ + status: 0, + stdout: "Sessions listed: 0\n", + stderr: "", + }); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw", { + sandboxName: "alpha", + command: ["openclaw", "sessions"], + maxOutputBytes: 64 * 1024 * 1024, + }); }); it("defaults to the openclaw binary for an unknown agent value (#6247)", async () => { getSandboxMock.mockReturnValue({ agent: "custom-future-agent" }); - captureMock.mockReturnValueOnce({ status: 0, output: "Sessions listed: 0\n" }); + readOnlyExecMock.mockResolvedValueOnce({ + status: 0, + stdout: "Sessions listed: 0\n", + stderr: "", + }); await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(captureMock).toHaveBeenCalledWith( - ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions"], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 * 1024 }, - ); + expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw", { + sandboxName: "alpha", + command: ["openclaw", "sessions"], + maxOutputBytes: 64 * 1024 * 1024, + }); }); it("prints captured output when OpenClaw exits non-zero", async () => { @@ -449,9 +466,8 @@ describe("runSessionsPassthrough", () => { ) => { throw new Error(`process.exit:${code}`); }) as never); - captureMock.mockReturnValueOnce({ + readOnlyExecMock.mockResolvedValueOnce({ status: 2, - output: "", stdout: "", stderr: "unknown flag: --bad\n", }); diff --git a/src/lib/actions/sandbox/sessions/passthrough.ts b/src/lib/actions/sandbox/sessions/passthrough.ts index 36f4ee5935f..a48545dee02 100644 --- a/src/lib/actions/sandbox/sessions/passthrough.ts +++ b/src/lib/actions/sandbox/sessions/passthrough.ts @@ -1,8 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { openShellSandboxControl } from "../../../adapters/openshell/sandbox-control"; +import { execSandboxReadOnlyWithGrpcFallback } from "../../../adapters/openshell/sandbox-control-routing"; import { CLI_NAME } from "../../../cli/branding"; +import { resolveSandboxGatewayName } from "../../../onboard/gateway-binding"; import * as registry from "../../../state/registry"; import { computeExitCode, execSandbox } from "../exec"; import { ensureLiveSandboxOrExit } from "../gateway-state"; @@ -36,11 +37,11 @@ export function printSessionsPassthroughHelp(verb?: SessionsPassthroughVerb): vo console.log( ` Pass-through to the sandbox agent's \`sessions${usageSuffix} ...\` command inside the sandbox`, ); - console.log(" via `openshell sandbox exec` — `openclaw sessions ...` for OpenClaw sandboxes,"); + console.log(" via OpenShell's supported sandbox execution API — `openclaw sessions ...` for"); console.log( - ` \`hermes sessions${hermesUsageSuffix} ...\` for Hermes sandboxes; the in-sandbox binary is picked`, + ` OpenClaw sandboxes, \`hermes sessions${hermesUsageSuffix} ...\` for Hermes sandboxes; the`, ); - console.log(" from the sandbox's agent."); + console.log(" in-sandbox binary is picked from the sandbox's agent."); console.log( " On OpenClaw sandboxes, internal NemoClaw onboard warm-up sessions are hidden from default", ); @@ -223,14 +224,15 @@ export async function runSessionsPassthrough( // `~/.nemoclaw/sandboxes.json` registry (`REGISTRY_FILE`). Sandbox processes // cannot access the host filesystem to change this agent selection; unknown // or missing values deliberately default to `openclaw` below. - const sandboxAgent = registry.getSandbox(sandboxName)?.agent; + const sandbox = registry.getSandbox(sandboxName); + const sandboxAgent = sandbox?.agent; const inSandboxBinary = sandboxAgent === "hermes" ? "hermes" : "openclaw"; const command = [inSandboxBinary, "sessions"]; if (verb) command.push(verb); else if (inSandboxBinary === "hermes") command.push("list"); for (const arg of extraArgs) command.push(arg); if (isFilterableListPassthrough(verb) && inSandboxBinary === "openclaw") { - const result = await openShellSandboxControl.exec({ + const result = await execSandboxReadOnlyWithGrpcFallback(resolveSandboxGatewayName(sandbox), { sandboxName, command, maxOutputBytes: SESSIONS_LIST_CAPTURE_MAX_BUFFER_BYTES, diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts new file mode 100644 index 00000000000..d4f87339854 --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import type { GrpcOpenShellSandboxControl } from "./grpc-sandbox-control"; +import type { OpenShellSandboxControl, SandboxExecResult } from "./sandbox-control"; +import { execSandboxReadOnlyWithGrpcFallback } from "./sandbox-control-routing"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; + +function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: SandboxExecResult) { + const close = vi.fn(); + const grpcExec = vi.fn(async () => { + if (grpcResult instanceof Error) throw grpcResult; + return grpcResult; + }); + const grpc: GrpcOpenShellSandboxControl = { close, exec: grpcExec }; + const cliExec = vi.fn(async () => cliResult ?? { status: 0, stdout: "cli", stderr: "" }); + const cli: OpenShellSandboxControl = { exec: cliExec }; + const createGrpc = vi.fn(() => grpc); + const debug = vi.fn(); + return { close, grpcExec, cliExec, createGrpc, debug, deps: { cli, createGrpc, debug } }; +} + +const request = { + sandboxName: "alpha", + command: ["openclaw", "sessions", "list"] as const, + maxOutputBytes: 4096, +}; + +describe("read-only OpenShell sandbox control routing", () => { + it("uses direct gRPC with a bounded deadline", async () => { + const test = dependencies({ status: 0, stdout: "grpc", stderr: "" }); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw-9090", request, test.deps), + ).resolves.toEqual({ status: 0, stdout: "grpc", stderr: "" }); + + expect(test.createGrpc).toHaveBeenCalledWith("nemoclaw-9090"); + expect(test.grpcExec).toHaveBeenCalledWith({ + ...request, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + expect(test.cliExec).not.toHaveBeenCalled(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("does not replay a completed non-zero command through the CLI", async () => { + const result = { status: 2, stdout: "", stderr: "unknown flag" }; + const test = dependencies(result); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", request, test.deps), + ).resolves.toEqual(result); + + expect(test.cliExec).not.toHaveBeenCalled(); + }); + + it("retries a gRPC transport failure through the CLI without forwarding its deadline", async () => { + const grpcError = new Error("UNAVAILABLE"); + const cliResult = { status: 0, stdout: "cli", stderr: "" }; + const test = dependencies( + { status: null, stdout: "partial", stderr: "", error: grpcError }, + cliResult, + ); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", request, test.deps), + ).resolves.toEqual(cliResult); + + expect(test.cliExec).toHaveBeenCalledWith(request); + expect(test.debug).toHaveBeenCalledWith(expect.stringContaining("gRPC read failed"), grpcError); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("uses the CLI when gateway configuration cannot create a gRPC client", async () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + const error = new Error("edge tunnel required"); + test.createGrpc.mockImplementation(() => { + throw error; + }); + + await expect(execSandboxReadOnlyWithGrpcFallback("edge", request, test.deps)).resolves.toEqual({ + status: 0, + stdout: "cli", + stderr: "", + }); + + expect(test.grpcExec).not.toHaveBeenCalled(); + expect(test.cliExec).toHaveBeenCalledWith(request); + expect(test.debug).toHaveBeenCalledWith(expect.stringContaining("configuration failed"), error); + }); + + it("does not let close failures replace a successful result", async () => { + const test = dependencies({ status: 0, stdout: "grpc", stderr: "" }); + const closeError = new Error("close failed"); + test.close.mockImplementation(() => { + throw closeError; + }); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", { ...request, timeoutMs: 0 }, test.deps), + ).resolves.toEqual({ status: 0, stdout: "grpc", stderr: "" }); + + expect(test.grpcExec).toHaveBeenCalledWith({ ...request, timeoutMs: 0 }); + expect(test.debug).toHaveBeenCalledWith( + "OpenShell direct gRPC client close failed", + closeError, + ); + }); +}); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts new file mode 100644 index 00000000000..f170bb100a6 --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { log } from "../../cli/logger"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; +import { createGrpcOpenShellSandboxControlForGateway } from "./grpc-gateway-config"; +import { + createCliOpenShellSandboxControl, + type OpenShellSandboxControl, + type SandboxExecRequest, + type SandboxExecResult, +} from "./sandbox-control"; +import type { GrpcOpenShellSandboxControl } from "./grpc-sandbox-control"; + +export interface ReadOnlyRoutingDependencies { + cli: OpenShellSandboxControl; + createGrpc: (gatewayName: string) => GrpcOpenShellSandboxControl; + debug: (message: string, context: unknown) => void; +} + +const defaultDependencies: ReadOnlyRoutingDependencies = { + cli: createCliOpenShellSandboxControl(), + createGrpc: createGrpcOpenShellSandboxControlForGateway, + debug: (message, context) => log.debug(message, context), +}; + +/** + * Prefer direct gRPC for a read-only sandbox exec and retry through the + * OpenShell CLI when gateway resolution or transport fails. This retry policy + * is intentionally restricted to read-only commands: a failed mutation may + * have committed remotely and must never be replayed automatically. + */ +export async function execSandboxReadOnlyWithGrpcFallback( + gatewayName: string, + request: SandboxExecRequest, + dependencies: ReadOnlyRoutingDependencies = defaultDependencies, +): Promise { + let grpc: GrpcOpenShellSandboxControl | undefined; + try { + grpc = dependencies.createGrpc(gatewayName); + const result = await grpc.exec({ + ...request, + timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, + }); + if (!result.error) return result; + dependencies.debug("OpenShell direct gRPC read failed; retrying through the CLI", result.error); + } catch (error) { + dependencies.debug( + "OpenShell direct gRPC configuration failed; retrying through the CLI", + error, + ); + } finally { + try { + grpc?.close(); + } catch (error) { + dependencies.debug("OpenShell direct gRPC client close failed", error); + } + } + return dependencies.cli.exec(request); +} From 9b76662c172a1be40da03e035d6c5ba2398d3364 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 13:56:12 -0700 Subject: [PATCH 02/16] feat(openshell): resolve gRPC gateway credentials Signed-off-by: Aaron Erickson --- .../openshell/grpc-gateway-config.test.ts | 263 ++++++++++++++++++ .../adapters/openshell/grpc-gateway-config.ts | 259 +++++++++++++++++ .../openshell/grpc-sandbox-control.ts | 12 +- 3 files changed, 530 insertions(+), 4 deletions(-) create mode 100644 src/lib/adapters/openshell/grpc-gateway-config.test.ts create mode 100644 src/lib/adapters/openshell/grpc-gateway-config.ts diff --git a/src/lib/adapters/openshell/grpc-gateway-config.test.ts b/src/lib/adapters/openshell/grpc-gateway-config.test.ts new file mode 100644 index 00000000000..6c91d82531b --- /dev/null +++ b/src/lib/adapters/openshell/grpc-gateway-config.test.ts @@ -0,0 +1,263 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { + createGrpcOpenShellSandboxControlForGateway, + resolveOpenShellGrpcGateway, +} from "./grpc-gateway-config"; + +const roots: string[] = []; + +afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { force: true, recursive: true }); +}); + +function fixture(): { root: string; xdg: string; system: string } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-grpc-gateway-")); + roots.push(root); + return { root, xdg: path.join(root, "xdg"), system: path.join(root, "system") }; +} + +function writeMetadata( + configRoot: string, + gatewayName: string, + metadata: Record, +): string { + const target = path.join(configRoot, "gateways", gatewayName, "metadata.json"); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, JSON.stringify({ name: gatewayName, ...metadata })); + return target; +} + +function writeMtls(xdg: string, gatewayName: string): void { + const target = path.join(xdg, "openshell", "gateways", gatewayName, "mtls"); + fs.mkdirSync(target, { recursive: true }); + fs.writeFileSync(path.join(target, "ca.crt"), "ca-pem"); + fs.writeFileSync(path.join(target, "tls.crt"), "cert-pem"); + fs.writeFileSync(path.join(target, "tls.key"), "key-pem"); +} + +describe("OpenShell gRPC gateway configuration", () => { + it("resolves user metadata and per-user mTLS materials", () => { + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "nemoclaw", { + gateway_endpoint: "https://127.0.0.1:8080", + auth_mode: "mtls", + }); + writeMtls(dirs.xdg, "nemoclaw"); + + const resolved = resolveOpenShellGrpcGateway("nemoclaw", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + }); + + expect(resolved).toEqual({ + gatewayName: "nemoclaw", + metadataSource: "user", + authMode: "mtls", + clientConfig: { + endpoint: "https://127.0.0.1:8080", + caCertificate: Buffer.from("ca-pem"), + clientCertificate: Buffer.from("cert-pem"), + clientKey: Buffer.from("key-pem"), + }, + }); + }); + + it("falls back to system metadata while keeping credentials in the user gateway directory", () => { + const dirs = fixture(); + writeMetadata(dirs.system, "nemoclaw", { + gateway_endpoint: "https://localhost:8080", + auth_mode: "mtls", + }); + writeMtls(dirs.xdg, "nemoclaw"); + + const resolved = resolveOpenShellGrpcGateway("nemoclaw", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + }); + + expect(resolved.metadataSource).toBe("system"); + expect(resolved.clientConfig.clientKey?.toString()).toBe("key-pem"); + }); + + it("lets a user metadata entry shadow system metadata even when malformed", () => { + const dirs = fixture(); + const userPath = writeMetadata(path.join(dirs.xdg, "openshell"), "nemoclaw", { + gateway_endpoint: "http://127.0.0.1:8080", + }); + fs.writeFileSync(userPath, "not-json"); + writeMetadata(dirs.system, "nemoclaw", { + gateway_endpoint: "http://127.0.0.1:9090", + auth_mode: "plaintext", + }); + + expect(() => + resolveOpenShellGrpcGateway("nemoclaw", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + }), + ).toThrow(`Failed to parse OpenShell gateway metadata from ${userPath}`); + }); + + it("infers plaintext for legacy HTTP metadata and constructs a direct client", () => { + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "nemoclaw", { + gateway_endpoint: "http://127.0.0.1:1", + }); + const options = { xdgConfigHome: dirs.xdg, systemConfigRoot: dirs.system }; + + expect(resolveOpenShellGrpcGateway("nemoclaw", options)).toMatchObject({ + authMode: "plaintext", + clientConfig: { endpoint: "http://127.0.0.1:1" }, + }); + const control = createGrpcOpenShellSandboxControlForGateway("nemoclaw", options); + control.close(); + }); + + it("loads an unexpired OIDC token and optional private CA", () => { + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "cloud", { + gateway_endpoint: "https://gateway.example:443", + auth_mode: "oidc", + }); + const gatewayDir = path.join(dirs.xdg, "openshell", "gateways", "cloud"); + fs.writeFileSync( + path.join(gatewayDir, "oidc_token.json"), + JSON.stringify({ access_token: "oidc-token", expires_at: 2000 }), + ); + fs.mkdirSync(path.join(gatewayDir, "mtls")); + fs.writeFileSync(path.join(gatewayDir, "mtls", "ca.crt"), "private-ca"); + + const resolved = resolveOpenShellGrpcGateway("cloud", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + nowSeconds: 1000, + }); + + expect(resolved.authMode).toBe("oidc"); + expect(resolved.clientConfig).toEqual({ + endpoint: "https://gateway.example:443", + bearerToken: "oidc-token", + caCertificate: Buffer.from("private-ca"), + }); + }); + + it("rejects OIDC tokens that need refresh", () => { + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "cloud", { + gateway_endpoint: "https://gateway.example:443", + auth_mode: "oidc", + }); + fs.writeFileSync( + path.join(dirs.xdg, "openshell", "gateways", "cloud", "oidc_token.json"), + JSON.stringify({ access_token: "expired", expires_at: 1020 }), + ); + + expect(() => + resolveOpenShellGrpcGateway("cloud", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + nowSeconds: 1000, + }), + ).toThrow("expired or near expiry"); + }); + + it("fails closed for edge-tunneled and unknown auth modes", () => { + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "edge", { + gateway_endpoint: "https://edge.example:443", + auth_mode: "cloudflare_jwt", + }); + writeMetadata(path.join(dirs.xdg, "openshell"), "unknown", { + gateway_endpoint: "https://unknown.example:443", + auth_mode: "future-auth", + }); + const options = { xdgConfigHome: dirs.xdg, systemConfigRoot: dirs.system }; + + expect(() => resolveOpenShellGrpcGateway("edge", options)).toThrow( + "require the OpenShell edge tunnel", + ); + expect(() => resolveOpenShellGrpcGateway("unknown", options)).toThrow( + "Unsupported OpenShell gateway auth mode 'future-auth'", + ); + }); + + it.each([ + ["plaintext", "https://gateway.example:443", "plaintext gateway metadata"], + ["mtls", "http://127.0.0.1:8080", "mTLS gateway metadata"], + ["oidc", "http://127.0.0.1:8080", "OIDC gateway metadata"], + ])("rejects %s metadata with an incompatible endpoint", (authMode, endpoint, message) => { + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "mismatch", { + gateway_endpoint: endpoint, + auth_mode: authMode, + }); + + expect(() => + resolveOpenShellGrpcGateway("mismatch", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + }), + ).toThrow(message); + }); + + it("rejects relative configuration roots and invalid clocks", () => { + expect(() => + resolveOpenShellGrpcGateway("nemoclaw", { xdgConfigHome: "relative/config" }), + ).toThrow("must be an absolute path"); + + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "nemoclaw", { + gateway_endpoint: "http://127.0.0.1:8080", + auth_mode: "plaintext", + }); + expect(() => + resolveOpenShellGrpcGateway("nemoclaw", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + nowSeconds: Number.NaN, + }), + ).toThrow("nowSeconds must be a non-negative safe integer"); + }); + + it("rejects unsafe names and metadata name mismatches", () => { + const dirs = fixture(); + const metadataPath = writeMetadata(path.join(dirs.xdg, "openshell"), "nemoclaw", { + gateway_endpoint: "http://127.0.0.1:8080", + auth_mode: "plaintext", + }); + fs.writeFileSync( + metadataPath, + JSON.stringify({ + name: "other", + gateway_endpoint: "http://127.0.0.1:8080", + auth_mode: "plaintext", + }), + ); + const options = { xdgConfigHome: dirs.xdg, systemConfigRoot: dirs.system }; + + expect(() => resolveOpenShellGrpcGateway("../escape", options)).toThrow("one path component"); + expect(() => resolveOpenShellGrpcGateway("nemoclaw", options)).toThrow("name mismatch"); + }); + + it("reports the exact missing mTLS material", () => { + const dirs = fixture(); + writeMetadata(path.join(dirs.xdg, "openshell"), "nemoclaw", { + gateway_endpoint: "https://127.0.0.1:8080", + auth_mode: "mtls", + }); + + expect(() => + resolveOpenShellGrpcGateway("nemoclaw", { + xdgConfigHome: dirs.xdg, + systemConfigRoot: dirs.system, + }), + ).toThrow(path.join("nemoclaw", "mtls", "ca.crt")); + }); +}); diff --git a/src/lib/adapters/openshell/grpc-gateway-config.ts b/src/lib/adapters/openshell/grpc-gateway-config.ts new file mode 100644 index 00000000000..ace3611bf52 --- /dev/null +++ b/src/lib/adapters/openshell/grpc-gateway-config.ts @@ -0,0 +1,259 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { + createGrpcOpenShellSandboxControl, + type GrpcOpenShellSandboxControl, + type OpenShellGrpcClientConfig, + validateOpenShellGrpcClientConfig, +} from "./grpc-sandbox-control"; + +interface GatewayMetadata { + name: string; + gateway_endpoint: string; + auth_mode?: string | null; +} + +interface OidcTokenBundle { + access_token: string; + expires_at?: number | null; +} + +export interface OpenShellGrpcGatewayResolverOptions { + env?: NodeJS.ProcessEnv; + homeDir?: string; + nowSeconds?: number; + systemConfigRoot?: string; + xdgConfigHome?: string; +} + +export interface ResolvedOpenShellGrpcGateway { + gatewayName: string; + metadataSource: "user" | "system"; + authMode: "plaintext" | "mtls" | "oidc"; + clientConfig: OpenShellGrpcClientConfig; +} + +function validateGatewayName(name: string): void { + if ( + !name || + name === "." || + name === ".." || + name.includes("/") || + name.includes("\\") || + name.includes("\0") + ) { + throw new Error(`Invalid OpenShell gateway name '${name}': expected one path component`); + } +} + +function configRoots(options: OpenShellGrpcGatewayResolverOptions): { + user: string; + system: string; +} { + const env = options.env ?? process.env; + const xdgConfigHome = options.xdgConfigHome ?? env.XDG_CONFIG_HOME; + const user = xdgConfigHome ?? path.join(options.homeDir ?? os.homedir(), ".config"); + if (!path.isAbsolute(user)) { + throw new Error("OpenShell XDG config home must be an absolute path"); + } + const systemOverride = options.systemConfigRoot ?? env.OPENSHELL_SYSTEM_GATEWAY_DIR; + const system = + systemOverride && path.isAbsolute(systemOverride) ? systemOverride : "/etc/openshell"; + return { user: path.join(user, "openshell"), system }; +} + +function readJson(pathname: string, label: string): unknown { + let source: string; + try { + source = fs.readFileSync(pathname, "utf8"); + } catch (error) { + throw new Error(`Failed to read ${label} from ${pathname}: ${(error as Error).message}`); + } + try { + return JSON.parse(source); + } catch (error) { + throw new Error(`Failed to parse ${label} from ${pathname}: ${(error as Error).message}`); + } +} + +function pathExists(pathname: string): boolean { + try { + fs.lstatSync(pathname); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw new Error(`Failed to inspect OpenShell path ${pathname}: ${(error as Error).message}`); + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function metadataAt(pathname: string, gatewayName: string): GatewayMetadata { + const value = readJson(pathname, "OpenShell gateway metadata"); + if (!isRecord(value)) throw new Error(`Invalid OpenShell gateway metadata in ${pathname}`); + if (value.name !== gatewayName) { + throw new Error( + `OpenShell gateway metadata name mismatch in ${pathname}: expected '${gatewayName}'`, + ); + } + if (typeof value.gateway_endpoint !== "string" || !value.gateway_endpoint) { + throw new Error(`OpenShell gateway metadata in ${pathname} has no gateway_endpoint`); + } + if ( + value.auth_mode !== undefined && + value.auth_mode !== null && + typeof value.auth_mode !== "string" + ) { + throw new Error(`OpenShell gateway metadata in ${pathname} has an invalid auth_mode`); + } + return value as unknown as GatewayMetadata; +} + +function resolveMetadata( + gatewayName: string, + roots: { user: string; system: string }, +): { metadata: GatewayMetadata; source: "user" | "system" } { + const userPath = path.join(roots.user, "gateways", gatewayName, "metadata.json"); + if (pathExists(userPath)) { + return { metadata: metadataAt(userPath, gatewayName), source: "user" }; + } + const systemPath = path.join(roots.system, "gateways", gatewayName, "metadata.json"); + if (pathExists(systemPath)) { + return { metadata: metadataAt(systemPath, gatewayName), source: "system" }; + } + throw new Error( + `No OpenShell metadata found for gateway '${gatewayName}' (looked in ${userPath} and ${systemPath})`, + ); +} + +function readRequired(pathname: string, label: string): Buffer { + let value: Buffer; + try { + value = fs.readFileSync(pathname); + } catch (error) { + throw new Error(`Failed to read ${label} from ${pathname}: ${(error as Error).message}`); + } + if (value.length === 0) throw new Error(`${label} is empty at ${pathname}`); + return value; +} + +function mtlsConfig(endpoint: string, mtlsDir: string): OpenShellGrpcClientConfig { + return { + endpoint, + caCertificate: readRequired(path.join(mtlsDir, "ca.crt"), "OpenShell TLS CA"), + clientCertificate: readRequired( + path.join(mtlsDir, "tls.crt"), + "OpenShell TLS client certificate", + ), + clientKey: readRequired(path.join(mtlsDir, "tls.key"), "OpenShell TLS client key"), + }; +} + +function oidcConfig( + endpoint: string, + gatewayDir: string, + nowSeconds: number, +): OpenShellGrpcClientConfig { + const tokenPath = path.join(gatewayDir, "oidc_token.json"); + const value = readJson(tokenPath, "OpenShell OIDC token"); + if (!isRecord(value) || typeof value.access_token !== "string" || !value.access_token) { + throw new Error(`OpenShell OIDC token in ${tokenPath} has no access_token`); + } + if ( + value.expires_at !== undefined && + value.expires_at !== null && + (!Number.isSafeInteger(value.expires_at) || Number(value.expires_at) < 0) + ) { + throw new Error(`OpenShell OIDC token in ${tokenPath} has an invalid expires_at`); + } + const token = value as unknown as OidcTokenBundle; + if ( + token.expires_at !== undefined && + token.expires_at !== null && + nowSeconds + 30 >= token.expires_at + ) { + throw new Error( + `OpenShell OIDC token for this gateway is expired or near expiry; refresh it with the OpenShell CLI`, + ); + } + + const config: OpenShellGrpcClientConfig = { endpoint, bearerToken: token.access_token }; + const mtlsDir = path.join(gatewayDir, "mtls"); + const caPath = path.join(mtlsDir, "ca.crt"); + const certPath = path.join(mtlsDir, "tls.crt"); + const keyPath = path.join(mtlsDir, "tls.key"); + const hasCa = pathExists(caPath); + if (hasCa) config.caCertificate = readRequired(caPath, "OpenShell TLS CA"); + if (hasCa && pathExists(certPath) && pathExists(keyPath)) { + config.clientCertificate = readRequired(certPath, "OpenShell TLS client certificate"); + config.clientKey = readRequired(keyPath, "OpenShell TLS client key"); + } + return config; +} + +function effectiveAuthMode(metadata: GatewayMetadata): string { + if (metadata.auth_mode) return metadata.auth_mode; + return metadata.gateway_endpoint.startsWith("http://") ? "plaintext" : "mtls"; +} + +export function resolveOpenShellGrpcGateway( + gatewayName: string, + options: OpenShellGrpcGatewayResolverOptions = {}, +): ResolvedOpenShellGrpcGateway { + validateGatewayName(gatewayName); + const roots = configRoots(options); + const { metadata, source } = resolveMetadata(gatewayName, roots); + const authMode = effectiveAuthMode(metadata); + const gatewayDir = path.join(roots.user, "gateways", gatewayName); + const nowSeconds = options.nowSeconds ?? Math.floor(Date.now() / 1000); + if (!Number.isSafeInteger(nowSeconds) || nowSeconds < 0) { + throw new Error("OpenShell gateway resolver nowSeconds must be a non-negative safe integer"); + } + + let clientConfig: OpenShellGrpcClientConfig; + if (authMode === "plaintext") { + if (!metadata.gateway_endpoint.startsWith("http://")) { + throw new Error("OpenShell plaintext gateway metadata must use an http:// endpoint"); + } + clientConfig = { endpoint: metadata.gateway_endpoint }; + } else if (authMode === "mtls") { + if (!metadata.gateway_endpoint.startsWith("https://")) { + throw new Error("OpenShell mTLS gateway metadata must use an https:// endpoint"); + } + clientConfig = mtlsConfig(metadata.gateway_endpoint, path.join(gatewayDir, "mtls")); + } else if (authMode === "oidc") { + if (!metadata.gateway_endpoint.startsWith("https://")) { + throw new Error("OpenShell OIDC gateway metadata must use an https:// endpoint"); + } + clientConfig = oidcConfig(metadata.gateway_endpoint, gatewayDir, nowSeconds); + } else if (authMode === "cloudflare_jwt") { + throw new Error( + "OpenShell Cloudflare JWT gateways require the OpenShell edge tunnel and are not supported by the direct gRPC client", + ); + } else { + throw new Error(`Unsupported OpenShell gateway auth mode '${authMode}'`); + } + validateOpenShellGrpcClientConfig(clientConfig); + + return { + gatewayName, + metadataSource: source, + authMode: authMode as ResolvedOpenShellGrpcGateway["authMode"], + clientConfig, + }; +} + +export function createGrpcOpenShellSandboxControlForGateway( + gatewayName: string, + options: OpenShellGrpcGatewayResolverOptions = {}, +): GrpcOpenShellSandboxControl { + const resolved = resolveOpenShellGrpcGateway(gatewayName, options); + return createGrpcOpenShellSandboxControl(resolved.clientConfig); +} diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index 63addd72717..e37e6fe1da6 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -125,6 +125,12 @@ function validateTlsMaterial(config: OpenShellGrpcClientConfig, secure: boolean) } } +export function validateOpenShellGrpcClientConfig(config: OpenShellGrpcClientConfig): void { + const { secure } = parseEndpoint(config.endpoint); + validateBearerToken(config.bearerToken, secure); + validateTlsMaterial(config, secure); +} + function createChannelCredentials( config: OpenShellGrpcClientConfig, secure: boolean, @@ -148,8 +154,8 @@ function protocolPath(): string { } export function createOpenShellGrpcApi(config: OpenShellGrpcClientConfig): OpenShellGrpcApi { + validateOpenShellGrpcClientConfig(config); const { target, secure } = parseEndpoint(config.endpoint); - validateBearerToken(config.bearerToken, secure); const credentials = createChannelCredentials(config, secure); const protoFile = protocolPath(); const packageDefinition = protoLoader.loadSync(protoFile, { @@ -268,9 +274,7 @@ export function createGrpcOpenShellSandboxControl( config: OpenShellGrpcClientConfig, injectedClient?: OpenShellGrpcApi, ): GrpcOpenShellSandboxControl { - const { secure } = parseEndpoint(config.endpoint); - validateBearerToken(config.bearerToken, secure); - validateTlsMaterial(config, secure); + validateOpenShellGrpcClientConfig(config); const client = injectedClient ?? createOpenShellGrpcApi(config); return { close: () => client.close(), From 90aadd5441e55c05337b99372a53b7ac7b62370a Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:06:09 -0700 Subject: [PATCH 03/16] feat(openshell): carry sandbox stdin over gRPC Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/client.test.ts | 18 ++++++++++++++++++ src/lib/adapters/openshell/client.ts | 6 ++++-- .../openshell/grpc-sandbox-control.test.ts | 12 +++++++++--- .../adapters/openshell/grpc-sandbox-control.ts | 14 ++++++++++++-- src/lib/adapters/openshell/runtime.ts | 3 ++- .../adapters/openshell/sandbox-control.test.ts | 9 ++++++++- src/lib/adapters/openshell/sandbox-control.ts | 3 +++ 7 files changed, 56 insertions(+), 9 deletions(-) diff --git a/src/lib/adapters/openshell/client.test.ts b/src/lib/adapters/openshell/client.test.ts index d3e31e3e7bf..2941879dd00 100644 --- a/src/lib/adapters/openshell/client.test.ts +++ b/src/lib/adapters/openshell/client.test.ts @@ -251,6 +251,24 @@ describe("openshell helpers", () => { }); }); + it("pipes binary stdin through captured OpenShell commands", () => { + const stdin = Buffer.from([0, 255, 10]); + let observedStdio: unknown; + let observedInput: unknown; + const result = captureOpenshellCommand("openshell", ["sandbox", "exec"], { + input: stdin, + spawnSyncImpl: (_command, _args, options) => { + observedStdio = options.stdio; + observedInput = options.input; + return makeSpawnResult({ status: 0, stdout: "ok\n", stderr: "" }); + }, + }); + + expect(observedStdio).toEqual(["pipe", "pipe", "pipe"]); + expect(observedInput).toBe(stdin); + expect(result).toEqual({ status: 0, output: "ok" }); + }); + it("verifies sandbox existence before requesting SSH config", () => { const calls: string[][] = []; const spawnSyncImpl: OpenshellSpawnSync = (_command, args) => { diff --git a/src/lib/adapters/openshell/client.ts b/src/lib/adapters/openshell/client.ts index 39b3c5b6355..621313e4386 100644 --- a/src/lib/adapters/openshell/client.ts +++ b/src/lib/adapters/openshell/client.ts @@ -42,12 +42,13 @@ function openshellSpawnEnv(opts: OpenshellSpawnOptions): NodeJS.ProcessEnv { export interface RunOpenshellOptions extends OpenshellSpawnOptions { stdio?: SpawnSyncOptions["stdio"]; - input?: string; + input?: string | Buffer; } export interface CaptureOpenshellOptions extends OpenshellSpawnOptions { includeStderr?: boolean; includeStreams?: boolean; + input?: string | Buffer; maxBuffer?: number; } @@ -212,7 +213,8 @@ export function captureOpenshellCommand( cwd: opts.cwd, env: openshellSpawnEnv(opts), encoding: "utf-8", - stdio: ["ignore", "pipe", "pipe"], + stdio: [opts.input === undefined ? "ignore" : "pipe", "pipe", "pipe"], + input: opts.input, timeout: opts.timeout, maxBuffer: opts.maxBuffer, }); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 8d528f667a1..8792c12749a 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -129,6 +129,7 @@ describe("gRPC OpenShell sandbox control", () => { control.exec({ sandboxName: "alpha", command: ["sh", "-lc", "echo hello"], + stdin: "request body", }), ).resolves.toEqual({ status: 7, @@ -140,6 +141,7 @@ describe("gRPC OpenShell sandbox control", () => { expect((fake.stream as FakeStream & { request: unknown }).request).toEqual({ sandboxId: "sb-id", command: ["sh", "-lc", "echo hello"], + stdin: Buffer.from("request body"), }); control.close(); expect(fake.close).toHaveBeenCalledOnce(); @@ -172,7 +174,7 @@ describe("gRPC OpenShell sandbox control", () => { }, execSandbox( call: ServerWritableStream< - { sandboxId: string; command: string[] }, + { sandboxId: string; command: string[]; stdin?: Buffer }, { stdout?: { data: Buffer }; stderr?: { data: Buffer }; @@ -193,7 +195,11 @@ describe("gRPC OpenShell sandbox control", () => { }); try { await expect( - control.exec({ sandboxName: "alpha", command: ["printf", "wire"] }), + control.exec({ + sandboxName: "alpha", + command: ["cat"], + stdin: Buffer.from([0, 255, 10]), + }), ).resolves.toEqual({ status: 0, stdout: "wire stdout", @@ -201,7 +207,7 @@ describe("gRPC OpenShell sandbox control", () => { }); expect(requests).toEqual([ { name: "alpha" }, - { sandboxId: "wire-id", command: ["printf", "wire"] }, + { sandboxId: "wire-id", command: ["cat"], stdin: Buffer.from([0, 255, 10]) }, ]); } finally { control.close(); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index e37e6fe1da6..de0b0fd80af 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -39,7 +39,12 @@ export interface OpenShellGrpcApi { callback: (error: grpc.ServiceError | null, response?: GetSandboxResponse) => void, ): unknown; execSandbox( - request: { sandboxId: string; command: readonly string[]; timeoutSeconds?: number }, + request: { + sandboxId: string; + command: readonly string[]; + stdin?: Buffer; + timeoutSeconds?: number; + }, metadata: grpc.Metadata, options: grpc.CallOptions, ): ExecEventStream; @@ -217,7 +222,12 @@ function execute( const timeoutSeconds = request.timeoutMs && request.timeoutMs > 0 ? Math.ceil(request.timeoutMs / 1000) : undefined; const stream = client.execSandbox( - { sandboxId: id, command: request.command, timeoutSeconds }, + { + sandboxId: id, + command: request.command, + stdin: request.stdin === undefined ? undefined : Buffer.from(request.stdin), + timeoutSeconds, + }, metadata, options, ); diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index 178159b13f8..c269fb48208 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -20,7 +20,7 @@ type RunnerOptions = { env?: NodeJS.ProcessEnv; replaceEnv?: boolean; stdio?: StdioOptions; - input?: string; + input?: string | Buffer; ignoreError?: boolean; includeStderr?: boolean; includeStreams?: boolean; @@ -70,6 +70,7 @@ export function captureOpenshell(args: CommandArgs, opts: RunnerOptions = {}) { ignoreError: opts.ignoreError, includeStderr: opts.includeStderr, includeStreams: opts.includeStreams, + input: opts.input, timeout: opts.timeout, maxBuffer: opts.maxBuffer, errorLine: console.error, diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index d2403a22216..d016d39d699 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -21,13 +21,20 @@ describe("CLI OpenShell sandbox control", () => { const result = await control.exec({ sandboxName: "alpha", command: ["openclaw", "sessions", "list", "--json"], + stdin: Buffer.from("request body"), maxOutputBytes: 4096, timeoutMs: 30_000, }); expect(capture).toHaveBeenCalledWith( ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions", "list", "--json"], - { ignoreError: true, includeStreams: true, maxBuffer: 4096, timeout: 30_000 }, + { + ignoreError: true, + includeStreams: true, + input: Buffer.from("request body"), + maxBuffer: 4096, + timeout: 30_000, + }, ); expect(result).toEqual({ status: 0, diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index e0baa204a91..35cae636812 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -7,6 +7,8 @@ import { captureOpenshell } from "./runtime"; export interface SandboxExecRequest { sandboxName: string; command: readonly string[]; + /** Optional bytes supplied to the remote command's standard input. */ + stdin?: string | Buffer; /** Maximum combined stdout and stderr bytes retained by the transport. */ maxOutputBytes?: number; /** End-to-end lookup and execution deadline. Zero means no deadline. */ @@ -48,6 +50,7 @@ export function createCliOpenShellSandboxControl( { ignoreError: true, includeStreams: true, + input: request.stdin, maxBuffer: request.maxOutputBytes, timeout: request.timeoutMs, }, From 363dd800de23bd4dd8a2242be594196c76dcf3ac Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:00:51 -0700 Subject: [PATCH 04/16] test(openshell): keep routing fixture linear Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/sandbox-control-routing.test.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index d4f87339854..5a629f842d4 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -10,10 +10,9 @@ import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: SandboxExecResult) { const close = vi.fn(); - const grpcExec = vi.fn(async () => { - if (grpcResult instanceof Error) throw grpcResult; - return grpcResult; - }); + const grpcExec = vi.fn(() => + grpcResult instanceof Error ? Promise.reject(grpcResult) : Promise.resolve(grpcResult), + ); const grpc: GrpcOpenShellSandboxControl = { close, exec: grpcExec }; const cliExec = vi.fn(async () => cliResult ?? { status: 0, stdout: "cli", stderr: "" }); const cli: OpenShellSandboxControl = { exec: cliExec }; From 8d135fdd11619643029ebc40d55bf02b04d28290 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:06:28 -0700 Subject: [PATCH 05/16] fix(openshell): prevent replay after gRPC dispatch Signed-off-by: Aaron Erickson --- .../openshell/grpc-sandbox-control.test.ts | 6 +++- .../openshell/grpc-sandbox-control.ts | 15 +++++++++- .../openshell/sandbox-control-routing.test.ts | 28 ++++++++++++++++--- .../openshell/sandbox-control-routing.ts | 12 ++++++-- 4 files changed, 52 insertions(+), 9 deletions(-) diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 8d528f667a1..79b476db4ce 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -22,6 +22,7 @@ import { createGrpcOpenShellSandboxControl, createOpenShellGrpcApi, OpenShellGrpcOutputLimitError, + OpenShellGrpcPreDispatchError, type OpenShellGrpcApi, } from "./grpc-sandbox-control"; @@ -221,7 +222,10 @@ describe("gRPC OpenShell sandbox control", () => { status: null, stdout: "", stderr: "", - error, + error: expect.objectContaining({ + cause: error, + name: OpenShellGrpcPreDispatchError.name, + }), }); expect(fake.execMetadata).toEqual([]); }); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index e37e6fe1da6..ebeecde9edc 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -72,6 +72,13 @@ export class OpenShellGrpcOutputLimitError extends Error { } } +export class OpenShellGrpcPreDispatchError extends Error { + constructor(readonly cause: Error) { + super(cause.message, { cause }); + this.name = "OpenShellGrpcPreDispatchError"; + } +} + function isLoopback(hostname: string): boolean { const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase(); return ( @@ -309,7 +316,13 @@ export function createGrpcOpenShellSandboxControl( try { id = await sandboxId(client, request.sandboxName, metadata, options); } catch (error) { - return { status: null, stdout: "", stderr: "", error: error as Error }; + const cause = error instanceof Error ? error : new Error(String(error)); + return { + status: null, + stdout: "", + stderr: "", + error: new OpenShellGrpcPreDispatchError(cause), + }; } return execute(client, id, request, metadata, options); }, diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index 5a629f842d4..c74513629d9 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -3,7 +3,10 @@ import { describe, expect, it, vi } from "vitest"; -import type { GrpcOpenShellSandboxControl } from "./grpc-sandbox-control"; +import { + type GrpcOpenShellSandboxControl, + OpenShellGrpcPreDispatchError, +} from "./grpc-sandbox-control"; import type { OpenShellSandboxControl, SandboxExecResult } from "./sandbox-control"; import { execSandboxReadOnlyWithGrpcFallback } from "./sandbox-control-routing"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; @@ -55,11 +58,16 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.cliExec).not.toHaveBeenCalled(); }); - it("retries a gRPC transport failure through the CLI without forwarding its deadline", async () => { + it("retries a pre-dispatch gRPC lookup failure without forwarding its deadline", async () => { const grpcError = new Error("UNAVAILABLE"); const cliResult = { status: 0, stdout: "cli", stderr: "" }; const test = dependencies( - { status: null, stdout: "partial", stderr: "", error: grpcError }, + { + status: null, + stdout: "", + stderr: "", + error: new OpenShellGrpcPreDispatchError(grpcError), + }, cliResult, ); @@ -68,10 +76,22 @@ describe("read-only OpenShell sandbox control routing", () => { ).resolves.toEqual(cliResult); expect(test.cliExec).toHaveBeenCalledWith(request); - expect(test.debug).toHaveBeenCalledWith(expect.stringContaining("gRPC read failed"), grpcError); + expect(test.debug).toHaveBeenCalledWith(expect.stringContaining("before dispatch"), grpcError); expect(test.close).toHaveBeenCalledOnce(); }); + it("does not replay a post-dispatch gRPC stream failure", async () => { + const grpcError = new Error("stream reset"); + const result = { status: null, stdout: "partial", stderr: "", error: grpcError }; + const test = dependencies(result); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", request, test.deps), + ).resolves.toEqual(result); + + expect(test.cliExec).not.toHaveBeenCalled(); + }); + it("uses the CLI when gateway configuration cannot create a gRPC client", async () => { const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); const error = new Error("edge tunnel required"); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index f170bb100a6..b62647f5aa0 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -10,7 +10,10 @@ import { type SandboxExecRequest, type SandboxExecResult, } from "./sandbox-control"; -import type { GrpcOpenShellSandboxControl } from "./grpc-sandbox-control"; +import { + type GrpcOpenShellSandboxControl, + OpenShellGrpcPreDispatchError, +} from "./grpc-sandbox-control"; export interface ReadOnlyRoutingDependencies { cli: OpenShellSandboxControl; @@ -42,8 +45,11 @@ export async function execSandboxReadOnlyWithGrpcFallback( ...request, timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, }); - if (!result.error) return result; - dependencies.debug("OpenShell direct gRPC read failed; retrying through the CLI", result.error); + if (!(result.error instanceof OpenShellGrpcPreDispatchError)) return result; + dependencies.debug( + "OpenShell direct gRPC lookup failed before dispatch; retrying through the CLI", + result.error.cause, + ); } catch (error) { dependencies.debug( "OpenShell direct gRPC configuration failed; retrying through the CLI", From 7f21edc4f82dec7ac6b4847b793fc483eaa26ad4 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 21:04:35 -0700 Subject: [PATCH 06/16] fix(openshell): require literal loopback for plaintext gRPC Signed-off-by: Aaron Erickson --- .../openshell/grpc-sandbox-control.test.ts | 18 +++++++++++------- .../adapters/openshell/grpc-sandbox-control.ts | 4 +++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 8c134b38f87..32e04644127 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -4,25 +4,25 @@ import { EventEmitter } from "node:events"; import path from "node:path"; import { + type CallOptions, + loadPackageDefinition, Metadata, Server, ServerCredentials, - type CallOptions, - type sendUnaryData, type ServerUnaryCall, type ServerWritableStream, type ServiceClientConstructor, type ServiceError, + type sendUnaryData, } from "@grpc/grpc-js"; -import { loadPackageDefinition } from "@grpc/grpc-js"; import * as protoLoader from "@grpc/proto-loader"; import { describe, expect, it, vi } from "vitest"; import { createGrpcOpenShellSandboxControl, createOpenShellGrpcApi, - OpenShellGrpcOutputLimitError, type OpenShellGrpcApi, + OpenShellGrpcOutputLimitError, } from "./grpc-sandbox-control"; class FakeStream extends EventEmitter { @@ -251,7 +251,7 @@ describe("gRPC OpenShell sandbox control", () => { it("rejects sandbox responses without a stable id", async () => { const fake = fakeApi({ sandboxId: "" }); const control = createGrpcOpenShellSandboxControl( - { endpoint: "http://localhost:8080" }, + { endpoint: "http://127.0.0.1:8080" }, fake.api, ); @@ -348,7 +348,11 @@ describe("gRPC OpenShell sandbox control", () => { it.each([ ["ftp://localhost:8080", "must use http:// or https://"], + ["http://localhost:8080", "restricted to loopback"], ["http://gateway.example:8080", "restricted to loopback"], + ["http://128.0.0.1:8080", "restricted to loopback"], + ["http://[::2]:8080", "restricted to loopback"], + ["http://127.999.999.999:8080", "Invalid OpenShell gRPC endpoint"], ["http://localhost:8080/path", "must not contain"], ])("rejects unsafe endpoint %s", (endpoint, message) => { expect(() => createOpenShellGrpcApi({ endpoint })).toThrow(message); @@ -357,13 +361,13 @@ describe("gRPC OpenShell sandbox control", () => { it("rejects bearer tokens or TLS material on plaintext endpoints", () => { expect(() => createOpenShellGrpcApi({ - endpoint: "http://localhost:8080", + endpoint: "http://127.0.0.1:8080", bearerToken: "token", }), ).toThrow("requires TLS"); expect(() => createOpenShellGrpcApi({ - endpoint: "http://localhost:8080", + endpoint: "http://127.0.0.1:8080", caCertificate: Buffer.from("ca"), }), ).toThrow("require an https:// endpoint"); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index 63addd72717..246efc2382d 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { EventEmitter } from "node:events"; +import { isIP } from "node:net"; import path from "node:path"; import { StringDecoder } from "node:string_decoder"; @@ -74,8 +75,9 @@ export class OpenShellGrpcOutputLimitError extends Error { function isLoopback(hostname: string): boolean { const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase(); + const version = isIP(normalized); return ( - normalized === "localhost" || normalized === "::1" || /^127(?:\.\d{1,3}){3}$/.test(normalized) + (version === 4 && normalized.startsWith("127.")) || (version === 6 && normalized === "::1") ); } From 8d3da0c268a702ecc18b1fbae59529ac88bbdc27 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 21:06:49 -0700 Subject: [PATCH 07/16] docs(openshell): document direct session transport Signed-off-by: Aaron Erickson --- docs/reference/commands.mdx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index dd9d9b50cd1..0a43fe93d86 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2195,7 +2195,11 @@ Pass `-f` / `--file ` to point at the manifest; `--yes` confirms th List OpenClaw conversation sessions in the sandbox. With no subcommand the in-sandbox CLI lists stored sessions for the configured default agent. -NemoClaw invokes `openclaw sessions` via `openshell sandbox exec` and forwards OpenClaw flags verbatim, but filters default list output so internal `nemoclaw-onboard-warmup-*` sessions created during onboarding are hidden from user-facing output. +NemoClaw invokes the read-only `openclaw sessions` command through the sandbox's named OpenShell gateway and forwards OpenClaw flags verbatim. +It prefers the direct gRPC sandbox execution API. +If gateway configuration or the gRPC transport fails before NemoClaw receives a command result, it retries this read-only list operation through the OpenShell CLI. +A completed command, including a nonzero result, is never replayed during fallback. +NemoClaw filters default list output so internal `nemoclaw-onboard-warmup-*` sessions created during onboarding are hidden from user-facing output. ```bash $$nemoclaw my-assistant sessions From 96ec06e1d99c79c41b90b3f500f006fe780c0d24 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 21:56:29 -0700 Subject: [PATCH 08/16] test(openshell): accept IPv6 loopback gRPC endpoints Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/grpc-sandbox-control.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 32e04644127..bc4ec639a04 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -358,6 +358,14 @@ describe("gRPC OpenShell sandbox control", () => { expect(() => createOpenShellGrpcApi({ endpoint })).toThrow(message); }); + it.each([ + "http://127.0.0.1:8080", + "http://[::1]:8080", + ])("accepts literal loopback endpoint %s", (endpoint) => { + const api = createOpenShellGrpcApi({ endpoint }); + api.close(); + }); + it("rejects bearer tokens or TLS material on plaintext endpoints", () => { expect(() => createOpenShellGrpcApi({ From 025be8254fa370f8fea6d5f8c07c39ff3fccffa9 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 22:33:54 -0700 Subject: [PATCH 09/16] test(openshell): cover runtime stdin forwarding Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/runtime.test.ts | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/lib/adapters/openshell/runtime.test.ts diff --git a/src/lib/adapters/openshell/runtime.test.ts b/src/lib/adapters/openshell/runtime.test.ts new file mode 100644 index 00000000000..d74f53640ff --- /dev/null +++ b/src/lib/adapters/openshell/runtime.test.ts @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + captureOpenshellCommand: vi.fn(), +})); + +vi.mock("./client", () => ({ + captureOpenshellCommand: mocks.captureOpenshellCommand, + captureOpenshellCommandAsync: vi.fn(), + captureSandboxSshConfigCommand: vi.fn(), + getInstalledOpenshellVersion: vi.fn(), + runOpenshellCommand: vi.fn(), +})); + +vi.mock("./resolve", () => ({ + resolveOpenshell: () => "/test/openshell", +})); + +import { captureOpenshell } from "./runtime"; + +describe("OpenShell runtime capture", () => { + beforeEach(() => { + mocks.captureOpenshellCommand.mockReset(); + mocks.captureOpenshellCommand.mockReturnValue({ status: 0, output: "ok" }); + }); + + it("forwards binary stdin to the command capture boundary", () => { + const input = Buffer.from([0, 255, 10]); + const args = ["sandbox", "exec", "--name", "alpha", "--", "cat"]; + + captureOpenshell(args, { input }); + + expect(mocks.captureOpenshellCommand).toHaveBeenCalledWith( + "/test/openshell", + args, + expect.objectContaining({ input }), + ); + expect(mocks.captureOpenshellCommand.mock.calls[0]?.[2]?.input).toBe(input); + }); +}); From 6e041bd769bae2b8ee6b5c2541246383715d48f6 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 03:43:09 -0700 Subject: [PATCH 10/16] fix(openshell): bound encoded exec requests Signed-off-by: Aaron Erickson --- .../openshell/grpc-sandbox-control.test.ts | 21 ++++++ .../openshell/grpc-sandbox-control.ts | 5 ++ .../openshell/sandbox-control.test.ts | 57 +++++++++++++++++ src/lib/adapters/openshell/sandbox-control.ts | 64 ++++++++++++++++++- 4 files changed, 146 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 944219426d0..75ccdf6e1cb 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -122,6 +122,27 @@ describe("gRPC OpenShell sandbox control", () => { expect(fake.execMetadata).toEqual([]); }); + it("rejects an oversized encoded request after lookup and before exec", async () => { + const fake = fakeApi({ sandboxId: "00000000-0000-0000-0000-000000000000" }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["sh", "-s"], + stdin: Buffer.alloc(1_048_527), + }); + + expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); + expect((result.error as OpenShellExecRequestValidationError).issue.kind).toBe( + "encoded-request-too-large", + ); + expect(fake.getMetadata).toHaveLength(1); + expect(fake.execMetadata).toEqual([]); + }); + it("dispatches an exact 32768-byte UTF-8 argument unchanged", async () => { const fake = fakeApi({ emit(stream) { diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index 6fca44c744d..8ff1084627d 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -12,6 +12,7 @@ import * as protoLoader from "@grpc/proto-loader"; import { openShellExecRequestValidationFailure, validateOpenShellExecCommand, + validateOpenShellExecRequest, type OpenShellSandboxControl, type SandboxExecRequest, type SandboxExecResult, @@ -341,6 +342,10 @@ export function createGrpcOpenShellSandboxControl( error: new OpenShellGrpcPreDispatchError(cause), }; } + const requestValidationError = validateOpenShellExecRequest(request, id); + if (requestValidationError) { + return openShellExecRequestValidationFailure(requestValidationError); + } return execute(client, id, request, metadata, options); }, }; diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 6c2c02d6da3..044c971786a 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -8,6 +8,7 @@ import { createCliOpenShellSandboxControl, OpenShellExecRequestValidationError, validateOpenShellExecCommand, + validateOpenShellExecRequest, } from "./sandbox-control"; function expectValidationIssue( @@ -95,6 +96,45 @@ describe("OpenShell exec command validation", () => { }); }); +describe("OpenShell exec request validation", () => { + it("allows the exact unary request boundary and rejects one byte more", () => { + const exactRequest = { + sandboxName: "alpha", + command: ["sh", "-s"], + stdin: Buffer.alloc(1_048_526), + }; + + expect(validateOpenShellExecRequest(exactRequest)).toBeNull(); + const error = validateOpenShellExecRequest({ + ...exactRequest, + stdin: Buffer.alloc(1_048_527), + }); + expect(error?.issue).toEqual({ + kind: "encoded-request-too-large", + actualBytes: 1_048_577, + maxBytes: 1_048_576, + }); + }); + + it("includes timeoutSeconds in the encoded request boundary", () => { + const exactRequest = { + sandboxName: "alpha", + command: ["sh", "-s"], + stdin: Buffer.alloc(1_048_524), + timeoutMs: 120_000, + }; + + expect(validateOpenShellExecRequest(exactRequest)).toBeNull(); + expect( + validateOpenShellExecRequest({ ...exactRequest, stdin: Buffer.alloc(1_048_525) })?.issue, + ).toEqual({ + kind: "encoded-request-too-large", + actualBytes: 1_048_577, + maxBytes: 1_048_576, + }); + }); +}); + describe("CLI OpenShell sandbox control", () => { it("maps a typed exec request to the existing CLI contract", async () => { const capture = vi.fn( @@ -169,6 +209,23 @@ describe("CLI OpenShell sandbox control", () => { }); }); + it("rejects an oversized encoded request without invoking the CLI", async () => { + const capture = vi.fn<() => CaptureOpenshellResult>(); + const control = createCliOpenShellSandboxControl(capture); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["sh", "-s"], + stdin: Buffer.alloc(1_048_527), + }); + + expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); + expect((result.error as OpenShellExecRequestValidationError).issue.kind).toBe( + "encoded-request-too-large", + ); + expect(capture).not.toHaveBeenCalled(); + }); + it("forwards an exact-boundary argument unchanged", async () => { const capture = vi.fn( (_args: readonly string[]): CaptureOpenshellResult => ({ diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index d6bd9412625..b07aa7ff390 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -31,6 +31,7 @@ export type OpenShellExecRequestValidationIssue = | { kind: "empty-command" } | { kind: "too-many-arguments"; actual: number; max: number } | { kind: "assembled-command-too-large"; actualBytes: number; maxBytes: number } + | { kind: "encoded-request-too-large"; actualBytes: number; maxBytes: number } | { kind: "argument-too-large"; index: number; @@ -60,6 +61,8 @@ type CaptureOpenShell = typeof captureOpenshell; const OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS = 1024; const OPENSHELL_V0072_MAX_EXEC_ARGUMENT_BYTES = 32 * 1024; const OPENSHELL_V0072_MAX_ASSEMBLED_COMMAND_BYTES = 256 * 1024; +const OPENSHELL_V0072_MAX_DECODED_GRPC_MESSAGE_BYTES = 1024 * 1024; +const OPENSHELL_V0072_SANDBOX_ID_PLACEHOLDER = "00000000-0000-0000-0000-000000000000"; function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValidationIssue): string { switch (issue.kind) { @@ -69,6 +72,8 @@ function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValida return `command array exceeds ${String(issue.max)} argument limit`; case "assembled-command-too-large": return `assembled command string exceeds ${String(issue.maxBytes)} byte limit`; + case "encoded-request-too-large": + return `encoded exec request exceeds ${String(issue.maxBytes)} byte limit`; case "argument-too-large": return `command argument ${String(issue.index)} exceeds ${String(issue.maxBytes)} byte limit`; case "argument-control-character": @@ -164,6 +169,61 @@ export function validateOpenShellExecCommand( return null; } +function protobufVarintByteLength(value: number): number { + let remaining = value; + let bytes = 1; + while (remaining >= 0x80) { + remaining = Math.floor(remaining / 0x80); + bytes += 1; + } + return bytes; +} + +function protobufLengthDelimitedFieldByteLength(valueBytes: number): number { + // Every ExecSandboxRequest field used here has a one-byte protobuf tag. + return 1 + protobufVarintByteLength(valueBytes) + valueBytes; +} + +function openShellExecRequestEncodedByteLength( + request: SandboxExecRequest, + sandboxId: string, +): number { + let bytes = protobufLengthDelimitedFieldByteLength(Buffer.byteLength(sandboxId, "utf8")); + for (const argument of request.command) { + bytes += protobufLengthDelimitedFieldByteLength(Buffer.byteLength(argument, "utf8")); + } + if (request.timeoutMs !== undefined && request.timeoutMs > 0) { + const timeoutSeconds = Math.min(Math.ceil(request.timeoutMs / 1000), 0xffff_ffff); + bytes += 1 + protobufVarintByteLength(timeoutSeconds); + } + if (request.stdin !== undefined) { + const stdinBytes = Buffer.isBuffer(request.stdin) + ? request.stdin.length + : Buffer.byteLength(request.stdin, "utf8"); + bytes += protobufLengthDelimitedFieldByteLength(stdinBytes); + } + return bytes; +} + +/** Match v0.0.72's 1 MiB decoded unary gRPC request boundary. */ +export function validateOpenShellExecRequest( + request: SandboxExecRequest, + sandboxId: string = OPENSHELL_V0072_SANDBOX_ID_PLACEHOLDER, +): OpenShellExecRequestValidationError | null { + const commandError = validateOpenShellExecCommand(request.command); + if (commandError) return commandError; + + const actualBytes = openShellExecRequestEncodedByteLength(request, sandboxId); + if (actualBytes > OPENSHELL_V0072_MAX_DECODED_GRPC_MESSAGE_BYTES) { + return new OpenShellExecRequestValidationError({ + kind: "encoded-request-too-large", + actualBytes, + maxBytes: OPENSHELL_V0072_MAX_DECODED_GRPC_MESSAGE_BYTES, + }); + } + return null; +} + export function openShellExecRequestValidationFailure( error: OpenShellExecRequestValidationError, ): SandboxExecResult { @@ -186,7 +246,9 @@ export function createCliOpenShellSandboxControl( ): OpenShellSandboxControl { return { async exec(request): Promise { - const validationError = validateOpenShellExecCommand(request.command); + // v0.0.72 creates UUID sandbox ids. Reserve that exact encoded width + // before invoking the CLI, which resolves the name to the id internally. + const validationError = validateOpenShellExecRequest(request); if (validationError) return openShellExecRequestValidationFailure(validationError); const result = capture( From 5fec3ffa734f3921a1c12c1ea578c706972f54e5 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 03:54:07 -0700 Subject: [PATCH 11/16] fix(openshell): reject unrepresentable exec timeouts Signed-off-by: Aaron Erickson --- .../openshell/sandbox-control.test.ts | 57 +++++++++++++++++++ src/lib/adapters/openshell/sandbox-control.ts | 20 ++++++- 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 044c971786a..d5a20e5cc09 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -133,6 +133,46 @@ describe("OpenShell exec request validation", () => { maxBytes: 1_048_576, }); }); + + it("accepts the uint32 timeout boundary and rejects values protobufjs would wrap", () => { + const request = { + sandboxName: "alpha", + command: ["x"], + stdin: Buffer.alloc(1_048_525), + timeoutMs: 0xffff_ffff * 1000, + }; + + expect(validateOpenShellExecRequest(request)).toBeNull(); + expect( + validateOpenShellExecRequest({ ...request, stdin: Buffer.alloc(1_048_526) })?.issue, + ).toEqual({ + kind: "encoded-request-too-large", + actualBytes: 1_048_577, + maxBytes: 1_048_576, + }); + expect( + validateOpenShellExecRequest({ ...request, timeoutMs: request.timeoutMs + 1 })?.issue, + ).toEqual({ + kind: "timeout-out-of-range", + actualMs: 0xffff_ffff * 1000 + 1, + maxMs: 0xffff_ffff * 1000, + }); + }); + + it.each([ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + ])("rejects an invalid timeout of %s", (timeoutMs) => { + expect( + validateOpenShellExecRequest({ + sandboxName: "alpha", + command: ["true"], + timeoutMs, + })?.issue.kind, + ).toBe("timeout-out-of-range"); + }); }); describe("CLI OpenShell sandbox control", () => { @@ -226,6 +266,23 @@ describe("CLI OpenShell sandbox control", () => { expect(capture).not.toHaveBeenCalled(); }); + it("rejects a timeout that cannot be represented by the v0.0.72 request", async () => { + const capture = vi.fn<() => CaptureOpenshellResult>(); + const control = createCliOpenShellSandboxControl(capture); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["true"], + timeoutMs: 0xffff_ffff * 1000 + 1, + }); + + expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); + expect((result.error as OpenShellExecRequestValidationError).issue.kind).toBe( + "timeout-out-of-range", + ); + expect(capture).not.toHaveBeenCalled(); + }); + it("forwards an exact-boundary argument unchanged", async () => { const capture = vi.fn( (_args: readonly string[]): CaptureOpenshellResult => ({ diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index b07aa7ff390..3398218f5cd 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -32,6 +32,7 @@ export type OpenShellExecRequestValidationIssue = | { kind: "too-many-arguments"; actual: number; max: number } | { kind: "assembled-command-too-large"; actualBytes: number; maxBytes: number } | { kind: "encoded-request-too-large"; actualBytes: number; maxBytes: number } + | { kind: "timeout-out-of-range"; actualMs: number; maxMs: number } | { kind: "argument-too-large"; index: number; @@ -62,6 +63,8 @@ const OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS = 1024; const OPENSHELL_V0072_MAX_EXEC_ARGUMENT_BYTES = 32 * 1024; const OPENSHELL_V0072_MAX_ASSEMBLED_COMMAND_BYTES = 256 * 1024; const OPENSHELL_V0072_MAX_DECODED_GRPC_MESSAGE_BYTES = 1024 * 1024; +const OPENSHELL_V0072_MAX_EXEC_TIMEOUT_SECONDS = 0xffff_ffff; +const OPENSHELL_V0072_MAX_EXEC_TIMEOUT_MS = OPENSHELL_V0072_MAX_EXEC_TIMEOUT_SECONDS * 1000; const OPENSHELL_V0072_SANDBOX_ID_PLACEHOLDER = "00000000-0000-0000-0000-000000000000"; function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValidationIssue): string { @@ -74,6 +77,8 @@ function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValida return `assembled command string exceeds ${String(issue.maxBytes)} byte limit`; case "encoded-request-too-large": return `encoded exec request exceeds ${String(issue.maxBytes)} byte limit`; + case "timeout-out-of-range": + return `timeoutMs must be a non-negative safe integer no greater than ${String(issue.maxMs)}`; case "argument-too-large": return `command argument ${String(issue.index)} exceeds ${String(issue.maxBytes)} byte limit`; case "argument-control-character": @@ -193,7 +198,7 @@ function openShellExecRequestEncodedByteLength( bytes += protobufLengthDelimitedFieldByteLength(Buffer.byteLength(argument, "utf8")); } if (request.timeoutMs !== undefined && request.timeoutMs > 0) { - const timeoutSeconds = Math.min(Math.ceil(request.timeoutMs / 1000), 0xffff_ffff); + const timeoutSeconds = Math.ceil(request.timeoutMs / 1000); bytes += 1 + protobufVarintByteLength(timeoutSeconds); } if (request.stdin !== undefined) { @@ -213,6 +218,19 @@ export function validateOpenShellExecRequest( const commandError = validateOpenShellExecCommand(request.command); if (commandError) return commandError; + if ( + request.timeoutMs !== undefined && + (!Number.isSafeInteger(request.timeoutMs) || + request.timeoutMs < 0 || + request.timeoutMs > OPENSHELL_V0072_MAX_EXEC_TIMEOUT_MS) + ) { + return new OpenShellExecRequestValidationError({ + kind: "timeout-out-of-range", + actualMs: request.timeoutMs, + maxMs: OPENSHELL_V0072_MAX_EXEC_TIMEOUT_MS, + }); + } + const actualBytes = openShellExecRequestEncodedByteLength(request, sandboxId); if (actualBytes > OPENSHELL_V0072_MAX_DECODED_GRPC_MESSAGE_BYTES) { return new OpenShellExecRequestValidationError({ From d2d59ad059a758979ccf750e86a6ed497fafa802 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 04:47:15 -0700 Subject: [PATCH 12/16] fix(openshell): unify output capture limits Signed-off-by: Aaron Erickson --- .../openshell/grpc-sandbox-control.test.ts | 97 +++++++++++- .../openshell/grpc-sandbox-control.ts | 46 ++---- .../openshell/sandbox-control-routing.test.ts | 35 ++++- .../openshell/sandbox-control-routing.ts | 25 ++- .../openshell/sandbox-control.test.ts | 143 +++++++++++++++++- src/lib/adapters/openshell/sandbox-control.ts | 96 +++++++++++- 6 files changed, 366 insertions(+), 76 deletions(-) diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 75ccdf6e1cb..6b09e36065b 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -25,7 +25,10 @@ import { OpenShellGrpcOutputLimitError, OpenShellGrpcPreDispatchError, } from "./grpc-sandbox-control"; -import { OpenShellExecRequestValidationError } from "./sandbox-control"; +import { + OPENSHELL_EXEC_MAX_OUTPUT_BYTES, + OpenShellExecRequestValidationError, +} from "./sandbox-control"; class FakeStream extends EventEmitter { cancelled = false; @@ -79,7 +82,15 @@ function fakeApi(fixture: FakeApiOptions = {}): { return Object.assign(stream, { request }); }, }; - return { api, stream, getMetadata, execMetadata, getOptions, execOptions, close }; + return { + api, + stream, + getMetadata, + execMetadata, + getOptions, + execOptions, + close, + }; } function serviceError(message: string): ServiceError { @@ -114,7 +125,10 @@ describe("gRPC OpenShell sandbox control", () => { fake.api, ); - const result = await control.exec({ sandboxName: "alpha", command: ["bad\ncommand"] }); + const result = await control.exec({ + sandboxName: "alpha", + command: ["bad\ncommand"], + }); expect(result).toMatchObject({ status: null, stdout: "", stderr: "" }); expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); @@ -122,7 +136,7 @@ describe("gRPC OpenShell sandbox control", () => { expect(fake.execMetadata).toEqual([]); }); - it("rejects an oversized encoded request after lookup and before exec", async () => { + it("rejects an oversized encoded request before lookup or exec", async () => { const fake = fakeApi({ sandboxId: "00000000-0000-0000-0000-000000000000" }); const control = createGrpcOpenShellSandboxControl( { endpoint: "http://127.0.0.1:8080" }, @@ -139,6 +153,29 @@ describe("gRPC OpenShell sandbox control", () => { expect((result.error as OpenShellExecRequestValidationError).issue.kind).toBe( "encoded-request-too-large", ); + expect(fake.getMetadata).toEqual([]); + expect(fake.execMetadata).toEqual([]); + }); + + it("revalidates the encoded boundary with the sandbox id returned by lookup", async () => { + const fake = fakeApi({ sandboxId: "00000000-0000-0000-0000-000000000000x" }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["sh", "-s"], + stdin: Buffer.alloc(1_048_526), + }); + + expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); + expect((result.error as OpenShellExecRequestValidationError).issue).toEqual({ + kind: "encoded-request-too-large", + actualBytes: 1_048_577, + maxBytes: 1_048_576, + }); expect(fake.getMetadata).toHaveLength(1); expect(fake.execMetadata).toEqual([]); }); @@ -157,7 +194,10 @@ describe("gRPC OpenShell sandbox control", () => { const boundaryArgument = "é".repeat(16 * 1024); await expect( - control.exec({ sandboxName: "alpha", command: ["printf", boundaryArgument] }), + control.exec({ + sandboxName: "alpha", + command: ["printf", boundaryArgument], + }), ).resolves.toMatchObject({ status: 0 }); expect( @@ -264,7 +304,11 @@ describe("gRPC OpenShell sandbox control", () => { }); expect(requests).toEqual([ { name: "alpha" }, - { sandboxId: "wire-id", command: ["cat"], stdin: Buffer.from([0, 255, 10]) }, + { + sandboxId: "wire-id", + command: ["cat"], + stdin: Buffer.from([0, 255, 10]), + }, ]); } finally { control.close(); @@ -305,7 +349,11 @@ describe("gRPC OpenShell sandbox control", () => { ); const before = Date.now(); - await control.exec({ sandboxName: "alpha", command: ["true"], timeoutMs: 1500 }); + await control.exec({ + sandboxName: "alpha", + command: ["true"], + timeoutMs: 1500, + }); expect(fake.getOptions[0].deadline).toBeInstanceOf(Date); expect(fake.execOptions[0].deadline).toBe(fake.getOptions[0].deadline); @@ -341,6 +389,8 @@ describe("gRPC OpenShell sandbox control", () => { it.each([ [{ maxOutputBytes: -1 }, "maxOutputBytes"], + [{ maxOutputBytes: 1.5 }, "maxOutputBytes"], + [{ maxOutputBytes: OPENSHELL_EXEC_MAX_OUTPUT_BYTES + 1 }, "maxOutputBytes"], [{ timeoutMs: 1.5 }, "timeoutMs"], ])("rejects invalid execution limits before gateway lookup", async (limits, field) => { const fake = fakeApi(); @@ -349,8 +399,13 @@ describe("gRPC OpenShell sandbox control", () => { fake.api, ); - const result = await control.exec({ sandboxName: "alpha", command: ["true"], ...limits }); + const result = await control.exec({ + sandboxName: "alpha", + command: ["true"], + ...limits, + }); + expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); expect(result.error?.message).toContain(field); expect(fake.getMetadata).toEqual([]); }); @@ -379,6 +434,32 @@ describe("gRPC OpenShell sandbox control", () => { expect(fake.stream.cancelled).toBe(true); }); + it("treats zero as a zero-byte output cap", async () => { + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: Buffer.from("x") } }); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["true"], + maxOutputBytes: 0, + }); + + expect(result).toEqual({ + status: null, + stdout: "", + stderr: "", + error: expect.any(OpenShellGrpcOutputLimitError), + }); + expect(fake.stream.cancelled).toBe(true); + }); + it("preserves partial output when the stream fails", async () => { const error = serviceError("relay reset"); const fake = fakeApi({ diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index 8ff1084627d..8806e7c91c1 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -10,15 +10,15 @@ import * as grpc from "@grpc/grpc-js"; import * as protoLoader from "@grpc/proto-loader"; import { - openShellExecRequestValidationFailure, - validateOpenShellExecCommand, - validateOpenShellExecRequest, + OPENSHELL_EXEC_DEFAULT_MAX_OUTPUT_BYTES, + OpenShellExecOutputLimitError, type OpenShellSandboxControl, + openShellExecRequestValidationFailure, type SandboxExecRequest, type SandboxExecResult, + validateOpenShellExecRequest, } from "./sandbox-control"; -const DEFAULT_EXEC_MAX_OUTPUT_BYTES = 1024 * 1024; const PROTO_VERSION = "0.0.72"; interface GetSandboxResponse { @@ -72,14 +72,7 @@ export interface GrpcOpenShellSandboxControl extends OpenShellSandboxControl { close(): void; } -export class OpenShellGrpcOutputLimitError extends Error { - readonly code = "ENOBUFS"; - - constructor(readonly maxOutputBytes: number) { - super(`OpenShell gRPC exec output exceeded ${maxOutputBytes} bytes`); - this.name = "OpenShellGrpcOutputLimitError"; - } -} +export { OpenShellExecOutputLimitError as OpenShellGrpcOutputLimitError } from "./sandbox-control"; export class OpenShellGrpcPreDispatchError extends Error { constructor(readonly cause: Error) { @@ -229,7 +222,7 @@ function execute( metadata: grpc.Metadata, options: grpc.CallOptions, ): Promise { - const maxOutputBytes = request.maxOutputBytes ?? DEFAULT_EXEC_MAX_OUTPUT_BYTES; + const maxOutputBytes = request.maxOutputBytes ?? OPENSHELL_EXEC_DEFAULT_MAX_OUTPUT_BYTES; return new Promise((resolve) => { const timeoutSeconds = request.timeoutMs && request.timeoutMs > 0 ? Math.ceil(request.timeoutMs / 1000) : undefined; @@ -268,7 +261,7 @@ function execute( if (destination === "stdout") stdout += stdoutDecoder.write(retained); else stderr += stderrDecoder.write(retained); if (retained.length < data.length) { - finish(new OpenShellGrpcOutputLimitError(maxOutputBytes)); + finish(new OpenShellExecOutputLimitError(maxOutputBytes)); stream.cancel(); } }; @@ -301,29 +294,10 @@ export function createGrpcOpenShellSandboxControl( return { close: () => client.close(), async exec(request): Promise { - const validationError = validateOpenShellExecCommand(request.command); + // Validate against the exact v0.0.72 UUID-width request before lookup so + // transport-independent limits cannot cause any gateway activity. + const validationError = validateOpenShellExecRequest(request); if (validationError) return openShellExecRequestValidationFailure(validationError); - - const maxOutputBytes = request.maxOutputBytes ?? DEFAULT_EXEC_MAX_OUTPUT_BYTES; - if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0) { - return { - status: null, - stdout: "", - stderr: "", - error: new Error("maxOutputBytes must be a non-negative safe integer"), - }; - } - if ( - request.timeoutMs !== undefined && - (!Number.isSafeInteger(request.timeoutMs) || request.timeoutMs < 0) - ) { - return { - status: null, - stdout: "", - stderr: "", - error: new Error("timeoutMs must be a non-negative safe integer"), - }; - } const metadata = callMetadata(config.bearerToken); const deadline = request.timeoutMs && request.timeoutMs > 0 diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index e1664056f34..c53badef11b 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -8,8 +8,9 @@ import { OpenShellGrpcPreDispatchError, } from "./grpc-sandbox-control"; import { - type OpenShellSandboxControl, + OPENSHELL_EXEC_MAX_OUTPUT_BYTES, OpenShellExecRequestValidationError, + type OpenShellSandboxControl, openShellExecRequestValidationFailure, type SandboxExecResult, } from "./sandbox-control"; @@ -89,8 +90,31 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.cliExec).not.toHaveBeenCalled(); }); + it.each([ + -1, + 1.5, + OPENSHELL_EXEC_MAX_OUTPUT_BYTES + 1, + ])("rejects maxOutputBytes=%s before creating either transport", async (maxOutputBytes) => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + + const result = await execSandboxReadOnlyWithGrpcFallback( + "nemoclaw", + { ...request, maxOutputBytes }, + test.deps, + ); + + expect(result.error).toBeInstanceOf(OpenShellExecRequestValidationError); + expect((result.error as OpenShellExecRequestValidationError).issue.kind).toBe( + "max-output-out-of-range", + ); + expect(test.createGrpc).not.toHaveBeenCalled(); + expect(test.createCli).not.toHaveBeenCalled(); + }); + it("does not route a thrown typed validation error through the CLI", async () => { - const error = new OpenShellExecRequestValidationError({ kind: "empty-command" }); + const error = new OpenShellExecRequestValidationError({ + kind: "empty-command", + }); const test = dependencies(error); await expect( @@ -198,7 +222,12 @@ describe("read-only OpenShell sandbox control routing", () => { it("does not replay a post-dispatch gRPC stream failure", async () => { const grpcError = new Error("stream reset"); - const result = { status: null, stdout: "partial", stderr: "", error: grpcError }; + const result = { + status: null, + stdout: "partial", + stderr: "", + error: grpcError, + }; const test = dependencies(result); await expect( diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index 579ed0d4eac..c5f6a366010 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -10,11 +10,11 @@ import { import { createGatewayScopedCliOpenShellSandboxControl, OpenShellExecRequestValidationError, - openShellExecRequestValidationFailure, type OpenShellSandboxControl, + openShellExecRequestValidationFailure, type SandboxExecRequest, type SandboxExecResult, - validateOpenShellExecCommand, + validateOpenShellExecRequest, } from "./sandbox-control"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; @@ -49,7 +49,11 @@ export async function execSandboxReadOnlyWithGrpcFallback( request: SandboxExecRequest, dependencies: ReadOnlyRoutingDependencies = defaultDependencies, ): Promise { - const validationError = validateOpenShellExecCommand(request.command); + const routedRequest = { + ...request, + timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, + }; + const validationError = validateOpenShellExecRequest(routedRequest); if (validationError) return openShellExecRequestValidationFailure(validationError); let grpc: GrpcOpenShellSandboxControl; @@ -63,18 +67,12 @@ export async function execSandboxReadOnlyWithGrpcFallback( "OpenShell direct gRPC configuration failed; retrying through the CLI", error, ); - return dependencies.createCli(gatewayName).exec({ - ...request, - timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, - }); + return dependencies.createCli(gatewayName).exec(routedRequest); } let preDispatchError: OpenShellGrpcPreDispatchError | undefined; try { - const result = await grpc.exec({ - ...request, - timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, - }); + const result = await grpc.exec(routedRequest); if (!(result.error instanceof OpenShellGrpcPreDispatchError)) return result; preDispatchError = result.error; } catch (error) { @@ -96,8 +94,5 @@ export async function execSandboxReadOnlyWithGrpcFallback( "OpenShell direct gRPC lookup failed before dispatch; retrying through the CLI", preDispatchError.cause, ); - return dependencies.createCli(gatewayName).exec({ - ...request, - timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, - }); + return dependencies.createCli(gatewayName).exec(routedRequest); } diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 72371cac1b6..1018dd17984 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -7,6 +7,8 @@ import type { CaptureOpenshellResult } from "./client"; import { createCliOpenShellSandboxControl, createGatewayScopedCliOpenShellSandboxControl, + OPENSHELL_EXEC_MAX_OUTPUT_BYTES, + OpenShellExecOutputLimitError, OpenShellExecRequestValidationError, validateOpenShellExecCommand, validateOpenShellExecRequest, @@ -127,7 +129,10 @@ describe("OpenShell exec request validation", () => { expect(validateOpenShellExecRequest(exactRequest)).toBeNull(); expect( - validateOpenShellExecRequest({ ...exactRequest, stdin: Buffer.alloc(1_048_525) })?.issue, + validateOpenShellExecRequest({ + ...exactRequest, + stdin: Buffer.alloc(1_048_525), + })?.issue, ).toEqual({ kind: "encoded-request-too-large", actualBytes: 1_048_577, @@ -145,14 +150,20 @@ describe("OpenShell exec request validation", () => { expect(validateOpenShellExecRequest(request)).toBeNull(); expect( - validateOpenShellExecRequest({ ...request, stdin: Buffer.alloc(1_048_526) })?.issue, + validateOpenShellExecRequest({ + ...request, + stdin: Buffer.alloc(1_048_526), + })?.issue, ).toEqual({ kind: "encoded-request-too-large", actualBytes: 1_048_577, maxBytes: 1_048_576, }); expect( - validateOpenShellExecRequest({ ...request, timeoutMs: request.timeoutMs + 1 })?.issue, + validateOpenShellExecRequest({ + ...request, + timeoutMs: request.timeoutMs + 1, + })?.issue, ).toEqual({ kind: "timeout-out-of-range", actualMs: 0xffff_ffff * 1000 + 1, @@ -174,6 +185,44 @@ describe("OpenShell exec request validation", () => { })?.issue.kind, ).toBe("timeout-out-of-range"); }); + + it.each([ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + OPENSHELL_EXEC_MAX_OUTPUT_BYTES + 1, + ])("rejects an invalid output limit of %s", (maxOutputBytes) => { + expect( + validateOpenShellExecRequest({ + sandboxName: "alpha", + command: ["true"], + maxOutputBytes, + })?.issue, + ).toEqual({ + kind: "max-output-out-of-range", + actualBytes: maxOutputBytes, + minBytes: 0, + maxBytes: OPENSHELL_EXEC_MAX_OUTPUT_BYTES, + }); + }); + + it("accepts zero and the hard maximum output limits", () => { + expect( + validateOpenShellExecRequest({ + sandboxName: "alpha", + command: ["true"], + maxOutputBytes: 0, + }), + ).toBeNull(); + expect( + validateOpenShellExecRequest({ + sandboxName: "alpha", + command: ["true"], + maxOutputBytes: OPENSHELL_EXEC_MAX_OUTPUT_BYTES, + }), + ).toBeNull(); + }); }); describe("CLI OpenShell sandbox control", () => { @@ -214,7 +263,9 @@ describe("CLI OpenShell sandbox control", () => { }); it("preserves transport failures without throwing", async () => { - const error = Object.assign(new Error("spawnSync openshell ENOBUFS"), { code: "ENOBUFS" }); + const error = Object.assign(new Error("spawnSync openshell EIO"), { + code: "EIO", + }); const capture = vi.fn( (): CaptureOpenshellResult => ({ status: null, @@ -268,7 +319,10 @@ describe("CLI OpenShell sandbox control", () => { const capture = vi.fn<() => CaptureOpenshellResult>(); const control = createCliOpenShellSandboxControl(capture); - const result = await control.exec({ sandboxName: "alpha", command: ["bad\ncommand"] }); + const result = await control.exec({ + sandboxName: "alpha", + command: ["bad\ncommand"], + }); expect(capture).not.toHaveBeenCalled(); expect(result).toMatchObject({ status: null, stdout: "", stderr: "" }); @@ -314,6 +368,80 @@ describe("CLI OpenShell sandbox control", () => { expect(capture).not.toHaveBeenCalled(); }); + it("implements a zero-byte output cap without passing Node's unlimited maxBuffer=0", async () => { + const capture = vi.fn( + (): CaptureOpenshellResult => ({ + status: 0, + output: "visible output", + stdout: "visible output", + stderr: "warning", + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["true"], + maxOutputBytes: 0, + }); + + expect(result).toEqual({ + status: null, + stdout: "", + stderr: "", + error: expect.any(OpenShellExecOutputLimitError), + }); + expect(capture).toHaveBeenCalledWith( + expect.any(Array), + expect.objectContaining({ maxBuffer: 1 }), + ); + }); + + it("allows a command with a zero-byte output cap when it emits nothing", async () => { + const capture = vi.fn( + (): CaptureOpenshellResult => ({ status: 0, output: "", stdout: "", stderr: "" }), + ); + const control = createCliOpenShellSandboxControl(capture); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 0 }), + ).resolves.toEqual({ status: 0, stdout: "", stderr: "" }); + expect(capture).toHaveBeenCalledWith( + expect.any(Array), + expect.objectContaining({ maxBuffer: 1 }), + ); + }); + + it("retains at most the requested combined CLI output and normalizes ENOBUFS", async () => { + const captureError = Object.assign(new Error("spawnSync openshell ENOBUFS"), { + code: "ENOBUFS", + }); + const capture = vi.fn( + (): CaptureOpenshellResult => ({ + status: null, + output: "abcdef", + stdout: "abcdef", + stderr: "warning", + error: captureError, + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + const result = await control.exec({ + sandboxName: "alpha", + command: ["true"], + maxOutputBytes: 4, + }); + + expect(result).toEqual({ + status: null, + stdout: "abcd", + stderr: "", + error: expect.any(OpenShellExecOutputLimitError), + }); + expect((result.error as NodeJS.ErrnoException).code).toBe("ENOBUFS"); + }); + it("forwards an exact-boundary argument unchanged", async () => { const capture = vi.fn( (_args: readonly string[]): CaptureOpenshellResult => ({ @@ -326,7 +454,10 @@ describe("CLI OpenShell sandbox control", () => { const control = createCliOpenShellSandboxControl(capture); const boundaryArgument = "é".repeat(16 * 1024); - await control.exec({ sandboxName: "alpha", command: ["printf", boundaryArgument] }); + await control.exec({ + sandboxName: "alpha", + command: ["printf", boundaryArgument], + }); expect(capture).toHaveBeenCalledOnce(); expect(capture.mock.calls[0]?.[0]).toEqual([ diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index 59cc2f0714d..31df0d964c3 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -1,12 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { CaptureOpenshellResult } from "./client"; -import { captureOpenshell } from "./runtime"; import { assertNoOpenShellGatewayEndpointOverride, type OpenShellGatewayEndpointEnvironment, } from "../../openshell-gateway-endpoint-guard"; +import type { CaptureOpenshellResult } from "./client"; +import { captureOpenshell } from "./runtime"; export interface SandboxExecRequest { sandboxName: string; @@ -34,8 +34,18 @@ export interface OpenShellSandboxControl { export type OpenShellExecRequestValidationIssue = | { kind: "empty-command" } | { kind: "too-many-arguments"; actual: number; max: number } - | { kind: "assembled-command-too-large"; actualBytes: number; maxBytes: number } + | { + kind: "assembled-command-too-large"; + actualBytes: number; + maxBytes: number; + } | { kind: "encoded-request-too-large"; actualBytes: number; maxBytes: number } + | { + kind: "max-output-out-of-range"; + actualBytes: number; + minBytes: number; + maxBytes: number; + } | { kind: "timeout-out-of-range"; actualMs: number; maxMs: number } | { kind: "argument-too-large"; @@ -50,6 +60,8 @@ export type OpenShellExecRequestValidationIssue = }; export const OPENSHELL_EXEC_INVALID_ARGUMENT = "OPENSHELL_EXEC_INVALID_ARGUMENT"; +export const OPENSHELL_EXEC_DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024; +export const OPENSHELL_EXEC_MAX_OUTPUT_BYTES = 256 * 1024 * 1024; /** A command OpenShell v0.0.72 will reject before attempting sandbox execution. */ export class OpenShellExecRequestValidationError extends Error { @@ -61,6 +73,16 @@ export class OpenShellExecRequestValidationError extends Error { } } +/** A transport-neutral combined stdout/stderr retention failure. */ +export class OpenShellExecOutputLimitError extends Error { + readonly code = "ENOBUFS"; + + constructor(readonly maxOutputBytes: number) { + super(`OpenShell exec output exceeded ${String(maxOutputBytes)} bytes`); + this.name = "OpenShellExecOutputLimitError"; + } +} + type CaptureOpenShell = typeof captureOpenshell; const OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS = 1024; @@ -81,6 +103,8 @@ function openShellExecRequestValidationMessage(issue: OpenShellExecRequestValida return `assembled command string exceeds ${String(issue.maxBytes)} byte limit`; case "encoded-request-too-large": return `encoded exec request exceeds ${String(issue.maxBytes)} byte limit`; + case "max-output-out-of-range": + return `maxOutputBytes must be a safe integer from ${String(issue.minBytes)} through ${String(issue.maxBytes)}`; case "timeout-out-of-range": return `timeoutMs must be a non-negative safe integer no greater than ${String(issue.maxMs)}`; case "argument-too-large": @@ -222,6 +246,20 @@ export function validateOpenShellExecRequest( const commandError = validateOpenShellExecCommand(request.command); if (commandError) return commandError; + if ( + request.maxOutputBytes !== undefined && + (!Number.isSafeInteger(request.maxOutputBytes) || + request.maxOutputBytes < 0 || + request.maxOutputBytes > OPENSHELL_EXEC_MAX_OUTPUT_BYTES) + ) { + return new OpenShellExecRequestValidationError({ + kind: "max-output-out-of-range", + actualBytes: request.maxOutputBytes, + minBytes: 0, + maxBytes: OPENSHELL_EXEC_MAX_OUTPUT_BYTES, + }); + } + if ( request.timeoutMs !== undefined && (!Number.isSafeInteger(request.timeoutMs) || @@ -252,11 +290,50 @@ export function openShellExecRequestValidationFailure( return { status: null, stdout: "", stderr: "", error }; } -function normalizeExecResult(result: CaptureOpenshellResult): SandboxExecResult { +function isOutputLimitError(error: Error | undefined): boolean { + return (error as NodeJS.ErrnoException | undefined)?.code === "ENOBUFS"; +} + +function retainCombinedTextOutput( + stdout: string, + stderr: string, + maxOutputBytes: number, +): { stdout: string; stderr: string; truncated: boolean } { + const stdoutBytes = Buffer.from(stdout, "utf8"); + const stderrBytes = Buffer.from(stderr, "utf8"); + const retainedStdout = stdoutBytes.subarray(0, maxOutputBytes); + const remaining = Math.max(0, maxOutputBytes - retainedStdout.length); + const retainedStderr = stderrBytes.subarray(0, remaining); + return { + stdout: retainedStdout.toString("utf8"), + stderr: retainedStderr.toString("utf8"), + truncated: + retainedStdout.length < stdoutBytes.length || retainedStderr.length < stderrBytes.length, + }; +} + +function normalizeExecResult( + result: CaptureOpenshellResult, + maxOutputBytes: number, +): SandboxExecResult { + const retained = retainCombinedTextOutput( + result.stdout ?? result.output, + result.stderr ?? "", + maxOutputBytes, + ); + if (retained.truncated || isOutputLimitError(result.error)) { + return { + status: null, + stdout: retained.stdout, + stderr: retained.stderr, + error: new OpenShellExecOutputLimitError(maxOutputBytes), + ...(result.signal !== undefined ? { signal: result.signal } : {}), + }; + } const normalized: SandboxExecResult = { status: result.status, - stdout: result.stdout ?? result.output, - stderr: result.stderr ?? "", + stdout: retained.stdout, + stderr: retained.stderr, }; if (result.error) normalized.error = result.error; if (result.signal !== undefined) normalized.signal = result.signal; @@ -275,6 +352,7 @@ function createCliSandboxControl( if (validationError) return openShellExecRequestValidationFailure(validationError); const gatewayArgs = gatewayName ? ["--gateway", gatewayName] : []; + const maxOutputBytes = request.maxOutputBytes ?? OPENSHELL_EXEC_DEFAULT_MAX_OUTPUT_BYTES; const result = capture( [ ...gatewayArgs, @@ -289,11 +367,13 @@ function createCliSandboxControl( ignoreError: true, includeStreams: true, input: request.stdin, - maxBuffer: request.maxOutputBytes, + // Node treats maxBuffer=0 as unlimited. One byte is the smallest + // bounded capture; normalize it back to the requested zero-byte cap. + maxBuffer: maxOutputBytes === 0 ? 1 : maxOutputBytes, timeout: request.timeoutMs, }, ); - return normalizeExecResult(result); + return normalizeExecResult(result, maxOutputBytes); }, }; } From 781735620bec6771a8103afbf0ed4e12ddd6c648 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 05:43:35 -0700 Subject: [PATCH 13/16] fix(openshell): cap raw CLI output before decoding Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/client.test.ts | 23 ++++ src/lib/adapters/openshell/client.ts | 50 +++++++- .../openshell/grpc-sandbox-control.test.ts | 40 ++++++ src/lib/adapters/openshell/runtime.test.ts | 27 ++++- src/lib/adapters/openshell/runtime.ts | 13 ++ .../openshell/sandbox-control.test.ts | 114 +++++++++++++----- src/lib/adapters/openshell/sandbox-control.ts | 55 ++++----- 7 files changed, 258 insertions(+), 64 deletions(-) diff --git a/src/lib/adapters/openshell/client.test.ts b/src/lib/adapters/openshell/client.test.ts index 2941879dd00..72790784215 100644 --- a/src/lib/adapters/openshell/client.test.ts +++ b/src/lib/adapters/openshell/client.test.ts @@ -8,9 +8,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { captureOpenshellCommand, captureOpenshellCommandAsync, + captureOpenshellCommandBinary, captureSandboxSshConfigCommand, getInstalledOpenshellVersion, type OpenshellSpawnSync, + type OpenshellSpawnSyncBinary, parseVersionFromText, runOpenshellCommand, stripAnsi, @@ -41,6 +43,17 @@ function stubSpawnSync(spec: SpawnResultSpec): OpenshellSpawnSync { return () => makeSpawnResult(spec); } +function stubBinarySpawnSync(stdout: Buffer, stderr = Buffer.alloc(0)): OpenshellSpawnSyncBinary { + return () => ({ + pid: 123, + output: [stdout, stderr], + stdout, + stderr, + status: 0, + signal: null, + }); +} + function timeoutError(): Error { return Object.assign(new Error("spawnSync openshell ETIMEDOUT"), { code: "ETIMEDOUT" }); } @@ -125,6 +138,16 @@ describe("openshell helpers", () => { }); }); + it("captures raw stdout and stderr without UTF-8 decoding", () => { + const bytes = Buffer.from([0, 255, 128, 10]); + const stderr = Buffer.from("warning"); + const result = captureOpenshellCommandBinary("openshell", ["sandbox", "exec"], { + spawnSyncImpl: stubBinarySpawnSync(bytes, stderr), + }); + + expect(result).toEqual({ status: 0, stdout: bytes, stderr }); + }); + it("returns the spawn result when the command succeeds", () => { const result = runOpenshellCommand("openshell", ["status"], { spawnSyncImpl: stubSpawnSync({ diff --git a/src/lib/adapters/openshell/client.ts b/src/lib/adapters/openshell/client.ts index 621313e4386..54f5512ab6a 100644 --- a/src/lib/adapters/openshell/client.ts +++ b/src/lib/adapters/openshell/client.ts @@ -18,6 +18,12 @@ export type OpenshellSpawnSync = ( options: SpawnSyncOptionsWithStringEncoding, ) => SpawnSyncReturns; +export type OpenshellSpawnSyncBinary = ( + command: string, + args: readonly string[], + options: SpawnSyncOptions, +) => SpawnSyncReturns; + export type OpenshellSpawn = typeof spawn; interface OpenshellSpawnOptions { @@ -31,7 +37,9 @@ interface OpenshellSpawnOptions { exit?: (code: number) => never; } -function openshellSpawnEnv(opts: OpenshellSpawnOptions): NodeJS.ProcessEnv { +function openshellSpawnEnv( + opts: Pick, +): NodeJS.ProcessEnv { const explicitEnv = Object.fromEntries( Object.entries(opts.env ?? {}).filter( (entry): entry is [string, string] => entry[1] !== undefined, @@ -66,6 +74,22 @@ export interface CaptureOpenshellResult { signal?: NodeJS.Signals | null; } +export interface CaptureOpenshellBinaryOptions + extends Pick< + CaptureOpenshellOptions, + "cwd" | "env" | "replaceEnv" | "input" | "timeout" | "maxBuffer" + > { + spawnSyncImpl?: OpenshellSpawnSyncBinary; +} + +export interface CaptureOpenshellBinaryResult { + status: number | null; + stdout: Buffer; + stderr: Buffer; + error?: Error; + signal?: NodeJS.Signals | null; +} + const ANSI_RE = /\x1b\[[0-9;]*m/g; export function stripAnsi(value = ""): string { @@ -237,6 +261,30 @@ export function captureOpenshellCommand( }; } +/** Capture raw OpenShell output so byte limits are enforced before decoding. */ +export function captureOpenshellCommandBinary( + binary: string, + args: string[], + opts: CaptureOpenshellBinaryOptions = {}, +): CaptureOpenshellBinaryResult { + const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; + const result = spawnSyncImpl(binary, args, { + cwd: opts.cwd, + env: openshellSpawnEnv(opts), + stdio: [opts.input === undefined ? "ignore" : "pipe", "pipe", "pipe"], + input: opts.input, + timeout: opts.timeout, + maxBuffer: opts.maxBuffer, + }); + return { + status: result.status, + stdout: result.stdout ?? Buffer.alloc(0), + stderr: result.stderr ?? Buffer.alloc(0), + ...(result.error ? { error: result.error } : {}), + ...(result.signal !== null ? { signal: result.signal } : {}), + }; +} + export function captureSandboxSshConfigCommand( binary: string, sandboxName: string, diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 6b09e36065b..0663702cdd9 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -434,6 +434,46 @@ describe("gRPC OpenShell sandbox control", () => { expect(fake.stream.cancelled).toBe(true); }); + it("measures raw invalid UTF-8 bytes without a false output-limit failure", async () => { + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: Buffer.from([0xff]) } }); + stream.emit("data", { exit: { exitCode: 0 } }); + stream.emit("end"); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 1 }), + ).resolves.toEqual({ status: 0, stdout: "\ufffd", stderr: "" }); + }); + + it("reports raw-byte overflow when the cap splits a multibyte sequence", async () => { + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: Buffer.from("é") } }); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 1 }), + ).resolves.toEqual({ + status: null, + stdout: "\ufffd", + stderr: "", + error: expect.any(OpenShellGrpcOutputLimitError), + }); + expect(fake.stream.cancelled).toBe(true); + }); + it("treats zero as a zero-byte output cap", async () => { const fake = fakeApi({ emit(stream) { diff --git a/src/lib/adapters/openshell/runtime.test.ts b/src/lib/adapters/openshell/runtime.test.ts index d74f53640ff..13309c1cfdf 100644 --- a/src/lib/adapters/openshell/runtime.test.ts +++ b/src/lib/adapters/openshell/runtime.test.ts @@ -5,10 +5,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ captureOpenshellCommand: vi.fn(), + captureOpenshellCommandBinary: vi.fn(), })); vi.mock("./client", () => ({ captureOpenshellCommand: mocks.captureOpenshellCommand, + captureOpenshellCommandBinary: mocks.captureOpenshellCommandBinary, captureOpenshellCommandAsync: vi.fn(), captureSandboxSshConfigCommand: vi.fn(), getInstalledOpenshellVersion: vi.fn(), @@ -19,12 +21,19 @@ vi.mock("./resolve", () => ({ resolveOpenshell: () => "/test/openshell", })); -import { captureOpenshell } from "./runtime"; +import { ROOT } from "../../runner"; +import { captureOpenshell, captureOpenshellBinary } from "./runtime"; describe("OpenShell runtime capture", () => { beforeEach(() => { mocks.captureOpenshellCommand.mockReset(); mocks.captureOpenshellCommand.mockReturnValue({ status: 0, output: "ok" }); + mocks.captureOpenshellCommandBinary.mockReset(); + mocks.captureOpenshellCommandBinary.mockReturnValue({ + status: 0, + stdout: Buffer.from("ok"), + stderr: Buffer.alloc(0), + }); }); it("forwards binary stdin to the command capture boundary", () => { @@ -40,4 +49,20 @@ describe("OpenShell runtime capture", () => { ); expect(mocks.captureOpenshellCommand.mock.calls[0]?.[2]?.input).toBe(input); }); + + it("runs raw captures from the standard NemoClaw working directory", () => { + const input = Buffer.from([0, 255, 10]); + const args = ["sandbox", "exec", "--name", "alpha", "--", "cat"]; + + captureOpenshellBinary(args, { input, maxBuffer: 4096, timeout: 30_000 }); + + expect(mocks.captureOpenshellCommandBinary).toHaveBeenCalledWith("/test/openshell", args, { + cwd: ROOT, + env: undefined, + replaceEnv: undefined, + input, + maxBuffer: 4096, + timeout: 30_000, + }); + }); }); diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index c269fb48208..ed1d490a597 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -7,6 +7,7 @@ import { ROOT } from "../../runner"; import { captureOpenshellCommand, captureOpenshellCommandAsync, + captureOpenshellCommandBinary, captureSandboxSshConfigCommand, getInstalledOpenshellVersion, runOpenshellCommand, @@ -78,6 +79,18 @@ export function captureOpenshell(args: CommandArgs, opts: RunnerOptions = {}) { }); } +/** Run an OpenShell command and preserve output as raw bytes. */ +export function captureOpenshellBinary(args: CommandArgs, opts: RunnerOptions = {}) { + return captureOpenshellCommandBinary(getOpenshellBinary(), args, { + cwd: ROOT, + env: opts.env, + replaceEnv: opts.replaceEnv, + input: opts.input, + timeout: opts.timeout, + maxBuffer: opts.maxBuffer, + }); +} + /** Capture the SSH config OpenShell emits for a sandbox. */ export function captureSandboxSshConfig(sandboxName: string, opts: RunnerOptions = {}) { return captureSandboxSshConfigCommand(getOpenshellBinary(), sandboxName, { diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 1018dd17984..316d5701ed8 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"; -import type { CaptureOpenshellResult } from "./client"; +import type { CaptureOpenshellBinaryResult } from "./client"; import { createCliOpenShellSandboxControl, createGatewayScopedCliOpenShellSandboxControl, @@ -228,11 +228,10 @@ describe("OpenShell exec request validation", () => { describe("CLI OpenShell sandbox control", () => { it("maps a typed exec request to the existing CLI contract", async () => { const capture = vi.fn( - (): CaptureOpenshellResult => ({ + (): CaptureOpenshellBinaryResult => ({ status: 0, - output: "hello", - stdout: "hello\n", - stderr: "warning\n", + stdout: Buffer.from("hello\n"), + stderr: Buffer.from("warning\n"), }), ); const control = createCliOpenShellSandboxControl(capture); @@ -248,8 +247,6 @@ describe("CLI OpenShell sandbox control", () => { expect(capture).toHaveBeenCalledWith( ["sandbox", "exec", "--name", "alpha", "--", "openclaw", "sessions", "list", "--json"], { - ignoreError: true, - includeStreams: true, input: Buffer.from("request body"), maxBuffer: 4096, timeout: 30_000, @@ -267,9 +264,10 @@ describe("CLI OpenShell sandbox control", () => { code: "EIO", }); const capture = vi.fn( - (): CaptureOpenshellResult => ({ + (): CaptureOpenshellBinaryResult => ({ status: null, - output: "partial", + stdout: Buffer.from("partial"), + stderr: Buffer.alloc(0), error, signal: "SIGTERM", }), @@ -287,11 +285,10 @@ describe("CLI OpenShell sandbox control", () => { it("pins fallback execution to the requested gateway", async () => { const capture = vi.fn( - (): CaptureOpenshellResult => ({ + (): CaptureOpenshellBinaryResult => ({ status: 0, - output: "ok", - stdout: "ok\n", - stderr: "", + stdout: Buffer.from("ok\n"), + stderr: Buffer.alloc(0), }), ); const control = createGatewayScopedCliOpenShellSandboxControl("nemoclaw-19080", capture); @@ -300,12 +297,12 @@ describe("CLI OpenShell sandbox control", () => { expect(capture).toHaveBeenCalledWith( ["--gateway", "nemoclaw-19080", "sandbox", "exec", "--name", "alpha", "--", "true"], - expect.objectContaining({ ignoreError: true, includeStreams: true }), + expect.objectContaining({ maxBuffer: 1024 * 1024 }), ); }); it("rejects an ambient endpoint that could override the fallback gateway", () => { - const capture = vi.fn<() => CaptureOpenshellResult>(); + const capture = vi.fn<() => CaptureOpenshellBinaryResult>(); expect(() => createGatewayScopedCliOpenShellSandboxControl("nemoclaw-19080", capture, { @@ -316,7 +313,7 @@ describe("CLI OpenShell sandbox control", () => { }); it("returns a standard failure without capture for invalid commands", async () => { - const capture = vi.fn<() => CaptureOpenshellResult>(); + const capture = vi.fn<() => CaptureOpenshellBinaryResult>(); const control = createCliOpenShellSandboxControl(capture); const result = await control.exec({ @@ -335,7 +332,7 @@ describe("CLI OpenShell sandbox control", () => { }); it("rejects an oversized encoded request without invoking the CLI", async () => { - const capture = vi.fn<() => CaptureOpenshellResult>(); + const capture = vi.fn<() => CaptureOpenshellBinaryResult>(); const control = createCliOpenShellSandboxControl(capture); const result = await control.exec({ @@ -352,7 +349,7 @@ describe("CLI OpenShell sandbox control", () => { }); it("rejects a timeout that cannot be represented by the v0.0.72 request", async () => { - const capture = vi.fn<() => CaptureOpenshellResult>(); + const capture = vi.fn<() => CaptureOpenshellBinaryResult>(); const control = createCliOpenShellSandboxControl(capture); const result = await control.exec({ @@ -370,11 +367,10 @@ describe("CLI OpenShell sandbox control", () => { it("implements a zero-byte output cap without passing Node's unlimited maxBuffer=0", async () => { const capture = vi.fn( - (): CaptureOpenshellResult => ({ + (): CaptureOpenshellBinaryResult => ({ status: 0, - output: "visible output", - stdout: "visible output", - stderr: "warning", + stdout: Buffer.from("visible output"), + stderr: Buffer.from("warning"), }), ); const control = createCliOpenShellSandboxControl(capture); @@ -399,7 +395,11 @@ describe("CLI OpenShell sandbox control", () => { it("allows a command with a zero-byte output cap when it emits nothing", async () => { const capture = vi.fn( - (): CaptureOpenshellResult => ({ status: 0, output: "", stdout: "", stderr: "" }), + (): CaptureOpenshellBinaryResult => ({ + status: 0, + stdout: Buffer.alloc(0), + stderr: Buffer.alloc(0), + }), ); const control = createCliOpenShellSandboxControl(capture); @@ -417,11 +417,10 @@ describe("CLI OpenShell sandbox control", () => { code: "ENOBUFS", }); const capture = vi.fn( - (): CaptureOpenshellResult => ({ + (): CaptureOpenshellBinaryResult => ({ status: null, - output: "abcdef", - stdout: "abcdef", - stderr: "warning", + stdout: Buffer.from("abcdef"), + stderr: Buffer.from("warning"), error: captureError, }), ); @@ -442,13 +441,66 @@ describe("CLI OpenShell sandbox control", () => { expect((result.error as NodeJS.ErrnoException).code).toBe("ENOBUFS"); }); + it("measures raw invalid UTF-8 bytes without a false output-limit failure", async () => { + const capture = vi.fn( + (): CaptureOpenshellBinaryResult => ({ + status: 0, + stdout: Buffer.from([0xff]), + stderr: Buffer.alloc(0), + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 1 }), + ).resolves.toEqual({ status: 0, stdout: "\ufffd", stderr: "" }); + }); + + it("preserves a complete multibyte sequence at its exact raw-byte boundary", async () => { + const capture = vi.fn( + (): CaptureOpenshellBinaryResult => ({ + status: 0, + stdout: Buffer.from("é"), + stderr: Buffer.alloc(0), + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 2 }), + ).resolves.toEqual({ status: 0, stdout: "é", stderr: "" }); + }); + + it("reports raw-byte overflow even when the cap splits a multibyte sequence", async () => { + const captureError = Object.assign(new Error("spawnSync openshell ENOBUFS"), { + code: "ENOBUFS", + }); + const capture = vi.fn( + (): CaptureOpenshellBinaryResult => ({ + status: null, + stdout: Buffer.from("é"), + stderr: Buffer.alloc(0), + error: captureError, + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 1 }), + ).resolves.toEqual({ + status: null, + stdout: "\ufffd", + stderr: "", + error: expect.any(OpenShellExecOutputLimitError), + }); + }); + it("forwards an exact-boundary argument unchanged", async () => { const capture = vi.fn( - (_args: readonly string[]): CaptureOpenshellResult => ({ + (_args: readonly string[]): CaptureOpenshellBinaryResult => ({ status: 0, - output: "", - stdout: "", - stderr: "", + stdout: Buffer.alloc(0), + stderr: Buffer.alloc(0), }), ); const control = createCliOpenShellSandboxControl(capture); diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index 31df0d964c3..b4b1fe0d4cb 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -5,15 +5,15 @@ import { assertNoOpenShellGatewayEndpointOverride, type OpenShellGatewayEndpointEnvironment, } from "../../openshell-gateway-endpoint-guard"; -import type { CaptureOpenshellResult } from "./client"; -import { captureOpenshell } from "./runtime"; +import type { CaptureOpenshellBinaryResult } from "./client"; +import { captureOpenshellBinary } from "./runtime"; export interface SandboxExecRequest { sandboxName: string; command: readonly string[]; /** Optional bytes supplied to the remote command's standard input. */ stdin?: string | Buffer; - /** Maximum combined stdout and stderr bytes retained by the transport. */ + /** Maximum combined raw stdout and stderr bytes retained before UTF-8 decoding. */ maxOutputBytes?: number; /** End-to-end lookup and execution deadline. Zero means no deadline. */ timeoutMs?: number; @@ -83,7 +83,7 @@ export class OpenShellExecOutputLimitError extends Error { } } -type CaptureOpenShell = typeof captureOpenshell; +type CaptureOpenShellBinary = typeof captureOpenshellBinary; const OPENSHELL_V0072_MAX_EXEC_COMMAND_ARGS = 1024; const OPENSHELL_V0072_MAX_EXEC_ARGUMENT_BYTES = 32 * 1024; @@ -294,46 +294,41 @@ function isOutputLimitError(error: Error | undefined): boolean { return (error as NodeJS.ErrnoException | undefined)?.code === "ENOBUFS"; } -function retainCombinedTextOutput( - stdout: string, - stderr: string, +function retainCombinedOutput( + stdout: Buffer, + stderr: Buffer, maxOutputBytes: number, -): { stdout: string; stderr: string; truncated: boolean } { - const stdoutBytes = Buffer.from(stdout, "utf8"); - const stderrBytes = Buffer.from(stderr, "utf8"); - const retainedStdout = stdoutBytes.subarray(0, maxOutputBytes); +): { stdout: Buffer; stderr: Buffer; truncated: boolean } { + const retainedStdout = stdout.subarray(0, maxOutputBytes); const remaining = Math.max(0, maxOutputBytes - retainedStdout.length); - const retainedStderr = stderrBytes.subarray(0, remaining); + const retainedStderr = stderr.subarray(0, remaining); return { - stdout: retainedStdout.toString("utf8"), - stderr: retainedStderr.toString("utf8"), - truncated: - retainedStdout.length < stdoutBytes.length || retainedStderr.length < stderrBytes.length, + stdout: retainedStdout, + stderr: retainedStderr, + truncated: retainedStdout.length < stdout.length || retainedStderr.length < stderr.length, }; } function normalizeExecResult( - result: CaptureOpenshellResult, + result: CaptureOpenshellBinaryResult, maxOutputBytes: number, ): SandboxExecResult { - const retained = retainCombinedTextOutput( - result.stdout ?? result.output, - result.stderr ?? "", - maxOutputBytes, - ); + const retained = retainCombinedOutput(result.stdout, result.stderr, maxOutputBytes); + const stdout = retained.stdout.toString("utf8"); + const stderr = retained.stderr.toString("utf8"); if (retained.truncated || isOutputLimitError(result.error)) { return { status: null, - stdout: retained.stdout, - stderr: retained.stderr, + stdout, + stderr, error: new OpenShellExecOutputLimitError(maxOutputBytes), ...(result.signal !== undefined ? { signal: result.signal } : {}), }; } const normalized: SandboxExecResult = { status: result.status, - stdout: retained.stdout, - stderr: retained.stderr, + stdout, + stderr, }; if (result.error) normalized.error = result.error; if (result.signal !== undefined) normalized.signal = result.signal; @@ -341,7 +336,7 @@ function normalizeExecResult( } function createCliSandboxControl( - capture: CaptureOpenShell, + capture: CaptureOpenShellBinary, gatewayName?: string, ): OpenShellSandboxControl { return { @@ -364,8 +359,6 @@ function createCliSandboxControl( ...request.command, ], { - ignoreError: true, - includeStreams: true, input: request.stdin, // Node treats maxBuffer=0 as unlimited. One byte is the smallest // bounded capture; normalize it back to the requested zero-byte cap. @@ -379,7 +372,7 @@ function createCliSandboxControl( } export function createCliOpenShellSandboxControl( - capture: CaptureOpenShell = captureOpenshell, + capture: CaptureOpenShellBinary = captureOpenshellBinary, ): OpenShellSandboxControl { return createCliSandboxControl(capture); } @@ -387,7 +380,7 @@ export function createCliOpenShellSandboxControl( /** Bind every CLI fallback invocation to the gateway selected by the caller. */ export function createGatewayScopedCliOpenShellSandboxControl( gatewayName: string, - capture: CaptureOpenShell = captureOpenshell, + capture: CaptureOpenShellBinary = captureOpenshellBinary, env: OpenShellGatewayEndpointEnvironment = process.env, ): OpenShellSandboxControl { assertNoOpenShellGatewayEndpointOverride(env); From aa0dbd05740c29b21176428a6f90b34affcecc10 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 05:55:37 -0700 Subject: [PATCH 14/16] test(openshell): exercise real binary output limits Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/client.test.ts | 15 +++++++ .../openshell/sandbox-control.test.ts | 40 ++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/client.test.ts b/src/lib/adapters/openshell/client.test.ts index 72790784215..d870ebc9734 100644 --- a/src/lib/adapters/openshell/client.test.ts +++ b/src/lib/adapters/openshell/client.test.ts @@ -148,6 +148,21 @@ describe("openshell helpers", () => { expect(result).toEqual({ status: 0, stdout: bytes, stderr }); }); + it("preserves real child-process ENOBUFS metadata and partial raw output", () => { + const result = captureOpenshellCommandBinary( + process.execPath, + ["-e", "process.stdout.write(Buffer.from([0xc3, 0xa9]))"], + { maxBuffer: 1 }, + ); + + expect(result.status).toBeNull(); + expect((result.error as NodeJS.ErrnoException | undefined)?.code).toBe("ENOBUFS"); + expect(Buffer.isBuffer(result.stdout)).toBe(true); + expect(result.stdout.length).toBeGreaterThan(0); + expect(result.stdout[0]).toBe(0xc3); + expect(Buffer.isBuffer(result.stderr)).toBe(true); + }); + it("returns the spawn result when the command succeeds", () => { const result = runOpenshellCommand("openshell", ["status"], { spawnSyncImpl: stubSpawnSync({ diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 316d5701ed8..0a5e3762fdc 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"; -import type { CaptureOpenshellBinaryResult } from "./client"; +import { type CaptureOpenshellBinaryResult, captureOpenshellCommandBinary } from "./client"; import { createCliOpenShellSandboxControl, createGatewayScopedCliOpenShellSandboxControl, @@ -495,6 +495,44 @@ describe("CLI OpenShell sandbox control", () => { }); }); + it("normalizes real child-process ENOBUFS through the CLI boundary", async () => { + const control = createCliOpenShellSandboxControl((_args, options) => + captureOpenshellCommandBinary( + process.execPath, + ["-e", "process.stdout.write(Buffer.from([0xc3, 0xa9]))"], + options, + ), + ); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 1 }), + ).resolves.toMatchObject({ + status: null, + stdout: "\ufffd", + stderr: "", + error: expect.any(OpenShellExecOutputLimitError), + }); + }); + + it("normalizes the real child-process path back to a requested zero-byte cap", async () => { + const control = createCliOpenShellSandboxControl((_args, options) => + captureOpenshellCommandBinary( + process.execPath, + ["-e", "process.stdout.write(Buffer.from([0x78]))"], + options, + ), + ); + + await expect( + control.exec({ sandboxName: "alpha", command: ["true"], maxOutputBytes: 0 }), + ).resolves.toEqual({ + status: null, + stdout: "", + stderr: "", + error: expect.any(OpenShellExecOutputLimitError), + }); + }); + it("forwards an exact-boundary argument unchanged", async () => { const capture = vi.fn( (_args: readonly string[]): CaptureOpenshellBinaryResult => ({ From c6975baa07259439b3762e1c7aeb322fad5db7bf Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 06:12:43 -0700 Subject: [PATCH 15/16] test(openshell): ignore child exit status race Signed-off-by: Aaron Erickson --- src/lib/adapters/openshell/client.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/client.test.ts b/src/lib/adapters/openshell/client.test.ts index d870ebc9734..205dd8896d0 100644 --- a/src/lib/adapters/openshell/client.test.ts +++ b/src/lib/adapters/openshell/client.test.ts @@ -155,7 +155,8 @@ describe("openshell helpers", () => { { maxBuffer: 1 }, ); - expect(result.status).toBeNull(); + // Node can report either the completed exit status or null when ENOBUFS + // races a fast child exit. The error code and retained raw prefix are stable. expect((result.error as NodeJS.ErrnoException | undefined)?.code).toBe("ENOBUFS"); expect(Buffer.isBuffer(result.stdout)).toBe(true); expect(result.stdout.length).toBeGreaterThan(0); From dad87011642fef8952664db84a552ee659e1c03b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aaron=20Erickson=20=F0=9F=A6=9E?= Date: Mon, 20 Jul 2026 13:50:33 -0700 Subject: [PATCH 16/16] refactor(openshell): remove skill SSH transport (#6796) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Moves skill discovery and installation off host-managed SSH and onto the OpenShell sandbox-control boundary. This is PR 4 of 21 in the OpenShell gRPC migration stack. ## Changes - Use direct gRPC for skill reads and mutations. - Select one mutation transport before dispatch and never replay a failed mutation. - Remove skill-specific SSH configuration and invocation code. ## Stack - Stack index: https://github.com/NVIDIA/NemoClaw/pull/6790 - Depends on: https://github.com/NVIDIA/NemoClaw/pull/6795 - Review this PR against base branch `feat/openshell-grpc-stdin/ae` to see only this slice. ## Type of Change - [ ] Code change (feature, bug fix, or refactor) - [x] Code change with doc updates - [ ] Doc only (prose changes, no code sample modifications) - [ ] Doc only (includes code sample changes) ## Quality Gates - [x] Tests added or updated for changed behavior - [ ] Existing tests cover changed behavior — justification: - [ ] Tests not applicable — justification: - [x] Docs updated for user-facing behavior changes - [x] Sensitive paths changed (security, policy, credentials, preflight, onboarding, inference, runner, sandbox, or messaging) - [x] Sensitive-path review completed or maintainer-approved waiver recorded — reviewer/approval link/justification: transport-boundary self-review completed; mutations select one transport before dispatch and are never replayed automatically. - [ ] Non-success, skipped, or missing CI check accepted by maintainer — check name, approval link, and follow-up issue: ## Verification - [x] PR description includes the DCO sign-off declaration and every commit appears as `Verified` in GitHub - [x] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or `npm run check:diff` passed when hooks were skipped or unavailable - [x] Targeted behavior tests pass for the current change set, or tests are marked not applicable above — skill install/remote tests, transport inventory, and docs validation passed - [ ] Applicable broad gate passed — targeted and changed-graph tests were used; CI will run the repository-required broad gates - [x] Quality Gates section completed with required justifications or waivers - [x] No secrets, API keys, or credentials committed - [ ] `npm run docs` builds without warnings (doc changes only) — docs validation passed with 2 existing Fern warnings - [x] Doc pages follow the [style guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md) (doc changes only) - [ ] New doc pages include SPDX header and frontmatter (new pages only) --- Signed-off-by: Aaron Erickson --------- Signed-off-by: Aaron Erickson --- docs/reference/commands.mdx | 6 + scripts/checks/legacy-sandbox-transports.ts | 3 - src/lib/actions/sandbox/skill-install.test.ts | 131 +++++----- src/lib/actions/sandbox/skill-install.ts | 85 +++---- .../adapters/openshell/grpc-gateway-config.ts | 14 +- .../openshell/sandbox-control-routing.test.ts | 78 +++++- .../openshell/sandbox-control-routing.ts | 44 +++- src/lib/skill-install.test.ts | 81 ++++--- src/lib/skill-install.ts | 65 ++--- src/lib/skill-remote.test.ts | 227 +++++++++++------- src/lib/skill-remote.ts | 155 +++++------- 11 files changed, 536 insertions(+), 353 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 4a9f7e5cf6b..b0557a3a66b 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2068,6 +2068,11 @@ $$nemoclaw my-assistant mcp remove github [--force] Deploy a skill directory to a running sandbox. The command validates the `SKILL.md` frontmatter (a `name` field is required), uploads all non-dot files preserving subdirectory structure, and performs agent-specific post-install steps. +NemoClaw selects one OpenShell sandbox execution transport before it changes the skill. +It uses the named gateway's direct gRPC API for plaintext, mTLS, and OIDC gateways. +It preselects the OpenShell CLI only when Cloudflare edge-tunnel authentication requires the CLI-owned tunnel. +Any other direct-client configuration error stops the command before dispatch. +After dispatch starts, NemoClaw never retries the mutation through another transport. ```bash $$nemoclaw my-assistant skill install ./my-skill/ @@ -2111,6 +2116,7 @@ For new installs, the agent session index is refreshed so the agent discovers th Remove an installed skill from a running sandbox by skill name. The command validates the skill name, removes the sandbox upload directory, and refreshes the agent session index so the remaining skills are rediscovered on the next session. +It uses the same preselected, fail-closed OpenShell control path as `skill install`. diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index afcf4fb9278..b3ee4d654b7 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -39,8 +39,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], ["src/lib/actions/sandbox/process-recovery.ts", "ssh-command", 1], ["src/lib/actions/sandbox/process-recovery.ts", "ssh-temp-config", 1], - ["src/lib/actions/sandbox/skill-install.ts", "openshell-ssh-config", 2], - ["src/lib/actions/sandbox/skill-install.ts", "ssh-temp-config", 2], ["src/lib/actions/sandbox/snapshot.ts", "docker-exec-command", 1], ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], ["src/lib/adapters/openshell/client.ts", "openshell-ssh-config", 1], @@ -57,7 +55,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/share-command.ts", "sshfs-command", 1], ["src/lib/shields/index.ts", "privileged-sandbox-exec", 4], ["src/lib/shields/mutable-config-repair.ts", "privileged-sandbox-exec", 2], - ["src/lib/skill-remote.ts", "ssh-command", 1], ["src/lib/state/openclaw-config-restore-input.ts", "ssh-command", 1], ["src/lib/state/openclaw-plugin-restore.ts", "ssh-command", 2], ["src/lib/state/openclaw-plugin-restore.ts", "ssh-temp-config", 1], diff --git a/src/lib/actions/sandbox/skill-install.test.ts b/src/lib/actions/sandbox/skill-install.test.ts index 9f1dba812de..cde0d6302ae 100644 --- a/src/lib/actions/sandbox/skill-install.test.ts +++ b/src/lib/actions/sandbox/skill-install.test.ts @@ -6,7 +6,10 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const captureSandboxSshConfig = vi.hoisted(() => vi.fn()); +const selectOpenShellSandboxControlForMutation = vi.hoisted(() => vi.fn()); +const closeControl = vi.hoisted(() => vi.fn()); +const control = vi.hoisted(() => ({ exec: vi.fn() })); +const getSandbox = vi.hoisted(() => vi.fn()); const getSessionAgent = vi.hoisted(() => vi.fn()); const ensureLiveSandboxOrExit = vi.hoisted(() => vi.fn()); const skillInstall = vi.hoisted(() => ({ @@ -22,10 +25,12 @@ const skillInstall = vi.hoisted(() => ({ verifyInstall: vi.fn(), })); -vi.mock("../../adapters/openshell/runtime", () => ({ - captureSandboxSshConfig, +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + selectOpenShellSandboxControlForMutation, })); +vi.mock("../../state/registry", () => ({ getSandbox })); + vi.mock("../../agent/runtime", () => ({ getSessionAgent, })); @@ -57,14 +62,6 @@ function restoreExitCode(previousExitCode: typeof process.exitCode): void { process.exitCode = previousExitCode; } -function expectTempSshConfigCleanedUp(configFile: string): void { - const configDir = path.dirname(configFile); - expect(configDir).not.toBe(os.tmpdir()); - expect(path.basename(configDir)).toMatch(/^nemoclaw-ssh-skill-/); - expect(path.basename(configFile)).toBe("ssh_config"); - expect(fs.existsSync(configDir)).toBe(false); -} - describe("sandbox skill action orchestration", () => { let previousExitCode: typeof process.exitCode; @@ -73,34 +70,39 @@ describe("sandbox skill action orchestration", () => { process.exitCode = undefined; vi.clearAllMocks(); - captureSandboxSshConfig.mockReturnValue({ status: 0, output: "Host openshell-alpha\n" }); + selectOpenShellSandboxControlForMutation.mockReturnValue({ + control, + transport: "grpc", + close: closeControl, + }); + getSandbox.mockReturnValue({ gatewayName: "nemoclaw-9090", gatewayPort: 9090 }); ensureLiveSandboxOrExit.mockResolvedValue(undefined); getSessionAgent.mockReturnValue(agent); skillInstall.validateSkillName.mockReturnValue(true); skillInstall.resolveSkillPaths.mockReturnValue(paths); - skillInstall.checkExisting.mockReturnValue(true); - skillInstall.removeSkill.mockReturnValue({ + skillInstall.checkExisting.mockResolvedValue(true); + skillInstall.removeSkill.mockResolvedValue({ success: true, removedUploadDir: true, removedMirrorDir: true, clearedSessions: true, messages: [], }); - skillInstall.verifyRemove.mockReturnValue(true); + skillInstall.verifyRemove.mockResolvedValue(true); skillInstall.parseFrontmatter.mockReturnValue({ name: "demo-skill" }); skillInstall.collectFiles.mockReturnValue({ files: ["SKILL.md"], skippedDotfiles: [], unsafePaths: [], }); - skillInstall.uploadDirectory.mockReturnValue({ + skillInstall.uploadDirectory.mockResolvedValue({ uploaded: 1, failed: [], skippedDotfiles: [], unsafePaths: [], }); - skillInstall.postInstall.mockReturnValue({ success: true, messages: [] }); - skillInstall.verifyInstall.mockReturnValue(true); + skillInstall.postInstall.mockResolvedValue({ success: true, messages: [] }); + skillInstall.verifyInstall.mockResolvedValue(true); }); afterEach(() => { @@ -108,8 +110,10 @@ describe("sandbox skill action orchestration", () => { vi.restoreAllMocks(); }); - it("fails skill remove when SSH config capture fails", async () => { - captureSandboxSshConfig.mockReturnValue({ status: 1, output: "" }); + it("fails skill remove before dispatch when control selection fails", async () => { + selectOpenShellSandboxControlForMutation.mockImplementation(() => { + throw new Error("invalid mTLS material"); + }); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); const exit = vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null) => { throw new Error(`process.exit ${code}`); @@ -120,19 +124,16 @@ describe("sandbox skill action orchestration", () => { ); expect(ensureLiveSandboxOrExit).toHaveBeenCalledWith("alpha"); - expect(captureSandboxSshConfig).toHaveBeenCalledWith("alpha", expect.any(Object)); - expect(error).toHaveBeenCalledWith(" Failed to obtain SSH configuration for the sandbox."); + expect(selectOpenShellSandboxControlForMutation).toHaveBeenCalledWith("nemoclaw-9090"); + expect(error).toHaveBeenCalledWith( + " Failed to configure OpenShell sandbox execution: invalid mTLS material", + ); expect(skillInstall.checkExisting).not.toHaveBeenCalled(); expect(exit).toHaveBeenCalledWith(1); }); - it("treats unknown skill existence as fatal for remove and deletes the temp SSH config", async () => { - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx) => { - tempConfig = ctx.configFile; - expect(fs.existsSync(tempConfig)).toBe(true); - return null; - }); + it("treats unknown skill existence as fatal for remove and closes the control", async () => { + skillInstall.checkExisting.mockResolvedValue(null); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); await removeSandboxSkill("alpha", { name: "demo-skill" }); @@ -143,16 +144,11 @@ describe("sandbox skill action orchestration", () => { ); expect(skillInstall.removeSkill).not.toHaveBeenCalled(); expect(skillInstall.verifyRemove).not.toHaveBeenCalled(); - expect(tempConfig).not.toBe(""); - expect(fs.existsSync(tempConfig)).toBe(false); + expect(closeControl).toHaveBeenCalledOnce(); }); - it("reports an absent skill for remove and deletes the temp SSH config", async () => { - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx) => { - tempConfig = ctx.configFile; - return false; - }); + it("reports an absent skill for remove and closes the control", async () => { + skillInstall.checkExisting.mockResolvedValue(false); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); await removeSandboxSkill("alpha", { name: "demo-skill" }); @@ -161,14 +157,12 @@ describe("sandbox skill action orchestration", () => { expect(error).toHaveBeenCalledWith(" Skill 'demo-skill' is not installed in sandbox 'alpha'."); expect(skillInstall.removeSkill).not.toHaveBeenCalled(); expect(skillInstall.verifyRemove).not.toHaveBeenCalled(); - expect(tempConfig).not.toBe(""); - expect(fs.existsSync(tempConfig)).toBe(false); + expect(closeControl).toHaveBeenCalledOnce(); }); - it("removes and verifies an existing skill, then deletes the temp SSH config", async () => { - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx, resolvedPaths) => { - tempConfig = ctx.configFile; + it("removes and verifies an existing skill, then closes the selected control", async () => { + skillInstall.checkExisting.mockImplementation(async (ctx, resolvedPaths) => { + expect(ctx.control).toBe(control); expect(resolvedPaths).toBe(paths); return true; }); @@ -179,17 +173,13 @@ describe("sandbox skill action orchestration", () => { expect(ensureLiveSandboxOrExit).toHaveBeenCalledWith("alpha"); expect(getSessionAgent).toHaveBeenCalledWith("alpha"); expect(skillInstall.resolveSkillPaths).toHaveBeenCalledWith(agent, "demo-skill"); - expect(skillInstall.removeSkill).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), - paths, - ); + expect(skillInstall.removeSkill).toHaveBeenCalledWith({ control, sandboxName: "alpha" }, paths); expect(skillInstall.verifyRemove).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), + { control, sandboxName: "alpha" }, paths, ); expect(log).toHaveBeenCalledWith(expect.stringContaining("Skill 'demo-skill' removed")); - expect(fs.existsSync(tempConfig)).toBe(false); - expectTempSshConfigCleanedUp(tempConfig); + expect(closeControl).toHaveBeenCalledOnce(); expect(process.exitCode).toBeUndefined(); }); @@ -207,19 +197,15 @@ describe("sandbox skill action orchestration", () => { } expect(ensureLiveSandboxOrExit).toHaveBeenCalledWith("alpha"); - expect(captureSandboxSshConfig).not.toHaveBeenCalled(); + expect(selectOpenShellSandboxControlForMutation).not.toHaveBeenCalled(); expect(skillInstall.uploadDirectory).not.toHaveBeenCalled(); }); - it("continues skill install when the existence probe is unknown because upload plus verify are authoritative", async () => { + it("fails skill install before upload when the existence probe is inconclusive", async () => { const skillDir = makeSkillDir(); - let tempConfig = ""; - skillInstall.checkExisting.mockImplementation((ctx) => { - tempConfig = ctx.configFile; - return null; - }); + skillInstall.checkExisting.mockResolvedValue(null); const error = vi.spyOn(console, "error").mockImplementation(() => undefined); - const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.spyOn(console, "log").mockImplementation(() => undefined); try { await installSandboxSkill("alpha", { command: "install", path: skillDir }); @@ -228,22 +214,37 @@ describe("sandbox skill action orchestration", () => { } expect(error).toHaveBeenCalledWith( - expect.stringContaining( - "Warning: could not check sandbox for existing skill — treating as fresh install.", - ), + " Could not check if skill 'demo-skill' exists — sandbox may be unreachable. No files were uploaded.", ); + expect(skillInstall.uploadDirectory).not.toHaveBeenCalled(); + expect(skillInstall.postInstall).not.toHaveBeenCalled(); + expect(skillInstall.verifyInstall).not.toHaveBeenCalled(); + expect(closeControl).toHaveBeenCalledOnce(); + expect(process.exitCode).toBe(1); + }); + + it("installs when the existence probe confirms the skill is absent", async () => { + const skillDir = makeSkillDir(); + skillInstall.checkExisting.mockResolvedValue(false); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + + try { + await installSandboxSkill("alpha", { command: "install", path: skillDir }); + } finally { + fs.rmSync(skillDir, { recursive: true, force: true }); + } + expect(skillInstall.uploadDirectory).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), + { control, sandboxName: "alpha" }, skillDir, paths.uploadDir, ); expect(skillInstall.verifyInstall).toHaveBeenCalledWith( - expect.objectContaining({ configFile: tempConfig, sandboxName: "alpha" }), + { control, sandboxName: "alpha" }, paths, ); expect(log).toHaveBeenCalledWith(expect.stringContaining("Skill 'demo-skill' installed")); - expect(fs.existsSync(tempConfig)).toBe(false); - expectTempSshConfigCleanedUp(tempConfig); + expect(closeControl).toHaveBeenCalledOnce(); expect(process.exitCode).toBeUndefined(); }); }); diff --git a/src/lib/actions/sandbox/skill-install.ts b/src/lib/actions/sandbox/skill-install.ts index 3eb9d547257..6b81d099c20 100644 --- a/src/lib/actions/sandbox/skill-install.ts +++ b/src/lib/actions/sandbox/skill-install.ts @@ -3,13 +3,16 @@ import fs from "node:fs"; import path from "node:path"; -import { captureSandboxSshConfig } from "../../adapters/openshell/runtime"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { + type OpenShellMutationControlSelection, + selectOpenShellSandboxControlForMutation, +} from "../../adapters/openshell/sandbox-control-routing"; import * as agentRuntime from "../../agent/runtime"; import { CLI_NAME } from "../../cli/branding"; import { D, G, R, YW } from "../../cli/terminal-style"; -import { createTempSshConfig } from "../../sandbox/temp-ssh-config"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as skillInstall from "../../skill-install"; +import * as registry from "../../state/registry"; import { ensureLiveSandboxOrExit } from "./gateway-state"; export function printSkillInstallUsage(): void { @@ -80,6 +83,18 @@ export function printPluginInstallHint(): void { ); } +function selectSkillControl(sandboxName: string): OpenShellMutationControlSelection { + try { + return selectOpenShellSandboxControlForMutation( + resolveSandboxGatewayName(registry.getSandbox(sandboxName)), + ); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + console.error(` Failed to configure OpenShell sandbox execution: ${detail}`); + process.exit(1); + } +} + /** * Remove an installed skill from a live sandbox by name. */ @@ -114,21 +129,12 @@ export async function removeSandboxSkill( const agent = agentRuntime.getSessionAgent(sandboxName); const paths = skillInstall.resolveSkillPaths(agent, skillName); - const sshConfigResult = captureSandboxSshConfig(sandboxName, { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (sshConfigResult.status !== 0) { - console.error(" Failed to obtain SSH configuration for the sandbox."); - process.exit(1); - } - - const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ssh-skill-"); + const selected = selectSkillControl(sandboxName); try { - const ctx = { configFile: tmpSshConfig.file, sandboxName }; + const ctx = { control: selected.control, sandboxName }; - const existsCheck = skillInstall.checkExisting(ctx, paths); + const existsCheck = await skillInstall.checkExisting(ctx, paths); if (existsCheck === null) { console.error( ` Could not check if skill '${skillName}' exists — sandbox may be unreachable.`, @@ -142,7 +148,7 @@ export async function removeSandboxSkill( return; } - const result = skillInstall.removeSkill(ctx, paths); + const result = await skillInstall.removeSkill(ctx, paths); for (const msg of result.messages) { if (msg.startsWith("Warning:")) { console.error(` ${YW}${msg}${R}`); @@ -151,7 +157,7 @@ export async function removeSandboxSkill( } } - const gone = skillInstall.verifyRemove(ctx, paths); + const gone = await skillInstall.verifyRemove(ctx, paths); if (gone) { console.log(` ${G}✓${R} Skill '${skillName}' removed`); } else { @@ -161,7 +167,7 @@ export async function removeSandboxSkill( return; } } finally { - tmpSshConfig.cleanup(); + selected.close(); } } @@ -273,39 +279,28 @@ export async function installSandboxSkill( const agent = agentRuntime.getSessionAgent(sandboxName); const paths = skillInstall.resolveSkillPaths(agent, frontmatter.name); - // 4. Get SSH config - const sshConfigResult = captureSandboxSshConfig(sandboxName, { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (sshConfigResult.status !== 0) { - console.error(" Failed to obtain SSH configuration for the sandbox."); - process.exit(1); - } - - const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ssh-skill-"); + // 4. Select one control-plane transport before any mutation. + const selected = selectSkillControl(sandboxName); try { - const ctx = { configFile: tmpSshConfig.file, sandboxName }; - - // 5. Check if skill already exists (update vs fresh install). This probe is - // advisory for install only: stale SSH config files and transient remote - // shell startup failures can make the stat probe inconclusive even when a - // subsequent upload succeeds. Upload plus verifyInstall() remain the - // source of truth for install success; remove keeps null fatal because it - // is destructive. Once OpenShell exposes a typed stat API or SSH probe - // failures are reliably distinguishable from absent dirs across supported - // versions, remove this fallback and fail before upload. - const existingCheck = skillInstall.checkExisting(ctx, paths); + const ctx = { control: selected.control, sandboxName }; + + // 5. Check if skill already exists (update vs fresh install). A successful + // sentinel response distinguishes absence from an existing directory; + // an inconclusive control result is an execution failure, not absence. + // Fail closed before upload so a probe failure cannot precede mutation. + const existingCheck = await skillInstall.checkExisting(ctx, paths); if (existingCheck === null) { console.error( - ` ${YW}Warning: could not check sandbox for existing skill — treating as fresh install.${R}`, + ` Could not check if skill '${frontmatter.name}' exists — sandbox may be unreachable. No files were uploaded.`, ); + process.exitCode = 1; + return; } const isUpdate = existingCheck === true; // 6. Upload skill directory - const { uploaded, failed } = skillInstall.uploadDirectory(ctx, skillDir, paths.uploadDir); + const { uploaded, failed } = await skillInstall.uploadDirectory(ctx, skillDir, paths.uploadDir); if (failed.length > 0) { console.error(` Failed to upload ${failed.length} file(s): ${failed.join(", ")}`); process.exit(1); @@ -315,7 +310,7 @@ export async function installSandboxSkill( // 7. Post-install (OpenClaw mirror + refresh, or restart hint). // OpenClaw caches skill content per session, so always refresh the // session index after an install/update to avoid stale SKILL.md data. - const post = skillInstall.postInstall(ctx, paths, skillDir); + const post = await skillInstall.postInstall(ctx, paths, skillDir); for (const msg of post.messages) { if (msg.startsWith("Warning:")) { console.error(` ${YW}${msg}${R}`); @@ -325,7 +320,7 @@ export async function installSandboxSkill( } // 8. Verify - const verified = skillInstall.verifyInstall(ctx, paths); + const verified = await skillInstall.verifyInstall(ctx, paths); if (verified) { const verb = isUpdate ? "updated" : "installed"; console.log(` ${G}✓${R} Skill '${frontmatter.name}' ${verb}`); @@ -337,6 +332,6 @@ export async function installSandboxSkill( process.exit(1); } } finally { - tmpSshConfig.cleanup(); + selected.close(); } } diff --git a/src/lib/adapters/openshell/grpc-gateway-config.ts b/src/lib/adapters/openshell/grpc-gateway-config.ts index ace3611bf52..4492dc915db 100644 --- a/src/lib/adapters/openshell/grpc-gateway-config.ts +++ b/src/lib/adapters/openshell/grpc-gateway-config.ts @@ -38,6 +38,16 @@ export interface ResolvedOpenShellGrpcGateway { clientConfig: OpenShellGrpcClientConfig; } +/** Direct gRPC cannot traverse OpenShell's CLI-owned Cloudflare edge tunnel. */ +export class OpenShellGrpcEdgeTunnelRequiredError extends Error { + constructor() { + super( + "OpenShell Cloudflare JWT gateways require the OpenShell edge tunnel and are not supported by the direct gRPC client", + ); + this.name = "OpenShellGrpcEdgeTunnelRequiredError"; + } +} + function validateGatewayName(name: string): void { if ( !name || @@ -234,9 +244,7 @@ export function resolveOpenShellGrpcGateway( } clientConfig = oidcConfig(metadata.gateway_endpoint, gatewayDir, nowSeconds); } else if (authMode === "cloudflare_jwt") { - throw new Error( - "OpenShell Cloudflare JWT gateways require the OpenShell edge tunnel and are not supported by the direct gRPC client", - ); + throw new OpenShellGrpcEdgeTunnelRequiredError(); } else { throw new Error(`Unsupported OpenShell gateway auth mode '${authMode}'`); } diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index c53badef11b..f7ed4427781 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import { OpenShellGrpcEdgeTunnelRequiredError } from "./grpc-gateway-config"; import { type GrpcOpenShellSandboxControl, OpenShellGrpcPreDispatchError, @@ -14,7 +15,10 @@ import { openShellExecRequestValidationFailure, type SandboxExecResult, } from "./sandbox-control"; -import { execSandboxReadOnlyWithGrpcFallback } from "./sandbox-control-routing"; +import { + execSandboxReadOnlyWithGrpcFallback, + selectOpenShellSandboxControlForMutation, +} from "./sandbox-control-routing"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: SandboxExecResult) { @@ -30,6 +34,7 @@ function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: Sandbox const debug = vi.fn(); return { close, + cli, grpcExec, cliExec, createCli, @@ -296,3 +301,74 @@ describe("read-only OpenShell sandbox control routing", () => { ); }); }); + +describe("mutating OpenShell sandbox control routing", () => { + it("selects direct gRPC before a mutation and exposes its close hook", () => { + const test = dependencies({ status: 0, stdout: "grpc", stderr: "" }); + + const selected = selectOpenShellSandboxControlForMutation("nemoclaw", test.deps); + + expect(selected).toMatchObject({ control: expect.any(Object), transport: "grpc" }); + expect(selected.control).not.toBe(test.cli); + expect(test.createCli).not.toHaveBeenCalled(); + selected.close(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("preselects the CLI only for the edge-tunnel auth mode", () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + test.createGrpc.mockImplementation(() => { + throw new OpenShellGrpcEdgeTunnelRequiredError(); + }); + + const selected = selectOpenShellSandboxControlForMutation("edge", test.deps); + + expect(selected).toEqual({ + control: test.cli, + transport: "cli-edge-tunnel", + close: expect.any(Function), + }); + expect(test.createCli).toHaveBeenCalledWith("edge"); + selected.close(); + expect(test.close).not.toHaveBeenCalled(); + }); + + it("fails closed when the mutation CLI factory refuses an endpoint override", () => { + const refusal = new Error("Unset OPENSHELL_GATEWAY_ENDPOINT and retry"); + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + test.createGrpc.mockImplementation(() => { + throw new OpenShellGrpcEdgeTunnelRequiredError(); + }); + test.createCli.mockImplementation(() => { + throw refusal; + }); + + expect(() => selectOpenShellSandboxControlForMutation("edge", test.deps)).toThrow(refusal); + + expect(test.createCli).toHaveBeenCalledWith("edge"); + expect(test.cliExec).not.toHaveBeenCalled(); + }); + + it("does not turn a completed mutation into failure when the client cannot close", () => { + const test = dependencies({ status: 0, stdout: "grpc", stderr: "" }); + const error = new Error("close failed"); + test.close.mockImplementation(() => { + throw error; + }); + const selected = selectOpenShellSandboxControlForMutation("nemoclaw", test.deps); + + expect(() => selected.close()).not.toThrow(); + expect(test.debug).toHaveBeenCalledWith("OpenShell direct gRPC client close failed", error); + }); + + it("fails before dispatch for every other direct-client configuration error", () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + const error = new Error("invalid mTLS material"); + test.createGrpc.mockImplementation(() => { + throw error; + }); + + expect(() => selectOpenShellSandboxControlForMutation("nemoclaw", test.deps)).toThrow(error); + expect(test.cliExec).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index c5f6a366010..c0f85a6592a 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { log } from "../../cli/logger"; -import { createGrpcOpenShellSandboxControlForGateway } from "./grpc-gateway-config"; +import { + createGrpcOpenShellSandboxControlForGateway, + OpenShellGrpcEdgeTunnelRequiredError, +} from "./grpc-gateway-config"; import { type GrpcOpenShellSandboxControl, OpenShellGrpcPreDispatchError, @@ -30,6 +33,45 @@ const defaultDependencies: ReadOnlyRoutingDependencies = { debug: (message, context) => log.debug(message, context), }; +export interface OpenShellMutationControlSelection { + control: OpenShellSandboxControl; + transport: "grpc" | "cli-edge-tunnel"; + close(): void; +} + +/** + * Select one transport before a mutating workflow starts. Direct gRPC is the + * default. The CLI is selected only for the explicit Cloudflare edge-tunnel + * mode that a direct client cannot traverse. This function never retries an + * operation after dispatch. + */ +export function selectOpenShellSandboxControlForMutation( + gatewayName: string, + dependencies: ReadOnlyRoutingDependencies = defaultDependencies, +): OpenShellMutationControlSelection { + try { + const grpc = dependencies.createGrpc(gatewayName); + return { + control: grpc, + transport: "grpc", + close: () => { + try { + grpc.close(); + } catch (error) { + dependencies.debug("OpenShell direct gRPC client close failed", error); + } + }, + }; + } catch (error) { + if (!(error instanceof OpenShellGrpcEdgeTunnelRequiredError)) throw error; + return { + control: dependencies.createCli(gatewayName), + transport: "cli-edge-tunnel", + close: () => {}, + }; + } +} + /** * Prefer direct gRPC for the OpenClaw session-list read and retry through the * OpenShell CLI only when configuration or sandbox lookup fails before Exec is diff --git a/src/lib/skill-install.test.ts b/src/lib/skill-install.test.ts index d3d1438327b..72155f7deec 100644 --- a/src/lib/skill-install.test.ts +++ b/src/lib/skill-install.test.ts @@ -12,10 +12,18 @@ import { postInstall, resolveSkillPaths, shellQuote, + uploadFile, validateRelativePath, verifyInstall, } from "./skill-install"; +const controlContext = { + control: { + exec: async () => ({ status: 0, stdout: "", stderr: "" }), + }, + sandboxName: "alpha", +}; + describe("parseFrontmatter", () => { it("extracts name from valid frontmatter", () => { const result = parseFrontmatter("---\nname: my-skill\ndescription: test\n---\n# Body"); @@ -251,17 +259,17 @@ describe("resolveSkillPaths", () => { }); describe("postInstall", () => { - it("refreshes OpenClaw sessions after installing an updated skill", () => { + it("refreshes OpenClaw sessions after installing an updated skill", async () => { const skillDir = mkdtempSync(join(tmpdir(), "skill-postinstall-")); const commands: string[] = []; try { writeFileSync(skillDir + "/SKILL.md", "---\nname: weather\n---\n# Weather\n"); - const result = postInstall( - { configFile: "/tmp/ssh-config", sandboxName: "alpha" }, + const result = await postInstall( + controlContext, resolveSkillPaths(null, "weather"), skillDir, { - sshExecImpl: (_ctx, command) => { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "", stderr: "" }; }, @@ -277,7 +285,7 @@ describe("postInstall", () => { } }); - it("mirrors the uploaded skill into the OpenClaw home dir so the agent loads it", () => { + it("mirrors the uploaded skill into the OpenClaw home dir so the agent loads it", async () => { // Regression for #4819: on sandboxes whose agent $HOME differs from the // OpenClaw state dir, `skills list` shows the upload dir while the agent // loads skills from $HOME/.openclaw/skills. Install must populate that @@ -287,8 +295,8 @@ describe("postInstall", () => { try { writeFileSync(skillDir + "/SKILL.md", "---\nname: report-writer\n---\n# Report\n"); const paths = resolveSkillPaths(null, "report-writer"); - postInstall({ configFile: "/tmp/ssh-config", sandboxName: "alpha" }, paths, skillDir, { - sshExecImpl: (_ctx, command) => { + await postInstall(controlContext, paths, skillDir, { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "", stderr: "" }; }, @@ -307,24 +315,19 @@ describe("postInstall", () => { } }); - it("warns when the OpenClaw home mirror cannot be created", () => { + it("warns when the OpenClaw home mirror cannot be created", async () => { const skillDir = mkdtempSync(join(tmpdir(), "skill-postinstall-mirror-fail-")); try { writeFileSync(skillDir + "/SKILL.md", "---\nname: report-writer\n---\n# Report\n"); const paths = resolveSkillPaths(null, "report-writer"); - const result = postInstall( - { configFile: "/tmp/ssh-config", sandboxName: "alpha" }, - paths, - skillDir, - { - sshExecImpl: (_ctx, command) => ({ - // Fail only the mirror command; session refresh still succeeds. - status: command.includes("$HOME/.openclaw/skills") ? 1 : 0, - stdout: "", - stderr: "", - }), - }, - ); + const result = await postInstall(controlContext, paths, skillDir, { + execImpl: async (_ctx, command) => ({ + // Fail only the mirror command; session refresh still succeeds. + status: command.includes("$HOME/.openclaw/skills") ? 1 : 0, + stdout: "", + stderr: "", + }), + }); expect(result.success).toBe(true); expect(result.messages.some((m) => m.startsWith("Warning:") && m.includes("mirror"))).toBe( @@ -337,14 +340,14 @@ describe("postInstall", () => { }); describe("verifyInstall", () => { - it("requires SKILL.md in the OpenClaw home mirror, not only the upload dir (#4819)", () => { + it("requires SKILL.md in the OpenClaw home mirror, not only the upload dir (#4819)", async () => { // The agent loads skills from the home mirror, so an install whose mirror // copy failed must NOT verify as installed — otherwise the CLI reports // success while the skill stays invisible to the agent. const paths = resolveSkillPaths(null, "report-writer"); const commands: string[] = []; - const ok = verifyInstall({ configFile: "/tmp/ssh-config", sandboxName: "alpha" }, paths, { - sshExecImpl: (_ctx, command) => { + const ok = await verifyInstall(controlContext, paths, { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "EXISTS", stderr: "" }; }, @@ -357,14 +360,38 @@ describe("verifyInstall", () => { ).toBe(true); }); - it("returns false when the upload dir has SKILL.md but the home mirror does not", () => { + it("returns false when the upload dir has SKILL.md but the home mirror does not", async () => { const paths = resolveSkillPaths(null, "report-writer"); - const ok = verifyInstall({ configFile: "/tmp/ssh-config", sandboxName: "alpha" }, paths, { + const ok = await verifyInstall(controlContext, paths, { // A combined `test -f A && test -f B` shell command fails (non-zero, // no EXISTS) when the mirror file is absent. - sshExecImpl: () => ({ status: 1, stdout: "", stderr: "" }), + execImpl: async () => ({ status: 1, stdout: "", stderr: "" }), }); expect(ok).toBe(false); }); }); + +describe("uploadFile", () => { + it("sends file bytes through sandbox exec stdin", async () => { + const dir = mkdtempSync(join(tmpdir(), "skill-upload-")); + const localPath = join(dir, "binary.dat"); + const input = Buffer.from([0, 255, 10]); + writeFileSync(localPath, input); + let observedInput: string | Buffer | undefined; + try { + const result = await uploadFile(controlContext, localPath, "/sandbox/skill", "binary.dat", { + execImpl: async (_ctx, command, options) => { + expect(command).toBe("mkdir -p '/sandbox/skill' && cat > '/sandbox/skill/binary.dat'"); + observedInput = options?.input; + return { status: 0, stdout: "", stderr: "" }; + }, + }); + + expect(result?.status).toBe(0); + expect(observedInput).toEqual(input); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/lib/skill-install.ts b/src/lib/skill-install.ts index ffdcaf06e70..f6f5a6d7724 100644 --- a/src/lib/skill-install.ts +++ b/src/lib/skill-install.ts @@ -3,7 +3,7 @@ // // Skill install/remove logic for `nemoclaw skill install ` // and `nemoclaw skill remove `. -// Validates a local SKILL.md, uploads it to the sandbox via SSH, and +// Validates a local SKILL.md, uploads it through OpenShell sandbox exec, and // performs agent-specific post-install steps (session refresh for // OpenClaw). Non-OpenClaw agents get a "restart gateway" hint until a // generic refresh contract is defined in the manifest schema. @@ -16,18 +16,19 @@ import YAML from "yaml"; import { isObjectRecord } from "./core/json-types"; import { validateSkillName } from "./skill-name"; -import type { SshContext, SshResult } from "./skill-remote"; -import { shellQuote, sshExec } from "./skill-remote"; +import type { SandboxCommandResult, SandboxControlContext, SandboxExecImpl } from "./skill-remote"; +import { sandboxExec, shellQuote } from "./skill-remote"; export { validateSkillName } from "./skill-name"; export { checkExisting, type RemoveResult, removeSkill, - type SshContext, - type SshResult, + type SandboxCommandResult, + type SandboxControlContext, + type SandboxExecImpl, + sandboxExec, shellQuote, - sshExec, verifyRemove, } from "./skill-remote"; @@ -146,19 +147,20 @@ export function validateRelativePath(rel: string): boolean { // ── Upload helpers ─────────────────────────────────────────────── /** - * Upload a file to the sandbox by piping its content through SSH stdin. + * Upload a file to the sandbox through the selected OpenShell control plane. * Creates the target directory and writes the file in a single remote command. */ -export function uploadFile( - ctx: SshContext, +export async function uploadFile( + ctx: SandboxControlContext, localPath: string, remoteDir: string, remoteFilename: string, -): SshResult | null { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const content = fs.readFileSync(localPath); const remotePath = `${remoteDir}/${remoteFilename}`; const script = `mkdir -p ${shellQuote(remoteDir)} && cat > ${shellQuote(remotePath)}`; - return sshExec(ctx, script, { input: content }); + return (opts.execImpl ?? sandboxExec)(ctx, script, { input: content }); } export interface CollectedFiles { @@ -171,7 +173,7 @@ export interface CollectedFiles { * Collect files under `dir` recursively, returning paths relative to `dir`. * Dotfiles (names starting with `.`) are excluded by default and reported * separately so the caller can warn. Paths with unsafe characters are - * rejected to prevent shell injection when interpolated into SSH commands. + * rejected to prevent shell injection when interpolated into remote commands. */ export function collectFiles(dir: string): CollectedFiles { const files: string[] = []; @@ -204,11 +206,17 @@ export function collectFiles(dir: string): CollectedFiles { * Upload an entire skill directory to the sandbox, preserving subdirectory * structure. Rejects files with unsafe path characters and skips dotfiles. */ -export function uploadDirectory( - ctx: SshContext, +export async function uploadDirectory( + ctx: SandboxControlContext, localDir: string, remoteDir: string, -): { uploaded: number; failed: string[]; skippedDotfiles: string[]; unsafePaths: string[] } { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise<{ + uploaded: number; + failed: string[]; + skippedDotfiles: string[]; + unsafePaths: string[]; +}> { const { files, skippedDotfiles, unsafePaths } = collectFiles(localDir); if (unsafePaths.length > 0) { return { uploaded: 0, failed: unsafePaths, skippedDotfiles, unsafePaths }; @@ -217,7 +225,7 @@ export function uploadDirectory( for (const rel of files) { const localFile = path.join(localDir, rel); const remoteSubdir = rel.includes("/") ? `${remoteDir}/${path.dirname(rel)}` : remoteDir; - const result = uploadFile(ctx, localFile, remoteSubdir, path.basename(rel)); + const result = await uploadFile(ctx, localFile, remoteSubdir, path.basename(rel), opts); if (!result || result.status !== 0) { failed.push(rel); } @@ -229,17 +237,17 @@ export function uploadDirectory( * Run post-install steps: session refresh for OpenClaw, or * non-OpenClaw restart hint. */ -export function postInstall( - ctx: SshContext, +export async function postInstall( + ctx: SandboxControlContext, paths: SkillPaths, _localSkillDir: string, opts: { skipRefresh?: boolean; - sshExecImpl?: typeof sshExec; + execImpl?: SandboxExecImpl; } = {}, -): { success: boolean; messages: string[] } { +): Promise<{ success: boolean; messages: string[] }> { const messages: string[] = []; - const runSsh = opts.sshExecImpl ?? sshExec; + const run = opts.execImpl ?? sandboxExec; if (paths.isOpenClaw) { // Mirror the uploaded skill into the agent's home dir @@ -259,7 +267,7 @@ export function postInstall( // restricted to [A-Za-z0-9._-] by parseFrontmatter / the name regex. const dst = `"${paths.mirrorDir}"`; const mirrorParent = `"${paths.mirrorDir.slice(0, paths.mirrorDir.lastIndexOf("/"))}"`; - const mirrorResult = runSsh( + const mirrorResult = await run( ctx, `[ ${src} -ef ${dst} ] || { mkdir -p ${mirrorParent} && rm -rf ${dst} && cp -a ${src} ${dst}; }`, ); @@ -273,7 +281,7 @@ export function postInstall( // Clear sessions.json so OpenClaw re-discovers skills on the next // session even after an in-place skill update. if (paths.sessionFile && !opts.skipRefresh) { - const refreshResult = runSsh(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); + const refreshResult = await run(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); if (!refreshResult || refreshResult.status !== 0) { messages.push("Warning: failed to clear sessions (agent may need manual restart)"); } @@ -294,11 +302,11 @@ export function postInstall( * otherwise the CLI reports success while the skill stays invisible to the * agent. This mirrors verifyRemove(), which already checks both paths. */ -export function verifyInstall( - ctx: SshContext, +export async function verifyInstall( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): boolean { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const checks = [`test -f ${shellQuote(`${paths.uploadDir}/SKILL.md`)}`]; if (paths.isOpenClaw && paths.mirrorDir) { // mirrorDir contains $HOME, which must expand on the remote shell, so we @@ -306,7 +314,6 @@ export function verifyInstall( // restricted to [A-Za-z0-9._-]. checks.push(`test -f "${paths.mirrorDir}/SKILL.md"`); } - const runSsh = opts.sshExecImpl ?? sshExec; - const result = runSsh(ctx, `${checks.join(" && ")} && echo EXISTS`); + const result = await (opts.execImpl ?? sandboxExec)(ctx, `${checks.join(" && ")} && echo EXISTS`); return result !== null && result.stdout === "EXISTS"; } diff --git a/src/lib/skill-remote.test.ts b/src/lib/skill-remote.test.ts index 729514f657d..8a45b2a9f42 100644 --- a/src/lib/skill-remote.test.ts +++ b/src/lib/skill-remote.test.ts @@ -1,76 +1,153 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxControl } from "./adapters/openshell/sandbox-control"; import { resolveSkillPaths } from "./skill-install"; import { validateSkillName } from "./skill-name"; -import { checkExisting, removeSkill, verifyRemove } from "./skill-remote"; +import { + checkExisting, + removeSkill, + type SandboxControlContext, + sandboxExec, + verifyRemove, +} from "./skill-remote"; + +function context( + exec: OpenShellSandboxControl["exec"] = vi.fn(async () => { + throw new Error("unreachable"); + }), +): SandboxControlContext { + return { control: { exec }, sandboxName: "test-sandbox" }; +} describe("validateSkillName", () => { - it("accepts valid skill names", () => { - expect(validateSkillName("my-skill")).toBe(true); - expect(validateSkillName("my_skill")).toBe(true); - expect(validateSkillName("my.skill")).toBe(true); - expect(validateSkillName("MySkill123")).toBe(true); - expect(validateSkillName("digicon-zeiss-ai-strategy")).toBe(true); - }); - - it("rejects empty string", () => { - expect(validateSkillName("")).toBe(false); - }); - - it("rejects names with spaces", () => { - expect(validateSkillName("my skill")).toBe(false); - }); - - it("rejects names with shell metacharacters", () => { - expect(validateSkillName("my;skill")).toBe(false); - expect(validateSkillName("my$skill")).toBe(false); - expect(validateSkillName("my/skill")).toBe(false); - expect(validateSkillName("../escape")).toBe(false); - expect(validateSkillName("my`skill`")).toBe(false); - }); + it.each([ + "my-skill", + "my_skill", + "my.skill", + "MySkill123", + "digicon-zeiss-ai-strategy", + ])("accepts %s", (name) => expect(validateSkillName(name)).toBe(true)); + + it.each([ + "", + "my skill", + "my;skill", + "my$skill", + "my/skill", + "../escape", + "my`skill`", + ".", + "..", + ])("rejects %s", (name) => expect(validateSkillName(name)).toBe(false)); +}); - it("rejects dot and double-dot to prevent directory traversal on rm -rf", () => { - expect(validateSkillName(".")).toBe(false); - expect(validateSkillName("..")).toBe(false); +describe("sandboxExec", () => { + it("runs one shell command through the selected control without transport retry", async () => { + const exec = vi.fn(async () => ({ status: 0, stdout: "ok\n", stderr: " warning\n" })); + const ctx = context(exec); + + await expect( + sandboxExec(ctx, "cat > /tmp/file", { input: Buffer.from("body") }), + ).resolves.toEqual({ + status: 0, + stdout: "ok", + stderr: "warning", + }); + expect(exec).toHaveBeenCalledOnce(); + expect(exec).toHaveBeenCalledWith({ + sandboxName: "test-sandbox", + command: ["sh", "-lc", "cat > /tmp/file"], + stdin: Buffer.from("body"), + timeoutMs: 30_000, + }); }); }); -describe("removeSkill (unit — no SSH)", () => { - it("returns success=false and a warning when sshExec returns null (sandbox unreachable)", () => { - const paths = resolveSkillPaths(null, "test-skill"); - - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - const result = removeSkill(ctx, paths); +describe("removeSkill", () => { + it("returns failure and warnings when sandbox execution is unavailable", async () => { + const result = await removeSkill(context(), resolveSkillPaths(null, "test-skill")); expect(result.success).toBe(false); expect(result.removedUploadDir).toBe(false); - expect(result.messages.some((m) => m.startsWith("Warning:"))).toBe(true); + expect(result.messages.some((message) => message.startsWith("Warning:"))).toBe(true); }); - it("success is false for OpenClaw when mirrorDir removal fails even if uploadDir was removed", () => { - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; - const paths = resolveSkillPaths(null, "test-skill"); - const result = removeSkill(ctx, paths, { - sshExecImpl: (_ctx, command) => ({ + it("fails when the OpenClaw mirror removal fails after upload removal", async () => { + const result = await removeSkill(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => ({ status: command.includes("$HOME/.openclaw/skills") ? 1 : 0, stdout: "", stderr: "", }), }); - expect(result.removedUploadDir).toBe(true); - expect(result.removedMirrorDir).toBe(false); - expect(result.success).toBe(false); + expect(result).toMatchObject({ + removedUploadDir: true, + removedMirrorDir: false, + success: false, + }); }); - it("removes OpenClaw upload and mirror dirs, then clears sessions", () => { - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; + it("converges when retried after removing only the upload directory", async () => { const paths = resolveSkillPaths(null, "test-skill"); + const mirrorDir = paths.mirrorDir!; + const unrelatedPath = "/sandbox/.openclaw/skills/other-skill"; + const clearSessions = `printf '{}' > '${paths.sessionFile}'`; + const verifyGone = `test ! -e '${paths.uploadDir}' && test ! -e "${mirrorDir}" && echo GONE || echo EXISTS`; + const scriptedResults = [ + { + command: `rm -rf '${paths.uploadDir}'`, + result: { status: 0, stdout: "", stderr: "" }, + }, + { + command: `rm -rf "${mirrorDir}"`, + result: { status: 1, stdout: "", stderr: "failed" }, + }, + { command: clearSessions, result: { status: 0, stdout: "", stderr: "" } }, + { + command: `rm -rf '${paths.uploadDir}'`, + result: { status: 0, stdout: "", stderr: "" }, + }, + { + command: `rm -rf "${mirrorDir}"`, + result: { status: 0, stdout: "", stderr: "" }, + }, + { command: clearSessions, result: { status: 0, stdout: "", stderr: "" } }, + { + command: verifyGone, + result: { status: 0, stdout: "GONE", stderr: "" }, + }, + ]; + const execImpl = vi.fn(async (_ctx: SandboxControlContext, command: string) => { + const next = scriptedResults.shift(); + expect(next).toBeDefined(); + expect(command).toBe(next!.command); + expect(command).not.toContain(unrelatedPath); + return next!.result; + }); + + await expect(removeSkill(context(), paths, { execImpl })).resolves.toMatchObject({ + removedUploadDir: true, + removedMirrorDir: false, + success: false, + }); + await expect(removeSkill(context(), paths, { execImpl })).resolves.toMatchObject({ + clearedSessions: true, + removedMirrorDir: true, + removedUploadDir: true, + success: true, + }); + await expect(verifyRemove(context(), paths, { execImpl })).resolves.toBe(true); + + expect(scriptedResults).toEqual([]); + }); + + it("removes OpenClaw upload and mirror dirs, then clears sessions", async () => { const commands: string[] = []; - const result = removeSkill(ctx, paths, { - sshExecImpl: (_ctx, command) => { + const result = await removeSkill(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "", stderr: "" }; }, @@ -86,28 +163,17 @@ describe("removeSkill (unit — no SSH)", () => { }); }); -describe("verifyRemove (unit — no SSH)", () => { - it("returns false when SSH is unreachable (conservative — treat failure as not-gone)", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(verifyRemove(ctx, paths)).toBe(false); - }); - - it("returns false for non-OpenClaw paths when SSH is unreachable", () => { - const paths = resolveSkillPaths( - { name: "hermes", configPaths: { dir: "/sandbox/.hermes" } }, - "test-skill", +describe("verifyRemove", () => { + it("fails conservatively when sandbox execution is unavailable", async () => { + await expect(verifyRemove(context(), resolveSkillPaths(null, "test-skill"))).resolves.toBe( + false, ); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(verifyRemove(ctx, paths)).toBe(false); }); - it("verifies both OpenClaw skill directories are gone", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; + it("verifies both OpenClaw skill directories are gone", async () => { const commands: string[] = []; - const gone = verifyRemove(ctx, paths, { - sshExecImpl: (_ctx, command) => { + const gone = await verifyRemove(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "GONE", stderr: "" }; }, @@ -120,28 +186,25 @@ describe("verifyRemove (unit — no SSH)", () => { }); }); -describe("checkExisting (unit — no SSH)", () => { - it("returns null when SSH is unreachable for OpenClaw paths", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(checkExisting(ctx, paths)).toBeNull(); +describe("checkExisting", () => { + it("maps a selected-control execution failure to an inconclusive result", async () => { + await expect( + checkExisting(context(), resolveSkillPaths(null, "test-skill")), + ).resolves.toBeNull(); }); - it("returns null when SSH is unreachable for non-OpenClaw paths", () => { - const paths = resolveSkillPaths( - { name: "hermes", configPaths: { dir: "/sandbox/.hermes" } }, - "test-skill", - ); - const ctx = { configFile: "/nonexistent/ssh.conf", sandboxName: "test-sandbox" }; - expect(checkExisting(ctx, paths)).toBeNull(); + it("maps a successful absence sentinel to false", async () => { + const execImpl = vi.fn(async () => ({ status: 0, stdout: "ABSENT", stderr: "" })); + + await expect( + checkExisting(context(), resolveSkillPaths(null, "test-skill"), { execImpl }), + ).resolves.toBe(false); }); - it("probes skill directories so removal can clean partial uploads", () => { - const paths = resolveSkillPaths(null, "test-skill"); - const ctx = { configFile: "/tmp/ssh.conf", sandboxName: "test-sandbox" }; + it("probes directories so removal can clean partial uploads", async () => { const commands: string[] = []; - const exists = checkExisting(ctx, paths, { - sshExecImpl: (_ctx, command) => { + const exists = await checkExisting(context(), resolveSkillPaths(null, "test-skill"), { + execImpl: async (_ctx, command) => { commands.push(command); return { status: 0, stdout: "EXISTS", stderr: "" }; }, diff --git a/src/lib/skill-remote.ts b/src/lib/skill-remote.ts index 8b19d1780a7..73ddbd16f88 100644 --- a/src/lib/skill-remote.ts +++ b/src/lib/skill-remote.ts @@ -1,61 +1,46 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; - +import type { OpenShellSandboxControl } from "./adapters/openshell/sandbox-control"; import { shellQuote } from "./core/shell-quote"; import type { SkillPaths } from "./skill-install"; export { shellQuote }; -export interface SshContext { - configFile: string; +export interface SandboxControlContext { + control: OpenShellSandboxControl; sandboxName: string; } -export interface SshResult { - status: number; +export interface SandboxCommandResult { + status: number | null; stdout: string; stderr: string; } -/** - * Run a command on the sandbox via SSH with optional stdin content. - * Uses the same SSH flags as executeSandboxCommand in sandbox-process-recovery-action.ts. - */ -export function sshExec( - ctx: SshContext, +export type SandboxExecImpl = ( + ctx: SandboxControlContext, + command: string, + opts?: { input?: string | Buffer; timeout?: number }, +) => Promise; + +/** Execute one shell command through the selected OpenShell control plane. */ +export async function sandboxExec( + ctx: SandboxControlContext, command: string, opts: { input?: string | Buffer; timeout?: number } = {}, -): SshResult | null { +): Promise { try { - const result = spawnSync( - "ssh", - [ - "-F", - ctx.configFile, - "-o", - "StrictHostKeyChecking=no", - "-o", - "UserKnownHostsFile=/dev/null", - "-o", - "ConnectTimeout=10", - "-o", - "LogLevel=ERROR", - `openshell-${ctx.sandboxName}`, - command, - ], - { - encoding: "utf-8", - stdio: [opts.input !== undefined ? "pipe" : "ignore", "pipe", "pipe"], - input: opts.input, - timeout: opts.timeout ?? 30_000, - }, - ); + const result = await ctx.control.exec({ + sandboxName: ctx.sandboxName, + command: ["sh", "-lc", command], + stdin: opts.input, + timeoutMs: opts.timeout ?? 30_000, + }); return { - status: result.status ?? 1, - stdout: (result.stdout || "").trim(), - stderr: (result.stderr || "").trim(), + status: result.status, + stdout: result.stdout.trim(), + stderr: result.stderr.trim(), }; } catch { return null; @@ -63,30 +48,24 @@ export function sshExec( } /** - * Check whether a skill directory already exists on the sandbox at the upload - * path or (for OpenClaw) the mirror path. Probing directories instead of only - * SKILL.md lets `skill remove` clean up partial uploads whose manifest write - * failed after the directory was created. - * - * Returns: - * true — skill exists - * false — skill is absent - * null — SSH probe failed; existence could not be determined + * Check whether a skill directory already exists at the upload path or, for + * OpenClaw, the mirror path. Directory probes let removal clean partial + * uploads whose manifest write failed. A recognized sentinel from a + * successful command maps to true or false. Transport errors, nonzero status, + * and malformed output map to null so callers can fail before mutation. */ -export function checkExisting( - ctx: SshContext, +export async function checkExisting( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): boolean | null { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const checks = [`test -e ${shellQuote(paths.uploadDir)}`]; - if (paths.isOpenClaw && paths.mirrorDir) { - checks.push(`test -e "${paths.mirrorDir}"`); - } - const runSsh = opts.sshExecImpl ?? sshExec; - const result = runSsh(ctx, `{ ${checks.join(" || ")}; } && echo EXISTS || echo ABSENT`); - if (result === null || result.status !== 0) { - return null; - } + if (paths.isOpenClaw && paths.mirrorDir) checks.push(`test -e "${paths.mirrorDir}"`); + const result = await (opts.execImpl ?? sandboxExec)( + ctx, + `{ ${checks.join(" || ")}; } && echo EXISTS || echo ABSENT`, + ); + if (result === null || result.status !== 0) return null; if (result.stdout === "EXISTS") return true; if (result.stdout === "ABSENT") return false; return null; @@ -100,48 +79,33 @@ export interface RemoveResult { messages: string[]; } -/** - * Remove a skill from the sandbox by name. - * Deletes the immutable upload directory, the OpenClaw mirror directory - * (if applicable), and clears sessions.json so the agent re-discovers - * the remaining skills on the next session. - * - * Only the named skill directory is deleted — other skills are untouched. - */ -export function removeSkill( - ctx: SshContext, +/** Remove one named skill and clear OpenClaw's session index. */ +export async function removeSkill( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): RemoveResult { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const messages: string[] = []; - const runSsh = opts.sshExecImpl ?? sshExec; + const run = opts.execImpl ?? sandboxExec; - // 1. Remove the immutable upload directory (/sandbox/.openclaw/skills//) - const uploadDir = shellQuote(paths.uploadDir); - const removeUpload = runSsh(ctx, `rm -rf ${uploadDir}`); + const removeUpload = await run(ctx, `rm -rf ${shellQuote(paths.uploadDir)}`); const removedUploadDir = removeUpload !== null && removeUpload.status === 0; if (!removedUploadDir) { messages.push(`Warning: failed to remove upload directory ${paths.uploadDir}`); } - // 2. Remove the OpenClaw mirror ($HOME/.openclaw/skills//) - // mirrorDir contains $HOME which must expand on the remote shell, so we - // use double quotes (not shellQuote). This is safe because skill names - // are restricted to [A-Za-z0-9._-] by parseFrontmatter / the name - // validation regex, so $HOME expansion is the only variable substitution. let removedMirrorDir = false; if (paths.isOpenClaw && paths.mirrorDir) { - const removeMirror = runSsh(ctx, `rm -rf "${paths.mirrorDir}"`); + const removeMirror = await run(ctx, `rm -rf "${paths.mirrorDir}"`); removedMirrorDir = removeMirror !== null && removeMirror.status === 0; if (!removedMirrorDir) { messages.push(`Warning: failed to remove mirror directory ${paths.mirrorDir}`); } } - // 3. Clear sessions.json so the agent re-discovers the remaining skills. let clearedSessions = false; if (paths.isOpenClaw && paths.sessionFile) { - const clearResult = runSsh(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); + const clearResult = await run(ctx, `printf '{}' > ${shellQuote(paths.sessionFile)}`); clearedSessions = clearResult !== null && clearResult.status === 0; if (!clearedSessions) { messages.push("Warning: failed to clear sessions (agent may need manual restart)"); @@ -159,20 +123,17 @@ export function removeSkill( }; } -/** - * Verify the skill directory no longer exists on the sandbox. - * For OpenClaw sandboxes, both the upload dir and the mirror dir must be gone. - */ -export function verifyRemove( - ctx: SshContext, +/** Verify that both managed skill directories are absent. */ +export async function verifyRemove( + ctx: SandboxControlContext, paths: SkillPaths, - opts: { sshExecImpl?: typeof sshExec } = {}, -): boolean { + opts: { execImpl?: SandboxExecImpl } = {}, +): Promise { const checks = [`test ! -e ${shellQuote(paths.uploadDir)}`]; - if (paths.isOpenClaw && paths.mirrorDir) { - checks.push(`test ! -e "${paths.mirrorDir}"`); - } - const runSsh = opts.sshExecImpl ?? sshExec; - const result = runSsh(ctx, `${checks.join(" && ")} && echo GONE || echo EXISTS`); + if (paths.isOpenClaw && paths.mirrorDir) checks.push(`test ! -e "${paths.mirrorDir}"`); + const result = await (opts.execImpl ?? sandboxExec)( + ctx, + `${checks.join(" && ")} && echo GONE || echo EXISTS`, + ); return result !== null && result.stdout === "GONE"; }