diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-capability.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-capability.ts index 80d8a57860a..27a6fee0b7b 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-capability.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-capability.ts @@ -9,11 +9,11 @@ const DEEPAGENTS_MCP_CAPABILITY_MARKER = "NEMOCLAW_DEEPAGENTS_MCP_CAPABILITY=2"; const DEEPAGENTS_MCP_CAPABILITY_COMMAND = "/usr/local/bin/deepagents-code --nemoclaw-mcp-capability"; -export function assertDeepAgentsMcpMutationRuntimeCapability( +export async function assertDeepAgentsMcpMutationRuntimeCapability( sandboxName: string, runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { - const result = executeSandboxCommand(sandboxName, DEEPAGENTS_MCP_CAPABILITY_COMMAND, { +): Promise { + const result = await executeSandboxCommand(sandboxName, DEEPAGENTS_MCP_CAPABILITY_COMMAND, { runtimeSelection, }); if (result?.status !== 0 || result.stdout.trim() !== DEEPAGENTS_MCP_CAPABILITY_MARKER) { diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-command.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-command.ts index 4d03b6ba4cb..3fcb21ce108 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-command.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-command.ts @@ -8,15 +8,15 @@ import { redactBridgeSecretsForDisplay } from "./mcp-bridge-output"; import type { McpProviderInspectionRuntimeSelection } from "./mcp-bridge-provider-inspection"; import { executeSandboxCommand } from "./process-recovery"; -export function runDeepAgentsAdapterCommand( +export async function runDeepAgentsAdapterCommand( sandboxName: string, entry: Pick, command: string, failureMessage: string, runtimeSelection: McpProviderInspectionRuntimeSelection, options: AdapterMutationOptions = {}, -): string { - const result = executeSandboxCommand(sandboxName, command, { runtimeSelection }); +): Promise { + const result = await executeSandboxCommand(sandboxName, command, { runtimeSelection }); const output = redactBridgeSecretsForDisplay( [result?.stdout, result?.stderr].filter(Boolean).join("\n").trim(), entry, diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-inspection.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-inspection.ts index 3dc30f4dd9c..389aeb6f729 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-inspection.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-inspection.ts @@ -10,13 +10,13 @@ import { } from "./mcp-bridge-adapter-inspection"; import { buildDeepAgentsMcpStatusCommand } from "./mcp-bridge-adapter-status"; -export function inspectDeepAgentsAdapterRegistration( +export async function inspectDeepAgentsAdapterRegistration( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, credentialRevision?: McpAttachedCredentialRevision, -): AdapterRegistrationInspection { - return inspectAdapterRegistrationCommand( +): Promise { + return await inspectAdapterRegistrationCommand( sandboxName, entry, buildDeepAgentsMcpStatusCommand(entry, credentialRevision), diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.test.ts index b272e7cadb8..376755536e0 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.test.ts @@ -338,20 +338,20 @@ describe("Deep Agents MCP config adapter registration", () => { ).not.toThrow(); }); - it("repairs and verifies every registry-owned server through the sandbox command boundary (#10756)", () => { + it("repairs and verifies every registry-owned server through the sandbox command boundary (#10756)", async () => { const entries = [jiraEntry(), baseEntry]; executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) - .mockReturnValueOnce({ + .mockResolvedValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "NEMOCLAW_DEEPAGENTS_MCP_CAPABILITY=2\n", stderr: "", }) - .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "registered\n", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "registered\n", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "registered\n", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "registered\n", stderr: "" }); - restoreDeepAgentsManagedMcpProjection("alpha", entries, runtimeSelection); + await restoreDeepAgentsManagedMcpProjection("alpha", entries, runtimeSelection); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(5); expect( @@ -372,59 +372,60 @@ describe("Deep Agents MCP config adapter registration", () => { ); }); - it("resets the managed v2 projection when the registry has no Deep Agents bridges (#10756)", () => { + it("resets the managed v2 projection when the registry has no Deep Agents bridges (#10756)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) - .mockReturnValueOnce({ + .mockResolvedValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "NEMOCLAW_DEEPAGENTS_MCP_CAPABILITY=2\n", stderr: "", }) - .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }); - restoreDeepAgentsManagedMcpProjection("alpha", [], runtimeSelection); + await restoreDeepAgentsManagedMcpProjection("alpha", [], runtimeSelection); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(3); expect(executeSandboxCommandMock.mock.calls[2]?.[1]).toContain('\\"expectedServers\\":{}'); }); - it("stops after runtime detection returns an unknown kind (#10756)", () => { - executeSandboxCommandMock.mockReturnValueOnce({ + it("stops after runtime detection returns an unknown kind (#10756)", async () => { + executeSandboxCommandMock.mockResolvedValueOnce({ status: 0, stdout: "unknown\n", stderr: "", }); - expect(() => restoreDeepAgentsManagedMcpProjection("alpha", [], runtimeSelection)).toThrow( - "Could not identify the managed Deep Agents MCP runtime.", - ); + await expect( + async () => await restoreDeepAgentsManagedMcpProjection("alpha", [], runtimeSelection), + ).rejects.toThrow("Could not identify the managed Deep Agents MCP runtime."); expect(executeSandboxCommandMock).toHaveBeenCalledOnce(); }); - it("leaves the v2 projection unchanged for a legacy Deep Agents runtime (#10756)", () => { - executeSandboxCommandMock.mockReturnValueOnce({ + it("leaves the v2 projection unchanged for a legacy Deep Agents runtime (#10756)", async () => { + executeSandboxCommandMock.mockResolvedValueOnce({ status: 0, stdout: "legacy\n", stderr: "", }); - restoreDeepAgentsManagedMcpProjection("alpha", [baseEntry], runtimeSelection); + await restoreDeepAgentsManagedMcpProjection("alpha", [baseEntry], runtimeSelection); expect(executeSandboxCommandMock).toHaveBeenCalledOnce(); }); - it("rejects a v2 runtime without the managed MCP mutation capability (#10756)", () => { + it("rejects a v2 runtime without the managed MCP mutation capability (#10756)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) - .mockReturnValueOnce({ + .mockResolvedValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "NEMOCLAW_DEEPAGENTS_MCP_CAPABILITY=1\n", stderr: "", }); - expect(() => - restoreDeepAgentsManagedMcpProjection("alpha", [baseEntry], runtimeSelection), - ).toThrow("does not contain managed MCP capability v2"); + await expect( + async () => + await restoreDeepAgentsManagedMcpProjection("alpha", [baseEntry], runtimeSelection), + ).rejects.toThrow("does not contain managed MCP capability v2"); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(2); expect(executeSandboxCommandMock.mock.calls[1]?.[1]).toBe( "/usr/local/bin/deepagents-code --nemoclaw-mcp-capability", @@ -448,37 +449,47 @@ describe("Deep Agents MCP config adapter registration", () => { expect(inspection.legacyConfig).toEqual(legacyConfig); }); - it("fails when the managed projection mutation command fails (#10756)", () => { + it("fails when the managed projection mutation command fails (#10756)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) - .mockReturnValueOnce({ + .mockResolvedValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "NEMOCLAW_DEEPAGENTS_MCP_CAPABILITY=2\n", stderr: "", }) - .mockReturnValueOnce({ status: 2, stdout: "", stderr: "projection is unsafe" }); - - expect(() => - restoreDeepAgentsManagedMcpProjection("alpha", [baseEntry, jiraEntry()], runtimeSelection), - ).toThrow("projection is unsafe"); + .mockResolvedValueOnce({ status: 2, stdout: "", stderr: "projection is unsafe" }); + + await expect( + async () => + await restoreDeepAgentsManagedMcpProjection( + "alpha", + [baseEntry, jiraEntry()], + runtimeSelection, + ), + ).rejects.toThrow("projection is unsafe"); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(3); }); - it("fails when a repaired registry entry is not registered (#10756)", () => { + it("fails when a repaired registry entry is not registered (#10756)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) - .mockReturnValueOnce({ + .mockResolvedValueOnce({ status: 0, stdout: "v2\n", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "NEMOCLAW_DEEPAGENTS_MCP_CAPABILITY=2\n", stderr: "", }) - .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "registered\n", stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "mismatch\n", stderr: "" }); - - expect(() => - restoreDeepAgentsManagedMcpProjection("alpha", [baseEntry, jiraEntry()], runtimeSelection), - ).toThrow("config verification failed after adding 'jira': mismatch"); + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "registered\n", stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "mismatch\n", stderr: "" }); + + await expect( + async () => + await restoreDeepAgentsManagedMcpProjection( + "alpha", + [baseEntry, jiraEntry()], + runtimeSelection, + ), + ).rejects.toThrow("config verification failed after adding 'jira': mismatch"); }); it.each([ @@ -498,10 +509,15 @@ describe("Deep Agents MCP config adapter registration", () => { label: "another agent's entry", entry: { ...baseEntry, agent: "openclaw" }, }, - ])("rejects $label before running a sandbox command (#10756)", ({ entry }) => { - expect(() => - restoreDeepAgentsManagedMcpProjection("alpha", [entry as McpBridgeEntry], runtimeSelection), - ).toThrow("requires Deep Agents registry entries"); + ])("rejects $label before running a sandbox command (#10756)", async ({ entry }) => { + await expect( + async () => + await restoreDeepAgentsManagedMcpProjection( + "alpha", + [entry as McpBridgeEntry], + runtimeSelection, + ), + ).rejects.toThrow("requires Deep Agents registry entries"); expect(executeSandboxCommandMock).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.ts index 6201f017920..29fedd81627 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-registration.ts @@ -222,13 +222,13 @@ function registryOwnedDeepAgentsEntries( return [...entries.values()]; } -function verifyDeepAgentsAdapterRegistration( +async function verifyDeepAgentsAdapterRegistration( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, credentialRevision?: McpAttachedCredentialRevision, -): void { - const inspection = inspectDeepAgentsAdapterRegistration( +): Promise { + const inspection = await inspectDeepAgentsAdapterRegistration( sandboxName, entry, runtimeSelection, @@ -241,7 +241,7 @@ function verifyDeepAgentsAdapterRegistration( ); } -export function registerDeepAgentsAdapter( +export async function registerDeepAgentsAdapter( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, @@ -249,8 +249,8 @@ export function registerDeepAgentsAdapter( replaceExisting = false, teardownRollback = false, credentialRevision?: McpAttachedCredentialRevision, -): void { - const stdout = runDeepAgentsAdapterCommand( +): Promise { + const stdout = await runDeepAgentsAdapterCommand( sandboxName, entry, buildDeepAgentsMcpRegisterCommand( @@ -271,15 +271,20 @@ export function registerDeepAgentsAdapter( ); } } else { - verifyDeepAgentsAdapterRegistration(sandboxName, entry, runtimeSelection, credentialRevision); + await verifyDeepAgentsAdapterRegistration( + sandboxName, + entry, + runtimeSelection, + credentialRevision, + ); } } -export function restoreDeepAgentsManagedMcpProjection( +export async function restoreDeepAgentsManagedMcpProjection( sandboxName: string, entries: readonly McpBridgeEntry[], runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { +): Promise { const managedEntries = [...entries].sort((left, right) => left.server.localeCompare(right.server), ); @@ -295,12 +300,14 @@ export function restoreDeepAgentsManagedMcpProjection( } const entry = managedEntries[0]; const commandEntry: Pick = entry ?? { env: [] }; - const runtimeKind = runDeepAgentsAdapterCommand( - sandboxName, - commandEntry, - buildDeepAgentsMcpRuntimeKindCommand(), - "Could not identify the managed Deep Agents MCP runtime.", - runtimeSelection, + const runtimeKind = ( + await runDeepAgentsAdapterCommand( + sandboxName, + commandEntry, + buildDeepAgentsMcpRuntimeKindCommand(), + "Could not identify the managed Deep Agents MCP runtime.", + runtimeSelection, + ) ) .trim() .split(/\r?\n/u) @@ -309,8 +316,8 @@ export function restoreDeepAgentsManagedMcpProjection( if (runtimeKind !== "v2") { throw new McpBridgeError("Could not identify the managed Deep Agents MCP runtime."); } - assertDeepAgentsMcpMutationRuntimeCapability(sandboxName, runtimeSelection); - runDeepAgentsAdapterCommand( + await assertDeepAgentsMcpMutationRuntimeCapability(sandboxName, runtimeSelection); + await runDeepAgentsAdapterCommand( sandboxName, commandEntry, buildDeepAgentsMcpRegisterCommand(entry, true, managedEntries, false, undefined, { @@ -320,6 +327,6 @@ export function restoreDeepAgentsManagedMcpProjection( runtimeSelection, ); for (const managedEntry of managedEntries) { - verifyDeepAgentsAdapterRegistration(sandboxName, managedEntry, runtimeSelection); + await verifyDeepAgentsAdapterRegistration(sandboxName, managedEntry, runtimeSelection); } } diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-teardown.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-teardown.ts index 815ec3f5d4e..863c5245c83 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-teardown.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-deepagents-teardown.ts @@ -165,13 +165,13 @@ export function buildDeepAgentsMcpRemoveCommand( ].join("\n"); } -export function unregisterDeepAgentsAdapter( +export async function unregisterDeepAgentsAdapter( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, options: AdapterMutationOptions = {}, -): AdapterRemovalOutcome { - const stdout = runDeepAgentsAdapterCommand( +): Promise { + const stdout = await runDeepAgentsAdapterCommand( sandboxName, entry, buildDeepAgentsMcpRemoveCommand(entry, options.force === true, options.teardown === true), diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts index 3c2fea22e4b..0b4cc171809 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts @@ -73,13 +73,13 @@ export function buildHermesMcpProbeCommand(): string[] { return [HERMES_MCP_TRANSACTION_HELPER, "probe"]; } -export function inspectHermesAdapterRegistration( +export async function inspectHermesAdapterRegistration( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, credentialRevision?: McpAttachedCredentialRevision, -): AdapterRegistrationInspection { - return inspectAdapterRegistrationCommand( +): Promise { + return await inspectAdapterRegistrationCommand( sandboxName, entry, buildHermesMcpStatusCommand(entry, credentialRevision), @@ -224,13 +224,13 @@ function runHermesAdapterCommand( } } -function verifyHermesAdapterRegistration( +async function verifyHermesAdapterRegistration( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, credentialRevision?: McpAttachedCredentialRevision, -): void { - const inspection = inspectHermesAdapterRegistration( +): Promise { + const inspection = await inspectHermesAdapterRegistration( sandboxName, entry, runtimeSelection, @@ -243,14 +243,14 @@ function verifyHermesAdapterRegistration( ); } -export function registerHermesAdapter( +export async function registerHermesAdapter( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, envValues: Record = {}, replaceExisting = false, credentialRevision?: McpAttachedCredentialRevision, -): void { +): Promise { runHermesAdapterCommand( sandboxName, entry, @@ -259,7 +259,7 @@ export function registerHermesAdapter( runtimeSelection, { envValues, requireReload: true }, ); - verifyHermesAdapterRegistration(sandboxName, entry, runtimeSelection, credentialRevision); + await verifyHermesAdapterRegistration(sandboxName, entry, runtimeSelection, credentialRevision); } export function unregisterHermesAdapter( diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-inspection.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-inspection.ts index b5236992462..bb9ee0c6145 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-inspection.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-inspection.ts @@ -47,13 +47,13 @@ export function parseAdapterRegistrationInspection( }; } -export function inspectAdapterRegistrationCommand( +export async function inspectAdapterRegistrationCommand( sandboxName: string, entry: McpBridgeEntry, command: string, runtimeSelection: McpProviderInspectionRuntimeSelection, -): AdapterRegistrationInspection { - const result = executeSandboxCommand(sandboxName, command, { runtimeSelection }); +): Promise { + const result = await executeSandboxCommand(sandboxName, command, { runtimeSelection }); if (!result) return { state: "error", detail: "sandbox unreachable" }; return parseAdapterRegistrationInspection(result, entry); } diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.test.ts index b83a839963c..8cb94e10f54 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.test.ts @@ -539,7 +539,7 @@ agentDefs.loadAgent = () => ({ mcpCapability: { support: "bridge", adapter: "mcporter" }, }); const commands = []; -processRecovery.executeSandboxCommand = (_sandboxName, command) => { +processRecovery.executeSandboxCommand = async (_sandboxName, command) => { commands.push(command); return command === "command -v mcporter" ? { status: 0, stdout: "/usr/bin/mcporter\\n", stderr: "" } @@ -548,9 +548,11 @@ processRecovery.executeSandboxCommand = (_sandboxName, command) => { const adapter = require("./src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.js"); const entry = ${JSON.stringify(baseEntry)}; const runtimeSelection = { gatewayName: "nemoclaw-8091", workspace: "default" }; -adapter.registerOpenClawAdapter("custom-root-lifecycle", entry, runtimeSelection); -adapter.unregisterOpenClawAdapter("custom-root-lifecycle", entry, runtimeSelection); +(async () => { +await adapter.registerOpenClawAdapter("custom-root-lifecycle", entry, runtimeSelection); +await adapter.unregisterOpenClawAdapter("custom-root-lifecycle", entry, runtimeSelection); process.stdout.write(JSON.stringify(commands)); +})().catch((error) => { console.error(error); process.exitCode = 1; }); `; const result = spawnSync(process.execPath, ["-e", script], { cwd: process.cwd(), diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts index 689d95925f7..bed460c1c54 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-openclaw.ts @@ -40,11 +40,13 @@ function mcporterRootForEntry(entry: McpBridgeEntry): string { : OPENCLAW_MCPORTER_ROOT; } -function ensureMcporter( +async function ensureMcporter( sandboxName: string, runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { - const check = executeSandboxCommand(sandboxName, "command -v mcporter", { runtimeSelection }); +): Promise { + const check = await executeSandboxCommand(sandboxName, "command -v mcporter", { + runtimeSelection, + }); if (check?.status === 0 && check.stdout.trim()) return; throw new McpBridgeError( `mcporter is not available in sandbox '${sandboxName}'. Rebuild with a NemoClaw image that includes mcporter@${MCPORTER_VERSION}.`, @@ -131,13 +133,13 @@ export function buildOpenClawMcporterRemoveCommand( ].join("\n"); } -export function inspectOpenClawAdapterRegistration( +export async function inspectOpenClawAdapterRegistration( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, -): AdapterRegistrationInspection { +): Promise { const root = mcporterRootForEntry(entry); - return inspectAdapterRegistrationCommand( + return await inspectAdapterRegistrationCommand( sandboxName, entry, buildOpenClawMcporterInspectCommand(entry, false, root), @@ -145,17 +147,17 @@ export function inspectOpenClawAdapterRegistration( ); } -export function registerOpenClawAdapter( +export async function registerOpenClawAdapter( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, envValues: Record = {}, replaceExisting = false, credentialRevision?: McpAttachedCredentialRevision, -): void { - ensureMcporter(sandboxName, runtimeSelection); +): Promise { + await ensureMcporter(sandboxName, runtimeSelection); const root = mcporterRootForEntry(entry); - const result = executeSandboxCommand( + const result = await executeSandboxCommand( sandboxName, buildOpenClawMcporterRegisterCommand(entry, replaceExisting, root, credentialRevision), { runtimeSelection }, @@ -173,7 +175,7 @@ export function registerOpenClawAdapter( // command. Re-read the persisted definition before claiming ownership so a // changed mcporter normalization/schema cannot commit an entry that differs // from the URL and opaque OpenShell placeholder NemoClaw intended. - const verification = executeSandboxCommand( + const verification = await executeSandboxCommand( sandboxName, buildOpenClawMcporterInspectCommand(entry, true, root, credentialRevision), { runtimeSelection }, @@ -194,14 +196,14 @@ export function registerOpenClawAdapter( } } -export function unregisterOpenClawAdapter( +export async function unregisterOpenClawAdapter( sandboxName: string, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, options: AdapterMutationOptions = {}, -): void { +): Promise { const root = mcporterRootForEntry(entry); - const result = executeSandboxCommand( + const result = await executeSandboxCommand( sandboxName, buildOpenClawMcporterRemoveCommand(entry, options.force === true, root), { runtimeSelection }, diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts index 81ca6d9be65..4dd8107948b 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts @@ -178,14 +178,14 @@ describe.each(adapterCases)("$name MCP adapter registration", (adapterCase) => { mocks.getSandbox.mockReset().mockReturnValue(sandbox); }); - it("re-reads the persisted definition before registration succeeds", () => { + it("re-reads the persisted definition before registration succeeds", async () => { adapterCase.arrangeInspection(registered); - expect(() => + await expect( registerAgentAdapter("alpha", adapterCase.adapter, adapterCase.entry, runtimeSelection, { GITHUB_TOKEN: "host-only-secret", }), - ).not.toThrow(); + ).resolves.toBeUndefined(); expect(mocks.executeSandboxCommand).toHaveBeenLastCalledWith( "alpha", @@ -197,14 +197,16 @@ describe.each(adapterCases)("$name MCP adapter registration", (adapterCase) => { ); }); - it("rejects a persisted definition that differs from the requested entry", () => { + it("rejects a persisted definition that differs from the requested entry", async () => { adapterCase.arrangeInspection(mismatch); - expect(() => + await expect( registerAgentAdapter("alpha", adapterCase.adapter, adapterCase.entry, runtimeSelection, { GITHUB_TOKEN: "host-only-secret", }), - ).toThrow(`${adapterCase.adapter} config verification failed after adding 'github': mismatch.`); + ).rejects.toThrow( + `${adapterCase.adapter} config verification failed after adding 'github': mismatch.`, + ); }); }); @@ -214,7 +216,7 @@ describe("OpenClaw MCP adapter registration", () => { mocks.getSandbox.mockReset().mockReturnValue(sandbox); }); - it("rejects a v11 post-write observation after registering the readiness-proven v12", () => { + it("rejects a v11 post-write observation after registering the readiness-proven v12", async () => { const entry: McpBridgeEntry = { ...baseEntry, agent: "openclaw", @@ -231,7 +233,7 @@ describe("OpenClaw MCP adapter registration", () => { .mockReturnValueOnce(commandSuccess) .mockReturnValueOnce(verification); - expect(() => + await expect( registerOpenClawAdapter( "alpha", entry, @@ -240,7 +242,7 @@ describe("OpenClaw MCP adapter registration", () => { false, "v12", ), - ).toThrow("mcporter config verification failed after adding 'github': mismatch"); + ).rejects.toThrow("mcporter config verification failed after adding 'github': mismatch"); expect(mocks.executeSandboxCommand.mock.calls[1]?.[1]).toContain( "Authorization=Bearer openshell:resolve:env:v12_GITHUB_TOKEN", @@ -260,7 +262,7 @@ describe("Deep Agents MCP adapter credential revision", () => { mocks.getSandbox.mockReset().mockReturnValue(sandbox); }); - it("writes and verifies the readiness-proven revision", () => { + it("writes and verifies the readiness-proven revision", async () => { const entry: McpBridgeEntry = { ...baseEntry, agent: "langchain-deepagents-code", @@ -268,7 +270,7 @@ describe("Deep Agents MCP adapter credential revision", () => { }; mocks.executeSandboxCommand.mockReturnValueOnce(commandSuccess).mockReturnValueOnce(registered); - expect(() => + await expect( registerAgentAdapter( "alpha", "deepagents-config", @@ -277,7 +279,7 @@ describe("Deep Agents MCP adapter credential revision", () => { { GITHUB_TOKEN: "host-only-secret" }, { credentialRevision: "v12" }, ), - ).not.toThrow(); + ).resolves.toBeUndefined(); expect(mocks.executeSandboxCommand.mock.calls[0]?.[1]).toContain( "Bearer openshell:resolve:env:v12_GITHUB_TOKEN", @@ -299,7 +301,7 @@ describe("Hermes MCP adapter credential revision", () => { mocks.getSandbox.mockReset().mockReturnValue(sandbox); }); - it("writes and verifies the readiness-proven revision", () => { + it("writes and verifies the readiness-proven revision", async () => { mocks.runOpenshellProviderCommand.mockReturnValue(lifecycleSuccess); mocks.executeSandboxCommand.mockReturnValue(registered); mocks.executeSandboxExecCommand.mockReturnValue({ @@ -308,7 +310,7 @@ describe("Hermes MCP adapter credential revision", () => { stderr: "", }); - expect(() => + await expect( registerAgentAdapter( "alpha", "hermes-config", @@ -317,7 +319,7 @@ describe("Hermes MCP adapter credential revision", () => { { GITHUB_TOKEN: "host-only-secret" }, { credentialRevision: "v12" }, ), - ).not.toThrow(); + ).resolves.toBeUndefined(); expect(JSON.stringify(mocks.runOpenshellProviderCommand.mock.calls[0]?.[0])).toContain( "Bearer openshell:resolve:env:v12_GITHUB_TOKEN", diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts index 3a0a270a1ee..8f54b967daf 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts @@ -44,7 +44,7 @@ export async function scrubManagedMcpAdapterOrThrow( } const credentialRevision: McpAttachedCredentialRevision = observation; const adapter = resolveManagedMcpAdapter(sandbox, entry); - const removal = unregisterAgentAdapter(sandboxName, adapter, entry, runtimeSelection, { + const removal = await unregisterAgentAdapter(sandboxName, adapter, entry, runtimeSelection, { envValues: {}, teardown: true, }); diff --git a/src/lib/actions/sandbox/mcp-bridge-adapters.ts b/src/lib/actions/sandbox/mcp-bridge-adapters.ts index 1b0b4825fae..42032493fc7 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapters.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapters.ts @@ -65,30 +65,30 @@ export { openClawMcporterRoot, } from "./mcp-bridge-adapter-status"; -export function inspectAgentAdapterRegistration( +export async function inspectAgentAdapterRegistration( sandboxName: string, adapter: AgentMcpAdapter, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, -): AdapterRegistrationInspection { +): Promise { switch (adapter) { case "mcporter": - return inspectOpenClawAdapterRegistration(sandboxName, entry, runtimeSelection); + return await inspectOpenClawAdapterRegistration(sandboxName, entry, runtimeSelection); case "hermes-config": - return inspectHermesAdapterRegistration(sandboxName, entry, runtimeSelection); + return await inspectHermesAdapterRegistration(sandboxName, entry, runtimeSelection); case "deepagents-config": - return inspectDeepAgentsAdapterRegistration(sandboxName, entry, runtimeSelection); + return await inspectDeepAgentsAdapterRegistration(sandboxName, entry, runtimeSelection); } } -export function assertAgentMcpMutationRuntimeCapability( +export async function assertAgentMcpMutationRuntimeCapability( sandboxName: string, adapter: AgentMcpAdapter, runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { +): Promise { switch (adapter) { case "deepagents-config": - assertDeepAgentsMcpMutationRuntimeCapability(sandboxName, runtimeSelection); + await assertDeepAgentsMcpMutationRuntimeCapability(sandboxName, runtimeSelection); return; case "hermes-config": assertHermesMcpMutationRuntimeCapability(sandboxName, runtimeSelection); @@ -105,17 +105,17 @@ export function assertAgentMcpMutationRuntimeCapability( * ownership-checked config scrub directly and must remain available to images * that predate the new launcher marker. */ -export function assertAgentMcpTeardownRuntimeCapability( +export async function assertAgentMcpTeardownRuntimeCapability( sandboxName: string, adapter: AgentMcpAdapter, runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { +): Promise { if (adapter === "hermes-config") { - assertAgentMcpMutationRuntimeCapability(sandboxName, adapter, runtimeSelection); + await assertAgentMcpMutationRuntimeCapability(sandboxName, adapter, runtimeSelection); } } -export function registerAgentAdapter( +export async function registerAgentAdapter( sandboxName: string, adapter: AgentMcpAdapter, entry: McpBridgeEntry, @@ -126,10 +126,10 @@ export function registerAgentAdapter( teardownRollback?: boolean; credentialRevision?: McpAttachedCredentialRevision; } = {}, -): void { +): Promise { switch (adapter) { case "mcporter": - registerOpenClawAdapter( + await registerOpenClawAdapter( sandboxName, entry, runtimeSelection, @@ -139,7 +139,7 @@ export function registerAgentAdapter( ); return; case "hermes-config": - registerHermesAdapter( + await registerHermesAdapter( sandboxName, entry, runtimeSelection, @@ -149,7 +149,7 @@ export function registerAgentAdapter( ); return; case "deepagents-config": - registerDeepAgentsAdapter( + await registerDeepAgentsAdapter( sandboxName, entry, runtimeSelection, @@ -183,7 +183,7 @@ export async function registerAgentAdapterAtCurrentCredentialRevision( registration <= MAX_CREDENTIAL_REVISION_REGISTRATIONS; registration += 1 ) { - registerAgentAdapter(sandboxName, adapter, entry, runtimeSelection, envValues, { + await registerAgentAdapter(sandboxName, adapter, entry, runtimeSelection, envValues, { replaceExisting, teardownRollback: options.teardownRollback === true, credentialRevision, @@ -231,21 +231,21 @@ export async function registerAgentAdapterAtCurrentCredentialRevision( throw mcpAdapterCredentialRevisionUnstableError(entry.server); } -export function unregisterAgentAdapter( +export async function unregisterAgentAdapter( sandboxName: string, adapter: AgentMcpAdapter, entry: McpBridgeEntry, runtimeSelection: McpProviderInspectionRuntimeSelection, options: AdapterMutationOptions = {}, -): AdapterRemovalOutcome { +): Promise { switch (adapter) { case "mcporter": - unregisterOpenClawAdapter(sandboxName, entry, runtimeSelection, options); + await unregisterOpenClawAdapter(sandboxName, entry, runtimeSelection, options); return "removed"; case "hermes-config": unregisterHermesAdapter(sandboxName, entry, runtimeSelection, options); return "removed"; case "deepagents-config": - return unregisterDeepAgentsAdapter(sandboxName, entry, runtimeSelection, options); + return await unregisterDeepAgentsAdapter(sandboxName, entry, runtimeSelection, options); } } diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 339b8c4e7f0..b71a5905054 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -105,7 +105,7 @@ async function assertPreparedMcpAddResourcesAbsent( target: McpBridgeTargetValidation, providerRuntimeSelection: ReturnType, ): Promise { - const adapterInspection = inspectAgentAdapterRegistration( + const adapterInspection = await inspectAgentAdapterRegistration( sandboxName, adapter, entry, @@ -467,7 +467,7 @@ async function addMcpBridgeUnlocked( detachedMissingProviderReference = true; } } - assertAgentMcpMutationRuntimeCapability(sandboxName, adapter, providerRuntimeSelection); + await assertAgentMcpMutationRuntimeCapability(sandboxName, adapter, providerRuntimeSelection); if (detachedMissingProviderReference) { await waitForDetachedMcpCredential(sandboxName, entry, providerRuntimeSelection); } @@ -500,7 +500,7 @@ async function addMcpBridgeUnlocked( // may therefore reuse only missing or exact resources, never drift. writeBridgeEntry(sandboxName, entry); } - const adapterInspection = inspectAgentAdapterRegistration( + const adapterInspection = await inspectAgentAdapterRegistration( sandboxName, adapter, entry, @@ -639,15 +639,22 @@ async function addMcpBridgeUnlocked( // The adapter was proven absent above, so cleanup is safe even when a // command commits config and then fails during its runtime reload. adapterMutationAttempted = true; - registerAgentAdapter(sandboxName, adapter, entry, providerRuntimeSelection, adapterEnvValues, { - // An exact adapter entry is evidence of a post-commit process death. - // Replacing it is idempotent and, for Hermes, re-verifies runtime reload. - // The wait above already proved the same revision stable in consecutive - // fresh execs, so repeating reconciliation here can outlive the caller's - // bounded provider-synchronization contract. - replaceExisting: resumingPreflightedAdd && adapterInspection.state === "registered", - credentialRevision, - }); + await registerAgentAdapter( + sandboxName, + adapter, + entry, + providerRuntimeSelection, + adapterEnvValues, + { + // An exact adapter entry is evidence of a post-commit process death. + // Replacing it is idempotent and, for Hermes, re-verifies runtime reload. + // The wait above already proved the same revision stable in consecutive + // fresh execs, so repeating reconciliation here can outlive the caller's + // bounded provider-synchronization contract. + replaceExisting: resumingPreflightedAdd && adapterInspection.state === "registered", + credentialRevision, + }, + ); if (adapter === "hermes-config") { assertHermesMcpRuntimeIntent(sandboxName, { runtimeSelection: providerRuntimeSelection, @@ -664,7 +671,7 @@ async function addMcpBridgeUnlocked( !!rollbackProviderInspection && providerMatchesCredential(rollbackProviderInspection, entry.env[0], entry.providerId); if (adapterMutationAttempted) { - unregisterAgentAdapter(sandboxName, adapter, entry, providerRuntimeSelection, { + await unregisterAgentAdapter(sandboxName, adapter, entry, providerRuntimeSelection, { force: false, bestEffort: true, envValues: adapterEnvValues, diff --git a/src/lib/actions/sandbox/mcp-bridge-destroy.ts b/src/lib/actions/sandbox/mcp-bridge-destroy.ts index 3f7e07c665c..cb1ab3775c1 100644 --- a/src/lib/actions/sandbox/mcp-bridge-destroy.ts +++ b/src/lib/actions/sandbox/mcp-bridge-destroy.ts @@ -126,7 +126,7 @@ export async function prepareMcpBridgesForDestroy( }; } - assertMcpAdapterTeardownRuntimeCapabilities( + await assertMcpAdapterTeardownRuntimeCapabilities( sandboxName, sandbox, entries, diff --git a/src/lib/actions/sandbox/mcp-bridge-rebuild.ts b/src/lib/actions/sandbox/mcp-bridge-rebuild.ts index f7b043da093..60d41ccb75c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-rebuild.ts +++ b/src/lib/actions/sandbox/mcp-bridge-rebuild.ts @@ -255,7 +255,7 @@ export async function prepareMcpBridgesForRebuild( const entries = persistMcpRebuildEntryUpgrades(sandboxName, storedEntries, targets); await ensureSandboxGatewaySelected(sandboxName, providerRuntimeSelection); for (const entry of entries) assertGeneratedPolicyMutationSafe(sandboxName, entry); - assertMcpAdapterTeardownRuntimeCapabilities( + await assertMcpAdapterTeardownRuntimeCapabilities( sandboxName, sandbox, entries, @@ -388,7 +388,7 @@ export async function reattachMcpProvidersAfterRebuildAbort( const providerRuntimeSelection = runtimeSelection ?? getMcpProviderInspectionRuntimeSelection(sandbox); await ensureSandboxGatewaySelected(sandboxName, providerRuntimeSelection); - assertMcpAdapterTeardownRuntimeCapabilities( + await assertMcpAdapterTeardownRuntimeCapabilities( sandboxName, sandbox, [...entries, ...scrubbedAdapterEntries], diff --git a/src/lib/actions/sandbox/mcp-bridge-remove.ts b/src/lib/actions/sandbox/mcp-bridge-remove.ts index 2b17fd5c407..64158e05609 100644 --- a/src/lib/actions/sandbox/mcp-bridge-remove.ts +++ b/src/lib/actions/sandbox/mcp-bridge-remove.ts @@ -314,8 +314,8 @@ async function removeMcpBridgeUnlocked( // this probe precedes every provider/policy/adapter side effect. Hermes // retains its helper/lifecycle validation; Deep Agents intentionally // skips only the marker that an older image cannot expose. - assertAgentMcpTeardownRuntimeCapability(sandboxName, adapter, providerRuntimeSelection); - const adapterRemoval = unregisterAgentAdapter( + await assertAgentMcpTeardownRuntimeCapability(sandboxName, adapter, providerRuntimeSelection); + const adapterRemoval = await unregisterAgentAdapter( sandboxName, (entry.adapter as AgentMcpAdapter | undefined) ?? adapter, entry, diff --git a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts index 44b78115bbc..99fa7c8346b 100644 --- a/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts +++ b/src/lib/actions/sandbox/mcp-bridge-resolution-probe.ts @@ -431,6 +431,8 @@ export async function probeCredentialResolution( } const probeCommand = buildCredentialResolutionProbeCommand(entry, adapter, credentialRevision); if (!probeCommand) return { ok: null, detail: "no credential binding or safe endpoint to probe" }; - const result = executeSandboxCommand(sandboxName, probeCommand.command, { runtimeSelection }); + const result = await executeSandboxCommand(sandboxName, probeCommand.command, { + runtimeSelection, + }); return classifyCredentialResolutionProbe(result, entry, probeCommand.resultMarker); } diff --git a/src/lib/actions/sandbox/mcp-bridge-restart.ts b/src/lib/actions/sandbox/mcp-bridge-restart.ts index b7a3aab4216..975a84e8784 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart.ts @@ -200,7 +200,7 @@ async function restartMcpBridgeUnlocked(sandboxName: string, server?: string): P for (const entry of missingProviderEntries) { await detachMissingProviderReference(sandboxName, entry, providerRuntimeSelection); } - assertMcpAdapterMutationRuntimeCapabilities( + await assertMcpAdapterMutationRuntimeCapabilities( sandboxName, sandbox, targetEntries, @@ -339,14 +339,14 @@ export async function restoreExistingMcpBridgeRuntime( // Deep Agents entry on the same old image it just scrubbed. New/rebuilt // images use the default path and must prove the current marker before any // policy, provider, attachment, or adapter mutation. - assertMcpAdapterTeardownRuntimeCapabilities( + await assertMcpAdapterTeardownRuntimeCapabilities( sandboxName, sandbox, entries, providerRuntimeSelection, ); } else { - assertMcpAdapterMutationRuntimeCapabilities( + await assertMcpAdapterMutationRuntimeCapabilities( sandboxName, sandbox, entries, diff --git a/src/lib/actions/sandbox/mcp-bridge-runtime-capabilities.ts b/src/lib/actions/sandbox/mcp-bridge-runtime-capabilities.ts index e5700811b92..eedf230330d 100644 --- a/src/lib/actions/sandbox/mcp-bridge-runtime-capabilities.ts +++ b/src/lib/actions/sandbox/mcp-bridge-runtime-capabilities.ts @@ -22,14 +22,14 @@ function adaptersForEntries( ); } -export function assertMcpAdapterMutationRuntimeCapabilities( +export async function assertMcpAdapterMutationRuntimeCapabilities( sandboxName: string, sandbox: SandboxEntry, entries: readonly McpBridgeEntry[], runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { +): Promise { for (const adapter of adaptersForEntries(sandbox, entries)) { - assertAgentMcpMutationRuntimeCapability(sandboxName, adapter, runtimeSelection); + await assertAgentMcpMutationRuntimeCapability(sandboxName, adapter, runtimeSelection); } } @@ -39,13 +39,13 @@ export function assertMcpAdapterMutationRuntimeCapabilities( * NemoClaw release remain safe to scrub because their exact persisted adapter * definition is still ownership-checked by unregisterAgentAdapter. */ -export function assertMcpAdapterTeardownRuntimeCapabilities( +export async function assertMcpAdapterTeardownRuntimeCapabilities( sandboxName: string, sandbox: SandboxEntry, entries: readonly McpBridgeEntry[], runtimeSelection: McpProviderInspectionRuntimeSelection, -): void { +): Promise { for (const adapter of adaptersForEntries(sandbox, entries)) { - assertAgentMcpTeardownRuntimeCapability(sandboxName, adapter, runtimeSelection); + await assertAgentMcpTeardownRuntimeCapability(sandboxName, adapter, runtimeSelection); } } diff --git a/src/lib/actions/sandbox/mcp-bridge-status.ts b/src/lib/actions/sandbox/mcp-bridge-status.ts index 84debc1d0e1..1d76dcc1832 100644 --- a/src/lib/actions/sandbox/mcp-bridge-status.ts +++ b/src/lib/actions/sandbox/mcp-bridge-status.ts @@ -91,7 +91,7 @@ function storedCredentialWarning(entry: McpBridgeEntry): string | undefined { } } -function getAdapterRegistration( +async function getAdapterRegistration( sandboxName: string, adapter: AgentMcpAdapter | undefined, entry: McpBridgeEntry | undefined, @@ -99,7 +99,7 @@ function getAdapterRegistration( hermesReconciliation?: HermesMcpReconciliationResult, credentialRevision?: McpAttachedCredentialRevision, credentialObservationDetail?: string, -): McpBridgeStatus["adapter"] { +): Promise { if (!entry) return { registered: null }; if (!adapter) return { registered: null, detail: "MCP adapter is not declared" }; const credentialInspectionFailure = credentialObservationDetail @@ -126,7 +126,7 @@ function getAdapterRegistration( : adapter === "hermes-config" ? buildHermesMcpStatusCommand(entry, credentialRevision) : buildDeepAgentsMcpStatusCommand(entry, credentialRevision); - const result = executeSandboxCommand(sandboxName, command, { runtimeSelection }); + const result = await executeSandboxCommand(sandboxName, command, { runtimeSelection }); if (!result) return credentialInspectionFailure ?? { registered: null, detail: "sandbox unreachable" }; const unsafeProjection = @@ -405,7 +405,7 @@ export async function statusMcpBridge( providerAttached: attached, providerCredentialReady, }; - const adapterRegistration = getAdapterRegistration( + const adapterRegistration = await getAdapterRegistration( sandboxName, support.adapter, entry, diff --git a/src/lib/actions/sandbox/mcp-bridge-tool-discovery.ts b/src/lib/actions/sandbox/mcp-bridge-tool-discovery.ts index fe4d4e7d9c2..0330bcf8bbf 100644 --- a/src/lib/actions/sandbox/mcp-bridge-tool-discovery.ts +++ b/src/lib/actions/sandbox/mcp-bridge-tool-discovery.ts @@ -303,13 +303,13 @@ export function classifyMcpToolDiscoveryResult( }; } -export function discoverMcpTools( +export async function discoverMcpTools( sandboxName: string, entry: McpBridgeEntry, adapter: AgentMcpAdapter | undefined, readiness: McpToolDiscoveryReadiness, runtimeSelection: McpProviderInspectionRuntimeSelection, -): NonNullable { +): Promise> { if (!adapter) { return mcpToolDiscoveryPreconditionFailure( "tool discovery skipped: MCP adapter is not declared", @@ -329,7 +329,7 @@ export function discoverMcpTools( ); } return classifyMcpToolDiscoveryResult( - executeSandboxCommand(sandboxName, discoveryCommand.command, { runtimeSelection }), + await executeSandboxCommand(sandboxName, discoveryCommand.command, { runtimeSelection }), entry, discoveryCommand.resultMarker, ); diff --git a/src/lib/actions/sandbox/policy-channel-conflict.test.ts b/src/lib/actions/sandbox/policy-channel-conflict.test.ts index c4a839e54ef..d21621949b1 100644 --- a/src/lib/actions/sandbox/policy-channel-conflict.test.ts +++ b/src/lib/actions/sandbox/policy-channel-conflict.test.ts @@ -409,7 +409,7 @@ beforeEach(() => { // the exec path so the post-add verification never shells out and never trips // the exit spy unless a test explicitly overrides it. vi.spyOn(processRecovery, "executeSandboxExecCommand").mockResolvedValue(null); - vi.spyOn(processRecovery, "executeSandboxCommand").mockReturnValue(null); + vi.spyOn(processRecovery, "executeSandboxCommand").mockResolvedValue(null); process.env.NEMOCLAW_SKIP_TELEGRAM_REACHABILITY = "1"; process.env.NEMOCLAW_SKIP_SLACK_AUTH_VALIDATION = "1"; diff --git a/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts b/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts index d8e9dc2e0c8..68747c0ac4d 100644 --- a/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts +++ b/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts @@ -33,7 +33,7 @@ describe("policy channel remove/enable flows", () => { stdout: "NEMOCLAW_CHANNEL_CLEAR_OK\n", stderr: "", }); - vi.spyOn(processRecovery, "executeSandboxCommand").mockReturnValue(null); + vi.spyOn(processRecovery, "executeSandboxCommand").mockResolvedValue(null); }); afterEach(() => { @@ -185,7 +185,7 @@ describe("policy channel remove/enable flows", () => { stdout: execStatus === 0 ? "NEMOCLAW_CHANNEL_CLEAR_OK\n" : "", stderr: execStatus === 0 ? "" : "exec unavailable", }); - vi.mocked(processRecovery.executeSandboxCommand).mockReturnValue({ + vi.mocked(processRecovery.executeSandboxCommand).mockResolvedValue({ status: 0, stdout: "NEMOCLAW_CHANNEL_CLEAR_OK\n", stderr: "", @@ -219,7 +219,7 @@ describe("policy channel remove/enable flows", () => { stdout: "", stderr: "exec unavailable", }); - vi.mocked(processRecovery.executeSandboxCommand).mockReturnValue({ + vi.mocked(processRecovery.executeSandboxCommand).mockResolvedValue({ status: 1, stdout: "", stderr: "ssh unavailable", diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index f3d3f3e152b..5d80020d1cf 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -1794,7 +1794,7 @@ async function clearSandboxChannelDurableState( localDockerFallbackPolicy: "reconciled", }); if (!sentinelSeen(result)) { - result = executeSandboxCommand(sandboxName, cmd); + result = await executeSandboxCommand(sandboxName, cmd); } if (!sentinelSeen(result) && agent.name === "openclaw" && channelName === "wechat") { const stoppedCleanup = policyChannelDependencies.clearStoppedSandboxStateRoots( diff --git a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts index 7b7a2be6a0d..5ce4c8193c0 100644 --- a/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts +++ b/src/lib/actions/sandbox/process-recovery-temp-ssh.test.ts @@ -1,30 +1,28 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const captureSandboxSshConfig = vi.hoisted(() => vi.fn()); +const runSshBuffered = vi.hoisted(() => vi.fn()); const executePrivilegedSandboxCommand = vi.hoisted(() => vi.fn()); const runBuffered = vi.hoisted(() => vi.fn()); vi.mock("../../adapters/openshell/sandbox-command-cli", () => ({ + runCliOpenShellBufferedCommand: runSshBuffered, createCliOpenShellSandboxCommandExecutor: vi.fn(() => ({ runBuffered })), })); -vi.mock("node:child_process", async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, spawnSync: vi.fn(actual.spawnSync) }; -}); +vi.mock("../../adapters/openshell/resolve", () => ({ + resolveOpenshell: () => "openshell", +})); vi.mock("../../adapters/openshell/runtime", async (importOriginal) => ({ ...(await importOriginal()), captureOpenshell: vi.fn(), captureOpenshellForStatus: vi.fn(), - captureSandboxSshConfig, getOpenshellBinary: vi.fn(() => "openshell"), isCommandTimeout: vi.fn(() => false), runOpenshell: vi.fn(), @@ -45,6 +43,7 @@ import { executeSandboxCommand, executeSandboxExecCommand } from "./process-reco describe("executeSandboxCommand temp SSH config", () => { beforeEach(() => { vi.clearAllMocks(); + runSshBuffered.mockReset(); runBuffered.mockResolvedValue({ outcome: { kind: "completed", exitCode: 0 }, stdout: "", @@ -56,18 +55,21 @@ describe("executeSandboxCommand temp SSH config", () => { vi.unstubAllEnvs(); }); - it("pins SSH config and command execution to one authority-derived mTLS target (#10514)", () => { + it("pins SSH config and command execution to one authority-derived mTLS target (#10514)", async () => { vi.stubEnv("OPENSHELL_GATEWAY", "ambient-gateway"); vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://ambient.invalid"); vi.stubEnv("OPENSHELL_GATEWAY_INSECURE", "true"); vi.stubEnv("OPENSHELL_LOCAL_TLS_DIR", "/ambient/tls"); vi.stubEnv("OPENSHELL_TOKEN", "ambient-token"); vi.stubEnv("OPENSHELL_WORKSPACE", "ambient-workspace"); - captureSandboxSshConfig.mockReturnValue({ - status: 0, - output: "Host openshell-alpha.default\n HostName 127.0.0.1\n", - }); - vi.mocked(spawnSync).mockReturnValue({ + runSshBuffered + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ + status: 0, + stderr: "", + stdout: "Host openshell-alpha.default\n HostName 127.0.0.1\n", + }); + runSshBuffered.mockResolvedValueOnce({ status: 0, stdout: "ok\n", stderr: "", @@ -77,7 +79,7 @@ describe("executeSandboxCommand temp SSH config", () => { }); expect( - executeSandboxCommand("alpha", "echo ok", { + await executeSandboxCommand("alpha", "echo ok", { runtimeSelection: { gatewayName: "nemoclaw-8091", localTlsDir: "/authority/tls", @@ -86,29 +88,30 @@ describe("executeSandboxCommand temp SSH config", () => { }), ).toEqual({ status: 0, stdout: "ok", stderr: "" }); - const captureOptions = captureSandboxSshConfig.mock.calls[0]?.[1]; + const captureOptions = runSshBuffered.mock.calls[1]?.[2]; expect(captureOptions).toMatchObject({ - gatewayName: "nemoclaw-8091", - replaceEnv: true, - env: { + environment: { OPENSHELL_GATEWAY: "nemoclaw-8091", OPENSHELL_LOCAL_TLS_DIR: "/authority/tls", OPENSHELL_WORKSPACE: "default", }, }); - expect(captureOptions?.env).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); - expect(captureOptions?.env).not.toHaveProperty("OPENSHELL_GATEWAY_INSECURE"); - expect(captureOptions?.env).not.toHaveProperty("OPENSHELL_TOKEN"); - expect(vi.mocked(spawnSync).mock.calls[0]?.[2]?.env).toEqual(captureOptions?.env); + expect(captureOptions?.environment).not.toHaveProperty("OPENSHELL_GATEWAY_ENDPOINT"); + expect(captureOptions?.environment).not.toHaveProperty("OPENSHELL_GATEWAY_INSECURE"); + expect(captureOptions?.environment).not.toHaveProperty("OPENSHELL_TOKEN"); + expect(runSshBuffered.mock.calls[2]?.[2]?.environment).toEqual(captureOptions?.environment); }); - it("removes ambient mTLS when the selected gateway does not use it (#10514)", () => { + it("removes ambient mTLS when the selected gateway does not use it (#10514)", async () => { vi.stubEnv("OPENSHELL_LOCAL_TLS_DIR", "/ambient/tls"); - captureSandboxSshConfig.mockReturnValue({ - status: 0, - output: "Host openshell-alpha.default\n HostName 127.0.0.1\n", - }); - vi.mocked(spawnSync).mockReturnValue({ + runSshBuffered + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ + status: 0, + stderr: "", + stdout: "Host openshell-alpha.default\n HostName 127.0.0.1\n", + }); + runSshBuffered.mockResolvedValueOnce({ status: 0, stdout: "ok\n", stderr: "", @@ -117,14 +120,14 @@ describe("executeSandboxCommand temp SSH config", () => { signal: null, }); - executeSandboxCommand("alpha", "echo ok", { + await executeSandboxCommand("alpha", "echo ok", { runtimeSelection: { gatewayName: "external-http", workspace: "default" }, }); - expect(captureSandboxSshConfig.mock.calls[0]?.[1]?.env).not.toHaveProperty( + expect(runSshBuffered.mock.calls[1]?.[2]?.environment).not.toHaveProperty( "OPENSHELL_LOCAL_TLS_DIR", ); - expect(vi.mocked(spawnSync).mock.calls[0]?.[2]?.env).not.toHaveProperty( + expect(runSshBuffered.mock.calls[2]?.[2]?.environment).not.toHaveProperty( "OPENSHELL_LOCAL_TLS_DIR", ); }); @@ -194,12 +197,15 @@ describe("executeSandboxCommand temp SSH config", () => { expect(executePrivilegedSandboxCommand).not.toHaveBeenCalled(); }); - it("uses the exact legacy alias while backing up a pre-upgrade sandbox", () => { - captureSandboxSshConfig.mockReturnValue({ - status: 0, - output: "Host openshell-alpha\n HostName 127.0.0.1\n", - }); - vi.mocked(spawnSync).mockReturnValue({ + it("uses the exact legacy alias while backing up a pre-upgrade sandbox", async () => { + runSshBuffered + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ + status: 0, + stderr: "", + stdout: "Host openshell-alpha\n HostName 127.0.0.1\n", + }); + runSshBuffered.mockResolvedValueOnce({ status: 0, stdout: "ok\n", stderr: "", @@ -208,10 +214,10 @@ describe("executeSandboxCommand temp SSH config", () => { signal: null, }); - const result = executeSandboxCommand("alpha", "echo ok"); + const result = await executeSandboxCommand("alpha", "echo ok"); expect(result).toEqual({ status: 0, stdout: "ok", stderr: "" }); - const sshArgs = vi.mocked(spawnSync).mock.calls[0]?.[1] as string[]; + const sshArgs = runSshBuffered.mock.calls[2]?.[1] as string[]; const configFile = sshArgs[sshArgs.indexOf("-F") + 1]; const configDir = path.dirname(configFile); expect(configDir).not.toBe(os.tmpdir()); @@ -222,12 +228,15 @@ describe("executeSandboxCommand temp SSH config", () => { expect(fs.existsSync(configDir)).toBe(false); }); - it("uses the workspace-qualified alias emitted by OpenShell v0.0.99", () => { - captureSandboxSshConfig.mockReturnValue({ - status: 0, - output: "Host openshell-alpha.default\n HostName 127.0.0.1\n", - }); - vi.mocked(spawnSync).mockReturnValue({ + it("uses the workspace-qualified alias emitted by OpenShell v0.0.99", async () => { + runSshBuffered + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ + status: 0, + stderr: "", + stdout: "Host openshell-alpha.default\n HostName 127.0.0.1\n", + }); + runSshBuffered.mockResolvedValueOnce({ status: 0, stdout: "ok\n", stderr: "", @@ -236,31 +245,36 @@ describe("executeSandboxCommand temp SSH config", () => { signal: null, }); - expect(executeSandboxCommand("alpha", "echo ok")).toEqual({ + expect(await executeSandboxCommand("alpha", "echo ok")).toEqual({ status: 0, stdout: "ok", stderr: "", }); - const sshArgs = vi.mocked(spawnSync).mock.calls[0]?.[1] as string[]; + const sshArgs = runSshBuffered.mock.calls[2]?.[1] as string[]; expect(sshArgs).toContain("openshell-alpha.default"); expect(sshArgs).not.toContain("openshell-alpha"); }); - it("returns null without creating an SSH process when config capture fails", () => { - captureSandboxSshConfig.mockReturnValue({ status: 1, output: "" }); + it("returns null without creating an SSH process when config capture fails", async () => { + runSshBuffered + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "" }); - expect(executeSandboxCommand("alpha", "echo ok")).toBeNull(); - expect(spawnSync).not.toHaveBeenCalled(); + expect(await executeSandboxCommand("alpha", "echo ok")).toBeNull(); + expect(runSshBuffered).toHaveBeenCalledTimes(2); }); - it("returns null when the captured config declares no exact sandbox alias", () => { - captureSandboxSshConfig.mockReturnValue({ - status: 0, - output: "Host openshell-*\n HostName 127.0.0.1\n", - }); + it("returns null when the captured config declares no exact sandbox alias", async () => { + runSshBuffered + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockResolvedValueOnce({ + status: 0, + stderr: "", + stdout: "Host openshell-*\n HostName 127.0.0.1\n", + }); - expect(executeSandboxCommand("alpha", "echo ok")).toBeNull(); - expect(spawnSync).not.toHaveBeenCalled(); + expect(await executeSandboxCommand("alpha", "echo ok")).toBeNull(); + expect(runSshBuffered).toHaveBeenCalledTimes(2); }); }); diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 7ec254f0a81..ad614de02e0 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -16,7 +16,6 @@ import { import { buildOpenShellRuntimeSelectionEnv, captureOpenshell, - captureSandboxSshConfig, isCommandTimeout, type OpenShellRuntimeSelection, runOpenshell, @@ -150,12 +149,10 @@ function commandTransportDependencies(): CommandTransportDependencies { return { buildSandboxExecMarkedCommand, buildSubprocessEnv, - captureSandboxSshConfig, executePrivilegedSandboxCommand: executeProviderPrivilegedSandboxCommand, extractSandboxExecCommandStdout, commandExecutor: createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }), isDirectSandboxFallbackUnavailableError, - openshellProbeTimeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, }; } @@ -196,11 +193,11 @@ function getSandboxHealthProbeUrl(sandboxName: string): string { * Run a command inside the sandbox via SSH and return { status, stdout, stderr }. * Returns null if SSH config cannot be obtained. */ -export function executeSandboxCommand( +export async function executeSandboxCommand( sandboxName: string, command: string, timeoutOrOptions: number | SandboxCommandExecutionOptions = DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, -): SandboxCommandResult | null { +): Promise { const timeout = typeof timeoutOrOptions === "number" ? timeoutOrOptions @@ -210,7 +207,7 @@ export function executeSandboxCommand( const runtimeEnv = runtimeSelection ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), runtimeSelection) : undefined; - return executeSandboxCommandTransport( + return await executeSandboxCommandTransport( commandTransportDependencies(), sandboxName, command, @@ -436,7 +433,7 @@ async function isSandboxGatewayRunning( // declare a trusted runtime user/supervisor. if (!agent || agent.name === "openclaw" || agent.name === "hermes") return null; return parseSandboxGatewayProbe( - executeSandboxCommand( + await executeSandboxCommand( sandboxName, command, runtimeSelection ? { runtimeSelection } : DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, @@ -853,7 +850,7 @@ type SandboxProcessRecovery = | { kind: "provider" } | { kind: "relaunched"; relaunch: ManagedSupervisorRelaunch }; -function recoverSandboxProcesses( +async function recoverSandboxProcesses( sandboxName: string, { quiet = false, @@ -874,7 +871,7 @@ function recoverSandboxProcesses( onFailureLayer?: (layer: GatewayRestartFailureLayer, detail: string) => void; runtimeSelection?: OpenShellRuntimeSelection; } = {}, -): SandboxProcessRecovery | null { +): Promise { const effectiveGatewaySupervisorAction = runtimeSelection && requestGatewaySupervisorAction === executeGatewaySupervisorAction ? refuseHostLocalSupervisorForSelectedRuntime @@ -1080,7 +1077,7 @@ function recoverSandboxProcesses( // runtime user. Recover them over SSH so the launch inherits the sandbox // login user instead of creating root-owned agent state under /sandbox. return recoveredSsh( - executeSandboxCommand( + await executeSandboxCommand( sandboxName, agentScript, runtimeSelection ? { runtimeSelection } : DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, @@ -1885,20 +1882,22 @@ async function checkAndRecoverSandboxProcessesWithoutHostLock( let managedRecoveryFailureLayer: GatewayRestartFailureLayer | null = null; let managedRecoveryFailureDetail: string | null = null; - const recovery = measure("processes", () => - recoverSandboxProcesses(sandboxName, { - quiet, - requestGatewaySupervisorAction: effectiveGatewaySupervisorAction, - requestPinnedGatewaySupervisorAction: effectivePinnedGatewaySupervisorAction, - relaunchManagedSupervisorSessionImpl, - managedControlNowImpl, - managedControlTimeoutMs, - runtimeSelection, - onFailureLayer: (layer, detail) => { - managedRecoveryFailureLayer = layer; - managedRecoveryFailureDetail = detail; - }, - }), + const recovery = await measureAsync( + "processes", + async () => + await recoverSandboxProcesses(sandboxName, { + quiet, + requestGatewaySupervisorAction: effectiveGatewaySupervisorAction, + requestPinnedGatewaySupervisorAction: effectivePinnedGatewaySupervisorAction, + relaunchManagedSupervisorSessionImpl, + managedControlNowImpl, + managedControlTimeoutMs, + runtimeSelection, + onFailureLayer: (layer, detail) => { + managedRecoveryFailureLayer = layer; + managedRecoveryFailureDetail = detail; + }, + }), ); if (recovery !== null) { const withManagedControlCompletion = ( diff --git a/src/lib/actions/sandbox/rebuild-config-hash.test.ts b/src/lib/actions/sandbox/rebuild-config-hash.test.ts index 22f8e305d48..0e9cdfa36a0 100644 --- a/src/lib/actions/sandbox/rebuild-config-hash.test.ts +++ b/src/lib/actions/sandbox/rebuild-config-hash.test.ts @@ -38,15 +38,19 @@ describe("OpenClaw rebuild config hash target selection", () => { vi.unstubAllEnvs(); }); - it("refreshes the config hash on the selected target instead of the ambient target (#10514)", () => { - const execute = vi.spyOn(processRecovery, "executeSandboxCommand").mockReturnValue({ + it("refreshes the config hash on the selected target instead of the ambient target (#10514)", async () => { + const execute = vi.spyOn(processRecovery, "executeSandboxCommand").mockResolvedValue({ status: 0, stdout: "", stderr: "", }); expect( - refreshMutableOpenClawConfigHashAfterPostRestoreWrites("alpha", vi.fn(), runtimeSelection), + await refreshMutableOpenClawConfigHashAfterPostRestoreWrites( + "alpha", + vi.fn(), + runtimeSelection, + ), ).toBe(true); expect(execute).toHaveBeenCalledExactlyOnceWith( "alpha", @@ -56,14 +60,16 @@ describe("OpenClaw rebuild config hash target selection", () => { expect(process.env.OPENSHELL_GATEWAY).toBe("hostile-gateway"); }); - it("verifies the config hash on the selected target instead of the ambient target (#10514)", () => { - const execute = vi.spyOn(processRecovery, "executeSandboxCommand").mockReturnValue({ + it("verifies the config hash on the selected target instead of the ambient target (#10514)", async () => { + const execute = vi.spyOn(processRecovery, "executeSandboxCommand").mockResolvedValue({ status: 0, stdout: "", stderr: "", }); - expect(verifyFinalMutableOpenClawConfigHash("alpha", vi.fn(), runtimeSelection)).toBe(true); + expect(await verifyFinalMutableOpenClawConfigHash("alpha", vi.fn(), runtimeSelection)).toBe( + true, + ); expect(execute).toHaveBeenCalledExactlyOnceWith( "alpha", buildVerifyMutableOpenClawConfigHashCommand(), diff --git a/src/lib/actions/sandbox/rebuild-config-hash.ts b/src/lib/actions/sandbox/rebuild-config-hash.ts index 8b14bfae80f..de87a9451c2 100644 --- a/src/lib/actions/sandbox/rebuild-config-hash.ts +++ b/src/lib/actions/sandbox/rebuild-config-hash.ts @@ -12,16 +12,16 @@ import { export { buildRefreshMutableOpenClawConfigHashCommand }; -export function refreshMutableOpenClawConfigHashAfterPostRestoreWrites( +export async function refreshMutableOpenClawConfigHashAfterPostRestoreWrites( sandboxName: string, log: (msg: string) => void, runtimeSelection?: OpenShellRuntimeSelection, -): boolean { +): Promise { const result = runtimeSelection - ? executeSandboxCommand(sandboxName, buildRefreshMutableOpenClawConfigHashCommand(), { + ? await executeSandboxCommand(sandboxName, buildRefreshMutableOpenClawConfigHashCommand(), { runtimeSelection, }) - : executeSandboxCommand(sandboxName, buildRefreshMutableOpenClawConfigHashCommand()); + : await executeSandboxCommand(sandboxName, buildRefreshMutableOpenClawConfigHashCommand()); if (result && result.status === 0) { log("Mutable OpenClaw config hash refreshed after post-restore config writes"); return true; @@ -34,16 +34,16 @@ export function refreshMutableOpenClawConfigHashAfterPostRestoreWrites( return false; } -export function verifyFinalMutableOpenClawConfigHash( +export async function verifyFinalMutableOpenClawConfigHash( sandboxName: string, log: (msg: string) => void, runtimeSelection?: OpenShellRuntimeSelection, -): boolean { +): Promise { const result = runtimeSelection - ? executeSandboxCommand(sandboxName, buildVerifyMutableOpenClawConfigHashCommand(), { + ? await executeSandboxCommand(sandboxName, buildVerifyMutableOpenClawConfigHashCommand(), { runtimeSelection, }) - : executeSandboxCommand(sandboxName, buildVerifyMutableOpenClawConfigHashCommand()); + : await executeSandboxCommand(sandboxName, buildVerifyMutableOpenClawConfigHashCommand()); if (result && result.status === 0) { log("Final mutable OpenClaw config hash verified after post-restore finalization"); return true; diff --git a/src/lib/actions/sandbox/rebuild-mcp-phase.ts b/src/lib/actions/sandbox/rebuild-mcp-phase.ts index ea555af7115..cf6a789c507 100644 --- a/src/lib/actions/sandbox/rebuild-mcp-phase.ts +++ b/src/lib/actions/sandbox/rebuild-mcp-phase.ts @@ -53,7 +53,7 @@ async function canExecuteMcpPreparation( // inspection/mutation and OpenShell-mediated adapter/provider operations. // Prove both before any mutation. A direct Docker fallback would not prove // that the OpenShell transport itself can run. - const sshProbe = executeSandboxCommand(sandboxName, ":", { runtimeSelection }); + const sshProbe = await executeSandboxCommand(sandboxName, ":", { runtimeSelection }); const execProbe = await executeSandboxExecCommand(sandboxName, ":", undefined, { localDockerFallbackPolicy: "never", runtimeSelection, diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts index e58c3ceffad..929491ec647 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts @@ -51,7 +51,7 @@ describe("rebuild post-restore phase", () => { return { status: 0, stdout: "", stderr: "" }; }); vi.spyOn(sessionModels, "reconcileStalePinnedSessionModelsAfterRebuild").mockImplementation( - () => { + async () => { order.push("reconcile"); }, ); @@ -63,14 +63,16 @@ describe("rebuild post-restore phase", () => { vi.spyOn( rebuildConfigHash, "refreshMutableOpenClawConfigHashAfterPostRestoreWrites", - ).mockImplementation(() => { + ).mockImplementation(async () => { order.push("config-hash"); return true; }); - vi.spyOn(rebuildConfigHash, "verifyFinalMutableOpenClawConfigHash").mockImplementation(() => { - order.push("config-hash-final"); - return true; - }); + vi.spyOn(rebuildConfigHash, "verifyFinalMutableOpenClawConfigHash").mockImplementation( + async () => { + order.push("config-hash-final"); + return true; + }, + ); vi.spyOn(mutableConfigPerms, "repairMutableConfigPerms").mockImplementation(() => { order.push("permissions"); return { @@ -395,7 +397,7 @@ describe("rebuild post-restore phase", () => { }); vi.mocked( rebuildConfigHash.refreshMutableOpenClawConfigHashAfterPostRestoreWrites, - ).mockImplementation(() => { + ).mockImplementation(async () => { configHashValid = true; return true; }); @@ -406,7 +408,7 @@ describe("rebuild post-restore phase", () => { }, ); vi.mocked(rebuildConfigHash.verifyFinalMutableOpenClawConfigHash).mockImplementation( - () => configHashValid, + async () => configHashValid, ); const args = input(); @@ -987,7 +989,7 @@ describe("rebuild post-restore phase", () => { it("prints every incomplete OpenClaw recovery report in a fixed order (#8283)", async () => { vi.mocked( rebuildConfigHash.refreshMutableOpenClawConfigHashAfterPostRestoreWrites, - ).mockReturnValue(false); + ).mockResolvedValue(false); vi.mocked(mutableConfigPerms.repairMutableConfigPerms).mockReturnValue({ applied: true, verified: false, diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts index 3249a597902..9f2368c080f 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts @@ -258,7 +258,7 @@ export async function runRebuildPostRestorePhase( // #7102: clear stale per-session pinned models left over from an // `inference set` before this rebuild, while the gateway is still down. - reconcileStalePinnedSessionModelsAfterRebuild(sandboxName, log, mcpRuntimeSelection); + await reconcileStalePinnedSessionModelsAfterRebuild(sandboxName, log, mcpRuntimeSelection); try { await reapplyMessagingManifestAfterOpenClawDoctor( @@ -333,10 +333,16 @@ export async function runRebuildPostRestorePhase( } else if (targetAgentName === "openclaw") { log("Refreshing mutable OpenClaw config hash after MCP restoration"); if ( - !refreshMutableOpenClawConfigHashAfterPostRestoreWrites(sandboxName, log, mcpRuntimeSelection) + !(await refreshMutableOpenClawConfigHashAfterPostRestoreWrites( + sandboxName, + log, + mcpRuntimeSelection, + )) ) { mutableConfigHashRefreshUnverified = true; - } else if (!verifyFinalMutableOpenClawConfigHash(sandboxName, log, mcpRuntimeSelection)) { + } else if ( + !(await verifyFinalMutableOpenClawConfigHash(sandboxName, log, mcpRuntimeSelection)) + ) { finalMutableConfigHashUnverified = true; } } @@ -484,7 +490,7 @@ export async function runRebuildPostRestorePhase( targetAgentName === "openclaw" && !mcpBridgeRestoreUnverified && !mutableConfigHashRefreshUnverified && - !verifyFinalMutableOpenClawConfigHash(sandboxName, log, mcpRuntimeSelection) + !(await verifyFinalMutableOpenClawConfigHash(sandboxName, log, mcpRuntimeSelection)) ) { finalMutableConfigHashUnverified = true; } diff --git a/src/lib/actions/sandbox/reconcile-session-models.test.ts b/src/lib/actions/sandbox/reconcile-session-models.test.ts index 77978d01ed3..b13e174f9a2 100644 --- a/src/lib/actions/sandbox/reconcile-session-models.test.ts +++ b/src/lib/actions/sandbox/reconcile-session-models.test.ts @@ -272,14 +272,14 @@ describe("reconcileStalePinnedSessionModelsAfterRebuild", () => { }, }); - it("reads restored state and dispatches a guarded write for stale pins (#7102)", () => { + it("reads restored state and dispatches a guarded write for stale pins (#7102)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: config, stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: staleStore, stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: config, stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: staleStore, stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }); const log = vi.fn(); - reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); + await reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(3); expect(executeSandboxCommandMock.mock.calls[0]).toEqual([ @@ -295,18 +295,18 @@ describe("reconcileStalePinnedSessionModelsAfterRebuild", () => { ); }); - it("reuses the rebuild target for every restored session read and write (#10514)", () => { + it("reuses the rebuild target for every restored session read and write (#10514)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: config, stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: staleStore, stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); + .mockResolvedValueOnce({ status: 0, stdout: config, stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: staleStore, stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" }); const runtimeSelection = { gatewayName: "recorded-gateway", workspace: "default", localTlsDir: "/authority/tls", }; - reconcileStalePinnedSessionModelsAfterRebuild("alpha", vi.fn(), runtimeSelection); + await reconcileStalePinnedSessionModelsAfterRebuild("alpha", vi.fn(), runtimeSelection); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(3); expect(executeSandboxCommandMock.mock.calls.map((call) => call[2])).toEqual([ @@ -316,15 +316,15 @@ describe("reconcileStalePinnedSessionModelsAfterRebuild", () => { ]); }); - it("stops when the restored config has no primary model (#7102)", () => { - executeSandboxCommandMock.mockReturnValueOnce({ + it("stops when the restored config has no primary model (#7102)", async () => { + executeSandboxCommandMock.mockResolvedValueOnce({ status: 0, stdout: '{"agents":{"defaults":{}}}', stderr: "", }); const log = vi.fn(); - reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); + await reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(1); expect(log).toHaveBeenLastCalledWith( @@ -332,8 +332,8 @@ describe("reconcileStalePinnedSessionModelsAfterRebuild", () => { ); }); - it("rejects a restored primary model with terminal control characters (#7102)", () => { - executeSandboxCommandMock.mockReturnValueOnce({ + it("rejects a restored primary model with terminal control characters (#7102)", async () => { + executeSandboxCommandMock.mockResolvedValueOnce({ status: 0, stdout: JSON.stringify({ agents: { defaults: { model: { primary: "inference/model\u001b[2J" } } }, @@ -342,7 +342,7 @@ describe("reconcileStalePinnedSessionModelsAfterRebuild", () => { }); const log = vi.fn(); - reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); + await reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(1); expect(log).toHaveBeenLastCalledWith( @@ -351,13 +351,13 @@ describe("reconcileStalePinnedSessionModelsAfterRebuild", () => { expect(log.mock.calls.flat().join(" ")).not.toContain("\u001b"); }); - it("stops when the restored session store cannot be read (#7102)", () => { + it("stops when the restored session store cannot be read (#7102)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: config, stderr: "" }) - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "missing" }); + .mockResolvedValueOnce({ status: 0, stdout: config, stderr: "" }) + .mockResolvedValueOnce({ status: 1, stdout: "", stderr: "missing" }); const log = vi.fn(); - reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); + await reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(2); expect(log).toHaveBeenLastCalledWith( @@ -365,14 +365,14 @@ describe("reconcileStalePinnedSessionModelsAfterRebuild", () => { ); }); - it("reports an atomic write failure without retrying or claiming success (#7102)", () => { + it("reports an atomic write failure without retrying or claiming success (#7102)", async () => { executeSandboxCommandMock - .mockReturnValueOnce({ status: 0, stdout: config, stderr: "" }) - .mockReturnValueOnce({ status: 0, stdout: staleStore, stderr: "" }) - .mockReturnValueOnce({ status: 9, stdout: "", stderr: "refused" }); + .mockResolvedValueOnce({ status: 0, stdout: config, stderr: "" }) + .mockResolvedValueOnce({ status: 0, stdout: staleStore, stderr: "" }) + .mockResolvedValueOnce({ status: 9, stdout: "", stderr: "refused" }); const log = vi.fn(); - reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); + await reconcileStalePinnedSessionModelsAfterRebuild("alpha", log); expect(executeSandboxCommandMock).toHaveBeenCalledTimes(3); expect(log).toHaveBeenLastCalledWith( diff --git a/src/lib/actions/sandbox/reconcile-session-models.ts b/src/lib/actions/sandbox/reconcile-session-models.ts index 39be8602e33..5aef4807a4a 100644 --- a/src/lib/actions/sandbox/reconcile-session-models.ts +++ b/src/lib/actions/sandbox/reconcile-session-models.ts @@ -222,21 +222,21 @@ export function reconcilePinnedSessionModels( }; } -function executeReconcileCommand( +async function executeReconcileCommand( sandboxName: string, command: string, runtimeSelection?: OpenShellRuntimeSelection, ) { return runtimeSelection - ? executeSandboxCommand(sandboxName, command, { runtimeSelection }) - : executeSandboxCommand(sandboxName, command); + ? await executeSandboxCommand(sandboxName, command, { runtimeSelection }) + : await executeSandboxCommand(sandboxName, command); } -function readPrimaryModelRef( +async function readPrimaryModelRef( sandboxName: string, runtimeSelection?: OpenShellRuntimeSelection, -): string | null { - const res = executeReconcileCommand( +): Promise { + const res = await executeReconcileCommand( sandboxName, `cat ${OPENCLAW_CONFIG_PATH} 2>/dev/null`, runtimeSelection, @@ -267,18 +267,18 @@ function readPrimaryModelRef( * discard conversation state. This recovery can be removed when OpenClaw * exposes an offline, race-free session-model reset operation. */ -export function reconcileStalePinnedSessionModelsAfterRebuild( +export async function reconcileStalePinnedSessionModelsAfterRebuild( sandboxName: string, log: RebuildLog, runtimeSelection?: OpenShellRuntimeSelection, -): void { - const primary = readPrimaryModelRef(sandboxName, runtimeSelection); +): Promise { + const primary = await readPrimaryModelRef(sandboxName, runtimeSelection); if (!primary) { log("Session model reconcile skipped: could not read agents.defaults.model.primary"); return; } const sessionsPath = defaultAgentSessionsPath(DEFAULT_AGENT_ID); - const readResult = executeReconcileCommand( + const readResult = await executeReconcileCommand( sandboxName, `cat ${sessionsPath} 2>/dev/null`, runtimeSelection, @@ -292,7 +292,7 @@ export function reconcileStalePinnedSessionModelsAfterRebuild( log("Session model reconcile: no stale pinned session models"); return; } - const writeResult = executeReconcileCommand( + const writeResult = await executeReconcileCommand( sandboxName, buildSessionStoreReplaceCommand(sessionsPath, reconciled.content, readResult.stdout), runtimeSelection, diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index dc0c999c22e..90ffd513b52 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -188,7 +188,7 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { }, }, }); - f.restoreDeepAgentsManagedMcpProjectionMock.mockImplementation(() => { + f.restoreDeepAgentsManagedMcpProjectionMock.mockImplementation(async () => { f.lifecycleMock.events.push("restore-mcp-projection"); }); f.restoreSandboxStateMock.mockImplementation(() => { @@ -249,7 +249,7 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { }, }); f.restoreDeepAgentsManagedMcpProjectionMock - .mockImplementationOnce(() => { + .mockImplementationOnce(async () => { throw new Error("managed MCP projection path is a directory"); }) .mockImplementationOnce(() => {}); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index f6a7cd83905..eacc7d3dfdb 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -57,7 +57,10 @@ import { streamSandboxCreate } from "../../sandbox/create-stream"; import { repairMutableConfigPerms } from "../../sandbox/mutable-config-perms"; import { isSandboxReady } from "../../state/gateway"; import { withSandboxMutationLock } from "../../state/mcp-lifecycle-lock"; -import { withMcpLifecycleLockSync } from "../../state/mcp-lifecycle-lock-acquisition"; +import { + withMcpLifecycleLock, + withMcpLifecycleLockSync, +} from "../../state/mcp-lifecycle-lock-acquisition"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { getSandboxEntryInference } from "../../state/registry-entry-view"; @@ -1483,7 +1486,7 @@ async function runSnapshotRestoreUnlocked( } } } - withMcpLifecycleLockSync(targetSandbox, () => { + await withMcpLifecycleLock(targetSandbox, async () => { const snapshotTarget = registry.getSandbox(targetSandbox); const repairsManagedDeepAgentsProjection = snapshotTarget?.agent === "langchain-deepagents-code" && !snapshotTarget.fromDockerfile; @@ -1562,7 +1565,7 @@ async function runSnapshotRestoreUnlocked( throw new Error(`target '${targetSandbox}' is no longer registered`); } const runtimeSelection = getMcpProviderInspectionRuntimeSelection(currentTarget); - restoreDeepAgentsManagedMcpProjection( + await restoreDeepAgentsManagedMcpProjection( targetSandbox, managedDeepAgentsEntries, runtimeSelection, diff --git a/src/lib/adapters/openshell/sandbox-ssh-cli.test.ts b/src/lib/adapters/openshell/sandbox-ssh-cli.test.ts index 2981d903a89..7c30df380e2 100644 --- a/src/lib/adapters/openshell/sandbox-ssh-cli.test.ts +++ b/src/lib/adapters/openshell/sandbox-ssh-cli.test.ts @@ -8,7 +8,10 @@ import type { OpenShellBufferedCommandRunner, OpenShellBufferedCommandRunResult, } from "./sandbox-command-cli"; -import { createCliOpenShellSandboxSshExecutor } from "./sandbox-ssh-cli"; +import { + createCliOpenShellSandboxSshExecutor, + createCliOpenShellSandboxSshCommandExecutor, +} from "./sandbox-ssh-cli"; import { namedOpenShellGateway } from "./sandbox-observer"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; @@ -219,6 +222,27 @@ describe("CLI sandbox SSH execution", () => { expect(run).not.toHaveBeenCalled(); }); + it.each([ + { status: 255, reason: "transport", timedOut: false }, + { status: null, reason: "timeout", timedOut: true }, + ])( + "retains command diagnostics after $reason failure without retrying", + async ({ status, reason, timedOut }) => { + const { run } = fixture({ status, timedOut, stdout: "partial output", stderr: "diagnostic" }); + const executor = createCliOpenShellSandboxSshCommandExecutor({ + resolveBinary: () => "/bin/openshell", + runBuffered: run, + }); + expect(await executor.run(request)).toEqual({ + kind: "failed", + reason, + command: { exitCode: status ?? 1, stdout: "partial output", stderr: "diagnostic" }, + }); + expect(run).toHaveBeenCalledTimes(3); + expect(existsSync(dirname(run.mock.calls[2][1][1]))).toBe(false); + }, + ); + it("does not spawn when the executable is unavailable", async () => { const run = vi.fn(); const executor = createCliOpenShellSandboxSshExecutor({ diff --git a/src/lib/adapters/openshell/sandbox-ssh-cli.ts b/src/lib/adapters/openshell/sandbox-ssh-cli.ts index 18bcb3e7381..60b239a287b 100644 --- a/src/lib/adapters/openshell/sandbox-ssh-cli.ts +++ b/src/lib/adapters/openshell/sandbox-ssh-cli.ts @@ -35,6 +35,7 @@ export function createCliOpenShellSandboxSshExecutor( deps: { resolveBinary?: () => string | null; runBuffered?: OpenShellBufferedCommandRunner; + commandTransport?: boolean; } = {}, ): OpenShellSandboxSshExecutor { const run = deps.runBuffered ?? runCliOpenShellBufferedCommand; @@ -78,7 +79,10 @@ export function createCliOpenShellSandboxSshExecutor( if (sshHost === null) { return { kind: "failed", reason: "configuration" }; } - const temporary = createTempSshConfig(config.stdout, "nemoclaw-ver-"); + const temporary = createTempSshConfig( + config.stdout, + deps.commandTransport ? "nemoclaw-ssh-" : "nemoclaw-ver-", + ); try { const result = await run( "ssh", @@ -101,11 +105,24 @@ export function createCliOpenShellSandboxSshExecutor( timeoutMilliseconds: request.timeoutMilliseconds ?? 15000, }, ); - const commandFailure = failure(result); - if (commandFailure) return commandFailure; - // OpenSSH reserves 255 for connection errors; it cannot distinguish a - // remote command that also exits 255. Neither outcome permits a retry. - if (result.status === 255) return { kind: "failed", reason: "transport" }; + // OpenSSH cannot distinguish a transport failure from remote exit 255. + const commandFailure = + failure(result) ?? + (result.status === 255 + ? { kind: "failed" as const, reason: "transport" as const } + : null); + if (commandFailure) { + return deps.commandTransport + ? { + ...commandFailure, + command: { + exitCode: result.status ?? 1, + stdout: result.stdout, + stderr: result.stderr, + }, + } + : commandFailure; + } return { kind: "completed", exitCode: result.status ?? 1, @@ -121,3 +138,10 @@ export function createCliOpenShellSandboxSshExecutor( }, }; } + +/** Retain legacy host aliases and command diagnostics needed during recovery. */ +export function createCliOpenShellSandboxSshCommandExecutor( + deps: Parameters[0] = {}, +): OpenShellSandboxSshExecutor { + return createCliOpenShellSandboxSshExecutor({ ...deps, commandTransport: true }); +} diff --git a/src/lib/adapters/openshell/sandbox-ssh.ts b/src/lib/adapters/openshell/sandbox-ssh.ts index 4c625bd936f..230a5504667 100644 --- a/src/lib/adapters/openshell/sandbox-ssh.ts +++ b/src/lib/adapters/openshell/sandbox-ssh.ts @@ -17,6 +17,7 @@ export type OpenShellSandboxSshResult = kind: "failed"; reason: "configuration" | "unavailable" | "timeout" | "cancelled" | "transport" | "capture"; signal?: NodeJS.Signals; + command?: Readonly<{ exitCode: number; stdout: string; stderr: string }>; }>; export interface OpenShellSandboxSshExecutor { diff --git a/src/lib/adapters/sandbox/command-transport.test.ts b/src/lib/adapters/sandbox/command-transport.test.ts index 3d1cc251a3c..f3057a34601 100644 --- a/src/lib/adapters/sandbox/command-transport.test.ts +++ b/src/lib/adapters/sandbox/command-transport.test.ts @@ -1,63 +1,31 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { spawnSync } from "node:child_process"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { OpenShellSandboxBufferedCommandExecutor } from "../openshell/sandbox-command"; import { namedOpenShellGateway } from "../openshell/sandbox-observer"; -const mocks = vi.hoisted(() => ({ - createTempSshConfig: vi.fn(), - resolveOpenshellSandboxSshHost: vi.fn(), - spawnSync: vi.fn(), -})); - -vi.mock("node:child_process", async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, spawnSync: mocks.spawnSync }; -}); - -vi.mock("../../sandbox/temp-ssh-config", () => ({ - createTempSshConfig: mocks.createTempSshConfig, -})); - -vi.mock("../openshell/sandbox-ssh-host", () => ({ - resolveOpenshellSandboxSshHost: mocks.resolveOpenshellSandboxSshHost, -})); - import { type CommandTransportDependencies, executeSandboxCommandTransport, executeSandboxExecCommandTransport, } from "./command-transport"; -function spawnResult( - stdout: string, - overrides: Partial> = {}, -): ReturnType { - return { - error: undefined, - output: [], - pid: 1234, - signal: null, - status: 0, - stderr: "", - stdout, - ...overrides, - } as ReturnType; -} - function createDependencies( overrides: Partial = {}, ): CommandTransportDependencies { return { buildSandboxExecMarkedCommand: vi.fn((command: string) => `marked:${command}`), buildSubprocessEnv: vi.fn(() => ({ PATH: "/usr/bin" })), - captureSandboxSshConfig: vi.fn(() => ({ - output: "Host openshell-alpha.default\n HostName 127.0.0.1\n", - status: 0, - })), + sshExecutor: { + run: vi.fn(async () => ({ + kind: "completed" as const, + exitCode: 0, + stdout: "ok\n", + stderr: "", + })), + }, executePrivilegedSandboxCommand: vi.fn(() => ({ status: 0, stdout: "fallback-output", @@ -72,7 +40,6 @@ function createDependencies( })), } as OpenShellSandboxBufferedCommandExecutor, isDirectSandboxFallbackUnavailableError: vi.fn(() => false), - openshellProbeTimeoutMs: 5000, ...overrides, }; } @@ -82,65 +49,46 @@ describe("sandbox command transport", () => { vi.resetAllMocks(); }); - it("resolves SSH state and cleans the temporary config after the command", () => { - const events: string[] = []; - const deps = createDependencies({ - buildSubprocessEnv: vi.fn(() => { - events.push("environment"); - return { PATH: "/usr/bin" }; - }), - captureSandboxSshConfig: vi.fn(() => { - events.push("config"); - return { - output: "Host openshell-alpha.default\n HostName 127.0.0.1\n", - status: 0, - }; + it("passes the recorded gateway, environment, and command timeout to typed SSH", async () => { + const deps = createDependencies(); + const runtimeEnv = { PATH: "/pinned/bin" }; + expect( + await executeSandboxCommandTransport(deps, "alpha", "openclaw doctor --fix", 300_000, { + gatewayName: "recorded-gateway", + runtimeEnv, }), + ).toEqual({ status: 0, stdout: "ok", stderr: "" }); + expect(deps.sshExecutor?.run).toHaveBeenCalledWith({ + sandboxName: "alpha", + target: namedOpenShellGateway("recorded-gateway"), + command: "openclaw doctor --fix", + environment: runtimeEnv, + timeoutMilliseconds: 300_000, }); - mocks.resolveOpenshellSandboxSshHost.mockImplementation(() => { - events.push("host"); - return "openshell-alpha.default"; - }); - mocks.createTempSshConfig.mockImplementation(() => { - events.push("temp"); - return { - cleanup: () => events.push("cleanup"), - dir: "/tmp/nemoclaw-ssh-test", - file: "/tmp/nemoclaw-ssh-test/ssh_config", - }; - }); - mocks.spawnSync.mockImplementation(() => { - events.push("spawn"); - return spawnResult("ok\n"); - }); - - expect(executeSandboxCommandTransport(deps, "alpha", "id")).toEqual({ - status: 0, - stderr: "", - stdout: "ok", - }); - expect(events).toEqual(["config", "host", "temp", "environment", "spawn", "cleanup"]); }); - it("uses the caller's bounded SSH command timeout", () => { - const deps = createDependencies(); - mocks.resolveOpenshellSandboxSshHost.mockReturnValue("openshell-alpha.default"); - mocks.createTempSshConfig.mockReturnValue({ - cleanup: vi.fn(), - dir: "/tmp/nemoclaw-ssh-test", - file: "/tmp/nemoclaw-ssh-test/ssh_config", - }); - mocks.spawnSync.mockReturnValue(spawnResult("ok\n")); - - expect(executeSandboxCommandTransport(deps, "alpha", "openclaw doctor --fix", 300_000)).toEqual( - { - status: 0, - stderr: "", - stdout: "ok", + it.each([ + { result: { kind: "failed", reason: "configuration" }, expected: null }, + { + result: { kind: "completed", exitCode: 9, stdout: " out\n", stderr: " err\n" }, + expected: { status: 9, stdout: "out", stderr: "err" }, + }, + { + result: { + kind: "failed", + reason: "transport", + command: { exitCode: 255, stdout: " out\n", stderr: " err\n" }, }, - ); - expect(mocks.spawnSync.mock.calls[0]?.[2]).toMatchObject({ timeout: 300_000 }); - }); + expected: { status: 255, stdout: "out", stderr: "err" }, + }, + ] as const)( + "preserves the SSH command outcome $result without a Docker fallback", + async ({ result, expected }) => { + const deps = createDependencies({ sshExecutor: { run: vi.fn(async () => result) } }); + expect(await executeSandboxCommandTransport(deps, "alpha", "id")).toEqual(expected); + expect(deps.executePrivilegedSandboxCommand).not.toHaveBeenCalled(); + }, + ); it("pins OpenShell exec to the requested gateway (#9834)", async () => { const deps = createDependencies(); diff --git a/src/lib/adapters/sandbox/command-transport.ts b/src/lib/adapters/sandbox/command-transport.ts index 95bdfa6f31e..08141a799a3 100644 --- a/src/lib/adapters/sandbox/command-transport.ts +++ b/src/lib/adapters/sandbox/command-transport.ts @@ -1,11 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; -import { createTempSshConfig } from "../../sandbox/temp-ssh-config"; import type { OpenShellSandboxBufferedCommandExecutor } from "../openshell/sandbox-command"; import { namedOpenShellGateway, selectedOpenShellGateway } from "../openshell/sandbox-observer"; -import { resolveOpenshellSandboxSshHost } from "../openshell/sandbox-ssh-host"; +import { createCliOpenShellSandboxSshCommandExecutor } from "../openshell/sandbox-ssh-cli"; +import type { OpenShellSandboxSshExecutor } from "../openshell/sandbox-ssh"; export type SandboxCommandResult = { status: number; @@ -34,16 +33,7 @@ export type SandboxSshCommandOptions = { export type CommandTransportDependencies = { buildSandboxExecMarkedCommand: (command: string) => string; buildSubprocessEnv: () => NodeJS.ProcessEnv; - captureSandboxSshConfig: ( - sandboxName: string, - options: { - env?: NodeJS.ProcessEnv; - gatewayName?: string; - ignoreError: boolean; - replaceEnv?: boolean; - timeout: number; - }, - ) => { output: string; status: number | null }; + sshExecutor?: OpenShellSandboxSshExecutor; executePrivilegedSandboxCommand: ( sandboxName: string, command: readonly string[], @@ -57,7 +47,6 @@ export type CommandTransportDependencies = { extractSandboxExecCommandStdout: (output: string) => string | null; commandExecutor: OpenShellSandboxBufferedCommandExecutor; isDirectSandboxFallbackUnavailableError: (error: unknown) => boolean; - openshellProbeTimeoutMs: number; }; export const DEFAULT_SANDBOX_EXEC_TIMEOUT_MS = 15000; @@ -71,59 +60,30 @@ function permitsUnknownOutcomeFallback(policy: LocalDockerFallbackPolicy): boole return policy === "read-only" || policy === "reconciled"; } -export function executeSandboxCommandTransport( +export async function executeSandboxCommandTransport( deps: CommandTransportDependencies, sandboxName: string, command: string, timeout = DEFAULT_SANDBOX_EXEC_TIMEOUT_MS, options: SandboxSshCommandOptions = {}, -): SandboxCommandResult | null { - const sshConfigResult = deps.captureSandboxSshConfig(sandboxName, { - ...(options.runtimeEnv ? { env: options.runtimeEnv, replaceEnv: true } : {}), - ...(options.gatewayName ? { gatewayName: options.gatewayName } : {}), - ignoreError: true, - timeout: deps.openshellProbeTimeoutMs, +): Promise { + const result = await (deps.sshExecutor ?? createCliOpenShellSandboxSshCommandExecutor()).run({ + sandboxName, + target: options.gatewayName + ? namedOpenShellGateway(options.gatewayName) + : selectedOpenShellGateway(), + command, + environment: options.runtimeEnv ?? deps.buildSubprocessEnv(), + timeoutMilliseconds: timeout, }); - if (sshConfigResult.status !== 0) return null; - if (!sshConfigResult.output.trim()) return null; - const sshHost = resolveOpenshellSandboxSshHost(sandboxName, sshConfigResult.output); - if (sshHost === null) return null; - - const tmpSshConfig = createTempSshConfig(sshConfigResult.output, "nemoclaw-ssh-"); - try { - const result = spawnSync( - "ssh", - [ - "-F", - tmpSshConfig.file, - "-o", - "StrictHostKeyChecking=no", - "-o", - "UserKnownHostsFile=/dev/null", - "-o", - "ConnectTimeout=5", - "-o", - "LogLevel=ERROR", - sshHost, - command, - ], - { - encoding: "utf-8", - env: options.runtimeEnv ?? deps.buildSubprocessEnv(), - stdio: ["ignore", "pipe", "pipe"], - timeout, - }, - ); - return { - status: result.status ?? 1, - stdout: (result.stdout || "").trim(), - stderr: (result.stderr || "").trim(), - }; - } catch { - return null; - } finally { - tmpSshConfig.cleanup(); - } + const commandResult = result.kind === "completed" ? result : result.command; + return commandResult + ? { + status: commandResult.exitCode, + stdout: commandResult.stdout.trim(), + stderr: commandResult.stderr.trim(), + } + : null; } function parseSandboxCommandResult( diff --git a/test/agents/deepagents/deepagents-mcp-runtime-capability.test.ts b/test/agents/deepagents/deepagents-mcp-runtime-capability.test.ts index 5e04b0f6539..21aba7623c3 100644 --- a/test/agents/deepagents/deepagents-mcp-runtime-capability.test.ts +++ b/test/agents/deepagents/deepagents-mcp-runtime-capability.test.ts @@ -31,8 +31,8 @@ beforeEach(() => { type ProbeResult = { status: number; stdout: string; stderr: string } | null; -function runDeepAgentsProbe(result: ProbeResult) { - mocks.executeSandboxCommand.mockReset().mockReturnValue(result); +async function runDeepAgentsProbe(result: ProbeResult) { + mocks.executeSandboxCommand.mockReset().mockResolvedValue(result); const runtimeSelection = { gatewayName: "nemoclaw-8091", workspace: "default", @@ -40,7 +40,7 @@ function runDeepAgentsProbe(result: ProbeResult) { let message = ""; try { - assertAgentMcpMutationRuntimeCapability( + await assertAgentMcpMutationRuntimeCapability( "deepagents-box", "deepagents-config", runtimeSelection, @@ -60,9 +60,9 @@ function runDeepAgentsProbe(result: ProbeResult) { } describe("Deep Agents managed MCP runtime capability", () => { - it("accepts only the exact managed launcher capability marker", () => { + it("accepts only the exact managed launcher capability marker", async () => { expect( - runDeepAgentsProbe({ + await runDeepAgentsProbe({ status: 0, stdout: "NEMOCLAW_DEEPAGENTS_MCP_CAPABILITY=2\n", stderr: "", @@ -89,8 +89,8 @@ describe("Deep Agents managed MCP runtime capability", () => { { status: 0, stdout: "deepagents-code 0.1.12\n", stderr: "" }, ])( "requires a rebuild before MCP side effects on stale or unreachable images [case %#]", - (result) => { - const probe = runDeepAgentsProbe(result); + async (result) => { + const probe = await runDeepAgentsProbe(result); expect(probe.calls).toHaveLength(1); expect(probe.message).toMatch(/does not contain managed MCP capability v2/i); expect(probe.message).toMatch(/rebuild the sandbox before changing authenticated MCP state/i); diff --git a/test/agents/hermes/hermes-mcp-startup-probe.test.ts b/test/agents/hermes/hermes-mcp-startup-probe.test.ts index 99fb30d8b6b..0db927db73f 100644 --- a/test/agents/hermes/hermes-mcp-startup-probe.test.ts +++ b/test/agents/hermes/hermes-mcp-startup-probe.test.ts @@ -31,7 +31,7 @@ import { assertAgentMcpMutationRuntimeCapability } from "../../../src/lib/action type ProbeResult = { status: number; stdout: string; stderr: string }; -function runHermesProbe(results: ProbeResult[]) { +async function runHermesProbe(results: ProbeResult[]) { const runtimeSelection = { gatewayName: "nemoclaw-8091", workspace: "default", @@ -69,7 +69,7 @@ function runHermesProbe(results: ProbeResult[]) { ); let message = ""; try { - assertAgentMcpMutationRuntimeCapability("hermes-box", "hermes-config", runtimeSelection); + await assertAgentMcpMutationRuntimeCapability("hermes-box", "hermes-config", runtimeSelection); } catch (error) { message = error instanceof Error ? error.message : String(error); } @@ -92,24 +92,24 @@ const ready: ProbeResult = { stderr: "", }; describe("Hermes managed MCP startup probe", () => { - it("retries only the exact transient gateway-starting result", () => { - expect(runHermesProbe([starting, ready])).toEqual({ + it("retries only the exact transient gateway-starting result", async () => { + expect(await runHermesProbe([starting, ready])).toEqual({ calls: 2, recoveryActions: [], message: "", }); }); - it("does not recover when the third exact startup probe is ready", () => { - expect(runHermesProbe([starting, starting, ready])).toEqual({ + it("does not recover when the third exact startup probe is ready", async () => { + expect(await runHermesProbe([starting, starting, ready])).toEqual({ calls: 3, recoveryActions: [], message: "", }); }); - it("fails closed on the selected target without host-local supervisor recovery", () => { - const result = runHermesProbe([starting, starting, starting, ready]); + it("fails closed on the selected target without host-local supervisor recovery", async () => { + const result = await runHermesProbe([starting, starting, starting, ready]); expect(result.calls).toBe(3); expect(result.recoveryActions).toEqual([]); @@ -117,8 +117,8 @@ describe("Hermes managed MCP startup probe", () => { expect(result.message).toContain("NemoClaw did not attempt host-local supervisor recovery"); }); - it("fails immediately on trust and topology errors", () => { - const result = runHermesProbe([ + it("fails immediately on trust and topology errors", async () => { + const result = await runHermesProbe([ { status: 1, stdout: "", @@ -133,8 +133,8 @@ describe("Hermes managed MCP startup probe", () => { expect(result.message).not.toContain("nemoclaw hermes-box recover"); }); - it("directs an unmanaged but trusted gateway to recovery before mutation", () => { - const result = runHermesProbe([ + it("directs an unmanaged but trusted gateway to recovery before mutation", async () => { + const result = await runHermesProbe([ { status: 1, stdout: "", @@ -149,8 +149,8 @@ describe("Hermes managed MCP startup probe", () => { expect(result.message).toContain("managed service lifecycle"); }); - it("fails clearly when the gateway never becomes ready", () => { - const result = runHermesProbe([starting, starting, starting]); + it("fails clearly when the gateway never becomes ready", async () => { + const result = await runHermesProbe([starting, starting, starting]); expect(result.calls).toBe(3); expect(result.recoveryActions).toEqual([]); diff --git a/test/channels/channels-add-bridge-lifecycle.test.ts b/test/channels/channels-add-bridge-lifecycle.test.ts index ed311fd6fd1..7f7c7a03663 100644 --- a/test/channels/channels-add-bridge-lifecycle.test.ts +++ b/test/channels/channels-add-bridge-lifecycle.test.ts @@ -365,7 +365,7 @@ beforeEach(() => { stdout: "", stderr: "", }); - vi.spyOn(processRecovery, "executeSandboxCommand").mockReturnValue(null); + vi.spyOn(processRecovery, "executeSandboxCommand").mockResolvedValue(null); }); afterEach(() => { diff --git a/test/channels/channels-add-preset.test.ts b/test/channels/channels-add-preset.test.ts index c7dae312b6c..4571b0d4580 100644 --- a/test/channels/channels-add-preset.test.ts +++ b/test/channels/channels-add-preset.test.ts @@ -300,7 +300,7 @@ beforeEach(() => { ? { status: 0, stdout: testLog, stderr: "" } : { status: 0, stdout: "", stderr: "" }; }); - vi.spyOn(processRecovery, "executeSandboxCommand").mockReturnValue(null); + vi.spyOn(processRecovery, "executeSandboxCommand").mockResolvedValue(null); buildPlanSpy = vi .spyOn(MessagingWorkflowPlanner.prototype, "buildPlan") diff --git a/test/process-recovery/process-recovery-custom-agent.test.ts b/test/process-recovery/process-recovery-custom-agent.test.ts index e2e9ca64538..345979a07e6 100644 --- a/test/process-recovery/process-recovery-custom-agent.test.ts +++ b/test/process-recovery/process-recovery-custom-agent.test.ts @@ -42,20 +42,6 @@ type SpawnMockResult = { stderr: string; }; -function openshellExecResult(rawArgs: unknown, recovered: boolean): SpawnMockResult { - const shellCommand = getSandboxExecShellCommand(rawArgs); - const status = shellCommand.includes("HTTP_CODE=$(curl") - ? recovered - ? "RUNNING" - : "STOPPED" - : ""; - return { - status: 0, - stdout: `__NEMOCLAW_SANDBOX_EXEC_STARTED__\n${status}\n`, - stderr: "", - }; -} - function sshExecResult( rawArgs: unknown, sshCommands: string[], @@ -89,7 +75,7 @@ function spawnResultForCommand( setRecovered: (value: boolean) => void, ): SpawnMockResult { return String(command).endsWith("openshell") - ? openshellExecResult(rawArgs, recovered) + ? { status: 0, stdout: "Host openshell-custom-box\n HostName 127.0.0.1\n", stderr: "" } : command === "ssh" ? sshExecResult(rawArgs, sshCommands, recovered, setRecovered) : { status: 1, stdout: "", stderr: "" }; @@ -115,24 +101,34 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { const agentRuntime = requireSource("../../src/lib/agent/runtime.ts"); const registry = requireSource("../../src/lib/state/registry.ts"); const forwardHealth = requireSource("../../src/lib/actions/sandbox/forward-health.ts"); - const childProcess = requireSource("node:child_process"); const sshCommands: string[] = []; - - vi.spyOn(openshellRuntime, "captureSandboxSshConfig").mockReturnValue({ - status: 0, - output: "Host openshell-custom-box\n HostName 127.0.0.1\n", + const commandCli = requireSource("../../src/lib/adapters/openshell/sandbox-command-cli.ts"); + vi.spyOn(commandCli, "createCliOpenShellSandboxCommandExecutor").mockReturnValue({ + runBuffered: async () => ({ + outcome: { kind: "completed", exitCode: 1 }, + stdout: "", + stderr: "sandbox exec unavailable", + }), } as never); - vi.spyOn(childProcess, "spawnSync").mockImplementation((command: unknown, rawArgs: unknown) => { - const sshCommand = getSandboxExecShellCommand(rawArgs); - sshCommands.push(...(command === "ssh" ? [sshCommand] : [])); - return ( - String(command).endsWith("openshell") - ? { status: 1, stdout: "", stderr: "sandbox exec unavailable" } - : command === "ssh" - ? { status: 0, stdout: "RUNNING\n", stderr: "" } - : { status: 1, stdout: "", stderr: "" } - ) as never; + const privileged = requireSource("../../src/lib/sandbox/privileged-exec.ts"); + vi.spyOn(privileged, "executePrivilegedSandboxCommand").mockReturnValue({ + status: 1, + stdout: "", + stderr: "local sandbox unavailable", }); + vi.spyOn(commandCli, "runCliOpenShellBufferedCommand").mockImplementation( + async (command: unknown, rawArgs: unknown) => { + const sshCommand = getSandboxExecShellCommand(rawArgs); + sshCommands.push(...(command === "ssh" ? [sshCommand] : [])); + return ( + String(command).endsWith("openshell") + ? { status: 0, stdout: "Host openshell-custom-box\n HostName 127.0.0.1\n", stderr: "" } + : command === "ssh" + ? { status: 0, stdout: "RUNNING\n", stderr: "" } + : { status: 1, stdout: "", stderr: "" } + ) as never; + }, + ); vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ name: "custom-agent", displayName: "Custom Agent", @@ -171,9 +167,23 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { const agentRuntime = requireSource("../../src/lib/agent/runtime.ts"); const registry = requireSource("../../src/lib/state/registry.ts"); const forwardHealth = requireSource("../../src/lib/actions/sandbox/forward-health.ts"); - const childProcess = requireSource("node:child_process"); const runningForward = "SANDBOX BIND PORT PID STATUS"; const sshCommands: string[] = []; + const commandCli = requireSource("../../src/lib/adapters/openshell/sandbox-command-cli.ts"); + vi.spyOn(commandCli, "createCliOpenShellSandboxCommandExecutor").mockReturnValue({ + runBuffered: async () => ({ + outcome: { kind: "completed", exitCode: 1 }, + stdout: "", + stderr: "sandbox exec unavailable", + }), + } as never); + const privileged = requireSource("../../src/lib/sandbox/privileged-exec.ts"); + vi.spyOn(privileged, "executePrivilegedSandboxCommand").mockReturnValue({ + status: 1, + stdout: "", + stderr: "local sandbox unavailable", + }); + const previousWaitSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_WAIT_SECONDS; const previousPollInterval = process.env.NEMOCLAW_GATEWAY_RECOVERY_POLL_INTERVAL_SECONDS; const previousSettleSeconds = process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS; @@ -185,12 +195,8 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { process.env.NEMOCLAW_GATEWAY_RECOVERY_SETTLE_SECONDS = "0"; try { - vi.spyOn(openshellRuntime, "captureSandboxSshConfig").mockReturnValue({ - status: 0, - output: "Host openshell-custom-box\n HostName 127.0.0.1\n", - } as never); - vi.spyOn(childProcess, "spawnSync").mockImplementation( - (command: unknown, rawArgs: unknown) => { + vi.spyOn(commandCli, "runCliOpenShellBufferedCommand").mockImplementation( + async (command: unknown, rawArgs: unknown) => { healthProbeCalls += Number( command === "ssh" && getSandboxExecShellCommand(rawArgs).includes("HTTP_CODE=$(curl"), ); @@ -252,8 +258,8 @@ describe("checkAndRecoverSandboxProcesses custom agent recovery", () => { it("fails closed when a persisted non-OpenClaw manifest cannot be loaded", async () => { const agentRuntime = requireSource("../../src/lib/agent/runtime.ts"); const registry = requireSource("../../src/lib/state/registry.ts"); - const childProcess = requireSource("node:child_process"); const commands: string[] = []; + const childProcess = requireSource("node:child_process"); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); const logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); diff --git a/test/process-recovery/process-recovery-primitives.test.ts b/test/process-recovery/process-recovery-primitives.test.ts index 34f0549dca1..e75de35e27c 100644 --- a/test/process-recovery/process-recovery-primitives.test.ts +++ b/test/process-recovery/process-recovery-primitives.test.ts @@ -669,33 +669,34 @@ describe("executeSandboxExecCommand", () => { }); describe("executeSandboxCommand", () => { - it("does not forward an MCP credential to the SSH child process", () => { - const openshellRuntime = requireSource("../../src/lib/adapters/openshell/runtime.ts"); - const childProcess = requireSource("node:child_process"); - vi.spyOn(openshellRuntime, "captureSandboxSshConfig").mockReturnValue({ - status: 0, - output: "Host openshell-alpha\n HostName 127.0.0.1\n", - } as never); - const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: "registered\n", - stderr: "", - } as never); + it("does not forward an MCP credential to the SSH child process", async () => { + const resolve = requireSource("../../src/lib/adapters/openshell/resolve.ts"); + vi.spyOn(resolve, "resolveOpenshell").mockReturnValue("openshell"); + const commandCli = requireSource("../../src/lib/adapters/openshell/sandbox-command-cli.ts"); + const run = vi + .spyOn(commandCli, "runCliOpenShellBufferedCommand") + .mockResolvedValueOnce({ status: 0, stdout: "", stderr: "" } as never) + .mockResolvedValueOnce({ + status: 0, + stdout: "Host openshell-alpha\n HostName 127.0.0.1\n", + stderr: "", + } as never) + .mockResolvedValueOnce({ status: 0, stdout: "registered\n", stderr: "" } as never); const priorSecret = process.env.TEST_MCP_RAW_TOKEN; const priorGateway = process.env.OPENSHELL_GATEWAY; process.env.TEST_MCP_RAW_TOKEN = "must-reach-only-provider-mutation"; process.env.OPENSHELL_GATEWAY = "nemoclaw-19080"; try { - expect(executeSandboxCommand("alpha", "mcporter config get fake --json")).toEqual({ + expect(await executeSandboxCommand("alpha", "mcporter config get fake --json")).toEqual({ status: 0, stdout: "registered", stderr: "", }); - const options = spawn.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv }; - expect(options.env?.TEST_MCP_RAW_TOKEN).toBeUndefined(); - expect(options.env?.OPENSHELL_GATEWAY).toBe("nemoclaw-19080"); - expect(options.env?.PATH).toBe(process.env.PATH); + const options = run.mock.calls[2]?.[2] as { environment?: NodeJS.ProcessEnv }; + expect(options.environment?.TEST_MCP_RAW_TOKEN).toBeUndefined(); + expect(options.environment?.OPENSHELL_GATEWAY).toBe("nemoclaw-19080"); + expect(options.environment?.PATH).toBe(process.env.PATH); } finally { priorSecret === undefined ? delete process.env.TEST_MCP_RAW_TOKEN