diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index e0972d4a66b..68403a1dc2c 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -171,7 +171,7 @@ const pRetry = require("p-retry"); const runner: typeof import("./runner") = require("./runner"); const { ROOT, SCRIPTS, redact, run, runCapture, runCaptureEx, runFile, validateName } = runner; const braveProviderProfile: typeof import("./onboard/brave-provider-profile") = require("./onboard/brave-provider-profile"); -const { runSandboxProviderPreDeleteCleanup } = +const { reconcileRegisteredExtraProviders, runSandboxProviderPreDeleteCleanup } = require("./onboard/sandbox-provider-cleanup") as typeof import("./onboard/sandbox-provider-cleanup"); const nameValidation: typeof import("./name-validation") = require("./name-validation"); const { getNameValidationGuidance } = nameValidation; @@ -2747,7 +2747,7 @@ async function createSandboxWithBaseImageResolution( messagingTokenDefs, reusableMessagingChannels, reusableMessagingProviders, - extraProviders: registry.listExtraProviders(), + extraProviders: reconcileRegisteredExtraProviders(GATEWAY_NAME, { runOpenshell }), hermesToolGateways, sandboxGpuConfig: effectiveSandboxGpuConfig, dockerDriverGateway, diff --git a/src/lib/onboard/extra-provider-reconciliation.test.ts b/src/lib/onboard/extra-provider-reconciliation.test.ts new file mode 100644 index 00000000000..397d0671757 --- /dev/null +++ b/src/lib/onboard/extra-provider-reconciliation.test.ts @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { reconcileRegisteredExtraProviders } from "./extra-provider-reconciliation"; + +type RunResult = { status: number | null; stderr?: string; stdout?: string | Buffer }; + +describe("reconcileRegisteredExtraProviders", () => { + it("keeps every user-owned extra whose exact name appears in one scoped gateway list", () => { + const runOpenshell = vi.fn( + (_args: string[]): RunResult => ({ + status: 0, + stdout: Buffer.from( + " tavily-search\nbrave-search\ncustom-provider\nmy-slack-bridge\nunrelated\n", + ), + }), + ); + const recorded = ["tavily-search", "brave-search", "custom-provider", "my-slack-bridge"]; + + const result = reconcileRegisteredExtraProviders("nemoclaw", { + runOpenshell, + listExtraProviders: () => recorded, + }); + + expect(result).toEqual(recorded); + expect(runOpenshell).toHaveBeenCalledOnce(); + expect(runOpenshell).toHaveBeenCalledWith(["provider", "list", "-g", "nemoclaw", "--names"], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + suppressOutput: true, + }); + }); + + it("omits a stale tavily record only from the current create plan (#6501)", () => { + const recorded = ["tavily-search", "custom-provider"]; + + const result = reconcileRegisteredExtraProviders("nemoclaw", { + runOpenshell: vi.fn(() => ({ status: 0, stdout: "custom-provider\n" })), + listExtraProviders: () => recorded, + }); + + expect(result).toEqual(["custom-provider"]); + expect(recorded).toEqual(["tavily-search", "custom-provider"]); + }); + + it("matches complete names instead of prefixes or provider-name heuristics", () => { + const result = reconcileRegisteredExtraProviders("nemoclaw", { + runOpenshell: vi.fn(() => ({ + status: 0, + stdout: "tavily-search-backup\ncustom-provider-v2\n", + })), + listExtraProviders: () => ["tavily-search", "custom-provider"], + }); + + expect(result).toEqual([]); + }); + + it("preserves every recorded extra when the gateway list exits nonzero", () => { + const recorded = ["tavily-search", "brave-search", "custom-provider"]; + + const result = reconcileRegisteredExtraProviders("nemoclaw", { + runOpenshell: vi.fn(() => ({ status: 1, stderr: "gateway unavailable" })), + listExtraProviders: () => recorded, + }); + + expect(result).toEqual(recorded); + }); + + it("preserves every recorded extra when the gateway list throws", () => { + const recorded = ["tavily-search", "my-slack-bridge"]; + + const result = reconcileRegisteredExtraProviders("nemoclaw", { + runOpenshell: vi.fn(() => { + throw new Error("spawn failed"); + }), + listExtraProviders: () => recorded, + }); + + expect(result).toEqual(recorded); + }); + + it("does not query the gateway when no extras are recorded", () => { + const runOpenshell = vi.fn(); + + expect( + reconcileRegisteredExtraProviders("nemoclaw", { + runOpenshell, + listExtraProviders: () => [], + }), + ).toEqual([]); + expect(runOpenshell).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/extra-provider-reconciliation.ts b/src/lib/onboard/extra-provider-reconciliation.ts new file mode 100644 index 00000000000..833bb375e37 --- /dev/null +++ b/src/lib/onboard/extra-provider-reconciliation.ts @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { assertNoOpenShellGatewayEndpointOverride } from "../openshell-gateway-endpoint-guard"; + +type ExtraProviderRunOpenshell = ( + args: string[], + opts?: Record, +) => { + status: number | null; + stdout?: string | Buffer | null; + stderr?: string | Buffer | null; +}; + +export type ReconcileExtraProvidersDeps = { + runOpenshell?: ExtraProviderRunOpenshell; + listExtraProviders?: () => string[]; +}; + +function defaultRunOpenshell( + args: string[], + opts?: Record, +): ReturnType { + const runtime = require("../adapters/openshell/runtime") as { + runOpenshell: ExtraProviderRunOpenshell; + }; + return runtime.runOpenshell(args, opts); +} + +function defaultListExtraProviders(): string[] { + const { listExtraProviders } = require("../state/registry") as { + listExtraProviders: () => string[]; + }; + return listExtraProviders(); +} + +function outputText(value: string | Buffer | null | undefined): string { + if (typeof value === "string") return value; + return value?.toString() ?? ""; +} + +/** + * Reconcile user-owned registry extras with one authoritative gateway list (#6501). + * + * A successful list is safe to filter against because provider names are matched + * exactly; there are no reserved search-provider names or diagnostic heuristics. + * A failed or thrown list preserves every recorded name so an unavailable gateway + * cannot silently change sandbox-create intent. Local registry state is never + * mutated: a provider omitted for this create remains available for later retry. + */ +export function reconcileRegisteredExtraProviders( + gatewayName: string, + deps: ReconcileExtraProvidersDeps = {}, +): string[] { + const recorded = (deps.listExtraProviders ?? defaultListExtraProviders)(); + if (recorded.length === 0) return recorded; + if (!gatewayName) throw new Error("OpenShell gateway name is required."); + assertNoOpenShellGatewayEndpointOverride(); + + const runOpenshell = deps.runOpenshell ?? defaultRunOpenshell; + let result: ReturnType; + try { + result = runOpenshell(["provider", "list", "-g", gatewayName, "--names"], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + suppressOutput: true, + }); + } catch { + return recorded; + } + if (result.status !== 0) return recorded; + + const gatewayNames = new Set( + outputText(result.stdout) + .split("\n") + .map((name) => name.trim()) + .filter(Boolean), + ); + return recorded.filter((name) => gatewayNames.has(name)); +} diff --git a/src/lib/onboard/sandbox-provider-cleanup.ts b/src/lib/onboard/sandbox-provider-cleanup.ts index 68f18b3ab4c..9725d8b4991 100644 --- a/src/lib/onboard/sandbox-provider-cleanup.ts +++ b/src/lib/onboard/sandbox-provider-cleanup.ts @@ -4,6 +4,11 @@ import { listMessagingProviderSuffixes } from "../messaging/channels"; import { NAME_MAX_LENGTH, NAME_VALID_PATTERN } from "../name-validation"; +export { + type ReconcileExtraProvidersDeps, + reconcileRegisteredExtraProviders, +} from "./extra-provider-reconciliation"; + export type SandboxProviderRunOpenshell = ( args: string[], opts?: Record, diff --git a/test/onboard-extra-provider-reconciliation.test.ts b/test/onboard-extra-provider-reconciliation.test.ts new file mode 100644 index 00000000000..b89da34f7c8 --- /dev/null +++ b/test/onboard-extra-provider-reconciliation.test.ts @@ -0,0 +1,162 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, it } from "vitest"; +import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; + +type CommandEntry = { command: string }; + +const repoRoot = path.join(import.meta.dirname, ".."); +const onboardScriptMocksPath = JSON.stringify( + path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), +); + +describe("onboard extra-provider reconciliation", () => { + it("attaches live user extras, skips stale names, and preserves registry state (#6501)", { + timeout: 90_000, + }, () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-extra-provider-reconcile-")); + try { + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "reconcile-provider-check.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "registry.ts"), + ); + const preflightPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const registry = require(${registryPath}); +const preflight = require(${preflightPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); +const _n = (command) => (Array.isArray(command) ? command.join(" ") : String(command)).replace(/'/g, ""); + +const commands = []; +registry.addExtraProvider("tavily-search"); +registry.addExtraProvider("brave-search"); +registry.addExtraProvider("custom-provider"); +registry.addExtraProvider("my-slack-bridge"); + +runner.run = (command, opts = {}) => { + const normalized = _n(command); + commands.push({ command: normalized, env: opts.env || null }); + if (normalized.includes("provider list -g nemoclaw --names")) { + return { status: 0, stdout: "brave-search\ncustom-provider\nmy-slack-bridge\n" }; + } + return { status: 0 }; +}; +runner.runCapture = (command) => { + const normalized = _n(command); + if (normalized.includes("sandbox get my-assistant")) return ""; + if (normalized.includes("sandbox list")) return "my-assistant Ready"; + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); + if (mockedCapture !== null) return mockedCapture; + if (normalized.includes("forward list")) { + return "my-assistant 127.0.0.1 18789 12345 running"; + } + return ""; +}; +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; +preflight.checkPortAvailable = async () => ({ ok: true }); +credentials.prompt = async () => ""; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ + command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), + env: args[2]?.env || null, + }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const sandboxName = await createSandbox(null, "gpt-5.4"); + console.log(JSON.stringify({ + sandboxName, + commands, + extraProviders: registry.listExtraProviders(), + })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + OPENSHELL_GATEWAY_ENDPOINT: undefined, + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + assert.equal(payload.sandboxName, "my-assistant"); + + const createCommand = payload.commands.find((entry: CommandEntry) => + entry.command.includes("sandbox create"), + ); + assert.ok(createCommand, "expected sandbox create command"); + assert.match(createCommand.command, /--provider brave-search/); + assert.match(createCommand.command, /--provider custom-provider/); + assert.match(createCommand.command, /--provider my-slack-bridge/); + assert.doesNotMatch(createCommand.command, /--provider tavily-search/); + + const providerLists = payload.commands.filter((entry: CommandEntry) => + entry.command.includes("provider list -g nemoclaw --names"), + ); + assert.equal(providerLists.length, 1, "expected one gateway-scoped provider list"); + assert.deepEqual(payload.extraProviders, [ + "brave-search", + "custom-provider", + "my-slack-bridge", + "tavily-search", + ]); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); +}); diff --git a/test/onboard.test.ts b/test/onboard.test.ts index b4dc139ae8b..2cfde28942e 100644 --- a/test/onboard.test.ts +++ b/test/onboard.test.ts @@ -1774,7 +1774,7 @@ const { EventEmitter } = require("node:events"); const commands = []; const registerCalls = []; const updateCalls = []; -const defaultCalls = []; registry.addExtraProvider("tavily-search"); +const defaultCalls = []; runner.run = (command, opts = {}) => { commands.push({ command: _n(command), env: opts.env || null }); return { status: 0 }; @@ -1877,7 +1877,7 @@ const { createSandbox } = require(${onboardPath}); entry.command.includes("sandbox create"), ); assert.ok(createCommand, "expected sandbox create command"); - assert.match(createCommand.command, /(?=.*nemoclaw-start)(?=.*--provider tavily-search)/); + assert.match(createCommand.command, /nemoclaw-start/); assert.doesNotMatch(createCommand.command, /--upload/); assert.doesNotMatch(createCommand.command, /OPENCLAW_CONFIG_PATH/); assert.doesNotMatch(createCommand.command, /NVIDIA_INFERENCE_API_KEY=/);