diff --git a/src/commands/credentials.test.ts b/src/commands/credentials.test.ts index fd63551e406..320a5542b88 100644 --- a/src/commands/credentials.test.ts +++ b/src/commands/credentials.test.ts @@ -28,6 +28,7 @@ vi.mock("../lib/actions/global", () => ({ listManagedMcpCredentialReservations: mocks.listManagedMcpCredentialReservations, })); vi.mock("../lib/adapters/openshell/provider-command", () => ({ + OPENSHELL_OPERATION_TIMEOUT_MS: 30_000, runOpenshellProviderCommand: mocks.runOpenshellProviderCommand, })); vi.mock("../lib/onboard/gateway-teardown-authority", () => ({ @@ -219,4 +220,155 @@ describe("credentials oclif adapter source coverage", () => { mocks.runOpenshellProviderCommand.mock.invocationCallOrder[0], ); }); + + it("rejects an incompatible OpenAI profile before provider creation", async () => { + vi.stubEnv("OPENAI_API_KEY", "host-only-secret"); + mocks.runOpenshellProviderCommand.mockReturnValueOnce({ + status: 0, + stdout: JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [{ name: "untrusted", url: "https://example.invalid" }], + binaries: [], + inference_capable: true, + }), + stderr: "", + }); + + const result = await runCredentialsAddAction({ + provider: "openai-prod", + type: "openai", + credentials: ["OPENAI_API_KEY"], + configPairs: [], + fromExisting: false, + }); + + expect(result.exitCode).toBe(1); + expect(result.failureLines.join("\n")).toContain( + "does not match NemoClaw's endpointless inference contract", + ); + expect(result.failureLines.join("\n")).toContain("then retry this command"); + expect(result.failureLines.join("\n")).not.toContain("onboarding"); + expect(result.failureLines.join("\n")).not.toContain("host-only-secret"); + expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledTimes(1); + expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledWith( + ["provider", "profile", "export", "openai", "--output", "json"], + { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + ); + expect(mocks.recordExtraProvider).not.toHaveBeenCalled(); + }); + + it("stops before provider creation when OpenAI profile inspection times out", async () => { + vi.stubEnv("OPENAI_API_KEY", "host-only-secret"); + mocks.runOpenshellProviderCommand.mockReturnValueOnce({ + status: null, + stdout: "", + stderr: "operation timed out", + }); + + const result = await runCredentialsAddAction({ + provider: "openai-prod", + type: "openai", + credentials: ["OPENAI_API_KEY"], + configPairs: [], + fromExisting: false, + }); + + expect(result.exitCode).toBe(1); + expect(result.failureLines.join("\n")).toContain("could not be read for validation"); + expect(result.failureLines.join("\n")).toContain("then retry this command"); + expect(result.failureLines.join("\n")).not.toContain("onboarding"); + expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledOnce(); + expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledWith( + ["provider", "profile", "export", "openai", "--output", "json"], + { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + ); + expect(mocks.recordExtraProvider).not.toHaveBeenCalled(); + }); + + it("imports a missing OpenAI profile before provider creation", async () => { + vi.stubEnv("OPENAI_API_KEY", "host-only-secret"); + mocks.runOpenshellProviderCommand + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }) + .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); + + const result = await runCredentialsAddAction({ + provider: "openai-prod", + type: "openai", + credentials: ["OPENAI_API_KEY"], + configPairs: [], + fromExisting: false, + }); + + expect(result.exitCode).toBe(0); + expect(mocks.runOpenshellProviderCommand.mock.calls.map(([args]) => args)).toEqual([ + ["provider", "profile", "export", "openai", "--output", "json"], + [ + "provider", + "profile", + "import", + "--file", + expect.stringMatching(/provider-profiles\/openai\.yaml$/u), + ], + [ + "provider", + "create", + "--name", + "openai-prod", + "--type", + "openai", + "--credential", + "OPENAI_API_KEY", + ], + ]); + expect( + mocks.runOpenshellProviderCommand.mock.calls.slice(0, 2).map(([, options]) => options), + ).toEqual([ + { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + ]); + }); + + it("reports caller-neutral guidance when OpenAI profile import fails", async () => { + vi.stubEnv("OPENAI_API_KEY", "host-only-secret"); + mocks.runOpenshellProviderCommand + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "import failed" }); + + const result = await runCredentialsAddAction({ + provider: "openai-prod", + type: "openai", + credentials: ["OPENAI_API_KEY"], + configPairs: [], + fromExisting: false, + }); + + expect(result.exitCode).toBe(1); + expect(result.failureLines.join("\n")).toContain("could not import the checked-in"); + expect(result.failureLines.join("\n")).toContain("then retry this command"); + expect(result.failureLines.join("\n")).not.toContain("onboarding"); + expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledTimes(2); + expect(mocks.recordExtraProvider).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index 927ceabf31f..5c2d93acbbf 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -4,6 +4,10 @@ import fs from "node:fs"; import path from "node:path"; import { runOpenshellProviderCommand } from "../adapters/openshell/provider-command"; +import { + checkOpenAiInferenceProviderProfile, + OPENAI_GATEWAY_PROVIDER_TYPE, +} from "../adapters/openshell/provider-profile"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../adapters/openshell/timeouts"; import { CLI_NAME } from "../cli/branding"; import { @@ -142,6 +146,20 @@ function ensureBundledProviderProfile(type: string): CredentialsAddResult | null ]); } +function ensureCredentialProviderProfile(type: string): CredentialsAddResult | null { + if (type.toLowerCase() !== OPENAI_GATEWAY_PROVIDER_TYPE) { + return ensureBundledProviderProfile(type); + } + const profile = checkOpenAiInferenceProviderProfile({ + runOpenshell: (args, options) => + runOpenshellProviderCommand(args, { + ...options, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }), + }); + return profile.ok ? null : fail(profile.messages); +} + export async function runCredentialsAddAction( input: CredentialsAddInput, ): Promise { @@ -251,7 +269,7 @@ export async function runCredentialsAddAction( return fail(recoveryFailureLines); } - const providerProfileFailure = ensureBundledProviderProfile(type); + const providerProfileFailure = ensureCredentialProviderProfile(type); if (providerProfileFailure) return providerProfileFailure; let importedCredentialKeys: string[] | null = null; diff --git a/src/lib/actions/inference-set-compatible-provider.test.ts b/src/lib/actions/inference-set-compatible-provider.test.ts index 8749f06bc94..d6bc4befe96 100644 --- a/src/lib/actions/inference-set-compatible-provider.test.ts +++ b/src/lib/actions/inference-set-compatible-provider.test.ts @@ -15,6 +15,20 @@ type ProbeSandboxRoute = NonNullable< Parameters[0]["probeSandboxRoute"] >; +const OPENAI_PROFILE_OUTPUT = JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); +const OPENAI_PROFILE_RESULT = { + status: 0, + output: OPENAI_PROFILE_OUTPUT, + stdout: OPENAI_PROFILE_OUTPUT, + stderr: "", +}; + async function runRejectedCompatibleSwitchScenario(options: { targetFamily: "openai" | "anthropic"; probeSandboxRoute: ProbeSandboxRoute; @@ -295,6 +309,8 @@ describe("runInferenceSet compatible providers", () => { let providerCreated = false; const captureOpenshell = vi.fn((args: string[]) => { switch (`${args[0]}:${args[1]}`) { + case "provider:profile": + return OPENAI_PROFILE_RESULT; case "inference:set": return providerCreated ? { status: 0, output: "", stdout: "", stderr: "" } @@ -407,6 +423,8 @@ describe("runInferenceSet compatible providers", () => { let providerPresent = false; const captureOpenshell = vi.fn((args: string[]) => { switch (`${args[0]}:${args[1]}`) { + case "provider:profile": + return OPENAI_PROFILE_RESULT; case "provider:get": { const missingOutput = "Error: code: 'Some requested entity was not found', message: \"provider not found\""; @@ -599,6 +617,8 @@ describe("runInferenceSet compatible providers", () => { let providerVersion = 1; const captureOpenshell = vi.fn((args: string[]) => { switch (`${args[0]}:${args[1]}`) { + case "provider:profile": + return OPENAI_PROFILE_RESULT; case "provider:get": { const output = [ "Name: compatible-endpoint", diff --git a/src/lib/actions/inference-set-https-pin-runtime.test.ts b/src/lib/actions/inference-set-https-pin-runtime.test.ts index 96adaf3f55e..d1d536c4e77 100644 --- a/src/lib/actions/inference-set-https-pin-runtime.test.ts +++ b/src/lib/actions/inference-set-https-pin-runtime.test.ts @@ -15,6 +15,20 @@ const OLD_ROUTE_ID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa const ADAPTER_BASE_URL = `http://host.openshell.internal:11438/route/${NEW_ROUTE_ID}`; const OLD_ADAPTER_BASE_URL = `http://host.openshell.internal:11438/route/${OLD_ROUTE_ID}`; const PROVIDER_ID = "11111111-2222-4333-8444-555555555555"; +const OPENAI_PROFILE_OUTPUT = JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); +const ANTHROPIC_PROFILE_OUTPUT = JSON.stringify({ + id: "anthropic", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); function mockAdapter() { return vi.fn(async (_options: EnsureHttpsPinRuntimeAdapterOptions) => ({ @@ -43,6 +57,16 @@ function providerCapture(options: { ].join("\n"); return vi.fn((args: string[]) => { switch (`${args[0]}:${args[1]}`) { + case "provider:profile": { + const profile = + options.providerType === "anthropic" ? ANTHROPIC_PROFILE_OUTPUT : OPENAI_PROFILE_OUTPUT; + return { + status: 0, + output: profile, + stdout: profile, + stderr: "", + }; + } case "provider:get": { const text = output(); return { status: 0, stdout: text, stderr: "", output: text }; diff --git a/src/lib/actions/inference-set-provider.test.ts b/src/lib/actions/inference-set-provider.test.ts index 112be50725e..a9f653ef7e2 100644 --- a/src/lib/actions/inference-set-provider.test.ts +++ b/src/lib/actions/inference-set-provider.test.ts @@ -2,11 +2,27 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, describe, expect, it, vi } from "vitest"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../adapters/openshell/provider-command"; import type { InferenceSetDeps } from "./inference-set"; import { __test, prepareInferenceSetProviderBinding } from "./inference-set-provider"; import type { HttpsPinProviderBinding } from "./inference-set-route-containment"; const PROVIDER_ID = "11111111-2222-4333-8444-555555555555"; +const OPENAI_ENDPOINTLESS_PROFILE = JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); + +const OPENAI_ENDPOINTLESS_PROFILE_RESULT = { + status: 0, + stdout: OPENAI_ENDPOINTLESS_PROFILE, + stderr: "", + output: OPENAI_ENDPOINTLESS_PROFILE, +}; + function binding(overrides: Partial = {}): HttpsPinProviderBinding { return { baseUrl: "http://host.openshell.internal:11438/route/route-a/v1", @@ -42,7 +58,7 @@ function captureSequence( return vi.fn( (args: string[]) => (args[0] === "provider" && args[1] === "profile" - ? { status: 0, stdout: "", stderr: "" } + ? OPENAI_ENDPOINTLESS_PROFILE_RESULT : results.shift()) ?? (() => { throw new Error("unexpected OpenShell call"); @@ -76,10 +92,17 @@ describe("inference set provider binding", () => { "profile", "-g", "nemoclaw", - "import", - "--file", - expect.stringMatching(/openai\.yaml$/u), + "export", + "openai", + "--output", + "json", ]); + expect(capture.mock.calls[1][1]).toEqual({ + ignoreError: true, + includeStreams: true, + maxBuffer: 64 * 1024, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); expect(capture.mock.calls[2]).toEqual([ [ "provider", @@ -121,14 +144,17 @@ describe("inference set provider binding", () => { it("stops before an OpenAI provider mutation when profile registration fails (#9895)", () => { const before = providerOutput({ resourceVersion: 4 }); - const responses = new Map([ - ["get", { status: 0, stdout: before, stderr: "", output: before }], - ["profile", { status: 1, stdout: "", stderr: "sensitive profile failure" }], - ]); - const capture = vi.fn((args: string[]) => - responses.get(args[1]) ?? (() => { - throw new Error("provider mutation must not run"); - })(), + const responses = [ + { status: 0, stdout: before, stderr: "", output: before }, + { status: 1, stdout: "", stderr: "provider profile not found" }, + { status: 1, stdout: "", stderr: "sensitive profile failure" }, + ]; + const capture = vi.fn( + () => + responses.shift() ?? + (() => { + throw new Error("provider mutation must not run"); + })(), ) as InferenceSetDeps["captureOpenshell"] & ReturnType; const mutation = prepareInferenceSetProviderBinding({ @@ -141,7 +167,7 @@ describe("inference set provider binding", () => { expect(() => mutation.commit()).toThrow( "could not import the checked-in 'openai' inference provider profile", ); - expect(capture.mock.calls.map(([args]) => args[1])).toEqual(["get", "profile"]); + expect(capture.mock.calls.map(([args]) => args[1])).toEqual(["get", "profile", "profile"]); }); it("does not register the OpenAI profile before an Anthropic provider mutation", () => { @@ -282,7 +308,7 @@ describe("inference set provider binding", () => { return (args, opts) => { switch (args[1]) { case "profile": - return { status: 0, stdout: "", stderr: "", output: "" }; + return OPENAI_ENDPOINTLESS_PROFILE_RESULT; case "get": { const output = providerOutput({ id, resourceVersion: version }); return { status: 0, stdout: output, stderr: "", output }; diff --git a/src/lib/actions/inference-set-provider.ts b/src/lib/actions/inference-set-provider.ts index 6c77e82e914..440dadb543b 100644 --- a/src/lib/actions/inference-set-provider.ts +++ b/src/lib/actions/inference-set-provider.ts @@ -2,15 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import { type CaptureOpenshellResult, stripAnsi } from "../adapters/openshell/client"; +import { + checkOpenAiInferenceProviderProfile, + OPENAI_GATEWAY_PROVIDER_TYPE, +} from "../adapters/openshell/provider-profile"; import { retryUntilAsync } from "../core/retry"; import { matchesGatewayProviderBinding, parseGatewayProviderMetadata, } from "../onboard/gateway-provider-metadata"; -import { - checkOpenAiInferenceProviderProfile, - OPENAI_GATEWAY_PROVIDER_TYPE, -} from "../onboard/inference-providers/provider-profile"; import { assertHermesPortableCommandUnavailable } from "../onboard/experimental/portable-agent-lifecycle"; import { CURRENT_RUNTIME_PROVIDER_BUNDLES, @@ -51,9 +51,7 @@ export function sleepInferenceSetRouteConvergence(milliseconds: number): Promise export function probeInferenceSetSandboxRoute( input: SandboxInferenceInvocationInput, ): SandboxInferenceInvocationResult { - const probe: typeof import("./sandbox/inference-invocation-probe") = require( - "./sandbox/inference-invocation-probe", - ); + const probe: typeof import("./sandbox/inference-invocation-probe") = require("./sandbox/inference-invocation-probe"); return probe.probeSandboxInferenceInvocation( input, {}, @@ -91,9 +89,7 @@ export async function probeInferenceSetSandboxRouteUntilConverged( const inferenceApiChanged = options.previousInferenceApi !== options.targetInferenceApi; return await retryUntilAsync(() => deps.probe(options.input), { accept: (result) => - result.ok || - !inferenceApiChanged || - (result.httpStatus !== 400 && result.httpStatus !== 404), + result.ok || !inferenceApiChanged || (result.httpStatus !== 400 && result.httpStatus !== 404), retryDelaysMs: ROUTE_FAMILY_CONVERGENCE_RETRY_DELAYS_MS, onRetry: deps.onRetry, sleep: deps.sleep, @@ -118,6 +114,7 @@ type CaptureProviderCommand = ( ignoreError: true; includeStreams: true; maxBuffer: number; + timeout?: number; env?: NodeJS.ProcessEnv; }, ) => CaptureOpenshellResult; @@ -290,7 +287,7 @@ export function prepareInferenceSetProviderBinding(options: { const apply = (): void => { if (surface.type === OPENAI_GATEWAY_PROVIDER_TYPE) { const profile = checkOpenAiInferenceProviderProfile({ - runOpenshell: (args) => + runOpenshell: (args, runnerOptions) => captureOpenshell( args[0] === "provider" && args[1] === "profile" ? [args[0], args[1], "-g", gatewayName, ...args.slice(2)] @@ -299,6 +296,7 @@ export function prepareInferenceSetProviderBinding(options: { ignoreError: true, includeStreams: true, maxBuffer: OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER, + timeout: runnerOptions?.timeout, }, ), }); diff --git a/src/lib/actions/inference-set-reasoning-effort.test.ts b/src/lib/actions/inference-set-reasoning-effort.test.ts index d0c06617820..c1e4245f272 100644 --- a/src/lib/actions/inference-set-reasoning-effort.test.ts +++ b/src/lib/actions/inference-set-reasoning-effort.test.ts @@ -5,7 +5,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { REASONING_EFFORT_ENV } from "../onboard/reasoning-mode"; import type { ConfigObject } from "../security/credential-filter"; import { patchOpenClawInferenceConfig, runInferenceSet } from "./inference-set"; -import { baseSession, createDeps } from "./inference-set.test-support"; +import { + baseSession, + createDeps, + OPENAI_ENDPOINTLESS_PROFILE, +} from "./inference-set.test-support"; function compatibleEndpointConfig(modelOverrides: ConfigObject = {}): ConfigObject { return { @@ -331,6 +335,13 @@ describe("inference set reasoning effort (#7659)", () => { case "provider:update": providerVersion += 1; return { status: 0, output: "", stdout: "", stderr: "" }; + case "provider:profile": + return { + status: 0, + output: OPENAI_ENDPOINTLESS_PROFILE, + stdout: OPENAI_ENDPOINTLESS_PROFILE, + stderr: "", + }; default: return { status: 0, output: "", stdout: "", stderr: "" }; } diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index ed132e5d1e8..98f575c18de 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -30,6 +30,33 @@ export const HERMES_TARGET: AgentConfigTarget = { stateLockPlanInImage: true, }; +export const OPENAI_ENDPOINTLESS_PROFILE = JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); + +export const ANTHROPIC_ENDPOINTLESS_PROFILE = JSON.stringify({ + id: "anthropic", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); + +function defaultCaptureOpenshell( + args: string[], + status: number, +): { status: number; output: string; stdout: string; stderr: string } { + const output = + args[0] === "provider" && args[1] === "profile" && args.includes("export") + ? OPENAI_ENDPOINTLESS_PROFILE + : ""; + return { status, output, stdout: output, stderr: "" }; +} + export function baseSession(overrides: Partial = {}): Session { return { version: 1, @@ -84,6 +111,18 @@ export function createCompatibleProviderCapture(options: { let providerVersion = providerPresent ? 1 : 0; return vi.fn((args: string[]) => { switch (`${args[0]}:${args[1]}`) { + case "provider:profile": { + const profile = + options.type === "anthropic" + ? ANTHROPIC_ENDPOINTLESS_PROFILE + : OPENAI_ENDPOINTLESS_PROFILE; + return { + status: 0, + output: profile, + stdout: profile, + stderr: "", + }; + } case "provider:get": { if (!providerPresent) { const output = @@ -179,12 +218,7 @@ export function createDeps(options: { const calls = { captureOpenshell: vi.fn( options.captureOpenshell ?? - (() => ({ - status: options.openshellStatus ?? 0, - output: "", - stdout: "", - stderr: "", - })), + ((args: string[]) => defaultCaptureOpenshell(args, options.openshellStatus ?? 0)), ), writeSandboxConfig: vi.fn(), recomputeSandboxConfigHash: vi.fn(), 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 d4d35ccc0a5..4b788a2c870 100644 --- a/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-adapter-registration.test.ts @@ -18,6 +18,7 @@ vi.mock("./process-recovery", () => ({ })); vi.mock("../../adapters/openshell/provider-command", () => ({ + OPENSHELL_OPERATION_TIMEOUT_MS: 30_000, runOpenshellProviderCommand: mocks.runOpenshellProviderCommand, })); diff --git a/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.test.ts b/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.test.ts index be5528c436b..496feda1393 100644 --- a/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.test.ts @@ -16,6 +16,7 @@ vi.mock("../../state/registry", () => ({ })); vi.mock("../../adapters/openshell/provider-command", () => ({ + OPENSHELL_OPERATION_TIMEOUT_MS: 30_000, runOpenshellProviderCommand: mocks.runOpenshellProviderCommand, })); diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts b/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts index 6663c8b8ee9..575223e5943 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-mutation.ts @@ -16,11 +16,12 @@ */ import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-command"; -import { REPOSITORY_ROOT } from "../../core/repository-root"; import { + checkOpenAiInferenceProviderProfile, endpointlessProviderProfilePath, ensureEndpointlessProviderProfile, -} from "../../messaging/provider-profile"; +} from "../../adapters/openshell/provider-profile"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; import type { McpBridgeEntry } from "../../state/registry"; import { McpBridgeError, type ParsedEnvReference } from "./mcp-bridge-contracts"; import { commandOutput, type OpenShellCommandResult } from "./mcp-bridge-output"; @@ -47,8 +48,6 @@ export { providerDetachChangedState, } from "./mcp-bridge-provider-attachments"; -const OPENAI_GATEWAY_PROVIDER_TYPE = "openai"; - /** * OpenShell 0.0.106 still accepts the legacy `openai` provider type without a * declarative profile. Its static-credential resolver then emits the provider @@ -69,27 +68,12 @@ const OPENAI_GATEWAY_PROVIDER_TYPE = "openai"; * release classifies the `openai` inference credential as gateway-only itself. */ function ensureOpenAiGatewayProviderProfile(): void { - const result = ensureEndpointlessProviderProfile({ - profileId: OPENAI_GATEWAY_PROVIDER_TYPE, - inferenceCapable: true, - profilePath: endpointlessProviderProfilePath(REPOSITORY_ROOT, OPENAI_GATEWAY_PROVIDER_TYPE), + const result = checkOpenAiInferenceProviderProfile({ runOpenshell: (args, options) => runOpenshellProviderCommand(args, options) as OpenShellCommandResult, }); if (result.ok) return; - if (result.reason === "import-failed") { - throw new McpBridgeError( - result.diagnostic || "Could not import the OpenShell OpenAI gateway provider profile.", - ); - } - if (result.reason === "export-failed") { - throw new McpBridgeError( - `OpenShell provider profile '${OPENAI_GATEWAY_PROVIDER_TYPE}' already exists but could not be exported for validation. Refusing to classify gateway inference credentials with it.`, - ); - } - throw new McpBridgeError( - `OpenShell provider profile '${OPENAI_GATEWAY_PROVIDER_TYPE}' already exists but does not match NemoClaw's gateway-only endpointless credential contract. Refusing to classify gateway inference credentials with it.`, - ); + throw new McpBridgeError(result.messages.join("\n")); } /** Ensure the endpointless profile required by OpenShell static credential binding. */ @@ -105,8 +89,12 @@ export function ensureMcpBridgeProviderProfile(): void { if (result.ok) return; if (result.reason === "import-failed") { throw new McpBridgeError( - result.diagnostic || - `Could not import OpenShell provider profile '${MCP_BRIDGE_PROVIDER_TYPE}'.`, + `Could not import OpenShell provider profile '${MCP_BRIDGE_PROVIDER_TYPE}'.`, + ); + } + if (result.reason === "export-failed") { + throw new McpBridgeError( + `OpenShell provider profile '${MCP_BRIDGE_PROVIDER_TYPE}' could not be exported for validation. Refusing to attach MCP credentials to it.`, ); } throw new McpBridgeError( diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-profile.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider-profile.test.ts index 9b598e0c324..3ba6261ee85 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-profile.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-profile.test.ts @@ -26,11 +26,16 @@ function exportedEndpointlessProfile(id: string, inferenceCapable: boolean): str describe("OpenShell MCP provider profile", () => { it("imports the endpointless profile before managed provider use", () => { - const runOpenshell = vi.fn(() => ({ status: 0, stdout: "Imported", stderr: "" })); + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 0, stdout: "Imported", stderr: "" }) + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 0, stdout: "Imported", stderr: "" }); setProviderCommandRuntimeHooksForTest({ runOpenshell: runOpenshell as never }); expect(() => ensureMcpBridgeProviderProfile()).not.toThrow(); - expect(runOpenshell).toHaveBeenCalledTimes(2); + expect(runOpenshell).toHaveBeenCalledTimes(4); expect(runOpenshell).toHaveBeenCalledWith( ["provider", "profile", "import", "--file", expect.stringMatching(/openai\.yaml$/)], expect.any(Object), @@ -44,13 +49,11 @@ describe("OpenShell MCP provider profile", () => { it("accepts existing profiles only after proving both exact endpointless boundaries", () => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "already exists" }) .mockReturnValueOnce({ status: 0, stdout: exportedEndpointlessProfile("openai", true), stderr: "", }) - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "already exists" }) .mockReturnValueOnce({ status: 0, stdout: exportedEndpointlessProfile(MCP_BRIDGE_PROVIDER_TYPE, false), @@ -72,13 +75,11 @@ describe("OpenShell MCP provider profile", () => { it("rejects an existing profile that can supply its own endpoint authority", () => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "already exists" }) .mockReturnValueOnce({ status: 0, stdout: exportedEndpointlessProfile("openai", true), stderr: "", }) - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "already exists" }) .mockReturnValueOnce({ status: 0, stdout: JSON.stringify({ @@ -98,11 +99,52 @@ describe("OpenShell MCP provider profile", () => { }); it("fails closed when the gateway-only OpenAI profile cannot be registered", () => { - const runOpenshell = vi.fn(() => ({ status: 1, stdout: "", stderr: "import rejected" })); + const secret = "openai-import-secret-must-not-leak"; + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 1, stdout: "", stderr: `import rejected: ${secret}` }); setProviderCommandRuntimeHooksForTest({ runOpenshell: runOpenshell as never }); - expect(() => ensureMcpBridgeProviderProfile()).toThrow("import rejected"); - expect(runOpenshell).toHaveBeenCalledOnce(); + let message = ""; + try { + ensureMcpBridgeProviderProfile(); + } catch (error) { + message = error instanceof Error ? error.message : String(error); + } + expect(message).toContain( + "OpenShell could not import the checked-in 'openai' inference provider profile.", + ); + expect(message).toContain("retry this command"); + expect(message).not.toContain(secret); + expect(message).not.toContain("import rejected"); + expect(runOpenshell).toHaveBeenCalledTimes(2); + }); + + it("suppresses MCP profile import output at the bridge error boundary", () => { + const secret = "mcp-import-secret-must-not-leak"; + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ + status: 0, + stdout: exportedEndpointlessProfile("openai", true), + stderr: "", + }) + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 1, stdout: "", stderr: `import rejected: ${secret}` }); + setProviderCommandRuntimeHooksForTest({ runOpenshell: runOpenshell as never }); + + let message = ""; + try { + ensureMcpBridgeProviderProfile(); + } catch (error) { + message = error instanceof Error ? error.message : String(error); + } + expect(message).toBe( + `Could not import OpenShell provider profile '${MCP_BRIDGE_PROVIDER_TYPE}'.`, + ); + expect(message).not.toContain(secret); + expect(message).not.toContain("import rejected"); }); it.each([ @@ -128,31 +170,44 @@ describe("OpenShell MCP provider profile", () => { ], ["malformed export output", "not-json"], ])("rejects an existing OpenAI profile with %s before MCP setup", (_case, stdout) => { - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "already exists" }) - .mockReturnValueOnce({ status: 0, stdout, stderr: "" }); + const runOpenshell = vi.fn().mockReturnValueOnce({ status: 0, stdout, stderr: "" }); setProviderCommandRuntimeHooksForTest({ runOpenshell: runOpenshell as never }); expect(() => ensureMcpBridgeProviderProfile()).toThrow( - /does not match NemoClaw's gateway-only endpointless credential contract/, + /does not match NemoClaw's endpointless inference contract/, ); - expect(runOpenshell).toHaveBeenCalledTimes(2); + expect(runOpenshell).toHaveBeenCalledOnce(); expect(runOpenshell).toHaveBeenLastCalledWith( ["provider", "profile", "export", "openai", "--output", "json"], expect.any(Object), ); }); - it("fails closed with a distinct diagnostic when an existing OpenAI profile cannot be exported", () => { + it("fails closed when the OpenAI profile cannot be exported", () => { + const runOpenshell = vi.fn().mockReturnValueOnce({ + status: 1, + stdout: "", + stderr: "export rejected", + }); + setProviderCommandRuntimeHooksForTest({ runOpenshell: runOpenshell as never }); + + expect(() => ensureMcpBridgeProviderProfile()).toThrow(/could not be read for validation/); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it("fails closed when the MCP profile cannot be exported", () => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "already exists" }) + .mockReturnValueOnce({ + status: 0, + stdout: exportedEndpointlessProfile("openai", true), + stderr: "", + }) .mockReturnValueOnce({ status: 1, stdout: "", stderr: "export rejected" }); setProviderCommandRuntimeHooksForTest({ runOpenshell: runOpenshell as never }); expect(() => ensureMcpBridgeProviderProfile()).toThrow( - /already exists but could not be exported for validation/, + /nemoclaw-mcp-v1.*could not be exported for validation/u, ); expect(runOpenshell).toHaveBeenCalledTimes(2); }); diff --git a/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts b/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts index 7b2cd338903..df17e76ddf3 100644 --- a/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts +++ b/src/lib/actions/sandbox/snapshot-hermes-managed-clone-broker.test.ts @@ -100,11 +100,40 @@ function providerMetadata(name: string, type: string, credential: string): strin ].join("\n"); } -function providerRunner() { +function providerRunner(profileState: "valid" | "missing" | "import-failed" = "valid") { const live = new Map(); const createCredentials = new Map(); + let currentProfileState = profileState; const run = vi.fn((args: string[], options: { env?: NodeJS.ProcessEnv } = {}) => { switch (args.slice(0, 2).join(" ")) { + case "provider profile": { + switch (args[2]) { + case "export": + return currentProfileState === "valid" + ? { + status: 0, + stdout: JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, + }), + stderr: "", + } + : { status: 1, stdout: "", stderr: "provider profile 'openai' not found" }; + case "import": + switch (currentProfileState) { + case "import-failed": + return { status: 1, stdout: "", stderr: "profile import rejected" }; + default: + currentProfileState = "valid"; + return { status: 0, stdout: "", stderr: "" }; + } + default: + return { status: 1, stdout: "", stderr: "unsupported profile command" }; + } + } case "provider get": { const name = args[2] ?? ""; const binding = live.get(name); @@ -274,6 +303,76 @@ describe("Hermes managed clone broker transaction", () => { expect(receipt.phase).toBe("activated"); }); + it("imports the OpenAI profile before provider creation and broker activation (#10155)", () => { + const profile = hermesProfile(); + const source = sourceEntry(profile); + const runner = providerRunner("missing"); + const hostBroker = broker(); + const prepared = prepareHermesManagedCloneBrokerTransaction({ + handoff: handoff(profile), + destination: null, + environment: environment(), + runOpenshell: runner.run, + broker: hostBroker, + transactionId: "4".repeat(32), + }); + + provisionHermesManagedCloneBrokerTransaction(prepared, { + ...authority(source), + environment: environment(), + runOpenshell: runner.run, + broker: hostBroker, + }); + + const profileExportIndex = runner.run.mock.calls.findIndex( + ([args]) => args.slice(0, 3).join(" ") === "provider profile export", + ); + const profileImportIndex = runner.run.mock.calls.findIndex( + ([args]) => args.slice(0, 3).join(" ") === "provider profile import", + ); + const inferenceCreateIndex = runner.run.mock.calls.findIndex( + ([args]) => + args[0] === "provider" && + args[1] === "create" && + args[3] === "destination-hermes-inference", + ); + expect(profileExportIndex).toBeGreaterThanOrEqual(0); + expect(profileImportIndex).toBeGreaterThan(profileExportIndex); + expect(inferenceCreateIndex).toBeGreaterThan(profileImportIndex); + expect( + runner.run.mock.invocationCallOrder[inferenceCreateIndex], + ).toBeLessThan(hostBroker.activateHermesToolGatewayCloneBinding.mock.invocationCallOrder[0]); + }); + + it("blocks providers and broker mutation when the OpenAI profile import fails (#10155)", () => { + const profile = hermesProfile(); + const source = sourceEntry(profile); + const runner = providerRunner("import-failed"); + const hostBroker = broker(); + const prepared = prepareHermesManagedCloneBrokerTransaction({ + handoff: handoff(profile), + destination: null, + environment: environment(), + runOpenshell: runner.run, + broker: hostBroker, + transactionId: "5".repeat(32), + }); + + expect(() => + provisionHermesManagedCloneBrokerTransaction(prepared, { + ...authority(source), + environment: environment(), + runOpenshell: runner.run, + broker: hostBroker, + }), + ).toThrow("could not import the checked-in 'openai' inference provider profile"); + expect( + runner.run.mock.calls.some(([args]) => args.slice(0, 2).join(" ") === "provider create"), + ).toBe(false); + expect(hostBroker.stageHermesToolGatewayCloneBinding).not.toHaveBeenCalled(); + expect(hostBroker.activateHermesToolGatewayCloneBinding).not.toHaveBeenCalled(); + }); + it("preserves exact providers when activation outcome is unknown", () => { const profile = hermesProfile(); const source = sourceEntry(profile); diff --git a/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts b/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts index 245cb17bb38..b9e285c6a86 100644 --- a/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts +++ b/src/lib/actions/sandbox/snapshot-managed-clone-providers.test.ts @@ -153,6 +153,18 @@ function providerMetadata(binding: LiveBinding): string { ].join("\n"); } +const EXACT_MESSAGING_PROFILE = { + status: 0, + stdout: JSON.stringify({ + id: "nemoclaw-mcp-v1", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: false, + }), + stderr: "", +}; + function providerRunner(initial: readonly LiveBinding[] = []) { const live = new Map(initial.map((binding) => [binding.providerName, { ...binding }] as const)); const commands: string[] = []; @@ -160,7 +172,7 @@ function providerRunner(initial: readonly LiveBinding[] = []) { | ((binding: LiveBinding) => { readonly materialize?: LiveBinding; readonly status: number }) | undefined; let profileImportResult = { status: 0, stdout: "", stderr: "" }; - let profileExportResult = { status: 0, stdout: "", stderr: "" }; + let profileExportResult = EXACT_MESSAGING_PROFILE; let failDelete = false; const run = vi.fn((args: string[]) => { commands.push(args.join(" ")); @@ -304,6 +316,11 @@ describe("managed clone provider transaction", () => { const profile = managedStartupE2eProfile("openclaw"); const source = entry("source", profile); const runner = providerRunner(); + runner.setProfileExportResult({ + status: 1, + stdout: "", + stderr: "provider profile not found", + }); const prepared = prepareManagedCloneProviderTransaction({ handoff: handoff(profile, source, messagingPlan("destination")), destination: null, @@ -370,6 +387,11 @@ describe("managed clone provider transaction", () => { const profile = managedStartupE2eProfile("openclaw"); const source = entry("source", profile); const runner = providerRunner(); + runner.setProfileExportResult({ + status: 1, + stdout: "", + stderr: "provider profile not found", + }); runner.setProfileImportResult({ status: 1, stdout: "", stderr: "gateway unavailable" }); const prepared = prepareManagedCloneProviderTransaction({ handoff: handoff(profile, source, messagingPlan("destination")), diff --git a/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts b/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts index 32d984a7e74..afbc8ed8c71 100644 --- a/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts +++ b/src/lib/actions/sandbox/snapshot/hermes-managed-clone-broker.ts @@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto"; +import { checkOpenAiInferenceProviderProfile } from "../../../adapters/openshell/provider-profile"; import { cloneAndDeepFreeze } from "../../../core/immutable"; import { getHermesToolGatewayCloneBroker, @@ -15,6 +16,7 @@ import { cleanupManagedCloneProviderTransaction, type ManagedCloneProviderBinding, type ManagedCloneProviderCleanupResult, + MANAGED_CLONE_PROVIDER_CREATE_TIMEOUT_MS, type ManagedCloneProviderRunner, type ManagedCloneProviderTransactionReceipt, type PreparedManagedCloneProviderTransaction, @@ -197,6 +199,18 @@ function isUnknownActivationOutcome(error: unknown): boolean { ); } +function ensureHermesCloneInferenceProviderProfile(runOpenshell: ManagedCloneProviderRunner): void { + const profile = checkOpenAiInferenceProviderProfile({ + runOpenshell: (args, options) => + runOpenshell(args, { + ...options, + timeout: MANAGED_CLONE_PROVIDER_CREATE_TIMEOUT_MS, + }), + }); + if (profile.ok) return; + throw new HermesManagedCloneBrokerTransactionError(profile.messages.join("\n")); +} + export function provisionHermesManagedCloneBrokerTransaction( prepared: PreparedHermesManagedCloneBrokerTransaction, input: { @@ -219,6 +233,7 @@ export function provisionHermesManagedCloneBrokerTransaction( } revalidateManagedCloneMutationAuthority(prepared.providerTransaction, input); + ensureHermesCloneInferenceProviderProfile(input.runOpenshell); let staged: ReturnType; try { staged = broker.stageHermesToolGatewayCloneBinding( diff --git a/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts b/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts index 66ec75ee2ca..7288f7c4e75 100644 --- a/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts +++ b/src/lib/actions/sandbox/snapshot/managed-clone-providers.ts @@ -30,7 +30,7 @@ import type { SandboxEntry } from "../../../state/registry/types"; import * as sandboxState from "../../../state/sandbox"; const PROVIDER_PROBE_DIAGNOSTIC_LIMIT = 64 * 1024; -const PROVIDER_CREATE_TIMEOUT_MS = 30_000; +export const MANAGED_CLONE_PROVIDER_CREATE_TIMEOUT_MS = 30_000; const PROVIDER_PROBE_TIMEOUT_MS = 5_000; const PROVIDER_TYPE_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/u; const PROVIDER_ENV_KEY_PATTERN = /^[A-Z_][A-Z0-9_]{0,127}$/u; @@ -587,7 +587,7 @@ export function provisionManagedCloneProviderTransaction( maxBuffer: PROVIDER_PROBE_DIAGNOSTIC_LIMIT, stdio: ["ignore", "pipe", "pipe"], suppressOutput: true, - timeout: PROVIDER_CREATE_TIMEOUT_MS, + timeout: MANAGED_CLONE_PROVIDER_CREATE_TIMEOUT_MS, }, ); } catch (error) { diff --git a/src/lib/adapters/openshell/provider-command.ts b/src/lib/adapters/openshell/provider-command.ts index 80e4e7d7b9e..e332155a8d0 100644 --- a/src/lib/adapters/openshell/provider-command.ts +++ b/src/lib/adapters/openshell/provider-command.ts @@ -4,7 +4,9 @@ import type { StdioOptions } from "node:child_process"; import { buildSubprocessEnv } from "../../subprocess-env"; -import { runOpenshell } from "./runtime"; +import { OPENSHELL_OPERATION_TIMEOUT_MS, runOpenshell } from "./runtime"; + +export { OPENSHELL_OPERATION_TIMEOUT_MS }; export type ProviderCommandOptions = { env?: Record; diff --git a/src/lib/adapters/openshell/provider-profile.test.ts b/src/lib/adapters/openshell/provider-profile.test.ts new file mode 100644 index 00000000000..e5658de01c1 --- /dev/null +++ b/src/lib/adapters/openshell/provider-profile.test.ts @@ -0,0 +1,215 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; +import { describe, expect, it, vi } from "vitest"; + +import { + endpointlessProviderProfilePath, + ensureEndpointlessProviderProfile, + type EndpointlessProviderProfileRunner, +} from "./provider-profile"; + +const PROFILE_ID = "openai"; +const PROFILE_PATH = "/repo/nemoclaw-blueprint/provider-profiles/openai.yaml"; +const EXPECTED_PROFILE = JSON.stringify({ + id: PROFILE_ID, + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); + +function ensureProfile(runOpenshell: ReturnType) { + return ensureEndpointlessProviderProfile({ + profileId: PROFILE_ID, + inferenceCapable: true, + profilePath: PROFILE_PATH, + runOpenshell: runOpenshell as EndpointlessProviderProfileRunner, + }); +} + +describe("OpenShell endpointless provider profiles", () => { + it("resolves a checked-in profile path for the requested profile", () => { + expect(endpointlessProviderProfilePath("/repo", PROFILE_ID)).toBe( + path.join("/repo", "nemoclaw-blueprint", "provider-profiles", "openai.yaml"), + ); + }); + + it("imports a missing endpointless profile with suppressed command output (#9875)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 0 }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: true }); + expect(runOpenshell).toHaveBeenNthCalledWith( + 1, + ["provider", "profile", "export", PROFILE_ID, "--output", "json"], + { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + ); + expect(runOpenshell).toHaveBeenNthCalledWith( + 2, + ["provider", "profile", "import", "--file", PROFILE_PATH], + { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + ); + }); + + it("imports after the supported structured missing-profile response (#10155)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ + status: 1, + output: [ + null, + Buffer.from(""), + Buffer.from("Error: × status: 'NotFound', message: \"provider profile not found\"\n"), + ], + }) + .mockReturnValueOnce({ status: 0 }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: true }); + expect(runOpenshell).toHaveBeenCalledTimes(2); + }); + + it("imports after OpenShell wraps the missing-profile message (#10155)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ + status: 1, + stderr: + "Error: × code: 'Some requested entity was not found', message: \"provider profile\n │ not found\"", + }) + .mockReturnValueOnce({ status: 0 }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: true }); + expect(runOpenshell).toHaveBeenCalledTimes(2); + }); + + it("does not import after an unrelated structured not-found response (#10155)", () => { + const runOpenshell = vi.fn().mockReturnValueOnce({ + status: 1, + output: [ + null, + Buffer.from(""), + Buffer.from("Error: × status: 'NotFound', message: \"gateway not found\"\n"), + ], + }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "export-failed" }); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it("reuses an exact existing profile without importing it (#10155)", () => { + const runOpenshell = vi.fn().mockReturnValueOnce({ status: 0, stdout: EXPECTED_PROFILE }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: true }); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it("rejects an incompatible existing profile without importing it (#10155)", () => { + const runOpenshell = vi.fn().mockReturnValueOnce({ + status: 0, + stdout: JSON.stringify({ + id: PROFILE_ID, + credentials: [], + endpoints: ["https://example.invalid"], + binaries: [], + inference_capable: true, + }), + }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "incompatible" }); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it("does not import when profile inspection fails (#10155)", () => { + const runOpenshell = vi.fn().mockReturnValueOnce({ + status: 1, + stderr: "gateway unavailable", + }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "export-failed" }); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it("does not import when profile inspection has no exit status (#10155)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: null, stderr: "provider profile not found" }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "export-failed" }); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it.each(["not-json", `${EXPECTED_PROFILE}\n${EXPECTED_PROFILE}`])( + "rejects malformed or ambiguous existing profile output (#9875)", + (stdout) => { + const runOpenshell = vi.fn().mockReturnValueOnce({ status: 0, stdout }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "incompatible" }); + }, + ); + + it("classifies an import failure without returning command diagnostics (#9875)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stderr: "provider profile not found" }) + .mockReturnValueOnce({ + status: 1, + stderr: "request failed with credential-must-not-leak", + }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "import-failed" }); + }); + + it("reuses an exact profile created by a concurrent importer (#10155)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 1, stderr: "provider profile already exists" }) + .mockReturnValueOnce({ status: 0, stdout: EXPECTED_PROFILE }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: true }); + expect(runOpenshell).toHaveBeenCalledTimes(3); + }); + + it("rejects a conflicting profile created by a concurrent importer (#10155)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 1, stderr: "provider profile already exists" }) + .mockReturnValueOnce({ + status: 0, + stdout: JSON.stringify({ + id: PROFILE_ID, + credentials: [], + endpoints: ["https://foreign.invalid"], + binaries: [], + inference_capable: true, + }), + }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "incompatible" }); + }); + + it("fails closed when a concurrent import cannot be inspected (#10155)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 1, stderr: "provider profile already exists" }) + .mockReturnValueOnce({ status: 1, stderr: "gateway unavailable" }); + + expect(ensureProfile(runOpenshell)).toEqual({ ok: false, reason: "export-failed" }); + }); +}); diff --git a/src/lib/adapters/openshell/provider-profile.ts b/src/lib/adapters/openshell/provider-profile.ts new file mode 100644 index 00000000000..a891b4480be --- /dev/null +++ b/src/lib/adapters/openshell/provider-profile.ts @@ -0,0 +1,210 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./provider-command"; + +export type EndpointlessProviderProfileRunner = ( + args: string[], + options?: { + readonly ignoreError?: boolean; + readonly suppressOutput?: boolean; + readonly stdio?: ["ignore", "pipe", "pipe"]; + readonly timeout?: number; + }, +) => { + readonly status?: number | null; + readonly output?: unknown; + readonly stdout?: unknown; + readonly stderr?: unknown; +}; + +function outputText(value: unknown): string { + if (Buffer.isBuffer(value)) return value.toString("utf8"); + return typeof value === "string" ? value : ""; +} + +function commandOutput(result: { + readonly output?: unknown; + readonly stdout?: unknown; + readonly stderr?: unknown; +}): string { + const streams = [outputText(result.stderr), outputText(result.stdout)].filter(Boolean); + if (streams.length > 0) return streams.join("\n"); + if (Array.isArray(result.output)) { + return [outputText(result.output[2]), outputText(result.output[1])].filter(Boolean).join("\n"); + } + return outputText(result.output); +} + +function commandStdout(result: { readonly output?: unknown; readonly stdout?: unknown }): string { + const stdout = outputText(result.stdout); + if (stdout) return stdout; + return Array.isArray(result.output) ? outputText(result.output[1]) : outputText(result.output); +} + +function isMissingProviderProfile(output: string, profileId: string): boolean { + const normalized = output + .replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, "") + .replace(/\r/gu, "") + .replace(/\n\s*│\s*/gu, " ") + .trim(); + const escapedProfileId = profileId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const missingMessage = new RegExp( + `^(?:(?:custom )?provider )?profile(?: ['\"]${escapedProfileId}['\"])? not found[.!]?$`, + "iu", + ); + if (missingMessage.test(normalized)) return true; + + const structuredStatus = + /(?:status:\s*['"]?NotFound['"]?|code:\s*['"]Some requested entity was not found['"])/iu; + const message = normalized.match(/message:\s*['"]([^'"\r\n]+)['"]/iu)?.[1]?.trim() ?? ""; + return structuredStatus.test(normalized) && missingMessage.test(message); +} + +function profileHasExpectedCredentialBoundary( + output: string, + expected: { readonly id: string; readonly inferenceCapable: boolean }, +): boolean { + try { + const profile = JSON.parse(output) as Record; + return ( + profile.id === expected.id && + Array.isArray(profile.credentials) && + profile.credentials.length === 0 && + Array.isArray(profile.endpoints) && + profile.endpoints.length === 0 && + Array.isArray(profile.binaries) && + profile.binaries.length === 0 && + profile.inference_capable === expected.inferenceCapable + ); + } catch { + return false; + } +} + +export function endpointlessProviderProfilePath(root: string, profileId: string): string { + return path.join(root, "nemoclaw-blueprint", "provider-profiles", `${profileId}.yaml`); +} + +export type EndpointlessProviderProfileResult = + | { readonly ok: true } + | { + readonly ok: false; + readonly reason: "export-failed" | "import-failed" | "incompatible"; + }; + +/** OpenShell provider type registered for every OpenAI-surface inference route. */ +export const OPENAI_GATEWAY_PROVIDER_TYPE = "openai"; + +export type OpenAiProviderProfileCheck = + | { readonly ok: true } + | { readonly ok: false; readonly messages: readonly string[] }; + +/** Import one endpointless profile or validate the exact existing contract. */ +export function ensureEndpointlessProviderProfile(input: { + readonly profileId: string; + readonly inferenceCapable: boolean; + readonly profilePath: string; + readonly runOpenshell: EndpointlessProviderProfileRunner; +}): EndpointlessProviderProfileResult { + const exportProfile = () => + input.runOpenshell(["provider", "profile", "export", input.profileId, "--output", "json"], { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + + const exported = exportProfile(); + if (exported.status === 0) { + return profileHasExpectedCredentialBoundary(commandStdout(exported), { + id: input.profileId, + inferenceCapable: input.inferenceCapable, + }) + ? { ok: true } + : { ok: false, reason: "incompatible" }; + } + + if (!Number.isInteger(exported.status)) { + return { ok: false, reason: "export-failed" }; + } + const exportOutput = commandOutput(exported); + if (!isMissingProviderProfile(exportOutput, input.profileId)) { + return { ok: false, reason: "export-failed" }; + } + + const imported = input.runOpenshell( + ["provider", "profile", "import", "--file", input.profilePath], + { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }, + ); + if (imported.status === 0) return { ok: true }; + + const importOutput = commandOutput(imported); + if (!/already exists/iu.test(importOutput)) { + return { ok: false, reason: "import-failed" }; + } + + const racedExport = exportProfile(); + if (racedExport.status !== 0) { + return { ok: false, reason: "export-failed" }; + } + if ( + !profileHasExpectedCredentialBoundary(commandStdout(racedExport), { + id: input.profileId, + inferenceCapable: input.inferenceCapable, + }) + ) { + return { ok: false, reason: "incompatible" }; + } + return { ok: true }; +} + +/** Validate or import the endpointless OpenAI profile through the OpenShell adapter. */ +export function checkOpenAiInferenceProviderProfile(deps: { + readonly runOpenshell: EndpointlessProviderProfileRunner; + readonly root?: string; +}): OpenAiProviderProfileCheck { + const result = ensureEndpointlessProviderProfile({ + profileId: OPENAI_GATEWAY_PROVIDER_TYPE, + inferenceCapable: true, + profilePath: endpointlessProviderProfilePath( + deps.root ?? REPOSITORY_ROOT, + OPENAI_GATEWAY_PROVIDER_TYPE, + ), + runOpenshell: deps.runOpenshell, + }); + if (result.ok) return { ok: true }; + + if (result.reason === "import-failed") { + return { + ok: false, + messages: [ + `\n ✗ OpenShell could not import the checked-in '${OPENAI_GATEWAY_PROVIDER_TYPE}' inference provider profile.`, + " Confirm OpenShell is available and authorized, then retry this command.", + ], + }; + } + if (result.reason === "export-failed") { + return { + ok: false, + messages: [ + `\n ✗ OpenShell provider profile '${OPENAI_GATEWAY_PROVIDER_TYPE}' could not be read for validation.`, + " Confirm OpenShell is available, authorized, and the profile is readable, then retry this command.", + ], + }; + } + return { + ok: false, + messages: [ + `\n ✗ OpenShell provider profile '${OPENAI_GATEWAY_PROVIDER_TYPE}' already exists but does not match NemoClaw's endpointless inference contract.`, + " Remove the conflicting profile, then retry this command.", + ], + }; +} diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index f4fd2537907..87a21b47359 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -13,11 +13,11 @@ import { runOpenshellCommand, } from "./client"; import { buildOpenShellSubprocessEnv, resolveOpenshellBinaryOrNull } from "./resolve-shared"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; +import { OPENSHELL_OPERATION_TIMEOUT_MS, OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; type CommandArgs = string[]; -export { buildOpenShellSubprocessEnv }; +export { buildOpenShellSubprocessEnv, OPENSHELL_OPERATION_TIMEOUT_MS }; type RunnerOptions = { /** Exact canonical executable selected by the caller. */ diff --git a/src/lib/hermes-provider-auth.test.ts b/src/lib/hermes-provider-auth.test.ts index f558b4e66c2..22b539b3251 100644 --- a/src/lib/hermes-provider-auth.test.ts +++ b/src/lib/hermes-provider-auth.test.ts @@ -6,11 +6,18 @@ import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; const require = createRequire(import.meta.url); const SOURCE_AUTH = path.join(import.meta.dirname, "hermes-provider-auth.ts"); const SOURCE_BROKER = path.join(import.meta.dirname, "hermes-tool-gateway-broker.ts"); +const EXACT_OPENAI_PROFILE = JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); function clearSourceModule(modulePath: string): void { try { @@ -56,6 +63,85 @@ describe("Hermes provider OpenShell credential handoff", () => { ).toEqual({ exists: true, credentialKeys: null }); }); + it("imports the OpenAI profile before Hermes credential registration (#10155)", () => { + const auth = loadAuth(); + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 0, stdout: "Imported", stderr: "" }) + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider not found" }) + .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); + + auth.registerHermesInferenceProvider("nous-key", runOpenshell); + + expect(runOpenshell.mock.calls.map(([args]) => args)).toEqual([ + ["provider", "profile", "export", "openai", "--output", "json"], + ["provider", "profile", "import", "--file", expect.stringMatching(/openai\.yaml$/u)], + ["provider", "get", "hermes-provider"], + expect.arrayContaining([ + "provider", + "create", + "--name", + "hermes-provider", + "--type", + "openai", + ]), + ]); + expect(runOpenshell.mock.calls[0]?.[1]).toMatchObject({ + ignoreError: true, + suppressOutput: true, + timeout: 30_000, + }); + }); + + it("rejects an incompatible OpenAI profile before Hermes credential mutation (#10155)", () => { + const auth = loadAuth(); + const secret = "nous-incompatible-secret"; + const runOpenshell = vi.fn().mockReturnValueOnce({ + status: 0, + stdout: JSON.stringify({ + id: "openai", + credentials: [{ env: "OPENAI_API_KEY" }], + endpoints: [], + binaries: [], + inference_capable: true, + }), + stderr: "", + }); + + let thrown: unknown; + try { + auth.registerHermesInferenceProvider(secret, runOpenshell); + } catch (error) { + thrown = error; + } + + expect(String(thrown)).toContain("does not match NemoClaw's endpointless inference contract"); + expect(String(thrown)).not.toContain(secret); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it("suppresses failed OpenAI profile import output before Hermes credential mutation (#10155)", () => { + const auth = loadAuth(); + const secret = "profile-import-secret"; + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 1, stdout: "", stderr: `import rejected: ${secret}` }); + + let thrown: unknown; + try { + auth.registerHermesInferenceProvider("nous-key", runOpenshell); + } catch (error) { + thrown = error; + } + + expect(String(thrown)).toContain("could not import the checked-in 'openai'"); + expect(String(thrown)).not.toContain(secret); + expect(String(thrown)).not.toContain("import rejected"); + expect(runOpenshell).toHaveBeenCalledTimes(2); + }); + it("registers Nous API-key inference in OpenShell without host-side persistence", async () => { const originalHome = process.env.HOME; const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-api-key-")); @@ -67,10 +153,11 @@ describe("Hermes provider OpenShell credential handoff", () => { apiKey: "nous-key-1", runOpenshell: (args: string[], opts: { env?: Record } = {}) => { calls.push({ args, env: opts.env }); - if (args[0] === "provider" && args[1] === "get") { - return { status: 1, stdout: "", stderr: "" }; - } - return { status: 0, stdout: "", stderr: "" }; + return args[1] === "profile" + ? { status: 0, stdout: EXACT_OPENAI_PROFILE, stderr: "" } + : args[1] === "get" + ? { status: 1, stdout: "", stderr: "" } + : { status: 0, stdout: "", stderr: "" }; }, }); @@ -141,10 +228,11 @@ describe("Hermes provider OpenShell credential handoff", () => { noBrowser: true, runOpenshell: (args: string[], opts: { env?: Record } = {}) => { providerCalls.push({ args, env: opts.env }); - if (args[0] === "provider" && args[1] === "get") { - return { status: 1, stdout: "", stderr: "" }; - } - return { status: 0, stdout: "", stderr: "" }; + return args[1] === "profile" + ? { status: 0, stdout: EXACT_OPENAI_PROFILE, stderr: "" } + : args[1] === "get" + ? { status: 1, stdout: "", stderr: "" } + : { status: 0, stdout: "", stderr: "" }; }, }); @@ -224,10 +312,11 @@ describe("Hermes provider OpenShell credential handoff", () => { noBrowser: true, runOpenshell: (args: string[], opts: { env?: Record } = {}) => { providerCalls.push({ args, env: opts.env }); - if (args[0] === "provider" && args[1] === "get") { - return { status: 1, stdout: "", stderr: "" }; - } - return { status: 0, stdout: "", stderr: "" }; + return args[1] === "profile" + ? { status: 0, stdout: EXACT_OPENAI_PROFILE, stderr: "" } + : args[1] === "get" + ? { status: 1, stdout: "", stderr: "" } + : { status: 0, stdout: "", stderr: "" }; }, toolGatewayPresets: ["nous-web", "nous-audio"], }); diff --git a/src/lib/hermes-provider-auth.ts b/src/lib/hermes-provider-auth.ts index 2333a3feca9..c16176feb45 100644 --- a/src/lib/hermes-provider-auth.ts +++ b/src/lib/hermes-provider-auth.ts @@ -11,6 +11,7 @@ import type { StdioOptions } from "node:child_process"; +import { checkOpenAiInferenceProviderProfile } from "./adapters/openshell/provider-profile"; import * as oauth from "./oauth-device-code"; const onboardProviders = require("./onboard/providers") as { @@ -58,6 +59,7 @@ export type RunOpenshell = ( env?: NodeJS.ProcessEnv; stdio?: StdioOptions; ignoreError?: boolean; + suppressOutput?: boolean; timeout?: number; }, ) => RunOpenshellResult; @@ -122,6 +124,10 @@ export function registerHermesInferenceProvider( if (!normalizedApiKey) { throw new Error("Hermes Provider credential is empty"); } + const profile = checkOpenAiInferenceProviderProfile({ runOpenshell }); + if (!profile.ok) { + throw new Error(profile.messages.join("\n")); + } const result = onboardProviders.upsertProvider( HERMES_PROVIDER_NAME, "openai", diff --git a/src/lib/messaging/applier/setup-applier.test.ts b/src/lib/messaging/applier/setup-applier.test.ts index 16f63e712bb..fe4c46fd0ff 100644 --- a/src/lib/messaging/applier/setup-applier.test.ts +++ b/src/lib/messaging/applier/setup-applier.test.ts @@ -37,6 +37,17 @@ const TEST_CREDENTIALS: Readonly> = { MSTEAMS_APP_PASSWORD: "test-teams-client-secret", }; +const EXACT_MESSAGING_PROFILE = { + status: 0, + stdout: JSON.stringify({ + id: "nemoclaw-mcp-v1", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: false, + }), +}; + const ALL_CHANNEL_ENV = { TELEGRAM_BOT_TOKEN: "123456:telegram-token", TELEGRAM_ALLOWED_IDS: "1001,1002", @@ -403,6 +414,8 @@ describe("MessagingSetupApplier", () => { const runOpenshell: MessagingOpenShellRunner = (args, options) => { calls.push({ args, env: options?.env }); switch (args[1]) { + case "profile": + return EXACT_MESSAGING_PROFILE; case "get": { const name = String(args[2]); const credentialKey = @@ -430,7 +443,7 @@ describe("MessagingSetupApplier", () => { }); expect(calls.map((call) => call.args)).toEqual([ - ["provider", "profile", "import", "--file", expect.stringMatching(/nemoclaw-mcp-v1\.yaml$/)], + ["provider", "profile", "export", "nemoclaw-mcp-v1", "--output", "json"], ["provider", "get", "demo-telegram-bridge"], [ "provider", @@ -484,10 +497,12 @@ describe("MessagingSetupApplier", () => { const calls: string[] = []; const runOpenshell: MessagingOpenShellRunner = (args) => { calls.push(args.join(" ")); - return args[1] === "get" - ? { - status: 0, - stdout: + return args[1] === "profile" + ? EXACT_MESSAGING_PROFILE + : args[1] === "get" + ? { + status: 0, + stdout: "Name: demo-telegram-bridge\nType: generic\nCredential keys: TELEGRAM_BOT_TOKEN\nConfig keys: \n", } : { status: 0 }; @@ -545,7 +560,7 @@ describe("MessagingSetupApplier", () => { const runOpenshell: MessagingOpenShellRunner = (args) => { switch (args[1]) { case "profile": - return { status: 0 }; + return EXACT_MESSAGING_PROFILE; case "get": return { status: 1, @@ -584,7 +599,7 @@ describe("MessagingSetupApplier", () => { runOpenshell: (args) => { calls.push(args.join(" ")); return args[1] === "profile" - ? { status: 0 } + ? EXACT_MESSAGING_PROFILE : { status: 1, stderr: "gateway unavailable" }; }, }), @@ -603,7 +618,7 @@ describe("MessagingSetupApplier", () => { runOpenshell: (args) => { switch (args[1]) { case "profile": - return { status: 0 }; + return EXACT_MESSAGING_PROFILE; case "get": return { status: 1, stderr: "provider 'demo-telegram-bridge' not found" }; default: @@ -626,6 +641,7 @@ describe("MessagingSetupApplier", () => { runOpenshell: (args) => { switch (args[1]) { case "profile": + return EXACT_MESSAGING_PROFILE; case "create": return { status: 0 }; default: @@ -655,7 +671,7 @@ describe("MessagingSetupApplier", () => { runOpenshell: (args) => { calls.push(args.join(" ")); return args[1] === "profile" - ? { status: 0 } + ? EXACT_MESSAGING_PROFILE : { status: 1, stderr: 'Error: status: Unavailable, message: "provider not found"', @@ -782,6 +798,8 @@ describe("MessagingSetupApplier", () => { env: ALL_CHANNEL_ENV, runOpenshell: (args) => { switch (args[1]) { + case "profile": + return EXACT_MESSAGING_PROFILE; case "get": { const name = String(args[2]); const credentialKey = providers.get(name); @@ -929,6 +947,8 @@ describe("MessagingSetupApplier", () => { runOpenshell: (args) => { providerCalls.push([...args]); switch (args[1]) { + case "profile": + return EXACT_MESSAGING_PROFILE; case "get": { const name = String(args[2]); const credentialKey = providers.get(name); diff --git a/src/lib/messaging/provider-profile.test.ts b/src/lib/messaging/provider-profile.test.ts index b10b1f66d0c..e9e57a2b209 100644 --- a/src/lib/messaging/provider-profile.test.ts +++ b/src/lib/messaging/provider-profile.test.ts @@ -1,8 +1,8 @@ // 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 path from "node:path"; +import { describe, expect, it, vi } from "vitest"; import { REPOSITORY_ROOT } from "../core/repository-root"; import { @@ -10,32 +10,30 @@ import { MESSAGING_CREDENTIAL_PROVIDER_TYPE, messagingCredentialProviderProfilePath, } from "./provider-profile"; - -const EXPECTED_PROFILE = JSON.stringify({ - id: MESSAGING_CREDENTIAL_PROVIDER_TYPE, - credentials: [], - endpoints: [], - binaries: [], - inference_capable: false, -}); +import * as providerProfileModule from "./provider-profile"; describe("messaging credential provider profile", () => { + it("exports only the messaging-specific profile surface (#10155)", () => { + expect(providerProfileModule).not.toHaveProperty("endpointlessProviderProfilePath"); + expect(providerProfileModule).not.toHaveProperty("ensureEndpointlessProviderProfile"); + }); + it("resolves the checked-in profile from the source repository root (#9875)", () => { expect(messagingCredentialProviderProfilePath(REPOSITORY_ROOT)).toBe( path.join(REPOSITORY_ROOT, "nemoclaw-blueprint", "provider-profiles", "nemoclaw-mcp-v1.yaml"), ); }); - it("imports the endpointless profile from the checked-in path (#9875)", () => { - const runOpenshell = vi.fn(() => ({ status: 0 })); + it("imports the messaging profile from the checked-in path (#9875)", () => { + const runOpenshell = vi + .fn() + .mockReturnValueOnce({ status: 1, stderr: "provider profile not found" }) + .mockReturnValueOnce({ status: 0 }); - ensureMessagingCredentialProviderProfile({ - root: "/repo", - runOpenshell, - }); + ensureMessagingCredentialProviderProfile({ root: "/repo", runOpenshell }); - expect(runOpenshell).toHaveBeenCalledOnce(); - expect(runOpenshell).toHaveBeenCalledWith( + expect(runOpenshell).toHaveBeenNthCalledWith( + 2, [ "provider", "profile", @@ -43,95 +41,56 @@ describe("messaging credential provider profile", () => { "--file", "/repo/nemoclaw-blueprint/provider-profiles/nemoclaw-mcp-v1.yaml", ], - { ignoreError: true, stdio: ["ignore", "pipe", "pipe"] }, + { + ignoreError: true, + suppressOutput: true, + timeout: 30_000, + stdio: ["ignore", "pipe", "pipe"], + }, ); }); - it("validates an existing profile before accepting it (#9875)", () => { + it("reports a fixed messaging import failure without command diagnostics (#9875)", () => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 1, stderr: "profile already exists" }) - .mockReturnValueOnce({ status: 0, stdout: EXPECTED_PROFILE }); - - expect(() => - ensureMessagingCredentialProviderProfile({ - root: "/repo", - runOpenshell, - }), - ).not.toThrow(); - - expect(runOpenshell).toHaveBeenNthCalledWith( - 2, - ["provider", "profile", "export", MESSAGING_CREDENTIAL_PROVIDER_TYPE, "--output", "json"], - { ignoreError: true, stdio: ["ignore", "pipe", "pipe"] }, - ); - }); - - it("rejects an incompatible existing profile (#9875)", () => { - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 1, stderr: "profile already exists" }) + .mockReturnValueOnce({ status: 1, stderr: "provider profile not found" }) .mockReturnValueOnce({ - status: 0, - stdout: JSON.stringify({ - id: MESSAGING_CREDENTIAL_PROVIDER_TYPE, - credentials: [], - endpoints: ["https://example.invalid"], - binaries: [], - inference_capable: false, - }), + status: 1, + stderr: "request failed with discord-credential-must-not-leak", }); expect(() => - ensureMessagingCredentialProviderProfile({ - root: "/repo", - runOpenshell, - }), - ).toThrow(/does not match NemoClaw's endpointless messaging credential contract/); + ensureMessagingCredentialProviderProfile({ root: "/repo", runOpenshell }), + ).toThrow("Could not import the OpenShell messaging credential profile."); }); - it("reports a failed existing-profile export separately (#9875)", () => { - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 1, stderr: "profile already exists" }) - .mockReturnValueOnce({ status: 1, stderr: "gateway unavailable" }); + it("reports a messaging-specific export failure (#10155)", () => { + const runOpenshell = vi.fn().mockReturnValueOnce({ + status: 1, + stderr: "gateway unavailable", + }); expect(() => - ensureMessagingCredentialProviderProfile({ - root: "/repo", - runOpenshell, - }), - ).toThrow(/already exists but could not be exported for validation/); + ensureMessagingCredentialProviderProfile({ root: "/repo", runOpenshell }), + ).toThrow( + `OpenShell provider profile '${MESSAGING_CREDENTIAL_PROVIDER_TYPE}' could not be exported for validation.`, + ); }); - it.each(["not-json", `${EXPECTED_PROFILE}\n${EXPECTED_PROFILE}`])( - "rejects malformed or ambiguous existing profile output (#9875)", - (stdout) => { - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 1, stderr: "profile already exists" }) - .mockReturnValueOnce({ status: 0, stdout }); - - expect(() => - ensureMessagingCredentialProviderProfile({ - root: "/repo", - runOpenshell, - }), - ).toThrow(/does not match NemoClaw's endpointless messaging credential contract/); - }, - ); - - it("suppresses profile import diagnostics (#9875)", () => { - const runOpenshell = vi.fn(() => ({ - status: 1, - stderr: "request failed with discord-credential-must-not-leak", - })); + it("reports a messaging-specific incompatible-profile failure (#10155)", () => { + const runOpenshell = vi.fn().mockReturnValueOnce({ + status: 0, + stdout: JSON.stringify({ + id: MESSAGING_CREDENTIAL_PROVIDER_TYPE, + credentials: [], + endpoints: ["https://example.invalid"], + binaries: [], + inference_capable: false, + }), + }); expect(() => - ensureMessagingCredentialProviderProfile({ - root: "/repo", - runOpenshell, - }), - ).toThrow("Could not import the OpenShell messaging credential profile."); + ensureMessagingCredentialProviderProfile({ root: "/repo", runOpenshell }), + ).toThrow(/does not match NemoClaw's endpointless messaging credential contract/u); }); }); diff --git a/src/lib/messaging/provider-profile.ts b/src/lib/messaging/provider-profile.ts index 7f2762cd392..98beb1d80bd 100644 --- a/src/lib/messaging/provider-profile.ts +++ b/src/lib/messaging/provider-profile.ts @@ -1,104 +1,18 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import path from "node:path"; +import { + endpointlessProviderProfilePath, + ensureEndpointlessProviderProfile, + type EndpointlessProviderProfileRunner, +} from "../adapters/openshell/provider-profile"; export const MESSAGING_CREDENTIAL_PROVIDER_TYPE = "nemoclaw-mcp-v1"; // gitleaks:allow -export type EndpointlessProviderProfileRunner = ( - args: string[], - options?: { - readonly ignoreError?: boolean; - readonly stdio?: ["ignore", "pipe", "pipe"]; - }, -) => { - readonly status?: number | null; - readonly stdout?: unknown; - readonly stderr?: unknown; -}; - -function outputText(value: unknown): string { - if (Buffer.isBuffer(value)) return value.toString("utf8"); - return typeof value === "string" ? value : ""; -} - -function commandOutput(result: { readonly stdout?: unknown; readonly stderr?: unknown }): string { - return `${outputText(result.stderr)}\n${outputText(result.stdout)}`; -} - -function profileHasExpectedCredentialBoundary( - output: string, - expected: { readonly id: string; readonly inferenceCapable: boolean }, -): boolean { - try { - const profile = JSON.parse(output) as Record; - return ( - profile.id === expected.id && - Array.isArray(profile.credentials) && - profile.credentials.length === 0 && - Array.isArray(profile.endpoints) && - profile.endpoints.length === 0 && - Array.isArray(profile.binaries) && - profile.binaries.length === 0 && - profile.inference_capable === expected.inferenceCapable - ); - } catch { - return false; - } -} - export function messagingCredentialProviderProfilePath(root: string): string { return endpointlessProviderProfilePath(root, MESSAGING_CREDENTIAL_PROVIDER_TYPE); } -export function endpointlessProviderProfilePath(root: string, profileId: string): string { - return path.join(root, "nemoclaw-blueprint", "provider-profiles", `${profileId}.yaml`); -} - -export type EndpointlessProviderProfileResult = - | { readonly ok: true } - | { - readonly ok: false; - readonly reason: "export-failed" | "import-failed" | "incompatible"; - readonly diagnostic: string; - }; - -/** Import one endpointless profile or validate the exact existing contract. */ -export function ensureEndpointlessProviderProfile(input: { - readonly profileId: string; - readonly inferenceCapable: boolean; - readonly profilePath: string; - readonly runOpenshell: EndpointlessProviderProfileRunner; -}): EndpointlessProviderProfileResult { - const imported = input.runOpenshell( - ["provider", "profile", "import", "--file", input.profilePath], - { ignoreError: true, stdio: ["ignore", "pipe", "pipe"] }, - ); - if (imported.status === 0) return { ok: true }; - - const importOutput = commandOutput(imported); - if (!/already exists/iu.test(importOutput)) { - return { ok: false, reason: "import-failed", diagnostic: importOutput.trim() }; - } - - const exported = input.runOpenshell( - ["provider", "profile", "export", input.profileId, "--output", "json"], - { ignoreError: true, stdio: ["ignore", "pipe", "pipe"] }, - ); - if (exported.status !== 0) { - return { ok: false, reason: "export-failed", diagnostic: "" }; - } - if ( - !profileHasExpectedCredentialBoundary(outputText(exported.stdout), { - id: input.profileId, - inferenceCapable: input.inferenceCapable, - }) - ) { - return { ok: false, reason: "incompatible", diagnostic: "" }; - } - return { ok: true }; -} - /** Register and verify the endpointless profile used by static messaging credentials. */ export function ensureMessagingCredentialProviderProfile(input: { readonly root: string; @@ -116,7 +30,7 @@ export function ensureMessagingCredentialProviderProfile(input: { } if (result.reason === "export-failed") { throw new Error( - `OpenShell provider profile '${MESSAGING_CREDENTIAL_PROVIDER_TYPE}' already exists but could not be exported for validation.`, + `OpenShell provider profile '${MESSAGING_CREDENTIAL_PROVIDER_TYPE}' could not be exported for validation.`, ); } throw new Error( diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 2d8fbf7f2bc..5a7d13fe503 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -742,7 +742,8 @@ const { getGatewayReuseSnapshot, selectNamedGatewayForReuseIfNeeded } = const { refreshDockerDriverGatewayReuseState } = gatewayReuse.createDockerDriverGatewayReuseApplication({ gatewayName: () => GATEWAY_NAME, - getGatewayCompatContainerName: () => gatewayBinding.resolveGatewayCompatContainerName(GATEWAY_PORT), + getGatewayCompatContainerName: () => + gatewayBinding.resolveGatewayCompatContainerName(GATEWAY_PORT), isDockerDriverGatewayEnabled: isLinuxDockerDriverGatewayEnabled, resolveOpenShellGatewayBinary, getDockerDriverGatewayEnv, @@ -1668,7 +1669,6 @@ const createSandboxWithBaseImageResolution = sandboxCreateOrchestrationRuntime, ); - const { createSandbox, createSandboxWithTemporaryManagedRuntime } = agentOnboard.createHermesApiPortScopedSandboxEntryPoints({ createBaseImageResolutionContext: () => @@ -2810,7 +2810,9 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { collector: null, span: null, }; - let completed = false, preserveDeferredExitSession = false, preserveIncompleteSession = false; + let completed = false, + preserveDeferredExitSession = false, + preserveIncompleteSession = false; try { await portableRetirementEntry.run(async () => { const lockedRuntime = await resumeRuntime.prepare( @@ -2919,7 +2921,10 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { process.exit(1); } - registerIncompleteOnboardExitHandlerForSession(onboardSession, () => completed || preserveIncompleteSession); + registerIncompleteOnboardExitHandlerForSession( + onboardSession, + () => completed || preserveIncompleteSession, + ); const agent = await selectOnboardAgent({ agentFlag: opts.agent, session, @@ -3095,8 +3100,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { recordRepairEvent, }); - // #2753: for an unfinished sandbox, an explicit requested name precedes - // the checkpointed name from the interrupted session. + // #2753: An explicit requested name precedes its checkpointed name for an unfinished sandbox. const coreFlowContext = prepareCoreOnboardFlowContext({ initial: initialFlowResult, recordedSandboxName, @@ -3175,7 +3179,13 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { recoverySessionId, ), setupInference, - resolveHostLocalInferenceStartupSelection: setupNimFlow.createHermesPortableOllamaInferenceResolver({ runtimeContext: lockedRuntime.portableRuntimeContext, credentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, getReservationSessionId: () => session?.sessionId, runGatewayOpenshell: runCoreGatewayOpenshell }), + resolveHostLocalInferenceStartupSelection: + setupNimFlow.createHermesPortableOllamaInferenceResolver({ + runtimeContext: lockedRuntime.portableRuntimeContext, + credentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, + getReservationSessionId: () => session?.sessionId, + runGatewayOpenshell: runCoreGatewayOpenshell, + }), startRecordedStep, recordStepComplete, recordStepRejected, @@ -3196,21 +3206,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { isInferenceRouteReady, isRoutedInferenceProvider, reconcileModelRouter, - reupsertRoutedProvider: (gatewayName, p, url, ce) => { - const r = routedInference.upsertRoutedProvider(p, url, ce, { - upsertProvider: setupInferenceFactory.bindGatewayUpsertProvider( - upsertProvider, - gatewayName, - ), - hydrateCredentialEnv, - }); - return { - ok: r.ok, - endpointUrl: r.endpointUrl, - message: r.result.message, - status: r.result.status, - }; - }, + reupsertRoutedProvider: setupInferenceFactory.createRoutedResumeProviderUpsert({ + upsertProvider, + runGatewayOpenshell: runCoreGatewayOpenshell, + hydrateCredentialEnv, + }), reserveSandboxInferenceRoute: registry.reserveSandboxInferenceRoute, registryUpdateSandbox: (name, updates) => registry.updateSandbox(name, updates), ...providerReviewDeps, @@ -3308,7 +3308,6 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { hermesApiPortReservationScope, ...createArgs, ), - ), ), updateSandboxRegistry: (name, updates) => registry.updateSandbox(name, updates), @@ -3487,7 +3486,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { process.exitCode = completed ? 0 : 1; }); } catch (error) { - preserveDeferredExitSession = onboardSessionBootstrap.shouldPreserveIncompleteOnboardSession(error); + preserveDeferredExitSession = + onboardSessionBootstrap.shouldPreserveIncompleteOnboardSession(error); throw error; } finally { try { diff --git a/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts b/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts index e68a0061040..3e5d9c88c81 100644 --- a/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts +++ b/src/lib/onboard/experimental/hermes-portable-ollama-gateway-transaction.ts @@ -6,6 +6,7 @@ import fs from "node:fs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; +import { checkOpenAiInferenceProviderProfile } from "../../adapters/openshell/provider-profile"; import { ensureConfigDir, rejectSymlinksOnPath } from "../../state/config-io"; import { parseGatewayProviderMetadata } from "../gateway-provider-metadata"; import type { HostLocalInferenceReceiptWriter } from "../runtime-provider/host-local-inference"; @@ -689,14 +690,30 @@ function exactGatewayMutation( throw new Error("Hermes Portable inference gateway provider intent disappeared."); } let before = readExact(input.provider); + const requireOpenAiProfile = () => { + const profile = checkOpenAiInferenceProviderProfile({ + runOpenshell: (args, options) => + runGatewayOpenshell(args, { + ignoreError: true, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: options?.timeout ?? GATEWAY_PROVIDER_MUTATION_TIMEOUT_MS, + }), + }); + if (!profile.ok) { + throw new Error(profile.messages.join("\n")); + } + }; if (active.phase === "created" || active.phase === "committed") { if (!active.providerAuthority || !matchesAuthority(before, active.providerAuthority)) { throw new Error( "Hermes Portable inference recorded gateway provider authority changed.", ); } + requireOpenAiProfile(); return { ok: true }; } + requireOpenAiProfile(); if (active.phase === "prepared") { if (before.kind !== "absent") { throw new Error("Hermes Portable inference provider name is no longer unclaimed."); diff --git a/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts b/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts index 4248ec7e886..3cc53b9d049 100644 --- a/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts +++ b/src/lib/onboard/experimental/hermes-portable-ollama-inference.test.ts @@ -798,6 +798,80 @@ describe("Hermes Portable Ollama inference activation", () => { expect(fixture.gatewayProvider.isPresent()).toBe(false); }); + it("validates the exact OpenAI profile before Portable provider creation (#10155)", async () => { + const fixture = createRuntimeFixture(); + const mutation = await fixture.resolve()!.prepareGatewayMutation(gatewayMutationInput); + + expect(createExactGatewayProvider(mutation)).toEqual({ ok: true }); + + const profileExport = fixture.events.indexOf( + "openshell:provider profile export openai --output json", + ); + const providerCreate = fixture.events.findIndex((event) => + event.includes("provider create --name ollama-local"), + ); + expect(profileExport).toBeGreaterThanOrEqual(0); + expect(providerCreate).toBeGreaterThan(profileExport); + expect(fixture.events.some((event) => event.includes("provider profile import"))).toBe(false); + }); + + it("imports a missing OpenAI profile before Portable provider creation (#10155)", async () => { + const fixture = createRuntimeFixture(); + fixture.gatewayProvider.setProfileState("missing"); + const mutation = await fixture.resolve()!.prepareGatewayMutation(gatewayMutationInput); + + expect(createExactGatewayProvider(mutation)).toEqual({ ok: true }); + + const profileExport = fixture.events.indexOf( + "openshell:provider profile export openai --output json", + ); + const profileImport = fixture.events.findIndex((event) => + event.includes("provider profile import --file"), + ); + const providerCreate = fixture.events.findIndex((event) => + event.includes("provider create --name ollama-local"), + ); + expect(profileExport).toBeGreaterThanOrEqual(0); + expect(profileImport).toBeGreaterThan(profileExport); + expect(providerCreate).toBeGreaterThan(profileImport); + }); + + it("rejects an incompatible OpenAI profile before Portable provider mutation (#10155)", async () => { + const fixture = createRuntimeFixture(); + fixture.gatewayProvider.setProfileState("incompatible"); + const mutation = await fixture.resolve()!.prepareGatewayMutation(gatewayMutationInput); + + expect(() => createExactGatewayProvider(mutation)).toThrow( + "does not match NemoClaw's endpointless inference contract", + ); + + expect(fixture.gatewayProvider.isPresent()).toBe(false); + expect( + fixture.events.some((event) => event.includes("provider create --name ollama-local")), + ).toBe(false); + expect(gatewayJournal(fixture)).toMatchObject({ phase: "prepared" }); + }); + + it("revalidates the OpenAI profile before reusing a Portable provider (#10155)", async () => { + const fixture = createRuntimeFixture(); + await publishPortableInference(fixture); + fixture.gatewayProvider.setProfileState("incompatible"); + const resumed = fixture.resolve({ + ...freshPortableInput, + allowPublishedResume: true, + recover: true, + })!; + const mutation = await resumed.prepareGatewayMutation(gatewayMutationInput); + + expect(() => createExactGatewayProvider(mutation)).toThrow( + "does not match NemoClaw's endpointless inference contract", + ); + + expect(fixture.gatewayProvider.isPresent()).toBe(true); + expect(gatewayJournal(fixture)).toMatchObject({ phase: "committed" }); + expect(fixture.events.some((event) => event.includes("provider delete"))).toBe(false); + }); + it("resumes the journaled provider-create crash window and publishes exact ownership (#9596)", async () => { // Crash-window state transitions: // S0 has no runtime, provider, journal, or receipt. Runtime preparation creates the container. diff --git a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts index 0702c67f2bb..cff07e4ace6 100644 --- a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts +++ b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts @@ -99,16 +99,23 @@ describe("compatible endpoint gateway routing", () => { describe("recovered provider reuse and the openai provider profile (#9895)", () => { const REGISTERED_URL = "http://host.openshell.internal:8000/v1"; + const OPENAI_ENDPOINTLESS_PROFILE = JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, + }); - function createRunOpenshell(profileStatus: number) { + function createRunOpenshell( + profileResults: Array<{ status: number; stdout?: string; stderr?: string }>, + ) { const commands: string[] = []; const runOpenshell = vi.fn((args: string[]) => { commands.push(args.join(" ")); - return { - status: args[1] === "profile" ? profileStatus : 0, - stdout: "", - stderr: "import refused", - }; + return args[1] === "profile" + ? (profileResults.shift() ?? { status: 1, stderr: "unexpected profile call" }) + : { status: 0, stdout: "", stderr: "" }; }); return { commands, runOpenshell }; } @@ -122,7 +129,9 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () }; it("declares the openai profile for an unchanged gateway route that performs no upsert", () => { - const { commands, runOpenshell } = createRunOpenshell(0); + const { commands, runOpenshell } = createRunOpenshell([ + { status: 0, stdout: OPENAI_ENDPOINTLESS_PROFILE }, + ]); const upsertProvider = vi.fn(() => ({ ok: true })); expect( @@ -132,14 +141,15 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () expect(upsertProvider).not.toHaveBeenCalled(); expect(commands).toEqual([ "provider get compatible-endpoint", - expect.stringMatching( - /^provider profile import --file .*\/provider-profiles\/openai\.yaml$/u, - ), + "provider profile export openai --output json", ]); }); it("reports a failed profile import instead of reusing the recovered provider", () => { - const { runOpenshell } = createRunOpenshell(1); + const { runOpenshell } = createRunOpenshell([ + { status: 1, stderr: "provider profile not found" }, + { status: 1, stderr: "import refused" }, + ]); const upsertProvider = vi.fn(() => ({ ok: true })); const result = reuseRegisteredProviderWithGatewayEndpoint({ @@ -158,7 +168,7 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () }); it("leaves a non-openai recovered provider untouched", () => { - const { commands, runOpenshell } = createRunOpenshell(1); + const { commands, runOpenshell } = createRunOpenshell([]); const upsertProvider = vi.fn(() => ({ ok: true })); expect( diff --git a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts index ec8bfbf1b49..e464d161523 100644 --- a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts +++ b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts @@ -2,11 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import { VLLM_PORT } from "../../core/vllm-port"; -import { LLAMA_CPP_PORT } from "../../inference/llama-cpp/contract"; import { checkOpenAiInferenceProviderProfile, OPENAI_GATEWAY_PROVIDER_TYPE, -} from "./provider-profile"; +} from "../../adapters/openshell/provider-profile"; +import { LLAMA_CPP_PORT } from "../../inference/llama-cpp/contract"; import type { RunOpenshell, UpsertProvider, UpsertProviderResult } from "./types"; // Keep this list aligned with the materialized host.openshell.internal endpoints diff --git a/src/lib/onboard/inference-providers/provider-profile.ts b/src/lib/onboard/inference-providers/provider-profile.ts index d1981739150..c8a7f015459 100644 --- a/src/lib/onboard/inference-providers/provider-profile.ts +++ b/src/lib/onboard/inference-providers/provider-profile.ts @@ -1,15 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { REPOSITORY_ROOT } from "../../core/repository-root"; import { - endpointlessProviderProfilePath, - ensureEndpointlessProviderProfile, + checkOpenAiInferenceProviderProfile, type EndpointlessProviderProfileRunner, -} from "../../messaging/provider-profile"; +} from "../../adapters/openshell/provider-profile"; -/** OpenShell provider type registered for every OpenAI-surface inference route. */ -export const OPENAI_GATEWAY_PROVIDER_TYPE = "openai"; +export { OPENAI_GATEWAY_PROVIDER_TYPE } from "../../adapters/openshell/provider-profile"; export type InferenceProviderProfileDeps = { readonly runOpenshell: EndpointlessProviderProfileRunner; @@ -43,54 +40,3 @@ export function ensureOpenAiInferenceProviderProfile(deps: InferenceProviderProf const exit = deps.exit ?? ((code: number) => process.exit(code)); return exit(1); } - -export type OpenAiProviderProfileCheck = - | { readonly ok: true } - | { readonly ok: false; readonly messages: readonly string[] }; - -/** - * Result-returning variant for callers that report failure through an - * `UpsertProviderResult` instead of an injected exit, such as the recovered - * gateway-credential reuse path. - */ -export function checkOpenAiInferenceProviderProfile(deps: { - readonly runOpenshell: EndpointlessProviderProfileRunner; - readonly root?: string; -}): OpenAiProviderProfileCheck { - const result = ensureEndpointlessProviderProfile({ - profileId: OPENAI_GATEWAY_PROVIDER_TYPE, - inferenceCapable: true, - profilePath: endpointlessProviderProfilePath( - deps.root ?? REPOSITORY_ROOT, - OPENAI_GATEWAY_PROVIDER_TYPE, - ), - runOpenshell: deps.runOpenshell, - }); - if (result.ok) return { ok: true }; - - if (result.reason === "import-failed") { - return { - ok: false, - messages: [ - `\n ✗ OpenShell could not import the checked-in '${OPENAI_GATEWAY_PROVIDER_TYPE}' inference provider profile.`, - " Confirm the NemoClaw checkout is complete, then re-run onboarding.", - ], - }; - } - if (result.reason === "export-failed") { - return { - ok: false, - messages: [ - `\n ✗ OpenShell provider profile '${OPENAI_GATEWAY_PROVIDER_TYPE}' already exists but could not be read for validation.`, - " Repair or remove that profile, then re-run onboarding.", - ], - }; - } - return { - ok: false, - messages: [ - `\n ✗ OpenShell provider profile '${OPENAI_GATEWAY_PROVIDER_TYPE}' already exists but does not match NemoClaw's endpointless inference contract.`, - " Remove the conflicting profile, then re-run onboarding.", - ], - }; -} diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 5cdb61b074e..086d1b7a3b8 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -125,7 +125,7 @@ runtime mutation | **Managed snapshot clone handoff and provider transaction (internal and dormant)** — `prepareManagedWorkloadCloneHandoff`; `prepareManagedCloneProviderTransaction` | The current source registry row owns mutable operator intent; the selected snapshot owns immutable managed-workload and provider-runtime history. Handoff preparation proves the selected runtime provider and its `clone` capability, exact current registry generation and live-identity fingerprint, snapshot/source workload equivalence, snapshot runtime generation, and the state layer's selected-manifest/payload digest. It rebinds the secret-free startup profile, messaging intent, dashboard identity, and provider-owned contributions for OpenClaw, Hermes, or DCode without a central Podman-specific switch. Provider preparation then resolves active application bindings plus provider-contributed bindings, treating a live exact provider as reusable only when the destination registry independently proves that same logical binding. | The handoff and provider plan are inert. The internal materializer can create only bindings proven absent at preflight; it never updates or deletes an existing destination-owned provider. Immediately before each create it revalidates the source and optional destination registry rows plus the exact `SnapshotRestoreAuthority`. Production snapshot restore does not invoke this transaction and continues to reject cross-sandbox managed-image restore through `rejectManagedSnapshotCloneUntilRebind`; no user-visible clone support is advertised. | Both plans are deeply frozen and secret-free. A successful create produces an exact process-local ownership receipt; a non-zero create reconciled to an exact provider remains ambiguous and unowned. The receipt ledger remembers completed cleanup so a repeated cleanup cannot delete a later same-name provider. Raw credentials exist only in the explicit apply environment and one OpenShell child environment. | Failure rolls back only providers confirmed created by the exact in-process receipt, preserves collisions and ambiguous creates, reports incomplete cleanup for retry, and never rewrites a reused provider. `src/lib/onboard/managed-workload-clone-handoff.test.ts`, `src/lib/onboard/managed-startup-clone-rebinder.test.ts`, and `src/lib/actions/sandbox/snapshot-managed-clone-handoff-dormancy.test.ts` cover the all-agent, Docker/MXC-style provider, canonical-name, and fail-closed boundaries; provider transaction tests cover race, force-replace, disappearing-credential, rollback, and idempotent cleanup. This PR intentionally covers only the dormant contract. Epic [#7744](https://github.com/NVIDIA/NemoClaw/issues/7744) tracks destination creation/bootstrap, filesystem mutation-edge invocation, Hermes broker activation, durable recovery, protected E2E, and user-visible activation. | | **Channel add/remove/start/stop** — `addSandboxChannel`, `removeSandboxChannel`, `sandboxChannelsSetEnabled` in `policy-channel.ts` | Add compiles and merges a manifest-derived channel delta with `MessagingWorkflowPlanner`. Start, stop, and remove transform the registry plan and rehydrate executable render/build/runtime/forward details from current manifests. | Token-backed add can mutate gateway credentials before policy and plan persistence; QR/in-sandbox-auth add skips that credential upsert. Start persists the enabled plan before policy; stop persists the disabled plan before the rebuild prompt. Remove clears QR-backed durable state when applicable, detaches gateway/bridge state, removes policy, then persists the plan. A queued rebuild has a separate delete boundary. | The compact registry messaging plan is authoritative; render/build/runtime/state/health entries and nested host-forward details are rehydrated rather than persisted. Session policy-preset sync is best-effort, and channel mutations do not rewrite `Session.messagingPlan`. Raw tokens stay in process/gateway bindings. | `rollbackChannelAdd`, re-disable after failed start, and fail-closed QR-state cleanup provide partial compensation. Covered by `policy-channel*.test.ts`, `workflow-planner.test.ts`, and channel integration tests. Gaps: channel add has a separate `--force` conflict policy; add/remove effects can precede plan persistence, and persistence failures are not fully rolled back. | | **Provider, model, or credential-binding change** — `runInferenceSet` | CLI intent plus registry/session metadata. Target resolution and OpenShell preparation occur before locking. The target is re-resolved in the mutating phase under the sandbox lifecycle and timer-bound shields locks; that phase validates provider/model syntax, selected agent, shields state, and local reachability before the first write. | First mutation is the gateway route, then a minimal registry write, API-family/config resolution, registry refresh, best-effort config/hash sync, matching-session update, and audit. An OpenClaw API-family change can then restart the managed gateway after the shields lock is released but while the outer sandbox lock remains held. No sandbox deletion. | Registry and matching session store logical provider/model/credential-environment metadata. Audit records the action, sandbox, and reason rather than credentials; raw values remain gateway-bound. | Forward-only; no rollback. `rebuild` is the repair path for degraded state. Covered by `inference-set*.test.ts`. Gap: several stores can diverge after a mid-sequence failure. | -| **Credential rotation** — `configRotateToken` in `src/lib/sandbox/config.ts` | A session with `credentialEnv` selects the provider and binding. A non-null different `sandboxName` is rejected, but a legacy/null session name is accepted for the requested sandbox. The new value comes from a named environment variable, stdin, or a secret prompt; it is trimmed, then rejected when empty or still containing internal whitespace. | `saveCredential` first stages the value in the current process. OpenShell provider update is the first external mutation, with provider create as a fallback; audit follows. No sandbox deletion. | The logical binding is unchanged, so session and registry are not rewritten. The raw value exists only in process memory/environment and the gateway provider; audit records action/sandbox/reason without the value. | No rollback after a successful provider update; an audit failure can report failure after the credential is already active. Covered by the rotate-token cases in `test/security/config-set-nested-ssrf.test.ts`. Gap: a null-name legacy session is not strongly bound to the requested sandbox. | +| **Credential rotation** — `configRotateToken` in `src/lib/sandbox/config.ts`; `rotateSandboxToken` in `src/lib/sandbox/config-rotate-token.ts` | A session with `credentialEnv` selects the provider and binding. A non-null different `sandboxName` is rejected, but a legacy/null session name is accepted for the requested sandbox. The new value comes from a named environment variable, stdin, or a secret prompt; it is trimmed, then rejected when empty or still containing internal whitespace. | An OpenAI provider profile is validated before credential staging. When that profile is missing, its import is the first external mutation. `saveCredential` then stages the value in the current process. OpenShell provider update follows, with provider create as a fallback; audit is last. Other provider types begin with `saveCredential`. No sandbox deletion. | The logical binding is unchanged, so session and registry are not rewritten. The raw value exists only in process memory/environment and the gateway provider; audit records action/sandbox/reason without the value. | Profile validation or import failure stops credential staging and provider mutation. No rollback follows a successful profile import or provider update; an audit failure can report failure after the credential is already active. Covered by `test/security/config-rotate-token-provider-profile.test.ts` and the rotate-token case in `test/security/config-set-nested-ssrf.test.ts`. Gap: a null-name legacy session is not strongly bound to the requested sandbox. | | **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers can stop an existing forward and start its replacement in place after readiness, without recreating the sandbox. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, gateway provider state, and shields audit. An interrupted onboarding session records the selected resource values or an explicit OpenShell-default choice; the resolved create intent remains process-local. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution effect transaction/checkpoint. | ## Durable resumed recreate journal diff --git a/src/lib/onboard/machine/handlers/sandbox-checkpoint-crash-recovery.test.ts b/src/lib/onboard/machine/handlers/sandbox-checkpoint-crash-recovery.test.ts index 119fed87687..2d45cc579bb 100644 --- a/src/lib/onboard/machine/handlers/sandbox-checkpoint-crash-recovery.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-checkpoint-crash-recovery.test.ts @@ -70,6 +70,17 @@ function crashedCheckpoint(overrides: Partial = {}): OnboardC type StubbedRunOpenshellResult = { status: number; stdout: string; stderr: string }; const OK_RESULT: StubbedRunOpenshellResult = { status: 0, stdout: "", stderr: "" }; +const EXACT_MESSAGING_PROFILE: StubbedRunOpenshellResult = { + status: 0, + stdout: JSON.stringify({ + id: "nemoclaw-mcp-v1", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: false, + }), + stderr: "", +}; function fakeGatewayRunOpenshell() { const createdProviders = new Map(); @@ -105,6 +116,7 @@ function fakeGatewayRunOpenshell() { }; const handlersByAction: Record StubbedRunOpenshellResult> = { + profile: () => EXACT_MESSAGING_PROFILE, get: handleGet, create: handleCreate, update: () => OK_RESULT, diff --git a/src/lib/onboard/providers.test.ts b/src/lib/onboard/providers.test.ts index 058d3943e3a..a41b698bc71 100644 --- a/src/lib/onboard/providers.test.ts +++ b/src/lib/onboard/providers.test.ts @@ -38,6 +38,14 @@ const DISCORD_STATIC_PROFILE_EXPORT = JSON.stringify({ inference_capable: false, }); +const MESSAGING_ENDPOINTLESS_PROFILE_EXPORT = JSON.stringify({ + id: "nemoclaw-mcp-v1", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: false, +}); + const { HOSTED_INFERENCE_ENDPOINT_URL, HOSTED_INFERENCE_MODEL, @@ -693,6 +701,10 @@ describe("onboard provider helpers", () => { (command, options) => { calls.push({ command, env: options?.env }); switch (command[1]) { + case "profile": + return command.includes("export") + ? { status: 1, stdout: "", stderr: "provider profile not found" } + : { status: 0, stdout: "", stderr: "" }; case "get": return created ? { @@ -714,19 +726,19 @@ describe("onboard provider helpers", () => { expect(providers).toEqual(["alpha-discord-bridge"]); expect(calls.map(({ command }) => command.join(" "))).toEqual([ + "provider profile export nemoclaw-mcp-v1 --output json", expect.stringMatching(/^provider profile import --file .*nemoclaw-mcp-v1\.yaml$/), "provider get alpha-discord-bridge", "provider create --name alpha-discord-bridge --type nemoclaw-mcp-v1 --credential DISCORD_BOT_TOKEN", "provider get alpha-discord-bridge", ]); - expect(calls[2]?.env).toEqual({ DISCORD_BOT_TOKEN: credential }); + expect(calls[3]?.env).toEqual({ DISCORD_BOT_TOKEN: credential }); expect(calls.flatMap(({ command }) => command)).not.toContain(credential); }); it("rejects credential-free reuse when the messaging profile is incompatible (#9875)", () => { const commands: string[] = []; const profileResults: Record = { - import: { status: 1, stdout: "", stderr: "profile already exists" }, export: { status: 0, stdout: JSON.stringify({ @@ -758,10 +770,7 @@ describe("onboard provider helpers", () => { { bestEffort: true }, ), ).toThrow(/does not match NemoClaw's endpointless messaging credential contract/u); - expect(commands).toEqual([ - expect.stringMatching(/^provider profile import --file /u), - "provider profile export nemoclaw-mcp-v1 --output json", - ]); + expect(commands).toEqual(["provider profile export nemoclaw-mcp-v1 --output json"]); }); it.each([ @@ -783,7 +792,7 @@ describe("onboard provider helpers", () => { (command) => { commands.push(command.join(" ")); return command[1] === "profile" - ? { status: 0 } + ? { status: 0, stdout: MESSAGING_ENDPOINTLESS_PROFILE_EXPORT } : { status: 0, stdout: `Name: ${name}\nType: generic\nCredential keys: ${credentialKey}\nConfig keys: \n`, @@ -802,7 +811,11 @@ describe("onboard provider helpers", () => { stdout: "", stderr: 'Error: status: Unavailable, message: "provider not found"', }; - const profileResult = { status: 0, stdout: "", stderr: "" }; + const profileResult = { + status: 0, + stdout: MESSAGING_ENDPOINTLESS_PROFILE_EXPORT, + stderr: "", + }; expect(() => upsertMessagingProviders( @@ -816,7 +829,7 @@ describe("onboard provider helpers", () => { ], (command) => { const joined = command.join(" "); - const result = joined.startsWith("provider profile import ") + const result = joined.startsWith("provider profile ") ? profileResult : new Map([["provider get alpha-discord-bridge", getResult]]).get(joined); mutations.push(...(result ? [] : [joined])); @@ -847,6 +860,7 @@ describe("onboard provider helpers", () => { commands.push(command.join(" ")); switch (command[1]) { case "profile": + return { status: 0, stdout: MESSAGING_ENDPOINTLESS_PROFILE_EXPORT }; case "delete": return { status: 0 }; case "create": @@ -864,7 +878,7 @@ describe("onboard provider helpers", () => { expect(providers).toEqual([name]); expect(commands).toEqual([ - expect.stringMatching(/^provider profile import --file /u), + "provider profile export nemoclaw-mcp-v1 --output json", `provider get ${name}`, `provider delete ${name}`, `provider create --name ${name} --type nemoclaw-mcp-v1 --credential ${credentialKey}`, diff --git a/src/lib/onboard/sandbox-create/provider-publication.test.ts b/src/lib/onboard/sandbox-create/provider-publication.test.ts index 741f0a9e8ae..000bd04506a 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.test.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.test.ts @@ -21,6 +21,17 @@ const exactState: ProviderState = { credentialKey: "TELEGRAM_BOT_TOKEN", configKeys: "", }; +const exactProfile = { + status: 0, + stdout: JSON.stringify({ + id: MESSAGING_CREDENTIAL_PROVIDER_TYPE, + credentials: [], + endpoints: [], + binaries: [], + inference_capable: false, + }), + stderr: "", +}; function providerOutput(name: string, state: ProviderState): string { return [ @@ -36,7 +47,7 @@ function createHarness( initialState: ProviderState | null = exactState, postUpdateState: ProviderState = initialState || exactState, profileImportResult = { status: 0, stdout: "", stderr: "" }, - profileExportResult = { status: 0, stdout: "", stderr: "" }, + profileExportResult = exactProfile, ) { let updated = false; const cleanupCreateSources = vi.fn(); @@ -116,9 +127,10 @@ describe("sandbox provider preparation", () => { "profile", "-g", "nemoclaw", - "import", - "--file", - expect.stringContaining("nemoclaw-mcp-v1.yaml"), + "export", + MESSAGING_CREDENTIAL_PROVIDER_TYPE, + "--output", + "json", ], ["provider", "get", "-g", "nemoclaw", providerName], ["provider", "update", "-g", "nemoclaw", providerName], @@ -167,9 +179,10 @@ describe("sandbox provider preparation", () => { "profile", "-g", "nemoclaw", - "import", - "--file", - expect.stringContaining("nemoclaw-mcp-v1.yaml"), + "export", + MESSAGING_CREDENTIAL_PROVIDER_TYPE, + "--output", + "json", ], ["provider", "get", "-g", "nemoclaw", providerName], ["provider", "update", "-g", "nemoclaw", providerName], @@ -233,9 +246,14 @@ describe("sandbox provider preparation", () => { ).toThrowError(/does not match NemoClaw's endpointless messaging credential contract/u); expect( harness.runOpenshell.mock.calls.some(([args]) => - args.join(" ").startsWith("provider profile -g nemoclaw import"), + args.join(" ").startsWith("provider profile -g nemoclaw export"), ), ).toBe(true); + expect( + harness.runOpenshell.mock.calls.some(([args]) => + args.join(" ").startsWith("provider profile -g nemoclaw import"), + ), + ).toBe(false); expect( harness.runOpenshell.mock.calls.some( ([args]) => args.slice(0, 2).join(" ") === "provider update", diff --git a/src/lib/onboard/setup-inference-gateway-scope.test.ts b/src/lib/onboard/setup-inference-gateway-scope.test.ts index 7d06e0a808e..7ea7656edd5 100644 --- a/src/lib/onboard/setup-inference-gateway-scope.test.ts +++ b/src/lib/onboard/setup-inference-gateway-scope.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { createInferenceRouteHelpers } from "./inference-route"; import { bindGatewayUpsertProvider, + createRoutedResumeProviderUpsert, createGatewayScopedOpenshellRunner, scopeGatewayOpenshellArgs, selectGatewayForFollowupOrExit, @@ -70,20 +71,22 @@ describe("gateway-scoped onboarding OpenShell commands", () => { it.each([ ["--gateway-endpoint", "https://other.example.test"], ["--gateway-endpoint=https://other.example.test"], - ])("rejects an explicit endpoint override before the payload separator: %j", (...endpointArgs) => { - expect(() => - scopeGatewayOpenshellArgs(["provider", "get", ...endpointArgs, "openai-api"], GATEWAY), - ).toThrow(/--gateway-endpoint may bypass the gateway recorded/); - }); + ])( + "rejects an explicit endpoint override before the payload separator: %j", + (...endpointArgs) => { + expect(() => + scopeGatewayOpenshellArgs(["provider", "get", ...endpointArgs, "openai-api"], GATEWAY), + ).toThrow(/--gateway-endpoint may bypass the gateway recorded/); + }, + ); - it.each([ - ["-g", GATEWAY], - ["--gateway", GATEWAY], - [`--gateway=${GATEWAY}`], - ])("accepts an identical existing target: %j", (...gatewayArgs) => { - const command = ["provider", "list", ...gatewayArgs]; - expect(scopeGatewayOpenshellArgs(command, GATEWAY)).toEqual(command); - }); + it.each([["-g", GATEWAY], ["--gateway", GATEWAY], [`--gateway=${GATEWAY}`]])( + "accepts an identical existing target: %j", + (...gatewayArgs) => { + const command = ["provider", "list", ...gatewayArgs]; + expect(scopeGatewayOpenshellArgs(command, GATEWAY)).toEqual(command); + }, + ); it("rejects a conflicting, duplicate, missing, or selection-based target", () => { expect(() => @@ -134,6 +137,103 @@ describe("gateway-scoped onboarding OpenShell commands", () => { ); }); + it("registers the OpenAI profile before a routed resume provider mutation (#10155)", () => { + const events: string[] = []; + const results = [ + { + status: 1, + stdout: "", + stderr: "Error: status: 'NotFound', message: \"provider profile not found\"", + }, + { status: 0, stdout: "", stderr: "" }, + ]; + const run = vi.fn((args: string[]) => { + events.push(args.join(" ")); + return results.shift()!; + }); + const upsert = vi.fn(() => { + events.push("provider mutation"); + return { ok: true }; + }); + const reupsertRoutedProvider = createRoutedResumeProviderUpsert({ + upsertProvider: upsert, + runGatewayOpenshell: createGatewayScopedOpenshellRunner(run, GATEWAY), + hydrateCredentialEnv: () => "test-secret", + error: vi.fn(), + exitProcess: (code): never => { + throw new Error(`exit ${code}`); + }, + }); + + expect( + reupsertRoutedProvider( + GATEWAY, + "nvidia-router", + "http://host.openshell.internal:4000/v1", + "NVIDIA_INFERENCE_API_KEY", + ), + ).toEqual({ + ok: true, + endpointUrl: "http://host.openshell.internal:4000/v1", + message: undefined, + status: undefined, + }); + + expect(events[0]).toBe(`provider profile -g ${GATEWAY} export openai --output json`); + expect(events[1]).toMatch( + new RegExp(`^provider profile -g ${GATEWAY} import --file .*openai\\.yaml$`, "u"), + ); + expect(events[2]).toBe("provider mutation"); + expect(upsert).toHaveBeenCalledWith( + "nvidia-router", + "openai", + "NVIDIA_INFERENCE_API_KEY", + "http://host.openshell.internal:4000/v1", + { NVIDIA_INFERENCE_API_KEY: "test-secret" }, + GATEWAY, + ); + }); + + it("blocks a routed resume provider mutation when OpenAI profile import fails (#10155)", () => { + const sensitiveDiagnostic = "unauthorized nvapi-TEST-NOT-A-REAL-VALUE"; + const results = [ + { + status: 1, + stdout: "", + stderr: "Error: status: 'NotFound', message: \"provider profile not found\"", + }, + { status: 13, stdout: "", stderr: sensitiveDiagnostic }, + ]; + const run = vi.fn(() => results.shift()!); + const upsert = vi.fn(() => ({ ok: true })); + const error = vi.fn(); + const reupsertRoutedProvider = createRoutedResumeProviderUpsert({ + upsertProvider: upsert, + runGatewayOpenshell: createGatewayScopedOpenshellRunner(run, GATEWAY), + hydrateCredentialEnv: () => "test-secret", + error, + exitProcess: (code): never => { + throw new Error(`exit ${code}`); + }, + }); + + expect(() => + reupsertRoutedProvider( + GATEWAY, + "nvidia-router", + "http://host.openshell.internal:4000/v1", + "NVIDIA_INFERENCE_API_KEY", + ), + ).toThrow("exit 1"); + + expect(upsert).not.toHaveBeenCalled(); + expect(run).toHaveBeenCalledTimes(2); + const output = error.mock.calls.flat().join("\n"); + expect(output).toContain("OpenShell could not import"); + expect(output).toContain("available and authorized"); + expect(output).not.toContain(sensitiveDiagnostic); + }); + it("selects the managed gateway for follow-up commands and fails closed on error", () => { const run = vi.fn().mockReturnValueOnce({ status: 0 }).mockReturnValueOnce({ status: 17 }); const error = vi.fn(); diff --git a/src/lib/onboard/setup-inference-route-containment.test.ts b/src/lib/onboard/setup-inference-route-containment.test.ts index 973c59d2261..0790862dcd2 100644 --- a/src/lib/onboard/setup-inference-route-containment.test.ts +++ b/src/lib/onboard/setup-inference-route-containment.test.ts @@ -55,7 +55,19 @@ describe("onboard shared gateway route containment", () => { await operation(), step: vi.fn(), getGatewayName: () => "nemoclaw", - runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + runOpenshell: vi.fn((args: string[]) => ({ + status: 0, + stdout: args.includes("export") + ? JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, + }) + : "", + stderr: "", + })), updateSandbox: vi.fn(() => true), upsertProvider: vi.fn(() => ({ ok: true })), verifyInferenceRoute: vi.fn(), diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index c5598b881c6..d7a3deeba7b 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -9,9 +9,15 @@ import { bindOpenAiProviderProfile, createProviderReviewDeps } from "./setup-inf describe("bindOpenAiProviderProfile", () => { it("imports the profile immediately before an OpenAI provider upsert", () => { const events: string[] = []; + const profileEvents = ["profile-export", "profile-import"]; + const profileResults = [ + { status: 1, stdout: "", stderr: "provider profile not found" }, + { status: 0, stdout: "", stderr: "" }, + ]; + let profileIndex = 0; const runOpenshell = vi.fn(() => { - events.push("profile"); - return { status: 0, stdout: "", stderr: "" }; + events.push(profileEvents[profileIndex]!); + return profileResults[profileIndex++]!; }); const upsertProvider = vi.fn(() => { events.push("upsert"); @@ -36,10 +42,26 @@ describe("bindOpenAiProviderProfile", () => { ), ).toEqual({ ok: true }); - expect(events).toEqual(["profile", "upsert"]); - expect(runOpenshell).toHaveBeenCalledWith( + expect(events).toEqual(["profile-export", "profile-import", "upsert"]); + expect(runOpenshell).toHaveBeenNthCalledWith( + 1, + ["provider", "profile", "export", "openai", "--output", "json"], + { + ignoreError: true, + suppressOutput: true, + timeout: 30_000, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + expect(runOpenshell).toHaveBeenNthCalledWith( + 2, ["provider", "profile", "import", "--file", expect.stringMatching(/openai\.yaml$/u)], - { ignoreError: true, stdio: ["ignore", "pipe", "pipe"] }, + { + ignoreError: true, + suppressOutput: true, + timeout: 30_000, + stdio: ["ignore", "pipe", "pipe"], + }, ); }); @@ -70,21 +92,22 @@ describe("bindOpenAiProviderProfile", () => { it.each([ { reason: "import failure", - results: [{ status: 1, stdout: "", stderr: "sensitive-import-output" }], + results: [ + { status: 1, stdout: "", stderr: "provider profile not found" }, + { status: 1, stdout: "", stderr: "sensitive-import-output" }, + ], expected: "could not import the checked-in 'openai' inference provider profile", + guidance: "OpenShell is available and authorized", }, { reason: "export failure", - results: [ - { status: 1, stdout: "", stderr: "provider profile already exists" }, - { status: 1, stdout: "sensitive-export-output", stderr: "" }, - ], - expected: "already exists but could not be read for validation", + results: [{ status: 1, stdout: "sensitive-export-output", stderr: "" }], + expected: "could not be read for validation", + guidance: "OpenShell is available, authorized, and the profile is readable", }, { reason: "incompatible profile", results: [ - { status: 1, stdout: "", stderr: "provider profile already exists" }, { status: 0, stdout: JSON.stringify({ @@ -98,8 +121,9 @@ describe("bindOpenAiProviderProfile", () => { }, ], expected: "does not match NemoClaw's endpointless inference contract", + guidance: "Remove the conflicting profile", }, - ])("fails closed with fixed guidance for $reason", ({ results, expected }) => { + ])("fails closed with fixed guidance for $reason", ({ results, expected, guidance }) => { let resultIndex = 0; const runOpenshell = vi.fn(() => results[resultIndex++]!); const upsertProvider = vi.fn(() => ({ ok: true })); @@ -126,6 +150,7 @@ describe("bindOpenAiProviderProfile", () => { expect(upsertProvider).not.toHaveBeenCalled(); const output = error.mock.calls.flat().join("\n"); expect(output).toContain(expected); + expect(output).toContain(guidance); expect(output).not.toMatch(/sensitive-(?:import|export|profile)-/u); }); }); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 8b0d7b67834..bfec5b52c55 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -19,10 +19,7 @@ import { withModelRouterPortLifecycleLock, } from "../inference/gateway-route-mutation-lock"; import { getManagedVllmProviderBinding } from "../inference/local"; -import { - type OllamaModelHolder, - supersededOllamaModel, -} from "../inference/ollama/model-ownership"; +import { type OllamaModelHolder, supersededOllamaModel } from "../inference/ollama/model-ownership"; import { getOllamaProxyToken, persistAndProbeOllamaProxy, @@ -39,6 +36,10 @@ import type { Session } from "../state/onboard-session"; import { createSandboxHostLocalInferenceProvenance } from "../state/registry/host-local-inference"; import { shouldFrontOllamaWithProxy } from "./local-inference-topology"; import { resolveModelRouterPort } from "./model-router"; +import { + type RoutedProviderDeps, + upsertRoutedProvider as upsertRoutedInferenceProvider, +} from "./routed-inference"; export { assertNoOpenShellGatewayEndpointOverride }; @@ -306,6 +307,37 @@ export function bindOpenAiProviderProfile( }; } +export function createRoutedResumeProviderUpsert(deps: { + upsertProvider: SetupInferenceDeps["upsertProvider"]; + runGatewayOpenshell: InferenceProviderProfileDeps["runOpenshell"]; + hydrateCredentialEnv: RoutedProviderDeps["hydrateCredentialEnv"]; + error?: CommonDeps["error"]; + exitProcess?: CommonDeps["exitProcess"]; +}) { + return ( + gatewayName: string, + provider: string, + endpointUrl: string | null, + credentialEnv: string | null, + ) => { + const result = upsertRoutedInferenceProvider(provider, endpointUrl, credentialEnv, { + upsertProvider: bindOpenAiProviderProfile( + bindGatewayUpsertProvider(deps.upsertProvider, gatewayName), + deps.runGatewayOpenshell, + deps.error ?? console.error, + deps.exitProcess ?? ((code) => process.exit(code)), + ), + hydrateCredentialEnv: deps.hydrateCredentialEnv, + }); + return { + ok: result.ok, + endpointUrl: result.endpointUrl, + message: result.result.message, + status: result.result.status, + }; + }; +} + export function selectGatewayForFollowupOrExit( gatewayName: string, runOpenshell: SetupInferenceDeps["runOpenshell"], @@ -508,8 +540,7 @@ function releaseSupersededOllamaModel( // still owns its model. if (!previous || result.retry) return; try { - const withOwnershipLock = - deps.withOllamaModelOwnershipLock ?? withOllamaModelOwnershipLock; + const withOwnershipLock = deps.withOllamaModelOwnershipLock ?? withOllamaModelOwnershipLock; withOwnershipLock(() => { const peers = deps.listSandboxes?.().sandboxes ?? []; const superseded = supersededOllamaModel(previous, nextModel, peers); @@ -1068,18 +1099,17 @@ export function createSetupInference( // happens before the lock opens, so a serialized re-onboard can neither // replace the row under the read nor select the captured model before // this cleanup runs. - const mutateGatewayRouteAndReleaseSupersededModel = - async (): Promise => { - let previousSandbox: OllamaModelHolder | null = null; - try { - previousSandbox = sandboxName ? (deps.getSandbox?.(sandboxName) ?? null) : null; - } catch { - /* An unreadable registry skips GPU release; it must not fail onboarding. */ - } - const result = await mutateGatewayRoute(); - releaseSupersededOllamaModel(previousSandbox, model, result, deps); - return result; - }; + const mutateGatewayRouteAndReleaseSupersededModel = async (): Promise => { + let previousSandbox: OllamaModelHolder | null = null; + try { + previousSandbox = sandboxName ? (deps.getSandbox?.(sandboxName) ?? null) : null; + } catch { + /* An unreadable registry skips GPU release; it must not fail onboarding. */ + } + const result = await mutateGatewayRoute(); + releaseSupersededOllamaModel(previousSandbox, model, result, deps); + return result; + }; return sandboxName ? deps.withSandboxMutationLock(sandboxName, mutateGatewayRouteAndReleaseSupersededModel) : mutateGatewayRouteAndReleaseSupersededModel(); diff --git a/src/lib/sandbox/config-rotate-token.ts b/src/lib/sandbox/config-rotate-token.ts new file mode 100644 index 00000000000..7260c122899 --- /dev/null +++ b/src/lib/sandbox/config-rotate-token.ts @@ -0,0 +1,156 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { checkOpenAiInferenceProviderProfile } from "../adapters/openshell/provider-profile"; +import type { Session } from "../state/onboard-session"; + +export interface RotateTokenOpts { + fromEnv?: string | null; + fromStdin?: boolean; +} + +type RotateTokenFailure = (lines: string | readonly string[], exitCode?: number) => never; + +type RotateTokenSession = Pick & { + readonly providerType?: string; +}; + +export function loadRotateTokenSession(): RotateTokenSession | null { + const { loadSession } = + require("../state/onboard-session") as typeof import("../state/onboard-session"); + return loadSession(); +} + +export type RotateTokenDeps = { + readonly appendAuditEntry: typeof import("../shields/audit").appendAuditEntry; + readonly captureOpenshellCommand: typeof import("../adapters/openshell/client").captureOpenshellCommand; + readonly fail: RotateTokenFailure; + readonly loadSession: () => RotateTokenSession | null; + readonly promptSecret: typeof import("../credentials/store").promptSecret; + readonly resolveAgentConfig: (sandboxName: string) => import("./agent-config").AgentConfigTarget; + readonly runOpenshellCommand: typeof import("../adapters/openshell/client").runOpenshellCommand; + readonly saveCredential: typeof import("../credentials/store").saveCredential; + readonly validateName: typeof import("../runner").validateName; +}; + +export async function rotateSandboxToken( + sandboxName: string, + opts: RotateTokenOpts, + deps: RotateTokenDeps, +): Promise { + deps.validateName(sandboxName, "sandbox name"); + + const session = deps.loadSession(); + if (!session || !session.credentialEnv) { + deps.fail([ + ` Cannot determine credential for sandbox '${sandboxName}'.`, + " No onboard session found with a credentialEnv.", + " Re-run: nemoclaw onboard --recreate-sandbox", + ]); + } + + if (session.sandboxName && session.sandboxName !== sandboxName) { + deps.fail(` Onboard session is for sandbox '${session.sandboxName}', not '${sandboxName}'.`); + } + + const target = deps.resolveAgentConfig(sandboxName); + const credentialEnv: string = session.credentialEnv; + const providerName: string = session.provider || "inference"; + + console.log(` Agent: ${target.agentName}`); + console.log(` Provider: ${providerName}`); + console.log(` Credential env: ${credentialEnv}`); + + let newToken: string | null = null; + if (opts.fromEnv) { + newToken = process.env[opts.fromEnv] || null; + if (!newToken) deps.fail(` Environment variable "${opts.fromEnv}" is not set or empty.`); + } else if (opts.fromStdin) { + newToken = await readStdin(); + } else { + newToken = await deps.promptSecret(` New ${credentialEnv} value: `); + } + + if (!newToken || !newToken.trim()) deps.fail(" Token cannot be empty."); + newToken = newToken.trim(); + if (/\s/.test(newToken)) deps.fail(" Token contains whitespace. This is likely a paste error."); + + const binary = getOpenshellBinary(); + const providerType = session.providerType || "generic"; + if (providerType === "openai") { + const profile = checkOpenAiInferenceProviderProfile({ + runOpenshell: (args, options) => + deps.captureOpenshellCommand(binary, args, { + ignoreError: true, + includeStreams: true, + timeout: options?.timeout, + }), + }); + if (!profile.ok) deps.fail(profile.messages); + } + + deps.saveCredential(credentialEnv, newToken); + + console.log(" Updating openshell provider..."); + const result = deps.runOpenshellCommand( + binary, + ["provider", "update", providerName, "--credential", credentialEnv], + { + env: { [credentialEnv]: newToken }, + ignoreError: true, + errorLine: console.error, + exit: (code: number) => process.exit(code), + }, + ); + + if (result.status !== 0) { + const createResult = deps.runOpenshellCommand( + binary, + [ + "provider", + "create", + "--name", + providerName, + "--type", + providerType, + "--credential", + credentialEnv, + ], + { + env: { [credentialEnv]: newToken }, + ignoreError: true, + errorLine: console.error, + exit: (code: number) => process.exit(code), + }, + ); + if (createResult.status !== 0) + deps.fail(" Failed to update provider. You may need to re-onboard."); + } + + deps.appendAuditEntry({ + action: "rotate_token", + sandbox: sandboxName, + timestamp: new Date().toISOString(), + reason: `rotate-token ${target.agentName}:${credentialEnv}`, + }); + + const lastFour = newToken.length > 4 ? newToken.slice(-4) : "****"; + console.log(` Token rotated: ****${lastFour}`); + console.log(""); + console.log(" The new credential is active immediately for new sandbox requests."); +} + +function getOpenshellBinary(): string { + return process.env.NEMOCLAW_OPENSHELL_BIN || "openshell"; +} + +/** Read all data from stdin until EOF. */ +export function readStdin(): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + process.stdin.on("data", (chunk: Buffer) => chunks.push(chunk)); + process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8").trim())); + process.stdin.on("error", reject); + process.stdin.resume(); + }); +} diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index b2bec0175bc..7ac7771fae4 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -64,6 +64,11 @@ const { OPENSHELL_OPERATION_TIMEOUT_MS, }: typeof import("../adapters/openshell/timeouts") = require("../adapters/openshell/timeouts"); const { redactFull }: typeof import("../security/redact") = require("../security/redact"); +const { + loadRotateTokenSession, + readStdin, + rotateSandboxToken, +}: typeof import("./config-rotate-token") = require("./config-rotate-token"); type ConfigObject = import("../security/credential-filter").ConfigObject; type ConfigValue = import("../security/credential-filter").ConfigValue; @@ -1409,137 +1414,21 @@ async function configSet(sandboxName: string, opts: ConfigSetOpts = {}): Promise // config rotate-token // --------------------------------------------------------------------------- -interface RotateTokenOpts { - fromEnv?: string | null; - fromStdin?: boolean; -} +type RotateTokenOpts = import("./config-rotate-token").RotateTokenOpts; async function configRotateToken(sandboxName: string, opts: RotateTokenOpts = {}): Promise { - validateName(sandboxName, "sandbox name"); - - // 1. Determine which provider and credentialEnv the sandbox uses. - // Load the onboard session and verify it matches this sandbox. - const { loadSession } = require("../state/onboard-session"); - const session = loadSession(); - - if (!session || !session.credentialEnv) { - configFail([ - ` Cannot determine credential for sandbox '${sandboxName}'.`, - " No onboard session found with a credentialEnv.", - " Re-run: nemoclaw onboard --recreate-sandbox", - ]); - } - - if (session.sandboxName && session.sandboxName !== sandboxName) { - configFail(` Onboard session is for sandbox '${session.sandboxName}', not '${sandboxName}'.`); - } - - const target = resolveAgentConfig(sandboxName); - const credentialEnv: string = session.credentialEnv; - const providerName: string = session.provider || "inference"; - - console.log(` Agent: ${target.agentName}`); - console.log(` Provider: ${providerName}`); - console.log(` Credential env: ${credentialEnv}`); - - // 2. Read new token - let newToken: string | null = null; - - if (opts.fromEnv) { - newToken = process.env[opts.fromEnv] || null; - if (!newToken) { - configFail(` Environment variable "${opts.fromEnv}" is not set or empty.`); - } - } else if (opts.fromStdin) { - newToken = await readStdin(); - } else { - const { promptSecret } = require("../credentials/store"); - newToken = await promptSecret(` New ${credentialEnv} value: `); - } - - if (!newToken || !newToken.trim()) { - configFail(" Token cannot be empty."); - } - - newToken = newToken.trim(); - - // 3. Validate — no whitespace in token - if (/\s/.test(newToken)) { - configFail(" Token contains whitespace. This is likely a paste error."); - } - - // 4. Stage the new value in the current process so the openshell update - // that follows can read it via --credential . The OpenShell - // gateway becomes the system of record once the update succeeds. - const { saveCredential } = require("../credentials/store"); - saveCredential(credentialEnv, newToken); - - // 5. Update the openshell provider - console.log(" Updating openshell provider..."); - const binary = getOpenshellBinary(); - const result = runOpenshellCommand( - binary, - ["provider", "update", providerName, "--credential", credentialEnv], - { - env: { [credentialEnv]: newToken }, - ignoreError: true, - errorLine: console.error, - exit: (code: number) => process.exit(code), - }, - ); - - if (result.status !== 0) { - const providerType = session.providerType || "generic"; - const createResult = runOpenshellCommand( - binary, - [ - "provider", - "create", - "--name", - providerName, - "--type", - providerType, - "--credential", - credentialEnv, - ], - { - env: { [credentialEnv]: newToken }, - ignoreError: true, - errorLine: console.error, - exit: (code: number) => process.exit(code), - }, - ); - - if (createResult.status !== 0) { - configFail(" Failed to update provider. You may need to re-onboard."); - } - } - - // 6. Audit log - appendAuditEntry({ - action: "rotate_token", - sandbox: sandboxName, - timestamp: new Date().toISOString(), - reason: `rotate-token ${target.agentName}:${credentialEnv}`, - }); - - // 7. Output (redacted) - const lastFour = newToken.length > 4 ? newToken.slice(-4) : "****"; - console.log(` Token rotated: ****${lastFour}`); - console.log(""); - console.log(" The new credential is active immediately for new sandbox requests."); -} - -/** - * Read all data from stdin until EOF. - */ -function readStdin(): Promise { - return new Promise((resolve, reject) => { - const chunks: Buffer[] = []; - process.stdin.on("data", (chunk: Buffer) => chunks.push(chunk)); - process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8").trim())); - process.stdin.on("error", reject); - process.stdin.resume(); + const { promptSecret, saveCredential } = + require("../credentials/store") as typeof import("../credentials/store"); + return rotateSandboxToken(sandboxName, opts, { + appendAuditEntry, + captureOpenshellCommand, + fail: configFail, + loadSession: loadRotateTokenSession, + promptSecret, + resolveAgentConfig, + runOpenshellCommand, + saveCredential, + validateName, }); } diff --git a/test/agents/deepagents/deepagents-mcp-legacy-lifecycle.test.ts b/test/agents/deepagents/deepagents-mcp-legacy-lifecycle.test.ts index 2d7c075e5a1..18e5404d017 100644 --- a/test/agents/deepagents/deepagents-mcp-legacy-lifecycle.test.ts +++ b/test/agents/deepagents/deepagents-mcp-legacy-lifecycle.test.ts @@ -7,6 +7,8 @@ import path from "node:path"; import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { mockManagedEndpointlessProviderProfileRun } from "../../helpers/onboard-script-mocks.cjs"; + const mocks = vi.hoisted(() => ({ applyPresetContent: vi.fn(), executeGatewaySupervisorAction: vi.fn(), @@ -20,6 +22,7 @@ const mocks = vi.hoisted(() => ({ })); vi.mock("../../../src/lib/adapters/openshell/provider-command", () => ({ + OPENSHELL_OPERATION_TIMEOUT_MS: 30_000, runOpenshellProviderCommand: mocks.runOpenshellProviderCommand, })); @@ -116,8 +119,9 @@ beforeEach(() => { switch (true) { case command === "status --output json": return { status: 0, stdout: "ready", stderr: "" }; - case args[0] === "provider" && args[1] === "profile" && args[2] === "import": - return { status: 0, stdout: "Imported provider profile", stderr: "" }; + case args[0] === "provider" && args[1] === "profile": + return mockManagedEndpointlessProviderProfileRun(args) ?? + { status: 0, stdout: "Imported provider profile", stderr: "" }; case args[0] === "provider" && args[1] === "get": return providerExists ? { diff --git a/test/agents/hermes/hermes-mcp-startup-probe.test.ts b/test/agents/hermes/hermes-mcp-startup-probe.test.ts index f83398ad272..de2e5ab8d7c 100644 --- a/test/agents/hermes/hermes-mcp-startup-probe.test.ts +++ b/test/agents/hermes/hermes-mcp-startup-probe.test.ts @@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({ })); vi.mock("../../../src/lib/adapters/openshell/provider-command", () => ({ + OPENSHELL_OPERATION_TIMEOUT_MS: 30_000, runOpenshellProviderCommand: mocks.runOpenshellProviderCommand, })); diff --git a/test/cli/credentials-command.test.ts b/test/cli/credentials-command.test.ts index 5d4fe1d447d..e56fd36e044 100644 --- a/test/cli/credentials-command.test.ts +++ b/test/cli/credentials-command.test.ts @@ -15,6 +15,7 @@ vi.mock("../../src/lib/actions/global", () => ({ recoverNamedGatewayRuntime: vi.fn().mockResolvedValue({ recovered: true }), })); vi.mock("../../src/lib/adapters/openshell/provider-command", () => ({ + OPENSHELL_OPERATION_TIMEOUT_MS: 30_000, runOpenshellProviderCommand: vi.fn(), })); diff --git a/test/helpers/hermes-portable-ollama-test-harness.ts b/test/helpers/hermes-portable-ollama-test-harness.ts index 41798218114..ffbab50c439 100644 --- a/test/helpers/hermes-portable-ollama-test-harness.ts +++ b/test/helpers/hermes-portable-ollama-test-harness.ts @@ -171,6 +171,9 @@ export interface PortableGatewayProviderHarness { readonly setLookupFailure: (value: boolean) => void; readonly setMalformed: (value: boolean) => void; readonly setPresent: (value: boolean) => void; + readonly setProfileState: ( + value: "exact" | "missing" | "incompatible" | "import-failed", + ) => void; } export function createPortableGatewayProviderHarness( @@ -184,6 +187,7 @@ export function createPortableGatewayProviderHarness( let lookupFailure = false; let resourceVersion = 1; let credentialEnv = "NEMOCLAW_OLLAMA_PROXY_TOKEN"; + let profileState: "exact" | "missing" | "incompatible" | "import-failed" = "exact"; const calls: Array<{ readonly args: readonly string[]; readonly timeout: number }> = []; return Object.freeze({ calls: () => calls, @@ -213,9 +217,35 @@ export function createPortableGatewayProviderHarness( setPresent: (value: boolean) => { present = value; }, + setProfileState: (value: "exact" | "missing" | "incompatible" | "import-failed") => { + profileState = value; + }, run(args: string[], options: Parameters[1]) { calls.push(Object.freeze({ args: Object.freeze([...args]), timeout: options.timeout })); events.push(`openshell:${args.join(" ")}`); + if (args[0] === "provider" && args[1] === "profile" && args[2] === "export") { + if (profileState === "missing" || profileState === "import-failed") { + return { status: 1, stdout: "", stderr: "provider profile not found" }; + } + return { + status: 0, + stdout: JSON.stringify({ + id: "openai", + credentials: [], + endpoints: profileState === "exact" ? [] : ["https://example.invalid"], + binaries: [], + inference_capable: true, + }), + stderr: "", + }; + } + if (args[0] === "provider" && args[1] === "profile" && args[2] === "import") { + if (profileState === "import-failed") { + return { status: 1, stdout: "", stderr: "profile import failed" }; + } + profileState = "exact"; + return { status: 0, stdout: "", stderr: "" }; + } if (args[0] === "provider" && args[1] === "get") { if (lookupFailure) { return { status: 1, stdout: "", stderr: "gateway lookup failed" }; diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index 73b400b732c..9873d4d7e68 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -55,6 +55,47 @@ function providerNameAfterAction(args, providerIndex) { return args[firstArgument] === "-g" ? args[firstArgument + 2] : args[firstArgument]; } +function mockEndpointlessProviderProfileRun(command, profileId, inferenceCapable) { + const args = normalizeCommand(command).split(/\s+/); + const providerIndex = args.indexOf("provider"); + if (providerIndex < 0 || args[providerIndex + 1] !== "profile") return null; + const profileActionIndex = providerIndex + 2; + const profileAction = + args[profileActionIndex] === "-g" ? args[profileActionIndex + 2] : args[profileActionIndex]; + if (profileAction === "export") { + const requestedProfile = args[args.indexOf("export") + 1]; + if (requestedProfile !== profileId) return null; + return { + status: 0, + stdout: JSON.stringify({ + id: profileId, + credentials: [], + endpoints: [], + binaries: [], + inference_capable: inferenceCapable, + }), + stderr: "", + }; + } + const fileIndex = args.indexOf("--file"); + if ( + profileAction === "import" && + (fileIndex < 0 || !String(args[fileIndex + 1] ?? "").endsWith(`/${profileId}.yaml`)) + ) { + return null; + } + return profileAction === "import" + ? { status: 0, stdout: "", stderr: "" } + : { status: 1, stdout: "", stderr: "unsupported provider profile command" }; +} + +function mockManagedEndpointlessProviderProfileRun(command) { + return ( + mockEndpointlessProviderProfileRun(command, "openai", true) ?? + mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false) + ); +} + function createStatefulMessagingProviderRunner({ commands, initialProviders = [], @@ -63,6 +104,14 @@ function createStatefulMessagingProviderRunner({ const providers = new Map( initialProviders.map(([name, type, credential]) => [name, { type, credential }]), ); + const messagingProfile = JSON.stringify({ + id: "nemoclaw-mcp-v1", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: false, + }); + let messagingProfileImported = false; let lifecycleReleased = false; return (command, options = {}) => { const normalized = normalizeCommand(command); @@ -77,10 +126,17 @@ function createStatefulMessagingProviderRunner({ args[profileActionIndex] === "-g" ? args[profileActionIndex + 2] : args[profileActionIndex]; + if (profileAction === "export") { + return messagingProfileImported + ? { status: 0, stdout: messagingProfile, stderr: "" } + : { status: 1, stdout: "", stderr: "provider profile not found" }; + } const fileIndex = args.indexOf("--file"); - return profileAction === "import" && fileIndex >= 0 && args[fileIndex + 1] - ? { status: 0 } - : { status: 1, stderr: "unsupported provider profile command" }; + if (profileAction === "import" && fileIndex >= 0 && args[fileIndex + 1]) { + messagingProfileImported = true; + return { status: 0 }; + } + return { status: 1, stderr: "unsupported provider profile command" }; } if ( args[providerIndex - 1] === "sandbox" && @@ -574,6 +630,8 @@ if (process.env.NEMOCLAW_TEST_MANAGED_IMAGE_CATALOG === "1") { } module.exports = { + mockEndpointlessProviderProfileRun, + mockManagedEndpointlessProviderProfileRun, createStatefulMessagingProviderRunner, isOpenClawSecurityInventoryProbe, mockDockerSandboxLifecycleReleaseFromRunner, diff --git a/test/mcp/mcp-add-crash-consistency.test.ts b/test/mcp/mcp-add-crash-consistency.test.ts index 3438fdb738b..a9099784655 100644 --- a/test/mcp/mcp-add-crash-consistency.test.ts +++ b/test/mcp/mcp-add-crash-consistency.test.ts @@ -69,6 +69,7 @@ let credentialFreeRefreshAfterAbsenceCountThisProcess = 0; const registry = require("./src/lib/state/registry.js"); const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); +const { mockManagedEndpointlessProviderProfileRun } = require("./test/helpers/onboard-script-mocks.cjs"); const gatewayRuntime = require("./src/lib/gateway-runtime-action.js"); const policies = require("./src/lib/policy/index.js"); const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); @@ -90,6 +91,8 @@ gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ }); providerCommands.runOpenshellProviderCommand = (args) => { + const profileResult = mockManagedEndpointlessProviderProfileRun(args); + if (profileResult) return profileResult; if (args[0] === "status" && args[1] === "--output" && args[2] === "json") { return { status: 0, stdout: JSON.stringify({ gateway: "nemoclaw" }), stderr: "" }; } @@ -392,12 +395,15 @@ const marker = (name) => path.join(process.env.HOME, name + ".marker"); const mark = (name) => fs.writeFileSync(marker(name), "yes\n", { mode: 0o600 }); const marked = (name) => fs.existsSync(marker(name)); const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); +const { mockManagedEndpointlessProviderProfileRun } = require("./test/helpers/onboard-script-mocks.cjs"); const gatewayRuntime = require("./src/lib/gateway-runtime-action.js"); const teardownAuthority = require("./src/lib/onboard/gateway-teardown-authority.js"); gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ recovered: true, attempted: false }); teardownAuthority.resolveGatewayCredentialMutationAuthority = () => ({}); providerCommands.runOpenshellProviderCommand = (args) => { + const profileResult = mockManagedEndpointlessProviderProfileRun(args); + if (profileResult) return profileResult; if (args[0] === "provider" && args[1] === "create") { mark("credential-provider-create-entered"); const sleep = new Int32Array(new SharedArrayBuffer(4)); @@ -441,6 +447,7 @@ const providerId = "11111111-2222-4333-8444-555555555555"; let observedProviderName = null; const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); +const { mockManagedEndpointlessProviderProfileRun } = require("./test/helpers/onboard-script-mocks.cjs"); const gatewayRuntime = require("./src/lib/gateway-runtime-action.js"); const policies = require("./src/lib/policy/index.js"); const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); @@ -453,6 +460,8 @@ gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ }); providerCommands.runOpenshellProviderCommand = (args) => { + const profileResult = mockManagedEndpointlessProviderProfileRun(args); + if (profileResult) return profileResult; if (args[0] === "status" && args[1] === "--output" && args[2] === "json") { return { status: 0, stdout: JSON.stringify({ gateway: "nemoclaw" }), stderr: "" }; } @@ -538,6 +547,7 @@ function runStatusProcess(home: string) { const script = String.raw` process.env.HOME = ${JSON.stringify(home)}; const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); +const { mockManagedEndpointlessProviderProfileRun } = require("./test/helpers/onboard-script-mocks.cjs"); const gatewayRuntime = require("./src/lib/gateway-runtime-action.js"); const policies = require("./src/lib/policy/index.js"); const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); @@ -549,6 +559,8 @@ gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ after: { state: "healthy_named" }, }); providerCommands.runOpenshellProviderCommand = (args) => { + const profileResult = mockManagedEndpointlessProviderProfileRun(args); + if (profileResult) return profileResult; if (args[0] === "provider" && args[1] === "get") { return { status: 0, diff --git a/test/mcp/mcp-destroy-lifecycle.test.ts b/test/mcp/mcp-destroy-lifecycle.test.ts index d7d7d59bbb2..a905a42a90b 100644 --- a/test/mcp/mcp-destroy-lifecycle.test.ts +++ b/test/mcp/mcp-destroy-lifecycle.test.ts @@ -8,6 +8,7 @@ import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; import type { AgentMcpAdapter } from "../../src/lib/agent/defs"; import type { McpBridgeEntry } from "../../src/lib/state/registry"; +import { mockManagedEndpointlessProviderProfileRun } from "../helpers/onboard-script-mocks.cjs"; const testState = vi.hoisted(() => { const home = `/tmp/nemoclaw-mcp-destroy-${process.pid}-${Date.now()}`; @@ -51,9 +52,9 @@ const testState = vi.hoisted(() => { }); vi.mock("../../src/lib/adapters/openshell/provider-command", () => ({ + OPENSHELL_OPERATION_TIMEOUT_MS: 30_000, runOpenshellProviderCommand: testState.runOpenshellProviderCommand, })); - vi.mock("../../src/lib/adapters/dns/resolve", () => ({ resolveHostAddresses: testState.resolveHostAddresses, })); @@ -255,8 +256,7 @@ beforeEach(() => { return { status: 0, stdout: "ready", stderr: "" }; } switch (true) { - case args[0] === "provider" && args[1] === "profile" && args[2] === "import": - return { status: 0, stdout: "Imported provider profile", stderr: "" }; + case args[0] === "provider" && args[1] === "profile": return mockManagedEndpointlessProviderProfileRun(args) ?? { status: 0, stdout: "Imported provider profile", stderr: "" }; case args[0] === "provider" && args[1] === "get": { const provider = testState.providers.get(args[2]); return provider diff --git a/test/mcp/mcp-policy-key-ownership.test.ts b/test/mcp/mcp-policy-key-ownership.test.ts index 8ab9d742eda..02518ae87db 100644 --- a/test/mcp/mcp-policy-key-ownership.test.ts +++ b/test/mcp/mcp-policy-key-ownership.test.ts @@ -300,6 +300,14 @@ if [ "$1 $2 $3" = "status --output json" ]; then printf '%s\n' 'ready' exit 0 fi +if [ "$1 $2 $3 $4 $5 $6" = "provider profile export openai --output json" ]; then + printf '%s\n' '{"id":"openai","credentials":[],"endpoints":[],"binaries":[],"inference_capable":true}' + exit 0 +fi +if [ "$1 $2 $3 $4 $5 $6" = "provider profile export nemoclaw-mcp-v1 --output json" ]; then + printf '%s\n' '{"id":"nemoclaw-mcp-v1","credentials":[],"endpoints":[],"binaries":[],"inference_capable":false}' + exit 0 +fi if [ "$1 $2 $3" = "sandbox provider list" ]; then printf '%s\n' 'No providers attached to sandbox alpha.' exit 0 @@ -391,6 +399,14 @@ if [ "$1 $2 $3" = "status --output json" ]; then printf '%s\n' 'ready' exit 0 fi +if [ "$1 $2 $3 $4 $5 $6" = "provider profile export openai --output json" ]; then + printf '%s\n' '{"id":"openai","credentials":[],"endpoints":[],"binaries":[],"inference_capable":true}' + exit 0 +fi +if [ "$1 $2 $3 $4 $5 $6" = "provider profile export nemoclaw-mcp-v1 --output json" ]; then + printf '%s\n' '{"id":"nemoclaw-mcp-v1","credentials":[],"endpoints":[],"binaries":[],"inference_capable":false}' + exit 0 +fi if [ "$1 $2 $3" = "sandbox provider list" ]; then printf '%s\n' 'No providers attached to sandbox alpha.' exit 0 @@ -477,6 +493,7 @@ bridge.addMcpBridge("alpha", { process.env.HOME = ${JSON.stringify(home)}; const registry = require("./src/lib/state/registry.js"); const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); +const { mockManagedEndpointlessProviderProfileRun } = require("./test/helpers/onboard-script-mocks.cjs"); const gatewayRuntime = require("./src/lib/gateway-runtime-action.js"); const policies = require("./src/lib/policy/index.js"); const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); @@ -490,6 +507,8 @@ gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ after: { state: "healthy_named" }, }); providerCommands.runOpenshellProviderCommand = (args) => { + const profileResult = mockManagedEndpointlessProviderProfileRun(args); + if (profileResult) return profileResult; if (args.join(" ") === "status --output json") { return { status: 0, diff --git a/test/mcp/mcp-restart-policy-order.test.ts b/test/mcp/mcp-restart-policy-order.test.ts index 7f4360e6f3a..5b91e847f2c 100644 --- a/test/mcp/mcp-restart-policy-order.test.ts +++ b/test/mcp/mcp-restart-policy-order.test.ts @@ -21,6 +21,7 @@ process.env.FIRST_MCP_TOKEN = "first-host-only-secret"; process.env.SECOND_MCP_TOKEN = "second-host-only-secret"; const registry = require("./src/lib/state/registry.js"); const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); +const { mockManagedEndpointlessProviderProfileRun } = require("./test/helpers/onboard-script-mocks.cjs"); const gatewayRuntime = require("./src/lib/gateway-runtime-action.js"); const policies = require("./src/lib/policy/index.js"); const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); @@ -62,6 +63,8 @@ gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ after: { state: "healthy_named" }, }); providerCommands.runOpenshellProviderCommand = (args) => { + const profileResult = mockManagedEndpointlessProviderProfileRun(args); + if (profileResult) return profileResult; if (args.join(" ") === "status --output json") { return { status: 0, stdout: JSON.stringify({ gateway: "nemoclaw" }), stderr: "" }; } @@ -176,6 +179,7 @@ process.env.HOME = ${JSON.stringify(home)}; process.env.MCP_TOKEN = "host-only-secret"; const registry = require("./src/lib/state/registry.js"); const providerCommands = require("./src/lib/adapters/openshell/provider-command.js"); +const { mockManagedEndpointlessProviderProfileRun } = require("./test/helpers/onboard-script-mocks.cjs"); const gatewayRuntime = require("./src/lib/gateway-runtime-action.js"); const policies = require("./src/lib/policy/index.js"); const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); @@ -205,6 +209,8 @@ gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ after: { state: "healthy_named" }, }); providerCommands.runOpenshellProviderCommand = (args) => { + const profileResult = mockManagedEndpointlessProviderProfileRun(args); + if (profileResult) return profileResult; const command = args.join(" "); if (command === "status --output json") { return { status: 0, stdout: JSON.stringify({ gateway: "nemoclaw" }), stderr: "" }; diff --git a/test/onboarding/onboard-custom-dockerfile.test.ts b/test/onboarding/onboard-custom-dockerfile.test.ts index cd73bec90b8..c3d850aea1f 100644 --- a/test/onboarding/onboard-custom-dockerfile.test.ts +++ b/test/onboarding/onboard-custom-dockerfile.test.ts @@ -230,6 +230,8 @@ fs.statSync = (target, ...rest) => { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (normalized.includes("sandbox list")) return { status: 0, stdout: "No sandboxes found." }; return normalized.includes("sandbox get") && normalized.includes("my-assistant") ? { status: 0, stdout: Buffer.from("Name: my-assistant\nId: sbx-4f2a91c0d7\n"), stderr: Buffer.alloc(0) } diff --git a/test/onboarding/onboard-extra-provider-reconciliation.test.ts b/test/onboarding/onboard-extra-provider-reconciliation.test.ts index 585ae8f23eb..6ea7cd36068 100644 --- a/test/onboarding/onboard-extra-provider-reconciliation.test.ts +++ b/test/onboarding/onboard-extra-provider-reconciliation.test.ts @@ -61,6 +61,8 @@ registry.addExtraProvider("my-slack-bridge"); runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (normalized.includes("sandbox list")) return { status: 0, stdout: "No sandboxes found." }; if (normalized.includes("provider get -g nemoclaw tavily-search")) { const stderr = Buffer.from("Error: provider 'tavily-search' not found"); diff --git a/test/onboarding/onboard-host-local-inference-routing.test.ts b/test/onboarding/onboard-host-local-inference-routing.test.ts index 436eb20e0f6..a8a3196671d 100644 --- a/test/onboarding/onboard-host-local-inference-routing.test.ts +++ b/test/onboarding/onboard-host-local-inference-routing.test.ts @@ -549,7 +549,7 @@ describe("onboard host-local inference routing", () => { acceleration: "nvidia-gpu", }); expect(harness.commands.map(({ command }) => command)).toEqual([ - expect.stringMatching(/^provider profile -g nemoclaw import --file .*openai\.yaml$/u), + "provider profile -g nemoclaw export openai --output json", "provider get -g nemoclaw ollama-local", "provider create -g nemoclaw --name ollama-local --type openai --credential NEMOCLAW_OLLAMA_PROXY_TOKEN --config OPENAI_BASE_URL=http://host.openshell.internal:11434/v1", `inference set -g nemoclaw --no-verify --provider ollama-local --model ${MODEL} --timeout 180`, diff --git a/test/onboarding/onboard-inference-failure-paths.test.ts b/test/onboarding/onboard-inference-failure-paths.test.ts index e6a6b4c4ca4..d54ebe5416f 100644 --- a/test/onboarding/onboard-inference-failure-paths.test.ts +++ b/test/onboarding/onboard-inference-failure-paths.test.ts @@ -72,13 +72,10 @@ function stubMissingBedrockAuth(): void { function expectNoPostFailureSideEffects( harness: DirectSetupInferenceHarness, expectedCommands: string[] = [], - expectOpenAiProfileImport = false, + expectOpenAiProfileValidation = false, ): void { - const expected = expectOpenAiProfileImport - ? [ - expect.stringMatching(/^provider profile -g nemoclaw import --file .*openai\.yaml$/u), - ...expectedCommands, - ] + const expected = expectOpenAiProfileValidation + ? ["provider profile -g nemoclaw export openai --output json", ...expectedCommands] : expectedCommands; expect(harness.commands.map(({ command }) => command)).toEqual(expected); expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 3416539df8a..d3911bf3fc8 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -48,9 +48,7 @@ describe("onboarding inference gateway scope", () => { ).resolves.toEqual({ ok: true }); expect(harness.commands.map(({ command }) => command)).toEqual([ - expect.stringMatching( - new RegExp(`^provider profile -g ${GATEWAY} import --file .*openai\\.yaml$`, "u"), - ), + `provider profile -g ${GATEWAY} export openai --output json`, `provider get -g ${GATEWAY} openai-api`, `provider create -g ${GATEWAY} --name openai-api --type openai --credential OPENAI_API_KEY --config OPENAI_BASE_URL=https://api.openai.com/v1`, `inference set -g ${GATEWAY} --no-verify --provider openai-api --model gpt-test`, @@ -85,9 +83,7 @@ describe("onboarding inference gateway scope", () => { ).resolves.toEqual({ ok: true }); expect(harness.commands.map(({ command }) => command)).toEqual([ - expect.stringMatching( - new RegExp(`^provider profile -g ${GATEWAY} import --file .*openai\\.yaml$`, "u"), - ), + `provider profile -g ${GATEWAY} export openai --output json`, `provider get -g ${GATEWAY} compatible-endpoint`, `provider create -g ${GATEWAY} --name compatible-endpoint --type openai --credential COMPATIBLE_API_KEY --config OPENAI_BASE_URL=http://host.openshell.internal:8000/v1?tenant=local#models`, `inference set -g ${GATEWAY} --no-verify --provider compatible-endpoint --model ${model} --timeout 180`, @@ -144,9 +140,7 @@ describe("onboarding inference gateway scope", () => { expect(harness.commands.map(({ command }) => command)).toEqual([ `provider get -g ${GATEWAY} compatible-endpoint`, - expect.stringMatching( - new RegExp(`^provider profile -g ${GATEWAY} import --file .*openai\\.yaml$`, "u"), - ), + `provider profile -g ${GATEWAY} export openai --output json`, `provider get -g ${GATEWAY} compatible-endpoint`, `provider update -g ${GATEWAY} compatible-endpoint --config OPENAI_BASE_URL=http://host.openshell.internal:8000/v1`, `inference set -g ${GATEWAY} --no-verify --provider compatible-endpoint --model ${model} --timeout 180`, diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 21c872581ca..08caf4ec8eb 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -559,8 +559,8 @@ const { onboard } = require(${onboardPath}); overrides: { applyLocalInferenceRoute }, }); await harness.setupInference("test-box", "meta-llama", "vllm-local"); - const profileCommandIndex = harness.commands.findIndex((entry) => - entry.command.startsWith("provider profile -g nemoclaw import --file "), + const profileCommandIndex = harness.commands.findIndex( + (entry) => entry.command === "provider profile -g nemoclaw export openai --output json", ); const providerCommandIndex = harness.commands.findIndex((entry) => entry.command.includes("provider create"), @@ -569,10 +569,10 @@ const { onboard } = require(${onboardPath}); entry.command.includes("provider create"), ); assert.ok(providerCommand, "expected local vLLM provider create command"); - assert.ok(profileCommandIndex >= 0, "expected OpenAI profile import"); + assert.ok(profileCommandIndex >= 0, "expected OpenAI profile validation"); assert.ok( profileCommandIndex < providerCommandIndex, - "OpenAI profile import must precede local vLLM registration", + "OpenAI profile validation must precede local vLLM registration", ); assert.match(providerCommand.command, /--credential NEMOCLAW_VLLM_LOCAL_TOKEN/); assert.doesNotMatch(providerCommand.command, /--credential OPENAI_API_KEY/); @@ -616,8 +616,8 @@ const { onboard } = require(${onboardPath}); warn.mockRestore(); } assert.deepEqual(proxyCalls, ["ensure", "healthy", "persist:proxy-token"]); - const profileCommandIndex = harness.commands.findIndex((entry) => - entry.command.startsWith("provider profile -g nemoclaw import --file "), + const profileCommandIndex = harness.commands.findIndex( + (entry) => entry.command === "provider profile -g nemoclaw export openai --output json", ); const providerCommandIndex = harness.commands.findIndex( (entry) => @@ -628,10 +628,10 @@ const { onboard } = require(${onboardPath}); entry.command.includes("provider create") && entry.command.includes("ollama-local"), ); assert.ok(providerCommand, "expected ollama-local provider create command"); - assert.ok(profileCommandIndex >= 0, "expected OpenAI profile import"); + assert.ok(profileCommandIndex >= 0, "expected OpenAI profile validation"); assert.ok( profileCommandIndex < providerCommandIndex, - "OpenAI profile import must precede Ollama registration", + "OpenAI profile validation must precede Ollama registration", ); assert.match(providerCommand.command, /--credential NEMOCLAW_OLLAMA_PROXY_TOKEN/); assert.equal(providerCommand.env?.NEMOCLAW_OLLAMA_PROXY_TOKEN, "proxy-token"); @@ -964,10 +964,7 @@ console.log(JSON.stringify({ const commands = harness.commands; assert.equal(commands.length, 4); - assert.match( - commands[0].command, - /^provider profile -g nemoclaw import --file .*openai\.yaml$/, - ); + assert.equal(commands[0].command, "provider profile -g nemoclaw export openai --output json"); assert.match(commands[1].command, /^provider get -g nemoclaw /); assert.match(commands[2].command, /^provider update -g nemoclaw openai-api/); assert.doesNotMatch(commands[2].command, /--type/); diff --git a/test/onboarding/onboard-inference-smoke.test.ts b/test/onboarding/onboard-inference-smoke.test.ts index 64cf8a7dceb..d704946e9e0 100644 --- a/test/onboarding/onboard-inference-smoke.test.ts +++ b/test/onboarding/onboard-inference-smoke.test.ts @@ -30,6 +30,9 @@ describe("onboard inference smoke guard (#3253)", () => { const registryPath = JSON.stringify( path.join(REPO_ROOT, "src", "lib", "state", "registry.ts"), ); + const onboardScriptMocksPath = JSON.stringify( + path.join(REPO_ROOT, "test", "helpers", "onboard-script-mocks.cjs"), + ); fs.mkdirSync(fakeBin, { recursive: true }); fs.writeFileSync(path.join(fakeBin, "openshell"), "#!/usr/bin/env bash\nexit 0\n", { @@ -67,6 +70,8 @@ const normalize = (command) => (Array.isArray(command) ? command.join(" ") : Str runner.run = (command) => { const text = normalize(command); calls.push(["run", text]); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (text.includes("provider") && text.includes("upsert")) { return { status: 0, stdout: "Created provider compatible-endpoint\n", stderr: "" }; } diff --git a/test/onboarding/onboard-installer-restore-intent.test.ts b/test/onboarding/onboard-installer-restore-intent.test.ts index 48fd7288768..0c5d869aa86 100644 --- a/test/onboarding/onboard-installer-restore-intent.test.ts +++ b/test/onboarding/onboard-installer-restore-intent.test.ts @@ -64,6 +64,8 @@ let sandboxRecreated = false; runner.run = (command) => { const cmd = _n(command); events.push({ kind: "run", cmd }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (cmd.includes("sandbox list")) return { status: 0, stdout: "No sandboxes found." }; if (cmd.includes("sandbox delete")) sandboxDeleted = true; if (cmd.includes("sandbox list")) { diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index f69b50c9270..7fae85cf043 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -525,8 +525,8 @@ const rawGatewayCredential = ${JSON.stringify(rawGatewayCredential)}, gatewaySec registry.registerSandbox({ name: "my-assistant", messaging: { schemaVersion: 1, plan: ${messagingPlanLiteral(["slack", "telegram", "whatsapp"])} } }); registry.addExtraProvider("my-assistant-extra-telegram-bot-token-agent-a"); registry.addExtraProvider("my-assistant-extra-telegram-bot-token-agent-b"); runner.run = (command, opts = {}) => { - const normalized = _n(command); - commands.push({ command: normalized, env: opts.env || null }); + const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); if (profileResult !== null) return profileResult; const providerGet = normalized.match(/provider get -g nemoclaw ([^ ]+)$/)?.[1]; if (providerGet === process.env.NEMOCLAW_TEST_FAIL_PROVIDER) return { status: 2, stderr: "transport unavailable" }; if (providerGet && revisions.has(providerGet)) return { status: 0, stdout: "Name: " + providerGet + "\nType: " + (providerGet === "compatible-endpoint" ? "openai" : "nemoclaw-mcp-v1") + "\nCredential keys: " + credentialKeys[providerGet] + "\nConfig keys: " + (providerGet === "compatible-endpoint" ? "OPENAI_BASE_URL" : "") + "\n" }; const refresh = normalized.match(/provider update -g nemoclaw ([^ ]+)$/)?.[1]; diff --git a/test/onboarding/onboard-openrouter-inference.test.ts b/test/onboarding/onboard-openrouter-inference.test.ts index 16d76641cf9..bc409de7f9c 100644 --- a/test/onboarding/onboard-openrouter-inference.test.ts +++ b/test/onboarding/onboard-openrouter-inference.test.ts @@ -52,7 +52,7 @@ describe("OpenRouter onboarding inference setup", () => { expect(ensureAdapter).toHaveBeenCalledWith({ authorizationToken: "sk-or-test" }); const commands = harness.commands.map(({ command }) => command); expect(commands).toEqual([ - expect.stringMatching(/^provider profile -g nemoclaw import --file .*openai\.yaml$/u), + "provider profile -g nemoclaw export openai --output json", "provider get -g nemoclaw openrouter-api", "provider update -g nemoclaw openrouter-api --credential OPENROUTER_API_KEY --config OPENAI_BASE_URL=http://host.openshell.internal:11437/v1", "inference set -g nemoclaw --no-verify --provider openrouter-api --model moonshotai/kimi-k2.6 --timeout 180", @@ -157,7 +157,7 @@ describe("OpenRouter onboarding inference setup", () => { expect(ensureAdapter).toHaveBeenCalledWith({ authorizationToken: null }); expect(harness.commands.map(({ command }) => command)).toEqual([ - expect.stringMatching(/^provider profile -g nemoclaw import --file .*openai\.yaml$/u), + "provider profile -g nemoclaw export openai --output json", "provider get -g nemoclaw openrouter-api", "provider update -g nemoclaw openrouter-api --config OPENAI_BASE_URL=http://host.openshell.internal:11437/v1", "inference set -g nemoclaw --no-verify --provider openrouter-api --model moonshotai/kimi-k2.6 --timeout 180", diff --git a/test/onboarding/onboard-prepared-build-context.test.ts b/test/onboarding/onboard-prepared-build-context.test.ts index bf37f1d75a2..73c9acd71df 100644 --- a/test/onboarding/onboard-prepared-build-context.test.ts +++ b/test/onboarding/onboard-prepared-build-context.test.ts @@ -71,6 +71,9 @@ function runPreparedContextScenario(scenario: PreparedContextScenario): Prepared path.join(repoRoot, "src", "lib", "onboard", "docker-gpu-sandbox-create.ts"), ); const waitPath = JSON.stringify(path.join(repoRoot, "src", "lib", "core", "wait.ts")); + const onboardScriptMocksPath = JSON.stringify( + path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), + ); const script = String.raw` const fs = require("node:fs"); @@ -143,6 +146,8 @@ const normalize = (command) => runner.run = (command) => { const normalized = normalize(command); commands.push(normalized); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; return normalized.includes("sandbox get") && normalized.includes(sandboxName) ? { status: 0, stdout: Buffer.from(sandboxName + "\nId: sbx-4f2a91c0d7\n"), stderr: Buffer.alloc(0) } : { status: 0 }; diff --git a/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts b/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts index 3d9e2fc3782..d261a52a8d5 100644 --- a/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts @@ -36,6 +36,10 @@ describe("onboard recovered remote-provider credential reuse", () => { "openshell", `#!/usr/bin/env bash printf '%s\\n' "$*" >> "$OPENSHELL_FAKE_COMMAND_LOG" +if [ "$1 $2 $3 $5 $6" = "provider profile -g export openai" ]; then + printf '%s\\n' '{"id":"openai","credentials":[],"endpoints":[],"binaries":[],"inference_capable":true}' + exit 0 +fi if [ "$1" = "inference" ] && [ "$2" = "get" ]; then cat <<'EOF' Gateway inference: diff --git a/test/onboarding/onboard-reservation-recreate.test.ts b/test/onboarding/onboard-reservation-recreate.test.ts index 2463c9d61c5..5c7549591af 100644 --- a/test/onboarding/onboard-reservation-recreate.test.ts +++ b/test/onboarding/onboard-reservation-recreate.test.ts @@ -66,6 +66,8 @@ let sandboxRecreated = false; runner.run = (command) => { const cmd = _n(command); events.push({ kind: "run", cmd }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (cmd.includes("sandbox list")) return { status: 0, stdout: "No sandboxes found." }; if (cmd.includes("sandbox delete")) sandboxDeleted = true; if (cmd.includes("sandbox list")) { diff --git a/test/onboarding/onboard-sandbox-build.test.ts b/test/onboarding/onboard-sandbox-build.test.ts index 8db1f8c0a9f..259ab7e9e3e 100644 --- a/test/onboarding/onboard-sandbox-build.test.ts +++ b/test/onboarding/onboard-sandbox-build.test.ts @@ -58,6 +58,8 @@ const defaultCalls = []; runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (normalized.includes("sandbox list")) { return { status: 0, stdout: Buffer.from("No sandboxes found.\n"), stderr: Buffer.alloc(0) }; } @@ -280,6 +282,8 @@ agentOnboard.createAgentSandbox = () => { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (normalized.includes("sandbox list")) { return { status: 0, stdout: Buffer.from("No sandboxes found.\n"), stderr: Buffer.alloc(0) }; } @@ -488,6 +492,8 @@ buildContext.stageOptimizedSandboxBuildContext = () => { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (normalized.includes("sandbox list")) { return { status: 0, stdout: Buffer.from("No sandboxes found.\n"), stderr: Buffer.alloc(0) }; } @@ -599,6 +605,8 @@ const commands = []; runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (normalized.includes("sandbox list")) { return { status: 0, stdout: Buffer.from("No sandboxes found.\n"), stderr: Buffer.alloc(0) }; } @@ -703,6 +711,8 @@ const commands = []; runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; if (normalized.includes("sandbox list")) { return { status: 0, stdout: Buffer.from("No sandboxes found.\n"), stderr: Buffer.alloc(0) }; } diff --git a/test/onboarding/onboard-sandbox-recreation.test.ts b/test/onboarding/onboard-sandbox-recreation.test.ts index b1abbc9d42c..1b96bb4a61c 100644 --- a/test/onboarding/onboard-sandbox-recreation.test.ts +++ b/test/onboarding/onboard-sandbox-recreation.test.ts @@ -141,6 +141,8 @@ const sourceSandbox = { }; runner.run = (command, opts = {}) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); commands.push({ command: cmd, env: opts.env || null }); if (cmd.includes("sandbox list")) { @@ -278,6 +280,8 @@ const { EventEmitter } = require("node:events"); const events = []; runner.run = (command) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); events.push({ kind: "run", cmd }); if (cmd.includes("sandbox list")) { @@ -435,6 +439,8 @@ const { EventEmitter } = require("node:events"); const events = []; runner.run = (command) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); events.push({ kind: "run", cmd }); if (cmd.includes("sandbox list")) { @@ -567,6 +573,8 @@ const events = []; let sandboxDeleted = false; runner.run = (command) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); events.push({ kind: "run", cmd }); if (cmd.includes("sandbox list")) return { status: 0, stdout: "No sandboxes found." }; @@ -721,6 +729,8 @@ const { EventEmitter } = require("node:events"); const commands = []; runner.run = (command, opts = {}) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); commands.push({ command: cmd, env: opts.env || null }); if (cmd.includes("sandbox list")) { @@ -851,6 +861,8 @@ const path = require("node:path"); const commands = []; runner.run = (command, opts = {}) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); const commandString = Array.isArray(command) ? command.join(" ") : String(command); if (cmd.includes("sandbox download")) { @@ -990,6 +1002,8 @@ const path = require("node:path"); const commands = []; runner.run = (command, opts = {}) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); const commandString = Array.isArray(command) ? command.join(" ") : String(command); if (cmd.includes("sandbox download")) { @@ -1141,6 +1155,8 @@ const commands = []; let sandboxDeleted = false; runner.run = (command, opts = {}) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); commands.push({ command: cmd, env: opts.env || null }); if (cmd.includes("sandbox list")) return { status: 0, stdout: "No sandboxes found." }; @@ -1304,6 +1320,8 @@ let registeredSandbox = null; const keepAlive = setInterval(() => {}, 1000); runner.run = (command, opts = {}) => { const cmd = _n(command); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; _deleted = _deleted || cmd.includes("sandbox delete"); commands.push({ command: cmd, env: opts.env || null }); if (cmd.includes("sandbox list")) { diff --git a/test/onboarding/onboard-selection.test.ts b/test/onboarding/onboard-selection.test.ts index 543005920d8..14b24b477ea 100644 --- a/test/onboarding/onboard-selection.test.ts +++ b/test/onboarding/onboard-selection.test.ts @@ -4124,8 +4124,8 @@ if (args[0] === "inference" && args[1] === "set") { fs.writeFileSync(stateFile, JSON.stringify(state)); process.exit(0); } -// provider get: exit 1 so upsertProvider uses "create" -if (args[0] === "provider" && args[1] === "get") { process.exit(1); } +if (args[0] === "provider" && args[1] === "profile" && args.includes("export")) { process.stdout.write(JSON.stringify({ id: "openai", credentials: [], endpoints: [], binaries: [], inference_capable: true })); process.exit(0); } +if (args[0] === "provider" && args[1] === "get") { process.exit(1); } // Force provider creation. process.exit(0); `, { mode: 0o755 }, diff --git a/test/onboarding/onboard-terminal-dashboard.test.ts b/test/onboarding/onboard-terminal-dashboard.test.ts index 803be370f9c..8b5ed239452 100644 --- a/test/onboarding/onboard-terminal-dashboard.test.ts +++ b/test/onboarding/onboard-terminal-dashboard.test.ts @@ -41,6 +41,9 @@ function runTerminalDashboardScenario(scenario: "create" | "reuse") { const dockerGpuSandboxCreatePath = JSON.stringify( path.join(repoRoot, "src", "lib", "onboard", "docker-gpu-sandbox-create.ts"), ); + const onboardScriptMocksPath = JSON.stringify( + path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), + ); fs.mkdirSync(fakeBin, { recursive: true }); writeExecutable( @@ -94,6 +97,8 @@ agentOnboard.createAgentSandbox = () => { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); + if (profileResult !== null) return profileResult; return normalized.includes("sandbox get") && normalized.includes(sandboxName) ? { status: 0, stdout: Buffer.from("Name: " + sandboxName + "\nId: sbx-4f2a91c0d7\n"), stderr: Buffer.alloc(0) } : { status: 0 }; diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index 1b7b69d4345..7a264339374 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -672,6 +672,9 @@ startGateway(null).catch((error) => { 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 onboardScriptMocksPath = JSON.stringify( + path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), + ); fs.mkdirSync(fakeBin, { recursive: true }); writeOkOpenshell(fakeBin); @@ -686,6 +689,8 @@ const { EventEmitter } = require("node:events"); const commands = []; runner.run = (command, opts = {}) => { commands.push({ command: _n(command), env: opts.env || null }); + const profileResult = require(${onboardScriptMocksPath}).mockEndpointlessProviderProfileRun(command, "nemoclaw-mcp-v1", false); + if (profileResult !== null) return profileResult; return { status: 0 }; }; runner.runCapture = (command) => { @@ -782,10 +787,10 @@ const { createSandbox } = require(${onboardPath}); "OPENAI_API_KEY", ); - // openai provider profile import + provider get + provider update + inference set - assert.match( + // openai provider profile validation + provider get + provider update + inference set + assert.equal( harness.commands[0].command, - /^provider profile -g nemoclaw import --file .*openai\.yaml$/u, + "provider profile -g nemoclaw export openai --output json", ); assert.equal(harness.commands.length, 4); }); @@ -821,10 +826,10 @@ const { createSandbox } = require(${onboardPath}); "OPENAI_API_KEY", ); - // openai provider profile import + provider get + provider update + inference set - assert.match( + // openai provider profile validation + provider get + provider update + inference set + assert.equal( harness.commands[0].command, - /^provider profile -g nemoclaw import --file .*openai\.yaml$/u, + "provider profile -g nemoclaw export openai --output json", ); assert.equal(harness.commands.length, 4); }); diff --git a/test/security/config-rotate-token-provider-profile.test.ts b/test/security/config-rotate-token-provider-profile.test.ts new file mode 100644 index 00000000000..f0dd5782f63 --- /dev/null +++ b/test/security/config-rotate-token-provider-profile.test.ts @@ -0,0 +1,151 @@ +// 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 { DEFAULT_AGENT_CONFIG } from "../../src/lib/sandbox/agent-config"; +import { + rotateSandboxToken, + type RotateTokenDeps, +} from "../../src/lib/sandbox/config-rotate-token"; + +type CaptureResult = ReturnType; +type RunResult = ReturnType; + +function loadRotateTokenFixture(input: { providerType: string; captureResults: CaptureResult[] }) { + const queuedCaptureResults = [...input.captureResults]; + const captureOpenshellCommand = vi.fn( + (_binary: string, _args: string[], _options?: unknown): CaptureResult => + queuedCaptureResults.shift() ?? { status: 1, output: "" }, + ); + const runOpenshellCommand = vi.fn( + (): RunResult => + ({ + status: 0, + }) as RunResult, + ); + const appendAuditEntry = vi.fn(); + const saveCredential = vi.fn(); + const fail = vi.fn((lines: string | readonly string[]): never => { + throw new Error(typeof lines === "string" ? lines : lines.join("\n")); + }); + + const deps = { + appendAuditEntry, + captureOpenshellCommand, + fail, + loadSession: () => ({ + sandboxName: "rotate-profile-test", + credentialEnv: "OPENAI_API_KEY", + provider: "inference", + providerType: input.providerType, + }), + promptSecret: vi.fn().mockResolvedValue("rotation-secret"), + resolveAgentConfig: () => DEFAULT_AGENT_CONFIG, + runOpenshellCommand, + saveCredential, + validateName: vi.fn((name: string) => name), + } satisfies RotateTokenDeps; + + return { + appendAuditEntry, + captureOpenshellCommand, + deps, + runOpenshellCommand, + saveCredential, + }; +} + +describe("config rotate-token OpenAI provider profile", () => { + it("imports a missing OpenAI profile before rotating the provider token (#10155)", async () => { + const fixture = loadRotateTokenFixture({ + providerType: "openai", + captureResults: [ + { status: 1, output: "", stdout: "", stderr: "provider profile not found" }, + { status: 0, output: "Imported", stdout: "Imported", stderr: "" }, + ], + }); + + await rotateSandboxToken("rotate-profile-test", {}, fixture.deps); + + expect(fixture.captureOpenshellCommand.mock.calls.map(([, args]) => args)).toEqual([ + ["provider", "profile", "export", "openai", "--output", "json"], + ["provider", "profile", "import", "--file", expect.stringMatching(/openai\.yaml$/u)], + ]); + expect(fixture.captureOpenshellCommand.mock.calls[0]?.[2]).toMatchObject({ + ignoreError: true, + includeStreams: true, + timeout: 30_000, + }); + expect(fixture.captureOpenshellCommand.mock.invocationCallOrder[1]).toBeLessThan( + fixture.saveCredential.mock.invocationCallOrder[0]!, + ); + expect(fixture.saveCredential.mock.invocationCallOrder[0]).toBeLessThan( + fixture.runOpenshellCommand.mock.invocationCallOrder[0]!, + ); + }); + + it("rejects an incompatible OpenAI profile before staging or rotating the token (#10155)", async () => { + const incompatibleProfile = JSON.stringify({ + id: "openai", + credentials: [{ env: "OPENAI_API_KEY" }], + endpoints: [], + binaries: [], + inference_capable: true, + }); + const fixture = loadRotateTokenFixture({ + providerType: "openai", + captureResults: [ + { status: 0, output: incompatibleProfile, stdout: incompatibleProfile, stderr: "" }, + ], + }); + + await expect(rotateSandboxToken("rotate-profile-test", {}, fixture.deps)).rejects.toThrow( + "does not match NemoClaw's endpointless inference contract", + ); + expect(fixture.saveCredential).not.toHaveBeenCalled(); + expect(fixture.runOpenshellCommand).not.toHaveBeenCalled(); + }); + + it("suppresses failed profile import output before rotating the token (#10155)", async () => { + const profileSecret = "profile-import-secret"; + const fixture = loadRotateTokenFixture({ + providerType: "openai", + captureResults: [ + { status: 1, output: "", stdout: "", stderr: "provider profile not found" }, + { + status: 1, + output: `import rejected: ${profileSecret}`, + stdout: "", + stderr: `import rejected: ${profileSecret}`, + }, + ], + }); + + let thrown = ""; + try { + await rotateSandboxToken("rotate-profile-test", {}, fixture.deps); + } catch (error) { + thrown = error instanceof Error ? error.message : String(error); + } + + expect(thrown).toContain("could not import the checked-in 'openai'"); + expect(thrown).not.toContain(profileSecret); + expect(thrown).not.toContain("rotation-secret"); + expect(fixture.saveCredential).not.toHaveBeenCalled(); + expect(fixture.runOpenshellCommand).not.toHaveBeenCalled(); + }); + + it("does not inspect the OpenAI profile for another provider type (#10155)", async () => { + const fixture = loadRotateTokenFixture({ providerType: "nvidia", captureResults: [] }); + + await rotateSandboxToken("rotate-profile-test", {}, fixture.deps); + + expect(fixture.captureOpenshellCommand).not.toHaveBeenCalled(); + expect(fixture.saveCredential).toHaveBeenCalledWith("OPENAI_API_KEY", "rotation-secret"); + expect(fixture.runOpenshellCommand).toHaveBeenCalledOnce(); + expect(fixture.appendAuditEntry).toHaveBeenCalledWith( + expect.objectContaining({ action: "rotate_token" }), + ); + }); +}); diff --git a/test/security/config-set-nested-ssrf.test.ts b/test/security/config-set-nested-ssrf.test.ts index 60a9b4e0181..e24d44d174c 100644 --- a/test/security/config-set-nested-ssrf.test.ts +++ b/test/security/config-set-nested-ssrf.test.ts @@ -811,7 +811,16 @@ describe("config set nested URL SSRF enforcement", () => { loaded: true, // provider update succeeds, so rotation never falls into the create path. exports: { - captureOpenshellCommand: () => ({ status: 0, output: "" }), + captureOpenshellCommand: () => ({ + status: 0, + stdout: JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, + }), + }), runOpenshellCommand: () => ({ status: 0 }), }, } as any; diff --git a/test/security/shellquote-sandbox.test.ts b/test/security/shellquote-sandbox.test.ts index 094fb4afa66..c9fff1dc750 100644 --- a/test/security/shellquote-sandbox.test.ts +++ b/test/security/shellquote-sandbox.test.ts @@ -88,6 +88,19 @@ const asText = (command) => Array.isArray(command) ? command.join(" ") : String( runner.run = (command, opts = {}) => { const text = asText(command); commands.push({ type: "run", command: text, env: opts.env || null }); + if (text.includes("provider profile") && text.includes("export nemoclaw-mcp-v1")) { + return { + status: 0, + stdout: Buffer.from(JSON.stringify({ + id: "nemoclaw-mcp-v1", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: false, + })), + stderr: Buffer.alloc(0), + }; + } if (text.includes("sandbox get") && text.includes("my-assistant")) { return { status: 0, diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index e55ecdbbce5..7555f26e036 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -52,6 +52,14 @@ export type DirectSetupHarnessOptions = { overrides?: Partial; }; +const OPENAI_ENDPOINTLESS_PROFILE = JSON.stringify({ + id: "openai", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, +}); + type DirectCommandRoute = { name: string; matches(command: string): boolean; @@ -280,7 +288,17 @@ export function createDirectSetupInferenceHarnessFactory( env: runOptions.env, ignoreError: runOptions.ignoreError, }); - return directRunResult(options.runOpenshell?.(args, runOptions, commands)); + const routed = options.runOpenshell?.(args, runOptions, commands); + if (routed !== undefined) return directRunResult(routed); + if ( + args[0] === "provider" && + args[1] === "profile" && + args.includes("export") && + args.includes("openai") + ) { + return directRunResult({ status: 0, stdout: OPENAI_ENDPOINTLESS_PROFILE }); + } + return directRunResult(); }; const setupInference = createSetupInference({ checkGatewayRouteCompatibility: () => ({ ok: true }),