diff --git a/docs/inference/switch-providers.mdx b/docs/inference/switch-providers.mdx index 281b0cbd555..439fa6b41c8 100644 --- a/docs/inference/switch-providers.mdx +++ b/docs/inference/switch-providers.mdx @@ -3,14 +3,15 @@ # SPDX-License-Identifier: Apache-2.0 title: "Switch Inference Providers" sidebar-title: "Switch Providers" -description: "Move a NemoClaw-managed sandbox to another registered inference provider." +description: "Move a NemoClaw-managed sandbox to another inference provider." description-agent: "Switches inference provider families. Use when moving a sandbox between hosted, local, or compatible provider routes." keywords: ["switch nemoclaw provider", "change inference provider", "nemoclaw inference set provider"] content: type: "how_to" --- Move a sandbox to another provider family while keeping the OpenShell route, agent configuration, and host registry aligned. -Use onboarding first when the target provider is not registered. +Use onboarding first when the target is neither `compatible-endpoint` nor `compatible-anthropic-endpoint` and is not registered. +The compatible endpoint workflow below can register an absent custom provider from complete route metadata. ## Find a Registered Provider @@ -25,8 +26,9 @@ $$nemoclaw credentials list `inference set` also accepts installer-facing provider names such as `anthropicCompatible`, `build`, and `custom`. NemoClaw normalizes an accepted alias to its canonical OpenShell provider ID and records the canonical name in the sandbox registry. -If OpenShell cannot find the requested provider, NemoClaw leaves the route and sandbox state unchanged. +If OpenShell cannot find a requested provider other than `compatible-endpoint` or `compatible-anthropic-endpoint`, NemoClaw leaves the route and sandbox state unchanged. Run `$$nemoclaw onboard` to register the provider, then retry the switch. +For a compatible custom endpoint, pass the complete route metadata described below so NemoClaw can register the provider. @@ -80,17 +82,26 @@ $$nemoclaw onboard --fresh --name --recreate-sandbox When moving from another provider family to `compatible-endpoint` or `compatible-anthropic-endpoint`, provide the trusted endpoint URL and enough API metadata to record the complete route identity. +Export the canonical credential environment variable for the target provider. Run this command within the shields-down window shown in the runtime switching workflow. ```bash +export COMPATIBLE_API_KEY="" $$nemoclaw inference set \ --provider compatible-endpoint \ --model \ --endpoint-url \ + --credential-env COMPATIBLE_API_KEY \ --inference-api openai-completions \ --sandbox ``` +NemoClaw validates the endpoint before it changes the route. +For an HTTPS IP-literal or DNS-pinned HTTP endpoint, NemoClaw registers and verifies an absent provider before selecting the route. +If OpenShell still reports the provider as absent, NemoClaw retries the switch once. +If route selection fails, NemoClaw removes a newly created provider and leaves the inference selection unchanged. +For a DNS-backed HTTPS endpoint, NemoClaw registers the HTTPS Pin Runtime provider before the first route attempt. + Supported API-family values are `openai-completions`, `anthropic-messages`, and `openai-responses`. For a Hermes `compatible-anthropic-endpoint` target, omit `--inference-api` because NemoClaw selects `openai-completions`. An explicit different API family is rejected for that route. diff --git a/src/lib/actions/inference-set-compatible-provider.test.ts b/src/lib/actions/inference-set-compatible-provider.test.ts index 692b16aec79..549e84f4065 100644 --- a/src/lib/actions/inference-set-compatible-provider.test.ts +++ b/src/lib/actions/inference-set-compatible-provider.test.ts @@ -1,13 +1,19 @@ // 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 { afterEach, describe, expect, it, vi } from "vitest"; import { ensureHttpsPinRuntimeAdapter as realEnsureHttpsPinRuntimeAdapter } from "../inference/https-pin-runtime-adapter"; import type { ConfigObject } from "../security/credential-filter"; import { runInferenceSet } from "./inference-set"; -import { baseSession, createDeps } from "./inference-set.test-support"; +import { + baseSession, + createDeps, + createExistingCompatibleProviderCapture, +} from "./inference-set.test-support"; describe("runInferenceSet compatible providers", () => { + afterEach(() => vi.unstubAllEnvs()); + it("reuses durable endpoint metadata for same-provider model switches", async () => { const config: ConfigObject = { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } }, @@ -177,6 +183,216 @@ describe("runInferenceSet compatible providers", () => { expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); + it.each([ + ["an HTTPS IP-literal", "https://198.51.100.10/v1", "https://198.51.100.10/v1"], + ["a DNS-pinned HTTP", "http://compatible.example/v1", "http://198.51.100.10/v1"], + ])("creates an absent direct compatible provider for %s endpoint (#7725)", async (_kind, endpointUrl, validatedEndpointUrl) => { + let providerCreated = false; + const captureOpenshell = vi.fn((args: string[]) => { + switch (`${args[0]}:${args[1]}`) { + case "inference:set": + return providerCreated + ? { status: 0, output: "", stdout: "", stderr: "" } + : { + status: 1, + output: "Error: provider 'compatible-endpoint' not found", + stdout: "", + stderr: "Error: provider 'compatible-endpoint' not found", + }; + case "provider:get": { + const output = [ + "Name: compatible-endpoint", + "Id: 11111111-2222-4333-8444-555555555555", + "Type: openai", + "Resource version: 1", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: OPENAI_BASE_URL", + ].join("\n"); + return providerCreated + ? { status: 0, output, stdout: output, stderr: "" } + : { + status: 1, + output: + "Error: code: 'Some requested entity was not found', message: \"provider not found\"", + stdout: "", + stderr: + "Error: code: 'Some requested entity was not found', message: \"provider not found\"", + }; + } + case "provider:create": + providerCreated = true; + return { status: 0, output: "", stdout: "", stderr: "" }; + default: + return { status: 0, output: "", stdout: "", stderr: "" }; + } + }); + const deps = createDeps({ + config: { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/model-a", + }, + session: baseSession({ + provider: "nvidia-prod", + model: "nvidia/model-a", + }), + captureOpenshell, + rewriteConfigUrlsWithDnsPinning: async () => validatedEndpointUrl, + resolveCredentialValue: () => "real-upstream-secret", + }); + + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "mock-model", + noVerify: true, + endpointUrl, + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions", + }, + deps, + ), + ).resolves.toMatchObject({ + sandboxName: "alpha", + provider: "compatible-endpoint", + model: "mock-model", + }); + + const providerCreateIndex = captureOpenshell.mock.calls.findIndex( + ([args]) => args[0] === "provider" && args[1] === "create", + ); + const successfulSetIndex = captureOpenshell.mock.calls.findIndex( + ([args], index) => + index > providerCreateIndex && args[0] === "inference" && args[1] === "set", + ); + expect(providerCreateIndex).toBeGreaterThanOrEqual(0); + expect(successfulSetIndex).toBeGreaterThan(providerCreateIndex); + expect(captureOpenshell.mock.calls[providerCreateIndex]).toEqual([ + [ + "provider", + "create", + "-g", + "nemoclaw", + "--name", + "compatible-endpoint", + "--type", + "openai", + "--credential", + "COMPATIBLE_API_KEY", + "--config", + `OPENAI_BASE_URL=${validatedEndpointUrl}`, + ], + expect.objectContaining({ + env: { COMPATIBLE_API_KEY: "real-upstream-secret" }, + }), + ]); + expect(deps.calls.updateSandbox.mock.calls.at(-1)).toEqual([ + "alpha", + expect.objectContaining({ + provider: "compatible-endpoint", + endpointUrl: validatedEndpointUrl, + }), + ]); + }); + + it("updates an existing direct compatible provider when its endpoint changes (#7725)", async () => { + let providerVersion = 4; + const captureOpenshell = vi.fn((args: string[]) => { + switch (`${args[0]}:${args[1]}`) { + case "provider:get": { + const output = [ + "Name: compatible-endpoint", + "Id: 11111111-2222-4333-8444-555555555555", + "Type: openai", + `Resource version: ${providerVersion}`, + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: OPENAI_BASE_URL", + ].join("\n"); + return { status: 0, output, stdout: output, stderr: "" }; + } + case "provider:update": + providerVersion += 1; + return { status: 0, output: "", stdout: "", stderr: "" }; + default: + return { status: 0, output: "", stdout: "", stderr: "" }; + } + }); + const deps = createDeps({ + config: { agents: { defaults: { model: { primary: "inference/old-model" } } } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "compatible-endpoint", + model: "old-model", + endpointUrl: "http://198.51.100.9/v1", + endpointSource: "inference-set", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }, + session: baseSession({ + provider: "compatible-endpoint", + model: "old-model", + endpointUrl: "http://198.51.100.9/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }), + captureOpenshell, + rewriteConfigUrlsWithDnsPinning: async () => "http://198.51.100.10/v1", + resolveCredentialValue: () => "replacement-upstream-secret", + }); + + await runInferenceSet( + { + provider: "compatible-endpoint", + model: "new-model", + noVerify: true, + endpointUrl: "http://compatible.example/v1", + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions", + }, + deps, + ); + + const providerGetIndex = captureOpenshell.mock.calls.findIndex( + ([args]) => args[0] === "provider" && args[1] === "get", + ); + const inferenceSetIndex = captureOpenshell.mock.calls.findIndex( + ([args]) => args[0] === "inference" && args[1] === "set", + ); + const providerUpdateIndex = captureOpenshell.mock.calls.findIndex( + ([args]) => args[0] === "provider" && args[1] === "update", + ); + expect(providerGetIndex).toBeLessThan(inferenceSetIndex); + expect(inferenceSetIndex).toBeLessThan(providerUpdateIndex); + expect(captureOpenshell.mock.calls[providerUpdateIndex]).toEqual([ + [ + "provider", + "update", + "-g", + "nemoclaw", + "compatible-endpoint", + "--credential", + "COMPATIBLE_API_KEY", + "--config", + "OPENAI_BASE_URL=http://198.51.100.10/v1", + ], + expect.objectContaining({ + env: { COMPATIBLE_API_KEY: "replacement-upstream-secret" }, + }), + ]); + expect(deps.calls.updateSandbox.mock.calls.at(-1)).toEqual([ + "alpha", + expect.objectContaining({ + provider: "compatible-endpoint", + model: "new-model", + endpointUrl: "http://198.51.100.10/v1", + }), + ]); + }); + it("preserves explicit inference API through the final registry and session sync", async () => { let providerVersion = 1; const captureOpenshell = vi.fn((args: string[]) => { @@ -275,6 +491,12 @@ describe("runInferenceSet compatible providers", () => { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } }, models: { providers: { inference: { api: "openai-completions", models: [] } } }, }; + const captureOpenshell = createExistingCompatibleProviderCapture({ + name: "compatible-anthropic-endpoint", + type: "anthropic", + credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", + configKey: "ANTHROPIC_BASE_URL", + }); const deps = createDeps({ config, entry: { @@ -289,6 +511,7 @@ describe("runInferenceSet compatible providers", () => { endpointUrl: "https://integrate.api.nvidia.com/v1", credentialEnv: "NVIDIA_INFERENCE_API_KEY", }), + captureOpenshell, }); await runInferenceSet( diff --git a/src/lib/actions/inference-set-degraded-state.test.ts b/src/lib/actions/inference-set-degraded-state.test.ts index 20ec3b27276..23d41556abd 100644 --- a/src/lib/actions/inference-set-degraded-state.test.ts +++ b/src/lib/actions/inference-set-degraded-state.test.ts @@ -5,7 +5,11 @@ import { describe, expect, it } from "vitest"; import { SandboxConfigError } from "../sandbox/config"; import type { ConfigObject } from "../security/credential-filter"; import { InferenceSetError, runInferenceSet } from "./inference-set"; -import { baseSession, createDeps } from "./inference-set.test-support"; +import { + baseSession, + createDeps, + createExistingCompatibleProviderCapture, +} from "./inference-set.test-support"; describe("runInferenceSet degraded state handling", () => { it("aborts before mutating any layer when the sandbox config read fails (#6997)", async () => { @@ -130,6 +134,12 @@ describe("runInferenceSet degraded state handling", () => { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", }), + captureOpenshell: createExistingCompatibleProviderCapture({ + name: "compatible-endpoint", + type: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + configKey: "OPENAI_BASE_URL", + }), }); deps.calls.readSandboxConfig.mockImplementation(() => structuredClone(persistedConfig)); deps.calls.updateSandbox.mockImplementation((_name, updates) => { diff --git a/src/lib/actions/inference-set-gateway-route-containment.test.ts b/src/lib/actions/inference-set-gateway-route-containment.test.ts index 96eb0585606..877610d4e31 100644 --- a/src/lib/actions/inference-set-gateway-route-containment.test.ts +++ b/src/lib/actions/inference-set-gateway-route-containment.test.ts @@ -324,6 +324,7 @@ describe("runtime shared gateway route containment", () => { onboardEndpointUrl: null, getSandboxes: () => [alpha, peer], rewriteUrlWithDnsPinning, + resolveCredentialValue: () => "", ensureHttpsPinRuntimeAdapter, }), ).rejects.toThrow("custom-peer"); @@ -371,6 +372,7 @@ describe("runtime shared gateway route containment", () => { onboardEndpointUrl: null, getSandboxes: () => [alpha, peer], rewriteUrlWithDnsPinning: vi.fn(async (value: unknown) => value as string), + resolveCredentialValue: () => "upstream-token", ensureHttpsPinRuntimeAdapter: vi.fn(async () => ({ baseUrl: adapterBaseUrl as string, credentialEnv: HTTPS_PIN_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV, @@ -459,6 +461,7 @@ describe("runtime shared gateway route containment", () => { onboardEndpointUrl: null, getSandboxes: () => [alpha, beta], rewriteUrlWithDnsPinning, + resolveCredentialValue: () => "upstream-token", ensureHttpsPinRuntimeAdapter, }); diff --git a/src/lib/actions/inference-set-provider-alias.test.ts b/src/lib/actions/inference-set-provider-alias.test.ts index 105d99f60f4..2285aa589a1 100644 --- a/src/lib/actions/inference-set-provider-alias.test.ts +++ b/src/lib/actions/inference-set-provider-alias.test.ts @@ -24,7 +24,11 @@ import { normalizeInferenceSetProvider, runInferenceSet, } from "./inference-set"; -import { baseSession, createDeps } from "./inference-set.test-support"; +import { + baseSession, + createDeps, + createExistingCompatibleProviderCapture, +} from "./inference-set.test-support"; import type { EnsureHttpsPinRuntimeAdapterOptions } from "./inference-set-route-containment"; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -348,6 +352,12 @@ describe("runInferenceSet SSRF-block guidance — facet 2 (#6321)", () => { // onboarding. DNS re-resolution is not required for that exact identity. const guard = ssrfGuard(); const adapterGuard = httpsPinAdapterGuard(); + const captureOpenshell = createExistingCompatibleProviderCapture({ + name: "compatible-anthropic-endpoint", + type: "anthropic", + credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", + configKey: "ANTHROPIC_BASE_URL", + }); const deps = createDeps({ config: { agents: { defaults: { model: { primary: "inference/anthropic/model-a" } } } }, entry: { @@ -362,6 +372,7 @@ describe("runInferenceSet SSRF-block guidance — facet 2 (#6321)", () => { }, rewriteConfigUrlsWithDnsPinning: guard, ensureHttpsPinRuntimeAdapter: adapterGuard, + captureOpenshell, }); await expect( runInferenceSet( @@ -385,6 +396,12 @@ describe("runInferenceSet SSRF-block guidance — facet 2 (#6321)", () => { it("accepts the same onboard-provenanced internal endpoint after canonicalization (#6321)", async () => { const guard = ssrfGuard(); const adapterGuard = httpsPinAdapterGuard(); + const captureOpenshell = createExistingCompatibleProviderCapture({ + name: "compatible-endpoint", + type: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + configKey: "OPENAI_BASE_URL", + }); const deps = createDeps({ config: { agents: { defaults: { model: { primary: "inference/nvidia/model-a" } } }, @@ -402,6 +419,7 @@ describe("runInferenceSet SSRF-block guidance — facet 2 (#6321)", () => { }, rewriteConfigUrlsWithDnsPinning: guard, ensureHttpsPinRuntimeAdapter: adapterGuard, + captureOpenshell, }); await expect( diff --git a/src/lib/actions/inference-set-https-pin-provider.test.ts b/src/lib/actions/inference-set-provider.test.ts similarity index 86% rename from src/lib/actions/inference-set-https-pin-provider.test.ts rename to src/lib/actions/inference-set-provider.test.ts index 755f6d7dbf8..2efb9286cd6 100644 --- a/src/lib/actions/inference-set-https-pin-provider.test.ts +++ b/src/lib/actions/inference-set-provider.test.ts @@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type { InferenceSetDeps } from "./inference-set"; -import { __test, prepareHttpsPinProviderBinding } from "./inference-set-https-pin-provider"; +import { __test, prepareInferenceSetProviderBinding } from "./inference-set-provider"; import type { HttpsPinProviderBinding } from "./inference-set-route-containment"; const PROVIDER_ID = "11111111-2222-4333-8444-555555555555"; @@ -48,7 +48,7 @@ function captureSequence( ) as InferenceSetDeps["captureOpenshell"] & ReturnType; } -describe("HTTPS-pin provider binding", () => { +describe("inference set provider binding", () => { afterEach(() => vi.unstubAllEnvs()); it("updates an owned provider with only the route token in invocation-local env", () => { @@ -61,7 +61,7 @@ describe("HTTPS-pin provider binding", () => { { status: 0, stdout: after, stderr: "", output: after }, ]); - const mutation = prepareHttpsPinProviderBinding({ + const mutation = prepareInferenceSetProviderBinding({ gatewayName: "nemoclaw", providerName: "compatible-endpoint", binding: binding(), @@ -97,7 +97,7 @@ describe("HTTPS-pin provider binding", () => { ]); expect(() => - prepareHttpsPinProviderBinding({ + prepareInferenceSetProviderBinding({ gatewayName: "nemoclaw", providerName: "compatible-endpoint", binding: binding(), @@ -107,6 +107,30 @@ describe("HTTPS-pin provider binding", () => { expect(capture.mock.calls[1][0]).toContain("create"); }); + it("creates a provider after the OpenShell 0.0.85 generic lookup miss (#7725)", () => { + const after = providerOutput({ resourceVersion: 1 }); + const capture = captureSequence([ + { + status: 1, + stdout: "", + stderr: + "Error: code: 'Some requested entity was not found', message: \"provider not found\"", + }, + { status: 0, stdout: "", stderr: "" }, + { status: 0, stdout: after, stderr: "" }, + ]); + + const mutation = prepareInferenceSetProviderBinding({ + gatewayName: "nemoclaw", + providerName: "compatible-endpoint", + binding: binding(), + captureOpenshell: capture, + }); + + expect(mutation.action).toBe("create"); + expect(capture.mock.calls[1][0]).toContain("create"); + }); + it("removes a newly created provider when the caller rolls back", () => { const after = providerOutput({ resourceVersion: 1 }); const capture = captureSequence([ @@ -117,7 +141,7 @@ describe("HTTPS-pin provider binding", () => { { status: 1, stdout: "", stderr: "Provider 'compatible-endpoint' not found" }, ]); - const mutation = prepareHttpsPinProviderBinding({ + const mutation = prepareInferenceSetProviderBinding({ gatewayName: "nemoclaw", providerName: "compatible-endpoint", binding: binding(), @@ -146,7 +170,7 @@ describe("HTTPS-pin provider binding", () => { ]); expect(() => - prepareHttpsPinProviderBinding({ + prepareInferenceSetProviderBinding({ gatewayName: "nemoclaw", providerName: "compatible-endpoint", binding: binding(), @@ -160,7 +184,7 @@ describe("HTTPS-pin provider binding", () => { const capture = captureSequence([{ status: 0, stdout: malformed, stderr: "" }]); expect(() => - prepareHttpsPinProviderBinding({ + prepareInferenceSetProviderBinding({ gatewayName: "nemoclaw", providerName: "compatible-endpoint", binding: binding(), @@ -180,7 +204,7 @@ describe("HTTPS-pin provider binding", () => { ]); expect(() => - prepareHttpsPinProviderBinding({ + prepareInferenceSetProviderBinding({ gatewayName: "nemoclaw", providerName: "compatible-endpoint", binding: binding(), @@ -207,13 +231,13 @@ describe("HTTPS-pin provider binding", () => { }; }; - prepareHttpsPinProviderBinding({ + prepareInferenceSetProviderBinding({ gatewayName: "gateway-a", providerName: "compatible-endpoint", binding: binding({ token: "route-token-a" }), captureOpenshell: makeCapture("aaaaaaaa-2222-4333-8444-555555555555"), }).commit(); - prepareHttpsPinProviderBinding({ + prepareInferenceSetProviderBinding({ gatewayName: "gateway-b", providerName: "compatible-endpoint", binding: binding({ token: "route-token-b", routeId: "route-b" }), diff --git a/src/lib/actions/inference-set-https-pin-provider.ts b/src/lib/actions/inference-set-provider.ts similarity index 85% rename from src/lib/actions/inference-set-https-pin-provider.ts rename to src/lib/actions/inference-set-provider.ts index 058b5487a0d..022526999e4 100644 --- a/src/lib/actions/inference-set-https-pin-provider.ts +++ b/src/lib/actions/inference-set-provider.ts @@ -11,7 +11,7 @@ import { OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER, openshellReportsProviderNotFound, } from "./inference-set-error"; -import type { HttpsPinProviderBinding } from "./inference-set-route-containment"; +import type { InferenceSetProviderBinding } from "./inference-set-route-containment"; type CaptureProviderCommand = ( args: string[], @@ -38,7 +38,7 @@ type ProviderObservation = } | { kind: "error"; status: number | null }; -function providerSurface(binding: HttpsPinProviderBinding): ProviderSurface { +function providerSurface(binding: InferenceSetProviderBinding): ProviderSurface { return binding.providerType === "anthropic" ? { type: "anthropic", configKey: "ANTHROPIC_BASE_URL" } : { type: "openai", configKey: "OPENAI_BASE_URL" }; @@ -80,7 +80,7 @@ function inspectProvider( }); const output = resultText(result); if (result.status !== 0) { - return openshellReportsProviderNotFound(output, providerName) + return providerLookupReportsNotFound(output, providerName) ? { kind: "absent" } : { kind: "error", status: result.status }; } @@ -90,6 +90,21 @@ function inspectProvider( return { kind: "present", ...version, metadata }; } +function providerLookupReportsNotFound(output: string, providerName: string): boolean { + if (openshellReportsProviderNotFound(output, providerName)) return true; + // OpenShell 0.0.85 omits the name only from this exact-name `provider get` + // command. Keep the route-update parser strict because its output can name + // a different missing provider. + return stripAnsi(output) + .toLowerCase() + .split("\n") + .some( + (line) => + /code:\s*['"]some requested entity was not found['"]/u.test(line) && + /message:\s*['"]provider not found['"]/u.test(line), + ); +} + function expectedShape(providerName: string, surface: ProviderSurface, credentialEnv: string) { return { name: providerName, @@ -103,7 +118,7 @@ function assertProviderOwnership(options: { observation: ProviderObservation; providerName: string; surface: ProviderSurface; - binding: HttpsPinProviderBinding; + binding: InferenceSetProviderBinding; }): "create" | "update" { const { observation, providerName, surface, binding } = options; if (observation.kind === "absent") return "create"; @@ -157,10 +172,10 @@ function mutationArgs(options: { return args; } -export function prepareHttpsPinProviderBinding(options: { +export function prepareInferenceSetProviderBinding(options: { gatewayName: string; providerName: string; - binding: HttpsPinProviderBinding; + binding: InferenceSetProviderBinding; captureOpenshell: CaptureProviderCommand; }): { action: "create" | "update"; commit: () => void; rollback: () => void } { const { gatewayName, providerName, binding, captureOpenshell } = options; @@ -193,8 +208,8 @@ export function prepareHttpsPinProviderBinding(options: { const after = inspectProvider(captureOpenshell, gatewayName, providerName); if (result.status !== 0) { throw new InferenceSetError( - `Failed to ${action} HTTPS-pinned provider '${providerName}' on gateway '${gatewayName}' (status ${result.status ?? "unknown"}). ` + - `The provider command may have partially applied; retry this command or re-run onboarding to converge the safe adapter binding.`, + `Failed to ${action} provider '${providerName}' on gateway '${gatewayName}' (status ${result.status ?? "unknown"}). ` + + `The provider command may have partially applied; retry this command or re-run onboarding to converge the requested binding.`, 1, ); } @@ -210,7 +225,7 @@ export function prepareHttpsPinProviderBinding(options: { ) ) { throw new InferenceSetError( - `Provider '${providerName}' did not converge to the expected HTTPS-pinned type and binding-key shape after ${action}. ` + + `Provider '${providerName}' did not converge to the expected type and binding-key shape after ${action}. ` + `Provider state may be partial; retry this command or re-run onboarding to reconcile it.`, 1, ); @@ -250,5 +265,6 @@ export const __test = { inspectProvider, parseProviderVersion, providerSurface, + providerLookupReportsNotFound, mutationArgs, }; diff --git a/src/lib/actions/inference-set-route-containment.ts b/src/lib/actions/inference-set-route-containment.ts index 1024486aeed..4625e3559e2 100644 --- a/src/lib/actions/inference-set-route-containment.ts +++ b/src/lib/actions/inference-set-route-containment.ts @@ -62,14 +62,17 @@ export type EnsureHttpsPinRuntimeAdapterFn = ( options: EnsureHttpsPinRuntimeAdapterOptions, ) => Promise<{ baseUrl: string; credentialEnv: string; token: string; routeId: string }>; -export interface HttpsPinProviderBinding { +export interface InferenceSetProviderBinding { baseUrl: string; credentialEnv: string; token: string; - routeId: string; providerType: HttpsPinCredentialProviderType; } +export interface HttpsPinProviderBinding extends InferenceSetProviderBinding { + routeId: string; +} + type EnsureHttpsPinAdapterRoute = (endpointUrl: string) => Promise; export interface PreparedInferenceSetRoute { @@ -416,11 +419,13 @@ export async function finalizeInferenceSetRoute(options: { onboardEndpointUrl: string | null; getSandboxes: () => SandboxEntry[]; rewriteUrlWithDnsPinning: RewriteConfigUrlsWithDnsPinning; + resolveCredentialValue: (credentialEnv: string) => string; ensureHttpsPinRuntimeAdapter: EnsureHttpsPinRuntimeAdapterFn; effectiveInferenceApi?: string | null; }): Promise<{ registryMetadata: RegistryInferenceMetadata; explicitPreferredInferenceApi: string | null; + directProviderBinding: InferenceSetProviderBinding | null; httpsPinProviderBinding: HttpsPinProviderBinding | null; }> { const { prepared } = options; @@ -428,14 +433,23 @@ export async function finalizeInferenceSetRoute(options: { return { registryMetadata: prepared.preliminaryRegistryMetadata, explicitPreferredInferenceApi: null, + directProviderBinding: null, httpsPinProviderBinding: null, }; } // Bound once per finalize call: the credential env var name is fixed per // provider (normalizeExplicitCredentialEnv already enforced this), and the - // real credential value is read directly from the host process environment - // at invocation time, never persisted, and never returned to the caller. + // real credential value is resolved once at invocation time through the + // injected credential resolver. Direct routes return it only in the + // invocation-local provider binding consumed below; no registry or sandbox + // field receives it. const httpsPinCredentialEnv = CUSTOM_COMPATIBLE_CREDENTIAL_ENV[options.provider]; + const credentialValue = options.resolveCredentialValue(httpsPinCredentialEnv); + const providerType: HttpsPinCredentialProviderType = + (options.effectiveInferenceApi ?? + prepared.preliminaryExplicitMetadata.preferredInferenceApi) === "anthropic-messages" + ? "anthropic" + : "openai"; // Set only when the adapter route is actually used. The canonical provider // credential key stays stable; only its invocation-local value becomes the // route-scoped adapter token. @@ -444,12 +458,6 @@ export async function finalizeInferenceSetRoute(options: { // The credential is held only for this invocation and handed directly // to the adapter. It is never persisted, returned, or copied to a shared // process.env slot. - const credentialValue = process.env[httpsPinCredentialEnv] ?? ""; - const providerType: HttpsPinCredentialProviderType = - (options.effectiveInferenceApi ?? - prepared.preliminaryExplicitMetadata?.preferredInferenceApi) === "anthropic-messages" - ? "anthropic" - : "openai"; const adapter = await options.ensureHttpsPinRuntimeAdapter({ gatewayName: prepared.gatewayName, provider: options.provider, @@ -518,6 +526,14 @@ export async function finalizeInferenceSetRoute(options: { endpointUrl, endpointSource, }; + const directProviderBinding: InferenceSetProviderBinding | null = httpsPinProviderBinding + ? null + : { + baseUrl: endpointUrl, + credentialEnv: httpsPinCredentialEnv, + token: credentialValue, + providerType, + }; assertGatewayRouteCompatibility({ gatewayName: prepared.gatewayName, sandboxName: options.sandboxName, @@ -529,6 +545,7 @@ export async function finalizeInferenceSetRoute(options: { return { registryMetadata, explicitPreferredInferenceApi: registryMetadata.preferredInferenceApi ?? null, + directProviderBinding, httpsPinProviderBinding, }; } diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index 581574af36c..b5b73c112af 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -71,6 +71,35 @@ export function baseSession(overrides: Partial = {}): Session { } as Session; } +export function createExistingCompatibleProviderCapture(options: { + name: string; + type: "openai" | "anthropic"; + credentialEnv: string; + configKey: "OPENAI_BASE_URL" | "ANTHROPIC_BASE_URL"; +}): InferenceSetDeps["captureOpenshell"] { + let providerVersion = 1; + return vi.fn((args: string[]) => { + switch (`${args[0]}:${args[1]}`) { + case "provider:get": { + const output = [ + `Name: ${options.name}`, + "Id: 11111111-2222-4333-8444-555555555555", + `Type: ${options.type}`, + `Resource version: ${providerVersion}`, + `Credential keys: ${options.credentialEnv}`, + `Config keys: ${options.configKey}`, + ].join("\n"); + return { status: 0, output, stdout: output, stderr: "" }; + } + case "provider:update": + providerVersion += 1; + return { status: 0, output: "", stdout: "", stderr: "" }; + default: + return { status: 0, output: "", stdout: "", stderr: "" }; + } + }); +} + export function createDeps(options: { config: ConfigObject; entry?: SandboxEntry | null; @@ -87,6 +116,7 @@ export function createDeps(options: { shieldsMutable?: boolean; prepareRunOpenshell?: () => void; rewriteConfigUrlsWithDnsPinning?: (value: ConfigValue) => Promise; + resolveCredentialValue?: InferenceSetDeps["resolveCredentialValue"]; ensureHttpsPinRuntimeAdapter?: EnsureHttpsPinRuntimeAdapterFn; revokeHttpsPinRuntimeAdapterRoute?: InferenceSetDeps["revokeHttpsPinRuntimeAdapterRoute"]; updateSandbox?: InferenceSetDeps["updateSandbox"]; @@ -109,6 +139,7 @@ export function createDeps(options: { resolveContextWindowForModel: ReturnType; prepareRunOpenshell: ReturnType; rewriteConfigUrlsWithDnsPinning: ReturnType; + resolveCredentialValue: ReturnType; ensureHttpsPinRuntimeAdapter: ReturnType; revokeHttpsPinRuntimeAdapterRoute: ReturnType; restartSandboxGateway: ReturnType; @@ -155,6 +186,10 @@ export function createDeps(options: { rewriteConfigUrlsWithDnsPinning: vi.fn( options.rewriteConfigUrlsWithDnsPinning ?? (async (value: ConfigValue) => value), ), + resolveCredentialValue: vi.fn( + options.resolveCredentialValue ?? + ((credentialEnv: string) => process.env[credentialEnv] ?? ""), + ), ensureHttpsPinRuntimeAdapter: vi.fn( options.ensureHttpsPinRuntimeAdapter ?? (async () => ({ @@ -206,6 +241,7 @@ export function createDeps(options: { resolveContextWindowForModel: calls.resolveContextWindowForModel, isSandboxConfigMutable: () => options.shieldsMutable ?? true, rewriteConfigUrlsWithDnsPinning: calls.rewriteConfigUrlsWithDnsPinning, + resolveCredentialValue: calls.resolveCredentialValue, ensureHttpsPinRuntimeAdapter: calls.ensureHttpsPinRuntimeAdapter as unknown as EnsureHttpsPinRuntimeAdapterFn, revokeHttpsPinRuntimeAdapterRoute: diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index fa157601564..c3e5684e78f 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -57,7 +57,11 @@ import type { SandboxEntry } from "../state/registry"; import * as registry from "../state/registry"; import { isSafeModelId } from "../validation"; import { hermesApiMode, resolveRuntimeInferenceApi } from "./inference-route-api"; -import { InferenceSetError, OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER } from "./inference-set-error"; +import { + InferenceSetError, + OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER, + openshellReportsProviderNotFound, +} from "./inference-set-error"; import { completeInferenceGatewayRestart, defaultInferenceGatewayRestart, @@ -66,7 +70,7 @@ import { type InferenceMutation, readPreviousOpenClawInferenceApi, } from "./inference-set-gateway-restart"; -import { prepareHttpsPinProviderBinding } from "./inference-set-https-pin-provider"; +import { prepareInferenceSetProviderBinding } from "./inference-set-provider"; import { buildInferenceSetFailure } from "./inference-set-provider-diagnostics"; import { applyOpenClawAnthropicReplyBudget, @@ -148,6 +152,7 @@ export interface InferenceSetDeps extends InferenceGatewayRestartDeps { resolveContextWindowForModel: (provider: string, model: string) => number | null; isSandboxConfigMutable: (sandboxName: string) => boolean; rewriteConfigUrlsWithDnsPinning: (value: ConfigValue) => Promise; + resolveCredentialValue: (credentialEnv: string) => string; ensureHttpsPinRuntimeAdapter: EnsureHttpsPinRuntimeAdapterFn; revokeHttpsPinRuntimeAdapterRoute: (routeId: string) => Promise; withGatewayRouteMutationLock: typeof withGatewayRouteMutationLock; @@ -251,6 +256,7 @@ function defaultDeps(): InferenceSetDeps { ensureLocalProviderReachable, resolveContextWindowForModel, rewriteConfigUrlsWithDnsPinning, + resolveCredentialValue: (credentialEnv) => process.env[credentialEnv] ?? "", ensureHttpsPinRuntimeAdapter, revokeHttpsPinRuntimeAdapterRoute, withGatewayRouteMutationLock, @@ -850,28 +856,32 @@ async function runInferenceSetWithoutHostLock( preparedRoute.preliminaryExplicitMetadata.preferredInferenceApi ?? null, ); } - const { registryMetadata, explicitPreferredInferenceApi, httpsPinProviderBinding } = - await finalizeInferenceSetRoute({ - prepared: preparedRoute, - sandboxName, - provider, - model, - canReuseRecordedRoute: - entry.provider === provider && - typeof entry.endpointUrl === "string" && - entry.endpointUrl.trim().length > 0 && - typeof entry.preferredInferenceApi === "string" && - entry.preferredInferenceApi.trim().length > 0, - onboardEndpointUrl: - entry.provider === provider && entry.endpointSource === "onboard" - ? (entry.endpointUrl ?? null) - : null, - getSandboxes: () => deps.listSandboxes().sandboxes, - rewriteUrlWithDnsPinning: deps.rewriteConfigUrlsWithDnsPinning, - ensureHttpsPinRuntimeAdapter: deps.ensureHttpsPinRuntimeAdapter, - effectiveInferenceApi: - preparedRoute.preliminaryExplicitMetadata?.preferredInferenceApi ?? null, - }); + const { + registryMetadata, + explicitPreferredInferenceApi, + directProviderBinding, + httpsPinProviderBinding, + } = await finalizeInferenceSetRoute({ + prepared: preparedRoute, + sandboxName, + provider, + model, + canReuseRecordedRoute: + entry.provider === provider && + typeof entry.endpointUrl === "string" && + entry.endpointUrl.trim().length > 0 && + typeof entry.preferredInferenceApi === "string" && + entry.preferredInferenceApi.trim().length > 0, + onboardEndpointUrl: + entry.provider === provider && entry.endpointSource === "onboard" + ? (entry.endpointUrl ?? null) + : null, + getSandboxes: () => deps.listSandboxes().sandboxes, + rewriteUrlWithDnsPinning: deps.rewriteConfigUrlsWithDnsPinning, + resolveCredentialValue: deps.resolveCredentialValue, + ensureHttpsPinRuntimeAdapter: deps.ensureHttpsPinRuntimeAdapter, + effectiveInferenceApi: preparedRoute.preliminaryExplicitMetadata?.preferredInferenceApi ?? null, + }); // Local providers (ollama-local, vllm-local) route through the sandbox-facing // host.openshell.internal hostname, which the host-side `openshell inference set` @@ -916,7 +926,7 @@ async function runInferenceSetWithoutHostLock( provider, registryMetadata.endpointUrl ?? null, deps, - httpsPinProviderBinding, + httpsPinProviderBinding ?? directProviderBinding, ); // Read the in-sandbox config *before* mutating the gateway route or registry. @@ -940,22 +950,24 @@ async function runInferenceSetWithoutHostLock( assertReasoningEffortRoute(reasoningEffortRequest, provider, preMutationInferenceApi); const previousProvider = typeof entry.provider === "string" ? entry.provider.trim() : ""; const previousModel = typeof entry.model === "string" ? entry.model.trim() : ""; - let appliedHttpsPinProvider = false; + + let appliedProvider = false; let appliedInferenceSelection = false; let restoredSelectionAfterProviderFailure = false; - let httpsPinProviderMutation: ReturnType | null = null; + let providerMutation: ReturnType | null = null; try { - if (httpsPinProviderBinding) { - httpsPinProviderMutation = prepareHttpsPinProviderBinding({ + const providerBinding = httpsPinProviderBinding ?? directProviderBinding; + if (providerBinding) { + providerMutation = prepareInferenceSetProviderBinding({ gatewayName: preparedRoute.gatewayName, providerName: provider, - binding: httpsPinProviderBinding, + binding: providerBinding, captureOpenshell: deps.captureOpenshell, }); - appliedHttpsPinProvider = httpsPinProviderMutation.action === "create"; - if (httpsPinProviderMutation.action === "update" && (!previousProvider || !previousModel)) { + appliedProvider = providerMutation.action === "create"; + if (providerMutation.action === "update" && (!previousProvider || !previousModel)) { throw new InferenceSetError( - `Cannot update existing HTTPS-pinned provider '${provider}' because sandbox '${sandboxName}' ` + + `Cannot update existing ${httpsPinProviderBinding ? "HTTPS-pinned " : ""}provider '${provider}' because sandbox '${sandboxName}' ` + `does not record the previous provider and model needed to restore its inference selection.`, 2, ); @@ -963,28 +975,40 @@ async function runInferenceSetWithoutHostLock( } deps.log(` Setting OpenShell inference route: ${provider} / ${model}`); - const setResult = deps.captureOpenshell( - openshellInferenceSetArgs({ - gatewayName: preparedRoute.gatewayName, + const setInferenceRoute = () => + deps.captureOpenshell( + openshellInferenceSetArgs({ + gatewayName: preparedRoute.gatewayName, + provider, + model, + noVerify: effectiveNoVerify, + }), + { + ignoreError: true, + includeStreams: true, + maxBuffer: OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER, + }, + ); + let setResult = setInferenceRoute(); + if ( + setResult.status !== 0 && + directProviderBinding && + openshellReportsProviderNotFound( + `${setResult.stderr ?? ""}\n${setResult.stdout ?? ""}`, provider, - model, - noVerify: effectiveNoVerify, - }), - { - ignoreError: true, - includeStreams: true, - maxBuffer: OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER, - }, - ); + ) + ) { + setResult = setInferenceRoute(); + } if (setResult.status !== 0) { const failure = buildInferenceSetFailure(setResult, provider, deps); throw new InferenceSetError(failure.message, failure.exitCode); } appliedInferenceSelection = true; - if (httpsPinProviderMutation) { + if (providerMutation) { try { - httpsPinProviderMutation.commit(); - appliedHttpsPinProvider = true; + providerMutation.commit(); + appliedProvider = true; } catch (providerError) { const providerDetail = providerError instanceof Error ? providerError.message : String(providerError); @@ -1217,13 +1241,13 @@ async function runInferenceSetWithoutHostLock( deps, ); } catch (error) { - if (!httpsPinProviderMutation) throw error; + if (!providerMutation) throw error; if (restoredSelectionAfterProviderFailure) throw error; const detail = error instanceof Error ? error.message : String(error); const exitCode = error instanceof InferenceSetError ? error.exitCode : 1; if (!appliedInferenceSelection) { try { - httpsPinProviderMutation.rollback(); + providerMutation.rollback(); } catch (rollbackError) { const rollbackDetail = rollbackError instanceof Error ? rollbackError.message : String(rollbackError); @@ -1233,14 +1257,18 @@ async function runInferenceSetWithoutHostLock( ); } const unchanged = - httpsPinProviderMutation.action === "create" + providerMutation.action === "create" ? "The newly created OpenShell provider was removed; the inference selection was not changed." : "The existing OpenShell provider binding and inference selection were not changed."; throw new InferenceSetError(`${detail}\n ${unchanged}`, exitCode); } - const residual = appliedHttpsPinProvider - ? "The OpenShell provider and inference selection remain committed to the safer HTTPS-pinned adapter, but NemoClaw state may not have converged. Retry this command; if convergence still fails, rebuild the sandbox." - : "The inference selection changed, but the HTTPS-pinned provider binding did not converge. Retry this command immediately; if convergence still fails, rebuild the sandbox."; + const residual = appliedProvider + ? httpsPinProviderBinding + ? "The OpenShell provider and inference selection remain committed to the safer HTTPS-pinned adapter, but NemoClaw state may not have converged. Retry this command; if convergence still fails, rebuild the sandbox." + : "The OpenShell provider and inference selection remain committed, but NemoClaw state may not have converged. Retry this command; if convergence still fails, rebuild the sandbox." + : httpsPinProviderBinding + ? "The inference selection changed, but the HTTPS-pinned provider binding did not converge. Retry this command immediately; if convergence still fails, rebuild the sandbox." + : "The inference selection changed, but the OpenShell provider binding did not converge. Retry this command immediately; if convergence still fails, rebuild the sandbox."; throw new InferenceSetError(`${detail}\n ${residual}`, exitCode); } } diff --git a/test/e2e/support/e2e-report-to-pr-workflow-boundary.test.ts b/test/e2e/support/e2e-report-to-pr-workflow-boundary.test.ts index a52440b09e3..69360e6cb9e 100644 --- a/test/e2e/support/e2e-report-to-pr-workflow-boundary.test.ts +++ b/test/e2e/support/e2e-report-to-pr-workflow-boundary.test.ts @@ -904,7 +904,7 @@ it("carries the generated planner matrix through the workflow output and PR repo } finally { fs.rmSync(directory, { force: true, recursive: true }); } -}); +}, 30_000); it("builds controller target matrices only from trusted runner mappings (#7031)", () => { const target = "ubuntu-repo-cloud-langchain-deepagents-code";