From ae141630c850bb97a3ce102749465ab3d24f0fe4 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 14:02:09 -0700 Subject: [PATCH 1/5] 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 2/5] 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 363dd800de23bd4dd8a2242be594196c76dcf3ac Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:00:51 -0700 Subject: [PATCH 3/5] 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 4/5] 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 55e7d3f0a230ab9d776324a14ebfad986f6396b5 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 04:40:36 -0700 Subject: [PATCH 5/5] fix(openshell): contain session transport fallback Co-authored-by: Aaron Erickson Signed-off-by: Apurv Kumaria --- .../sandbox/sessions/passthrough.test.ts | 12 +++- .../actions/sandbox/sessions/passthrough.ts | 11 +++- .../openshell/sandbox-control-routing.test.ts | 56 +++++++++++++++-- .../openshell/sandbox-control-routing.ts | 62 ++++++++++++------- .../openshell/sandbox-control.test.ts | 33 +++++++++- src/lib/adapters/openshell/sandbox-control.ts | 36 ++++++++++- 6 files changed, 174 insertions(+), 36 deletions(-) diff --git a/src/lib/actions/sandbox/sessions/passthrough.test.ts b/src/lib/actions/sandbox/sessions/passthrough.test.ts index b59787c6724..7210ac231e1 100644 --- a/src/lib/actions/sandbox/sessions/passthrough.test.ts +++ b/src/lib/actions/sandbox/sessions/passthrough.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const readOnlyExecMock = vi.hoisted(() => vi.fn()); +const legacyCliExecMock = vi.hoisted(() => vi.fn()); const execMock = vi.hoisted(() => vi.fn(async () => {})); const ensureLiveMock = vi.hoisted(() => vi.fn(async () => ({}))); const getSandboxMock = vi.hoisted(() => @@ -20,6 +21,9 @@ const getSandboxMock = vi.hoisted(() => vi.mock("../../../adapters/openshell/sandbox-control-routing", () => ({ execSandboxReadOnlyWithGrpcFallback: readOnlyExecMock, })); +vi.mock("../../../adapters/openshell/sandbox-control", () => ({ + openShellSandboxControl: { exec: legacyCliExecMock }, +})); vi.mock("../exec", async () => { const actual = await vi.importActual("../exec"); return { ...actual, execSandbox: execMock }; @@ -227,10 +231,11 @@ describe("runSessionsPassthrough", () => { beforeEach(() => { readOnlyExecMock.mockReset(); + legacyCliExecMock.mockReset(); execMock.mockClear(); ensureLiveMock.mockClear(); getSandboxMock.mockReset(); - getSandboxMock.mockReturnValue(null); + getSandboxMock.mockReturnValue({ agent: "openclaw" }); stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true); stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true); consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); @@ -426,7 +431,7 @@ describe("runSessionsPassthrough", () => { it("defaults to the openclaw binary + filter path when the registry has no entry (#6247)", async () => { getSandboxMock.mockReturnValue(null); - readOnlyExecMock.mockResolvedValueOnce({ + legacyCliExecMock.mockResolvedValueOnce({ status: 0, stdout: "Sessions listed: 0\n", stderr: "", @@ -435,7 +440,8 @@ describe("runSessionsPassthrough", () => { await runSessionsPassthrough("alpha", { extraArgs: [] }); expect(execMock).not.toHaveBeenCalled(); - expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw", { + expect(readOnlyExecMock).not.toHaveBeenCalled(); + expect(legacyCliExecMock).toHaveBeenCalledWith({ sandboxName: "alpha", command: ["openclaw", "sessions"], maxOutputBytes: 64 * 1024 * 1024, diff --git a/src/lib/actions/sandbox/sessions/passthrough.ts b/src/lib/actions/sandbox/sessions/passthrough.ts index a48545dee02..4d001a621da 100644 --- a/src/lib/actions/sandbox/sessions/passthrough.ts +++ b/src/lib/actions/sandbox/sessions/passthrough.ts @@ -1,6 +1,7 @@ // 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"; @@ -232,11 +233,17 @@ export async function runSessionsPassthrough( else if (inSandboxBinary === "hermes") command.push("list"); for (const arg of extraArgs) command.push(arg); if (isFilterableListPassthrough(verb) && inSandboxBinary === "openclaw") { - const result = await execSandboxReadOnlyWithGrpcFallback(resolveSandboxGatewayName(sandbox), { + const request = { sandboxName, command, maxOutputBytes: SESSIONS_LIST_CAPTURE_MAX_BUFFER_BYTES, - }); + }; + // Without a registry row, the live check above may have validated the + // sandbox on whichever gateway is currently active. Preserve that legacy + // CLI route instead of guessing the default gateway for direct gRPC. + const result = sandbox + ? await execSandboxReadOnlyWithGrpcFallback(resolveSandboxGatewayName(sandbox), request) + : await openShellSandboxControl.exec(request); const { code, errorMessage } = computeExitCode(result); const capturedOutput = capturedStdout(result); const capturedError = capturedStderr(result); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index c74513629d9..d8ec4098f18 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -19,9 +19,18 @@ function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: Sandbox const grpc: GrpcOpenShellSandboxControl = { close, exec: grpcExec }; const cliExec = vi.fn(async () => cliResult ?? { status: 0, stdout: "cli", stderr: "" }); const cli: OpenShellSandboxControl = { exec: cliExec }; + const createCli = vi.fn(() => cli); const createGrpc = vi.fn(() => grpc); const debug = vi.fn(); - return { close, grpcExec, cliExec, createGrpc, debug, deps: { cli, createGrpc, debug } }; + return { + close, + grpcExec, + cliExec, + createCli, + createGrpc, + debug, + deps: { createCli, createGrpc, debug }, + }; } const request = { @@ -58,7 +67,7 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.cliExec).not.toHaveBeenCalled(); }); - it("retries a pre-dispatch gRPC lookup failure without forwarding its deadline", async () => { + it("retries a pre-dispatch gRPC lookup failure through the requested gateway", async () => { const grpcError = new Error("UNAVAILABLE"); const cliResult = { status: 0, stdout: "cli", stderr: "" }; const test = dependencies( @@ -75,7 +84,11 @@ describe("read-only OpenShell sandbox control routing", () => { execSandboxReadOnlyWithGrpcFallback("nemoclaw", request, test.deps), ).resolves.toEqual(cliResult); - expect(test.cliExec).toHaveBeenCalledWith(request); + expect(test.createCli).toHaveBeenCalledWith("nemoclaw"); + expect(test.cliExec).toHaveBeenCalledWith({ + ...request, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); expect(test.debug).toHaveBeenCalledWith(expect.stringContaining("before dispatch"), grpcError); expect(test.close).toHaveBeenCalledOnce(); }); @@ -92,6 +105,37 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.cliExec).not.toHaveBeenCalled(); }); + it("does not replay a rejected gRPC execution through the CLI", async () => { + const error = new Error("stream rejected after dispatch"); + const test = dependencies(error); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", request, test.deps), + ).resolves.toEqual({ status: null, stdout: "", stderr: "", error }); + + expect(test.grpcExec).toHaveBeenCalledOnce(); + expect(test.createCli).not.toHaveBeenCalled(); + expect(test.cliExec).not.toHaveBeenCalled(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("retries a rejected explicit pre-dispatch failure through the requested gateway", async () => { + const cause = new Error("UNAVAILABLE"); + const test = dependencies(new OpenShellGrpcPreDispatchError(cause)); + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw-9090", request, test.deps), + ).resolves.toEqual({ status: 0, stdout: "cli", stderr: "" }); + + expect(test.createCli).toHaveBeenCalledWith("nemoclaw-9090"); + expect(test.cliExec).toHaveBeenCalledWith({ + ...request, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + expect(test.debug).toHaveBeenCalledWith(expect.stringContaining("before dispatch"), cause); + 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"); @@ -106,7 +150,11 @@ describe("read-only OpenShell sandbox control routing", () => { }); expect(test.grpcExec).not.toHaveBeenCalled(); - expect(test.cliExec).toHaveBeenCalledWith(request); + expect(test.createCli).toHaveBeenCalledWith("edge"); + expect(test.cliExec).toHaveBeenCalledWith({ + ...request, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); expect(test.debug).toHaveBeenCalledWith(expect.stringContaining("configuration failed"), error); }); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index b62647f5aa0..caaf4c110b1 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -2,65 +2,81 @@ // 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 GrpcOpenShellSandboxControl, + OpenShellGrpcPreDispatchError, +} from "./grpc-sandbox-control"; +import { + createGatewayScopedCliOpenShellSandboxControl, type OpenShellSandboxControl, type SandboxExecRequest, type SandboxExecResult, } from "./sandbox-control"; -import { - type GrpcOpenShellSandboxControl, - OpenShellGrpcPreDispatchError, -} from "./grpc-sandbox-control"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; export interface ReadOnlyRoutingDependencies { - cli: OpenShellSandboxControl; + createCli: (gatewayName: string) => OpenShellSandboxControl; createGrpc: (gatewayName: string) => GrpcOpenShellSandboxControl; debug: (message: string, context: unknown) => void; } const defaultDependencies: ReadOnlyRoutingDependencies = { - cli: createCliOpenShellSandboxControl(), + createCli: createGatewayScopedCliOpenShellSandboxControl, 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. + * gateway-scoped OpenShell CLI only when client configuration or sandbox + * lookup fails before dispatch. A rejected execution has an unknown outcome + * and must not be replayed automatically. */ export async function execSandboxReadOnlyWithGrpcFallback( gatewayName: string, request: SandboxExecRequest, dependencies: ReadOnlyRoutingDependencies = defaultDependencies, ): Promise { - let grpc: GrpcOpenShellSandboxControl | undefined; + const routedRequest = { + ...request, + timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, + }; + + let grpc: GrpcOpenShellSandboxControl; try { grpc = dependencies.createGrpc(gatewayName); - const result = await grpc.exec({ - ...request, - timeoutMs: request.timeoutMs ?? OPENSHELL_OPERATION_TIMEOUT_MS, - }); - 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", error, ); + return dependencies.createCli(gatewayName).exec(routedRequest); + } + + let preDispatchError: OpenShellGrpcPreDispatchError | undefined; + try { + const result = await grpc.exec(routedRequest); + if (!(result.error instanceof OpenShellGrpcPreDispatchError)) return result; + preDispatchError = result.error; + } catch (error) { + if (error instanceof OpenShellGrpcPreDispatchError) { + preDispatchError = error; + } else { + const cause = error instanceof Error ? error : new Error(String(error)); + return { status: null, stdout: "", stderr: "", error: cause }; + } } finally { try { - grpc?.close(); + grpc.close(); } catch (error) { dependencies.debug("OpenShell direct gRPC client close failed", error); } } - return dependencies.cli.exec(request); + + dependencies.debug( + "OpenShell direct gRPC lookup failed before dispatch; retrying through the CLI", + preDispatchError.cause, + ); + 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 d2403a22216..48da7136f72 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -4,7 +4,10 @@ import { describe, expect, it, vi } from "vitest"; import type { CaptureOpenshellResult } from "./client"; -import { createCliOpenShellSandboxControl } from "./sandbox-control"; +import { + createCliOpenShellSandboxControl, + createGatewayScopedCliOpenShellSandboxControl, +} from "./sandbox-control"; describe("CLI OpenShell sandbox control", () => { it("maps a typed exec request to the existing CLI contract", async () => { @@ -56,4 +59,32 @@ describe("CLI OpenShell sandbox control", () => { signal: "SIGTERM", }); }); + + it("pins fallback execution to the requested gateway", async () => { + const capture = vi.fn( + (): CaptureOpenshellResult => ({ + status: 0, + output: "ok", + }), + ); + const control = createGatewayScopedCliOpenShellSandboxControl("nemoclaw-19080", capture, {}); + + await control.exec({ sandboxName: "alpha", command: ["true"] }); + + expect(capture).toHaveBeenCalledWith( + ["--gateway", "nemoclaw-19080", "sandbox", "exec", "--name", "alpha", "--", "true"], + expect.objectContaining({ ignoreError: true, includeStreams: true }), + ); + }); + + it("rejects an ambient endpoint that could override the fallback gateway", () => { + const capture = vi.fn<() => CaptureOpenshellResult>(); + + expect(() => + createGatewayScopedCliOpenShellSandboxControl("nemoclaw-19080", capture, { + OPENSHELL_GATEWAY_ENDPOINT: "https://other.example.test", + }), + ).toThrow(/Unset OPENSHELL_GATEWAY_ENDPOINT/); + expect(capture).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index e0baa204a91..5bf661044cd 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + assertNoOpenShellGatewayEndpointOverride, + type OpenShellGatewayEndpointEnvironment, +} from "../../openshell-gateway-endpoint-guard"; import type { CaptureOpenshellResult } from "./client"; import { captureOpenshell } from "./runtime"; @@ -38,13 +42,23 @@ function normalizeExecResult(result: CaptureOpenshellResult): SandboxExecResult return normalized; } -export function createCliOpenShellSandboxControl( - capture: CaptureOpenShell = captureOpenshell, +function createCliSandboxControl( + capture: CaptureOpenShell, + gatewayName?: string, ): OpenShellSandboxControl { return { async exec(request): Promise { + const gatewayArgs = gatewayName ? ["--gateway", gatewayName] : []; const result = capture( - ["sandbox", "exec", "--name", request.sandboxName, "--", ...request.command], + [ + ...gatewayArgs, + "sandbox", + "exec", + "--name", + request.sandboxName, + "--", + ...request.command, + ], { ignoreError: true, includeStreams: true, @@ -57,4 +71,20 @@ export function createCliOpenShellSandboxControl( }; } +export function createCliOpenShellSandboxControl( + capture: CaptureOpenShell = captureOpenshell, +): OpenShellSandboxControl { + return createCliSandboxControl(capture); +} + +/** Bind every CLI fallback invocation to the gateway selected by the caller. */ +export function createGatewayScopedCliOpenShellSandboxControl( + gatewayName: string, + capture: CaptureOpenShell = captureOpenshell, + env: OpenShellGatewayEndpointEnvironment = process.env, +): OpenShellSandboxControl { + assertNoOpenShellGatewayEndpointOverride(env); + return createCliSandboxControl(capture, gatewayName); +} + export const openShellSandboxControl = createCliOpenShellSandboxControl();