From 2de59705881a84023a09c9ff73bd128eab6478bf Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 22 Jun 2026 09:35:48 -0700 Subject: [PATCH 1/7] fix(sandbox/recover): parse framed exec output for Hermes boundary Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/process-recovery.ts | 52 ++++++++++--- test/process-recovery.test.ts | 81 +++++++++++++++++++++ 2 files changed, 121 insertions(+), 12 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 2693bd0408b..3e0434d1c90 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -61,6 +61,40 @@ export type SandboxForwardHealth = boolean | "occupied" | null; const SANDBOX_EXEC_STARTED_MARKER = "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; +function stripSandboxExecStdoutFrame(line: string): string { + const trimmed = line.trimStart(); + const stdoutPrefix = trimmed.match(/^(?:\[stdout\]|stdout:)\s*/i); + if (!stdoutPrefix) return line; + return trimmed.slice(stdoutPrefix[0].length); +} + +function extractSandboxExecCommandStdout(output: string): string | null { + const stdout = output.trim(); + if (!stdout) return null; + const lines = stdout.split(/\r?\n/); + const exactMarkerIndex = lines.findIndex( + (line) => stripSandboxExecStdoutFrame(line).trim() === SANDBOX_EXEC_STARTED_MARKER, + ); + if (exactMarkerIndex >= 0) { + return lines + .slice(exactMarkerIndex + 1) + .map(stripSandboxExecStdoutFrame) + .join("\n") + .trim(); + } + + const markerLineIndex = lines.findIndex((line) => line.includes(SANDBOX_EXEC_STARTED_MARKER)); + if (markerLineIndex === -1) return null; + const markerLine = lines[markerLineIndex]; + const afterMarker = markerLine.slice( + markerLine.indexOf(SANDBOX_EXEC_STARTED_MARKER) + SANDBOX_EXEC_STARTED_MARKER.length, + ); + return [afterMarker, ...lines.slice(markerLineIndex + 1)] + .map(stripSandboxExecStdoutFrame) + .join("\n") + .trim(); +} + function isValidPort(value: unknown): value is number { return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535; } @@ -155,14 +189,11 @@ export function executeSandboxExecCommand( }, ); if (result.error) return null; - const stdout = (result.stdout || "").trim(); - const stdoutLines = stdout.split(/\r?\n/); - const markerIndex = stdoutLines.indexOf(SANDBOX_EXEC_STARTED_MARKER); - if (markerIndex === -1) return null; - const commandStdoutLines = stdoutLines.slice(markerIndex + 1); + const commandStdout = extractSandboxExecCommandStdout(result.stdout || ""); + if (commandStdout === null) return null; return { status: result.status ?? 1, - stdout: commandStdoutLines.join("\n").trim(), + stdout: commandStdout, stderr: (result.stderr || "").trim(), }; } catch { @@ -180,14 +211,11 @@ async function executeSandboxExecCommandForStatus( { ignoreError: true }, ); if (isCommandTimeout(result) || result.error) return null; - const stdout = (result.output || "").trim(); - const stdoutLines = stdout.split(/\r?\n/); - const markerIndex = stdoutLines.indexOf(SANDBOX_EXEC_STARTED_MARKER); - if (markerIndex === -1) return null; - const commandStdoutLines = stdoutLines.slice(markerIndex + 1); + const commandStdout = extractSandboxExecCommandStdout(result.output || ""); + if (commandStdout === null) return null; return { status: result.status ?? 1, - stdout: commandStdoutLines.join("\n").trim(), + stdout: commandStdout, stderr: "", }; } diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index b79d4b90e4b..80db7b0738a 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -11,6 +11,7 @@ import { checkAndRecoverSandboxProcesses, classifyForwardHealthWithReachability, classifySandboxForwardHealth, + executeSandboxExecCommand, resolveSandboxDashboardPort, type SandboxForwardListEntry, } from "../dist/lib/actions/sandbox/process-recovery.js"; @@ -173,6 +174,27 @@ describe("classifyForwardHealthWithReachability", () => { }); }); +describe("executeSandboxExecCommand", () => { + it("parses stdout-framed root exec output after the startup marker", () => { + const childProcess = requireDist("node:child_process"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: [ + "OpenShell sandbox exec output:", + "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__", + "stdout: SECRET_BOUNDARY_OK", + ].join("\n"), + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), + ); + + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + }); +}); + describe("checkAndRecoverSandboxProcesses", () => { it("scopes forward stop to the target sandbox when restarting a dead forward", () => { const openshellRuntime = requireDist("../dist/lib/adapters/openshell/runtime.js"); @@ -746,6 +768,65 @@ hermes-box 127.0.0.1 8642 12346 running`; ); }); + it("falls through when the Hermes secret-boundary check parses stdout-framed root exec markers", () => { + const openshellRuntime = requireDist("../dist/lib/adapters/openshell/runtime.js"); + const agentRuntime = requireDist("../dist/lib/agent/runtime.js"); + const registry = requireDist("../dist/lib/state/registry.js"); + const forwardHealth = requireDist("../dist/lib/actions/sandbox/forward-health.js"); + const childProcess = requireDist("node:child_process"); + let secretBoundaryCalls = 0; + + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (_command: unknown, rawArgs: unknown) => { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + const shellCommand = String(args.at(-1) ?? ""); + if (shellCommand.includes("HTTP_CODE=$(curl")) { + return { + status: 0, + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: RUNNING\n", + stderr: "", + } as never; + } + if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { + secretBoundaryCalls += 1; + return { + status: 0, + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: SECRET_BOUNDARY_OK\n", + stderr: "", + } as never; + } + return { status: 0, stdout: "", stderr: "" } as never; + }, + ); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "hermes", + forwardPort: 8642, + displayName: "Hermes Agent", + }); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "hermes-box", + agent: "hermes", + dashboardPort: 18789, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: `SANDBOX BIND PORT PID STATUS\nhermes-box 127.0.0.1 18789 12345 running`, + }); + vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); + + const result = withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + ); + expect(result).toEqual({ + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + }); + expect(secretBoundaryCalls).toBe(1); + }); + it("falls through to the forward-refresh path when the Hermes secret-boundary check passes", () => { const openshellRuntime = requireDist("../dist/lib/adapters/openshell/runtime.js"); const agentRuntime = requireDist("../dist/lib/agent/runtime.js"); From fdd7acbbea72a7eb12bd98d428a21cc0041db5c2 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 22 Jun 2026 09:44:01 -0700 Subject: [PATCH 2/7] test(sandbox/recover): avoid branching in Hermes framing test Signed-off-by: Carlos Villela --- test/process-recovery.test.ts | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index 80db7b0738a..921f9f63f78 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -776,26 +776,36 @@ hermes-box 127.0.0.1 8642 12346 running`; const childProcess = requireDist("node:child_process"); let secretBoundaryCalls = 0; - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); - if (shellCommand.includes("HTTP_CODE=$(curl")) { - return { + const execResponses: Array<[string, () => never]> = [ + [ + "HTTP_CODE=$(curl", + () => + ({ status: 0, stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: RUNNING\n", stderr: "", - } as never; - } - if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { + }) as never, + ], + [ + "validate-hermes-env-secret-boundary.py", + () => { secretBoundaryCalls += 1; return { status: 0, stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: SECRET_BOUNDARY_OK\n", stderr: "", } as never; - } - return { status: 0, stdout: "", stderr: "" } as never; + }, + ], + ]; + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (_command: unknown, rawArgs: unknown) => { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + const shellCommand = String(args.at(-1) ?? ""); + return ( + execResponses.find(([needle]) => shellCommand.includes(needle))?.[1] ?? + (() => ({ status: 0, stdout: "", stderr: "" }) as never) + )(); }, ); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ From 9ab4f00a1b73bf810d5f3ba4607941a010deec8d Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 22 Jun 2026 09:54:29 -0700 Subject: [PATCH 3/7] fix(sandbox/recover): constrain framed exec marker parsing Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/process-recovery.ts | 21 +++++++++++---------- test/process-recovery.test.ts | 4 ++-- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 3e0434d1c90..63f8af562c6 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -61,36 +61,37 @@ export type SandboxForwardHealth = boolean | "occupied" | null; const SANDBOX_EXEC_STARTED_MARKER = "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; -function stripSandboxExecStdoutFrame(line: string): string { +function parseSandboxExecStdoutFrame(line: string): { text: string; framed: boolean } { const trimmed = line.trimStart(); const stdoutPrefix = trimmed.match(/^(?:\[stdout\]|stdout:)\s*/i); - if (!stdoutPrefix) return line; - return trimmed.slice(stdoutPrefix[0].length); + if (!stdoutPrefix) return { text: line, framed: false }; + return { text: trimmed.slice(stdoutPrefix[0].length), framed: true }; } function extractSandboxExecCommandStdout(output: string): string | null { const stdout = output.trim(); if (!stdout) return null; - const lines = stdout.split(/\r?\n/); + const lines = stdout.split(/\r?\n/).map(parseSandboxExecStdoutFrame); const exactMarkerIndex = lines.findIndex( - (line) => stripSandboxExecStdoutFrame(line).trim() === SANDBOX_EXEC_STARTED_MARKER, + (line) => line.text.trim() === SANDBOX_EXEC_STARTED_MARKER, ); if (exactMarkerIndex >= 0) { return lines .slice(exactMarkerIndex + 1) - .map(stripSandboxExecStdoutFrame) + .map((line) => line.text) .join("\n") .trim(); } - const markerLineIndex = lines.findIndex((line) => line.includes(SANDBOX_EXEC_STARTED_MARKER)); + const markerLineIndex = lines.findIndex( + (line) => line.framed && line.text.includes(SANDBOX_EXEC_STARTED_MARKER), + ); if (markerLineIndex === -1) return null; - const markerLine = lines[markerLineIndex]; + const markerLine = lines[markerLineIndex].text; const afterMarker = markerLine.slice( markerLine.indexOf(SANDBOX_EXEC_STARTED_MARKER) + SANDBOX_EXEC_STARTED_MARKER.length, ); - return [afterMarker, ...lines.slice(markerLineIndex + 1)] - .map(stripSandboxExecStdoutFrame) + return [afterMarker, ...lines.slice(markerLineIndex + 1).map((line) => line.text)] .join("\n") .trim(); } diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index 921f9f63f78..1fbbfe4d437 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -639,7 +639,7 @@ hermes-box 127.0.0.1 8642 12346 running`; if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: RUNNING\n", stderr: "", } as never; } @@ -647,7 +647,7 @@ hermes-box 127.0.0.1 8642 12346 running`; secretBoundaryCalls += 1; return { status: 1, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_REFUSED\n", + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: SECRET_BOUNDARY_REFUSED\n", stderr: "[SECURITY] Refusing Hermes startup because /sandbox/.hermes/.env contains raw secret-shaped values\n[SECURITY] TELEGRAM_BOT_TOKEN (line 3)", } as never; From 9a650bf2d87a2f6933abd4c17763aebaab8d7808 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 22 Jun 2026 10:05:41 -0700 Subject: [PATCH 4/7] fix(sandbox/recover): document exec frame parsing boundary Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/process-recovery.ts | 26 ++++++++++++--------- test/process-recovery.test.ts | 18 ++++++++++++++ 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 63f8af562c6..8741c01066b 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -68,6 +68,20 @@ function parseSandboxExecStdoutFrame(line: string): { text: string; framed: bool return { text: trimmed.slice(stdoutPrefix[0].length), framed: true }; } +/** + * Extract child-command stdout from `openshell sandbox exec` output after the + * sentinel printed by `markedCommand`. Some OpenShell versions frame child + * stdout for humans, e.g. `stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__`, while + * older versions pass raw stdout through unchanged. Normalize only recognized + * stdout frame prefixes at this transport boundary so recovery, status, and + * Hermes boundary callers keep consuming plain command stdout. + * + * Security boundary: the sentinel must occupy its own stdout line after optional + * frame-prefix stripping. A preamble that merely contains the sentinel string is + * rejected so sandbox output cannot move the parser boundary forward. Remove + * this compatibility shim once OpenShell exposes a stable machine-readable exec + * output mode that preserves child stdout/stderr without human framing. + */ function extractSandboxExecCommandStdout(output: string): string | null { const stdout = output.trim(); if (!stdout) return null; @@ -83,17 +97,7 @@ function extractSandboxExecCommandStdout(output: string): string | null { .trim(); } - const markerLineIndex = lines.findIndex( - (line) => line.framed && line.text.includes(SANDBOX_EXEC_STARTED_MARKER), - ); - if (markerLineIndex === -1) return null; - const markerLine = lines[markerLineIndex].text; - const afterMarker = markerLine.slice( - markerLine.indexOf(SANDBOX_EXEC_STARTED_MARKER) + SANDBOX_EXEC_STARTED_MARKER.length, - ); - return [afterMarker, ...lines.slice(markerLineIndex + 1).map((line) => line.text)] - .join("\n") - .trim(); + return null; } function isValidPort(value: unknown): value is number { diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index 1fbbfe4d437..239a2c1c7bc 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -193,6 +193,24 @@ describe("executeSandboxExecCommand", () => { expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); }); + + it("rejects a non-frame preamble that contains the startup marker", () => { + const childProcess = requireDist("node:child_process"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: [ + "operator preamble mentions __NEMOCLAW_SANDBOX_EXEC_STARTED__ before child stdout", + "stdout: RUNNING", + ].join("\n"), + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo RUNNING"), + ); + + expect(result).toBeNull(); + }); }); describe("checkAndRecoverSandboxProcesses", () => { From 2829b1d04c5baddde7dcec2628663966d41fa5fc Mon Sep 17 00:00:00 2001 From: San Dang Date: Mon, 22 Jun 2026 22:54:26 +0530 Subject: [PATCH 5/7] fix(sandbox/recover): avoid newlines in sandbox exec payloads --- src/lib/actions/sandbox/process-recovery.ts | 14 +++- test/process-recovery.test.ts | 75 +++++++++++++-------- 2 files changed, 59 insertions(+), 30 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 8741c01066b..04f2be3197e 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { Buffer } from "node:buffer"; import { spawnSync } from "node:child_process"; import { captureOpenshell, @@ -61,6 +62,15 @@ export type SandboxForwardHealth = boolean | "occupied" | null; const SANDBOX_EXEC_STARTED_MARKER = "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; +function buildSandboxExecMarkedCommand(command: string): string { + const encodedCommand = Buffer.from(command, "utf8").toString("base64"); + return [ + `printf '%s\\n' '${SANDBOX_EXEC_STARTED_MARKER}'`, + "command -v base64 >/dev/null 2>&1 || { echo NEMOCLAW_BASE64_MISSING >&2; exit 127; }", + `printf '%s' '${encodedCommand}' | base64 -d | sh`, + ].join("; "); +} + function parseSandboxExecStdoutFrame(line: string): { text: string; framed: boolean } { const trimmed = line.trimStart(); const stdoutPrefix = trimmed.match(/^(?:\[stdout\]|stdout:)\s*/i); @@ -177,7 +187,7 @@ export function executeSandboxExecCommand( command: string, timeout = 15000, ): SandboxCommandResult | null { - const markedCommand = `printf '%s\n' '${SANDBOX_EXEC_STARTED_MARKER}'; ${command}`; + const markedCommand = buildSandboxExecMarkedCommand(command); const timeoutOverride = Number(process.env.NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS || ""); const effectiveTimeout = Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : timeout; @@ -210,7 +220,7 @@ async function executeSandboxExecCommandForStatus( sandboxName: string, command: string, ): Promise { - const markedCommand = `printf '%s\n' '${SANDBOX_EXEC_STARTED_MARKER}'; ${command}`; + const markedCommand = buildSandboxExecMarkedCommand(command); const result = await captureOpenshellForStatus( ["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", markedCommand], { ignoreError: true }, diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index 239a2c1c7bc..bbc7206a9c7 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { Buffer } from "node:buffer"; import fs from "node:fs"; import { createRequire } from "node:module"; import os from "node:os"; @@ -22,6 +23,17 @@ afterEach(() => { vi.restoreAllMocks(); }); +function decodeSandboxExecShellPayload(payload: string): string { + const match = payload.match(/printf '%s' '([A-Za-z0-9+\/=]+)' \| base64 -d \| sh/); + if (!match) return payload; + return Buffer.from(match[1], "base64").toString("utf8"); +} + +function getSandboxExecShellCommand(rawArgs: unknown): string { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + return decodeSandboxExecShellPayload(String(args.at(-1) ?? "")); +} + function withFakeOpenshellBinary(fn: () => T): T { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); const bin = path.join(dir, "openshell"); @@ -211,6 +223,27 @@ describe("executeSandboxExecCommand", () => { expect(result).toBeNull(); }); + + it("passes a newline-free shell payload to OpenShell", () => { + const childProcess = requireDist("node:child_process"); + const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo first\necho SECRET_BOUNDARY_OK"), + ); + + const args = spawn.mock.calls[0]?.[1] as string[]; + const shellPayload = args.at(-1) ?? ""; + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + expect(shellPayload.includes("\n")).toBe(false); + expect(shellPayload.includes("\r")).toBe(false); + expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); + expect(shellPayload).toContain("base64 -d | sh"); + }); }); describe("checkAndRecoverSandboxProcesses", () => { @@ -228,8 +261,7 @@ beta 127.0.0.1 18789 12345 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -303,8 +335,7 @@ beta 127.0.0.1 18789 12345 running`; try { vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { healthProbeCalls += 1; const status = healthProbeCalls >= 3 ? "RUNNING" : "STOPPED"; @@ -373,8 +404,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -464,8 +494,7 @@ sibling-box 127.0.0.1 8642 99999 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -526,8 +555,7 @@ hermes-box 127.0.0.1 18789 12345 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -584,8 +612,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -652,8 +679,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -734,8 +760,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -818,8 +843,7 @@ hermes-box 127.0.0.1 8642 12346 running`; ]; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); return ( execResponses.find(([needle]) => shellCommand.includes(needle))?.[1] ?? (() => ({ status: 0, stdout: "", stderr: "" }) as never) @@ -865,8 +889,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -924,8 +947,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -986,8 +1008,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { secretBoundaryCalls += 1; } @@ -1026,8 +1047,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -1093,8 +1113,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, From 7d2f991c3de7add110325b3935ab7e6e57a81ddf Mon Sep 17 00:00:00 2001 From: San Dang Date: Mon, 22 Jun 2026 23:09:29 +0530 Subject: [PATCH 6/7] test(sandbox/recover): avoid added test branch --- test/process-recovery.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index bbc7206a9c7..003598bfd5b 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -25,8 +25,7 @@ afterEach(() => { function decodeSandboxExecShellPayload(payload: string): string { const match = payload.match(/printf '%s' '([A-Za-z0-9+\/=]+)' \| base64 -d \| sh/); - if (!match) return payload; - return Buffer.from(match[1], "base64").toString("utf8"); + return match ? Buffer.from(match[1], "base64").toString("utf8") : payload; } function getSandboxExecShellCommand(rawArgs: unknown): string { From 7cfa0dbf8295a4ad0414ce0b174d25be853f2e40 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 22 Jun 2026 10:33:37 -0700 Subject: [PATCH 7/7] fix(sandbox/recover): fall back to docker root exec Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/process-recovery.ts | 72 ++++++++++++++++++--- test/process-recovery.test.ts | 45 ++++++++++++- 2 files changed, 106 insertions(+), 11 deletions(-) diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 04f2be3197e..5546070d88d 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -3,6 +3,7 @@ import { Buffer } from "node:buffer"; import { spawnSync } from "node:child_process"; +import { dockerSpawnSync } from "../../adapters/docker"; import { captureOpenshell, captureOpenshellForStatus, @@ -63,6 +64,9 @@ export type SandboxForwardHealth = boolean | "occupied" | null; const SANDBOX_EXEC_STARTED_MARKER = "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; function buildSandboxExecMarkedCommand(command: string): string { + if (!command.includes("validate-hermes-env-secret-boundary.py")) { + return `printf '%s\n' '${SANDBOX_EXEC_STARTED_MARKER}'; ${command}`; + } const encodedCommand = Buffer.from(command, "utf8").toString("base64"); return [ `printf '%s\\n' '${SANDBOX_EXEC_STARTED_MARKER}'`, @@ -182,6 +186,60 @@ export function executeSandboxCommand( } } +function parseSandboxCommandResult( + result: ReturnType, +): SandboxCommandResult | null { + if (result.error) return null; + const stdout = typeof result.stdout === "string" ? result.stdout : String(result.stdout || ""); + const stderr = typeof result.stderr === "string" ? result.stderr : String(result.stderr || ""); + const commandStdout = extractSandboxExecCommandStdout(stdout); + if (commandStdout === null) return null; + return { + status: result.status ?? 1, + stdout: commandStdout, + stderr: stderr.trim(), + }; +} + +function findLocalDockerSandboxContainer(sandboxName: string): string | null { + const expectedName = `openshell-${sandboxName}`; + try { + const result = dockerSpawnSync(["ps", "--format", "{{.ID}}\t{{.Names}}"], { + encoding: "utf-8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 5000, + }); + if (result.error || result.status !== 0) return null; + for (const line of String(result.stdout || "").split(/\r?\n/)) { + const [id = "", names = ""] = line.split("\t"); + const containerNames = names.split(",").map((name) => name.trim()); + if (id && containerNames.includes(expectedName)) return id; + } + return null; + } catch { + return null; + } +} + +function executeLocalDockerSandboxCommand( + sandboxName: string, + markedCommand: string, + timeout: number, +): SandboxCommandResult | null { + const containerId = findLocalDockerSandboxContainer(sandboxName); + if (!containerId) return null; + try { + const result = dockerSpawnSync(["exec", "-u", "root", containerId, "sh", "-c", markedCommand], { + encoding: "utf-8", + stdio: ["ignore", "pipe", "pipe"], + timeout, + }); + return parseSandboxCommandResult(result); + } catch { + return null; + } +} + export function executeSandboxExecCommand( sandboxName: string, command: string, @@ -203,16 +261,12 @@ export function executeSandboxExecCommand( timeout: effectiveTimeout, }, ); - if (result.error) return null; - const commandStdout = extractSandboxExecCommandStdout(result.stdout || ""); - if (commandStdout === null) return null; - return { - status: result.status ?? 1, - stdout: commandStdout, - stderr: (result.stderr || "").trim(), - }; + return ( + parseSandboxCommandResult(result) ?? + executeLocalDockerSandboxCommand(sandboxName, markedCommand, effectiveTimeout) + ); } catch { - return null; + return executeLocalDockerSandboxCommand(sandboxName, markedCommand, effectiveTimeout); } } diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index 003598bfd5b..6ef8b60a614 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -223,7 +223,7 @@ describe("executeSandboxExecCommand", () => { expect(result).toBeNull(); }); - it("passes a newline-free shell payload to OpenShell", () => { + it("passes a newline-free Hermes validator payload to OpenShell", () => { const childProcess = requireDist("node:child_process"); const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ status: 0, @@ -232,7 +232,10 @@ describe("executeSandboxExecCommand", () => { } as never); const result = withFakeOpenshellBinary(() => - executeSandboxExecCommand("hermes-box", "echo first\necho SECRET_BOUNDARY_OK"), + executeSandboxExecCommand( + "hermes-box", + "python3 /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py env-file /sandbox/.hermes/.env\necho SECRET_BOUNDARY_OK", + ), ); const args = spawn.mock.calls[0]?.[1] as string[]; @@ -243,6 +246,44 @@ describe("executeSandboxExecCommand", () => { expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); expect(shellPayload).toContain("base64 -d | sh"); }); + + it("falls back to local Docker root exec when OpenShell exec output has no marker", () => { + const childProcess = requireDist("node:child_process"); + const dockerExec = requireDist("../dist/lib/adapters/docker/exec.js"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "OpenShell transport preamble\n", + stderr: "", + } as never); + const dockerSpawnSync = vi + .spyOn(dockerExec, "dockerSpawnSync") + .mockReturnValueOnce({ + status: 0, + stdout: "abc123\topenshell-hermes-box\n", + stderr: "", + } as never) + .mockReturnValueOnce({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), + ); + + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + expect(dockerSpawnSync.mock.calls[0]?.[0]).toEqual(["ps", "--format", "{{.ID}}\t{{.Names}}"]); + expect(dockerSpawnSync.mock.calls[1]?.[0]).toEqual([ + "exec", + "-u", + "root", + "abc123", + "sh", + "-c", + expect.stringContaining("echo SECRET_BOUNDARY_OK"), + ]); + }); }); describe("checkAndRecoverSandboxProcesses", () => {