From 0f56334d9e13ef88691c1ce7970492a24a79102b Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 3 Sep 2026 11:22:47 -0700 Subject: [PATCH 1/3] refactor(cli): route streamed exec through adapter Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/exec-gateway-target.test.ts | 108 ++++---- .../exec-googlechat-pairing-restart.test.ts | 23 +- src/lib/actions/sandbox/exec-stdio.ts | 23 +- .../sandbox/exec.multiline-argv.test.ts | 94 +++++-- src/lib/actions/sandbox/exec.test.ts | 27 +- src/lib/actions/sandbox/exec.ts | 219 +++++++-------- .../openshell/sandbox-command-cli.test.ts | 233 ++++++++++++++++ .../adapters/openshell/sandbox-command-cli.ts | 261 ++++++++++++++++++ .../openshell/sandbox-command-stdio.ts | 23 ++ src/lib/adapters/openshell/sandbox-command.ts | 54 ++++ 10 files changed, 851 insertions(+), 214 deletions(-) create mode 100644 src/lib/adapters/openshell/sandbox-command-cli.test.ts create mode 100644 src/lib/adapters/openshell/sandbox-command-cli.ts create mode 100644 src/lib/adapters/openshell/sandbox-command-stdio.ts create mode 100644 src/lib/adapters/openshell/sandbox-command.ts diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts index 5d0a88c58f8..7b5a199343f 100644 --- a/src/lib/actions/sandbox/exec-gateway-target.test.ts +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -3,8 +3,24 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { execSandbox, type SandboxExecCleanupDeps } from "./exec"; +function commandExecutor(options: { + run?: OpenShellSandboxCommandExecutor["runStreaming"]; + probe?: OpenShellSandboxCommandExecutor["probeDirectory"]; +}): OpenShellSandboxCommandExecutor { + return { + probeDirectory: options.probe ?? (async () => ({ state: "present" })), + runStreaming: + options.run ?? + (async () => ({ + outcome: { kind: "completed", exitCode: 0 }, + release: () => {}, + })), + }; +} + const cleanupSkipped: SandboxExecCleanupDeps = { getSandbox: () => null, inspectMutableConfigPerms: (() => { @@ -27,9 +43,9 @@ describe("execSandbox gateway targeting", () => { order.push(`select:${name}`); return { outcome: "selected" as const, gatewayName: name }; }); - const run = vi.fn(async (_binary: string, _args: readonly string[]) => { + const run = vi.fn(async () => { order.push("run"); - return { status: 0 }; + return { outcome: { kind: "completed", exitCode: 0 }, release: () => {} }; }); vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`__exit_${code ?? 0}__`); @@ -42,9 +58,8 @@ describe("execSandbox gateway targeting", () => { ["hostname"], {}, { - resolveBinary: () => "openshell", selectGateway, - run, + commandExecutor: commandExecutor({ run }), cleanupDeps: cleanupSkipped, policyHint: { now: () => 0, @@ -61,10 +76,12 @@ describe("execSandbox gateway targeting", () => { expect(selectGateway).toHaveBeenCalledWith("beta"); expect(run).toHaveBeenCalled(); - const execArgs = run.mock.calls[0]?.[1] ?? []; - expect(execArgs.slice(0, 7)).toEqual(["sandbox", "exec", "--name", "beta", "-g", "beta", "--"]); - expect(execArgs.at(-2)).toBe("nemoclaw-runtime-env"); - expect(execArgs.at(-1)).toBe("hostname"); + expect(run.mock.calls[0]?.[0]).toMatchObject({ + sandboxName: "beta", + target: { kind: "named", gatewayName: "beta" }, + }); + expect(run.mock.calls[0]?.[0].command.at(-2)).toBe("nemoclaw-runtime-env"); + expect(run.mock.calls[0]?.[0].command.at(-1)).toBe("hostname"); expect(order.indexOf("select:beta")).toBeGreaterThanOrEqual(0); expect(order.indexOf("select:beta")).toBeLessThan(order.indexOf("run")); }); @@ -77,13 +94,13 @@ describe("execSandbox gateway targeting", () => { process.env.OPENSHELL_GATEWAY = "drifted-sibling"; return { outcome: "selected" as const, gatewayName: "nemoclaw-8091" }; }); - const probeWorkdir = vi.fn((_binary: string, _args: readonly string[]) => { + const probeWorkdir = vi.fn(async () => { order.push("probe"); - return { status: 0, error: undefined }; + return { state: "present" }; }); - const run = vi.fn(async (_binary: string, _args: readonly string[]) => { + const run = vi.fn(async () => { order.push("run"); - return { status: 0 }; + return { outcome: { kind: "completed", exitCode: 0 }, release: () => {} }; }); vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`__exit_${code ?? 0}__`); @@ -96,10 +113,8 @@ describe("execSandbox gateway targeting", () => { ["hostname"], { workdir: "/work" }, { - resolveBinary: () => "openshell", selectGateway, - probeWorkdir, - run, + commandExecutor: commandExecutor({ probe: probeWorkdir, run }), cleanupDeps: cleanupSkipped, policyHint: { now: () => 0, @@ -116,40 +131,26 @@ describe("execSandbox gateway targeting", () => { expect(order).toEqual(["select:beta", "probe", "run"]); expect(process.env.OPENSHELL_GATEWAY).toBe("drifted-sibling"); - expect(probeWorkdir.mock.calls[0]?.[1]).toEqual([ - "sandbox", - "exec", - "--name", - "beta", - "-g", - "nemoclaw-8091", - "--", - "test", - "-d", - "/work", - ]); - const execArgs = run.mock.calls[0]?.[1] ?? []; - expect(execArgs.slice(0, 9)).toEqual([ - "sandbox", - "exec", - "--name", - "beta", - "-g", - "nemoclaw-8091", - "--workdir", - "/work", - "--", - ]); - expect(execArgs.at(-2)).toBe("nemoclaw-runtime-env"); - expect(execArgs.at(-1)).toBe("hostname"); + expect(probeWorkdir).toHaveBeenCalledWith({ + sandboxName: "beta", + target: { kind: "named", gatewayName: "nemoclaw-8091" }, + path: "/work", + }); + expect(run.mock.calls[0]?.[0]).toMatchObject({ + sandboxName: "beta", + target: { kind: "named", gatewayName: "nemoclaw-8091" }, + workdir: "/work", + }); + expect(run.mock.calls[0]?.[0].command.at(-2)).toBe("nemoclaw-runtime-env"); + expect(run.mock.calls[0]?.[0].command.at(-1)).toBe("hostname"); }); it("rejects a direct endpoint override before selecting, probing, or dispatching", async () => { vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://sibling.invalid"); - const resolveBinary = vi.fn(() => "openshell"); const selectGateway = vi.fn(); const probeWorkdir = vi.fn(); const run = vi.fn(); + const executor = commandExecutor({ probe: probeWorkdir, run }); vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`__exit_${code ?? 0}__`); }) as never); @@ -160,14 +161,13 @@ describe("execSandbox gateway targeting", () => { "beta", ["hostname"], { workdir: "/work" }, - { resolveBinary, selectGateway, probeWorkdir, run }, + { commandExecutor: executor, selectGateway }, ), ).rejects.toThrow("__exit_1__"); expect(console.error).toHaveBeenCalledWith( expect.stringContaining("OPENSHELL_GATEWAY_ENDPOINT is set"), ); - expect(resolveBinary).not.toHaveBeenCalled(); expect(selectGateway).not.toHaveBeenCalled(); expect(probeWorkdir).not.toHaveBeenCalled(); expect(run).not.toHaveBeenCalled(); @@ -192,9 +192,13 @@ describe("execSandbox gateway targeting", () => { ["curl", "https://example.invalid"], {}, { - resolveBinary: () => "openshell", selectGateway, - run: async () => ({ status: 56 }), + commandExecutor: commandExecutor({ + run: async () => ({ + outcome: { kind: "completed", exitCode: 56 }, + release: () => {}, + }), + }), cleanupDeps: cleanupSkipped, policyHint: { now: () => 0, @@ -220,13 +224,13 @@ describe("execSandbox gateway targeting", () => { order.push("select"); return { outcome: "failed" as const, gatewayName: "nemoclaw-8091" }; }); - const probeWorkdir = vi.fn(() => { + const probeWorkdir = vi.fn(async () => { order.push("probe"); - return { status: 0, error: undefined }; + return { state: "present" }; }); - const run = vi.fn(async () => { + const run = vi.fn(async () => { order.push("run"); - return { status: 0 }; + return { outcome: { kind: "completed", exitCode: 0 }, release: () => {} }; }); vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`__exit_${code ?? 0}__`); @@ -239,10 +243,8 @@ describe("execSandbox gateway targeting", () => { ["hostname"], { workdir: "/work" }, { - resolveBinary: () => "openshell", selectGateway, - probeWorkdir, - run, + commandExecutor: commandExecutor({ probe: probeWorkdir, run }), cleanupDeps: cleanupSkipped, }, ), diff --git a/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts b/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts index 90336bb9839..231b8c32cff 100644 --- a/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts +++ b/src/lib/actions/sandbox/exec-googlechat-pairing-restart.test.ts @@ -7,6 +7,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; import { execSandbox, isGoogleChatPairingApproval, @@ -27,9 +28,14 @@ const CLEANUP_SKIPPED: SandboxExecCleanupDeps = { function depsFor(status: number, restartGateway = vi.fn(() => ({ ok: true }))): ExecSandboxDeps { return { - resolveBinary: () => "openshell", selectGateway: () => ({ outcome: "selected", gatewayName: "nemoclaw-alpha" }), - run: () => ({ status }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => ({ + outcome: { kind: "completed", exitCode: status }, + release: () => {}, + }), + }, cleanupDeps: CLEANUP_SKIPPED, restartGateway, resolveSandboxAgent: () => "openclaw", @@ -110,9 +116,12 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { return { ok: true }; }); const deps = depsFor(0, restartGateway); - deps.run = () => { - order.push("command"); - return { status: 0 }; + deps.commandExecutor = { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => { + order.push("command"); + return { outcome: { kind: "completed", exitCode: 0 }, release: () => {} }; + }, }; deps.cleanupDeps = { getSandbox: () => ({ agent: "openclaw" }), @@ -181,8 +190,10 @@ describe("Google Chat pairing approval gateway activation (#8553)", () => { const exitCode = await runAndCaptureExit( ["openclaw", "pairing", "approve", "googlechat", "ABCD1234"], { - resolveBinary: () => openshellPath, selectGateway: () => ({ outcome: "selected", gatewayName: "nemoclaw-alpha" }), + commandExecutor: createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => openshellPath, + }), cleanupDeps: { getSandbox: () => ({ agent: "openclaw" }), inspectMutableConfigPerms: () => ({ diff --git a/src/lib/actions/sandbox/exec-stdio.ts b/src/lib/actions/sandbox/exec-stdio.ts index f1fcac0daa1..6129a431ea4 100644 --- a/src/lib/actions/sandbox/exec-stdio.ts +++ b/src/lib/actions/sandbox/exec-stdio.ts @@ -1,23 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { StdioOptions } from "node:child_process"; -import { isStdinTty } from "../../core/stdin"; import type { SandboxExecOptions } from "./exec"; +import { + buildSandboxCommandStdio, + shouldInheritSandboxCommandStdin, +} from "../../adapters/openshell/sandbox-command-stdio"; -export function shouldInheritSandboxExecStdin( - requested: boolean | undefined, - stdinIsTty: boolean | undefined, -): boolean { - if (typeof requested === "boolean") return requested; - return stdinIsTty === true; -} +export const shouldInheritSandboxExecStdin = shouldInheritSandboxCommandStdin; -export function buildSandboxExecStdio( - options: SandboxExecOptions = {}, - stdinIsTty: boolean | undefined = isStdinTty(), -): StdioOptions { - return shouldInheritSandboxExecStdin(options.stdin, stdinIsTty) - ? "inherit" - : ["ignore", "inherit", "inherit"]; +export function buildSandboxExecStdio(options: SandboxExecOptions = {}, stdinIsTty?: boolean) { + return buildSandboxCommandStdio(options, stdinIsTty); } diff --git a/src/lib/actions/sandbox/exec.multiline-argv.test.ts b/src/lib/actions/sandbox/exec.multiline-argv.test.ts index c90772500c8..7a6cded719e 100644 --- a/src/lib/actions/sandbox/exec.multiline-argv.test.ts +++ b/src/lib/actions/sandbox/exec.multiline-argv.test.ts @@ -5,6 +5,9 @@ import { spawn } from "node:child_process"; import { EventEmitter } from "node:events"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; +import type { OpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command"; + // The default exec runner shells out via spawn and chooses whether to inherit // or ignore stdin. Mock node:child_process so the tests can assert that wiring // at the execSandbox boundary without spawning a real process. Every other test @@ -14,7 +17,46 @@ vi.mock("node:child_process", async (importOriginal) => { return { ...actual, spawn: vi.fn() }; }); -import { buildOpenshellExecArgs, execSandbox, wrapExecCommandWithRuntimeEnv } from "./exec"; +import { + buildOpenshellExecArgs, + execSandbox, + type ExecSandboxDeps, + type SandboxExecCleanupDeps, + wrapExecCommandWithRuntimeEnv, +} from "./exec"; + +const cleanupSkipped: SandboxExecCleanupDeps = { + getSandbox: () => null, + inspectMutableConfigPerms: () => { + throw new Error("cleanup should be skipped"); + }, + repairMutableConfigPerms: () => { + throw new Error("cleanup should be skipped"); + }, +}; + +function commandExecutor(options: { + run?: OpenShellSandboxCommandExecutor["runStreaming"]; + probe?: OpenShellSandboxCommandExecutor["probeDirectory"]; +}): OpenShellSandboxCommandExecutor { + return { + probeDirectory: options.probe ?? (async () => ({ state: "present" })), + runStreaming: + options.run ?? + (async () => ({ + outcome: { kind: "completed", exitCode: 0 }, + release: () => {}, + })), + }; +} + +function execDeps(executor: OpenShellSandboxCommandExecutor): ExecSandboxDeps { + return { + commandExecutor: executor, + cleanupDeps: cleanupSkipped, + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + }; +} function expectedExecArgs(sandboxName: string, command: readonly string[]): string[] { return buildOpenshellExecArgs(sandboxName, wrapExecCommandWithRuntimeEnv(command)); @@ -55,15 +97,17 @@ describe("execSandbox multi-line argv", () => { ])("forwards $label bytes unchanged through the OpenShell argv boundary", async ({ command }) => { const exitSpy = exitWithCode(); vi.spyOn(console, "error").mockImplementation(() => {}); - const run = vi.fn((_binary: string, _args: readonly string[]) => ({ status: 0 })); + const run = vi.fn(async () => ({ + outcome: { kind: "completed", exitCode: 0 }, + release: () => {}, + })); await expect( - execSandbox("multiline-test", command, {}, { run, resolveBinary: () => "openshell" }), + execSandbox("multiline-test", command, {}, execDeps(commandExecutor({ run }))), ).rejects.toThrow("exit:0"); expect(run).toHaveBeenCalledOnce(); - expect(run).toHaveBeenCalledWith("openshell", expectedExecArgs("multiline-test", command)); - const forwarded = vi.mocked(run).mock.calls[0][1]; + const forwarded = vi.mocked(run).mock.calls[0][0].command; expect(forwarded.slice(-command.length)).toEqual(command); expect(exitSpy).toHaveBeenCalledWith(0); }); @@ -71,11 +115,12 @@ describe("execSandbox multi-line argv", () => { it("still rejects a NUL-bearing command argument before dispatch", async () => { const exitSpy = exitWithCode(); const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - const run = vi.fn(() => ({ status: 0 })); + const run = vi.fn(); + const executor = commandExecutor({ run }); - await expect(execSandbox("multiline-test", ["printf", "a\0b"], {}, { run })).rejects.toThrow( - "exit:2", - ); + await expect( + execSandbox("multiline-test", ["printf", "a\0b"], {}, execDeps(executor)), + ).rejects.toThrow("exit:2"); expect(run).not.toHaveBeenCalled(); expect(errSpy).toHaveBeenCalledWith( @@ -91,15 +136,15 @@ describe("execSandbox multi-line argv", () => { ])("still rejects a multi-line --workdir before probing or dispatch: %j", async (workdir) => { const exitSpy = exitWithCode(); const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - const probeWorkdir = vi.fn(() => ({ status: 0 })); - const run = vi.fn(() => ({ status: 0 })); + const probeWorkdir = vi.fn(); + const run = vi.fn(); await expect( execSandbox( "multiline-test", ["pwd"], { workdir }, - { run, resolveBinary: () => "openshell", probeWorkdir }, + execDeps(commandExecutor({ run, probe: probeWorkdir })), ), ).rejects.toThrow("exit:2"); @@ -114,15 +159,15 @@ describe("execSandbox multi-line argv", () => { it("still rejects a NUL-bearing --workdir before probing or dispatch", async () => { const exitSpy = exitWithCode(); const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - const probeWorkdir = vi.fn(() => ({ status: 0 })); - const run = vi.fn(() => ({ status: 0 })); + const probeWorkdir = vi.fn(); + const run = vi.fn(); await expect( execSandbox( "multiline-test", ["pwd"], { workdir: "/sandbox/a\0b" }, - { run, resolveBinary: () => "openshell", probeWorkdir }, + execDeps(commandExecutor({ run, probe: probeWorkdir })), ), ).rejects.toThrow("exit:2"); @@ -145,15 +190,17 @@ describe("execSandbox multi-line argv", () => { it("still validates a single-line --workdir before dispatch", async () => { const exitSpy = exitWithCode(); const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - const probeWorkdir = vi.fn(() => ({ status: 1 })); - const run = vi.fn(() => ({ status: 0 })); + const probeWorkdir = vi.fn(async () => ({ + state: "missing", + })); + const run = vi.fn(); await expect( execSandbox( "multiline-test", ["pwd"], { workdir: "/no/such/dir" }, - { run, resolveBinary: () => "openshell", probeWorkdir }, + execDeps(commandExecutor({ run, probe: probeWorkdir })), ), ).rejects.toThrow("exit:1"); @@ -190,7 +237,16 @@ describe("execSandbox multi-line argv", () => { vi.spyOn(console, "error").mockImplementation(() => {}); await expect( - execSandbox("multiline-test", ["bash"], { stdin }, { resolveBinary: () => "openshell" }), + execSandbox( + "multiline-test", + ["bash"], + { stdin }, + execDeps( + createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "openshell", + }), + ), + ), ).rejects.toThrow("exit:0"); expect(spawn).toHaveBeenCalledWith("openshell", expectedExecArgs("multiline-test", ["bash"]), { diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts index b920e5851b8..da43f36d87a 100644 --- a/src/lib/actions/sandbox/exec.test.ts +++ b/src/lib/actions/sandbox/exec.test.ts @@ -354,11 +354,21 @@ describe("execSandbox policy-denial hint wiring (#5978)", () => { ["curl", "-sS", "https://example.com/"], {}, { - resolveBinary: () => "openshell", selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), - run: async () => { - options.onRun?.(); - return { status, ...(options.error ? { error: options.error } : {}) }; + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => { + options.onRun?.(); + return { + outcome: options.error + ? { + kind: "failed" as const, + error: { kind: "invocation" as const, message: options.error.message }, + } + : { kind: "completed" as const, exitCode: status ?? 1 }, + release: () => {}, + }; + }, }, cleanupDeps: options.cleanupDeps ?? cleanupSkipped, exit, @@ -529,9 +539,14 @@ describe("execSandbox scope-upgrade hint wiring (#9744)", () => { ["openclaw", "cron", "add"], {}, { - resolveBinary: () => "openshell", selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), - run: async () => ({ status }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => ({ + outcome: { kind: "completed", exitCode: status }, + release: () => {}, + }), + }, cleanupDeps: cleanupSkipped, exit, policyHint: { diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index 99d37aefc5e..bc769aa6458 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -1,7 +1,25 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawn, spawnSync } from "node:child_process"; +import { spawnSync } from "node:child_process"; +import { + buildCliOpenShellSandboxDirectoryProbeArgs, + buildCliOpenShellSandboxExecArgs, + createCliOpenShellSandboxCommandExecutor, + runCliOpenShellStreamingCommand, + type OpenShellCommandChild, + type OpenShellCommandChildOptions, + type OpenShellCommandSignalSource, + type OpenShellCommandSpawner, +} from "../../adapters/openshell/sandbox-command-cli"; +import type { + OpenShellSandboxCommandExecutor, + OpenShellSandboxCommandRequest, +} from "../../adapters/openshell/sandbox-command"; +import { + namedOpenShellGateway, + selectedOpenShellGateway, +} from "../../adapters/openshell/sandbox-observer"; import { spawnExitCode } from "../../core/process-exit"; import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import type { @@ -10,7 +28,6 @@ import type { } from "../../sandbox/mutable-config-perms"; import type { SandboxEntry } from "../../state/registry"; import { type ExecPolicyHintDeps, preparePolicyHint } from "./exec-policy-hint-integration"; -import { buildSandboxExecStdio } from "./exec-stdio"; import type { GatewaySelectResult } from "./gateway-select"; import { wrapExecCommandWithRuntimeEnv } from "./runtime-env"; @@ -25,12 +42,12 @@ export type SandboxExecOptions = { tty?: boolean | null; timeoutSeconds?: number; stdin?: boolean; - subprocessEnv?: NodeJS.ProcessEnv; }; export type SandboxExecChildOptions = SandboxExecOptions & { hostCwd?: string; hostEnv?: NodeJS.ProcessEnv; + subprocessEnv?: NodeJS.ProcessEnv; }; export type SandboxExecGatewayRestart = (sandboxName: string) => { ok: boolean }; @@ -49,29 +66,11 @@ export type SandboxExecRunner = ( args: readonly string[], ) => SpawnLikeResult | Promise; -export type SandboxExecChild = { - exitCode: number | null; - signalCode: NodeJS.Signals | null; - kill: (signal: NodeJS.Signals) => boolean; - once: { - (event: "error", listener: (error: Error) => void): unknown; - ( - event: "close", - listener: (code: number | null, signal: NodeJS.Signals | null) => void, - ): unknown; - }; -}; +export type SandboxExecChild = OpenShellCommandChild; -export type SandboxExecSpawner = ( - binary: string, - args: readonly string[], - options: SandboxExecChildOptions, -) => SandboxExecChild; +export type SandboxExecSpawner = OpenShellCommandSpawner; -export type SandboxExecSignalSource = { - add: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; - remove: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; -}; +export type SandboxExecSignalSource = OpenShellCommandSignalSource; export type SandboxExecCleanupDeps = { getSandbox: (sandboxName: string) => Pick | null; @@ -101,16 +100,15 @@ export function buildOpenshellExecArgs( options: SandboxExecOptions = {}, gatewayName?: string, ): string[] { - const argv = ["sandbox", "exec", "--name", sandboxName]; - if (gatewayName) argv.push("-g", gatewayName); - if (options.workdir) argv.push("--workdir", options.workdir); - if (options.tty === true) argv.push("--tty"); - if (options.tty === false) argv.push("--no-tty"); - if (typeof options.timeoutSeconds === "number") { - argv.push("--timeout", String(options.timeoutSeconds)); - } - argv.push("--", ...command); - return argv; + return buildCliOpenShellSandboxExecArgs({ + sandboxName, + target: gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(), + command, + workdir: options.workdir, + tty: options.tty, + timeoutSeconds: options.timeoutSeconds, + stdin: options.stdin, + }); } export function buildWorkdirProbeArgs( @@ -118,10 +116,11 @@ export function buildWorkdirProbeArgs( workdir: string, gatewayName?: string, ): string[] { - const argv = ["sandbox", "exec", "--name", sandboxName]; - if (gatewayName) argv.push("-g", gatewayName); - argv.push("--", "test", "-d", workdir); - return argv; + return buildCliOpenShellSandboxDirectoryProbeArgs({ + sandboxName, + target: gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(), + path: workdir, + }); } // OpenShell accepts LF/CR in command argv while retaining field-specific @@ -236,65 +235,19 @@ export function cleanupOpenClawAfterExec( return null; } -const defaultSandboxExecSpawner: SandboxExecSpawner = (binary, args, options) => - spawn(binary, [...args], { - stdio: buildSandboxExecStdio(options), - ...(options.hostCwd ? { cwd: options.hostCwd } : {}), - ...(options.hostEnv || options.subprocessEnv - ? { env: options.hostEnv ?? options.subprocessEnv } - : {}), - }); - -const defaultSandboxExecSignalSource: SandboxExecSignalSource = { - add: (signal, listener) => process.on(signal, listener), - remove: (signal, listener) => process.off(signal, listener), -}; - export async function runSandboxExecChild( binary: string, args: readonly string[], options: SandboxExecChildOptions = {}, - spawnChild: SandboxExecSpawner = defaultSandboxExecSpawner, - signalSource: SandboxExecSignalSource = defaultSandboxExecSignalSource, + spawnChild?: SandboxExecSpawner, + signalSource?: SandboxExecSignalSource, ): Promise { - let child: SandboxExecChild; - try { - child = spawnChild(binary, args, options); - } catch (error) { - return { status: null, error: error instanceof Error ? error : new Error(String(error)) }; - } - - return new Promise((resolve) => { - let spawnError: Error | undefined; - const forwardTerm = () => { - if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM"); - }; - // A terminal Ctrl+C is already delivered to every member of the foreground - // process group, including the non-detached OpenShell child. Hold SIGINT in - // the parent without re-sending it so one Ctrl+C stays one child signal and - // cleanup can finish. Headless/PID-targeted cancellation must use TERM; - // distinguishing its signal origin would require out-of-scope process-group - // or native siginfo machinery. - const holdInt = () => {}; - signalSource.add("SIGTERM", forwardTerm); - signalSource.add("SIGINT", holdInt); - child.once("error", (error) => { - spawnError = error; - }); - child.once("close", (status, signal) => { - resolve({ - status, - signal, - ...(spawnError ? { error: spawnError } : {}), - // Keep handlers installed through host-side permission cleanup. Once - // the child is reaped they suppress termination without forwarding. - releaseSignals: () => { - signalSource.remove("SIGTERM", forwardTerm); - signalSource.remove("SIGINT", holdInt); - }, - }); - }); - }); + const childOptions: OpenShellCommandChildOptions = { + stdin: options.stdin, + hostCwd: options.hostCwd, + hostEnv: options.hostEnv ?? options.subprocessEnv, + }; + return runCliOpenShellStreamingCommand(binary, args, childOptions, spawnChild, signalSource); } export async function runSandboxExecCommand( @@ -357,8 +310,6 @@ export function resolveSandboxExecBinary(): string { return getOpenshellBinary(); } -const defaultResolveBinary = resolveSandboxExecBinary; - function defaultSelectGateway(sandboxName: string): GatewaySelectResult { return ( require("./gateway-select") as typeof import("./gateway-select") @@ -369,11 +320,9 @@ function defaultSelectGateway(sandboxName: string): GatewaySelectResult { // inject them so the dispatch path stays hermetic without spawning a real // process or hitting the process-exiting OpenShell binary lookup. export type ExecSandboxDeps = { - /** Host lookup and pre-dispatch workdir seams. */ - resolveBinary?: () => string; - probeWorkdir?: WorkdirProbeRunner; - /** Command execution and post-command observability/cleanup seams. */ - run?: SandboxExecRunner; + /** Typed command execution and pre-dispatch workdir observation. */ + commandExecutor?: OpenShellSandboxCommandExecutor; + /** Post-command observability and cleanup seams. */ policyHint?: ExecPolicyHintDeps; cleanupDeps?: SandboxExecCleanupDeps; /** Activate config written by a successful direct Google Chat pairing approval. */ @@ -386,6 +335,42 @@ export type ExecSandboxDeps = { exit?: (code: number) => never; }; +async function runSandboxExecRequest( + executor: OpenShellSandboxCommandExecutor, + request: OpenShellSandboxCommandRequest, + cleanupDeps: SandboxExecCleanupDeps, +): Promise { + let completed: Awaited>; + try { + completed = await executor.runStreaming(request); + } catch (error) { + completed = { + outcome: { + kind: "failed", + error: { + kind: "invocation", + message: error instanceof Error ? error.message : String(error), + }, + }, + release: () => {}, + }; + } + try { + const commandCode = completed.outcome.kind === "completed" ? completed.outcome.exitCode : 1; + const invocationError = + completed.outcome.kind === "failed" ? completed.outcome.error.message : undefined; + const cleanupError = cleanupOpenClawAfterExec(request.sandboxName, cleanupDeps) ?? undefined; + return { + code: cleanupError ? 1 : commandCode, + commandCode, + ...(invocationError ? { invocationError } : {}), + ...(cleanupError ? { cleanupError } : {}), + }; + } finally { + completed.release(); + } +} + export function isGoogleChatPairingApproval(command: readonly string[]): boolean { return ( command.length >= 5 && @@ -451,7 +436,6 @@ export async function execSandbox( console.error(` Error: ${error instanceof Error ? error.message : String(error)}`); exit(1); } - const binary = (deps.resolveBinary ?? defaultResolveBinary)(); const gatewaySelection = (deps.selectGateway ?? defaultSelectGateway)(sandboxName); if (gatewaySelection.outcome === "failed") { console.error( @@ -461,15 +445,18 @@ export async function execSandbox( } const gatewayName = gatewaySelection.outcome === "selected" ? gatewaySelection.gatewayName : undefined; + const target = gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(); + const commandExecutor = deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor(); if (options.workdir) { - validateWorkdirOrFail( - binary, + const workdir = await commandExecutor.probeDirectory({ sandboxName, - options.workdir, - deps.probeWorkdir, - gatewayName, - exit, - ); + target, + path: options.workdir, + }); + if (workdir.state === "missing") { + console.error(workdirMissingMessage(options.workdir)); + exit(1); + } } const emitPolicyDenialHint = preparePolicyHint( CLI_NAME, @@ -478,12 +465,17 @@ export async function execSandbox( deps.policyHint, gatewayName, ); - const completion = await runSandboxExecCommand( - binary, - sandboxName, - wrapExecCommandWithRuntimeEnv(command), - options, - deps.run ?? ((runBinary, runArgs) => runSandboxExecChild(runBinary, runArgs, options)), + const completion = await runSandboxExecRequest( + commandExecutor, + { + sandboxName, + target, + command: wrapExecCommandWithRuntimeEnv(command), + workdir: options.workdir, + tty: options.tty, + timeoutSeconds: options.timeoutSeconds, + stdin: options.stdin, + }, deps.cleanupDeps ?? { getSandbox: (name) => (require("../../state/registry") as typeof import("../../state/registry")).getSandbox(name), @@ -496,7 +488,6 @@ export async function execSandbox( require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms") ).repairMutableConfigPerms(name), }, - gatewayName, ); if (completion.invocationError) { console.error(` Failed to invoke openshell: ${completion.invocationError}`); diff --git a/src/lib/adapters/openshell/sandbox-command-cli.test.ts b/src/lib/adapters/openshell/sandbox-command-cli.test.ts new file mode 100644 index 00000000000..3d1430b6dbc --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-command-cli.test.ts @@ -0,0 +1,233 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { EventEmitter } from "node:events"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + buildCliOpenShellSandboxExecArgs, + createCliOpenShellSandboxCommandExecutor, + type OpenShellCommandChild, + type OpenShellCommandSignalSource, +} from "./sandbox-command-cli"; +import { namedOpenShellGateway, selectedOpenShellGateway } from "./sandbox-observer"; + +function completedChild( + status: number | null, + signal: NodeJS.Signals | null = null, +): OpenShellCommandChild { + const events = new EventEmitter(); + const child: OpenShellCommandChild = { + exitCode: null, + signalCode: null, + kill: vi.fn(() => true), + once: ((event: string, listener: (...args: unknown[]) => void) => { + events.once(event, listener); + const notify = { + error: () => undefined, + close: () => queueMicrotask(() => events.emit("close", status, signal)), + }[event as "error" | "close"]; + notify(); + return child; + }) as OpenShellCommandChild["once"], + }; + return child; +} + +describe("CLI OpenShell sandbox command executor", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("keeps exact command bytes and CLI flags inside the implementation", () => { + const command = ["python3", "-c", "print('one')\nprint('two')"]; + expect( + buildCliOpenShellSandboxExecArgs({ + sandboxName: "alpha", + target: namedOpenShellGateway("nemoclaw-8091"), + command, + workdir: "/sandbox/work space", + tty: false, + timeoutSeconds: 30, + stdin: true, + }), + ).toEqual([ + "sandbox", + "exec", + "--name", + "alpha", + "-g", + "nemoclaw-8091", + "--workdir", + "/sandbox/work space", + "--no-tty", + "--timeout", + "30", + "--", + ...command, + ]); + }); + + it("streams with the configured host process authority and preserves a remote nonzero exit", async () => { + const spawnChild = vi.fn(() => completedChild(42)); + const hostEnv = { PATH: "/trusted/bin" }; + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + spawnChild, + hostCwd: "/repo", + hostEnv, + }); + + const completed = await executor.runStreaming({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["false"], + stdin: false, + }); + + expect(completed.outcome).toEqual({ kind: "completed", exitCode: 42 }); + expect(spawnChild).toHaveBeenCalledWith( + "/usr/bin/openshell", + ["sandbox", "exec", "--name", "alpha", "--", "false"], + { stdin: false, hostCwd: "/repo", hostEnv }, + ); + completed.release(); + }); + + it("distinguishes an unavailable executable without spawning", async () => { + const spawnChild = vi.fn(); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => null, + spawnChild, + }); + + const completed = await executor.runStreaming({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["true"], + }); + + expect(completed.outcome).toEqual({ + kind: "failed", + error: { kind: "unavailable", message: "OpenShell binary not found" }, + }); + expect(spawnChild).not.toHaveBeenCalled(); + }); + + it("distinguishes a host timeout from a remote nonzero exit", async () => { + const timeout = Object.assign(new Error("OpenShell command timed out"), { + code: "ETIMEDOUT", + }); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + spawnChild: () => { + throw timeout; + }, + }); + + const completed = await executor.runStreaming({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["sleep", "30"], + }); + + expect(completed.outcome).toEqual({ + kind: "failed", + error: { kind: "timeout", message: "OpenShell command timed out" }, + }); + }); + + it.each([ + [0, "present"], + [1, "missing"], + [2, "unobservable"], + [null, "unobservable"], + ] as const)("maps directory probe status %s to %s", async (status, state) => { + const spawnProbe = vi.fn(() => ({ status })); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + spawnProbe, + }); + + expect( + await executor.probeDirectory({ + sandboxName: "alpha", + target: namedOpenShellGateway("nemoclaw-8091"), + path: "/sandbox/work", + }), + ).toMatchObject({ state }); + expect(spawnProbe).toHaveBeenCalledWith("/usr/bin/openshell", [ + "sandbox", + "exec", + "--name", + "alpha", + "-g", + "nemoclaw-8091", + "--", + "test", + "-d", + "/sandbox/work", + ]); + }); + + it("holds TERM handlers until command-dependent cleanup releases the stream", async () => { + const childEvents = new EventEmitter(); + const signalEvents = new EventEmitter(); + const child: OpenShellCommandChild = { + exitCode: null, + signalCode: null, + kill: vi.fn((signal) => { + child.signalCode = signal; + queueMicrotask(() => childEvents.emit("close", null, signal)); + return true; + }), + once: ((event: string, listener: (...args: unknown[]) => void) => + childEvents.once(event, listener)) as OpenShellCommandChild["once"], + }; + const signalSource: OpenShellCommandSignalSource = { + add: (signal, listener) => signalEvents.on(signal, listener), + remove: (signal, listener) => signalEvents.off(signal, listener), + }; + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + spawnChild: () => child, + signalSource, + }); + + const pending = executor.runStreaming({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["sleep", "30"], + }); + signalEvents.emit("SIGTERM"); + const completed = await pending; + + expect(completed.outcome).toEqual({ + kind: "completed", + exitCode: 143, + signal: "SIGTERM", + }); + expect(child.kill).toHaveBeenCalledWith("SIGTERM"); + expect(signalEvents.listenerCount("SIGTERM")).toBe(1); + completed.release(); + expect(signalEvents.listenerCount("SIGTERM")).toBe(0); + expect(signalEvents.listenerCount("SIGINT")).toBe(0); + }); + + it("rejects endpoint overrides before resolving or spawning", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://sibling.invalid"); + const resolveBinary = vi.fn(() => "/usr/bin/openshell"); + const spawnChild = vi.fn(); + const executor = createCliOpenShellSandboxCommandExecutor({ resolveBinary, spawnChild }); + + await expect( + executor.runStreaming({ + sandboxName: "alpha", + target: namedOpenShellGateway("nemoclaw-8091"), + command: ["true"], + }), + ).rejects.toThrow("OPENSHELL_GATEWAY_ENDPOINT is set"); + expect(resolveBinary).not.toHaveBeenCalled(); + expect(spawnChild).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/adapters/openshell/sandbox-command-cli.ts b/src/lib/adapters/openshell/sandbox-command-cli.ts new file mode 100644 index 00000000000..a310092bd27 --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-command-cli.ts @@ -0,0 +1,261 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawn, spawnSync, type SpawnSyncReturns } from "node:child_process"; + +import { spawnExitCode } from "../../core/process-exit"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; +import { isValidName } from "../../sandbox-name-contract"; +import { resolveOpenshellBinaryOrNull } from "./resolve-shared"; +import { + type OpenShellSandboxCommandCompletion, + type OpenShellSandboxCommandExecutor, + type OpenShellSandboxCommandRequest, + type OpenShellSandboxCommandOutcome, +} from "./sandbox-command"; +import { buildSandboxCommandStdio } from "./sandbox-command-stdio"; +import type { OpenShellGatewayTarget } from "./sandbox-observer"; + +export type OpenShellCommandChild = { + exitCode: number | null; + signalCode: NodeJS.Signals | null; + kill: (signal: NodeJS.Signals) => boolean; + once: { + (event: "error", listener: (error: Error) => void): unknown; + ( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): unknown; + }; +}; + +export type OpenShellCommandSpawner = ( + binary: string, + args: readonly string[], + options: OpenShellCommandChildOptions, +) => OpenShellCommandChild; + +export type OpenShellCommandSignalSource = { + add: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; + remove: (signal: "SIGTERM" | "SIGINT", listener: () => void) => void; +}; + +export type OpenShellCommandChildOptions = Readonly<{ + stdin?: boolean; + hostCwd?: string; + hostEnv?: NodeJS.ProcessEnv; +}>; + +export type OpenShellCommandSpawnResult = Readonly<{ + status: number | null; + signal?: NodeJS.Signals | null; + error?: Error; + releaseSignals?: () => void; +}>; + +export type OpenShellCommandProbeRunner = ( + binary: string, + args: readonly string[], +) => Pick, "error" | "status">; + +export type CliOpenShellSandboxCommandExecutorDeps = Readonly<{ + resolveBinary?: () => string | null; + spawnChild?: OpenShellCommandSpawner; + spawnProbe?: OpenShellCommandProbeRunner; + signalSource?: OpenShellCommandSignalSource; + hostCwd?: string; + hostEnv?: NodeJS.ProcessEnv; +}>; + +function targetArgs(target: OpenShellGatewayTarget): string[] { + return target.kind === "named" ? ["-g", target.gatewayName] : []; +} + +function assertTarget(target: OpenShellGatewayTarget): void { + if (target.kind === "named" && !isValidName(target.gatewayName)) { + throw new Error("Invalid OpenShell gateway name"); + } + assertNoOpenShellGatewayEndpointOverride(); +} + +function assertSandboxName(sandboxName: string): void { + if (!isValidName(sandboxName)) throw new Error("Invalid OpenShell sandbox name"); +} + +export function buildCliOpenShellSandboxExecArgs( + request: OpenShellSandboxCommandRequest, +): string[] { + const argv = ["sandbox", "exec", "--name", request.sandboxName, ...targetArgs(request.target)]; + if (request.workdir) argv.push("--workdir", request.workdir); + if (request.tty === true) argv.push("--tty"); + if (request.tty === false) argv.push("--no-tty"); + if (typeof request.timeoutSeconds === "number") { + argv.push("--timeout", String(request.timeoutSeconds)); + } + argv.push("--", ...request.command); + return argv; +} + +export function buildCliOpenShellSandboxDirectoryProbeArgs(request: { + sandboxName: string; + target: OpenShellGatewayTarget; + path: string; +}): string[] { + return [ + "sandbox", + "exec", + "--name", + request.sandboxName, + ...targetArgs(request.target), + "--", + "test", + "-d", + request.path, + ]; +} + +const defaultSpawner: OpenShellCommandSpawner = (binary, args, options) => + spawn(binary, [...args], { + stdio: buildSandboxCommandStdio(options), + ...(options.hostCwd ? { cwd: options.hostCwd } : {}), + ...(options.hostEnv ? { env: options.hostEnv } : {}), + }); + +const defaultSignalSource: OpenShellCommandSignalSource = { + add: (signal, listener) => process.on(signal, listener), + remove: (signal, listener) => process.off(signal, listener), +}; + +export async function runCliOpenShellStreamingCommand( + binary: string, + args: readonly string[], + options: OpenShellCommandChildOptions = {}, + spawnChild: OpenShellCommandSpawner = defaultSpawner, + signalSource: OpenShellCommandSignalSource = defaultSignalSource, +): Promise { + let child: OpenShellCommandChild; + try { + child = spawnChild(binary, args, options); + } catch (error) { + return { status: null, error: error instanceof Error ? error : new Error(String(error)) }; + } + + return new Promise((resolve) => { + let spawnError: Error | undefined; + const forwardTerm = () => { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM"); + }; + // A terminal Ctrl+C already reaches every member of the foreground process + // group. Hold it in the parent without delivering it to the child twice. + const holdInt = () => {}; + signalSource.add("SIGTERM", forwardTerm); + signalSource.add("SIGINT", holdInt); + child.once("error", (error) => { + spawnError = error; + }); + child.once("close", (status, signal) => { + resolve({ + status, + signal, + ...(spawnError ? { error: spawnError } : {}), + releaseSignals: () => { + signalSource.remove("SIGTERM", forwardTerm); + signalSource.remove("SIGINT", holdInt); + }, + }); + }); + }); +} + +function commandError(error: Error) { + const code = (error as NodeJS.ErrnoException).code; + return { + kind: code === "ENOENT" ? "unavailable" : code === "ETIMEDOUT" ? "timeout" : "invocation", + message: error.message, + } as const; +} + +function commandFailure(error: Error): OpenShellSandboxCommandOutcome { + return { kind: "failed", error: commandError(error) }; +} + +function commandCompletion(result: OpenShellCommandSpawnResult): OpenShellSandboxCommandCompletion { + return { + outcome: result.error + ? commandFailure(result.error) + : { + kind: "completed", + exitCode: spawnExitCode(result), + ...(result.signal ? { signal: result.signal } : {}), + }, + release: result.releaseSignals ?? (() => {}), + }; +} + +function unavailableBinary(): OpenShellSandboxCommandCompletion { + return { + outcome: { + kind: "failed", + error: { kind: "unavailable", message: "OpenShell binary not found" }, + }, + release: () => {}, + }; +} + +export function createCliOpenShellSandboxCommandExecutor( + deps: CliOpenShellSandboxCommandExecutorDeps = {}, +): OpenShellSandboxCommandExecutor { + const resolveBinary = deps.resolveBinary ?? resolveOpenshellBinaryOrNull; + const spawnProbe = + deps.spawnProbe ?? + ((binary, args) => spawnSync(binary, [...args], { stdio: ["ignore", "ignore", "ignore"] })); + return { + probeDirectory: async (request) => { + assertSandboxName(request.sandboxName); + assertTarget(request.target); + const binary = resolveBinary(); + if (!binary) { + return { + state: "unobservable", + error: { kind: "unavailable", message: "OpenShell binary not found" }, + }; + } + let result: Pick, "error" | "status">; + try { + result = spawnProbe(binary, buildCliOpenShellSandboxDirectoryProbeArgs(request)); + } catch (error) { + const invocation = error instanceof Error ? error : new Error(String(error)); + return { + state: "unobservable", + error: commandError(invocation), + }; + } + if (result.error || result.status === null) { + return { + state: "unobservable", + ...(result.error ? { error: commandError(result.error) } : {}), + }; + } + if (result.status === 0) return { state: "present" }; + return result.status === 1 ? { state: "missing" } : { state: "unobservable" }; + }, + runStreaming: async (request) => { + assertSandboxName(request.sandboxName); + assertTarget(request.target); + const binary = resolveBinary(); + if (!binary) return unavailableBinary(); + const result = await runCliOpenShellStreamingCommand( + binary, + buildCliOpenShellSandboxExecArgs(request), + { + stdin: request.stdin, + hostCwd: deps.hostCwd, + hostEnv: deps.hostEnv, + }, + deps.spawnChild, + deps.signalSource, + ); + return commandCompletion(result); + }, + }; +} diff --git a/src/lib/adapters/openshell/sandbox-command-stdio.ts b/src/lib/adapters/openshell/sandbox-command-stdio.ts new file mode 100644 index 00000000000..3f304ac8017 --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-command-stdio.ts @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { StdioOptions } from "node:child_process"; + +import { isStdinTty } from "../../core/stdin"; + +export function shouldInheritSandboxCommandStdin( + requested: boolean | undefined, + stdinIsTty: boolean | undefined, +): boolean { + if (typeof requested === "boolean") return requested; + return stdinIsTty === true; +} + +export function buildSandboxCommandStdio( + options: { stdin?: boolean } = {}, + stdinIsTty: boolean | undefined = isStdinTty(), +): StdioOptions { + return shouldInheritSandboxCommandStdin(options.stdin, stdinIsTty) + ? "inherit" + : ["ignore", "inherit", "inherit"]; +} diff --git a/src/lib/adapters/openshell/sandbox-command.ts b/src/lib/adapters/openshell/sandbox-command.ts new file mode 100644 index 00000000000..1639998c8da --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-command.ts @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { OpenShellGatewayTarget } from "./sandbox-observer"; + +export type OpenShellSandboxCommandRequest = Readonly<{ + sandboxName: string; + target: OpenShellGatewayTarget; + command: readonly string[]; + workdir?: string; + tty?: boolean | null; + timeoutSeconds?: number; + stdin?: boolean; +}>; + +export type OpenShellSandboxCommandError = Readonly<{ + kind: "invocation" | "timeout" | "unavailable"; + message: string; +}>; + +export type OpenShellSandboxCommandOutcome = + | Readonly<{ + kind: "completed"; + exitCode: number; + signal?: NodeJS.Signals | null; + }> + | Readonly<{ + kind: "failed"; + error: OpenShellSandboxCommandError; + }>; + +/** + * A streaming command keeps its host signal handlers until the consumer has + * completed any command-dependent cleanup. + */ +export type OpenShellSandboxCommandCompletion = Readonly<{ + outcome: OpenShellSandboxCommandOutcome; + release: () => void; +}>; + +export type OpenShellSandboxDirectoryProbe = + | Readonly<{ state: "present" }> + | Readonly<{ state: "missing" }> + | Readonly<{ state: "unobservable"; error?: OpenShellSandboxCommandError }>; + +/** Transport-neutral streamed command capabilities used by NemoClaw actions. */ +export interface OpenShellSandboxCommandExecutor { + probeDirectory(request: { + sandboxName: string; + target: OpenShellGatewayTarget; + path: string; + }): Promise; + runStreaming(request: OpenShellSandboxCommandRequest): Promise; +} From 5948473d16caeeb7a3d5875fefe4c5351153b720 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 3 Sep 2026 13:15:52 -0700 Subject: [PATCH 2/3] fix(cli): complete streamed exec cutover Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/source-architecture-budget.json | 2 +- .../sandbox/exec-gateway-target.test.ts | 119 ++++++++ .../exec-openclaw-permission-cleanup.test.ts | 267 +++++++++++------- src/lib/actions/sandbox/exec.test.ts | 101 ------- src/lib/actions/sandbox/exec.ts | 117 ++------ src/lib/actions/sandbox/launch.test.ts | 1 - .../openshell/sandbox-command-cli.test.ts | 42 +++ .../onboard-installer-restore-intent.test.ts | 70 +++-- 8 files changed, 394 insertions(+), 325 deletions(-) diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 82856349185..ca1b2cf74fa 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -8,7 +8,7 @@ "src/lib/adapters/docker/index.ts": 42, "src/lib/adapters/openshell/client.ts": 21, "src/lib/adapters/openshell/resolve.ts": 25, - "src/lib/adapters/openshell/runtime.ts": 54, + "src/lib/adapters/openshell/runtime.ts": 53, "src/lib/adapters/openshell/timeouts.ts": 33, "src/lib/agent/defs.ts": 32, "src/lib/cli/branding.ts": 80, diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts index 7b5a199343f..385221fca39 100644 --- a/src/lib/actions/sandbox/exec-gateway-target.test.ts +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -3,6 +3,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { + createCliOpenShellSandboxCommandExecutor, + type OpenShellCommandChild, + type OpenShellCommandSpawner, +} from "../../adapters/openshell/sandbox-command-cli"; import type { OpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { execSandbox, type SandboxExecCleanupDeps } from "./exec"; @@ -145,6 +150,120 @@ describe("execSandbox gateway targeting", () => { expect(run.mock.calls[0]?.[0].command.at(-1)).toBe("hostname"); }); + it("carries the selected gateway through the CLI workdir probe and command dispatch", async () => { + const spawnProbe = vi.fn(() => ({ status: 0 })); + const child = { + exitCode: null, + signalCode: null, + kill: vi.fn(() => true), + once: vi.fn((event: "error" | "close", listener: (...args: unknown[]) => void) => { + const notify = { + error: () => undefined, + close: () => queueMicrotask(() => listener(0, null)), + }[event]; + notify(); + return child; + }), + } as unknown as OpenShellCommandChild; + const spawnChild = vi.fn(() => child); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + spawnProbe, + spawnChild, + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { + selectGateway: () => ({ + outcome: "selected", + gatewayName: "nemoclaw-8091", + }), + commandExecutor: executor, + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, + }, + ), + ).rejects.toThrow("__exit_0__"); + + expect(spawnProbe).toHaveBeenCalledWith("/usr/bin/openshell", [ + "sandbox", + "exec", + "--name", + "beta", + "-g", + "nemoclaw-8091", + "--", + "test", + "-d", + "/work", + ]); + expect(spawnChild.mock.calls[0]?.[0]).toBe("/usr/bin/openshell"); + const execArgs = spawnChild.mock.calls[0]?.[1]; + expect(execArgs?.slice(0, 9)).toEqual([ + "sandbox", + "exec", + "--name", + "beta", + "-g", + "nemoclaw-8091", + "--workdir", + "/work", + "--", + ]); + expect(execArgs?.at(-1)).toBe("hostname"); + }); + + it("reports a rejected workdir probe as a normal invocation failure", async () => { + const resolveBinary = vi.fn(() => "/usr/bin/openshell"); + const spawnProbe = vi.fn(); + const spawnChild = vi.fn(); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary, + spawnProbe, + spawnChild, + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "invalid/name", + ["hostname"], + { workdir: "/work" }, + { + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: executor, + cleanupDeps: cleanupSkipped, + }, + ), + ).rejects.toThrow("__exit_1__"); + + expect(console.error).toHaveBeenCalledWith( + " Failed to invoke openshell: Invalid OpenShell sandbox name", + ); + expect(resolveBinary).not.toHaveBeenCalled(); + expect(spawnProbe).not.toHaveBeenCalled(); + expect(spawnChild).not.toHaveBeenCalled(); + }); + it("rejects a direct endpoint override before selecting, probing, or dispatching", async () => { vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://sibling.invalid"); const selectGateway = vi.fn(); diff --git a/src/lib/actions/sandbox/exec-openclaw-permission-cleanup.test.ts b/src/lib/actions/sandbox/exec-openclaw-permission-cleanup.test.ts index 392f6a5757c..4f1bae9a318 100644 --- a/src/lib/actions/sandbox/exec-openclaw-permission-cleanup.test.ts +++ b/src/lib/actions/sandbox/exec-openclaw-permission-cleanup.test.ts @@ -4,10 +4,13 @@ import { EventEmitter } from "node:events"; import { describe, expect, it, vi } from "vitest"; +import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; +import type { + OpenShellSandboxCommandExecutor, + OpenShellSandboxCommandOutcome, +} from "../../adapters/openshell/sandbox-command"; import { - cleanupFailureMessage, - runSandboxExecChild, - runSandboxExecCommand, + execSandbox, type SandboxExecChild, type SandboxExecCleanupDeps, type SandboxExecSignalSource, @@ -45,20 +48,80 @@ function cleanupDeps(overrides: Partial = {}): SandboxEx }; } -describe("runSandboxExecCommand mutable OpenClaw cleanup (#6047)", () => { - it("preserves a nonzero command status when the mutable contract is already healthy", async () => { - const repair = vi.fn(() => ({ applied: true as const, verified: true, errors: [] })); - const completion = await runSandboxExecCommand( - "openshell", +async function runExecCase(options: { + cleanupDeps: SandboxExecCleanupDeps; + command?: readonly string[]; + executor?: OpenShellSandboxCommandExecutor; + onRun?: () => void; + outcome?: OpenShellSandboxCommandOutcome; + release?: () => void; +}): Promise<{ exitCode: number; stderr: string[] }> { + const exitSignal = new Error("__exec_exit__"); + const stderr: string[] = []; + let exitCode = Number.NaN; + const executor = + options.executor ?? + ({ + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => { + options.onRun?.(); + return { + outcome: options.outcome ?? { kind: "completed", exitCode: 0 }, + release: options.release ?? (() => {}), + }; + }, + } satisfies OpenShellSandboxCommandExecutor); + const errorSpy = vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + stderr.push(args.map(String).join(" ")); + }); + + try { + await execSandbox( "alpha", - ["false"], + options.command ?? ["true"], {}, - () => ({ status: 42 }), - cleanupDeps({ repairMutableConfigPerms: repair }), + { + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: executor, + cleanupDeps: options.cleanupDeps, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, + exit: ((code: number) => { + exitCode = code; + throw exitSignal; + }) as (code: number) => never, + }, ); + throw new Error("execSandbox returned without exiting"); + } catch (error) { + expect(error).toBe(exitSignal); + } finally { + errorSpy.mockRestore(); + } + return { exitCode, stderr }; +} - expect(completion).toEqual({ code: 42, commandCode: 42 }); +describe("execSandbox mutable OpenClaw cleanup (#6047)", () => { + it("preserves a nonzero command status when the mutable contract is already healthy", async () => { + const repair = vi.fn(() => ({ applied: true as const, verified: true, errors: [] })); + const release = vi.fn(); + const result = await runExecCase({ + command: ["false"], + outcome: { kind: "completed", exitCode: 42 }, + cleanupDeps: cleanupDeps({ repairMutableConfigPerms: repair }), + release, + }); + + expect(result.exitCode).toBe(42); expect(repair).not.toHaveBeenCalled(); + expect(release).toHaveBeenCalledOnce(); }); it("repairs a tightened tree after the command, re-inspects it, and preserves status 42", async () => { @@ -78,44 +141,40 @@ describe("runSandboxExecCommand mutable OpenClaw cleanup (#6047)", () => { return { applied: true as const, verified: true, errors: [] }; }); - const completion = await runSandboxExecCommand( - "openshell", - "alpha", - ["bash", "-c", "openclaw doctor --fix"], - {}, - () => { - order.push("command"); - return { status: 42 }; - }, - cleanupDeps({ inspectMutableConfigPerms: inspect, repairMutableConfigPerms: repair }), - ); + const result = await runExecCase({ + command: ["bash", "-c", "openclaw doctor --fix"], + outcome: { kind: "completed", exitCode: 42 }, + onRun: () => order.push("command"), + cleanupDeps: cleanupDeps({ + inspectMutableConfigPerms: inspect, + repairMutableConfigPerms: repair, + }), + release: () => order.push("release"), + }); - expect(completion).toEqual({ code: 42, commandCode: 42 }); - expect(order).toEqual(["command", "inspect-before", "repair", "inspect-after"]); + expect(result.exitCode).toBe(42); + expect(order).toEqual(["command", "inspect-before", "repair", "inspect-after", "release"]); }); it("lets cleanup failure override status 42 and reports both statuses", async () => { - const completion = await runSandboxExecCommand( - "openshell", - "alpha", - ["false"], - {}, - () => ({ status: 42 }), - cleanupDeps({ + const order: string[] = []; + const result = await runExecCase({ + command: ["false"], + outcome: { kind: "completed", exitCode: 42 }, + cleanupDeps: cleanupDeps({ inspectMutableConfigPerms: () => TIGHTENED_MUTABLE_CONFIG, - repairMutableConfigPerms: () => ({ - applied: true, - verified: false, - errors: ["chmod denied"], - }), + repairMutableConfigPerms: () => { + order.push("repair"); + return { applied: true, verified: false, errors: ["chmod denied"] }; + }, }), - ); + release: () => order.push("release"), + }); - expect(completion).toMatchObject({ code: 1, commandCode: 42 }); - expect(completion.cleanupError).toContain("chmod denied"); - expect(cleanupFailureMessage(completion.commandCode, completion.cleanupError || "")).toContain( - "command exit 42; cleanup exit 1", - ); + expect(result.exitCode).toBe(1); + expect(result.stderr.join("\n")).toContain("command exit 42; cleanup exit 1"); + expect(result.stderr.join("\n")).toContain("chmod denied"); + expect(order).toEqual(["repair", "release"]); }); it.each([ @@ -126,58 +185,51 @@ describe("runSandboxExecCommand mutable OpenClaw cleanup (#6047)", () => { const inspect = vi.fn(() => HEALTHY_MUTABLE_CONFIG); const repair = vi.fn(() => ({ applied: true as const, verified: true, errors: [] })); - const completion = await runSandboxExecCommand( - "openshell", - "alpha", - ["true"], - {}, - () => ({ status: 0 }), - cleanupDeps({ + const result = await runExecCase({ + outcome: { kind: "completed", exitCode: 0 }, + cleanupDeps: cleanupDeps({ getSandbox: () => entry, inspectMutableConfigPerms: inspect, repairMutableConfigPerms: repair, }), - ); + }); - expect(completion).toEqual({ code: 0, commandCode: 0 }); + expect(result.exitCode).toBe(0); expect(inspect).not.toHaveBeenCalled(); expect(repair).not.toHaveBeenCalled(); }); it("still verifies cleanup after an OpenShell transport failure", async () => { const inspect = vi.fn(() => HEALTHY_MUTABLE_CONFIG); - const completion = await runSandboxExecCommand( - "openshell", - "alpha", - ["true"], - {}, - () => ({ status: null, error: new Error("ENOENT") }), - cleanupDeps({ inspectMutableConfigPerms: inspect }), - ); + const release = vi.fn(); + const result = await runExecCase({ + outcome: { kind: "failed", error: { kind: "unavailable", message: "ENOENT" } }, + cleanupDeps: cleanupDeps({ inspectMutableConfigPerms: inspect }), + release, + }); - expect(completion).toEqual({ code: 1, commandCode: 1, invocationError: "ENOENT" }); + expect(result.exitCode).toBe(1); + expect(result.stderr.join("\n")).toContain("Failed to invoke openshell: ENOENT"); expect(inspect).toHaveBeenCalledOnce(); + expect(release).toHaveBeenCalledOnce(); }); it("reports registry read failure as cleanup failure after the command", async () => { const inspect = vi.fn(() => HEALTHY_MUTABLE_CONFIG); - const completion = await runSandboxExecCommand( - "openshell", - "alpha", - ["false"], - {}, - () => ({ status: 42 }), - cleanupDeps({ + const result = await runExecCase({ + command: ["false"], + outcome: { kind: "completed", exitCode: 42 }, + cleanupDeps: cleanupDeps({ getSandbox: () => { throw new Error("invalid registry JSON"); }, inspectMutableConfigPerms: inspect, }), - ); + }); - expect(completion).toMatchObject({ code: 1, commandCode: 42 }); - expect(completion.cleanupError).toContain("sandbox registry lookup failed"); - expect(completion.cleanupError).toContain("invalid registry JSON"); + expect(result.exitCode).toBe(1); + expect(result.stderr.join("\n")).toContain("sandbox registry lookup failed"); + expect(result.stderr.join("\n")).toContain("invalid registry JSON"); expect(inspect).not.toHaveBeenCalled(); }); @@ -204,7 +256,14 @@ describe("runSandboxExecCommand mutable OpenClaw cleanup (#6047)", () => { }; const signalSource: SandboxExecSignalSource = { add: (name, listener) => signalEvents.on(name, listener), - remove: (name, listener) => signalEvents.off(name, listener), + remove: (name, listener) => { + const recordRelease = { + SIGTERM: () => order.push("release"), + SIGINT: () => undefined, + }[name]; + recordRelease(); + signalEvents.off(name, listener); + }, }; const inspect = vi.fn(() => { order.push("cleanup"); @@ -213,21 +272,23 @@ describe("runSandboxExecCommand mutable OpenClaw cleanup (#6047)", () => { return HEALTHY_MUTABLE_CONFIG; }); - const pending = runSandboxExecCommand( - "openshell", - "alpha", - ["sleep", "30"], - {}, - (binary, args) => runSandboxExecChild(binary, args, {}, () => child, signalSource), - cleanupDeps({ inspectMutableConfigPerms: inspect }), - ); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "openshell", + spawnChild: () => child, + signalSource, + }); + const pending = runExecCase({ + command: ["sleep", "30"], + executor, + cleanupDeps: cleanupDeps({ inspectMutableConfigPerms: inspect }), + }); signalEvents.emit(signal); - const completion = await pending; + const result = await pending; - expect(completion).toEqual({ code, commandCode: code }); + expect(result.exitCode).toBe(code); expect(child.kill).toHaveBeenCalledWith(signal); expect(child.kill).toHaveBeenCalledTimes(1); - expect(order).toEqual([`kill:${signal}`, "close", "cleanup"]); + expect(order).toEqual([`kill:${signal}`, "close", "cleanup", "release"]); expect(signalEvents.listenerCount("SIGTERM")).toBe(0); expect(signalEvents.listenerCount("SIGINT")).toBe(0); }); @@ -252,20 +313,22 @@ describe("runSandboxExecCommand mutable OpenClaw cleanup (#6047)", () => { return HEALTHY_MUTABLE_CONFIG; }); - const pending = runSandboxExecCommand( - "openshell", - "alpha", - ["sleep", "30"], - {}, - (binary, args) => runSandboxExecChild(binary, args, {}, () => child, signalSource), - cleanupDeps({ inspectMutableConfigPerms: inspect }), - ); + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "openshell", + spawnChild: () => child, + signalSource, + }); + const pending = runExecCase({ + command: ["sleep", "30"], + executor, + cleanupDeps: cleanupDeps({ inspectMutableConfigPerms: inspect }), + }); signalEvents.emit("SIGINT"); child.signalCode = "SIGINT"; childEvents.emit("close", null, "SIGINT"); - const completion = await pending; + const result = await pending; - expect(completion).toEqual({ code: 130, commandCode: 130 }); + expect(result.exitCode).toBe(130); expect(child.kill).not.toHaveBeenCalled(); expect(inspect).toHaveBeenCalledOnce(); expect(signalEvents.listenerCount("SIGINT")).toBe(0); @@ -281,16 +344,12 @@ describe("runSandboxExecCommand mutable OpenClaw cleanup (#6047)", () => { reason: "could not stat config (container stopped)", }); - const completion = await runSandboxExecCommand( - "openshell", - "alpha", - ["true"], - {}, - () => ({ status: 0 }), - cleanupDeps({ inspectMutableConfigPerms: inspect }), - ); + const result = await runExecCase({ + outcome: { kind: "completed", exitCode: 0 }, + cleanupDeps: cleanupDeps({ inspectMutableConfigPerms: inspect }), + }); - expect(completion).toMatchObject({ code: 1, commandCode: 0 }); - expect(completion.cleanupError).toContain("post-repair permission verification unavailable"); + expect(result.exitCode).toBe(1); + expect(result.stderr.join("\n")).toContain("post-repair permission verification unavailable"); }); }); diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts index da43f36d87a..b73fdac8e84 100644 --- a/src/lib/actions/sandbox/exec.test.ts +++ b/src/lib/actions/sandbox/exec.test.ts @@ -15,15 +15,12 @@ vi.mock("node:child_process", async (importOriginal) => ({ // and the workdir probe. import { buildOpenshellExecArgs, - buildWorkdirProbeArgs, computeExitCode, - evaluateWorkdirProbe, execSandbox, runSandboxExecChild, type SandboxExecChild, type SandboxExecCleanupDeps, type SandboxExecSignalSource, - validateWorkdirOrFail, workdirMissingMessage, } from "./exec"; @@ -194,26 +191,6 @@ describe("computeExitCode", () => { }); }); -describe("buildWorkdirProbeArgs", () => { - it("targets the sandbox by name and probes the directory with test -d", () => { - expect(buildWorkdirProbeArgs("alpha", "/sandbox/workspace")).toEqual([ - "sandbox", - "exec", - "--name", - "alpha", - "--", - "test", - "-d", - "/sandbox/workspace", - ]); - }); - - it("does not split a path argument that contains whitespace", () => { - const argv = buildWorkdirProbeArgs("alpha", "/sandbox/with spaces/dir"); - expect(argv[argv.length - 1]).toBe("/sandbox/with spaces/dir"); - }); -}); - describe("workdirMissingMessage", () => { it("renders a user-facing CLI error with the offending path", () => { expect(workdirMissingMessage("/sandbox/workspace")).toBe( @@ -222,84 +199,6 @@ describe("workdirMissingMessage", () => { }); }); -describe("evaluateWorkdirProbe", () => { - it("returns 'ok' when the probe exits 0", () => { - expect(evaluateWorkdirProbe({ status: 0 })).toBe("ok"); - }); - - it("returns 'missing' only for the canonical test -d failure (exit 1)", () => { - expect(evaluateWorkdirProbe({ status: 1 })).toBe("missing"); - }); - - it("returns 'unclear' for any other exit code so the main exec surfaces it", () => { - expect(evaluateWorkdirProbe({ status: 2 })).toBe("unclear"); - expect(evaluateWorkdirProbe({ status: 127 })).toBe("unclear"); - expect(evaluateWorkdirProbe({ status: null })).toBe("unclear"); - }); - - it("returns 'unclear' when spawn reports a transport error", () => { - expect(evaluateWorkdirProbe({ status: null, error: new Error("ENOENT") })).toBe("unclear"); - }); -}); - -describe("validateWorkdirOrFail", () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("passes through when the directory exists", () => { - const run = vi.fn(() => ({ status: 0 })); - const exitSpy = vi.spyOn(process, "exit").mockImplementation(((_code?: number) => { - throw new Error("process.exit should not be called for ok outcome"); - }) as never); - const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - - validateWorkdirOrFail("openshell", "alpha", "/sandbox/workspace", run); - - expect(run).toHaveBeenCalledWith("openshell", [ - "sandbox", - "exec", - "--name", - "alpha", - "--", - "test", - "-d", - "/sandbox/workspace", - ]); - expect(exitSpy).not.toHaveBeenCalled(); - expect(errSpy).not.toHaveBeenCalled(); - }); - - it("prints a friendly error and exits 1 when the directory is missing", () => { - const run = vi.fn(() => ({ status: 1 })); - const exitSpy = vi.spyOn(process, "exit").mockImplementation(((_code?: number) => { - throw new Error("exit"); - }) as never); - const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - - expect(() => validateWorkdirOrFail("openshell", "alpha", "/sandbox/workspace", run)).toThrow( - "exit", - ); - expect(errSpy).toHaveBeenCalledWith( - "error: --workdir: /sandbox/workspace does not exist inside the sandbox", - ); - expect(exitSpy).toHaveBeenCalledWith(1); - }); - - it("does not abort when the probe outcome is unclear (lets main exec surface it)", () => { - const run = vi.fn(() => ({ status: 127 })); - const exitSpy = vi.spyOn(process, "exit").mockImplementation(((_code?: number) => { - throw new Error("process.exit should not be called for unclear outcome"); - }) as never); - const errSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - - validateWorkdirOrFail("openshell", "alpha", "/sandbox/workspace", run); - - expect(exitSpy).not.toHaveBeenCalled(); - expect(errSpy).not.toHaveBeenCalled(); - }); -}); - // End-to-end wiring of the post-exec policy-denial hint through execSandbox // (#5978): proves the breadcrumb fires for a denied failure while the command's // exit code is preserved, and stays silent on success and unrelated failures. diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index bc769aa6458..809131720eb 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -1,9 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; import { - buildCliOpenShellSandboxDirectoryProbeArgs, buildCliOpenShellSandboxExecArgs, createCliOpenShellSandboxCommandExecutor, runCliOpenShellStreamingCommand, @@ -61,11 +59,6 @@ export type SpawnLikeResult = { releaseSignals?: () => void; }; -export type SandboxExecRunner = ( - binary: string, - args: readonly string[], -) => SpawnLikeResult | Promise; - export type SandboxExecChild = OpenShellCommandChild; export type SandboxExecSpawner = OpenShellCommandSpawner; @@ -85,15 +78,10 @@ export type SandboxExecCompletion = { cleanupError?: string; }; -export type WorkdirProbeResult = { - status: number | null; - error?: Error; -}; - -export type WorkdirProbeOutcome = "ok" | "missing" | "unclear"; - -export type WorkdirProbeRunner = (binary: string, args: readonly string[]) => WorkdirProbeResult; - +/** + * Compatibility argv surface for buffered and interactive consumers tracked + * by #10991 and #10994. Remove it after those callers use typed executors. + */ export function buildOpenshellExecArgs( sandboxName: string, command: readonly string[], @@ -111,18 +99,6 @@ export function buildOpenshellExecArgs( }); } -export function buildWorkdirProbeArgs( - sandboxName: string, - workdir: string, - gatewayName?: string, -): string[] { - return buildCliOpenShellSandboxDirectoryProbeArgs({ - sandboxName, - target: gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(), - path: workdir, - }); -} - // OpenShell accepts LF/CR in command argv while retaining field-specific // rejection for NUL-bearing command args and NUL/LF/CR-bearing workdirs. Keep // the downstream check narrow so inline scripts remain byte-exact. NemoClaw's @@ -146,13 +122,6 @@ export function workdirMissingMessage(workdir: string): string { return `error: --workdir: ${workdir} does not exist inside the sandbox`; } -export function evaluateWorkdirProbe(probe: WorkdirProbeResult): WorkdirProbeOutcome { - if (probe.error) return "unclear"; - if (probe.status === 0) return "ok"; - if (probe.status === 1) return "missing"; - return "unclear"; -} - export function computeExitCode(result: SpawnLikeResult): { code: number; errorMessage?: string; @@ -235,6 +204,10 @@ export function cleanupOpenClawAfterExec( return null; } +/** + * Compatibility child-process surface for interactive consumers tracked by + * #10994. Remove it after those callers use a typed interactive executor. + */ export async function runSandboxExecChild( binary: string, args: readonly string[], @@ -250,66 +223,10 @@ export async function runSandboxExecChild( return runCliOpenShellStreamingCommand(binary, args, childOptions, spawnChild, signalSource); } -export async function runSandboxExecCommand( - binary: string, - sandboxName: string, - command: readonly string[], - options: SandboxExecOptions, - run: SandboxExecRunner, - cleanupDeps: SandboxExecCleanupDeps, - gatewayName?: string, -): Promise { - let result: SpawnLikeResult; - try { - result = await run(binary, buildOpenshellExecArgs(sandboxName, command, options, gatewayName)); - } catch (error) { - result = { status: null, error: error instanceof Error ? error : new Error(String(error)) }; - } - try { - const { code: commandCode, errorMessage: invocationError } = computeExitCode(result); - const cleanupError = cleanupOpenClawAfterExec(sandboxName, cleanupDeps) ?? undefined; - return { - code: cleanupError ? 1 : commandCode, - commandCode, - ...(invocationError ? { invocationError } : {}), - ...(cleanupError ? { cleanupError } : {}), - }; - } finally { - result.releaseSignals?.(); - } -} - export function cleanupFailureMessage(commandCode: number, detail: string): string { return ` OpenClaw permission cleanup failed (command exit ${commandCode}; cleanup exit 1): ${detail}`; } -const defaultWorkdirProbeRunner: WorkdirProbeRunner = (binary, args) => { - const probe = spawnSync(binary, args, { stdio: ["ignore", "ignore", "ignore"] }); - return { status: probe.status, error: probe.error }; -}; - -export function validateWorkdirOrFail( - binary: string, - sandboxName: string, - workdir: string, - run: WorkdirProbeRunner = defaultWorkdirProbeRunner, - gatewayName?: string, - exit: (code: number) => never = process.exit, -): void { - const outcome = evaluateWorkdirProbe( - run(binary, buildWorkdirProbeArgs(sandboxName, workdir, gatewayName)), - ); - if (outcome === "missing") { - console.error(workdirMissingMessage(workdir)); - exit(1); - } -} - -export function resolveSandboxExecBinary(): string { - const { getOpenshellBinary } = require("../../adapters/openshell/runtime"); - return getOpenshellBinary(); -} - function defaultSelectGateway(sandboxName: string): GatewaySelectResult { return ( require("./gateway-select") as typeof import("./gateway-select") @@ -448,11 +365,19 @@ export async function execSandbox( const target = gatewayName ? namedOpenShellGateway(gatewayName) : selectedOpenShellGateway(); const commandExecutor = deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor(); if (options.workdir) { - const workdir = await commandExecutor.probeDirectory({ - sandboxName, - target, - path: options.workdir, - }); + let workdir: Awaited>; + try { + workdir = await commandExecutor.probeDirectory({ + sandboxName, + target, + path: options.workdir, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + console.error(` Failed to invoke openshell: ${detail}`); + console.error(" Ensure 'openshell' is installed and on PATH."); + return exit(1); + } if (workdir.state === "missing") { console.error(workdirMissingMessage(options.workdir)); exit(1); diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index 73a47806b5b..3385082f004 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -38,7 +38,6 @@ vi.mock("./connect", () => ({ })); vi.mock("./exec", () => ({ execSandbox: mocks.execSandbox, - resolveSandboxExecBinary: () => "openshell", runSandboxExecChild: mocks.runSandboxExecChild, buildOpenshellExecArgs: ( sandboxName: string, diff --git a/src/lib/adapters/openshell/sandbox-command-cli.test.ts b/src/lib/adapters/openshell/sandbox-command-cli.test.ts index 3d1430b6dbc..bf47deda536 100644 --- a/src/lib/adapters/openshell/sandbox-command-cli.test.ts +++ b/src/lib/adapters/openshell/sandbox-command-cli.test.ts @@ -137,6 +137,48 @@ describe("CLI OpenShell sandbox command executor", () => { }); }); + it.each([ + ["an unavailable executable", "ENOENT", "unavailable"], + ["an unclassified transport failure", undefined, "invocation"], + ] as const)("maps an asynchronous child error from %s", async (_label, code, kind) => { + const events = new EventEmitter(); + const error = Object.assign(new Error("child process failed"), code ? { code } : {}); + const child: OpenShellCommandChild = { + exitCode: null, + signalCode: null, + kill: vi.fn(() => true), + once: ((event: string, listener: (...args: unknown[]) => void) => { + events.once(event, listener); + const notify = { + error: () => undefined, + close: () => + queueMicrotask(() => { + events.emit("error", error); + events.emit("close", 0, null); + }), + }[event as "error" | "close"]; + notify(); + return child; + }) as OpenShellCommandChild["once"], + }; + const executor = createCliOpenShellSandboxCommandExecutor({ + resolveBinary: () => "/usr/bin/openshell", + spawnChild: () => child, + }); + + const completed = await executor.runStreaming({ + sandboxName: "alpha", + target: selectedOpenShellGateway(), + command: ["true"], + }); + + expect(completed.outcome).toEqual({ + kind: "failed", + error: { kind, message: "child process failed" }, + }); + completed.release(); + }); + it.each([ [0, "present"], [1, "missing"], diff --git a/test/onboarding/onboard-installer-restore-intent.test.ts b/test/onboarding/onboard-installer-restore-intent.test.ts index ebd67b965d5..4810492c070 100644 --- a/test/onboarding/onboard-installer-restore-intent.test.ts +++ b/test/onboarding/onboard-installer-restore-intent.test.ts @@ -165,7 +165,7 @@ childProcess.spawn = (...args) => { }; const { createSandbox } = require(${onboardPath}); -const { runSandboxExecCommand } = require(${execActionPath}); +const { execSandbox } = require(${execActionPath}); const MARKER_PATH = "/sandbox/workspace/marker.txt"; const MARKER_SHA = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; @@ -181,27 +181,53 @@ const MARKER_SHA = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852 // Prove the recreated + restored sandbox is reachable through the real // "nemoclaw exec" boundary and can read a preserved workspace marker. - const completion = await runSandboxExecCommand( - "openshell", - sandboxName, - ["sha256sum", MARKER_PATH], - {}, - async (binary, args) => { - const joined = _n([binary, ...args]); - const reads = - joined.includes("sandbox exec") && - joined.includes("--name " + sandboxName) && - joined.includes("sha256sum " + MARKER_PATH); - events.push({ kind: "exec", cmd: joined, marker: reads ? MARKER_SHA : null }); - return { status: reads ? 0 : 1 }; - }, - { - getSandbox: () => ({ agent: "openclaw" }), - inspectMutableConfigPerms: () => ({ applies: true, ok: true }), - repairMutableConfigPerms: () => ({ applied: false }), - }, - ); - console.log(JSON.stringify({ sandboxName, events, execCode: completion.code })); + let execCode = null; + const execFinished = new Error("__exec_finished__"); + try { + await execSandbox( + sandboxName, + ["sha256sum", MARKER_PATH], + {}, + { + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async (request) => { + const joined = _n([ + "openshell", + "sandbox", + "exec", + "--name", + request.sandboxName, + "--", + ...request.command, + ]); + const reads = + joined.includes("sandbox exec") && + joined.includes("--name " + sandboxName) && + joined.includes("sha256sum " + MARKER_PATH); + events.push({ kind: "exec", cmd: joined, marker: reads ? MARKER_SHA : null }); + return { + outcome: { kind: "completed", exitCode: reads ? 0 : 1 }, + release: () => {}, + }; + }, + }, + cleanupDeps: { + getSandbox: () => ({ agent: "openclaw" }), + inspectMutableConfigPerms: () => ({ applies: true, ok: true }), + repairMutableConfigPerms: () => ({ applied: false }), + }, + exit: (code) => { + execCode = code; + throw execFinished; + }, + }, + ); + } catch (error) { + if (error !== execFinished) throw error; + } + console.log(JSON.stringify({ sandboxName, events, execCode })); })().catch((error) => { console.error(error); process.exit(1); From 5dcf90b3b92962cca94eb948da8a1488a18e545b Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 3 Sep 2026 14:24:04 -0700 Subject: [PATCH 3/3] refactor(cli): remove obsolete exec stdio wrapper --- ci/source-architecture-budget.json | 2 +- .../sandbox/agent/passthrough-dispatch.ts | 2 +- src/lib/actions/sandbox/exec-stdio.test.ts | 35 ---------------- src/lib/actions/sandbox/exec-stdio.ts | 14 ------- .../sandbox/exec.multiline-argv.test.ts | 8 ++-- src/lib/actions/sandbox/exec.ts | 1 - .../openshell/sandbox-command-stdio.test.ts | 42 +++++++++++++++++++ 7 files changed, 48 insertions(+), 56 deletions(-) delete mode 100644 src/lib/actions/sandbox/exec-stdio.test.ts delete mode 100644 src/lib/actions/sandbox/exec-stdio.ts create mode 100644 src/lib/adapters/openshell/sandbox-command-stdio.test.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index ca1b2cf74fa..f8b58bf960b 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -60,7 +60,7 @@ "maxRootFiles": { "src/lib/onboard": 302, "src/lib/actions": 18, - "src/lib/actions/sandbox": 179, + "src/lib/actions/sandbox": 178, "src/lib/state": 38, "src/lib/inference": 63, "scripts": 42 diff --git a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts index 123fea76904..134e58a4de0 100644 --- a/src/lib/actions/sandbox/agent/passthrough-dispatch.ts +++ b/src/lib/actions/sandbox/agent/passthrough-dispatch.ts @@ -31,7 +31,7 @@ // non-interactive one-shot, yet PR #8191 moved the non-JSON transport // off `execSandbox` onto a raw `spawnSync` with a hard-coded // `stdio[0] = "inherit"`, dropping the TTY-aware stdin guard that -// `buildSandboxExecStdio` applies to every other sandbox exec. The JSON +// `buildSandboxCommandStdio` applies to every other sandbox exec. The JSON // transport has carried the same hard-coded inherit since #5683. The // result is a live terminal on fd 0 handed to a dispatch whose stdout // and stderr are pipes and whose argv says `--no-tty`. diff --git a/src/lib/actions/sandbox/exec-stdio.test.ts b/src/lib/actions/sandbox/exec-stdio.test.ts deleted file mode 100644 index 7ab75687e73..00000000000 --- a/src/lib/actions/sandbox/exec-stdio.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { describe, expect, it } from "vitest"; -import { buildSandboxExecStdio, shouldInheritSandboxExecStdin } from "./exec-stdio"; - -describe("buildSandboxExecStdio", () => { - it("inherits terminal stdin by default", () => { - expect(buildSandboxExecStdio({}, true)).toBe("inherit"); - }); - - it("closes non-terminal or unknown stdin by default", () => { - expect(buildSandboxExecStdio({}, false)).toEqual(["ignore", "inherit", "inherit"]); - expect(buildSandboxExecStdio({}, undefined)).toEqual(["ignore", "inherit", "inherit"]); - }); - - it("honors explicit flags over terminal detection", () => { - expect(buildSandboxExecStdio({ stdin: true }, false)).toBe("inherit"); - expect(buildSandboxExecStdio({ stdin: true }, undefined)).toBe("inherit"); - expect(buildSandboxExecStdio({ stdin: false }, true)).toEqual(["ignore", "inherit", "inherit"]); - }); -}); - -describe("shouldInheritSandboxExecStdin", () => { - it("lets explicit --stdin and --no-stdin win", () => { - expect(shouldInheritSandboxExecStdin(true, false)).toBe(true); - expect(shouldInheritSandboxExecStdin(false, true)).toBe(false); - }); - - it("inherits only a positively identified TTY when no flag is present", () => { - expect(shouldInheritSandboxExecStdin(undefined, true)).toBe(true); - expect(shouldInheritSandboxExecStdin(undefined, false)).toBe(false); - expect(shouldInheritSandboxExecStdin(undefined, undefined)).toBe(false); - }); -}); diff --git a/src/lib/actions/sandbox/exec-stdio.ts b/src/lib/actions/sandbox/exec-stdio.ts deleted file mode 100644 index 6129a431ea4..00000000000 --- a/src/lib/actions/sandbox/exec-stdio.ts +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import type { SandboxExecOptions } from "./exec"; -import { - buildSandboxCommandStdio, - shouldInheritSandboxCommandStdin, -} from "../../adapters/openshell/sandbox-command-stdio"; - -export const shouldInheritSandboxExecStdin = shouldInheritSandboxCommandStdin; - -export function buildSandboxExecStdio(options: SandboxExecOptions = {}, stdinIsTty?: boolean) { - return buildSandboxCommandStdio(options, stdinIsTty); -} diff --git a/src/lib/actions/sandbox/exec.multiline-argv.test.ts b/src/lib/actions/sandbox/exec.multiline-argv.test.ts index 7a6cded719e..dcf1a26ea59 100644 --- a/src/lib/actions/sandbox/exec.multiline-argv.test.ts +++ b/src/lib/actions/sandbox/exec.multiline-argv.test.ts @@ -8,10 +8,10 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; import type { OpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command"; -// The default exec runner shells out via spawn and chooses whether to inherit -// or ignore stdin. Mock node:child_process so the tests can assert that wiring -// at the execSandbox boundary without spawning a real process. Every other test -// injects a runner/probe seam. +// The default CLI command executor shells out via spawn and chooses whether to +// inherit or ignore stdin. Mock node:child_process so the tests can assert that +// wiring at the execSandbox boundary without spawning a real process. Every +// other test injects a typed command-executor seam. vi.mock("node:child_process", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, spawn: vi.fn() }; diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index 809131720eb..c04c289355e 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -29,7 +29,6 @@ import { type ExecPolicyHintDeps, preparePolicyHint } from "./exec-policy-hint-i import type { GatewaySelectResult } from "./gateway-select"; import { wrapExecCommandWithRuntimeEnv } from "./runtime-env"; -export { buildSandboxExecStdio, shouldInheritSandboxExecStdin } from "./exec-stdio"; export { wrapExecCommandWithRuntimeEnv, wrapOpenClawAgentCommandWithRuntimeEnv, diff --git a/src/lib/adapters/openshell/sandbox-command-stdio.test.ts b/src/lib/adapters/openshell/sandbox-command-stdio.test.ts new file mode 100644 index 00000000000..39bff4d7894 --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-command-stdio.test.ts @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { + buildSandboxCommandStdio, + shouldInheritSandboxCommandStdin, +} from "./sandbox-command-stdio"; + +describe("buildSandboxCommandStdio", () => { + it("inherits terminal stdin by default", () => { + expect(buildSandboxCommandStdio({}, true)).toBe("inherit"); + }); + + it("closes non-terminal or unknown stdin by default", () => { + expect(buildSandboxCommandStdio({}, false)).toEqual(["ignore", "inherit", "inherit"]); + expect(buildSandboxCommandStdio({}, undefined)).toEqual(["ignore", "inherit", "inherit"]); + }); + + it("honors explicit flags over terminal detection", () => { + expect(buildSandboxCommandStdio({ stdin: true }, false)).toBe("inherit"); + expect(buildSandboxCommandStdio({ stdin: true }, undefined)).toBe("inherit"); + expect(buildSandboxCommandStdio({ stdin: false }, true)).toEqual([ + "ignore", + "inherit", + "inherit", + ]); + }); +}); + +describe("shouldInheritSandboxCommandStdin", () => { + it("lets explicit --stdin and --no-stdin win", () => { + expect(shouldInheritSandboxCommandStdin(true, false)).toBe(true); + expect(shouldInheritSandboxCommandStdin(false, true)).toBe(false); + }); + + it("inherits only a positively identified TTY when no flag is present", () => { + expect(shouldInheritSandboxCommandStdin(undefined, true)).toBe(true); + expect(shouldInheritSandboxCommandStdin(undefined, false)).toBe(false); + expect(shouldInheritSandboxCommandStdin(undefined, undefined)).toBe(false); + }); +});