From 05f5dafe655482077b42bd36c0230c88dcc6ec81 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:31:05 -0700 Subject: [PATCH 1/9] feat(inference): use native providers for custom hosted endpoints Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../credentials/reset-native-hosted.test.ts | 41 +- src/lib/actions/inference-get.test.ts | 20 +- src/lib/actions/inference-get.ts | 7 +- .../inference-set-native-hosted.test.ts | 102 ++++- .../inference-set-route-containment.ts | 20 + src/lib/actions/inference-set.ts | 48 ++- src/lib/actions/inference-set/native.ts | 73 +++- .../inference-invocation-probe.test.ts | 69 +++- .../sandbox/inference-invocation-probe.ts | 48 ++- .../sandbox/inference-route-health.test.ts | 16 + .../actions/sandbox/inference-route-health.ts | 20 +- .../sandbox/rebuild-credential-preflight.ts | 8 +- .../actions/sandbox/rebuild-resume-config.ts | 7 +- src/lib/core/provider-endpoint.ts | 62 +++ src/lib/core/url-utils.ts | 65 +-- src/lib/inference/config.ts | 20 +- .../inference/native-provider/agent-config.ts | 20 +- src/lib/inference/native-provider/contract.ts | 13 +- .../inference/native-provider/custom-setup.ts | 146 +++++++ .../inference/native-provider/custom.test.ts | 373 ++++++++++++++++++ src/lib/inference/native-provider/custom.ts | 197 +++++++++ .../native-provider/hosted-attachment.ts | 12 +- src/lib/inference/native-provider/hosted.ts | 12 +- src/lib/inference/native-provider/index.ts | 20 +- .../native-provider/network-policy.ts | 12 +- .../native-provider/recorded-selection.ts | 23 ++ src/lib/inference/native-provider/setup.ts | 2 + src/lib/onboard/setup-inference.ts | 61 ++- src/lib/onboard/setup-native-hosted.test.ts | 41 +- .../native-hosted-provider-authority.test.ts | 63 +++ .../registry/native-provider-authority.ts | 15 +- src/lib/state/registry/route-reservation.ts | 2 +- test/e2e/README.md | 5 +- ...drock-runtime-compatible-anthropic.test.ts | 4 +- test/e2e/live/full-e2e-inference-probe.ts | 87 +++- test/e2e/live/full-e2e-native-model.ts | 19 +- test/e2e/live/full-e2e.test.ts | 54 ++- .../support/full-e2e-inference-probe.test.ts | 126 ++++-- .../e2e/support/full-e2e-native-model.test.ts | 14 + .../generate-native-hosted-config.test.ts | 19 +- 40 files changed, 1765 insertions(+), 201 deletions(-) create mode 100644 src/lib/core/provider-endpoint.ts create mode 100644 src/lib/inference/native-provider/custom-setup.ts create mode 100644 src/lib/inference/native-provider/custom.test.ts create mode 100644 src/lib/inference/native-provider/custom.ts diff --git a/src/lib/actions/credentials/reset-native-hosted.test.ts b/src/lib/actions/credentials/reset-native-hosted.test.ts index fbe4a5ae6c6..60872d5046b 100644 --- a/src/lib/actions/credentials/reset-native-hosted.test.ts +++ b/src/lib/actions/credentials/reset-native-hosted.test.ts @@ -7,6 +7,7 @@ import { HOSTED_NATIVE_PROVIDERS, hostedNativeProvider, } from "../../inference/native-provider/hosted"; +import { customNativeProvider } from "../../inference/native-provider/custom"; import { resetNativeHostedProvider } from "./reset-native-hosted"; const target = { kind: "named", gatewayName: "gateway" } as const; @@ -14,13 +15,20 @@ const absent = { ok: false, error: { kind: "command", reason: "not_found", message: "absent" }, } as const; -function fixture(provider = "openai-api") { - const definition = hostedNativeProvider(provider)!; +function fixture(provider = "openai-api", custom?: ReturnType) { + const definition = custom ?? hostedNativeProvider(provider)!; const receipt = { schemaVersion: 1 as const, profileId: definition.profileId, providerName: definition.providerName, providerId: "owned-id", + ...(definition.custom + ? { + custom: definition.custom, + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + } + : {}), }; const metadata = { name: definition.providerName, @@ -154,3 +162,32 @@ describe("native hosted credential reset", () => { expect(f.clear).not.toHaveBeenCalled(); }); }); + +it("removes only an unreferenced custom provider selected by its owned name", async () => { + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const f = fixture(definition.logicalProvider, definition); + expect( + ( + await resetNativeHostedProvider(definition.providerName, target, f.adapter, { + ...f.deps, + listNativeHostedProviderAttachmentSandboxNames: () => ["alpha"], + }) + )?.exitCode, + ).toBe(1); + expect(f.remove).not.toHaveBeenCalled(); + f.get.mockResolvedValueOnce({ ok: true, value: f.metadata }).mockResolvedValueOnce(absent); + expect( + (await resetNativeHostedProvider(definition.providerName, target, f.adapter, f.deps))?.exitCode, + ).toBe(0); + expect(f.remove).toHaveBeenCalledExactlyOnceWith({ + target, + providerName: definition.providerName, + }); + expect(f.clear).toHaveBeenCalledWith("gateway", f.receipt); +}); diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index bbbe6de5052..d80547b0636 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -5,6 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import { describe, expect, it, vi } from "vitest"; +import { customNativeProvider } from "../inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS } from "../inference/native-provider/hosted"; import { buildHttpsPinRouteBaseUrl } from "../inference/https-pin-runtime"; import { @@ -1076,7 +1077,21 @@ describe("runInferenceGet", () => { }); describe("native hosted inference get", () => { - it.each(HOSTED_NATIVE_PROVIDERS)( + it.each([ + ...HOSTED_NATIVE_PROVIDERS.map((definition) => ({ + ...definition, + endpointUrl: undefined, + allowedIps: undefined, + custom: undefined, + })), + customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "CUSTOM_KEY", + allowedIps: ["8.8.8.8"], + }), + ])( "reports $logicalProvider from the selected sandbox rather than the shared route", async (definition) => { const deps = createDeps(configuredRoute("ollama-local", "other-sandbox-model")); @@ -1089,6 +1104,9 @@ describe("native hosted inference get", () => { profileId: definition.profileId, providerName: definition.providerName, providerId: "owned-provider-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, }, }); await expect(runInferenceGet({ sandboxName: "alpha", quiet: true }, deps)).resolves.toEqual({ diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index 352f7f08f86..ba653abb644 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -311,15 +311,18 @@ export async function runInferenceGet( const selectedSandbox = selectedSandboxName ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) : null; - if (selectedSandbox && recordedNativeProviderAttachment(selectedSandbox)) { + const nativeAttachment = selectedSandbox && recordedNativeProviderAttachment(selectedSandbox); + if (selectedSandbox && nativeAttachment) { const payload: InferenceGetResult = { provider: selectedSandbox.provider ?? null, model: selectedSandbox.model ?? null, endpointUrl: + nativeAttachment.endpointUrl ?? hostedNativeProvider( selectedSandbox.provider, selectedSandbox.nativeHostedProviderAttachment?.endpointUrl, - )?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT, + )?.endpoint ?? + NVIDIA_HOSTED_NATIVE_ENDPOINT, }; if (!options.quiet) { if (options.json) { diff --git a/src/lib/actions/inference-set-native-hosted.test.ts b/src/lib/actions/inference-set-native-hosted.test.ts index fd23215b1fe..ce715c76080 100644 --- a/src/lib/actions/inference-set-native-hosted.test.ts +++ b/src/lib/actions/inference-set-native-hosted.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { customNativeProvider } from "../inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS, hostedNativeProvider } from "../inference/native-provider/hosted"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; import { fixedNativeProvider } from "../inference/native-provider/fixed"; @@ -92,7 +93,7 @@ function fixture(extraDefinitions: ReturnType[] = [ deps.getNativeHostedProviderAuthority = (gateway, provider) => authorities.get(`${gateway}/${provider}`); deps.setNativeHostedProviderAuthority = (gateway, provider, receipt) => { - authorities.set(`${gateway}/${provider}`, receipt); + authorities.set(`${gateway}/${receipt.custom ? receipt.providerName : provider}`, receipt); }; return { deps, calls, attached, authorities, entry }; } @@ -514,3 +515,102 @@ describe("Hermes native gateway credential refresh", () => { }, ); }); + +describe("custom native inference selection", () => { + const custom = customNativeProvider({ + provider: "compatible-endpoint", + api: "openai-completions", + endpointUrl: "https://8.8.8.8/team/v1", + credentialEnv: "COMPATIBLE_API_KEY", + allowedIps: ["8.8.8.8"], + }); + const replacement = customNativeProvider({ + ...custom.custom, + endpointUrl: "https://1.1.1.1/team/v1", + allowedIps: ["1.1.1.1"], + }); + it("switches a native sandbox, reuses its key for model changes and preserves rebuild authority", async () => { + const { deps, calls, entry, attached } = fixture([custom, replacement]); + await runInferenceSet({ provider: "openai-api", model: "first-model" }, deps); + await runInferenceSet( + { + provider: "compatible-endpoint", + model: "custom-model", + endpointUrl: custom.endpoint, + inferenceApi: custom.api, + }, + deps, + ); + expect(entry.endpointUrl).toBe(custom.endpoint); + expect(entry.nativeHostedProviderAttachment?.custom).toEqual(custom.custom); + expect([...attached.get("alpha")!]).toEqual([custom.providerName]); + expect([...attached.get("beta")!]).toEqual(["unrelated-provider"]); + deps.resolveCredentialValue = () => ""; + await runInferenceSet({ provider: "compatible-endpoint", model: "second-model" }, deps); + expect(calls.updateProvider).not.toHaveBeenCalled(); + expect(entry.model).toBe("second-model"); + expect(JSON.stringify(deps.calls.setOpenClawConfigValues.mock.calls)).toContain( + custom.endpoint, + ); + const previous = structuredClone(entry); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "third-model", + endpointUrl: replacement.endpoint, + inferenceApi: replacement.api, + }, + deps, + ), + ).rejects.toThrow("A new credential is required"); + expect(entry).toEqual(previous); + expect([...attached.get("alpha")!]).toEqual([custom.providerName]); + expect(deps.inferenceRouteObserver.observeInferenceRoute).not.toHaveBeenCalled(); + }); + it("restores the prior attachment if a changed custom endpoint fails sandbox verification", async () => { + const { deps, calls, entry, attached, authorities } = fixture([custom, replacement]); + await runInferenceSet({ provider: "openai-api", model: "first-model" }, deps); + await runInferenceSet( + { + provider: "compatible-endpoint", + model: "custom-model", + endpointUrl: custom.endpoint, + inferenceApi: custom.api, + }, + deps, + ); + const previous = structuredClone(entry); + const attach = calls.attachProvider.getMockImplementation()!; + calls.attachProvider.mockImplementation(async (request) => { + const conflicting = + request.providerName === custom.providerName + ? replacement.providerName + : custom.providerName; + expect(attached.get(request.sandboxName)).not.toContain(conflicting); + return attach(request); + }); + deps.calls.probeSandboxRoute.mockResolvedValue({ + ok: false, + detail: "endpoint refused", + httpStatus: 401, + }); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "third-model", + endpointUrl: replacement.endpoint, + inferenceApi: replacement.api, + }, + deps, + ), + ).rejects.toThrow(); + expect(entry).toEqual(previous); + expect([...attached.get("alpha")!]).toEqual([custom.providerName]); + expect([...attached.get("beta")!]).toEqual(["unrelated-provider"]); + expect(authorities.get(`nemoclaw/${replacement.providerName}`)?.providerId).toBe( + `id-${replacement.providerName}`, + ); + }); +}); diff --git a/src/lib/actions/inference-set-route-containment.ts b/src/lib/actions/inference-set-route-containment.ts index 3319c39c9ed..c2718f5ec74 100644 --- a/src/lib/actions/inference-set-route-containment.ts +++ b/src/lib/actions/inference-set-route-containment.ts @@ -496,6 +496,7 @@ export async function finalizeInferenceSetRoute(options: { resolveCredentialValue: (credentialEnv: string) => string; ensureHttpsPinRuntimeAdapter: EnsureHttpsPinRuntimeAdapterFn; effectiveInferenceApi?: string | null; + nativeProvider?: boolean; }): Promise<{ registryMetadata: RegistryInferenceMetadata; explicitPreferredInferenceApi: string | null; @@ -504,6 +505,25 @@ export async function finalizeInferenceSetRoute(options: { routeImpactWarning: string | null; }> { const { prepared } = options; + if (options.nativeProvider) { + const metadata = prepared.preliminaryExplicitMetadata ?? prepared.preliminaryRegistryMetadata; + return { + registryMetadata: { + ...metadata, + ...(prepared.preliminaryExplicitSourceEndpointUrl + ? { + endpointUrl: prepared.preliminaryExplicitSourceEndpointUrl, + endpointSource: "inference-set" as const, + } + : {}), + }, + explicitPreferredInferenceApi: + prepared.preliminaryExplicitMetadata?.preferredInferenceApi ?? null, + directProviderBinding: null, + httpsPinProviderBinding: null, + routeImpactWarning: null, + }; + } if (!prepared.preliminaryExplicitMetadata) { return { registryMetadata: prepared.preliminaryRegistryMetadata, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index cb2b42d4a74..dfad3661534 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -63,6 +63,7 @@ import { prepareNativeTransitionAuthority, prepareNativeSelection, isNativeInferenceSelection, + usesNativeConfigByDefault, rollbackNativeSelection, detachPreviousNativeBeforePublish, restorePreviousNativeAfterFailedPublish, @@ -733,7 +734,7 @@ export function patchOpenClawInferenceConfig( reasoningEffort: ReasoningEffortRequest = { effort: null, explicit: false }, inheritPrimaryReplyBudget = true, nativeEndpointUrl?: string, - nativeProvider = true, + nativeProvider = usesNativeConfigByDefault(provider, nativeEndpointUrl), ): { changed: boolean; route: SandboxInferenceConfig } { const before = JSON.stringify(config); const route = getSandboxInferenceConfig( @@ -843,7 +844,7 @@ export function patchHermesInferenceConfig( preferredInferenceApi: string | null = null, contextWindow?: number, nativeEndpointUrl?: string, - nativeProvider = true, + nativeProvider = usesNativeConfigByDefault(provider, nativeEndpointUrl), nativeCredentialHandle?: string, ): { changed: boolean; route: SandboxInferenceConfig } { const before = JSON.stringify(config); @@ -1076,8 +1077,10 @@ async function assertHermesCompatibleAnthropicOpenAiProvider( httpsPinProviderBinding: { providerType: "openai" | "anthropic"; } | null = null, + nativeProvider = false, ): Promise { if ( + nativeProvider || agentName !== "hermes" || provider !== "compatible-anthropic-endpoint" || isBedrockRuntimeEndpoint(endpointUrl) @@ -1306,6 +1309,7 @@ async function runInferenceSetWithoutHostLock( httpsPinProviderBinding, routeImpactWarning, } = await finalizeInferenceSetRoute({ + nativeProvider: selectingNative, prepared: preparedRoute, sandboxName, provider, @@ -1396,6 +1400,7 @@ async function runInferenceSetWithoutHostLock( registryMetadata.endpointUrl ?? null, deps, httpsPinProviderBinding ?? directProviderBinding, + selectingNative, ); // Read the in-sandbox config *before* mutating the gateway route or registry. @@ -1522,6 +1527,20 @@ async function runInferenceSetWithoutHostLock( expectedAttachment: nativeProviderAuthority, gatewayName: preparedRoute.gatewayName, sandboxName, + endpointUrl: registryMetadata.endpointUrl, + credentialEnv: registryMetadata.credentialEnv, + inferenceApi: preMutationInferenceApi, + beforeAttach: async (receipt) => { + previousNativeDetached = await detachPreviousNativeBeforePublish({ + selectingNative, + selectedProvider: provider, + selectedAttachment: receipt, + previousAttachment: previousNativeAttachment, + gatewayName: preparedRoute.gatewayName, + sandboxName, + deps, + }); + }, deps, }); nativeProviderAttachment = nativeSelection.attachment; @@ -1690,9 +1709,10 @@ async function runInferenceSetWithoutHostLock( // Removing previous native access is a security gate for publishing another // route. Do not commit the non-native registry/config while the sandbox can // still use the credential-bearing attached provider. - previousNativeDetached = await detachPreviousNativeBeforePublish({ + previousNativeDetached ||= await detachPreviousNativeBeforePublish({ selectingNative, selectedProvider: provider, + selectedAttachment: nativeProviderAttachment, previousAttachment: previousNativeAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, @@ -1725,7 +1745,9 @@ async function runInferenceSetWithoutHostLock( }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), ...nativeSelectionRegistryFields(nativeProviderAttachment, previousNativeDetached), - ...(nativeSelection.endpointUrl ? { endpointUrl: nativeSelection.endpointUrl } : {}), + ...(nativeSelection.endpointUrl && !nativeProviderAttachment?.custom + ? { endpointUrl: nativeSelection.endpointUrl } + : {}), }); if ( !deps.updateSandbox( @@ -1958,19 +1980,21 @@ async function runInferenceSetWithoutHostLock( expectedGatewayName, ); if (error instanceof OpenClawInferenceConfigSyncError) throw error; - await restorePreviousNativeAfterFailedPublish({ - detached: previousNativeDetached, - committed: previousNativeDetachCommitted, - previousAttachment: previousNativeAttachment, + // Custom endpoints share an injection environment name. Remove the failed + // selection before restoring access so the provider composition cannot collide. + await rollbackNativeSelection({ + attachmentChanged: nativeAttachmentChanged, + registryCommitted: nativeRegistryCommitted, + attachment: nativeProviderAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, error, deps, }); - await rollbackNativeSelection({ - attachmentChanged: nativeAttachmentChanged, - registryCommitted: nativeRegistryCommitted, - attachment: nativeProviderAttachment, + await restorePreviousNativeAfterFailedPublish({ + detached: previousNativeDetached, + committed: previousNativeDetachCommitted, + previousAttachment: previousNativeAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, error, diff --git a/src/lib/actions/inference-set/native.ts b/src/lib/actions/inference-set/native.ts index 1ea2a0a4ffa..0ae5726bf76 100644 --- a/src/lib/actions/inference-set/native.ts +++ b/src/lib/actions/inference-set/native.ts @@ -20,9 +20,18 @@ import { import { hostedNativeProvider, usesNativeHermesEndpoint, + isCustomHostedProvider, + customNativeCredentialEnv, } from "../../inference/native-provider/hosted"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import type { SandboxEntry } from "../../state/registry"; +import { prepareCustomNativeProvider } from "../../inference/native-provider/custom-setup"; +import { isHostedCustomEndpoint } from "../../inference/native-provider/custom"; + +/** Preserve shared-route config unless a custom native endpoint is explicit. */ +export function usesNativeConfigByDefault(provider: string, nativeEndpointUrl?: string): boolean { + return !isCustomHostedProvider(provider) || Boolean(nativeEndpointUrl); +} export function isNativeInferenceSelection( provider: string, @@ -31,6 +40,11 @@ export function isNativeInferenceSelection( gatewayName: string, deps: InferenceSetDeps, ): boolean { + if (isCustomHostedProvider(provider)) { + const endpoint = endpointUrl ?? (entry.provider === provider ? entry.endpointUrl : undefined); + if (!endpoint || !recordedNativeProviderAttachment(entry)) return false; + return isHostedCustomEndpoint(provider, endpoint); + } if (!fixedNativeProvider(provider)) return false; if (provider !== "hermes-provider") return true; const authority = @@ -73,6 +87,10 @@ export function resolveNativeSelectionAuthority(input: { deps: InferenceSetDeps; }): NativeProviderAttachment | undefined { if (!input.selectingNative) return undefined; + if (isCustomHostedProvider(input.provider)) + return input.previousAttachment?.custom?.provider === input.provider + ? input.previousAttachment + : undefined; const fixed = fixedNativeProvider(input.provider); if (!fixed) return undefined; const previous = @@ -114,7 +132,9 @@ export function nativeSelectionRegistryFields( ? { nativeNvidiaProviderAttachment: nvidia } : { nativeHostedProviderAttachment: attachment, - credentialEnv: fixedNativeProviderForAttachment(attachment).credentialEnv, + credentialEnv: + attachment.custom?.credentialEnv ?? + fixedNativeProviderForAttachment(attachment).credentialEnv, }), }; } @@ -143,6 +163,10 @@ export async function prepareNativeSelection(input: { expectedAttachment?: NativeProviderAttachment; gatewayName: string; sandboxName: string; + endpointUrl?: string | null; + credentialEnv?: string | null; + inferenceApi?: string | null; + beforeAttach?: (receipt: NativeProviderAttachment) => Promise; deps: InferenceSetDeps; }): Promise<{ attachment?: NativeProviderAttachment; @@ -150,6 +174,44 @@ export async function prepareNativeSelection(input: { endpointUrl?: string; }> { if (!input.selectingNative) return { attachmentChanged: false }; + if (isCustomHostedProvider(input.provider)) { + if ( + !input.deps.getNativeHostedProviderAuthority || + !input.deps.setNativeHostedProviderAuthority + ) + throw new InferenceSetError("Native hosted provider ownership storage is unavailable"); + const credentialEnv = input.credentialEnv || customNativeCredentialEnv(input.provider); + const receipt = await prepareCustomNativeProvider({ + gatewayName: input.gatewayName, + provider: input.provider, + endpointUrl: input.endpointUrl || "", + api: + input.inferenceApi || + (input.provider === "compatible-anthropic-endpoint" + ? "anthropic-messages" + : "openai-completions"), + credentialEnv, + credentialValue: input.deps.resolveCredentialValue(credentialEnv) || null, + adapter: input.deps.providerAdapter, + recordedAttachment: input.expectedAttachment, + readAuthority: input.deps.getNativeHostedProviderAuthority, + writeAuthority: input.deps.setNativeHostedProviderAuthority, + }); + await input.beforeAttach?.(receipt); + const attached = await nativeProviderLifecycle( + fixedNativeProviderForAttachment(receipt), + ).ensureNativeProviderAttached({ + adapter: input.deps.providerAdapter, + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: receipt, + }); + return { + attachment: attached.receipt, + attachmentChanged: attached.changed, + endpointUrl: receipt.endpointUrl, + }; + } const definition = input.expectedAttachment ? fixedNativeProviderForAttachment(input.expectedAttachment) : fixedNativeProvider(input.provider); @@ -226,6 +288,7 @@ export async function rollbackNativeSelection(input: { export async function detachPreviousNativeBeforePublish(input: { selectingNative: boolean; selectedProvider: string; + selectedAttachment?: NativeProviderAttachment; previousAttachment?: NativeProviderAttachment; gatewayName: string; sandboxName: string; @@ -233,7 +296,13 @@ export async function detachPreviousNativeBeforePublish(input: { }): Promise { if (!input.previousAttachment) return false; const previous = fixedNativeProviderForAttachment(input.previousAttachment); - if (input.selectingNative && input.selectedProvider === previous.logicalProvider) return false; + if ( + input.selectingNative && + (input.selectedAttachment + ? input.selectedAttachment.providerName === input.previousAttachment.providerName + : !input.previousAttachment.custom && input.selectedProvider === previous.logicalProvider) + ) + return false; await nativeProviderLifecycle(previous).detachNativeProvider({ adapter: input.deps.providerAdapter, target: { kind: "named", gatewayName: input.gatewayName }, diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 182c9219468..9bcb4326d56 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -16,7 +16,7 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; +import { assert, describe, expect, it, vi } from "vitest"; import { isNvcfFunctionNotFoundForAccount } from "../../inference/nvcf-model-access"; import { @@ -755,6 +755,73 @@ it("gives native Ultra readiness the same reasoning budget as host onboarding", }); describe("native hosted inference probe credential boundary", () => { + it.each([ + [ + "compatible-endpoint", + "COMPATIBLE_API_KEY", + "openai-completions", + "https://custom.example/team/v1", + "/chat/completions", + "Authorization: Bearer", + ], + [ + "compatible-endpoint", + "COMPATIBLE_API_KEY", + "openai-responses", + "https://custom.example/team/v1", + "/responses", + "Authorization: Bearer", + ], + [ + "compatible-anthropic-endpoint", + "COMPATIBLE_ANTHROPIC_API_KEY", + "anthropic-messages", + "https://custom.example/team", + "/v1/messages", + "x-api-key:", + ], + ])("uses the custom %s %s %s binding", (provider, env, api, endpoint, suffix, header) => { + const placeholder = `openshell:resolve:env:v123_${env}`; + const result = runProbeCommandWithBody( + "200", + "{}", + tmpdir(), + { + ...input, + provider, + preferredInferenceApi: api, + nativeProvider: true, + nativeEndpointUrl: endpoint, + }, + { [env]: placeholder }, + ); + expect(result.argv.at(-1)).toBe(endpoint + suffix); + expect(result.argv).toContain(`${header} ${placeholder}`); + expect(result.stdout).toBe("200\n{}"); + }); + + it.each([true, false])( + "gives conditional legacy DNS guidance only for a shared route (native=%s)", + async (nativeProvider) => { + const result = await probeSandboxInferenceInvocation( + { + ...input, + nativeProvider, + ...(nativeProvider ? { nativeEndpointUrl: "https://custom.example/v1" } : {}), + }, + { execute: vi.fn(async () => ({ status: 6, stdout: "curl-error:6\n", stderr: "" })) }, + ); + expect(result.ok).toBe(false); + assert(result.ok === false); + expect(result.detail.includes("If that route is no longer available")).toBe(!nativeProvider); + expect(result.endpoint).toBe( + nativeProvider + ? "https://custom.example/v1/chat/completions" + : "https://inference.local/v1/chat/completions", + ); + }, + ); + it.each([ [ "openai-api", diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index c062fdfab04..2e41e77bd62 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -2,7 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; -import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { + hostedNativeProvider, + customNativeCredentialEnv, + isCustomHostedProvider, +} from "../../inference/native-provider/hosted"; import { nativeHostedAgentConfig } from "../../inference/native-provider/agent-config"; import { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; import type { @@ -79,6 +83,24 @@ export const INFERENCE_INVOCATION_REQUEST_TIMEOUT_SECONDS = 90; export const READINESS_INFERENCE_INVOCATION_TIMEOUT_MS = 95_000; const INFERENCE_INVOCATION_MAX_RESPONSE_BYTES = 64 * 1024; +function nativeProbeDefinition(input: SandboxInferenceInvocationInput) { + if (input.nativeProvider && isCustomHostedProvider(input.provider)) { + if (!input.nativeEndpointUrl) + throw new Error("Custom native inference probe is missing its endpoint"); + return { + logicalProvider: input.provider, + endpoint: input.nativeEndpointUrl, + credentialEnv: customNativeCredentialEnv(input.provider), + api: + input.preferredInferenceApi ?? + (input.provider === "compatible-anthropic-endpoint" + ? "anthropic-messages" + : "openai-completions"), + }; + } + return hostedNativeProvider(input.provider, input.nativeEndpointUrl); +} + /** Build the protocol-specific request used to verify sandbox inference. */ function buildProbeRequest(input: SandboxInferenceInvocationInput): { endpoint: string; @@ -91,7 +113,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { input.preferredInferenceApi, ); const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); - const hosted = hostedNativeProvider(input.provider, input.nativeEndpointUrl); + const hosted = nativeProbeDefinition(input); const nativeHosted = input.nativeProvider === true ? hosted : undefined; if (input.nativeProvider === true && !useNativeNvidia && !nativeHosted) { throw new Error("Unsupported native inference probe selection"); @@ -159,9 +181,10 @@ export function resolveSandboxInferenceInvocationEndpoint( } /** Accept only an OpenShell-issued placeholder, never a host credential. */ -function nativeHostedAuthHeaderScript(provider: string): string { - const definition = hostedNativeProvider(provider); - if (!definition) throw new Error("Unsupported native hosted inference probe"); +export function nativeHostedAuthHeaderScript(definition: { + credentialEnv: string; + api: string; +}): string { const env = definition.credentialEnv; const value = "${" + env + ":-}"; const header = definition.api === "anthropic-messages" ? "x-api-key:" : "Authorization: Bearer"; @@ -177,14 +200,11 @@ export function buildSandboxInferenceInvocationCommand( ): string { const request = buildProbeRequest(input); const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); - const nativeHosted = - input.nativeProvider === true - ? hostedNativeProvider(input.provider, input.nativeEndpointUrl) - : undefined; + const nativeHosted = input.nativeProvider === true ? nativeProbeDefinition(input) : undefined; const nativeAuth = useNativeNvidia ? NATIVE_NVIDIA_AUTH_HEADER_SCRIPT : nativeHosted - ? nativeHostedAuthHeaderScript(nativeHosted.logicalProvider) + ? nativeHostedAuthHeaderScript(nativeHosted) : undefined; const headerArgs = ["Content-Type: application/json", ...request.headers] @@ -325,12 +345,18 @@ export async function probeSandboxInferenceInvocation( const detail = httpStatus ? `sandbox inference invocation probe returned HTTP ${httpStatus}` : `sandbox inference invocation probe exited with status ${result.status}`; + const legacyDnsFailure = + input.nativeProvider !== true && + result.stdout.split("\n").some((line) => line.trim() === "curl-error:6") && + new URL(resolveSandboxInferenceInvocationEndpoint(input)).hostname === "inference.local"; return { ok: false, detail: httpStatus === "404" && nvcfFunctionNotFound ? `${detail}: ${nvcfFunctionNotFoundMessage(input.model).replace(/\.$/, "")}` - : detail, + : legacyDnsFailure + ? `${detail}. The legacy inference route could not be resolved. If that route is no longer available, recreate this sandbox to use native inference.` + : detail, httpStatus: httpStatus ? Number.parseInt(httpStatus, 10) : null, endpoint: resolveSandboxInferenceInvocationEndpoint(input), }; diff --git a/src/lib/actions/sandbox/inference-route-health.test.ts b/src/lib/actions/sandbox/inference-route-health.test.ts index d08c9ac4145..2ea3e29f6f3 100644 --- a/src/lib/actions/sandbox/inference-route-health.test.ts +++ b/src/lib/actions/sandbox/inference-route-health.test.ts @@ -446,3 +446,19 @@ describe("transient inference invocation failures", () => { expect(isTransientInferenceInvocationFailure(null)).toBe(false); }); }); + +it("offers conditional recreation guidance when the legacy route cannot be reached", () => { + const health = buildSandboxInferenceRouteHealth( + { + ok: false, + endpoint: "https://inference.local/v1/models", + httpStatus: 0, + detail: "Inference gateway is unreachable.", + }, + null, + null, + { provider: "compatible-endpoint", model: "selected" }, + ); + expect(health.ok).toBe(false); + expect(health.detail).toContain("If this legacy route is no longer available"); +}); diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 18f32cbbb1a..43ffa316dc6 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -4,6 +4,7 @@ import type { SandboxEntry } from "../../state/registry/types"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { hostedNativeProviderForAttachment } from "../../inference/native-provider/hosted-attachment"; import { fixedNativeProvider, fixedNativeProviderForAttachment, @@ -409,7 +410,13 @@ export function buildSandboxInferenceRouteHealth( invocation: SandboxInferenceInvocationResult | null, context: SandboxInferenceRouteHealthContext, ): ProviderHealthStatus { - const definition = fixedNativeProvider(context.provider); + const definition = + fixedNativeProvider(context.provider) ?? + (context.nativeProvider && + (context.provider === "compatible-endpoint" || + context.provider === "compatible-anthropic-endpoint") + ? { logicalProvider: context.provider, label: "custom hosted" } + : undefined); if ((context.nativeProvider || context.nativeNvidia) && definition) { const endpoint = invocation && !invocation.ok && invocation.endpoint @@ -493,6 +500,13 @@ export function buildSandboxInferenceRouteHealth( detail: `Could not probe ${endpoint} from inside the sandbox.`, }; } + if ( + !routeHealth.ok && + gateway?.httpStatus === 0 && + new URL(endpoint).hostname === "inference.local" + ) + routeHealth.detail += + " If this legacy route is no longer available, recreate the sandbox to use native inference."; const subprobes = [...(routeHealth.subprobes ?? []), ...diagnostics]; return subprobes.length > 0 ? { ...routeHealth, subprobes } : routeHealth; } @@ -526,7 +540,9 @@ export function readNativeStatusSelection(entry: SandboxEntry | null | undefined } catch { failure = "Recorded native provider ownership is invalid; no inference request was sent."; } - const definition = hostedNativeProvider(entry?.provider, attachment?.endpointUrl); + const definition = attachment + ? hostedNativeProviderForAttachment(attachment) + : hostedNativeProvider(entry?.provider); return { attachment, failure, diff --git a/src/lib/actions/sandbox/rebuild-credential-preflight.ts b/src/lib/actions/sandbox/rebuild-credential-preflight.ts index fc927b34f3f..7f73b8f33a2 100644 --- a/src/lib/actions/sandbox/rebuild-credential-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-credential-preflight.ts @@ -187,16 +187,18 @@ export async function preflightRebuildCredentials( return false; } if (nativeAttachment) { - const nativeCredentialEnv = fixedNativeProviderForAttachment(nativeAttachment).credentialEnv; + const definition = fixedNativeProviderForAttachment(nativeAttachment); + const nativeCredentialEnv = definition.credentialEnv; if ( !(await checkRebuildGatewayProviderOrBail(rebuildProvider, nativeCredentialEnv, log, bail, { nativeAttachment, })) ) return false; + const sourceCredentialEnv = definition.custom?.credentialEnv ?? nativeCredentialEnv; return preflightRebuildHostCredential( - { ...sb, credentialEnv: nativeCredentialEnv }, - rebuildOnboardDependencies.hydrateCredentialEnv(nativeCredentialEnv), + { ...sb, credentialEnv: sourceCredentialEnv }, + rebuildOnboardDependencies.hydrateCredentialEnv(sourceCredentialEnv), bail, ); } diff --git a/src/lib/actions/sandbox/rebuild-resume-config.ts b/src/lib/actions/sandbox/rebuild-resume-config.ts index 97a78f4f0e8..9d40cf6a2fa 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.ts @@ -257,11 +257,13 @@ export function prepareRebuildResumeConfig( return null; } if (hostedDefinition) { - const expectedEndpoint = hostedDefinition.endpoint; + const expectedEndpoint = hostedDefinition.custom?.endpointUrl ?? hostedDefinition.endpoint; if ( (sb.endpointUrl && sb.endpointUrl.replace(/\/+$/, "") !== expectedEndpoint.replace(/\/+$/, "")) || - (sb.credentialEnv && sb.credentialEnv !== hostedDefinition.credentialEnv) + (sb.credentialEnv && + sb.credentialEnv !== + (hostedDefinition.custom?.credentialEnv ?? hostedDefinition.credentialEnv)) ) { bail( "Native provider selection does not match recorded credential or endpoint; sandbox is untouched", @@ -271,6 +273,7 @@ export function prepareRebuildResumeConfig( endpointUrl = expectedEndpoint; } const credentialEnv = + hostedDefinition?.custom?.credentialEnv ?? hostedDefinition?.credentialEnv ?? getRebuildCredentialEnvFromRegistry( trustedSelection.provider, diff --git a/src/lib/core/provider-endpoint.ts b/src/lib/core/provider-endpoint.ts new file mode 100644 index 00000000000..42e240c8e0b --- /dev/null +++ b/src/lib/core/provider-endpoint.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { MAX_CANONICAL_ENDPOINT_LENGTH } from "./endpoint-url-safety.ts"; + +export function stripEndpointSuffix(pathname = "", suffixes: string[] = []): string { + for (const suffix of suffixes) { + if (pathname === suffix) return ""; + if (pathname.endsWith(suffix)) { + return pathname.slice(0, -suffix.length); + } + } + return pathname; +} + +export type EndpointFlavor = "anthropic" | "openai"; + +export function normalizeProviderBaseUrl( + value: string | URL | null | undefined, + flavor: EndpointFlavor, +): string { + const raw = String(value || "").trim(); + if (!raw) return ""; + + try { + const url = new URL(raw); + url.search = ""; + url.hash = ""; + const suffixes = + flavor === "anthropic" + ? ["/v1/messages", "/v1/models", "/v1", "/messages", "/models"] + : ["/responses", "/chat/completions", "/completions", "/models"]; + let pathname = stripEndpointSuffix(url.pathname.replace(/\/+$/, ""), suffixes); + pathname = pathname.replace(/\/+$/, ""); + url.pathname = pathname || "/"; + return url.pathname === "/" ? url.origin : `${url.origin}${url.pathname}`; + } catch { + return raw.replace(/[?#].*$/, "").replace(/\/+$/, ""); + } +} + +/** Return the bounded canonical form of a credential-free HTTP(S) provider endpoint. */ +export function canonicalEndpoint( + value: string | null | undefined, + flavor: EndpointFlavor, +): string | null { + const raw = typeof value === "string" ? value.trim() : ""; + if (!raw || raw.length > MAX_CANONICAL_ENDPOINT_LENGTH) return null; + try { + const parsed = new URL(raw); + if ( + (parsed.protocol !== "http:" && parsed.protocol !== "https:") || + parsed.username || + parsed.password + ) { + return null; + } + return normalizeProviderBaseUrl(parsed, flavor); + } catch { + return null; + } +} diff --git a/src/lib/core/url-utils.ts b/src/lib/core/url-utils.ts index 4c297fc4c6f..70f64592a61 100644 --- a/src/lib/core/url-utils.ts +++ b/src/lib/core/url-utils.ts @@ -6,70 +6,17 @@ * formatting helpers used across the CLI. */ -import { MAX_CANONICAL_ENDPOINT_LENGTH } from "./endpoint-url-safety.ts"; +export { + stripEndpointSuffix, + normalizeProviderBaseUrl, + canonicalEndpoint, + type EndpointFlavor, +} from "./provider-endpoint.ts"; export function compactText(value = ""): string { return String(value).replace(/\s+/g, " ").trim(); } -export function stripEndpointSuffix(pathname = "", suffixes: string[] = []): string { - for (const suffix of suffixes) { - if (pathname === suffix) return ""; - if (pathname.endsWith(suffix)) { - return pathname.slice(0, -suffix.length); - } - } - return pathname; -} - -export type EndpointFlavor = "anthropic" | "openai"; - -export function normalizeProviderBaseUrl( - value: string | URL | null | undefined, - flavor: EndpointFlavor, -): string { - const raw = String(value || "").trim(); - if (!raw) return ""; - - try { - const url = new URL(raw); - url.search = ""; - url.hash = ""; - const suffixes = - flavor === "anthropic" - ? ["/v1/messages", "/v1/models", "/v1", "/messages", "/models"] - : ["/responses", "/chat/completions", "/completions", "/models"]; - let pathname = stripEndpointSuffix(url.pathname.replace(/\/+$/, ""), suffixes); - pathname = pathname.replace(/\/+$/, ""); - url.pathname = pathname || "/"; - return url.pathname === "/" ? url.origin : `${url.origin}${url.pathname}`; - } catch { - return raw.replace(/[?#].*$/, "").replace(/\/+$/, ""); - } -} - -/** Return the bounded canonical form of a credential-free HTTP(S) provider endpoint. */ -export function canonicalEndpoint( - value: string | null | undefined, - flavor: EndpointFlavor, -): string | null { - const raw = typeof value === "string" ? value.trim() : ""; - if (!raw || raw.length > MAX_CANONICAL_ENDPOINT_LENGTH) return null; - try { - const parsed = new URL(raw); - if ( - (parsed.protocol !== "http:" && parsed.protocol !== "https:") || - parsed.username || - parsed.password - ) { - return null; - } - return normalizeProviderBaseUrl(parsed, flavor); - } catch { - return null; - } -} - export function isLoopbackHostname(hostname = ""): boolean { const normalized = String(hostname || "") .trim() diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index a81ae2dc431..f34facb6439 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -14,6 +14,12 @@ import { LLAMA_CPP_PROVIDER_NAME, } from "./llama-cpp/contract"; import { hostedNativeProvider, usesNativeHermesEndpoint } from "./native-provider/hosted"; +import { isCustomHostedProvider } from "./native-provider/hosted"; +import { + isBedrockRuntimeEndpoint, + BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, +} from "./bedrock-runtime"; +import { getCompatibleAnthropicOpenAiSurfaceBaseUrl } from "./anthropic/openai-surface"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; import type { ManagedLlamaCppOwnership } from "./llama-cpp/managed-state"; import { DEFAULT_OLLAMA_MODEL_TAG as DEFAULT_OLLAMA_MODEL } from "./ollama-model-registry"; @@ -333,7 +339,17 @@ export function getSandboxInferenceConfig( const hostedNative = useNativeProvider ? hostedNativeProvider(provider, nativeEndpointUrl) : undefined; - let inferenceBaseUrl = hostedNative?.endpoint ?? INFERENCE_ROUTE_URL; + let customEndpoint = + nativeProvider === true && isCustomHostedProvider(provider) ? nativeEndpointUrl : undefined; + if (nativeProvider === true && isCustomHostedProvider(provider) && !customEndpoint) + throw new Error("Native custom inference is missing its recorded endpoint"); + if (customEndpoint && provider === "compatible-anthropic-endpoint") + customEndpoint = isBedrockRuntimeEndpoint(customEndpoint) + ? BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL + : preferredInferenceApi && preferredInferenceApi !== "anthropic-messages" + ? getCompatibleAnthropicOpenAiSurfaceBaseUrl(customEndpoint) + : customEndpoint; + let inferenceBaseUrl = customEndpoint ?? hostedNative?.endpoint ?? INFERENCE_ROUTE_URL; let inferenceApi = preferredInferenceApi || "openai-completions"; // Providers without a /v1/responses endpoint must never be configured with the // Responses API. On a provider switch the runtime API resolves to null and the @@ -363,7 +379,7 @@ export function getSandboxInferenceConfig( } providerKey = "anthropic"; primaryModelRef = `anthropic/${model}`; - inferenceBaseUrl = hostedNative?.endpoint ?? "https://inference.local"; + inferenceBaseUrl = customEndpoint ?? hostedNative?.endpoint ?? "https://inference.local"; inferenceApi = "anthropic-messages"; break; case "gemini-api": diff --git a/src/lib/inference/native-provider/agent-config.ts b/src/lib/inference/native-provider/agent-config.ts index 61cf52941b5..7f5eacbfb61 100644 --- a/src/lib/inference/native-provider/agent-config.ts +++ b/src/lib/inference/native-provider/agent-config.ts @@ -1,10 +1,28 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { hostedNativeProvider } from "./hosted.ts"; +import { + hostedNativeProvider, + customNativeCredentialEnv, + isCustomHostedProvider, +} from "./hosted.ts"; /** Public configuration only. Never read the host's provider credential here. */ export function nativeHostedAgentConfig(provider: string | null | undefined, baseUrl: string) { + if (isCustomHostedProvider(provider) && new URL(baseUrl).hostname !== "inference.local") { + const endpoint = new URL(baseUrl); + if ( + !["https:", "http:"].includes(endpoint.protocol) || + endpoint.username || + endpoint.password || + endpoint.search || + endpoint.hash + ) + throw new Error("Invalid native custom inference endpoint"); + if (["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname)) return undefined; + const credentialEnv = customNativeCredentialEnv(provider!); + return { credentialEnv, apiKey: `openshell:resolve:env:${credentialEnv}` }; + } if (!hostedNativeProvider(provider)) return undefined; // Existing shared-route selections keep their original configuration until explicitly changed. if (new URL(baseUrl).hostname === "inference.local") return undefined; diff --git a/src/lib/inference/native-provider/contract.ts b/src/lib/inference/native-provider/contract.ts index 1134c47a06a..086b0456507 100644 --- a/src/lib/inference/native-provider/contract.ts +++ b/src/lib/inference/native-provider/contract.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { isDeepStrictEqual } from "node:util"; +import type { CustomNativeBinding } from "./custom"; export type NativeProviderAttachment< ProfileId extends string = string, @@ -11,10 +12,11 @@ export type NativeProviderAttachment< profileId: ProfileId; providerName: ProviderName; providerId: string; - /** Present only for Hermes endpoints returned by authenticated login. */ + /** Exact sandbox-facing endpoint for a dynamically bound provider. */ endpointUrl?: string; - /** Exact public destination addresses for an authenticated Hermes endpoint. */ + /** Exact admitted destination addresses for a dynamically bound provider. */ allowedIps?: readonly string[]; + custom?: CustomNativeBinding; }>; export type NativeProviderDefinition< @@ -27,8 +29,9 @@ export type NativeProviderDefinition< providerName: ProviderName; credentialEnv: string; endpointUrl?: string; - /** Exact public destination addresses for an authenticated Hermes endpoint. */ + /** Exact admitted destination addresses for a dynamically bound provider. */ allowedIps?: readonly string[]; + custom?: CustomNativeBinding; }>; /** Keep only the exact profile/name binding and immutable provider identity. */ @@ -36,7 +39,7 @@ export function normalizeNativeProviderAttachment

, - "profileId" | "providerName" | "endpointUrl" | "allowedIps" + "profileId" | "providerName" | "endpointUrl" | "allowedIps" | "custom" >, ): NativeProviderAttachment | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; @@ -47,6 +50,7 @@ export function normalizeNativeProviderAttachment

NativeProviderAttachment | undefined; + writeAuthority: (gateway: string, provider: string, receipt: NativeProviderAttachment) => void; +}): Promise { + if (unsafeEndpointUrlViolation(input.endpointUrl) || /%2f|%5c|%2e/iu.test(input.endpointUrl)) + throw new Error("Custom native inference requires a valid credential-free HTTP(S) endpoint"); + const api = input.api === "responses" ? "openai-responses" : input.api; + const endpointUrl = normalizeProviderBaseUrl( + input.endpointUrl, + input.provider === "compatible-anthropic-endpoint" ? "anthropic" : "openai", + ); + const classified = + input.provider === "compatible-anthropic-endpoint" + ? classifyCustomAnthropicEndpoint(input.endpointUrl) + : undefined; + const bedrock = classified?.kind === "bedrock-runtime" ? classified : undefined; + const previous = input.recordedAttachment + ? requireHostedProviderAttachment(input.recordedAttachment, input.provider) + : undefined; + const sameBinding = + previous?.custom && + previous.custom.endpointUrl === endpointUrl && + previous.custom.api === api && + previous.custom.credentialEnv === input.credentialEnv; + const admitted = + sameBinding || bedrock + ? undefined + : await assertEndpointResolvesPublic(endpointUrl, input.lookup, { + trustedPrivateHosts: + input.trustedPrivateHosts ?? parseTrustedPrivateInferenceHostsFromEnv(process.env), + }); + if (admitted && !admitted.ok) + throw new Error(`Custom native endpoint admission failed: ${admitted.reason}`); + const definition = customNativeProvider({ + provider: input.provider, + endpointUrl, + api, + credentialEnv: input.credentialEnv, + allowedIps: sameBinding + ? previous.custom!.allowedIps + : admitted?.ok + ? admitted.addresses?.length + ? admitted.addresses + : [new URL(endpointUrl).hostname.replace(/^\[|\]$/gu, "")] + : [], + ...(bedrock ? { adapterEndpointUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL } : {}), + } satisfies Omit & { provider: string; api: string }); + const lifecycle = nativeProviderLifecycle(definition); + const expected = lifecycle.resolveGatewayNativeProviderAuthority({ + gatewayName: input.gatewayName, + gatewayAuthority: input.readAuthority(input.gatewayName, definition.providerName), + recordedAttachment: sameBinding ? previous : undefined, + }); + // A credential key name alone cannot authorize reuse at a different endpoint or API. + if (!input.credentialValue && !expected && !(bedrock && hasBedrockRuntimeAwsAuthEnv())) + throw new Error( + `A new credential is required for this endpoint and API. Set ${input.credentialEnv} and retry. No provider was changed.`, + ); + const target = { kind: "named", gatewayName: input.gatewayName } as const; + let credentialValue = expected ? null : input.credentialValue; + if (bedrock && !expected) { + // Reject profile collisions before the existing adapter can start a process. + await lifecycle.requireNativeProviderProfileBoundary(input.adapter, target); + const transport = await (input.ensureBedrockAdapter ?? ensureBedrockRuntimeAdapter)({ + classification: bedrock, + compatibleCredential: input.credentialValue, + }); + if (transport.baseUrl !== definition.endpointUrl) + throw new Error("Bedrock adapter endpoint does not match native provider authority"); + credentialValue = expected ? null : transport.token; + } + const receipt = await lifecycle.ensureNativeProvider({ + adapter: input.adapter, + target, + // Model changes and rebuilds reuse verified ownership without rotating credentials. + credentialValue, + ...(expected ? { expected } : {}), + }); + await lifecycle.persistNativeProviderAuthority({ + adapter: input.adapter, + target, + gatewayName: input.gatewayName, + receipt, + ...(expected ? { existing: expected } : {}), + readAuthority: (gateway) => input.readAuthority(gateway, definition.providerName), + writeAuthority: (gateway, authority) => + input.writeAuthority(gateway, input.provider, authority), + }); + return receipt; +} diff --git a/src/lib/inference/native-provider/custom.test.ts b/src/lib/inference/native-provider/custom.test.ts new file mode 100644 index 00000000000..3fbb0eb77c0 --- /dev/null +++ b/src/lib/inference/native-provider/custom.test.ts @@ -0,0 +1,373 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import YAML from "yaml"; +import { describe, expect, it, vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; +import type { NativeProviderAttachment } from "./contract"; +import { boundCustomNativeProfile, customNativeProvider } from "./custom"; +import { recordedNativeProviderAttachment } from "./recorded-selection"; +import { prepareCustomNativeProvider, usesCustomNativeOnboarding } from "./custom-setup"; +import { requireHostedProviderAttachment } from "./hosted-attachment"; +import { buildNativeHostedSandboxPolicy } from "./network-policy"; +import { nativeProviderLifecycle } from "./index"; +import { getSandboxInferenceConfig } from "../config"; +import { nativeHostedAgentConfig } from "./agent-config"; +import { BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL } from "../bedrock-runtime"; + +const binding = { + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/team/v1", + api: "openai-completions", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], +} as const; + +function harness() { + let present = false; + let receipt: NativeProviderAttachment | undefined; + let definition = customNativeProvider(binding); + const attachments = new Map([["other", ["unrelated-provider"]]]); + const adapter = { + importProviderProfile: vi.fn( + async ({ profilePath }) => { + const profile = YAML.parse(fs.readFileSync(profilePath, "utf8")); + expect(profile.id).toBe(definition.profileId); + return { ok: true }; + }, + ), + ensureProviderPolicyComposition: vi.fn(async () => ({ ok: true, value: undefined })), + getProvider: vi.fn(async () => + present + ? { + ok: true, + value: { + name: definition.providerName, + type: definition.profileId, + credentialKeys: [definition.credentialEnv], + configKeys: [], + revision: { id: "identity", resourceVersion: 1 }, + }, + } + : { ok: false, error: { kind: "command", reason: "not_found", message: "absent" } }, + ), + createProvider: vi.fn(async () => { + present = true; + return { ok: true }; + }), + updateProvider: vi.fn(), + listProviderAttachments: vi.fn( + async ({ sandboxName }) => ({ + ok: true, + value: { names: [...(attachments.get(sandboxName) ?? [])] }, + }), + ), + attachProvider: vi.fn( + async ({ sandboxName, providerName }) => { + attachments.set(sandboxName, [...(attachments.get(sandboxName) ?? []), providerName]); + return { ok: true }; + }, + ), + detachProvider: vi.fn( + async ({ sandboxName, providerName }) => { + attachments.set( + sandboxName, + (attachments.get(sandboxName) ?? []).filter((name) => name !== providerName), + ); + return { ok: true, value: { changed: true } }; + }, + ), + }; + const lookup = vi.fn(async () => [{ address: "8.8.8.8", family: 4 }]); + const writeAuthority = vi.fn( + (_gateway: string, _provider: string, value: NativeProviderAttachment) => { + receipt = value; + }, + ); + const input = { + gatewayName: "gateway", + provider: binding.provider, + endpointUrl: binding.endpointUrl, + api: binding.api, + credentialEnv: binding.credentialEnv, + credentialValue: "synthetic-host-secret", + lookup, + adapter: adapter as unknown as OpenShellProviderAdapter, + readAuthority: (_gateway: string, name: string) => + receipt?.providerName === name ? receipt : undefined, + writeAuthority, + }; + return { + adapter, + input, + lookup, + writeAuthority, + attachments, + select: (value: Parameters[0]) => { + definition = customNativeProvider(value); + }, + }; +} + +describe("custom native endpoint ownership", () => { + it.each([ + ["compatible-endpoint", "openai-completions", "/team/v1/chat/completions"], + ["compatible-endpoint", "openai-responses", "/team/v1/responses"], + ["compatible-anthropic-endpoint", "anthropic-messages", "/team/v1/messages"], + ["compatible-anthropic-endpoint", "openai-completions", "/team/v1/chat/completions"], + ])( + "binds %s %s to the same agent, profile and health destination", + (provider, api, requestPath) => { + const endpointUrl = + provider === "compatible-endpoint" ? binding.endpointUrl : "https://custom.example/team"; + const definition = customNativeProvider({ ...binding, endpointUrl, provider, api }); + const profile = YAML.parse( + boundCustomNativeProfile( + definition, + nativeProviderLifecycle(definition).nativeProviderProfilePath(), + ), + ); + expect(profile.endpoints[0]).toMatchObject({ + host: "custom.example", + port: 443, + allowed_ips: binding.allowedIps, + enforcement: "enforce", + rules: expect.arrayContaining([{ allow: { method: "POST", path: requestPath } }]), + }); + expect( + profile.endpoints[0].rules.every( + (rule: { allow: { path: string } }) => !rule.allow.path.includes("*"), + ), + ).toBe(true); + expect(profile.binaries).not.toContain("*"); + expect(profile.credentials[0].env_vars).toEqual([definition.credentialEnv]); + const config = getSandboxInferenceConfig("selected-model", provider, api, true, endpointUrl); + expect(config.inferenceBaseUrl).toBe(definition.endpointUrl); + expect(config.inferenceApi).toBe(api); + expect(nativeHostedAgentConfig(provider, config.inferenceBaseUrl)?.apiKey).toBe( + `openshell:resolve:env:${definition.credentialEnv}`, + ); + }, + ); + + it("keeps endpoint, API, credential source and pin authorities distinct", () => { + const names = [ + binding, + { ...binding, endpointUrl: "https://other.example/team/v1" }, + { ...binding, api: "openai-responses" }, + { ...binding, credentialEnv: "OTHER_KEY" }, + { ...binding, allowedIps: ["1.1.1.1"] }, + ].map((value) => customNativeProvider(value).providerName); + expect(new Set(names).size).toBe(names.length); + }); + + it.each([ + "ftp://custom.example/v1", + "https://user:secret@custom.example/v1", + "https://custom.example/v1?key=secret", + "https://custom.example/v1#fragment", + "https://custom.example/%2e%2e/v1", + "https://inference.local/v1", + "https://127.0.0.1/v1", + ])("rejects unsafe endpoint %s before resource mutation", async (endpointUrl) => { + const h = harness(); + await expect(prepareCustomNativeProvider({ ...h.input, endpointUrl })).rejects.toThrow(); + expect(h.adapter.importProviderProfile).not.toHaveBeenCalled(); + expect(h.adapter.createProvider).not.toHaveBeenCalled(); + }); + + it("rejects a private DNS answer and missing API credentials before import", async () => { + const h = harness(); + await expect( + prepareCustomNativeProvider({ + ...h.input, + lookup: async () => [{ address: "169.254.169.254" }], + }), + ).rejects.toThrow("admission failed"); + await expect( + prepareCustomNativeProvider({ ...h.input, credentialValue: null }), + ).rejects.toThrow("A new credential is required"); + await expect(prepareCustomNativeProvider({ ...h.input, api: "unsupported" })).rejects.toThrow( + "Invalid custom", + ); + expect(h.adapter.importProviderProfile).not.toHaveBeenCalled(); + }); + + it.each([ + ["https://custom.example/team/v1", ["10.0.0.8"], ["custom.example"]], + ["https://8.8.8.8/team/v1", ["8.8.8.8"], []], + ] as const)( + "admits exact pins for %s without widening the host", + async (endpointUrl, addresses, trustedPrivateHosts) => { + const h = harness(); + h.select({ ...binding, endpointUrl, allowedIps: addresses }); + const result = await prepareCustomNativeProvider({ + ...h.input, + endpointUrl, + trustedPrivateHosts, + lookup: async () => addresses.map((address) => ({ address })), + }); + const policy = YAML.parse( + buildNativeHostedSandboxPolicy("network_policies: {}", result.providerName, result), + ); + expect(policy.network_policies.native_hosted_inference.endpoints[0].allowed_ips).toEqual( + addresses, + ); + }, + ); + + it("reuses verified credentials without rotating them, even when a host key is present", async () => { + const h = harness(); + const first = await prepareCustomNativeProvider(h.input); + const second = await prepareCustomNativeProvider({ + ...h.input, + recordedAttachment: first, + credentialValue: "another-host-key", + lookup: async () => { + throw new Error("Do not re-resolve admitted pins"); + }, + }); + expect(second).toEqual(first); + expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); + expect(h.adapter.updateProvider).not.toHaveBeenCalled(); + expect(JSON.stringify(h.writeAuthority.mock.calls)).not.toContain("synthetic-host-secret"); + expect(fs.existsSync(h.adapter.importProviderProfile.mock.calls[0][0].profilePath)).toBe(false); + await expect( + prepareCustomNativeProvider({ + ...h.input, + recordedAttachment: first, + credentialValue: null, + api: "openai-responses", + }), + ).rejects.toThrow("A new credential is required"); + expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); + }); + + it("rejects profile collisions before provider or attachment changes", async () => { + const h = harness(); + h.adapter.importProviderProfile.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "profile_incompatible", message: "collision" }, + }); + await expect(prepareCustomNativeProvider(h.input)).rejects.toThrow("conflicts"); + expect(h.adapter.createProvider).not.toHaveBeenCalled(); + expect(h.adapter.attachProvider).not.toHaveBeenCalled(); + }); + + it("observes an ambiguous create once and changes access only on the selected sandbox", async () => { + const h = harness(); + const create = h.adapter.createProvider.getMockImplementation()!; + h.adapter.createProvider.mockImplementation(async (request) => { + await create(request); + return { ok: false, error: { kind: "timeout", message: "timeout" } } as Awaited< + ReturnType + >; + }); + const receipt = await prepareCustomNativeProvider(h.input); + const lifecycle = nativeProviderLifecycle(customNativeProvider(binding)); + const operation = { + adapter: h.input.adapter, + target: { kind: "named", gatewayName: "gateway" } as const, + sandboxName: "selected", + expected: receipt, + }; + await lifecycle.ensureNativeProviderAttached(operation); + expect(h.attachments.get("selected")).toEqual([receipt.providerName]); + expect(h.attachments.get("other")).toEqual(["unrelated-provider"]); + await lifecycle.detachNativeProvider(operation); + expect(h.attachments.get("selected")).toEqual([]); + expect(h.attachments.get("other")).toEqual(["unrelated-provider"]); + expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); + }); + + it("keeps existing shared routes and rejects mismatched durable native selection", async () => { + expect(usesCustomNativeOnboarding(binding.provider, binding.endpointUrl, "alpha", {})).toBe( + false, + ); + expect(usesCustomNativeOnboarding(binding.provider, binding.endpointUrl, "alpha", null)).toBe( + true, + ); + expect( + usesCustomNativeOnboarding(binding.provider, "http://127.0.0.1:8080/v1", "alpha", null), + ).toBe(false); + const h = harness(); + const receipt = await prepareCustomNativeProvider(h.input); + expect( + recordedNativeProviderAttachment({ + provider: binding.provider, + endpointUrl: binding.endpointUrl, + credentialEnv: binding.credentialEnv, + preferredInferenceApi: binding.api, + nativeHostedProviderAttachment: receipt, + }), + ).toEqual(receipt); + expect(() => + recordedNativeProviderAttachment({ + provider: binding.provider, + preferredInferenceApi: "openai-responses", + nativeHostedProviderAttachment: receipt, + }), + ).toThrow("does not match"); + }); + + it("rejects altered receipts and unsafe recorded pins", async () => { + const h = harness(); + const receipt = await prepareCustomNativeProvider(h.input); + expect(() => + requireHostedProviderAttachment( + { ...receipt, endpointUrl: "https://other.example/v1" }, + binding.provider, + ), + ).toThrow(); + }); + + it.each([[[]], [["127.0.0.1"]], [["169.254.169.254"]], [["0.0.0.0/0"]]])( + "rejects unsafe recorded pins %j", + (allowedIps) => { + expect(() => customNativeProvider({ ...binding, allowedIps })).toThrow(); + }, + ); + + it("keeps Bedrock AWS credentials in the existing adapter and injects only its token", async () => { + const h = harness(); + const bedrock = { + ...binding, + provider: "compatible-anthropic-endpoint", + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + allowedIps: [], + adapterEndpointUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, + }; + h.select(bedrock); + const ensureBedrockAdapter = vi.fn(async () => ({ + baseUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, + token: "synthetic-adapter-token", + })) as unknown as NonNullable< + Parameters[0]["ensureBedrockAdapter"] + >; + const receipt = await prepareCustomNativeProvider({ + ...h.input, + provider: bedrock.provider, + endpointUrl: bedrock.endpointUrl, + ensureBedrockAdapter, + }); + expect(h.adapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + credentials: [{ name: "COMPATIBLE_ANTHROPIC_API_KEY", value: "synthetic-adapter-token" }], + }), + ); + expect(receipt.endpointUrl).toBe(BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL); + await prepareCustomNativeProvider({ + ...h.input, + provider: bedrock.provider, + endpointUrl: bedrock.endpointUrl, + credentialValue: null, + recordedAttachment: receipt, + ensureBedrockAdapter, + }); + expect(ensureBedrockAdapter).toHaveBeenCalledTimes(1); + expect(h.adapter.updateProvider).not.toHaveBeenCalled(); + expect(JSON.stringify(receipt)).not.toContain("synthetic-"); + expect(h.lookup).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/inference/native-provider/custom.ts b/src/lib/inference/native-provider/custom.ts new file mode 100644 index 00000000000..d5a990ea77b --- /dev/null +++ b/src/lib/inference/native-provider/custom.ts @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import { isIP } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import YAML from "yaml"; +import { + MAX_CANONICAL_ENDPOINT_LENGTH, + unsafeEndpointUrlViolation, +} from "../../core/endpoint-url-safety"; +import { normalizeProviderBaseUrl } from "../../core/provider-endpoint"; +import type { NativeProviderDefinition } from "./contract"; +import { nativeHostedAgentConfig } from "./agent-config"; +import { isPrivateIp, isLoopbackHostname } from "../../private-networks"; +import { + isOperatorTrustablePrivateIp, + isOpenShellManagedHost, +} from "../../security/trusted-private-endpoint"; +import { + isBedrockRuntimeEndpoint, + BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, +} from "../bedrock-runtime"; +import { getCompatibleAnthropicOpenAiSurfaceBaseUrl } from "../anthropic/openai-surface"; + +export type CustomNativeBinding = Readonly<{ + provider: "compatible-endpoint" | "compatible-anthropic-endpoint"; + endpointUrl: string; + api: "openai-completions" | "openai-responses" | "anthropic-messages"; + /** Host credential lookup name, never its value. */ + credentialEnv: string; + allowedIps: readonly string[]; + /** Existing Bedrock adapter transport; AWS credentials remain in its host process. */ + adapterEndpointUrl?: string; +}>; + +/** Hosted selections exclude the existing loopback and managed bridge routes. */ +export function isHostedCustomEndpoint( + provider: string, + endpointUrl: string | null | undefined, +): boolean { + if ( + (provider !== "compatible-endpoint" && provider !== "compatible-anthropic-endpoint") || + !endpointUrl + ) + return false; + const host = new URL(endpointUrl).hostname; + return !isLoopbackHostname(host) && !isOpenShellManagedHost(host); +} + +export function isCustomNativeProviderName(name: string): boolean { + return /^nemoclaw-custom-[a-f0-9]{32}-v1$/u.test(name); +} + +/** Validate persisted shape without granting DNS or credential authority. */ +export function customNativeProvider(value: unknown): NativeProviderDefinition & { + endpoint: string; + api: CustomNativeBinding["api"]; + custom: CustomNativeBinding; +} { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Missing custom native provider binding"); + const binding = value as CustomNativeBinding; + if ( + (binding.provider !== "compatible-endpoint" && + binding.provider !== "compatible-anthropic-endpoint") || + !["openai-completions", "openai-responses", "anthropic-messages"].includes(binding.api) || + (binding.provider === "compatible-endpoint" && binding.api === "anthropic-messages") || + !/^[A-Z_][A-Z0-9_]*$/u.test(binding.credentialEnv ?? "") || + typeof binding.endpointUrl !== "string" || + binding.endpointUrl.length > MAX_CANONICAL_ENDPOINT_LENGTH || + unsafeEndpointUrlViolation(binding.endpointUrl) || + /%2f|%5c|%2e/iu.test(binding.endpointUrl) + ) + throw new Error("Invalid custom native provider binding"); + const endpoint = new URL(binding.endpointUrl); + if (isOpenShellManagedHost(endpoint.hostname) || isLoopbackHostname(endpoint.hostname)) + throw new Error("Custom hosted native inference requires a hosted endpoint"); + const canonical = normalizeProviderBaseUrl( + binding.endpointUrl, + binding.provider === "compatible-anthropic-endpoint" ? "anthropic" : "openai", + ); + if (canonical !== binding.endpointUrl) throw new Error("Custom native endpoint is not canonical"); + const bedrock = + binding.provider === "compatible-anthropic-endpoint" && isBedrockRuntimeEndpoint(canonical); + const adapter = binding.adapterEndpointUrl ? new URL(binding.adapterEndpointUrl) : undefined; + if ( + bedrock !== Boolean(adapter) || + (adapter && + (binding.api !== "openai-completions" || + binding.adapterEndpointUrl !== BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL)) + ) + throw new Error("Invalid native Bedrock adapter binding"); + if ( + !Array.isArray(binding.allowedIps) || + (!bedrock && binding.allowedIps.length === 0) || + (bedrock && binding.allowedIps.length !== 0) || + binding.allowedIps.some( + (address) => + typeof address !== "string" || + !isIP(address) || + address.includes("%") || + (isPrivateIp(address) && !isOperatorTrustablePrivateIp(address)), + ) || + new Set(binding.allowedIps).size !== binding.allowedIps.length + ) + throw new Error("Custom native inference requires exact destination addresses"); + const custom: CustomNativeBinding = { + provider: binding.provider, + endpointUrl: canonical, + api: binding.api, + credentialEnv: binding.credentialEnv, + allowedIps: [...binding.allowedIps].sort(), + ...(adapter ? { adapterEndpointUrl: binding.adapterEndpointUrl } : {}), + }; + const suffix = createHash("sha256").update(JSON.stringify(custom)).digest("hex").slice(0, 32); + const nativeEndpoint = + custom.adapterEndpointUrl ?? + (custom.provider === "compatible-anthropic-endpoint" && custom.api !== "anthropic-messages" + ? getCompatibleAnthropicOpenAiSurfaceBaseUrl(canonical) + : canonical); + return { + logicalProvider: custom.provider, + label: "custom hosted", + profileId: `nemoclaw-custom-${suffix}-v1`, + providerName: `nemoclaw-custom-${suffix}-v1`, + credentialEnv: nativeHostedAgentConfig(custom.provider, nativeEndpoint)!.credentialEnv, + endpointUrl: nativeEndpoint, + endpoint: nativeEndpoint, + ...(custom.allowedIps.length ? { allowedIps: custom.allowedIps } : {}), + api: custom.api, + custom, + }; +} + +/** Bind the existing executable and credential boundary to one selected API. */ +export function boundCustomNativeProfile( + definition: NativeProviderDefinition, + templatePath: string, +): string { + const expected = customNativeProvider(definition.custom); + if ( + expected.profileId !== definition.profileId || + expected.providerName !== definition.providerName + ) + throw new Error("Custom native provider identity does not match its binding"); + const anthropic = expected.api === "anthropic-messages"; + const profile = YAML.parse(fs.readFileSync(templatePath, "utf8")); + const endpoint = new URL(expected.endpoint); + const prefix = endpoint.pathname.replace(/\/+$/u, ""); + const apiPrefix = anthropic ? `${prefix}/v1` : prefix; + const requestPath = anthropic + ? "messages" + : expected.api === "openai-responses" + ? "responses" + : "chat/completions"; + profile.id = expected.profileId; + profile.display_name = "NemoClaw Custom Hosted Inference"; + profile.description = "Native inference for one validated sandbox endpoint and API"; + profile.credentials[0].env_vars = [expected.credentialEnv]; + profile.endpoints = [ + { + host: endpoint.hostname.replace(/^\[|\]$/gu, ""), + port: Number(endpoint.port || (endpoint.protocol === "https:" ? 443 : 80)), + ...(expected.allowedIps ? { allowed_ips: expected.allowedIps } : {}), + protocol: "rest", + ...(endpoint.protocol === "https:" ? { tls: "terminate" } : {}), + enforcement: "enforce", + rules: [ + { allow: { method: "GET", path: `${apiPrefix}/models` } }, + { allow: { method: "POST", path: `${apiPrefix}/${requestPath}` } }, + ...(anthropic + ? [{ allow: { method: "POST", path: `${apiPrefix}/messages/count_tokens` } }] + : []), + ], + }, + ]; + return YAML.stringify(profile); +} + +export async function withCustomNativeProfile( + definition: NativeProviderDefinition, + use: (profilePath: string) => Promise | T, + templatePath: string, +): Promise { + const source = boundCustomNativeProfile(definition, templatePath); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-profile-")); + try { + const profilePath = path.join(directory, `${definition.profileId}.yaml`); + fs.writeFileSync(profilePath, source, { mode: 0o600 }); + return await use(profilePath); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/src/lib/inference/native-provider/hosted-attachment.ts b/src/lib/inference/native-provider/hosted-attachment.ts index b24558de2fd..854130a919f 100644 --- a/src/lib/inference/native-provider/hosted-attachment.ts +++ b/src/lib/inference/native-provider/hosted-attachment.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { requireHermesPublicPins } from "./hermes-pins"; +import { customNativeProvider, isCustomNativeProviderName } from "./custom"; import { normalizeNativeProviderAttachment, type NativeProviderAttachment } from "./contract"; import { HOSTED_NATIVE_PROVIDERS, @@ -14,6 +15,14 @@ export function hostedNativeProviderForAttachment( ): HostedProviderDefinition | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; const receipt = value as Record; + if (receipt.custom !== undefined) { + try { + const definition = customNativeProvider(receipt.custom); + return normalizeNativeProviderAttachment(value, definition) ? definition : undefined; + } catch { + return undefined; + } + } for (const fixed of HOSTED_NATIVE_PROVIDERS) { let definition: HostedProviderDefinition; try { @@ -59,7 +68,8 @@ export function requireHostedProviderAttachment( export function isNativeHostedProviderName(name: string | null | undefined): boolean { return ( !!name && - (HOSTED_NATIVE_PROVIDERS.some((definition) => definition.providerName === name) || + (isCustomNativeProviderName(name) || + HOSTED_NATIVE_PROVIDERS.some((definition) => definition.providerName === name) || /^nemoclaw-hermes-[a-f0-9]{20}-v1$/u.test(name)) ); } diff --git a/src/lib/inference/native-provider/hosted.ts b/src/lib/inference/native-provider/hosted.ts index 288a82f3241..39fed574019 100644 --- a/src/lib/inference/native-provider/hosted.ts +++ b/src/lib/inference/native-provider/hosted.ts @@ -5,10 +5,20 @@ import { createHash } from "node:crypto"; import { type NativeProviderAttachment, type NativeProviderDefinition } from "./contract.ts"; +export function isCustomHostedProvider(provider: string | null | undefined): boolean { + return provider === "compatible-endpoint" || provider === "compatible-anthropic-endpoint"; +} + +export function customNativeCredentialEnv(provider: string): string { + if (provider === "compatible-endpoint") return "COMPATIBLE_API_KEY"; + if (provider === "compatible-anthropic-endpoint") return "COMPATIBLE_ANTHROPIC_API_KEY"; + throw new Error("Unsupported custom hosted provider"); +} + export type HostedProviderDefinition = NativeProviderDefinition & Readonly<{ endpoint: string; - api: "openai-completions" | "anthropic-messages"; + api: "openai-completions" | "openai-responses" | "anthropic-messages"; }>; /** Existing fixed hosted selections only; custom and local endpoints have separate owners. */ diff --git a/src/lib/inference/native-provider/index.ts b/src/lib/inference/native-provider/index.ts index 7ca75fd2eeb..4956efe9af3 100644 --- a/src/lib/inference/native-provider/index.ts +++ b/src/lib/inference/native-provider/index.ts @@ -3,6 +3,7 @@ import path from "node:path"; import { withHermesNativeProfile } from "./hermes-profile"; +import { withCustomNativeProfile } from "./custom"; import type { OpenShellGatewayTarget, @@ -40,7 +41,7 @@ export class NativeProviderLifecycle { - const imported = this.definition.endpointUrl - ? await withHermesNativeProfile(this.definition, (boundPath) => - adapter.importProviderProfile({ target, profilePath: boundPath }), + const imported = this.definition.custom + ? await withCustomNativeProfile( + this.definition, + (boundPath) => adapter.importProviderProfile({ target, profilePath: boundPath }), + profilePath, ) - : await adapter.importProviderProfile({ target, profilePath }); + : this.definition.endpointUrl + ? await withHermesNativeProfile(this.definition, (boundPath) => + adapter.importProviderProfile({ target, profilePath: boundPath }), + ) + : await adapter.importProviderProfile({ target, profilePath }); if (imported.ok) return; const collision = imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; @@ -123,6 +130,7 @@ export class NativeProviderLifecycle => { + if (nativeCustomSelection) { + if ( + !deps.providerAdapter || + !deps.getNativeHostedProviderAuthority || + !deps.setNativeHostedProviderAuthority + ) + throw new Error( + "Native custom setup is missing its provider adapter or ownership store.", + ); + const selectedCredentialEnv = credentialEnv || customNativeCredentialEnv(provider); + const credentialValue = deps.hydrateCredentialEnv(selectedCredentialEnv) || null; + nativeHostedProviderAttachment = await prepareCustomNativeProvider({ + gatewayName, + provider, + endpointUrl: endpointUrl!, + api: + options.preferredInferenceApi || + (provider === "compatible-anthropic-endpoint" + ? "anthropic-messages" + : "openai-completions"), + credentialEnv: selectedCredentialEnv, + credentialValue, + adapter: deps.providerAdapter, + recordedAttachment: recordedSandbox?.nativeHostedProviderAttachment, + lookup: endpointPinnedAddresses + ? async () => endpointPinnedAddresses!.map((address) => ({ address })) + : deps.resolveEndpointHost, + trustedPrivateHosts: deps.trustedPrivateEndpointHosts, + readAuthority: deps.getNativeHostedProviderAuthority, + writeAuthority: deps.setNativeHostedProviderAuthority, + }); + retainedNativeHostedCredential = !credentialValue; + return null; + } const hosted = hostedNativeProvider(provider); if (hosted && provider !== deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { if ( @@ -1281,6 +1326,10 @@ export function createSetupInference( deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", ); + } else if (nativeHostedProviderAttachment?.custom) { + deps.log( + " Custom native inference will be verified from the sandbox using its selected API.", + ); } else if (options.skipHostInferenceSmoke === true || retainedNativeHostedCredential) { deps.log(" Reusing existing gateway credential; skipping host inference smoke."); } else { diff --git a/src/lib/onboard/setup-native-hosted.test.ts b/src/lib/onboard/setup-native-hosted.test.ts index 2fa021dec7e..c9d1e4697df 100644 --- a/src/lib/onboard/setup-native-hosted.test.ts +++ b/src/lib/onboard/setup-native-hosted.test.ts @@ -3,7 +3,11 @@ import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; -import { HOSTED_NATIVE_PROVIDERS } from "../inference/native-provider/hosted"; +import { customNativeProvider } from "../inference/native-provider/custom"; +import { + HOSTED_NATIVE_PROVIDERS, + type HostedProviderDefinition, +} from "../inference/native-provider/hosted"; import { createSetupInference, type SetupInferenceDeps } from "./setup-inference"; vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ @@ -11,13 +15,35 @@ vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ releaseAbandonedRouteReservation: vi.fn(() => false), })); -describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => { - it.each(["explicit", "omitted"])("uses %s native endpoint (#12589)", async (endpointMode) => { +const providers: HostedProviderDefinition[] = [ + ...HOSTED_NATIVE_PROVIDERS, + ...[ + ["compatible-endpoint", "openai-completions", "https://custom.example/v1"], + ["compatible-endpoint", "openai-responses", "https://custom.example/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example"], + ["compatible-anthropic-endpoint", "openai-completions", "https://custom.example"], + ].map(([provider, api, endpointUrl]) => + customNativeProvider({ + provider, + api, + endpointUrl, + credentialEnv: "HOST_KEY", + allowedIps: ["8.8.8.8"], + }), + ), +]; + +describe.each(providers)("native $label onboarding", (provider) => { + const endpointModes = provider.custom ? ["explicit"] : ["explicit", "omitted"]; + it.each(endpointModes)("uses %s native endpoint (#12589)", async (endpointMode) => { const receipt = { schemaVersion: 1, profileId: provider.profileId, providerName: provider.providerName, providerId: "identity", + ...(provider.endpointUrl ? { endpointUrl: provider.endpointUrl } : {}), + ...(provider.allowedIps ? { allowedIps: provider.allowedIps } : {}), + ...(provider.custom ? { custom: provider.custom } : {}), } as const; const getProvider = vi .fn() @@ -61,6 +87,7 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => getNativeHostedProviderAuthority: () => undefined, setNativeHostedProviderAuthority: writeAuthority, getSandbox: () => null, + resolveEndpointHost: async () => [{ address: "8.8.8.8", family: 4 }], upsertProvider: vi.fn(), verifyInferenceRoute, verifyOnboardInferenceSmoke, @@ -115,11 +142,11 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => "alpha", "supported-model", provider.logicalProvider, - endpointMode === "explicit" ? provider.endpoint : null, - provider.credentialEnv, + endpointMode === "explicit" ? (provider.custom?.endpointUrl ?? provider.endpoint) : null, + provider.custom?.credentialEnv ?? provider.credentialEnv, null, [], - { revalidateSandboxIdentity: () => undefined }, + { revalidateSandboxIdentity: () => undefined, preferredInferenceApi: provider.api }, ), ).resolves.toMatchObject({ ok: true }); expect(createProvider).toHaveBeenCalledExactlyOnceWith( @@ -138,7 +165,7 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => }), ); expect(verifyOnboardInferenceSmoke.mock.calls).toEqual( - provider.logicalProvider === "hermes-provider" + provider.logicalProvider === "hermes-provider" || provider.custom ? [] : [ [ diff --git a/src/lib/state/registry/native-hosted-provider-authority.test.ts b/src/lib/state/registry/native-hosted-provider-authority.test.ts index 39702678bfa..ea498b37ee0 100644 --- a/src/lib/state/registry/native-hosted-provider-authority.test.ts +++ b/src/lib/state/registry/native-hosted-provider-authority.test.ts @@ -9,6 +9,7 @@ import { HOSTED_NATIVE_PROVIDERS, hostedNativeProvider, } from "../../inference/native-provider/hosted"; +import { customNativeProvider } from "../../inference/native-provider/custom"; import { normalizeNativeHostedProviderAuthorities } from "./native-provider-authority-state"; const openai = { @@ -199,3 +200,65 @@ it("retains independent Hermes ownership across authenticated endpoint changes ( await fs.rm(temporaryHome, { recursive: true, force: true }); } }); + +it("persists custom endpoint ownership through reservation, registration and a model update", async () => { + const temporaryHome = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-custom-authority-")); + vi.stubEnv("HOME", temporaryHome); + vi.resetModules(); + try { + const registry = await import("../registry"); + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-responses", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const receipt = { + schemaVersion: 1 as const, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "custom-identity", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }; + registry.setNativeHostedProviderAuthority("gateway", definition.logicalProvider, receipt); + expect(registry.getNativeHostedProviderAuthority("gateway", definition.providerName)).toEqual( + receipt, + ); + expect( + registry.getNativeHostedProviderAuthority("other", definition.providerName), + ).toBeUndefined(); + registry.registerSandbox({ + name: "alpha", + gatewayName: "gateway", + provider: definition.logicalProvider, + model: "first", + nativeHostedProviderAttachment: receipt, + }); + registry.reserveSandboxInferenceRoute("alpha", { + gatewayName: "gateway", + provider: definition.logicalProvider, + model: "first", + credentialEnv: "TEAM_KEY", + endpointUrl: definition.custom.endpointUrl, + preferredInferenceApi: definition.custom.api, + nativeHostedProviderAttachment: receipt, + }); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual(receipt); + registry.updateSandbox("alpha", { model: "second" }); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual(receipt); + expect(registry.getSandbox("alpha")?.model).toBe("second"); + expect( + (await import("./native-provider-authority")).listNativeHostedProviderAttachmentSandboxNames( + "gateway", + definition.providerName, + ), + ).toEqual(["alpha"]); + } finally { + vi.unstubAllEnvs(); + vi.resetModules(); + await fs.rm(temporaryHome, { recursive: true, force: true }); + } +}); diff --git a/src/lib/state/registry/native-provider-authority.ts b/src/lib/state/registry/native-provider-authority.ts index bd880ac83fc..006b458545a 100644 --- a/src/lib/state/registry/native-provider-authority.ts +++ b/src/lib/state/registry/native-provider-authority.ts @@ -10,6 +10,8 @@ import { import { isDeepStrictEqual } from "node:util"; import type { NativeProviderAttachment } from "../../inference/native-provider/contract"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { isCustomNativeProviderName } from "../../inference/native-provider/custom"; +import { normalizeHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; import { requireHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; import { readNativeHostedGatewayAuthorities } from "./native-provider-authority-state"; import { withLock } from "./lock"; @@ -61,6 +63,10 @@ export function getNativeHostedProviderAuthority( provider: string, endpointUrl?: string | null, ): NativeProviderAttachment | undefined { + if (isCustomNativeProviderName(provider)) + return normalizeHostedProviderAttachment( + readNativeHostedGatewayAuthorities(load(), gatewayName)?.[provider], + ); if (!hostedNativeProvider(provider)) return undefined; const authorities = readNativeHostedGatewayAuthorities(load(), gatewayName); const current = requireHostedProviderAttachment(authorities?.[provider], provider); @@ -83,15 +89,16 @@ export function setNativeHostedProviderAuthority( const state = load(); const authorities = state.nativeHostedProviderAuthorities ?? {}; const gateway = authorities[gatewayName] ?? {}; - if (isDeepStrictEqual(gateway[provider], normalized)) return; + const authorityKey = normalized.custom ? normalized.providerName : provider; + if (isDeepStrictEqual(gateway[authorityKey], normalized)) return; state.nativeHostedProviderAuthorities = { ...authorities, [gatewayName]: { ...gateway, - ...(gateway[provider] && gateway[provider].providerName !== normalized.providerName - ? { [gateway[provider].providerName]: gateway[provider] } + ...(gateway[authorityKey] && gateway[authorityKey].providerName !== normalized.providerName + ? { [gateway[authorityKey].providerName]: gateway[authorityKey] } : {}), - [provider]: normalized, + [authorityKey]: normalized, }, }; save(state); diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index db83d35af79..128a6f43dc5 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -365,7 +365,7 @@ export function nativeHostedReservationAttachment( previous?: SandboxEntry, ) { const receipt = requireHostedProviderAttachment(value, provider); - return hostedNativeProvider(provider) + return receipt || hostedNativeProvider(provider) ? (receipt ?? (previous && previous.provider === provider ? previous.nativeHostedProviderAttachment diff --git a/test/e2e/README.md b/test/e2e/README.md index fef91269b58..305e086e7f1 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -870,8 +870,9 @@ The report also groups repeated observable outcomes. Those rows are retained onl ## Full E2E inference availability `live/full-e2e.test.ts` owns the live sandbox arithmetic probe. -Source installs use `inference.local`; the Brev Launchable uses the native NVIDIA endpoint -with its supervisor-issued credential handle. The test verifies the native provider attachment +Source installs use the recorded custom native endpoint when present, or retain the legacy fixture route. +The Brev Launchable uses the native NVIDIA endpoint. Native routes use supervisor-issued credential handles. +The test verifies the native provider attachment on the declared gateway and retains that route across its temporary native model edit. The live boundary proves attachment, credential resolution, and a real inference response. The support tests own route selection, command encoding, credential rejection, and model-edit configuration. diff --git a/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts b/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts index 47742e2a2ee..9efbfedefcb 100644 --- a/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts +++ b/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts @@ -815,7 +815,7 @@ async function assertNoBedrockLeaks(options: { } test( - "bedrock runtime compatible Anthropic endpoint routes through managed inference.local", + "bedrock runtime compatible Anthropic endpoint routes through an attached native provider", { timeout: TEST_TIMEOUT_MS, meta: { @@ -892,7 +892,7 @@ test( "the selected runtime, python3, source CLI, and OpenShell are available", "bedrock-runtime.us-east-1.amazonaws.com maps to the host fake endpoint", "non-interactive anthropicCompatible onboarding completes for OpenClaw and Hermes", - "the selected agent-native runtime path returns PONG through inference.local", + "the selected agent-native runtime path returns PONG through its native Bedrock adapter provider", "fake Bedrock Runtime endpoint observes authenticated Converse traffic", "the OpenClaw path observes authenticated ConverseStream traffic", "bounded sandbox credential, config, environment, and process-argument probes contain no forbidden Bedrock values", diff --git a/test/e2e/live/full-e2e-inference-probe.ts b/test/e2e/live/full-e2e-inference-probe.ts index 59eb34b9b00..bb5054b3c73 100644 --- a/test/e2e/live/full-e2e-inference-probe.ts +++ b/test/e2e/live/full-e2e-inference-probe.ts @@ -1,8 +1,18 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { parseCliOpenShellProviderMetadata } from "../../../src/lib/adapters/openshell/provider-metadata-cli.ts"; +import { hostedNativeProviderForAttachment } from "../../../src/lib/inference/native-provider/hosted-attachment.ts"; +import type { SandboxEntry } from "../../../src/lib/state/registry/types.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import { + PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, + readPublicNvidiaSwitchAttachmentEvidence, +} from "./public-nvidia-switch-provider.ts"; + import { runBoundedRetry, type RetryEvidence } from "../../../tools/e2e/retry-evidence.mts"; +import { nativeHostedAuthHeaderScript } from "../../../src/lib/actions/sandbox/inference-invocation-probe.ts"; import { resolveMaxTokensField } from "../../../src/lib/inference/max-tokens-field.ts"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT, @@ -26,14 +36,22 @@ const TRUNCATION_SUFFIX = "...[truncated]"; export function buildFullE2eSandboxInferenceCommand( requestBody: string, logicalProvider: string, + endpointUrl?: string, ): [string, ...string[]] { - if (logicalProvider === NVIDIA_HOSTED_LOGICAL_PROVIDER) { + const nativeCustom = logicalProvider === "compatible-endpoint" && endpointUrl; + if (logicalProvider === NVIDIA_HOSTED_LOGICAL_PROVIDER || nativeCustom) { + const auth = nativeCustom + ? nativeHostedAuthHeaderScript({ + credentialEnv: "COMPATIBLE_API_KEY", + api: "openai-completions", + }) + : NATIVE_NVIDIA_AUTH_HEADER_SCRIPT; return [ "bash", "-c", - `${NATIVE_NVIDIA_AUTH_HEADER_SCRIPT}; exec curl -fsS --max-time 90 "$1" -H 'Content-Type: application/json' -H "$AUTH_HEADER" --data-raw "$2"`, + `${auth}; exec curl -fsS --max-time 90 "$1" -H 'Content-Type: application/json' -H "$AUTH_HEADER" --data-raw "$2"`, "full-e2e-native-inference", - `${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions`, + `${(nativeCustom ? endpointUrl : NVIDIA_HOSTED_NATIVE_ENDPOINT).replace(/\/+$/u, "")}/chat/completions`, requestBody, ]; } @@ -341,3 +359,66 @@ export function fullE2eInferenceProbeEvidence { + const receipt = input.entry?.nativeHostedProviderAttachment; + if (receipt?.custom) { + const definition = hostedNativeProviderForAttachment(receipt); + if (!definition) return { ok: false, detail: "Invalid custom native ownership" }; + const options = { + env: input.env, + redactionValues: input.redactionValues, + timeoutMs: 60_000, + captureLimitBytes: 16 * 1024, + }; + const gateway = input.entry?.gatewayName || input.env.OPENSHELL_GATEWAY || "nemoclaw"; + const provider = await input.sandbox.openshell( + ["provider", "get", "-g", gateway, receipt.providerName], + { ...options, artifactName: "phase-3-native-custom-provider-metadata" }, + ); + const attachments = await input.sandbox.openshell( + ["sandbox", "provider", "list", "-g", gateway, input.sandboxName], + { ...options, artifactName: "phase-3-native-custom-provider-attachment" }, + ); + const metadata = + provider.exitCode === 0 ? parseCliOpenShellProviderMetadata(provider.stdout) : null; + const ok = + metadata?.name === receipt.providerName && + metadata.type === receipt.profileId && + metadata.revision?.id === receipt.providerId && + metadata.configKeys.length === 0 && + metadata.credentialKeys.length === 1 && + metadata.credentialKeys[0] === definition.credentialEnv && + attachments.exitCode === 0 && + attachments.stdout.split(/\s+/u).includes(receipt.providerName); + return { + ok, + detail: `Custom native provider ownership and attachment: ${ok ? "verified" : "mismatch"}`, + }; + } + const native = await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "phase-3-native-nvidia-provider-attachment", + env: input.env, + logicalProvider: input.logicalProvider, + receipt: input.entry?.nativeNvidiaProviderAttachment, + sandbox: input.sandbox, + sandboxName: input.sandboxName, + }); + if (native !== null) + return { ok: native === PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, detail: native }; + const route = await input.sandbox.openshell(["inference", "get"], { + artifactName: "phase-3-openshell-inference-get", + env: input.env, + timeoutMs: 60_000, + }); + return { ok: route.exitCode === 0 && route.stdout.includes(input.model), detail: route.stdout }; +} diff --git a/test/e2e/live/full-e2e-native-model.ts b/test/e2e/live/full-e2e-native-model.ts index 01c4eef8b6d..73f939cc2a9 100644 --- a/test/e2e/live/full-e2e-native-model.ts +++ b/test/e2e/live/full-e2e-native-model.ts @@ -26,7 +26,12 @@ export async function withNativeModelCleanup( // The preceding sandbox inference turn qualifies this model and route. A new // provider name makes a gateway that ignores the native edit distinguishable. -export function buildNativeModelRestartFixture(model: string, logicalProvider?: string) { +export function buildNativeModelRestartFixture( + model: string, + logicalProvider?: string, + endpointUrl?: string, +) { + const nativeCustom = logicalProvider === "compatible-endpoint" && endpointUrl; const nativeNvidia = logicalProvider === NVIDIA_HOSTED_LOGICAL_PROVIDER; const provider = `nemoclaw-e2e-native-${randomUUID()}`; const primary = `${provider}/${model}`; @@ -38,8 +43,16 @@ export function buildNativeModelRestartFixture(model: string, logicalProvider?: models: { providers: { [provider]: { - baseUrl: nativeNvidia ? NVIDIA_HOSTED_NATIVE_ENDPOINT : "https://inference.local/v1", - apiKey: nativeNvidia ? "${NVIDIA_INFERENCE_API_KEY}" : "unused", + baseUrl: nativeCustom + ? endpointUrl + : nativeNvidia + ? NVIDIA_HOSTED_NATIVE_ENDPOINT + : "https://inference.local/v1", + apiKey: nativeCustom + ? "${COMPATIBLE_API_KEY}" + : nativeNvidia + ? "${NVIDIA_INFERENCE_API_KEY}" + : "unused", api: "openai-completions", models: [{ id: model, name: model }], }, diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 621602e6047..f2d89ff321e 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -48,6 +48,7 @@ import { import { buildOpenClawFirstTurnLatencyEvidence } from "./agent-turn-latency-helpers.ts"; import { buildFullE2eSandboxInferenceCommand, + readFullE2eInferenceRoute, FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES, fullE2eInferenceProbeEvidence, runFullE2eInferenceProbe, @@ -72,10 +73,6 @@ import { agentReplyContainsToken, parseOpenClawGatewayModelRun, } from "./openclaw-inference-switch-helpers.ts"; -import { - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, - readPublicNvidiaSwitchAttachmentEvidence, -} from "./public-nvidia-switch-provider.ts"; import { createCliOpenShellGatewayReuseObserver } from "../../../src/lib/adapters/openshell/gateway-reuse-cli.ts"; import type { OpenShellGatewayReuseObservation } from "../../../src/lib/adapters/openshell/gateway-reuse.ts"; @@ -439,6 +436,7 @@ async function runOpenClawLaunchTurns(input: { host: HostCliClient; model: string; logicalProvider: string; + endpointUrl?: string; redactionValues: string[]; sandbox: SandboxClient; }): Promise { @@ -479,7 +477,11 @@ sha256sum /sandbox/.bashrc /sandbox/.profile > /tmp/nemoclaw-e2e-profiles.sha256 timeoutMs: 30_000, }, ); - const nativeModel = buildNativeModelRestartFixture(input.model, input.logicalProvider); + const nativeModel = buildNativeModelRestartFixture( + input.model, + input.logicalProvider, + input.endpointUrl, + ); const editNativeModel = await input.sandbox.exec( SANDBOX_NAME, ["/usr/bin/env", "HOME=/sandbox", "/usr/local/bin/openclaw", "config", "patch", "--stdin"], @@ -1209,30 +1211,17 @@ test( }, ); - const nativeAttachment = await readPublicNvidiaSwitchAttachmentEvidence({ - artifactName: "phase-3-native-nvidia-provider-attachment", - env: env(), - logicalProvider: hosted.providerName, - receipt: getSandbox(SANDBOX_NAME)?.nativeNvidiaProviderAttachment, + const nativeEndpointUrl = getSandbox(SANDBOX_NAME)?.nativeHostedProviderAttachment?.endpointUrl; + const inferenceRoute = await readFullE2eInferenceRoute({ sandbox, sandboxName: SANDBOX_NAME, + entry: getSandbox(SANDBOX_NAME), + logicalProvider: hosted.providerName, + model: hosted.model, + env: env(), + redactionValues, }); - const inference = - nativeAttachment === null - ? await sandbox.openshell(["inference", "get"], { - artifactName: "phase-3-openshell-inference-get", - env: env(), - timeoutMs: 60_000, - }) - : null; - expect( - inference !== null - ? inference.exitCode === 0 && resultText(inference).includes(hosted.model) - : nativeAttachment === PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, - inference !== null - ? resultText(inference) - : (nativeAttachment ?? "missing native attachment"), - ).toBe(true); + expect(inferenceRoute.ok, inferenceRoute.detail).toBe(true); const policy = await sandbox.openshell(["policy", "get", "--full", SANDBOX_NAME], { artifactName: "phase-3-openshell-policy-get", @@ -1265,7 +1254,11 @@ test( run: (availabilityAttempt) => sandbox.exec( SANDBOX_NAME, - buildFullE2eSandboxInferenceCommand(attempt.requestBody, hosted.providerName), + buildFullE2eSandboxInferenceCommand( + attempt.requestBody, + hosted.providerName, + nativeEndpointUrl, + ), { artifactName: `${attempt.artifactName}-availability-${availabilityAttempt}`, captureLimitBytes: FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES, @@ -1315,6 +1308,7 @@ test( host, model: hosted.model, logicalProvider: hosted.providerName, + endpointUrl: nativeEndpointUrl, redactionValues, sandbox, }) @@ -1402,7 +1396,11 @@ test( run: (availabilityAttempt) => sandbox.exec( SANDBOX_NAME, - buildFullE2eSandboxInferenceCommand(attempt.requestBody, hosted.providerName), + buildFullE2eSandboxInferenceCommand( + attempt.requestBody, + hosted.providerName, + nativeEndpointUrl, + ), { artifactName: `retained-${attempt.artifactName}-availability-${availabilityAttempt}`, captureLimitBytes: FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES, diff --git a/test/e2e/support/full-e2e-inference-probe.test.ts b/test/e2e/support/full-e2e-inference-probe.test.ts index 8340bda5f59..1256bc24ba3 100644 --- a/test/e2e/support/full-e2e-inference-probe.test.ts +++ b/test/e2e/support/full-e2e-inference-probe.test.ts @@ -6,10 +6,13 @@ import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { customNativeProvider } from "../../../src/lib/inference/native-provider/custom.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { buildFullE2eInferenceRequest, buildFullE2eSandboxInferenceCommand, + readFullE2eInferenceRoute, FULL_E2E_INFERENCE_EVIDENCE_LIMIT_BYTES, type FullE2eInferenceAttemptInput, fullE2eInferenceProbeEvidence, @@ -32,35 +35,102 @@ function completion(content: string, finishReason = "stop"): string { }); } +it.each([ + ["owned-id", true], + ["different-id", false], +] as const)( + "checks custom native provider identity %s on the recorded gateway", + async (observedId, expected) => { + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "SOURCE_KEY", + allowedIps: ["8.8.8.8"], + }); + const openshell = vi + .fn() + .mockResolvedValueOnce({ + exitCode: 0, + stdout: [ + `Name: ${definition.providerName}`, + `Id: ${observedId}`, + `Type: ${definition.profileId}`, + "Resource version: 1", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: ", + ].join("\n"), + }) + .mockResolvedValueOnce({ exitCode: 0, stdout: definition.providerName }); + const result = await readFullE2eInferenceRoute({ + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "alpha", + logicalProvider: definition.logicalProvider, + model: "selected-model", + env: {}, + redactionValues: ["synthetic-key"], + entry: { + name: "alpha", + gatewayName: "recorded-gateway", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "owned-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }, + }, + }); + expect(result.ok).toBe(expected); + expect(openshell.mock.calls.map(([args]) => args)).toEqual([ + ["provider", "get", "-g", "recorded-gateway", definition.providerName], + ["sandbox", "provider", "list", "-g", "recorded-gateway", "alpha"], + ]); + expect(openshell).toHaveBeenNthCalledWith( + 1, + expect.any(Array), + expect.objectContaining({ redactionValues: ["synthetic-key"], captureLimitBytes: 16 * 1024 }), + ); + }, +); + describe("full E2E sandbox inference probe", () => { - it("uses the sandbox's native NVIDIA handle and preserves the request as data", () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "full-e2e-native-probe-")); - try { - fs.writeFileSync(path.join(directory, "curl"), '#!/bin/sh\nprintf "%s\\n" "$@"\n', { - mode: 0o700, - }); - const body = JSON.stringify({ prompt: 'literal $(exit 99) "quote"' }); - const [command, ...args] = buildFullE2eSandboxInferenceCommand(body, "nvidia-prod"); - const handle = "openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY"; - const env = { PATH: `${directory}:/usr/bin:/bin`, NVIDIA_INFERENCE_API_KEY: handle }; - const result = execFileSync(command, args, { env, encoding: "utf8" }); - expect(result.split("\n")).toEqual([ - "-fsS", - "--max-time", - "90", - "https://integrate.api.nvidia.com/v1/chat/completions", - "-H", - "Content-Type: application/json", - "-H", - `Authorization: Bearer ${handle}`, - "--data-raw", - body, - "", - ]); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } - }); + it.each([ + ["nvidia-prod", "NVIDIA_INFERENCE_API_KEY", "https://integrate.api.nvidia.com/v1"], + ["compatible-endpoint", "COMPATIBLE_API_KEY", "https://custom.example/team/v1"], + ])( + "uses the sandbox native %s handle and preserves the request as data", + (provider, credentialEnv, endpointUrl) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "full-e2e-native-probe-")); + try { + fs.writeFileSync(path.join(directory, "curl"), '#!/bin/sh\nprintf "%s\\n" "$@"\n', { + mode: 0o700, + }); + const body = JSON.stringify({ prompt: 'literal $(exit 99) "quote"' }); + const [command, ...args] = buildFullE2eSandboxInferenceCommand(body, provider, endpointUrl); + const handle = `openshell:resolve:env:v3_${credentialEnv}`; + const env = { PATH: `${directory}:/usr/bin:/bin`, [credentialEnv]: handle }; + const result = execFileSync(command, args, { env, encoding: "utf8" }); + expect(result.split("\n")).toEqual([ + "-fsS", + "--max-time", + "90", + `${endpointUrl}/chat/completions`, + "-H", + "Content-Type: application/json", + "-H", + `Authorization: Bearer ${handle}`, + "--data-raw", + body, + "", + ]); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); it.each(["", "nvapi-raw-key", "$(exit 99)"])( "rejects the invalid native credential %j before invoking curl", diff --git a/test/e2e/support/full-e2e-native-model.test.ts b/test/e2e/support/full-e2e-native-model.test.ts index 56097d6afef..252a9a12334 100644 --- a/test/e2e/support/full-e2e-native-model.test.ts +++ b/test/e2e/support/full-e2e-native-model.test.ts @@ -98,3 +98,17 @@ it("reports the last cleanup failure when verification and both cleanup steps fa withNativeModelCleanup(fail(errors[0]), fail(errors[1]), fail(errors[2])), ).rejects.toBe(errors[2]); }); + +it("retains a custom native endpoint and opaque credential reference through a model edit", () => { + const fixture = buildNativeModelRestartFixture( + "team/model", + "compatible-endpoint", + "https://custom.example/team/v1", + ); + expect(JSON.parse(fixture.patch).models.providers[fixture.provider]).toMatchObject({ + baseUrl: "https://custom.example/team/v1", + apiKey: "${COMPATIBLE_API_KEY}", + api: "openai-completions", + models: [{ id: "team/model", name: "team/model" }], + }); +}); diff --git a/test/generation/generate-native-hosted-config.test.ts b/test/generation/generate-native-hosted-config.test.ts index b6d5382f27a..602c6869f78 100644 --- a/test/generation/generate-native-hosted-config.test.ts +++ b/test/generation/generate-native-hosted-config.test.ts @@ -4,10 +4,27 @@ import { describe, expect, it } from "vitest"; import { buildConfig } from "../../scripts/generate-openclaw-config.mts"; import { applyHermesManagedRoute } from "../../src/lib/hermes-managed-route"; +import { customNativeProvider } from "../../src/lib/inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS } from "../../src/lib/inference/native-provider/hosted"; import { baseOpenClawGenerationEnv } from "../helpers/openclaw-env-fixture"; -describe.each(HOSTED_NATIVE_PROVIDERS)("native $label agent configuration", (provider) => { +describe.each([ + ...HOSTED_NATIVE_PROVIDERS, + ...[ + ["compatible-endpoint", "openai-completions", "https://custom.example/team/v1"], + ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example/team"], + ["compatible-anthropic-endpoint", "openai-completions", "https://custom.example/team"], + ].map(([provider, api, endpointUrl]) => + customNativeProvider({ + provider, + api, + endpointUrl, + credentialEnv: "HOST_KEY", + allowedIps: ["8.8.8.8"], + }), + ), +])("native $label agent configuration", (provider) => { it("renders OpenClaw credentials as placeholders and keeps the native protocol (#12589)", () => { const config = buildConfig({ ...baseOpenClawGenerationEnv(), From e14836f5d134d146099079773bf52ba0c6fba188 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:07:54 -0700 Subject: [PATCH 2/9] fix(inference): preserve custom route recovery and export authority --- ci/e2e-assertion-budget.json | 6 +- ci/e2e-assertion-growth-exceptions.json | 6 +- ci/pi-agent-qualification-v1-linux-amd64.json | 8 +- ci/pi-agent-qualification-v1-linux-arm64.json | 8 +- .../sandbox/rebuild-provider-preflight.ts | 6 +- .../status-snapshot-inference-health.test.ts | 2 +- .../config/live-export-source.test.ts | 83 ++++++++++++++----- src/lib/adapters/config/live-export-source.ts | 1 + .../native-hosted-profile-response.test.ts | 79 +++++++++++++++++- .../native-hosted-profile-response.ts | 30 +++++-- src/lib/adapters/openshell/providers.ts | 16 +++- src/lib/agent/candidate-authority.ts | 4 +- src/lib/domain/config/export-evidence.ts | 1 + .../config/export-source-test-fixture.ts | 1 + src/lib/domain/config/verify-export-source.ts | 57 ++++++++----- src/lib/onboard.ts | 4 +- src/lib/onboard/openclaw-setup.test.ts | 1 + .../onboard/recovered-provider-reuse.test.ts | 24 ++++++ src/lib/onboard/recovered-provider-reuse.ts | 44 +++++++++- .../setup-inference-route-containment.test.ts | 4 + src/lib/onboard/setup-inference.ts | 5 +- src/lib/onboard/setup-native-hosted.test.ts | 23 ++++- test/e2e/live/full-e2e-inference-probe.ts | 45 +++++++++- test/e2e/mock-parity.json | 1 + .../support/full-e2e-inference-probe.test.ts | 60 ++++++++++++-- ...-anthropic-compatible-openai-agent.test.ts | 7 ++ .../onboard-inference-failure-paths.test.ts | 7 ++ .../onboard-inference-gateway-scope.test.ts | 1 + .../onboard-inference-reconciliation.test.ts | 13 ++- .../onboard-inference-smoke.test.ts | 1 + ...d-remote-recreate-credential-reuse.test.ts | 25 +++++- test/onboarding/onboard.test.ts | 1 + test/support/setup-inference-test-harness.ts | 13 ++- 33 files changed, 495 insertions(+), 92 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index ca0b779efe6..79acd087d5d 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -35,8 +35,8 @@ "throwGuards": 526, "objectFieldAssertions": 254, "assertionPoints": 3222, - "generatedProbeBlocks": 209, - "generatedProbeConditions": 721 + "generatedProbeBlocks": 210, + "generatedProbeConditions": 722 }, "fileMetricOrder": [ "directExpectCalls", @@ -62,7 +62,7 @@ "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], "test/e2e/live/double-onboard.test.ts": [42,47,42,47,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], - "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], + "test/e2e/live/full-e2e.test.ts": [27,30,28,60,8], "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [10,22,17,61,14], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 000451b565b..f4587421309 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.", "schemaVersion": 1, "exceptions": [ { @@ -38,6 +38,10 @@ { "pullRequest": 13055, "changeSha256": "d0435766039881c9598d3740f650e3bffdbace9f5a3f29fdc70238522c521f79" + }, + { + "pullRequest": 13201, + "changeSha256": "c5311b6d098e8d67b414e6bdf128f9a47afa88cc7342ff0989ad04601a3c313a" } ] } diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index 0f161bc93f9..e5e5825ccc4 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:a64fe4d7f96959259ac4bbf31078cc8479c8ad7f7b67e6a5f7ba72e5e338bd6b", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:a64fe4d7f96959259ac4bbf31078cc8479c8ad7f7b67e6a5f7ba72e5e338bd6b", + "digest": "sha256:ce0b27069d32239ad5b50c4ddea2d8aaa824b991c12f8e4a4e3883a66a4a7e7e", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:ce0b27069d32239ad5b50c4ddea2d8aaa824b991c12f8e4a4e3883a66a4a7e7e", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "482dd1305efd85d386757998fc8980de035f8b61", + "revision": "05f5dafe655482077b42bd36c0230c88dcc6ec81", "release": "v0.1.0", - "cohort": "ghrun-38530733040-1" + "cohort": "ghrun-38643585682-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index ab98540b49b..28d8ce99dc3 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:3eeeb5a85fad5c49939d627355c9f26267a82241510892bbb632c096ac84c2b1", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:3eeeb5a85fad5c49939d627355c9f26267a82241510892bbb632c096ac84c2b1", + "digest": "sha256:8d918cc7008a9c3320c8f864d2fceff9e1ef1867abed476bbd8656820bca04e2", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:8d918cc7008a9c3320c8f864d2fceff9e1ef1867abed476bbd8656820bca04e2", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "482dd1305efd85d386757998fc8980de035f8b61", + "revision": "05f5dafe655482077b42bd36c0230c88dcc6ec81", "release": "v0.1.0", - "cohort": "ghrun-38530733040-1" + "cohort": "ghrun-38643585682-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.ts index 84de7f0db69..3cb95332e26 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.ts @@ -498,7 +498,11 @@ export async function checkRebuildGatewayCredentialReuseOrBail( console.error( ` ${_RD}Rebuild preflight failed:${R} cannot safely reuse the recorded gateway credential.`, ); - console.error(` ${rebuildCredentialReuseCondition(decision.condition)}`); + console.error( + ` ${rebuildCredentialReuseCondition( + decision.kind === "reject" ? decision.condition : "gateway-provider-identity", + )}`, + ); console.error(" Export the provider credential to use normal validation and upsert."); console.error(" Sandbox is untouched — no data was lost."); bail("Unsafe gateway credential reuse"); diff --git a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts index 96e20c3891d..6928d93cf10 100644 --- a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -855,7 +855,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { expect(delayInferenceRecoveryProbe).toHaveBeenCalledOnce(); expect(snapshot.inferenceHealth).toMatchObject({ ok: false, - detail: brokenRoute.detail, + detail: expect.stringContaining(brokenRoute.detail), failureLabel: "unreachable", }); }); diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index fcbc924868d..27b4ca87929 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -8,8 +8,15 @@ import { expectExportRefusal, } from "../../../../test/support/config-export-harness"; import fs from "node:fs"; -import { HOSTED_NATIVE_PROVIDERS } from "../../inference/native-provider/hosted"; +import { + HOSTED_NATIVE_PROVIDERS, + type HostedProviderDefinition, +} from "../../inference/native-provider/hosted"; import { nativeProviderLifecycle } from "../../inference/native-provider"; +import { + customNativeProvider, + boundCustomNativeProfile, +} from "../../inference/native-provider/custom"; import { parseCheckedInProviderProfileContract } from "../openshell/provider-profile"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; import { getSandboxEntryInference } from "../../state/registry-entry-view"; @@ -152,12 +159,14 @@ function mockNativeNvidiaSource(profileWorkspace = "default") { }); } -function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[number]) { +function mockNativeHostedSource(definition: HostedProviderDefinition) { const route = resolveManagedStartupInferenceRoute( "openclaw", definition.logicalProvider, "model-a", definition.api, + true, + definition.endpointUrl, ); const startup = buildManagedStartupProfile({ ...startupInput, @@ -175,14 +184,21 @@ function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[num const native = { ...entry, provider: definition.logicalProvider, - endpointUrl: definition.endpoint, - credentialEnv: definition.credentialEnv, + endpointUrl: definition.custom?.endpointUrl ?? definition.endpoint, + credentialEnv: definition.custom?.credentialEnv ?? definition.credentialEnv, preferredInferenceApi: definition.api, nativeHostedProviderAttachment: { schemaVersion: 1 as const, profileId: definition.profileId, providerName: definition.providerName, providerId: "native-provider-id", + ...(definition.custom + ? { + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + } + : {}), }, workload: { ...entry.workload, @@ -210,12 +226,17 @@ function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[num }), }, }); + const profilePath = nativeProviderLifecycle(definition).nativeProviderProfilePath(); const contract = parseCheckedInProviderProfileContract( - fs.readFileSync(nativeProviderLifecycle(definition).nativeProviderProfilePath(), "utf8"), + definition.custom + ? boundCustomNativeProfile(definition, profilePath) + : fs.readFileSync(profilePath, "utf8"), )!; const credential = contract.boundary.credentials[0]; const endpoint = contract.boundary.endpoints[0] as { host: string; + port: number; + allowed_ips?: string[]; rules: { allow: { method: string; path: string } }[]; }; const base = managedBraveProfile(); @@ -236,6 +257,8 @@ function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[num { ...base.endpoints[0], host: endpoint.host, + port: endpoint.port, + allowedIps: endpoint.allowed_ips ?? [], access: "", rules: endpoint.rules.map((rule) => ({ allow: { @@ -796,23 +819,39 @@ describe("live export snapshot reader", () => { }, ); - it.each( - HOSTED_NATIVE_PROVIDERS.filter((definition) => definition.logicalProvider !== "gemini-api"), - )("exports native $label without reading shared routing or secret values", async (definition) => { - const { readCredential } = mockNativeHostedSource(definition); - const { result, writeStdout } = await exportLiveSource(); - expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); - const yaml = writeStdout.mock.calls[0]![0]; - const document = asExportedConfig(YAML.parse(yaml)); - expect(document.spec.inferenceProviders[0]).toMatchObject({ - endpoint: definition.endpoint, - api: definition.api, - credential: { env: definition.credentialEnv }, - }); - expect(readCredential).not.toHaveBeenCalled(); - expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); - expect(yaml).not.toContain(readFailureCanary); - }); + it.each([ + ...HOSTED_NATIVE_PROVIDERS.filter((definition) => definition.logicalProvider !== "gemini-api"), + ...[ + ["compatible-endpoint", "openai-completions", "https://custom.example/team/v1"], + ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example/team"], + ].map(([provider, api, endpointUrl]) => + customNativeProvider({ + provider, + api, + endpointUrl, + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }), + ), + ])( + "exports native $label without reading shared routing or secret values", + async (definition: HostedProviderDefinition) => { + const { readCredential } = mockNativeHostedSource(definition); + const { result, writeStdout } = await exportLiveSource(); + expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); + const yaml = writeStdout.mock.calls[0]![0]; + const document = asExportedConfig(YAML.parse(yaml)); + expect(document.spec.inferenceProviders[0]).toMatchObject({ + endpoint: definition.custom?.endpointUrl ?? definition.endpoint, + api: definition.api, + credential: { env: definition.custom?.credentialEnv ?? definition.credentialEnv }, + }); + expect(readCredential).not.toHaveBeenCalled(); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + expect(yaml).not.toContain(readFailureCanary); + }, + ); it("rejects native hosted export when the sandbox attaches an unrelated provider", async () => { mockNativeHostedSource(HOSTED_NATIVE_PROVIDERS[0]); diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index 99dabd2fc44..eab112c3808 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -198,6 +198,7 @@ async function readProviderEvidence( ? { nativeHostedEndpoint: nativeReceipt.endpointUrl, nativeHostedAllowedIps: nativeReceipt.allowedIps, + nativeHostedCustom: nativeReceipt.custom, } : {}), configKeys: [configKey], diff --git a/src/lib/adapters/openshell/native-hosted-profile-response.test.ts b/src/lib/adapters/openshell/native-hosted-profile-response.test.ts index 2889136c345..c8276f36808 100644 --- a/src/lib/adapters/openshell/native-hosted-profile-response.test.ts +++ b/src/lib/adapters/openshell/native-hosted-profile-response.test.ts @@ -7,19 +7,29 @@ import { managedBraveProfile } from "../../../../test/fixtures/openshell-provide import { hostedNativeProvider, HOSTED_NATIVE_PROVIDERS, + type HostedProviderDefinition, } from "../../inference/native-provider/hosted"; import { nativeProviderLifecycle } from "../../inference/native-provider"; +import { + customNativeProvider, + boundCustomNativeProfile, +} from "../../inference/native-provider/custom"; import { parseCheckedInProviderProfileContract } from "./provider-profile"; import { isManagedNativeHostedProfileResponse } from "./native-hosted-profile-response"; -function response(definition: (typeof HOSTED_NATIVE_PROVIDERS)[number]) { +function response(definition: HostedProviderDefinition) { + const profilePath = nativeProviderLifecycle(definition).nativeProviderProfilePath(); const contract = parseCheckedInProviderProfileContract( - fs.readFileSync(nativeProviderLifecycle(definition).nativeProviderProfilePath(), "utf8"), + definition.custom + ? boundCustomNativeProfile(definition, profilePath) + : fs.readFileSync(profilePath, "utf8"), )!; const base = managedBraveProfile(); const credential = contract.boundary.credentials[0]; const endpoint = contract.boundary.endpoints[0] as { host: string; + port: number; + allowed_ips?: string[]; rules: { allow: { method: string; path: string } }[]; }; return { @@ -39,6 +49,8 @@ function response(definition: (typeof HOSTED_NATIVE_PROVIDERS)[number]) { { ...base.endpoints[0], host: endpoint.host, + port: endpoint.port, + allowedIps: endpoint.allowed_ips ?? [], access: "", rules: endpoint.rules.map((rule) => ({ allow: { @@ -115,6 +127,69 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label profile read boundary", (d }); }); +it.each([ + ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1", ["8.8.8.8"]], + [ + "compatible-anthropic-endpoint", + "anthropic-messages", + "https://custom.example/team", + ["10.0.0.8"], + ], +] as const)( + "verifies custom %s %s against its complete binding", + (provider, api, endpointUrl, allowedIps) => { + const definition = customNativeProvider({ + provider, + api, + endpointUrl, + allowedIps, + credentialEnv: "TEAM_KEY", + }); + const value = response(definition); + const read = (observed: unknown, binding = definition.custom) => + isManagedNativeHostedProfileResponse( + observed, + definition.profileId, + definition.endpointUrl, + definition.allowedIps, + binding, + ); + expect(read(value)).toBe(value); + expect( + read(value, { ...definition.custom!, credentialEnv: "DIFFERENT_SOURCE" }), + ).toBeUndefined(); + expect( + read({ + profile: { + ...value.profile, + endpoints: [{ ...value.profile.endpoints[0], allowedIps: ["1.1.1.1"] }], + }, + }), + ).toBeUndefined(); + expect( + read({ + profile: { + ...value.profile, + credentials: [{ ...value.profile.credentials[0], envVars: ["TEAM_KEY"] }], + }, + }), + ).toBeUndefined(); + expect( + read({ + profile: { + ...value.profile, + endpoints: [ + { + ...value.profile.endpoints[0], + rules: [...value.profile.endpoints[0].rules, value.profile.endpoints[0].rules[0]], + }, + ], + }, + }), + ).toBeUndefined(); + }, +); + it("requires the exact public IP restriction on a Hermes bound profile", () => { const endpointUrl = "https://staging.nous.example/v1"; const definition = hostedNativeProvider("hermes-provider", endpointUrl)!; diff --git a/src/lib/adapters/openshell/native-hosted-profile-response.ts b/src/lib/adapters/openshell/native-hosted-profile-response.ts index fabd2c28220..75041878ac0 100644 --- a/src/lib/adapters/openshell/native-hosted-profile-response.ts +++ b/src/lib/adapters/openshell/native-hosted-profile-response.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { requireHermesPublicPins } from "../../inference/native-provider/hermes-pins"; +import { + customNativeProvider, + type CustomNativeBinding, +} from "../../inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS, type HostedProviderDefinition, @@ -14,12 +18,18 @@ import { export type HostedNativeProfileId = | (typeof HOSTED_NATIVE_PROVIDERS)[number]["profileId"] + | `nemoclaw-custom-${string}-v1` | `nemoclaw-hermes-inference-${string}-v1`; export function hostedNativeProfile( profileId: string, endpointUrl?: string, + custom?: CustomNativeBinding, ): HostedProviderDefinition | undefined { + if (custom) { + const bound = customNativeProvider(custom); + return bound.profileId === profileId && bound.endpoint === endpointUrl ? bound : undefined; + } if (endpointUrl) { const bound = hostedNativeProvider("hermes-provider", endpointUrl); return bound?.profileId === profileId ? bound : undefined; @@ -31,23 +41,28 @@ export function hostedNativeProfileBoundary( profileId: string, endpointUrl?: string, allowedIps?: readonly string[], + custom?: CustomNativeBinding, ): NativeProfileBoundary | undefined { - const definition = hostedNativeProfile(profileId, endpointUrl); + const definition = hostedNativeProfile(profileId, endpointUrl, custom); if (!definition) return undefined; const endpoint = new URL(definition.endpoint); - const prefix = - definition.api === "anthropic-messages" ? "/v1" : endpoint.pathname.replace(/\/+$/, ""); + const base = endpoint.pathname.replace(/\/+$/, ""); + const prefix = definition.api === "anthropic-messages" ? `${custom ? base : ""}/v1` : base; let paths = ["chat/completions"]; if (definition.api === "anthropic-messages") paths = ["messages", "messages/count_tokens"]; + else if (custom && definition.api === "openai-responses") paths = ["responses"]; else if (definition.logicalProvider === "openai-api") paths.push("responses"); + let pins: readonly string[] | undefined; + if (custom) pins = definition.allowedIps ?? []; + else if (definition.endpointUrl) pins = requireHermesPublicPins(allowedIps); return { profileId: definition.profileId as HostedNativeProfileId, - ...(definition.endpointUrl ? { allowedIps: requireHermesPublicPins(allowedIps) } : {}), + ...(pins ? { allowedIps: pins } : {}), credentialEnv: definition.credentialEnv, authStyle: definition.api === "anthropic-messages" ? "header" : "bearer", headerName: definition.api === "anthropic-messages" ? "x-api-key" : "authorization", - host: endpoint.hostname, - port: Number(endpoint.port || 443), + host: endpoint.hostname.replace(/^\[|\]$/gu, ""), + port: Number(endpoint.port || (endpoint.protocol === "https:" ? 443 : 80)), rules: [ { method: "GET", path: `${prefix}/models` }, ...paths.map((path) => ({ method: "POST" as const, path: `${prefix}/${path}` })), @@ -60,10 +75,11 @@ export function isManagedNativeHostedProfileResponse( profileId: string, endpointUrl?: string, allowedIps?: readonly string[], + custom?: CustomNativeBinding, ) { let boundary; try { - boundary = hostedNativeProfileBoundary(profileId, endpointUrl, allowedIps); + boundary = hostedNativeProfileBoundary(profileId, endpointUrl, allowedIps, custom); } catch { return undefined; } diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index c75a188d131..fb12c731bc9 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -47,6 +47,7 @@ const managedProfileSchemas = { }; type ManagedProfileContract = keyof typeof managedProfileSchemas; type ProfileContract = ManagedProfileContract | "native-nvidia" | "native-hosted"; +type CustomNativeBinding = import("../../inference/native-provider/custom").CustomNativeBinding; export type Provider = Readonly< Pick & { @@ -75,6 +76,7 @@ export interface Providers { profileContract?: ProfileContract; nativeHostedEndpoint?: string; nativeHostedAllowedIps?: readonly string[]; + nativeHostedCustom?: CustomNativeBinding; }>, ): Promise; } @@ -105,7 +107,11 @@ async function readManagedProfile( let profileId: string | undefined = profileContract; if (profileContract === "native-nvidia") profileId = NVIDIA_HOSTED_NATIVE_PROFILE_ID; else if (profileContract === "native-hosted") - profileId = hostedNativeProfile(providerType, request.nativeHostedEndpoint)?.profileId; + profileId = hostedNativeProfile( + providerType, + request.nativeHostedEndpoint, + request.nativeHostedCustom, + )?.profileId; if ( providerType !== profileId || (profileWorkspace !== "" && profileWorkspace !== request.workspace) @@ -131,6 +137,7 @@ async function readManagedProfile( providerType, request.nativeHostedEndpoint, request.nativeHostedAllowedIps, + request.nativeHostedCustom, ); } @@ -159,6 +166,7 @@ function validateManagedProfileResponse( providerType: string, nativeHostedEndpoint?: string, nativeHostedAllowedIps?: readonly string[], + nativeHostedCustom?: CustomNativeBinding, ): NonNullable { if (profileContract === "native-nvidia") { return validateNativeManagedProfileResponse(response, profileWorkspace); @@ -169,6 +177,7 @@ function validateManagedProfileResponse( providerType, nativeHostedEndpoint, nativeHostedAllowedIps, + nativeHostedCustom, ); if ( !validated || @@ -205,10 +214,12 @@ function validateManagedProfileResponse( function managedInferenceEndpointFor( managedProfile: Provider["managedProfile"], nativeHostedEndpoint?: string, + nativeHostedCustom?: CustomNativeBinding, ): string | undefined { return managedProfile?.id === NVIDIA_HOSTED_NATIVE_PROFILE_ID ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : hostedNativeProfile(managedProfile?.id ?? "", nativeHostedEndpoint)?.endpoint; + : hostedNativeProfile(managedProfile?.id ?? "", nativeHostedEndpoint, nativeHostedCustom) + ?.endpoint; } async function readProfileEvidence( @@ -246,6 +257,7 @@ async function readProfileEvidence( const managedInferenceEndpoint = managedInferenceEndpointFor( managedProfile, request.nativeHostedEndpoint, + request.nativeHostedCustom, ); return { ...(builtinInferenceEndpoint === undefined ? {} : { builtinInferenceEndpoint }), diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index c252607e77f..72576f71615 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "f9a90de7888ecac7ab20fa1b6a9b8b083fd30c4a37e41a032803ed0712b66cb6", - "86ffbb6cb781c28ec0d781027e03e120756c416beafcc3f95cde2235da9324cc", + "e15dbc530c6486136ebc450c02b2ea70245def3e37aad41bd4202482a9f49191", + "31618180d9ddc8a161ad3f7493df085ca3a705bad886189d9f6d7ea89a1f2bd4", ]), }); diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index af60fb598fe..a800b3db788 100644 --- a/src/lib/domain/config/export-evidence.ts +++ b/src/lib/domain/config/export-evidence.ts @@ -146,6 +146,7 @@ export interface ObservedExportEndpointEvidence { | "nemoclaw-gemini-inference-v1" | "nemoclaw-openrouter-inference-v1" | "nemoclaw-hermes-inference-v1" + | `nemoclaw-custom-${string}-v1` | `nemoclaw-hermes-inference-${string}-v1`; readonly source: "builtin" | "user"; readonly scope: "" | "platform" | "workspace"; diff --git a/src/lib/domain/config/export-source-test-fixture.ts b/src/lib/domain/config/export-source-test-fixture.ts index 531cfe90ba7..0a225045d99 100644 --- a/src/lib/domain/config/export-source-test-fixture.ts +++ b/src/lib/domain/config/export-source-test-fixture.ts @@ -518,6 +518,7 @@ export function compatibleSnapshot( "compatible-endpoint", "gpt-5", "openai-completions", + false, ); const input = { ...base, diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 22c7e06dbe9..8fc3df6aaac 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -7,7 +7,10 @@ import { cloneAndDeepFreeze } from "../../core/immutable"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; import { normalizeInferenceSelection } from "../../inference/selection"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; -import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { + hostedNativeProvider, + isCustomHostedProvider, +} from "../../inference/native-provider/hosted"; import { fixedNativeProviderForAttachment } from "../../inference/native-provider/fixed"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../inference/native-nvidia/contract"; @@ -571,7 +574,10 @@ function deepAgentsObservability( } function exportUsesNativeInference(entry: ObservedExportRegistry): boolean { - return !hostedNativeProvider(entry.provider) || Boolean(nativeExportReceipt(entry)); + return ( + (!hostedNativeProvider(entry.provider) && !isCustomHostedProvider(entry.provider)) || + Boolean(nativeExportReceipt(entry)) + ); } function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedStartupProfile { @@ -867,6 +873,35 @@ function nativeExportReceipt(entry: QualifiedExportSnapshot["registry"]) { } } +function expectedManagedEndpointRoute( + snapshot: QualifiedExportSnapshot, + receipt: NonNullable>, +) { + const definition = fixedNativeProviderForAttachment(receipt); + const identity = [ + receipt.profileId, + receipt.providerName, + receipt.providerId, + definition.logicalProvider, + ]; + if (receipt.custom) { + return [ + ...identity, + receipt.custom.api, + receipt.custom.endpointUrl, + receipt.endpointUrl, + receipt.custom.credentialEnv, + ]; + } + const hosted = hostedNativeProvider(snapshot.registry.provider, receipt.endpointUrl); + const endpoint = hosted?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT; + const api = + hosted?.logicalProvider === "openai-api" && snapshot.inference.api === "openai-responses" + ? "openai-responses" + : (hosted?.api ?? "openai-completions"); + return [...identity, api, endpoint, endpoint, definition.credentialEnv]; +} + function managedEndpointEvidenceMatchesRoute( snapshot: QualifiedExportSnapshot, evidence: NonNullable & { @@ -876,13 +911,6 @@ function managedEndpointEvidenceMatchesRoute( const { inference } = snapshot; const receipt = nativeExportReceipt(snapshot.registry); if (!receipt) return false; - const definition = fixedNativeProviderForAttachment(receipt); - const hosted = hostedNativeProvider(snapshot.registry.provider, receipt.endpointUrl); - const endpoint = hosted?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT; - const api = - hosted?.logicalProvider === "openai-api" && inference.api === "openai-responses" - ? "openai-responses" - : (hosted?.api ?? "openai-completions"); return isDeepStrictEqual( [ evidence.source.profileId, @@ -894,16 +922,7 @@ function managedEndpointEvidenceMatchesRoute( evidence.endpoint, inference.credentialEnv, ], - [ - receipt.profileId, - receipt.providerName, - receipt.providerId, - definition.logicalProvider, - api, - endpoint, - endpoint, - definition.credentialEnv, - ], + expectedManagedEndpointRoute(snapshot, receipt), ); } diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index a0bd185746a..e5d6253ed98 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2029,8 +2029,7 @@ async function handleRemoteProviderSelection( log: (message) => console.log(message), }); if (bedrockSelection.action === "retry-selection") { - console.log(" Returning to provider selection."); - console.log(""); + console.log(" Returning to provider selection.\n"); return "retry-selection"; } if (bedrockSelection.action === "selected") { @@ -2058,6 +2057,7 @@ async function handleRemoteProviderSelection( }, { resolveProviderCredential, + getSandbox: registry.getSandbox, readRecordedInferenceRoute: (name) => readRecordedInferenceRoute(name, args.recoverySessionId), readRecordedProviderEndpoints, diff --git a/src/lib/onboard/openclaw-setup.test.ts b/src/lib/onboard/openclaw-setup.test.ts index f2023c05ea4..3210e1c23f1 100644 --- a/src/lib/onboard/openclaw-setup.test.ts +++ b/src/lib/onboard/openclaw-setup.test.ts @@ -415,6 +415,7 @@ describe("restored native OpenClaw inference fields", () => { const writeValues = vi.fn(); const identity = vi.fn(); const write = createOpenclawInferenceRouteWriter({ + readInferenceSelection: () => ({ nativeProvider: false }), readOpenclawConfig: () => config, patchOpenclawInferenceConfig: patchOpenClawInferenceConfig, writeOpenclawInferenceConfigNatively: (name, patched, route, gateway) => diff --git a/src/lib/onboard/recovered-provider-reuse.test.ts b/src/lib/onboard/recovered-provider-reuse.test.ts index 0cfc9961d00..bf593392184 100644 --- a/src/lib/onboard/recovered-provider-reuse.test.ts +++ b/src/lib/onboard/recovered-provider-reuse.test.ts @@ -54,6 +54,30 @@ describe("assessRecoveredProviderCredentialReuse", () => { }); }); + it("defers native credential verification without trusting legacy provider metadata", () => { + expect( + assessRecoveredProviderCredentialReuse({ + ...completeRecovery, + nativeCustom: true, + gatewayProvider: null, + endpointIdentity: { + ...completeRecovery.endpointIdentity, + otherRecorded: ["https://other.example/v1"], + }, + }), + ).toEqual({ kind: "verify-native-credential", preferredInferenceApi: "openai-completions" }); + expect( + assessRecoveredProviderCredentialReuse({ + ...completeRecovery, + nativeCustom: true, + endpointIdentity: { + ...completeRecovery.endpointIdentity, + recovered: "https://other.example/v1", + }, + }), + ).toMatchObject({ kind: "reject", condition: "endpoint-identity" }); + }); + it.each( Array.from([[], ["WRONG_BASE_URL"], ["OPENAI_BASE_URL", "EXTRA_FLAG"]], (value) => [value]), )( diff --git a/src/lib/onboard/recovered-provider-reuse.ts b/src/lib/onboard/recovered-provider-reuse.ts index 9a6d91bd453..ee1f9bb0482 100644 --- a/src/lib/onboard/recovered-provider-reuse.ts +++ b/src/lib/onboard/recovered-provider-reuse.ts @@ -3,6 +3,7 @@ import { canonicalEndpoint, type EndpointFlavor } from "../core/url-utils"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; +import { usesCustomNativeOnboarding } from "../inference/native-provider/custom-setup"; import { isSafeModelId } from "../validation"; import type { GatewayProviderMetadata } from "./gateway-provider-metadata"; import type { RecordedInferenceRoute } from "./provider-recovery"; @@ -37,6 +38,7 @@ export type RecoveredProviderReuseRejectCondition = export type RecoveredProviderReuseDecision = | { kind: "validate-host-credential" } | { kind: "reuse-gateway-credential"; preferredInferenceApi: string } + | { kind: "verify-native-credential"; preferredInferenceApi: string } | { kind: "reject"; condition: RecoveredProviderReuseRejectCondition; reason: string }; type EndpointIdentity = { @@ -67,6 +69,7 @@ type RecoveredProviderSelection = { }; type RecoveredProviderSelectionDeps = { + getSandbox?: (name: string) => Parameters[3]; resolveProviderCredential(name: string): string | null; readRecordedInferenceRoute(sandboxName: string | null): RecordedInferenceRoute | null; readRecordedProviderEndpoints( @@ -112,6 +115,7 @@ export function assessRecoveredProviderCredentialReuse(options: { expectedCredentialEnv: string; gatewayProvider: GatewayProviderMetadata | null; endpointIdentity?: EndpointIdentity; + nativeCustom?: boolean; }): RecoveredProviderReuseDecision { if (options.hostCredentialAvailable) return { kind: "validate-host-credential" }; if (!options.recoveredFromSandbox) { @@ -148,6 +152,26 @@ export function assessRecoveredProviderCredentialReuse(options: { reason: "the recovered inference API is missing or unsupported", }; } + if (options.nativeCustom) { + const endpoint = options.endpointIdentity; + const selected = endpoint && canonicalEndpoint(endpoint.selected, endpoint.flavor); + if ( + !selected || + endpoint?.routeSource !== "registry" || + selected !== canonicalEndpoint(endpoint.recovered, endpoint.flavor) + ) + return { + kind: "reject", + condition: "endpoint-identity", + reason: "the recovered endpoint identity is missing or incompatible", + }; + // Selection can defer host validation, but only provider setup can verify + // the endpoint-bound receipt and current OpenShell resource identity. + return { + kind: "verify-native-credential", + preferredInferenceApi: options.recoveredPreferredInferenceApi as string, + }; + } const gatewayProvider = options.gatewayProvider; // #6294: an OpenAI-only agent coerced onto openai-completions registers the // compatible-anthropic-endpoint provider as type=openai (OPENAI_BASE_URL), @@ -259,6 +283,15 @@ export function resolveRecoveredProviderCredentialReuse( : selected.key === "anthropicCompatible" ? "anthropic" : null; + const nativeCustom = Boolean( + deps.getSandbox && + usesCustomNativeOnboarding( + state.provider, + state.endpointUrl, + options.sandboxName, + options.sandboxName ? deps.getSandbox(options.sandboxName) : null, + ), + ); const decision = assessRecoveredProviderCredentialReuse({ hostCredentialAvailable: false, recoveredFromSandbox, @@ -270,14 +303,17 @@ export function resolveRecoveredProviderCredentialReuse( recoveredPreferredInferenceApi: recoveredRoute?.preferredInferenceApi, expectedProviderType: remoteConfig.providerType, expectedCredentialEnv: selectedCredentialEnv, - gatewayProvider: deps.readGatewayProviderMetadata(state.provider), + gatewayProvider: nativeCustom ? null : deps.readGatewayProviderMetadata(state.provider), + nativeCustom, endpointIdentity: customFlavor ? { flavor: customFlavor, routeSource: recoveredRoute?.source ?? null, selected: state.endpointUrl, recovered: recoveredRoute?.endpointUrl, - otherRecorded: deps.readRecordedProviderEndpoints(state.provider, options.sandboxName), + otherRecorded: nativeCustom + ? [] + : deps.readRecordedProviderEndpoints(state.provider, options.sandboxName), } : undefined, }); @@ -294,7 +330,9 @@ export function resolveRecoveredProviderCredentialReuse( state.reuseGatewayCredentialWithoutLocalKey = true; state.preferredInferenceApi = decision.preferredInferenceApi; deps.note( - ` Reusing existing gateway credential for '${state.provider}'; skipping direct endpoint validation.`, + decision.kind === "verify-native-credential" + ? " Checking for a matching endpoint-bound credential during provider setup; a new credential may be required." + : ` Reusing existing gateway credential for '${state.provider}'; skipping direct endpoint validation.`, ); return true; } diff --git a/src/lib/onboard/setup-inference-route-containment.test.ts b/src/lib/onboard/setup-inference-route-containment.test.ts index 55647fc68b2..45565caf9e3 100644 --- a/src/lib/onboard/setup-inference-route-containment.test.ts +++ b/src/lib/onboard/setup-inference-route-containment.test.ts @@ -81,6 +81,9 @@ describe("onboard shared gateway route containment", () => { }); const verifyOnboardInferenceSmoke = vi.fn(); const setupInference = createSetupInference({ + getSandbox: () => ({ name: "sandbox-a", provider: "compatible-endpoint" }), + localInference: { loadPendingOllamaModelCleanup: () => [] }, + withOllamaModelOwnershipLock: (operation: () => unknown) => operation(), checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), @@ -309,6 +312,7 @@ describe("onboard shared gateway route containment", () => { checkGatewayRouteCompatibility: ( request: Parameters[0], ) => checkGatewayRouteCompatibility({ ...request, sandboxes: [peer] }), + getSandbox: () => ({ name: "new-custom", provider: "compatible-endpoint" }), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index deec395160d..77b1445a531 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -999,7 +999,10 @@ export function createSetupInference( credentialEnv: selectedCredentialEnv, credentialValue, adapter: deps.providerAdapter, - recordedAttachment: recordedSandbox?.nativeHostedProviderAttachment, + recordedAttachment: + recordedSandbox?.provider === provider + ? recordedSandbox.nativeHostedProviderAttachment + : undefined, lookup: endpointPinnedAddresses ? async () => endpointPinnedAddresses!.map((address) => ({ address })) : deps.resolveEndpointHost, diff --git a/src/lib/onboard/setup-native-hosted.test.ts b/src/lib/onboard/setup-native-hosted.test.ts index c9d1e4697df..c0df0e71e2d 100644 --- a/src/lib/onboard/setup-native-hosted.test.ts +++ b/src/lib/onboard/setup-native-hosted.test.ts @@ -34,7 +34,9 @@ const providers: HostedProviderDefinition[] = [ ]; describe.each(providers)("native $label onboarding", (provider) => { - const endpointModes = provider.custom ? ["explicit"] : ["explicit", "omitted"]; + const endpointModes = provider.custom + ? ["explicit", "previous-provider"] + : ["explicit", "omitted"]; it.each(endpointModes)("uses %s native endpoint (#12589)", async (endpointMode) => { const receipt = { schemaVersion: 1, @@ -84,9 +86,24 @@ describe.each(providers)("native $label onboarding", (provider) => { getGatewayName: () => "gateway", runOpenshell, updateSandbox, + localInference: { loadPendingOllamaModelCleanup: () => [] }, + withOllamaModelOwnershipLock: (operation: () => unknown) => operation(), getNativeHostedProviderAuthority: () => undefined, setNativeHostedProviderAuthority: writeAuthority, - getSandbox: () => null, + getSandbox: () => + endpointMode === "previous-provider" + ? { + name: "alpha", + provider: "openai-api", + pendingRouteReservation: true, + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: HOSTED_NATIVE_PROVIDERS[0].profileId, + providerName: HOSTED_NATIVE_PROVIDERS[0].providerName, + providerId: "previous-provider-id", + }, + } + : null, resolveEndpointHost: async () => [{ address: "8.8.8.8", family: 4 }], upsertProvider: vi.fn(), verifyInferenceRoute, @@ -142,7 +159,7 @@ describe.each(providers)("native $label onboarding", (provider) => { "alpha", "supported-model", provider.logicalProvider, - endpointMode === "explicit" ? (provider.custom?.endpointUrl ?? provider.endpoint) : null, + endpointMode !== "omitted" ? (provider.custom?.endpointUrl ?? provider.endpoint) : null, provider.custom?.credentialEnv ?? provider.credentialEnv, null, [], diff --git a/test/e2e/live/full-e2e-inference-probe.ts b/test/e2e/live/full-e2e-inference-probe.ts index bb5054b3c73..a0d8b9aaca2 100644 --- a/test/e2e/live/full-e2e-inference-probe.ts +++ b/test/e2e/live/full-e2e-inference-probe.ts @@ -3,6 +3,7 @@ import { parseCliOpenShellProviderMetadata } from "../../../src/lib/adapters/openshell/provider-metadata-cli.ts"; import { hostedNativeProviderForAttachment } from "../../../src/lib/inference/native-provider/hosted-attachment.ts"; +import { getSandboxInferenceConfig } from "../../../src/lib/inference/config.ts"; import type { SandboxEntry } from "../../../src/lib/state/registry/types.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { @@ -391,6 +392,44 @@ export async function readFullE2eInferenceRoute(input: { ); const metadata = provider.exitCode === 0 ? parseCliOpenShellProviderMetadata(provider.stdout) : null; + const route = getSandboxInferenceConfig( + input.model, + input.logicalProvider, + receipt.custom.api, + true, + receipt.endpointUrl, + ); + // Inspect the selected agent's real configuration inside the sandbox. + // Keep credential references out of retained command output. + const agent = await input.sandbox.exec( + input.sandboxName, + [ + "node", + "-e", + [ + 'const config = JSON.parse(require("node:fs").readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', + 'const assert = require("node:assert/strict");', + "const expected = JSON.parse(process.argv[1]);", + "const provider = config.models?.providers?.[expected.providerKey];", + 'assert.equal(config.agents?.defaults?.model?.primary, expected.primaryModelRef, "selected model mismatch");', + 'assert.equal(provider?.baseUrl, expected.endpoint, "selected endpoint mismatch");', + 'assert.equal(provider?.api, expected.api, "selected API mismatch");', + 'assert.ok(provider?.models?.some(model => model.id === expected.model), "selected model is absent");', + "const handle = process.env[expected.credentialEnv];", + 'assert.ok(new RegExp("^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_" + expected.credentialEnv + "$").test(handle ?? "") && provider?.apiKey === handle, "selected credential reference mismatch");', + 'process.stdout.write("selected agent route verified");', + ].join(" "), + JSON.stringify({ + providerKey: route.providerKey, + primaryModelRef: route.primaryModelRef, + endpoint: route.inferenceBaseUrl, + api: route.inferenceApi, + model: input.model, + credentialEnv: definition.credentialEnv, + }), + ], + { ...options, artifactName: "phase-3-native-custom-agent-route" }, + ); const ok = metadata?.name === receipt.providerName && metadata.type === receipt.profileId && @@ -399,10 +438,12 @@ export async function readFullE2eInferenceRoute(input: { metadata.credentialKeys.length === 1 && metadata.credentialKeys[0] === definition.credentialEnv && attachments.exitCode === 0 && - attachments.stdout.split(/\s+/u).includes(receipt.providerName); + attachments.stdout.split(/\s+/u).includes(receipt.providerName) && + agent.exitCode === 0 && + agent.stdout === "selected agent route verified"; return { ok, - detail: `Custom native provider ownership and attachment: ${ok ? "verified" : "mismatch"}`, + detail: `Custom native provider ownership, attachment and selected agent route: ${ok ? "verified" : "mismatch"}`, }; } const native = await readPublicNvidiaSwitchAttachmentEvidence({ diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 4be623f7215..384ff40f15a 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -485,6 +485,7 @@ "test/e2e/fixtures/admin-approval-connect.sh" ], "fast": [ + "src/lib/inference/native-provider/custom.test.ts", "test/e2e/support/bedrock-runtime-compatible-anthropic-leaks.test.ts", "test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", diff --git a/test/e2e/support/full-e2e-inference-probe.test.ts b/test/e2e/support/full-e2e-inference-probe.test.ts index 1256bc24ba3..9f46244a50e 100644 --- a/test/e2e/support/full-e2e-inference-probe.test.ts +++ b/test/e2e/support/full-e2e-inference-probe.test.ts @@ -6,6 +6,8 @@ import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import assert from "node:assert/strict"; +import { runInNewContext } from "node:vm"; import { customNativeProvider } from "../../../src/lib/inference/native-provider/custom.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; @@ -36,11 +38,15 @@ function completion(content: string, finishReason = "stop"): string { } it.each([ - ["owned-id", true], - ["different-id", false], + ["owned-id", "none", true], + ["different-id", "none", false], + ["owned-id", "endpoint", false], + ["owned-id", "api", false], + ["owned-id", "credential", false], + ["owned-id", "model", false], ] as const)( - "checks custom native provider identity %s on the recorded gateway", - async (observedId, expected) => { + "checks custom native provider identity %s and agent drift %s on the recorded gateway", + async (observedId, drift, expected) => { const definition = customNativeProvider({ provider: "compatible-endpoint", endpointUrl: "https://custom.example/v1", @@ -62,8 +68,47 @@ it.each([ ].join("\n"), }) .mockResolvedValueOnce({ exitCode: 0, stdout: definition.providerName }); + const handle = "openshell:resolve:env:v3_COMPATIBLE_API_KEY"; + const config = { + agents: { + defaults: { + model: { primary: drift === "model" ? "inference/other" : "inference/selected-model" }, + }, + }, + models: { + providers: { + inference: { + baseUrl: drift === "endpoint" ? "https://wrong.example/v1" : definition.endpoint, + api: drift === "api" ? "openai-responses" : definition.api, + apiKey: drift === "credential" ? "raw-secret" : handle, + models: [{ id: "selected-model" }], + }, + }, + }, + }; + const exec = vi.fn(async (_name, command) => { + let stdout = ""; + try { + runInNewContext(command[2], { + require: (name: string) => + name === "node:fs" ? { readFileSync: () => JSON.stringify(config) } : assert, + process: { + argv: ["node", command[3]], + env: { COMPATIBLE_API_KEY: handle }, + stdout: { + write: (value: string) => { + stdout += value; + }, + }, + }, + }); + return { exitCode: 0, stdout }; + } catch { + return { exitCode: 1, stdout }; + } + }); const result = await readFullE2eInferenceRoute({ - sandbox: { openshell } as unknown as SandboxClient, + sandbox: { openshell, exec } as unknown as SandboxClient, sandboxName: "alpha", logicalProvider: definition.logicalProvider, model: "selected-model", @@ -84,6 +129,11 @@ it.each([ }, }); expect(result.ok).toBe(expected); + expect(exec).toHaveBeenCalledExactlyOnceWith( + "alpha", + expect.any(Array), + expect.objectContaining({ artifactName: "phase-3-native-custom-agent-route" }), + ); expect(openshell.mock.calls.map(([args]) => args)).toEqual([ ["provider", "get", "-g", "recorded-gateway", definition.providerName], ["sandbox", "provider", "list", "-g", "recorded-gateway", "alpha"], diff --git a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts index a4234926077..e5f6e24ca99 100644 --- a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts +++ b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts @@ -104,6 +104,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: providerAbsentRunner, overrides: { probeOpenAiLikeEndpoint }, }); @@ -135,6 +136,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV), overrides: { probeOpenAiLikeEndpoint }, }); @@ -158,6 +160,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, ["test-box"]), overrides: { probeOpenAiLikeEndpoint }, }); @@ -182,6 +185,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 const exitProcess = createInjectedExit(); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, [ "other-box", "test-box", @@ -218,6 +222,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 message: "POST /v1/chat/completions returned 404", })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: providerAbsentRunner, overrides: { probeOpenAiLikeEndpoint, exitProcess, isNonInteractive: () => true }, }); @@ -242,6 +247,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: providerAbsentRunner, overrides: { probeOpenAiLikeEndpoint }, }); @@ -261,6 +267,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 it("skips the surface probe on keyless gateway-credential reuse", async () => { const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: commandStubs({ "provider get": { status: 0 } }), overrides: { probeOpenAiLikeEndpoint }, }); diff --git a/test/onboarding/onboard-inference-failure-paths.test.ts b/test/onboarding/onboard-inference-failure-paths.test.ts index 8d13b5367a0..bffa3d77338 100644 --- a/test/onboarding/onboard-inference-failure-paths.test.ts +++ b/test/onboarding/onboard-inference-failure-paths.test.ts @@ -603,6 +603,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -640,6 +641,7 @@ describe("setupInference dependency failures", () => { }); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { exitProcess, upsertProvider, @@ -675,6 +677,7 @@ describe("setupInference dependency failures", () => { }); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -714,6 +717,7 @@ describe("setupInference dependency failures", () => { message: "Bedrock provider registration failed", })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -751,6 +755,7 @@ describe("setupInference dependency failures", () => { message: "Bedrock provider registration failed without status", })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -784,6 +789,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "inference set" ? { status: 37, stdout: "", stderr: "route denied" } @@ -825,6 +831,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "inference set" ? { status: null, stdout: "", stderr: "" } diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 007ac2f0cf7..23965d9dd14 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -197,6 +197,7 @@ describe("onboarding inference gateway scope", () => { }, ]); const harness = createHarness({ + legacyCustomRoute: true, runOpenshell: commandRouter.runOpenshell, overrides: { probeOpenAiLikeEndpoint: vi.fn(() => ({ ok: true })), diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 1297c8348d6..08d2f18a678 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -109,6 +109,7 @@ describe("onboard helpers", () => { })); const setupBedrockRuntimeInference = bedrockRuntimeOnboard.setupBedrockRuntimeInference; const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.join(" ") === "provider get -g nemoclaw compatible-anthropic-endpoint" ? { status: 1, stdout: "", stderr: "" } @@ -949,6 +950,7 @@ const { isOpenclawReady } = require(${onboardPath}); it("updates OpenAI-compatible providers without passing an unsupported --type flag", async () => { await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" } @@ -989,6 +991,7 @@ const { isOpenclawReady } = require(${onboardPath}); }, ]); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: commandRouter.runOpenshell, overrides: { promptValidationRecovery: async () => { @@ -1034,6 +1037,7 @@ const { isOpenclawReady } = require(${onboardPath}); }, ]); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: commandRouter.runOpenshell, overrides: { promptValidationRecovery: async () => "selection" }, }); @@ -1418,15 +1422,20 @@ describe("re-onboard Ollama GPU release (#9110)", () => { } // A serialized re-onboard can neither replace the row under the read nor // select the captured model before this cleanup runs. - expect(events).toEqual([ + expect(events.filter((event) => event !== "read-prior-route")).toEqual([ "lock-enter", - "read-prior-route", "ownership-lock-enter", "peer-scan", "unload", "ownership-lock-exit", "lock-exit", ]); + const priorReads = events.flatMap((event, index) => + event === "read-prior-route" ? [index] : [], + ); + expect(priorReads.length).toBeGreaterThan(0); + expect(Math.min(...priorReads)).toBeGreaterThan(events.indexOf("lock-enter")); + expect(Math.max(...priorReads)).toBeLessThan(events.indexOf("ownership-lock-enter")); }); it("skips the release when the route returns to selection (#9110)", async () => { diff --git a/test/onboarding/onboard-inference-smoke.test.ts b/test/onboarding/onboard-inference-smoke.test.ts index 703f3aadb9b..75ae93d1463 100644 --- a/test/onboarding/onboard-inference-smoke.test.ts +++ b/test/onboarding/onboard-inference-smoke.test.ts @@ -121,6 +121,7 @@ process.env.BROKEN_API_KEY = "test-key"; const { createSetupInference } = require(${onboardPath}); const setupInference = createSetupInference({ + getSandbox: () => ({ name: "test-sandbox", provider: "compatible-endpoint" }), resolveEndpointHost: async () => [{ address: "93.184.216.34", family: 4 }], }); diff --git a/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts b/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts index b5697e7e5a3..c51383effdb 100644 --- a/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts @@ -18,7 +18,7 @@ const REPO_ROOT = path.join(import.meta.dirname, "../.."); describe("onboard recovered remote-provider credential reuse", () => { it( - "re-applies an exact compatible route without exporting or directly validating its gateway credential", + "re-applies a registered legacy route and requires a new credential after its authority is removed", testTimeoutOptions(90_000), () => { const workspace = createOnboardProcessWorkspace("nemoclaw-remote-recreate-", { @@ -103,8 +103,11 @@ if (process.env.NEMOCLAW_TEST_CONFLICTING_ENDPOINT === "1") { credentialEnv: "COMPATIBLE_API_KEY", }); } -registry.removeSandbox("recovered-custom"); -const { setupNim, setupInference } = require(${onboardPath}); +if (process.env.NEMOCLAW_TEST_RECREATE === "1") registry.removeSandbox("recovered-custom"); +const { setupNim, createSetupInference } = require(${onboardPath}); +const setupInference = createSetupInference({ + resolveEndpointHost: async () => [{ address: "8.8.8.8", family: 4 }], +}); (async () => { const selected = await setupNim(null, "recovered-custom", null, true, { @@ -192,6 +195,22 @@ const { setupNim, setupInference } = require(${onboardPath}); assert.ok(!openshellLog.includes("OPENAI_BASE_URL="), openshellLog); assert.ok(!openshellLog.includes("--credential"), openshellLog); + fs.writeFileSync(openshellLogPath, ""); + const recreateResult = runOnboardProcess([scriptPath], { + env: scenarioEnv({ NEMOCLAW_TEST_RECREATE: "1" }), + timeoutMs: 80_000, + }); + assert.notEqual(recreateResult.status, 0, recreateResult.output); + assert.match( + recreateResult.output, + /A new credential is required for this endpoint and API/, + ); + assert.doesNotMatch(recreateResult.output, /Reusing existing gateway credential/); + assert.doesNotMatch( + fs.readFileSync(openshellLogPath, "utf8"), + /provider (create|update)|inference set/, + ); + fs.writeFileSync(openshellLogPath, ""); const overrideResult = runOnboardProcess([scriptPath], { env: scenarioEnv({ diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index edbd7264578..1c634135b7e 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -845,6 +845,7 @@ const { createSandbox } = require(${onboardPath}); await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 39dca3365cd..dbc9b236547 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -47,6 +47,8 @@ export type DirectRunStubResult = { }; export type DirectSetupHarnessOptions = { + /** Exercise an existing custom sandbox's shared inference route. */ + legacyCustomRoute?: boolean; runOpenshell?: ( args: string[], options: DirectRunOptions, @@ -378,6 +380,7 @@ export function createDirectSetupInferenceHarnessFactory( createSetupInference: CreateSetupInference, ) { return function createDirectSetupInferenceHarness(options: DirectSetupHarnessOptions = {}) { + let legacySandbox: ReturnType> = null; const commands: DirectCommandEntry[] = []; const errors: string[] = []; const logs: string[] = []; @@ -539,7 +542,7 @@ export function createDirectSetupInferenceHarnessFactory( // #9110: neutralize the GPU-release seams so harness consumers backed by // the production defaults never read the developer's real registry or // curl a live Ollama daemon. - getSandbox: () => null, + getSandbox: () => legacySandbox, listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), unloadOllamaModels, withOllamaModelOwnershipLock: (operation) => operation(), @@ -555,8 +558,11 @@ export function createDirectSetupInferenceHarnessFactory( hermesAuthMethod, hermesToolGateways, inferenceOptions = {}, - ) => - setupInferenceWithoutPolicyAuthority( + ) => { + if (options.legacyCustomRoute && sandboxName) { + legacySandbox = { name: sandboxName, provider, model, endpointUrl, credentialEnv }; + } + return setupInferenceWithoutPolicyAuthority( sandboxName, model, provider, @@ -570,6 +576,7 @@ export function createDirectSetupInferenceHarnessFactory( inferenceOptions.revalidateSandboxIdentity ?? revalidateSandboxIdentity, }, ); + }; return { commands, errors, From 92e4cc4cda6cbe72f712df4e62dbb080d96ce1de Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:33:35 -0700 Subject: [PATCH 3/9] fix(inference): preserve native hosted recovery authority --- .../sandbox/inference-invocation-probe.ts | 16 +-- .../native-hosted-profile-response.test.ts | 16 +++ .../native-hosted-profile-response.ts | 1 + .../native-nvidia-profile-response.ts | 3 +- src/lib/inference/native-provider/contract.ts | 15 +++ .../inference/native-provider/custom-setup.ts | 5 + .../inference/native-provider/custom.test.ts | 28 +++- src/lib/onboard.ts | 120 +++++++++--------- .../credential-provider-registration.ts | 48 ++++--- .../handlers/provider-inference.test.ts | 81 +++++++----- .../machine/handlers/provider-inference.ts | 16 ++- .../machine/resume-provider-shim.test.ts | 65 ++++++++++ .../onboard/machine/resume-provider-shim.ts | 26 ++++ src/lib/onboard/resume-provider-recovery.ts | 2 + src/lib/onboard/setup-inference.ts | 14 ++ src/lib/onboard/setup-native-hosted.test.ts | 14 ++ ...egistry-native-provider-attachment.test.ts | 56 ++++++++ src/lib/state/registry.ts | 1 + src/lib/state/registry/route-reservation.ts | 36 +++++- ...redential-migration-reconciliation.test.ts | 47 +++++++ test/e2e/fixtures/inference-adapter.ts | 2 +- .../live/openclaw-inference-switch-helpers.ts | 11 +- .../live/openclaw-inference-switch.test.ts | 23 +++- test/e2e/support/inference-adapter.test.ts | 12 ++ ...openclaw-inference-switch-baseline.test.ts | 109 +++++++++------- .../openclaw-inference-switch-helpers.test.ts | 31 +++-- 26 files changed, 592 insertions(+), 206 deletions(-) diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index 2e41e77bd62..d6fbfd3bdfa 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedAuthHeaderScript } from "../../inference/native-provider/contract"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; import { hostedNativeProvider, @@ -180,21 +181,6 @@ export function resolveSandboxInferenceInvocationEndpoint( return buildProbeRequest(input).endpoint; } -/** Accept only an OpenShell-issued placeholder, never a host credential. */ -export function nativeHostedAuthHeaderScript(definition: { - credentialEnv: string; - api: string; -}): string { - const env = definition.credentialEnv; - const value = "${" + env + ":-}"; - const header = definition.api === "anthropic-messages" ? "x-api-key:" : "Authorization: Bearer"; - return [ - `case "${value}" in *[!a-zA-Z0-9:_]*) exit 2 ;; esac`, - `printf '%s' "${value}" | LC_ALL=C grep -Eq '^openshell:resolve:env:((v[0-9]{1,20}|s[a-f0-9]{64})_)?${env}$' || exit 2`, - `AUTH_HEADER="${header} ${value}"`, - ].join("; "); -} - export function buildSandboxInferenceInvocationCommand( input: SandboxInferenceInvocationInput, ): string { diff --git a/src/lib/adapters/openshell/native-hosted-profile-response.test.ts b/src/lib/adapters/openshell/native-hosted-profile-response.test.ts index c8276f36808..bbdd6439e94 100644 --- a/src/lib/adapters/openshell/native-hosted-profile-response.test.ts +++ b/src/lib/adapters/openshell/native-hosted-profile-response.test.ts @@ -29,6 +29,7 @@ function response(definition: HostedProviderDefinition) { const endpoint = contract.boundary.endpoints[0] as { host: string; port: number; + tls?: string; allowed_ips?: string[]; rules: { allow: { method: string; path: string } }[]; }; @@ -50,6 +51,7 @@ function response(definition: HostedProviderDefinition) { ...base.endpoints[0], host: endpoint.host, port: endpoint.port, + tls: endpoint.tls ?? "", allowedIps: endpoint.allowed_ips ?? [], access: "", rules: endpoint.rules.map((rule) => ({ @@ -128,6 +130,7 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label profile read boundary", (d }); it.each([ + ["compatible-endpoint", "openai-completions", "http://custom.example/team/v1", ["8.8.8.8"]], ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1", ["8.8.8.8"]], [ "compatible-anthropic-endpoint", @@ -155,6 +158,19 @@ it.each([ binding, ); expect(read(value)).toBe(value); + expect( + read({ + profile: { + ...value.profile, + endpoints: [ + { + ...value.profile.endpoints[0], + tls: endpointUrl.startsWith("https:") ? "" : "terminate", + }, + ], + }, + }), + ).toBeUndefined(); expect( read(value, { ...definition.custom!, credentialEnv: "DIFFERENT_SOURCE" }), ).toBeUndefined(); diff --git a/src/lib/adapters/openshell/native-hosted-profile-response.ts b/src/lib/adapters/openshell/native-hosted-profile-response.ts index 75041878ac0..8a5e22dbbf8 100644 --- a/src/lib/adapters/openshell/native-hosted-profile-response.ts +++ b/src/lib/adapters/openshell/native-hosted-profile-response.ts @@ -58,6 +58,7 @@ export function hostedNativeProfileBoundary( return { profileId: definition.profileId as HostedNativeProfileId, ...(pins ? { allowedIps: pins } : {}), + ...(custom && endpoint.protocol === "https:" ? { tls: "terminate" as const } : {}), credentialEnv: definition.credentialEnv, authStyle: definition.api === "anthropic-messages" ? "header" : "bearer", headerName: definition.api === "anthropic-messages" ? "x-api-key" : "authorization", diff --git a/src/lib/adapters/openshell/native-nvidia-profile-response.ts b/src/lib/adapters/openshell/native-nvidia-profile-response.ts index 53aab3a1c83..7823b9b34f3 100644 --- a/src/lib/adapters/openshell/native-nvidia-profile-response.ts +++ b/src/lib/adapters/openshell/native-nvidia-profile-response.ts @@ -17,6 +17,7 @@ export type NativeProfileBoundary = Readonly<{ headerName: string; host: string; port?: number; + tls?: "terminate"; allowedIps?: readonly string[]; rules: readonly Readonly<{ method: "GET" | "POST"; path: string }>[]; }>; @@ -98,7 +99,7 @@ function nativeEndpoint(value: unknown, expected: NativeProfileBoundary): boolea endpoint.port === (expected.port ?? 443) && emptyArray(endpoint.ports) && endpoint.protocol === "rest" && - endpoint.tls === "" && + endpoint.tls === (expected.tls ?? "") && endpoint.enforcement === "enforce" && endpoint.access === "" && Array.isArray(rules) && diff --git a/src/lib/inference/native-provider/contract.ts b/src/lib/inference/native-provider/contract.ts index 086b0456507..733c0189e40 100644 --- a/src/lib/inference/native-provider/contract.ts +++ b/src/lib/inference/native-provider/contract.ts @@ -65,3 +65,18 @@ export function normalizeNativeProviderAttachment

NativeProviderAttachment | undefined; writeAuthority: (gateway: string, provider: string, receipt: NativeProviderAttachment) => void; + onCredentialPersisted?: (credentialEnv: string, value: string) => void; }): Promise { if (unsafeEndpointUrlViolation(input.endpointUrl) || /%2f|%5c|%2e/iu.test(input.endpointUrl)) throw new Error("Custom native inference requires a valid credential-free HTTP(S) endpoint"); @@ -142,5 +143,9 @@ export async function prepareCustomNativeProvider(input: { writeAuthority: (gateway, authority) => input.writeAuthority(gateway, input.provider, authority), }); + // Reuse does not prove that an ambient legacy value was stored. Bedrock + // stores an adapter token, so its source credential is not retired here. + if (!expected && !bedrock && credentialValue) + input.onCredentialPersisted?.(input.credentialEnv, credentialValue); return receipt; } diff --git a/src/lib/inference/native-provider/custom.test.ts b/src/lib/inference/native-provider/custom.test.ts index 3fbb0eb77c0..0a656f4f6a6 100644 --- a/src/lib/inference/native-provider/custom.test.ts +++ b/src/lib/inference/native-provider/custom.test.ts @@ -219,16 +219,24 @@ describe("custom native endpoint ownership", () => { it("reuses verified credentials without rotating them, even when a host key is present", async () => { const h = harness(); - const first = await prepareCustomNativeProvider(h.input); + const onCredentialPersisted = vi.fn(); + const first = await prepareCustomNativeProvider({ ...h.input, onCredentialPersisted }); + expect(onCredentialPersisted).toHaveBeenCalledExactlyOnceWith( + binding.credentialEnv, + "synthetic-host-secret", + ); + onCredentialPersisted.mockClear(); const second = await prepareCustomNativeProvider({ ...h.input, recordedAttachment: first, credentialValue: "another-host-key", + onCredentialPersisted, lookup: async () => { throw new Error("Do not re-resolve admitted pins"); }, }); expect(second).toEqual(first); + expect(onCredentialPersisted).not.toHaveBeenCalled(); expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); expect(h.adapter.updateProvider).not.toHaveBeenCalled(); expect(JSON.stringify(h.writeAuthority.mock.calls)).not.toContain("synthetic-host-secret"); @@ -244,6 +252,21 @@ describe("custom native endpoint ownership", () => { expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); }); + it("does not retire a credential when authority persistence fails", async () => { + const h = harness(); + const onCredentialPersisted = vi.fn(); + await expect( + prepareCustomNativeProvider({ + ...h.input, + onCredentialPersisted, + writeAuthority: () => { + throw new Error("authority write failed"); + }, + }), + ).rejects.toThrow("authority write failed"); + expect(onCredentialPersisted).not.toHaveBeenCalled(); + }); + it("rejects profile collisions before provider or attachment changes", async () => { const h = harness(); h.adapter.importProviderProfile.mockResolvedValue({ @@ -331,6 +354,7 @@ describe("custom native endpoint ownership", () => { it("keeps Bedrock AWS credentials in the existing adapter and injects only its token", async () => { const h = harness(); + const onCredentialPersisted = vi.fn(); const bedrock = { ...binding, provider: "compatible-anthropic-endpoint", @@ -350,6 +374,7 @@ describe("custom native endpoint ownership", () => { provider: bedrock.provider, endpointUrl: bedrock.endpointUrl, ensureBedrockAdapter, + onCredentialPersisted, }); expect(h.adapter.createProvider).toHaveBeenCalledWith( expect.objectContaining({ @@ -369,5 +394,6 @@ describe("custom native endpoint ownership", () => { expect(h.adapter.updateProvider).not.toHaveBeenCalled(); expect(JSON.stringify(receipt)).not.toContain("synthetic-"); expect(h.lookup).not.toHaveBeenCalled(); + expect(onCredentialPersisted).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 635e0f1ebe8..7eba5396220 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2272,66 +2272,65 @@ function getSetupNimDeps(): SetupNimDeps { } const setupNim = setupNimFlow.createSetupNim(getSetupNimDeps()); // ── Step 4: Inference provider ─────────────────────────────────── -function getSetupInferenceDeps(): SetupInferenceDeps { - return { - checkGatewayRouteCompatibility, - withGatewayRouteMutationLock: gatewayRouteMutationLock.withGatewayRouteMutationLock, - withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, - step, - getGatewayName: () => GATEWAY_NAME, - runOpenshell, - inferenceRouteMutator, - inferenceRouteObserver, - upsertProvider, - verifyInferenceRoute, - verifyOnboardInferenceSmoke, - isNonInteractive, - updateSandbox: registry.reserveSandboxInferenceRoute, - getSandbox: registry.getSandbox, - listSandboxes: registry.listSandboxes, - unloadOllamaModels, - hermesProviderAuth, - getHermesToolGatewayBroker, - ...onboardProviders.setupInferenceProviderDeps(runOpenshell), - normalizeHermesAuthMethod, - resolveHermesNousApiKey, - checkHermesProviderStoreReachable, - hermesAuthMethodLabel, - hermesConstants: { - HERMES_NOUS_API_KEY_CREDENTIAL_ENV, - HERMES_AUTH_METHOD_API_KEY, - HERMES_AUTH_METHOD_OAUTH, - }, - requireValue, - redact, - compactText, - REMOTE_PROVIDER_CONFIG, - hydrateCredentialEnv, - promptValidationRecovery, - classifyApplyFailure, - localInferenceTimeoutSecs: LOCAL_INFERENCE_TIMEOUT_SECS, - bedrockRuntimeOnboard, - openrouterRuntimeOnboard, - validateLocalProvider, - getLocalProviderHealthCheck, - getLocalProviderBaseUrl, - run, - vllmLocalCredentialEnv: VLLM_LOCAL_CREDENTIAL_ENV, - shouldFrontOllamaWithProxy, - ensureOllamaAuthProxy, - isProxyHealthy, - getOllamaProxyToken, - persistAndProbeOllamaProxy, - localInference, - ollamaProxyCredentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, - isRoutedInferenceProvider, - reconcileModelRouter, - routedInference, - log: (message: string) => console.log(message), - error: (message: string) => console.error(message), - exitProcess: (code: number): never => process.exit(code), - }; -} +const getSetupInferenceDeps = (): SetupInferenceDeps => ({ + checkGatewayRouteCompatibility, + withGatewayRouteMutationLock: gatewayRouteMutationLock.withGatewayRouteMutationLock, + withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, + step, + getGatewayName: () => GATEWAY_NAME, + runOpenshell, + inferenceRouteMutator, + inferenceRouteObserver, + upsertProvider, + recordMigratedProviderCredential: registration.recordMigratedProviderCredential, + verifyInferenceRoute, + verifyOnboardInferenceSmoke, + isNonInteractive, + updateSandbox: registry.reserveSandboxInferenceRoute, + getSandbox: registry.getSandbox, + listSandboxes: registry.listSandboxes, + unloadOllamaModels, + hermesProviderAuth, + getHermesToolGatewayBroker, + ...onboardProviders.setupInferenceProviderDeps(runOpenshell), + normalizeHermesAuthMethod, + resolveHermesNousApiKey, + checkHermesProviderStoreReachable, + hermesAuthMethodLabel, + hermesConstants: { + HERMES_NOUS_API_KEY_CREDENTIAL_ENV, + HERMES_AUTH_METHOD_API_KEY, + HERMES_AUTH_METHOD_OAUTH, + }, + requireValue, + redact, + compactText, + REMOTE_PROVIDER_CONFIG, + hydrateCredentialEnv, + promptValidationRecovery, + classifyApplyFailure, + localInferenceTimeoutSecs: LOCAL_INFERENCE_TIMEOUT_SECS, + bedrockRuntimeOnboard, + openrouterRuntimeOnboard, + validateLocalProvider, + getLocalProviderHealthCheck, + getLocalProviderBaseUrl, + run, + vllmLocalCredentialEnv: VLLM_LOCAL_CREDENTIAL_ENV, + shouldFrontOllamaWithProxy, + ensureOllamaAuthProxy, + isProxyHealthy, + getOllamaProxyToken, + persistAndProbeOllamaProxy, + localInference, + ollamaProxyCredentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, + isRoutedInferenceProvider, + reconcileModelRouter, + routedInference, + log: (message: string) => console.log(message), + error: (message: string) => console.error(message), + exitProcess: (code: number): never => process.exit(code), +}); export type SetupInferenceDeps = import("./onboard/setup-inference").SetupInferenceDeps; export type SetupInference = import("./onboard/setup-inference").SetupInference; function createSetupInference(overrides: Partial = {}): SetupInference { @@ -2921,6 +2920,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { import("./resources-cmd").ResourceProfile >({ resumeProvider: { + getSandbox: registry.getSandbox, isNonInteractive, isRoutedInferenceProvider, providerExistsInGateway, diff --git a/src/lib/onboard/credential-provider-registration.ts b/src/lib/onboard/credential-provider-registration.ts index 2998823e699..4281e0feb96 100644 --- a/src/lib/onboard/credential-provider-registration.ts +++ b/src/lib/onboard/credential-provider-registration.ts @@ -239,6 +239,22 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg const refreshReceipts = new Map(); const gatewayRunner = (gatewayName = deps.getGatewayName()) => createGatewayScopedOpenshellRunner(deps.runOpenshell, gatewayName); + function recordMigratedProviderCredential( + name: string, + credentialEnv: string, + persistedValue: string | null, + revalidateSandboxIdentity?: (operation: string) => void, + ): void { + // Retire only the staged value actually written, including declared aliases. + const migrationKeys = stagedMigrationKeys(credentialEnv, deps.stagedLegacyValues); + if (migrationKeys.length === 0) return; + revalidateSandboxIdentity?.(`record migrated credential for provider ${JSON.stringify(name)}`); + for (const key of migrationKeys) { + if (persistedValue === deps.stagedLegacyValues.get(key)) deps.migratedLegacyKeys.add(key); + else deps.migratedLegacyKeys.delete(key); + } + } + async function upsertProvider( name: string, type: string, @@ -257,26 +273,17 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg gatewayRunner(gatewayName), options, ); - if (result.ok && credentialEnv) { - // The legacy file can carry the value under an alias of the canonical - // credential env (NVIDIA_API_KEY for NVIDIA_INFERENCE_API_KEY), which - // resolveProviderCredential resolves transparently. Account the alias - // too, or the staged key never looks migrated and the plaintext file - // survives an onboard that used it (#10373). - const migrationKeys = stagedMigrationKeys(credentialEnv, deps.stagedLegacyValues); - if (migrationKeys.length > 0) { - options.revalidateSandboxIdentity?.( - `record migrated credential for provider ${JSON.stringify(name)}`, - ); - const upsertedValue = env[credentialEnv] ?? deps.getCredential(credentialEnv); - for (const key of migrationKeys) { - if (upsertedValue === deps.stagedLegacyValues.get(key)) { - deps.migratedLegacyKeys.add(key); - } else { - deps.migratedLegacyKeys.delete(key); - } - } - } + if ( + result.ok && + credentialEnv && + stagedMigrationKeys(credentialEnv, deps.stagedLegacyValues).length > 0 + ) { + recordMigratedProviderCredential( + name, + credentialEnv, + env[credentialEnv] ?? deps.getCredential(credentialEnv), + options.revalidateSandboxIdentity, + ); } return result; } @@ -487,6 +494,7 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg } return { + recordMigratedProviderCredential, inspectGatewayCredential, providerMatchesGatewayCredential, applyMessagingProviders, diff --git a/src/lib/onboard/machine/handlers/provider-inference.test.ts b/src/lib/onboard/machine/handlers/provider-inference.test.ts index 419687d02da..9eeab948ad9 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test.ts @@ -308,6 +308,8 @@ describe("handleProviderInferenceState", () => { "nemoclaw", "compatible-endpoint", "COMPATIBLE_API_KEY", + undefined, + { sandboxName: "mcp-rebuild", endpointUrl: "https://compatible.example.test/v1" }, ); expect(calls.complete).toHaveBeenCalledWith( "provider_selection", @@ -450,7 +452,13 @@ describe("handleProviderInferenceState", () => { expect(calls.setupNim).not.toHaveBeenCalled(); expect(calls.setupInference).not.toHaveBeenCalled(); - expect(calls.recoverProvider).toHaveBeenCalledWith("nemoclaw", "ollama-local", null); + expect(calls.recoverProvider).toHaveBeenCalledWith( + "nemoclaw", + "ollama-local", + null, + undefined, + { sandboxName: null, endpointUrl: null }, + ); expect(calls.skipped).toHaveBeenCalledWith("provider_selection", "ollama-local / llama3.1"); expect(calls.recordSkip).toHaveBeenCalledWith("provider_selection", { reason: "resume", @@ -878,41 +886,46 @@ describe("handleProviderInferenceState", () => { expect(calls.repairEvent).not.toHaveBeenCalledWith("state.repair.completed", expect.anything()); }); - it("reruns inference setup when resumed provider recovery forces recreation", async () => { - const session = createSession({ - provider: "compatible-endpoint", - model: "custom-model", - credentialEnv: null, - }); - session.steps.provider_selection.status = "complete"; - const { deps, calls } = createDeps({ - isInferenceRouteReady: vi.fn(() => true), - ensureResumeProviderReady: vi.fn(async () => ({ - forceInferenceSetup: true, - credentialEnv: "COMPATIBLE_API_KEY", - })), - }); - calls.complete.mockResolvedValue(session); + it.each([false, true])( + "reruns resumed provider setup with native custom recovery %s", + async (nativeCustomSetup) => { + const session = createSession({ + provider: "compatible-endpoint", + model: "custom-model", + credentialEnv: null, + }); + session.steps.provider_selection.status = "complete"; + const { deps, calls } = createDeps({ + isInferenceRouteReady: vi.fn(() => true), + ensureResumeProviderReady: vi.fn(async () => ({ + forceInferenceSetup: true, + credentialEnv: "COMPATIBLE_API_KEY", + nativeCustomSetup, + })), + }); + calls.complete.mockResolvedValue(session); - await handleProviderInferenceState({ - ...baseOptions(deps, session), - resume: true, - sandboxName: "my-assistant", - }); + await handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "my-assistant", + ...(nativeCustomSetup ? { selectedMessagingChannels: ["telegram"] } : {}), + }); - expect(calls.setupNim).not.toHaveBeenCalled(); - expect(calls.hydrate).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); - expect(calls.setupInference).toHaveBeenCalledWith( - "my-assistant", - "custom-model", - "compatible-endpoint", - null, - "COMPATIBLE_API_KEY", - null, - [], - setupOptions(session), - ); - }); + expect(calls.setupNim).not.toHaveBeenCalled(); + expect(calls.hydrate).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); + expect(calls.setupInference).toHaveBeenCalledWith( + "my-assistant", + "custom-model", + "compatible-endpoint", + null, + "COMPATIBLE_API_KEY", + null, + [], + setupOptions(session), + ); + }, + ); it("forces canonical setup for a preflighted provider even if a matching route appears (#6114)", async () => { const session = createSession({ diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 8b76dec3ce9..07d071291ad 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -266,7 +266,12 @@ export interface ProviderInferenceStateOptions { provider: string | null | undefined, credentialEnv: string | null | undefined, revalidateSandboxIdentity?: (operation: string) => void, - ): Promise<{ forceInferenceSetup: boolean; credentialEnv: string | null }>; + selection?: { sandboxName: string | null; endpointUrl: string | null }, + ): Promise<{ + forceInferenceSetup: boolean; + credentialEnv: string | null; + nativeCustomSetup?: boolean; + }>; ensureManagedLlamaCppResumeReady( provider: string | null | undefined, sandboxName: string | null | undefined, @@ -1496,7 +1501,13 @@ export async function handleProviderInferenceState({ sandboxName, deps.ensureManagedLlamaCppResumeReady, ); - const recovery = await deps.ensureResumeProviderReady(gatewayName, provider, credentialEnv); + const recovery = await deps.ensureResumeProviderReady( + gatewayName, + provider, + credentialEnv, + undefined, + { sandboxName: reusableResumeSandboxName, endpointUrl }, + ); forceInferenceSetup ||= recovery.forceInferenceSetup; credentialEnv = recovery.credentialEnv; // Rebuild may be resuming a legacy session whose step marker was never @@ -1549,6 +1560,7 @@ export async function handleProviderInferenceState({ // of the stored gateway credential and suppression of the unauthenticated // host smoke. if ( + !recovery.nativeCustomSetup && shouldRefreshCompatibleEndpointRouteForMessaging( provider, selectedMessagingChannels, diff --git a/src/lib/onboard/machine/resume-provider-shim.test.ts b/src/lib/onboard/machine/resume-provider-shim.test.ts index 3c33eb3f0c5..732ae3f73ec 100644 --- a/src/lib/onboard/machine/resume-provider-shim.test.ts +++ b/src/lib/onboard/machine/resume-provider-shim.test.ts @@ -7,6 +7,7 @@ vi.mock("../../credentials/store", () => ({ resolveProviderCredential: vi.fn(() => null), })); +import { customNativeProvider } from "../../inference/native-provider/custom"; import { createResumeProviderShim } from "./resume-provider-shim"; describe("createResumeProviderShim", () => { @@ -92,3 +93,67 @@ describe("createResumeProviderShim", () => { ).rejects.toBe(ownershipConflict); }); }); + +it.each([ + ["native", "TEAM_KEY"], + ["native", null], + ["reservation", "TEAM_KEY"], + ["legacy", "TEAM_KEY"], +] as const)( + "routes %s custom resume through its owning credential recovery", + async (state, credentialEnv) => { + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const recorded = + state === "native" + ? { + nativeHostedProviderAttachment: { + schemaVersion: 1 as const, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "owned-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }, + } + : { pendingRouteReservation: state === "reservation" }; + const providerExistsInGateway = vi.fn(() => true); + const replaceNamedCredential = vi.fn(async () => "unexpected"); + const shim = createResumeProviderShim({ + getSandbox: (name) => { + expect(name).toBe("alpha"); + return recorded; + }, + isNonInteractive: () => true, + providerExistsInGateway, + isRoutedInferenceProvider: () => false, + replaceNamedCredential, + }); + const result = await shim.ensureResumeProviderReady( + "gateway-west", + "compatible-endpoint", + credentialEnv, + undefined, + { sandboxName: "alpha", endpointUrl: "https://custom.example/v1" }, + ); + expect(result).toEqual( + state === "legacy" + ? { forceInferenceSetup: false, credentialEnv: "TEAM_KEY" } + : { + forceInferenceSetup: true, + credentialEnv: credentialEnv ?? "COMPATIBLE_API_KEY", + nativeCustomSetup: true, + }, + ); + expect(providerExistsInGateway.mock.calls).toEqual( + state === "legacy" ? [["compatible-endpoint", "gateway-west"]] : [], + ); + expect(replaceNamedCredential).not.toHaveBeenCalled(); + }, +); diff --git a/src/lib/onboard/machine/resume-provider-shim.ts b/src/lib/onboard/machine/resume-provider-shim.ts index 5380eecc80e..ac138260083 100644 --- a/src/lib/onboard/machine/resume-provider-shim.ts +++ b/src/lib/onboard/machine/resume-provider-shim.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 import { runOpenshell } from "../../adapters/openshell/runtime"; +import { usesCustomNativeOnboarding } from "../../inference/native-provider/custom-setup"; import { D, R } from "../../cli/terminal-style"; import { isBedrockRuntimeEndpoint } from "../../inference/bedrock-runtime"; import { DEFAULT_ROUTE_CREDENTIAL_ENV } from "../../inference/config"; @@ -19,9 +20,11 @@ import { const onboardProviders = require("../providers") as { REMOTE_PROVIDER_CONFIG: ResumeProviderRecoveryDeps["remoteProviderConfig"]; getProviderLabel: ResumeProviderRecoveryDeps["getProviderLabel"]; + getRemoteProviderConfigForName(name: string): { credentialEnv: string } | null; }; export type ResumeProviderShimDeps = { + getSandbox?: (name: string) => Parameters[3]; isNonInteractive: ResumeProviderRecoveryDeps["isNonInteractive"]; providerExistsInGateway(name: string, gatewayName: string): boolean | Promise; isRoutedInferenceProvider: ResumeProviderRecoveryDeps["isRoutedInferenceProvider"]; @@ -50,7 +53,30 @@ export function createResumeProviderShim(deps: ResumeProviderShimDeps) { provider: string | null | undefined, credentialEnv: string | null | undefined, revalidateSandboxIdentity?: (operation: string) => void, + selection?: { sandboxName: string | null; endpointUrl: string | null }, ): Promise { + if ( + provider && + selection?.sandboxName && + deps.getSandbox && + usesCustomNativeOnboarding( + provider, + selection.endpointUrl, + selection.sandboxName, + deps.getSandbox(selection.sandboxName), + ) + ) { + // Setup verifies the endpoint-bound receipt and live resource identity. + // Looking up the logical name here would demand a key before that check. + return { + forceInferenceSetup: true, + credentialEnv: + credentialEnv || + onboardProviders.getRemoteProviderConfigForName(provider)?.credentialEnv || + null, + nativeCustomSetup: true, + }; + } return ensureResumeProviderReadyImpl(provider, credentialEnv, { remoteProviderConfig: onboardProviders.REMOTE_PROVIDER_CONFIG, defaultRouteCredentialEnv: DEFAULT_ROUTE_CREDENTIAL_ENV, diff --git a/src/lib/onboard/resume-provider-recovery.ts b/src/lib/onboard/resume-provider-recovery.ts index 841610a0e75..f20e066f86a 100644 --- a/src/lib/onboard/resume-provider-recovery.ts +++ b/src/lib/onboard/resume-provider-recovery.ts @@ -48,6 +48,8 @@ export type ResumeProviderRecoveryDeps = { }; export type ResumeProviderRecoveryResult = { + /** Route recovery through native setup; this is not evidence of credential ownership. */ + nativeCustomSetup?: boolean; forceInferenceSetup: boolean; credentialEnv: string | null; }; diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index d54f2a764c0..f971213823a 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -220,6 +220,12 @@ type ProviderBranchDeps = Pick< Pick; export type SetupInferenceDeps = ProviderBranchDeps & { + recordMigratedProviderCredential?: ( + name: string, + credentialEnv: string, + persistedValue: string, + revalidateSandboxIdentity?: (operation: string) => void, + ) => void; /** Injectable resolver for resumed custom-endpoint SSRF preflight tests. */ resolveEndpointHost?: EndpointDnsLookupFn; /** Exact private endpoint hosts trusted by the operator (tests may inject this). */ @@ -1228,6 +1234,14 @@ export function createSetupInference( trustedPrivateHosts: deps.trustedPrivateEndpointHosts, readAuthority: deps.getNativeHostedProviderAuthority, writeAuthority: deps.setNativeHostedProviderAuthority, + onCredentialPersisted: (env, value) => { + deps.recordMigratedProviderCredential?.( + provider, + env, + value, + revalidateSandboxIdentity, + ); + }, }); retainedNativeHostedCredential = !credentialValue; return null; diff --git a/src/lib/onboard/setup-native-hosted.test.ts b/src/lib/onboard/setup-native-hosted.test.ts index c0df0e71e2d..74c7066eec3 100644 --- a/src/lib/onboard/setup-native-hosted.test.ts +++ b/src/lib/onboard/setup-native-hosted.test.ts @@ -77,6 +77,7 @@ describe.each(providers)("native $label onboarding", (provider) => { const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); const updateSandbox = vi.fn(() => true); const writeAuthority = vi.fn(); + const recordMigratedProviderCredential = vi.fn(); const setup = createSetupInference({ checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true })), withSandboxMutationLock: async (_name: string, fn: () => T | Promise) => await fn(), @@ -106,6 +107,7 @@ describe.each(providers)("native $label onboarding", (provider) => { : null, resolveEndpointHost: async () => [{ address: "8.8.8.8", family: 4 }], upsertProvider: vi.fn(), + recordMigratedProviderCredential, verifyInferenceRoute, verifyOnboardInferenceSmoke, isNonInteractive: () => true, @@ -173,6 +175,18 @@ describe.each(providers)("native $label onboarding", (provider) => { type: provider.profileId, }), ); + expect(recordMigratedProviderCredential.mock.calls).toEqual( + provider.custom + ? [ + [ + provider.logicalProvider, + provider.custom.credentialEnv, + "host-secret", + expect.any(Function), + ], + ] + : [], + ); expect(writeAuthority).toHaveBeenCalledWith("gateway", provider.logicalProvider, receipt); expect(updateSandbox).toHaveBeenCalledWith( "alpha", diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index 71fbc7e26e9..09686039f15 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -120,3 +120,59 @@ it("lists registered sandboxes that retain native NVIDIA provider ownership", as vi.unstubAllEnvs(); } }); + +it.each([ + ["unchanged binding", {}, true], + ["model change", { model: "model-b" }, true], + ["endpoint change", { endpointUrl: "https://other.example/v1" }, false], + ["API change", { preferredInferenceApi: "openai-responses" }, false], + ["credential change", { credentialEnv: "OTHER_KEY" }, false], + ["gateway change", { gatewayName: "other-gateway" }, false], +] as const)( + "preserves custom native reservation authority only for its binding: %s", + async (_label, changes, retained) => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-custom-reservation-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + const { customNativeProvider } = await import("../inference/native-provider/custom"); + const route = { + provider: "compatible-endpoint", + model: "model-a", + endpointUrl: "https://custom.example/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + gatewayName: "nemoclaw", + }; + const definition = customNativeProvider({ + provider: route.provider, + endpointUrl: route.endpointUrl, + credentialEnv: route.credentialEnv, + api: route.preferredInferenceApi, + allowedIps: ["8.8.8.8"], + }); + const receipt = { + schemaVersion: 1 as const, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "owned-provider-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }; + registry.registerSandbox({ + name: "alpha", + ...route, + nativeHostedProviderAttachment: receipt, + }); + expect(registry.reserveSandboxInferenceRoute("alpha", { ...route, ...changes })).toBe(true); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual( + retained ? receipt : undefined, + ); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } + }, +); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index d4ff65b247a..fcf64fd81a0 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -770,6 +770,7 @@ export function reserveSandboxInferenceRoute( nativeHostedProviderAttachment, normalized.provider, existing ?? undefined, + { ...normalized, gatewayName: route.gatewayName }, ), nativeNvidiaProviderAttachment: isNativeNvidiaProvider(normalized.provider) ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 128a6f43dc5..2c19274aa0c 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -4,6 +4,7 @@ import { isDeepStrictEqual } from "node:util"; import { normalizeInferenceSelection, type InferenceSelection } from "../../inference/selection"; +import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; import { requireHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; @@ -363,12 +364,35 @@ export function nativeHostedReservationAttachment( value: unknown, provider: string | null | undefined, previous?: SandboxEntry, + selection?: Pick< + SandboxEntry, + "provider" | "endpointUrl" | "credentialEnv" | "preferredInferenceApi" | "gatewayName" + >, ) { const receipt = requireHostedProviderAttachment(value, provider); - return receipt || hostedNativeProvider(provider) - ? (receipt ?? - (previous && previous.provider === provider - ? previous.nativeHostedProviderAttachment - : undefined)) - : undefined; + if (receipt) return receipt; + if (!previous || previous.provider !== provider) return undefined; + const retained = requireHostedProviderAttachment( + previous.nativeHostedProviderAttachment, + provider, + ); + if (retained?.custom) { + if ( + !selection?.endpointUrl || + !selection.credentialEnv || + !selection.preferredInferenceApi || + selection.gatewayName !== previous.gatewayName + ) + return undefined; + try { + return recordedNativeProviderAttachment({ + ...selection, + nativeHostedProviderAttachment: retained, + }); + } catch { + // A changed binding needs new authority from provider setup. + return undefined; + } + } + return hostedNativeProvider(provider) ? retained : undefined; } diff --git a/test/credentials/credential-migration-reconciliation.test.ts b/test/credentials/credential-migration-reconciliation.test.ts index 83542b97e0c..c5817c91147 100644 --- a/test/credentials/credential-migration-reconciliation.test.ts +++ b/test/credentials/credential-migration-reconciliation.test.ts @@ -404,3 +404,50 @@ describe("legacy credential reconciliation", () => { } }); }); + +it.each([true, false])( + "retires only the persisted native credential value (matches=%s)", + async (matches) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "native-credential-migration-")); + const legacy = path.join(directory, ".nemoclaw", "credentials.json"); + fs.mkdirSync(path.dirname(legacy), { recursive: true }); + fs.writeFileSync(legacy, JSON.stringify({ COMPATIBLE_API_KEY: LEGACY_SECRET }), { + mode: 0o600, + }); + try { + await withProcessEnv({ HOME: directory, COMPATIBLE_API_KEY: undefined }, async () => { + const stagedKeys = stageLegacyCredentialsToEnv(); + const stagedValues = new Map(stagedKeys.map((key) => [key, process.env[key] ?? ""])); + const migrated = new Set(); + const revalidate = vi.fn(); + const registration = createCredentialProviderRegistration({ + root: directory, + getGatewayName: () => "gateway", + getCredential: () => null, + runOpenshell: vi.fn(), + updateSession: vi.fn(), + stagedLegacyValues: stagedValues, + migratedLegacyKeys: migrated, + }); + registration.recordMigratedProviderCredential( + "compatible-endpoint", + "COMPATIBLE_API_KEY", + matches ? LEGACY_SECRET : "different-persisted-key", + revalidate, + ); + expect(revalidate).toHaveBeenCalledTimes(1); + await finalizeMigration(stagedKeys, migrated, stagedValues); + expect(fs.existsSync(legacy)).toBe(!matches); + const retainedCredentials = fs + .readdirSync(path.dirname(legacy)) + .filter((name) => name === "credentials.json") + .map((name) => + JSON.parse(fs.readFileSync(path.join(path.dirname(legacy), name), "utf8")), + ); + expect(retainedCredentials).toEqual(matches ? [] : [{ COMPATIBLE_API_KEY: LEGACY_SECRET }]); + }); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, +); diff --git a/test/e2e/fixtures/inference-adapter.ts b/test/e2e/fixtures/inference-adapter.ts index 01ede00c813..5b7229622f8 100644 --- a/test/e2e/fixtures/inference-adapter.ts +++ b/test/e2e/fixtures/inference-adapter.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { randomBytes } from "node:crypto"; -import { nativeHostedAuthHeaderScript } from "../../../src/lib/actions/sandbox/inference-invocation-probe.ts"; +import { nativeHostedAuthHeaderScript } from "../../../src/lib/inference/native-provider/contract.ts"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT, NVIDIA_HOSTED_LOGICAL_PROVIDER, diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index 906d71fc07c..9a6aaf87226 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -158,13 +158,14 @@ export const MOCK_BASELINE_MODEL = "openclaw-switch-baseline-model"; export function startMockOpenClawBaselineProvider( progress: FakeOpenAiCompatibleServerOptions["progress"], + publicHost = "host.openshell.internal", ) { return startFakeOpenAiCompatibleServer({ apiKey: MOCK_BASELINE_API_KEY, chatContent: "PONG", host: "0.0.0.0", model: MOCK_BASELINE_MODEL, - publicHost: "host.openshell.internal", + publicHost, progress, requireAuth: true, }); @@ -213,23 +214,23 @@ export async function readOpenClawConfig( timeoutMs: number; artifactName: string; nativeNvidia?: boolean; - nativeAnthropic?: boolean; + nativeCustomApi?: string; }, ): Promise { return sandbox.exec( sandboxName, - options.nativeNvidia || options.nativeAnthropic + options.nativeNvidia || options.nativeCustomApi ? [ "node", "-e", [ 'const fs = require("node:fs");', 'const config = JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', - `const provider = config.models?.providers?.${options.nativeAnthropic ? "anthropic" : "inference"};`, + `const provider = config.models?.providers?.${options.nativeCustomApi === "anthropic-messages" ? "anthropic" : "inference"};`, // A fresh exec receives the newly attached provider handle. Keep // both values inside the sandbox because ShellProbe redacts the // credential-shaped config field before returning stdout. - `const credentialEnv = ${JSON.stringify(options.nativeAnthropic ? "COMPATIBLE_ANTHROPIC_API_KEY" : "NVIDIA_INFERENCE_API_KEY")};`, + `const credentialEnv = ${JSON.stringify(options.nativeCustomApi ? (options.nativeCustomApi === "anthropic-messages" ? "COMPATIBLE_ANTHROPIC_API_KEY" : "COMPATIBLE_API_KEY") : "NVIDIA_INFERENCE_API_KEY")};`, "const handle = process.env[credentialEnv];", 'require("node:assert/strict").ok(new RegExp("^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_" + credentialEnv + "$").test(handle ?? "") && provider?.apiKey === handle, "native credential reference mismatch");', "delete provider.apiKey;", diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index fbbd9d883f0..7e3a6c738cb 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -17,7 +17,7 @@ import os from "node:os"; import path from "node:path"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; -import { nativeHostedAuthHeaderScript } from "../../../src/lib/actions/sandbox/inference-invocation-probe.ts"; +import { nativeHostedAuthHeaderScript } from "../../../src/lib/inference/native-provider/contract.ts"; import { discoverHostAddress } from "../fixtures/host-address.ts"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; @@ -171,7 +171,7 @@ interface MockAnthropicRequest { } function proveMockBaselineAuthentication( - baseline: Pick | undefined, + baseline: Pick | undefined, sandbox: SandboxClient, home: string, artifacts: { writeJson(path: string, value: unknown): Promise }, @@ -182,7 +182,7 @@ function proveMockBaselineAuthentication( } async function proveSelectedMockBaselineAuthentication( - baseline: Pick, + baseline: Pick, sandbox: SandboxClient, home: string, artifacts: { writeJson(path: string, value: unknown): Promise }, @@ -199,7 +199,9 @@ async function proveSelectedMockBaselineAuthentication( const probe = await sandboxShell( sandbox, home, - `curl -fsS --max-time 60 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null`, + SWITCH_NATIVE_CUSTOM + ? `${nativeHostedAuthHeaderScript({ credentialEnv: "COMPATIBLE_API_KEY", api: "openai-completions" })}; curl -fsS --max-time 60 ${shellQuote(`${baseline.baseUrl}/chat/completions`)} -H "$AUTH_HEADER" -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null` + : `curl -fsS --max-time 60 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null`, { artifactName: "baseline-explicit-authenticated-inference-post", timeoutMs: 90_000, @@ -632,7 +634,7 @@ async function readAndAssertOpenClawConfig( ): Promise { const configResult = await readOpenClawConfig(sandbox, SANDBOX_NAME, { nativeNvidia: expected.nativeNvidia, - nativeAnthropic: Boolean(expected.nativeCustomEndpoint), + nativeCustomApi: expected.nativeCustomEndpoint ? expected.inferenceApi : undefined, artifactName: expected.artifactName, env: commandEnv(home), timeoutMs: COMMAND_TIMEOUT_MS, @@ -995,6 +997,7 @@ exit "$rc" } async function runInitialRouteLifecycle(options: { + nativeCustomEndpoint?: string; artifacts: ArtifactSink; baselineProvider?: Pick; home: string; @@ -1009,6 +1012,7 @@ async function runInitialRouteLifecycle(options: { model: options.model, inferenceApi: "openai-completions", artifactName: `read-openclaw-initial-route-${artifactSuffix}`, + nativeCustomEndpoint: options.nativeCustomEndpoint, }); await checkOpenClawGatewayInference( options.host, @@ -1192,8 +1196,11 @@ test( (SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"); // OpenShell reaches this fixture from its gateway network namespace, where // the runner's loopback address is not routable. + const nativeBaselineHost = SWITCH_NATIVE_CUSTOM + ? (await discoverHostAddress(host, "native-baseline-endpoint-address")).address + : undefined; const baselineProvider: FakeOpenAiCompatibleServer | undefined = useMockBaseline - ? await startMockOpenClawBaselineProvider(progress) + ? await startMockOpenClawBaselineProvider(progress, nativeBaselineHost) : undefined; cleanup.trackDisposable("close baseline inference provider", async () => { await baselineProvider?.close(); @@ -1248,6 +1255,9 @@ test( artifactName: "onboard-custom-image-openclaw-inference-switch", env: commandEnv(home, { ...baseline.env, + ...(nativeBaselineHost + ? { NEMOCLAW_TRUSTED_PRIVATE_INFERENCE_HOSTS: nativeBaselineHost } + : {}), NEMOCLAW_RECREATE_SANDBOX: "1", }), redactionValues, @@ -1282,6 +1292,7 @@ test( false, ); await runInitialRouteLifecycle({ + nativeCustomEndpoint: nativeBaselineHost ? baseline.endpointUrl : undefined, artifacts, baselineProvider, home, diff --git a/test/e2e/support/inference-adapter.test.ts b/test/e2e/support/inference-adapter.test.ts index 9a03ba91016..83b9fe2c10f 100644 --- a/test/e2e/support/inference-adapter.test.ts +++ b/test/e2e/support/inference-adapter.test.ts @@ -21,6 +21,18 @@ import { } from "../fixtures/inference-adapter.ts"; import { startTestProgress } from "../fixtures/progress.ts"; +// Protected image qualification imports the fixture before CLI artifacts exist. +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + const readFileSync = new Proxy(actual.readFileSync, { + apply(target, thisArg, args) { + expect(String(args[0])).not.toMatch(/\/dist\/managed-inference\/catalog\.json$/u); + return Reflect.apply(target, thisArg, args); + }, + }); + return { ...actual, readFileSync, default: { ...actual, readFileSync } }; +}); + const adapters: E2EInferenceAdapter[] = []; const NOOP_PROGRESS = startTestProgress( "inference adapter support", diff --git a/test/e2e/support/openclaw-inference-switch-baseline.test.ts b/test/e2e/support/openclaw-inference-switch-baseline.test.ts index 5b89318ced2..7ad2cbc9ecb 100644 --- a/test/e2e/support/openclaw-inference-switch-baseline.test.ts +++ b/test/e2e/support/openclaw-inference-switch-baseline.test.ts @@ -22,11 +22,15 @@ afterEach(async () => { vi.unstubAllEnvs(); }); -async function loadNativeSwitchRun() { +async function loadNativeSwitchRun(nativeCustom = false) { vi.resetModules(); captured.test.mockClear(); - vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); - vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", "0"); + vi.stubEnv( + "NEMOCLAW_SWITCH_PROVIDER", + nativeCustom ? "compatible-anthropic-endpoint" : "nvidia-prod", + ); + vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", nativeCustom ? "1" : "0"); + vi.stubEnv("NEMOCLAW_SWITCH_NATIVE_CUSTOM", nativeCustom ? "1" : "0"); const exists = fs.existsSync; vi.spyOn(fs, "existsSync").mockImplementation((file) => String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), @@ -43,49 +47,64 @@ async function loadNativeSwitchRun() { return { progress, run }; } -it("keeps the public NVIDIA key out of the native switch baseline", async () => { - const { progress, run } = await loadNativeSwitchRun(); - const result = { exitCode: 0, stdout: "", stderr: "" }; - const stop = new Error("onboarding captured"); - const nemoclaw = vi.fn( - async (_args: string[], _options: { env: NodeJS.ProcessEnv; redactionValues: string[] }) => { - throw stop; - }, - ); - const required = vi.fn((name: string) => { - expect(name).toBe("NVIDIA_API_KEY"); - return "nvapi-public-fixture-key"; - }); - await expect( - run({ - artifacts: { target: { declare: vi.fn() } }, - cleanup: { - trackDisposable: (_name: string, dispose: () => unknown) => disposables.push(dispose), - trackGateway: vi.fn(), - trackSandbox: vi.fn(), +it.each([false, true])( + "selects the authenticated baseline with native custom=%s", + async (nativeCustom) => { + const { progress, run } = await loadNativeSwitchRun(nativeCustom); + const result = { exitCode: 0, stdout: "", stderr: "" }; + const stop = new Error("onboarding captured"); + const nemoclaw = vi.fn( + async (_args: string[], _options: { env: NodeJS.ProcessEnv; redactionValues: string[] }) => { + throw stop; }, - host: { nemoclaw, command: vi.fn(async () => result) }, - progress, - runtimeProvider: { requireAvailable: vi.fn() }, - sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, - secrets: { required }, - }), - ).rejects.toBe(stop); - expect(required).toHaveBeenCalledExactlyOnceWith("NVIDIA_API_KEY"); - const args = nemoclaw.mock.calls[0]![0]; - const customDockerfile = args[args.indexOf("--from") + 1]; - expect(fs.readFileSync(customDockerfile, "utf8")).toContain("ARG NEMOCLAW_MESSAGING_PLAN_B64="); - const options = nemoclaw.mock.calls[0]![1]; - const environment = options.env; - expect(environment.NEMOCLAW_PROVIDER).toBe("custom"); - expect(environment.NEMOCLAW_ENDPOINT_URL).toMatch(/^http:\/\/host\.openshell\.internal:\d+\/v1$/); - expect(environment.NEMOCLAW_MODEL).toBe("openclaw-switch-baseline-model"); - expect(environment.COMPATIBLE_API_KEY).toBe("openclaw-switch-baseline-credential"); - expect(environment.NVIDIA_INFERENCE_API_KEY).toBeUndefined(); - expect(environment.NVIDIA_API_KEY).toBeUndefined(); - expect(options.redactionValues).toContain("nvapi-public-fixture-key"); - expect(options.redactionValues).toContain("openclaw-switch-baseline-credential"); -}); + ); + const required = vi.fn((name: string) => { + expect(name).toBe("NVIDIA_API_KEY"); + return "nvapi-public-fixture-key"; + }); + await expect( + run({ + artifacts: { target: { declare: vi.fn() } }, + cleanup: { + trackDisposable: (_name: string, dispose: () => unknown) => disposables.push(dispose), + trackGateway: vi.fn(), + trackSandbox: vi.fn(), + }, + host: { + nemoclaw, + command: vi.fn(async (_cmd, _args, options) => + options?.artifactName === "native-baseline-endpoint-address" + ? { ...result, stdout: "route 10.20.30.40" } + : result, + ), + }, + progress, + runtimeProvider: { requireAvailable: vi.fn() }, + sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, + secrets: { required }, + }), + ).rejects.toBe(stop); + expect(required.mock.calls).toEqual(nativeCustom ? [] : [["NVIDIA_API_KEY"]]); + const args = nemoclaw.mock.calls[0]![0]; + const customDockerfile = args[args.indexOf("--from") + 1]; + expect(fs.readFileSync(customDockerfile, "utf8")).toContain("ARG NEMOCLAW_MESSAGING_PLAN_B64="); + const options = nemoclaw.mock.calls[0]![1]; + const environment = options.env; + expect(environment.NEMOCLAW_PROVIDER).toBe("custom"); + expect(new URL(environment.NEMOCLAW_ENDPOINT_URL!).hostname).toBe( + nativeCustom ? "10.20.30.40" : "host.openshell.internal", + ); + expect(environment.NEMOCLAW_TRUSTED_PRIVATE_INFERENCE_HOSTS).toBe( + nativeCustom ? "10.20.30.40" : undefined, + ); + expect(environment.NEMOCLAW_MODEL).toBe("openclaw-switch-baseline-model"); + expect(environment.COMPATIBLE_API_KEY).toBe("openclaw-switch-baseline-credential"); + expect(environment.NVIDIA_INFERENCE_API_KEY).toBeUndefined(); + expect(environment.NVIDIA_API_KEY).toBeUndefined(); + expect(options.redactionValues.includes("nvapi-public-fixture-key")).toBe(!nativeCustom); + expect(options.redactionValues).toContain("openclaw-switch-baseline-credential"); + }, +); it.each([ { diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index b634c2e604d..da681e3fdfb 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -349,7 +349,7 @@ async function probeOpenClawConfig( env: { HOME: home }, timeoutMs: 1000, nativeNvidia: expected.nativeNvidia, - nativeAnthropic: Boolean(expected.nativeCustomEndpoint), + nativeCustomApi: expected.nativeCustomEndpoint ? expected.inferenceApi : undefined, }); expect(result.exitCode).toBe(0); const config = JSON.parse(result.stdout); @@ -390,6 +390,7 @@ function sandboxForOpenClawConfig(config: object, handle = scopedNativeHandle) { ...process.env, NVIDIA_INFERENCE_API_KEY: handle, COMPATIBLE_ANTHROPIC_API_KEY: handle, + COMPATIBLE_API_KEY: handle, }, stdio: ["pipe", "pipe", "pipe"], }, @@ -429,32 +430,42 @@ it("checks the actual switched Anthropic model budget", async () => { }); }); -it.each([true, false])( - "checks the native custom Anthropic credential before redaction (valid=%s)", - async (valid) => { +it.each([ + ["anthropic-messages", true], + ["anthropic-messages", false], + ["openai-completions", true], + ["openai-completions", false], +] as const)( + "checks native custom %s credentials before redaction (valid=%s)", + async (api, valid) => { const model = "mock-anthropic-model"; const endpoint = "http://10.20.30.40:3000"; - const handle = "openshell:resolve:env:v7_COMPATIBLE_ANTHROPIC_API_KEY"; + const provider = + api === "anthropic-messages" ? "compatible-anthropic-endpoint" : "compatible-endpoint"; + const providerKey = api === "anthropic-messages" ? "anthropic" : "inference"; + const credentialEnv = + api === "anthropic-messages" ? "COMPATIBLE_ANTHROPIC_API_KEY" : "COMPATIBLE_API_KEY"; + const handle = `openshell:resolve:env:v7_${credentialEnv}`; const config: any = {}; patchOpenClawInferenceConfig( config, - "compatible-anthropic-endpoint", + provider, model, - "anthropic-messages", + api, undefined, - "compatible-anthropic-endpoint", + provider, { effort: null, explicit: false }, false, endpoint, true, ); - config.models.providers.anthropic.apiKey = valid ? handle : "synthetic-raw-credential"; + config.models.providers[providerKey].apiKey = valid ? handle : "synthetic-raw-credential"; const result = probeOpenClawConfig( sandboxForOpenClawConfig(config, handle) as never, "/tmp/switch-home", { model, - inferenceApi: "anthropic-messages", + inferenceApi: api, artifactName: "native-anthropic-config", nativeCustomEndpoint: endpoint, }, From 9029658852ce5600bbfcfae943be13e265a482cf Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:51:25 -0700 Subject: [PATCH 4/9] fix(inference): refresh native hosted handles across lifecycle --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 +- ci/pi-agent-qualification-v1-linux-arm64.json | 8 +- scripts/nemoclaw-start.sh | 30 +++-- .../config/live-export-source.test.ts | 2 + src/lib/agent/candidate-authority.ts | 4 +- .../compose-sandbox-config-body.test.ts | 75 ++++++++++-- src/lib/sandbox/openclaw-native-config.ts | 59 ++++++---- .../provider-placeholder-refresh.test.ts | 74 +++++++++++- test/e2e/README.md | 4 +- .../e2e/fixtures/hermes-config-export-live.ts | 5 +- .../support/hermes-config-export-live.test.ts | 111 ++++++++++-------- 11 files changed, 272 insertions(+), 108 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index e5e5825ccc4..c076a6dd816 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:ce0b27069d32239ad5b50c4ddea2d8aaa824b991c12f8e4a4e3883a66a4a7e7e", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:ce0b27069d32239ad5b50c4ddea2d8aaa824b991c12f8e4a4e3883a66a4a7e7e", + "digest": "sha256:d0e979b0ae1ee7abdfe666f5d8444f495a6c428980f7d57c8794f59fc08dc5cb", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:d0e979b0ae1ee7abdfe666f5d8444f495a6c428980f7d57c8794f59fc08dc5cb", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "05f5dafe655482077b42bd36c0230c88dcc6ec81", + "revision": "92e4cc4cda6cbe72f712df4e62dbb080d96ce1de", "release": "v0.1.0", - "cohort": "ghrun-38643585682-1" + "cohort": "ghrun-38707069678-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 28d8ce99dc3..c47744f5c19 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:8d918cc7008a9c3320c8f864d2fceff9e1ef1867abed476bbd8656820bca04e2", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:8d918cc7008a9c3320c8f864d2fceff9e1ef1867abed476bbd8656820bca04e2", + "digest": "sha256:c8ffe907c4ad08a8b0c127989ed84275cf60adf62690756d35a19ec7a5f4cf89", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:c8ffe907c4ad08a8b0c127989ed84275cf60adf62690756d35a19ec7a5f4cf89", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "05f5dafe655482077b42bd36c0230c88dcc6ec81", + "revision": "92e4cc4cda6cbe72f712df4e62dbb080d96ce1de", "release": "v0.1.0", - "cohort": "ghrun-38643585682-1" + "cohort": "ghrun-38707069678-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index adff049d2db..5b4c5fe934c 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -899,25 +899,31 @@ config = json.loads(parsed.stdout) refreshed = set() native_refreshed = False -# A native NVIDIA handle persisted by the host-side config batch belongs to -# the provider revision that issued it. After a supervisor restart, only the -# current revision is available, so replace that exact config field before -# OpenClaw starts. Never copy a raw value or rewrite config for other providers. +# Persisted native handles belong to the provider revision that issued them. +# Refresh only inference credentials before OpenClaw starts. Raw values and +# unrelated fields must not cross this boundary. models = config.get("models") if isinstance(config, dict) else None providers = models.get("providers") if isinstance(models, dict) else None -native = providers.get("inference") if isinstance(providers, dict) else None -if isinstance(native, dict) and native.get("baseUrl") == "https://integrate.api.nvidia.com/v1": - key = "NVIDIA_INFERENCE_API_KEY" - scoped = re.compile(rf"^{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{key}$") +for provider_key in ("inference", "openai", "anthropic"): + native = providers.get(provider_key) if isinstance(providers, dict) else None + if not isinstance(native, dict): + continue saved = native.get("apiKey") + scoped = re.fullmatch( + rf"{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_([A-Z][A-Z0-9_]*)", + saved if isinstance(saved, str) else "", + ) + if not scoped: + continue + key = scoped.group(1) + if key == "NVIDIA_INFERENCE_API_KEY" and native.get("baseUrl") != "https://integrate.api.nvidia.com/v1": + continue state = runtime_state(key) current = state.get("value", "") if ( - isinstance(saved, str) - and scoped.fullmatch(saved) - and state.get("kind") == "placeholder" + state.get("kind") == "placeholder" and isinstance(current, str) - and scoped.fullmatch(current) + and re.fullmatch(rf"{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{re.escape(key)}", current) and saved != current ): native["apiKey"] = current diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index 27b4ca87929..9911398ecd7 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -237,6 +237,7 @@ function mockNativeHostedSource(definition: HostedProviderDefinition) { host: string; port: number; allowed_ips?: string[]; + tls?: string; rules: { allow: { method: string; path: string } }[]; }; const base = managedBraveProfile(); @@ -259,6 +260,7 @@ function mockNativeHostedSource(definition: HostedProviderDefinition) { host: endpoint.host, port: endpoint.port, allowedIps: endpoint.allowed_ips ?? [], + tls: endpoint.tls ?? "", access: "", rules: endpoint.rules.map((rule) => ({ allow: { diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 72576f71615..dcbaa03c2e9 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "e15dbc530c6486136ebc450c02b2ea70245def3e37aad41bd4202482a9f49191", - "31618180d9ddc8a161ad3f7493df085ca3a705bad886189d9f6d7ea89a1f2bd4", + "50176f3cc04b1e36e45a78619c9985ab493418eb6ba2ee8c467776a710677011", + "769c1f598bc8f78763944e3f6d0f8c8a07e2b19e3262cf7211c8d6169104da57", ]), }); diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index fa843358c3f..0f6f6bd922a 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -42,7 +42,7 @@ const { ) => string; hermesConfigAllowsPrivateUrls: (config: Record) => boolean; runOpenClawNativeConfigBatchUntilHandleReady: ( - nativeNvidiaUpdate: boolean, + nativeProviderUpdate: boolean, run: () => { status: number; stderr: string; error?: Error; signal?: string }, wait?: (ms: number) => void, warn?: (message: string) => void, @@ -238,12 +238,66 @@ describe("composeSandboxConfigBody", () => { }); it.each([ - { value: undefined, expectedStatus: 75 }, - { value: "nvapi-do-not-write", expectedStatus: 1 }, - { value: "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", expectedStatus: 1 }, + ["inference", "COMPATIBLE_API_KEY", "http://10.1.1.225:8123/v1", "openai-completions"], + ["anthropic", "COMPATIBLE_ANTHROPIC_API_KEY", "https://fixture.example", "anthropic-messages"], + ["openai", "OPENAI_API_KEY", "https://api.openai.com/v1", "openai-completions"], + ["anthropic", "ANTHROPIC_API_KEY", "https://api.anthropic.com", "anthropic-messages"], + ["inference", "OPENAI_API_KEY", "https://hermes.example/v1", "openai-completions"], ])( - "refuses invalid native NVIDIA handle $value before config mutation", - ({ value, expectedStatus }) => { + "materializes %s native credentials from %s before the atomic config write", + (provider, key, baseUrl, api) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-config-")); + try { + fs.writeFileSync(path.join(directory, "openclaw"), '#!/bin/sh\ncat "$4"\n', { + mode: 0o700, + }); + const canonical = `openshell:resolve:env:${key}`; + const handle = `openshell:resolve:env:s${"a".repeat(64)}_${key}`; + const updates = [ + { dotpath: "agents.defaults.model.primary", value: `${provider}/model-a` }, + { + dotpath: `models.providers.${provider}`, + value: { baseUrl, api, apiKey: canonical, models: [{ id: "model-a" }] }, + }, + { dotpath: "channels.telegram.botToken", value: canonical }, + ]; + const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", updates); + const command = invocation.args.slice(invocation.args.indexOf("--") + 1); + const result = spawnSync(command[0]!, command.slice(1), { + input: invocation.input, + encoding: "utf8", + timeout: 5_000, + env: { ...process.env, PATH: `${directory}:${process.env.PATH ?? ""}`, [key]: handle }, + }); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([ + { path: updates[0]!.dotpath, value: updates[0]!.value }, + { + path: updates[1]!.dotpath, + value: { baseUrl, api, apiKey: handle, models: [{ id: "model-a" }] }, + }, + { path: updates[2]!.dotpath, value: canonical }, + ]); + expect(invocation.input).not.toContain(handle); + expect(invocation.args.join(" ")).not.toContain(handle); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it.each( + [ + { value: undefined, expectedStatus: 75 }, + { value: "nvapi-do-not-write", expectedStatus: 1 }, + { value: "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", expectedStatus: 1 }, + { value: "openshell:resolve:env:v43_OTHER_API_KEY", expectedStatus: 1 }, + ].flatMap((scenario) => + ["NVIDIA_INFERENCE_API_KEY", "COMPATIBLE_API_KEY"].map((key) => ({ ...scenario, key })), + ), + )( + "refuses invalid native $key handle $value before config mutation", + ({ value, expectedStatus, key }) => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-config-")); try { fs.writeFileSync(path.join(directory, "openclaw"), '#!/bin/sh\ncat "$4"\n', { @@ -252,7 +306,10 @@ describe("composeSandboxConfigBody", () => { const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", [ { dotpath: "models.providers.inference", - value: { baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, apiKey: NVIDIA_INFERENCE_PLACEHOLDER }, + value: { + baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + apiKey: `openshell:resolve:env:${key}`, + }, }, ]); const command = invocation.args.slice(invocation.args.indexOf("--") + 1); @@ -263,7 +320,7 @@ describe("composeSandboxConfigBody", () => { env: { ...process.env, PATH: `${directory}:${process.env.PATH ?? ""}`, - NVIDIA_INFERENCE_API_KEY: value, + [key]: value, }, }); expect(failed.status).toBe(expectedStatus); @@ -286,7 +343,7 @@ describe("composeSandboxConfigBody", () => { expect(run).toHaveBeenCalledTimes(2); expect(wait).toHaveBeenCalledExactlyOnceWith(2_000); expect(warn).toHaveBeenCalledExactlyOnceWith( - "Native NVIDIA provider handle pending; config attempt 1/10", + "Native provider handle pending; config attempt 1/10", ); const exhaustedRun = vi.fn().mockReturnValue(pending); diff --git a/src/lib/sandbox/openclaw-native-config.ts b/src/lib/sandbox/openclaw-native-config.ts index a72da9a2cd1..c335b71dbdb 100644 --- a/src/lib/sandbox/openclaw-native-config.ts +++ b/src/lib/sandbox/openclaw-native-config.ts @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// Host-side OpenClaw native config commands and scoped NVIDIA handle materialization. +// Host-side OpenClaw native config commands and scoped provider handle materialization. import type { OpenShellRuntimeSelection } from "../adapters/openshell/client"; import type { ConfigValue } from "../security/credential-filter"; @@ -83,31 +83,40 @@ export interface OpenClawConfigUpdate { // gateway restart replaces that process image with its old environment. Pin // the supervisor-issued handle in the native config batch before restarting; // the actual credential remains outside the sandbox and endpoint-bound. -const materializeNativeNvidiaHandle = [ +const materializeNativeProviderHandle = [ "import json, os, re, sys", - 'handle = os.environ.get("NVIDIA_INFERENCE_API_KEY", "")', - "if not handle:", - ' sys.stderr.write("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\\n")', - " raise SystemExit(75)", - 'if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY", handle):', - ' raise SystemExit("Native NVIDIA provider handle is unavailable or invalid")', 'with open(sys.argv[1], "r+", encoding="utf-8") as stream:', " updates = json.load(stream)", " if not isinstance(updates, list):", ' raise SystemExit("Invalid OpenClaw config batch")', " matched = 0", " for update in updates:", - ' if not isinstance(update, dict) or update.get("path") != "models.providers.inference":', + ' if not isinstance(update, dict) or update.get("path") not in (', + ' "models.providers.inference", "models.providers.openai", "models.providers.anthropic"', + " ):", " continue", ' provider = update.get("value")', - ' if not isinstance(provider, dict) or provider.get("apiKey") != sys.argv[3]:', + " if not isinstance(provider, dict):", " continue", - ' if provider.get("baseUrl") != sys.argv[2]:', + ' api_key = provider.get("apiKey", "")', + " if api_key == sys.argv[3]:", + ' api_key = "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY"', + ' key = re.fullmatch(r"openshell:resolve:env:([A-Z][A-Z0-9_]*)", str(api_key))', + " if not key:", + " continue", + " key = key.group(1)", + ' if key == "NVIDIA_INFERENCE_API_KEY" and provider.get("baseUrl") != sys.argv[2]:', ' raise SystemExit("Native NVIDIA provider endpoint does not match")', + ' handle = os.environ.get(key, "")', + " if not handle:", + ' sys.stderr.write("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\\n")', + " raise SystemExit(75)", + ' if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_" + re.escape(key), handle):', + ' raise SystemExit("Native provider handle is unavailable or invalid")', ' provider["apiKey"] = handle', " matched += 1", " if matched != 1:", - ' raise SystemExit("Expected one native NVIDIA provider config update")', + ' raise SystemExit("Expected one native provider config update")', " stream.seek(0)", ' json.dump(updates, stream, separators=(",", ":"))', " stream.truncate()", @@ -117,17 +126,23 @@ export function buildOpenClawNativeConfigBatchInvocation( updates: readonly OpenClawConfigUpdate[], gateway?: string | OpenShellRuntimeSelection, ) { - const nativeNvidiaUpdate = updates.some( + const nativeProviderUpdate = updates.some( ({ dotpath, value }) => - dotpath === "models.providers.inference" && + [ + "models.providers.inference", + "models.providers.openai", + "models.providers.anthropic", + ].includes(dotpath) && isConfigObject(value) && - value.apiKey === NVIDIA_INFERENCE_PLACEHOLDER, + typeof value.apiKey === "string" && + (value.apiKey === NVIDIA_INFERENCE_PLACEHOLDER || + /^openshell:resolve:env:[A-Z][A-Z0-9_]*$/.test(value.apiKey)), ); - const materializeCommand = nativeNvidiaUpdate - ? `python3 -c ${shellQuote(materializeNativeNvidiaHandle)} "$file" ${shellQuote(NVIDIA_HOSTED_NATIVE_ENDPOINT)} ${shellQuote(NVIDIA_INFERENCE_PLACEHOLDER)} || exit $?; ` + const materializeCommand = nativeProviderUpdate + ? `python3 -c ${shellQuote(materializeNativeProviderHandle)} "$file" ${shellQuote(NVIDIA_HOSTED_NATIVE_ENDPOINT)} ${shellQuote(NVIDIA_INFERENCE_PLACEHOLDER)} || exit $?; ` : ""; return { - nativeNvidiaUpdate, + nativeProviderUpdate, ...(!gateway || typeof gateway === "string" ? {} : { @@ -185,7 +200,7 @@ export function executeOpenClawNativeConfigBatch( gateway?: string | OpenShellRuntimeSelection, ): void { const invocation = buildOpenClawNativeConfigBatchInvocation(sandboxName, updates, gateway); - runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeNvidiaUpdate, () => + runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeProviderUpdate, () => runOpenshellCommand(binary, invocation.args, { env: invocation.env, replaceEnv: invocation.replaceEnv, @@ -204,7 +219,7 @@ type NativeConfigBatchResult = Pick< >; export function runOpenClawNativeConfigBatchUntilHandleReady( - nativeNvidiaUpdate: boolean, + nativeProviderUpdate: boolean, run: () => NativeConfigBatchResult, wait: (ms: number) => void = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms), @@ -213,7 +228,7 @@ export function runOpenClawNativeConfigBatchUntilHandleReady( // OpenShell 0.0.116 attach can confirm desired state before a fresh process // receives the new environment. This retry is owned by native inference and // applies only when the materializer exited before OpenClaw changed config. - const maxAttempts = nativeNvidiaUpdate ? 10 : 1; + const maxAttempts = nativeProviderUpdate ? 10 : 1; for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { const result = run(); if (!result.error && !result.signal && result.status === 0) return; @@ -223,7 +238,7 @@ export function runOpenClawNativeConfigBatchUntilHandleReady( result.status === 75 && String(result.stderr ?? "").includes("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING"); if (handlePending && attempt < maxAttempts) { - warn(`Native NVIDIA provider handle pending; config attempt ${attempt}/${maxAttempts}`); + warn(`Native provider handle pending; config attempt ${attempt}/${maxAttempts}`); wait(2_000); continue; } diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts index c99aa6eadeb..9dad76aba9c 100644 --- a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts @@ -27,7 +27,7 @@ function execFileResult(file, args, options) { ); } -describe.concurrent("native NVIDIA handle refresh", () => { +describe.concurrent("native provider handle refresh", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); async function runRefresh( config: unknown, @@ -115,6 +115,78 @@ describe.concurrent("native NVIDIA handle refresh", () => { }, ); + it.each( + [false, true].flatMap((rootMode) => + [ + { provider: "inference", key: "COMPATIBLE_API_KEY", endpoint: "http://10.1.1.225:8123/v1" }, + { + provider: "anthropic", + key: "COMPATIBLE_ANTHROPIC_API_KEY", + endpoint: "https://fixture.example", + }, + { provider: "openai", key: "OPENAI_API_KEY", endpoint: "https://api.openai.com/v1" }, + ].map((route) => ({ ...route, rootMode })), + ), + )( + "refreshes only the persisted $provider credential on restart (root=$rootMode)", + async ({ provider, key, endpoint, rootMode }) => { + const saved = `openshell:resolve:env:v42_${key}`; + const current = `openshell:resolve:env:s${"a".repeat(64)}_${key}`; + const run = await runRefresh( + { + models: { + providers: { + [provider]: { baseUrl: endpoint, apiKey: saved }, + unrelated: { baseUrl: endpoint, apiKey: saved }, + }, + }, + channels: { telegram: { botToken: saved } }, + }, + { [key]: current }, + rootMode, + ); + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers[provider].apiKey).toBe(current); + expect(run.config.models.providers.unrelated.apiKey).toBe(saved); + expect(run.config.channels.telegram.botToken).toBe(saved); + }, + ); + + it.each( + [false, true].flatMap((rootMode) => + [ + "", + "raw-do-not-copy", + "openshell:resolve:env:v43_OTHER_API_KEY", + "openshell:resolve:env:COMPATIBLE_API_KEY", + ].map((runtime) => ({ runtime, rootMode })), + ), + )( + "keeps the saved custom credential when the runtime handle is invalid (root=$rootMode, runtime=$runtime)", + async ({ runtime, rootMode }) => { + const saved = "openshell:resolve:env:v42_COMPATIBLE_API_KEY"; + const run = await runRefresh( + { + models: { + providers: { + inference: { + baseUrl: "https://fixture.example/v1", + apiKey: saved, + }, + }, + }, + }, + { COMPATIBLE_API_KEY: runtime }, + rootMode, + ); + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers.inference.apiKey).toBe(saved); + expect(JSON.stringify(run.config)).not.toContain("raw-do-not-copy"); + expect(run.result.stderr).not.toContain("raw-do-not-copy"); + expect(run.handoffEnv).not.toContain("raw-do-not-copy"); + }, + ); + it.each([ { reason: "raw credential in root environment", diff --git a/test/e2e/README.md b/test/e2e/README.md index 1cd670fe2c1..10381c36f19 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -729,8 +729,8 @@ Custom Dockerfile onboarding uses the existing startup and pairing settlement ch restarting the native gateway for the initial inference route, as external-image onboarding does. The target requires onboarding to create the selected model without those limits, then preserves that native configuration through restart and rebuild. The OpenClaw native NVIDIA and mock Anthropic switch variants start with an authenticated local OpenAI-compatible fixture. -The Anthropic variant starts on the legacy host-alias route, then switches to a native custom endpoint. -It uses the runner's private address through the existing explicit private-host trust setting. +The Anthropic variant starts on a native OpenAI-compatible route, then switches to a native Anthropic endpoint. +Both endpoints use the runner's private address through the existing explicit private-host trust setting. Its mock rejects a missing or incorrect credential, and the existing sandbox request and OpenClaw model run must both succeed. The config probe validates the scoped Anthropic credential reference inside the sandbox before redaction. The native NVIDIA destination uses the public endpoint and its public credential only after switching. diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index 0e3dcb2e3f7..237cf0dceec 100644 --- a/test/e2e/fixtures/hermes-config-export-live.ts +++ b/test/e2e/fixtures/hermes-config-export-live.ts @@ -356,8 +356,11 @@ export async function verifyHermesConfigExportLive( (diagnostic) => { if (!expectsMessagingRefusal) return diagnostic === expectedDiagnostic; const lines = diagnostic.split("\n"); + const categories = /^Config export failed \(([^)]+)\)\.$/ + .exec(lines[0] ?? "")?.[1] + ?.split(", "); return ( - lines[0] === "Config export failed (unsupported)." && + categories?.includes("unsupported") === true && expectedRefusals.every((refusal) => lines.includes(refusal)) ); }, diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 9941407dd28..d566df80f1b 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -452,62 +452,71 @@ describe("Hermes config export live evidence", () => { }, ); - it("accepts messaging refusal alongside other unsupported export findings", async () => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - gatewayName: "nemoclaw", - messaging: { schemaVersion: 1, plan: { channels: [] } }, - workload: { kind: "managed-image", reference: IMAGE_REF }, + it.each(["unsupported", "unsupported, policy-not-representable"])( + "accepts messaging refusal with %s export findings", + async (categories) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + gatewayName: "nemoclaw", + messaging: { schemaVersion: 1, plan: { channels: [] } }, + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, }, - }, - }); - mocks.command.mockResolvedValue({ - exitCode: 2, - stdout: "", - stderr: [ - "Config export failed (unsupported).", - "V1 export does not support messaging.", - "The sandbox provider attachments do not match its supported configuration.", - "The managed startup profile is not the canonical profile supported by v1 export.", - ].join("\n"), - }); + }); + mocks.command.mockResolvedValue({ + exitCode: 2, + stdout: "", + stderr: [ + `Config export failed (${categories}).`, + "V1 export does not support messaging.", + "The sandbox provider attachments do not match its supported configuration.", + "The managed startup profile is not the canonical profile supported by v1 export.", + ].join("\n"), + }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); - expect(mocks.writeJson).toHaveBeenCalledWith( - "hermes-config-export-live-evidence.json", - expect.objectContaining({ - refusalCategory: "unsupported", - refusalDiagnosticMatches: true, - }), - ); - }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); + expect(mocks.writeJson).toHaveBeenCalledWith( + "hermes-config-export-live-evidence.json", + expect.objectContaining({ + refusalCategory: "unsupported", + refusalDiagnosticMatches: true, + }), + ); + }, + ); - it("rejects other unsupported findings without the messaging refusal", async () => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - gatewayName: "nemoclaw", - messaging: { schemaVersion: 1, plan: { channels: [] } }, - workload: { kind: "managed-image", reference: IMAGE_REF }, + it.each([ + { + categories: "unsupported", + refusal: "The sandbox provider attachments do not match its supported configuration.", + }, + { categories: "policy-not-representable", refusal: "V1 export does not support messaging." }, + ])( + "rejects messaging export evidence missing the expected category or refusal ($categories)", + async ({ categories, refusal }) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + gatewayName: "nemoclaw", + messaging: { schemaVersion: 1, plan: { channels: [] } }, + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, }, - }, - }); - mocks.command.mockResolvedValue({ - exitCode: 2, - stdout: "", - stderr: [ - "Config export failed (unsupported).", - "The sandbox provider attachments do not match its supported configuration.", - ].join("\n"), - }); + }); + mocks.command.mockResolvedValue({ + exitCode: 2, + stdout: "", + stderr: [`Config export failed (${categories}).`, refusal].join("\n"), + }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: false }); - }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: false }); + }, + ); it.each(["http", "https"])("accepts the exact Podman %s export refusal", async (scheme) => { mocks.load.mockReturnValue({ From 8e004b2ecee0c34d8fafc9a41868fcadf693fb24 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:40:38 -0700 Subject: [PATCH 5/9] chore(pi): qualify integrated native hosted candidate Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index c076a6dd816..c41fc21d171 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:d0e979b0ae1ee7abdfe666f5d8444f495a6c428980f7d57c8794f59fc08dc5cb", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:d0e979b0ae1ee7abdfe666f5d8444f495a6c428980f7d57c8794f59fc08dc5cb", + "digest": "sha256:8e66c063a36d158b9d443eb9d38f0ee810824fc30cf934ee9b16204a0d332189", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:8e66c063a36d158b9d443eb9d38f0ee810824fc30cf934ee9b16204a0d332189", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "92e4cc4cda6cbe72f712df4e62dbb080d96ce1de", + "revision": "8fb87cba9a7864465c9deb9423318766af7f1239", "release": "v0.1.0", - "cohort": "ghrun-38707069678-1" + "cohort": "ghrun-38770328038-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index c47744f5c19..12e38bec086 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:c8ffe907c4ad08a8b0c127989ed84275cf60adf62690756d35a19ec7a5f4cf89", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:c8ffe907c4ad08a8b0c127989ed84275cf60adf62690756d35a19ec7a5f4cf89", + "digest": "sha256:508e6d06a88ca7998f365b17b9ee6f4590a7c9c7b418cca6e209fe37d140f5d9", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:508e6d06a88ca7998f365b17b9ee6f4590a7c9c7b418cca6e209fe37d140f5d9", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "92e4cc4cda6cbe72f712df4e62dbb080d96ce1de", + "revision": "8fb87cba9a7864465c9deb9423318766af7f1239", "release": "v0.1.0", - "cohort": "ghrun-38707069678-1" + "cohort": "ghrun-38770328038-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index dcbaa03c2e9..fb284c567f3 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "50176f3cc04b1e36e45a78619c9985ab493418eb6ba2ee8c467776a710677011", - "769c1f598bc8f78763944e3f6d0f8c8a07e2b19e3262cf7211c8d6169104da57", + "8a77983abbf75ddbaba5abbf1288a6d2778babf76d4f8f3acd2afaf19c855955", + "5b14a2c5bec37ec048063667a08d5f56a2e52f1d3e3969d1986e0c107786ef51", ]), }); From 19f521416a5dbb62ac9fa169e5f03eb817c72297 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:46:17 -0700 Subject: [PATCH 6/9] fix(inference): align custom native API selection --- src/lib/inference/config.ts | 23 +++++++++++-------- .../inference/native-provider/custom.test.ts | 20 ++++++++++++++++ src/lib/inference/native-provider/fixed.ts | 2 +- src/lib/inference/native-provider/hosted.ts | 13 +++++++++++ src/lib/onboard/setup-inference.ts | 18 ++++++++------- src/lib/onboard/setup-native-hosted.test.ts | 18 +++++++++++++-- .../compose-sandbox-config-body.test.ts | 7 ++++++ 7 files changed, 81 insertions(+), 20 deletions(-) diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 8fa62df2521..74271f06d8f 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -14,7 +14,7 @@ import { LLAMA_CPP_PROVIDER_NAME, } from "./llama-cpp/contract"; import { hostedNativeProvider, usesNativeHermesEndpoint } from "./native-provider/hosted"; -import { isCustomHostedProvider } from "./native-provider/hosted"; +import { isCustomHostedProvider, resolveCustomNativeApi } from "./native-provider/hosted"; import { isBedrockRuntimeEndpoint, BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, @@ -332,8 +332,9 @@ export function getSandboxInferenceConfig( nativeProvider?: boolean, nativeEndpointUrl?: string | null, ): SandboxInferenceConfig { - let providerKey: string = - nativeOpenClawProviderKey(provider, preferredInferenceApi) ?? MANAGED_PROVIDER_ID; + const nativeCustom = nativeProvider === true && isCustomHostedProvider(provider); + const selectedApi = resolveCustomNativeApi(provider, preferredInferenceApi, nativeCustom); + let providerKey: string = nativeOpenClawProviderKey(provider, selectedApi) ?? MANAGED_PROVIDER_ID; let primaryModelRef: string; const useNativeProvider = nativeProvider ?? @@ -341,18 +342,17 @@ export function getSandboxInferenceConfig( const hostedNative = useNativeProvider ? hostedNativeProvider(provider, nativeEndpointUrl) : undefined; - let customEndpoint = - nativeProvider === true && isCustomHostedProvider(provider) ? nativeEndpointUrl : undefined; - if (nativeProvider === true && isCustomHostedProvider(provider) && !customEndpoint) + let customEndpoint = nativeCustom ? nativeEndpointUrl : undefined; + if (nativeCustom && !customEndpoint) throw new Error("Native custom inference is missing its recorded endpoint"); if (customEndpoint && provider === "compatible-anthropic-endpoint") customEndpoint = isBedrockRuntimeEndpoint(customEndpoint) ? BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL - : preferredInferenceApi && preferredInferenceApi !== "anthropic-messages" + : selectedApi && selectedApi !== "anthropic-messages" ? getCompatibleAnthropicOpenAiSurfaceBaseUrl(customEndpoint) : customEndpoint; let inferenceBaseUrl = customEndpoint ?? hostedNative?.endpoint ?? INFERENCE_ROUTE_URL; - let inferenceApi = preferredInferenceApi || "openai-completions"; + let inferenceApi = selectedApi || "openai-completions"; // Providers without a /v1/responses endpoint must never be configured with the // Responses API. On a provider switch the runtime API resolves to null and the // caller falls back to the persisted (shared "inference") provider api, which @@ -370,7 +370,11 @@ export function getSandboxInferenceConfig( break; case "anthropic-prod": case "compatible-anthropic-endpoint": - if (provider === "compatible-anthropic-endpoint" && inferenceApi === "openai-completions") { + if ( + provider === "compatible-anthropic-endpoint" && + (inferenceApi === "openai-completions" || + (nativeCustom && inferenceApi === "openai-responses")) + ) { providerKey = MANAGED_PROVIDER_ID; primaryModelRef = `${MANAGED_PROVIDER_ID}/${model}`; inferenceCompat = { @@ -378,6 +382,7 @@ export function getSandboxInferenceConfig( }; break; } + providerKey = "anthropic"; primaryModelRef = `anthropic/${model}`; inferenceBaseUrl = customEndpoint ?? hostedNative?.endpoint ?? "https://inference.local"; inferenceApi = "anthropic-messages"; diff --git a/src/lib/inference/native-provider/custom.test.ts b/src/lib/inference/native-provider/custom.test.ts index 0a656f4f6a6..4517d7157e4 100644 --- a/src/lib/inference/native-provider/custom.test.ts +++ b/src/lib/inference/native-provider/custom.test.ts @@ -116,6 +116,7 @@ describe("custom native endpoint ownership", () => { ["compatible-endpoint", "openai-responses", "/team/v1/responses"], ["compatible-anthropic-endpoint", "anthropic-messages", "/team/v1/messages"], ["compatible-anthropic-endpoint", "openai-completions", "/team/v1/chat/completions"], + ["compatible-anthropic-endpoint", "openai-responses", "/team/v1/responses"], ])( "binds %s %s to the same agent, profile and health destination", (provider, api, requestPath) => { @@ -145,12 +146,31 @@ describe("custom native endpoint ownership", () => { const config = getSandboxInferenceConfig("selected-model", provider, api, true, endpointUrl); expect(config.inferenceBaseUrl).toBe(definition.endpointUrl); expect(config.inferenceApi).toBe(api); + expect(config.primaryModelRef).toBe( + `${api === "anthropic-messages" ? "anthropic" : "inference"}/selected-model`, + ); expect(nativeHostedAgentConfig(provider, config.inferenceBaseUrl)?.apiKey).toBe( `openshell:resolve:env:${definition.credentialEnv}`, ); }, ); + it.each([ + ["compatible-endpoint", "openai-completions", "https://custom.example/team/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example/team"], + ])( + "uses the native %s default API when selection is omitted (#13195)", + (provider, api, endpointUrl) => { + const definition = customNativeProvider({ ...binding, provider, api, endpointUrl }); + const config = getSandboxInferenceConfig("selected-model", provider, null, true, endpointUrl); + expect(config).toMatchObject({ + inferenceApi: definition.api, + inferenceBaseUrl: definition.endpointUrl, + primaryModelRef: `${api === "anthropic-messages" ? "anthropic" : "inference"}/selected-model`, + }); + }, + ); + it("keeps endpoint, API, credential source and pin authorities distinct", () => { const names = [ binding, diff --git a/src/lib/inference/native-provider/fixed.ts b/src/lib/inference/native-provider/fixed.ts index 8faf1f0b5ac..9c67e7b2bbd 100644 --- a/src/lib/inference/native-provider/fixed.ts +++ b/src/lib/inference/native-provider/fixed.ts @@ -34,7 +34,7 @@ export function nativeOpenClawProviderKey( ): "openai" | "anthropic" | "inference" | undefined { if (provider === "compatible-endpoint") return "inference"; if (provider === "compatible-anthropic-endpoint") - return inferenceApi && inferenceApi !== "openai-completions" ? "anthropic" : "inference"; + return inferenceApi === "anthropic-messages" ? "anthropic" : "inference"; const definition = fixedNativeProvider(provider); if (!definition) return undefined; if (definition.logicalProvider === "openai-api") return "openai"; diff --git a/src/lib/inference/native-provider/hosted.ts b/src/lib/inference/native-provider/hosted.ts index 39fed574019..f796637f6a1 100644 --- a/src/lib/inference/native-provider/hosted.ts +++ b/src/lib/inference/native-provider/hosted.ts @@ -9,6 +9,19 @@ export function isCustomHostedProvider(provider: string | null | undefined): boo return provider === "compatible-endpoint" || provider === "compatible-anthropic-endpoint"; } +/** Resolve the native binding and agent configuration from the same API selection. */ +export function resolveCustomNativeApi( + provider: string | null | undefined, + preferredApi: string | null | undefined, + nativeProvider: boolean, +): string | null { + if (!nativeProvider || !isCustomHostedProvider(provider)) return preferredApi ?? null; + return ( + preferredApi || + (provider === "compatible-anthropic-endpoint" ? "anthropic-messages" : "openai-completions") + ); +} + export function customNativeCredentialEnv(provider: string): string { if (provider === "compatible-endpoint") return "COMPATIBLE_API_KEY"; if (provider === "compatible-anthropic-endpoint") return "COMPATIBLE_ANTHROPIC_API_KEY"; diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index f971213823a..b852cc164c6 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -5,6 +5,7 @@ import { hostedNativeProvider, usesNativeHermesEndpoint, customNativeCredentialEnv, + resolveCustomNativeApi, } from "../inference/native-provider/hosted"; import { requireHostedProviderAttachment } from "../inference/native-provider/hosted-attachment"; import { @@ -907,6 +908,11 @@ export function createSetupInference( sandboxName, recordedSandbox, ); + const selectedInferenceApi = resolveCustomNativeApi( + provider, + options.preferredInferenceApi, + nativeCustomSelection, + ); const nativeHostedSelection = nativeCustomSelection || (hostedNativeProvider(provider) && @@ -930,7 +936,7 @@ export function createSetupInference( model, endpointUrl, credentialEnv, - preferredInferenceApi: options.preferredInferenceApi ?? null, + preferredInferenceApi: selectedInferenceApi, }, }); if (!compatibility.ok) { @@ -1051,7 +1057,7 @@ export function createSetupInference( endpointUrl: nativeHostedEndpoint ?? hostLocalRoute?.applicationBaseUrl ?? endpointUrl, endpointSource: hostLocalRoute ? "inference-set" : endpointSource, credentialEnv: nativeHostedCredentialEnv ?? credentialEnv, - preferredInferenceApi: options.preferredInferenceApi ?? null, + preferredInferenceApi: selectedInferenceApi, gatewayName, reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, @@ -1216,11 +1222,7 @@ export function createSetupInference( gatewayName, provider, endpointUrl: endpointUrl!, - api: - options.preferredInferenceApi || - (provider === "compatible-anthropic-endpoint" - ? "anthropic-messages" - : "openai-completions"), + api: selectedInferenceApi!, credentialEnv: selectedCredentialEnv, credentialValue, adapter: deps.providerAdapter, @@ -1391,7 +1393,7 @@ export function createSetupInference( allowLegacyRecordedNoAuthEndpoint: options.allowLegacyRecordedNoAuthEndpoint === true, skipHostInferenceSmoke: options.skipHostInferenceSmoke === true, - preferredInferenceApi: options.preferredInferenceApi ?? null, + preferredInferenceApi: selectedInferenceApi, pinnedAddresses: endpointPinnedAddresses, trustedPrivateCapability: endpointTrustedPrivateCapability, capabilityCache: options.inferenceCapabilityCache, diff --git a/src/lib/onboard/setup-native-hosted.test.ts b/src/lib/onboard/setup-native-hosted.test.ts index 74c7066eec3..7c258cee7dc 100644 --- a/src/lib/onboard/setup-native-hosted.test.ts +++ b/src/lib/onboard/setup-native-hosted.test.ts @@ -22,6 +22,7 @@ const providers: HostedProviderDefinition[] = [ ["compatible-endpoint", "openai-responses", "https://custom.example/v1"], ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example"], ["compatible-anthropic-endpoint", "openai-completions", "https://custom.example"], + ["compatible-anthropic-endpoint", "openai-responses", "https://custom.example"], ].map(([provider, api, endpointUrl]) => customNativeProvider({ provider, @@ -35,7 +36,16 @@ const providers: HostedProviderDefinition[] = [ describe.each(providers)("native $label onboarding", (provider) => { const endpointModes = provider.custom - ? ["explicit", "previous-provider"] + ? [ + "explicit", + "previous-provider", + ...(provider.api === + (provider.logicalProvider === "compatible-anthropic-endpoint" + ? "anthropic-messages" + : "openai-completions") + ? ["default-api"] + : []), + ] : ["explicit", "omitted"]; it.each(endpointModes)("uses %s native endpoint (#12589)", async (endpointMode) => { const receipt = { @@ -165,7 +175,10 @@ describe.each(providers)("native $label onboarding", (provider) => { provider.custom?.credentialEnv ?? provider.credentialEnv, null, [], - { revalidateSandboxIdentity: () => undefined, preferredInferenceApi: provider.api }, + { + revalidateSandboxIdentity: () => undefined, + preferredInferenceApi: endpointMode === "default-api" ? null : provider.api, + }, ), ).resolves.toMatchObject({ ok: true }); expect(createProvider).toHaveBeenCalledExactlyOnceWith( @@ -193,6 +206,7 @@ describe.each(providers)("native $label onboarding", (provider) => { expect.objectContaining({ nativeHostedProviderAttachment: receipt, provider: provider.logicalProvider, + preferredInferenceApi: provider.api, }), ); expect(verifyOnboardInferenceSmoke.mock.calls).toEqual( diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index 67e5aaa81d7..c3c7ab3af10 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -250,6 +250,13 @@ describe("composeSandboxConfigBody", () => { "https://fixture.example/openai/v1", "openai-completions", ], + [ + "compatible-anthropic-endpoint", + "inference", + "COMPATIBLE_ANTHROPIC_API_KEY", + "https://fixture.example/openai/v1", + "openai-responses", + ], [ "compatible-anthropic-endpoint", "anthropic", From b8065df5b1de956b533c278b77b8ba23a3efba5e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:21:53 -0700 Subject: [PATCH 7/9] fix(pi): refresh qualification for native routing repair Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index 54c61dba0bc..516ed0cc966 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:cfdeae93e0f8ae802a6e0fc9e8e68f2bcaf1fb6f45ec16791a995229a75391bb", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:cfdeae93e0f8ae802a6e0fc9e8e68f2bcaf1fb6f45ec16791a995229a75391bb", + "digest": "sha256:428530c256fd5b76014fd2561aed153ef759f4fb23d4c7d0f42304e0b37e989d", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:428530c256fd5b76014fd2561aed153ef759f4fb23d4c7d0f42304e0b37e989d", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "b1302d38f8b3b084a884fa0efcf17ff9251f697d", + "revision": "19f521416a5dbb62ac9fa169e5f03eb817c72297", "release": "v0.1.0", - "cohort": "ghrun-38769032420-1" + "cohort": "ghrun-38826692761-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index df73cd3d28d..bca82d559e5 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:1cb6c6ee7622ba870f14fef62e353c1e422a18597cc0701d942e0fbbde800fa1", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:1cb6c6ee7622ba870f14fef62e353c1e422a18597cc0701d942e0fbbde800fa1", + "digest": "sha256:cb7292a4aabf56a85d75d47015fffc583d437c0ee26941df79359a12734fac27", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:cb7292a4aabf56a85d75d47015fffc583d437c0ee26941df79359a12734fac27", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "b1302d38f8b3b084a884fa0efcf17ff9251f697d", + "revision": "19f521416a5dbb62ac9fa169e5f03eb817c72297", "release": "v0.1.0", - "cohort": "ghrun-38769032420-1" + "cohort": "ghrun-38826692761-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 6f561ad77a0..8c47abb297e 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "001bc67c3e46cb7916709dd159f230abdf6f52dd74dc0573b4eb7d089e6c6984", - "239043cc0620eb5110d45e830a8b6a9da11bb4ee875023468d44e9a4f2ab6739", + "900cc0ed35229b30cb7dfe7852dfc8a03433d0b742eb977192f82673f871a6fe", + "af27661bb60b1483d45468d5bc82ae7b2907a23006dee0cbfa660fd77b9094e4", ]), }); From a472ac7dae7076110960bc4d40b52dcc447c2a95 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:24:36 -0700 Subject: [PATCH 8/9] fix(e2e): select native Anthropic route coverage Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ...inference-switch-workflow-boundary.test.ts | 46 +++++++++++++++++++ tools/e2e/target-catalogue.mts | 3 ++ 2 files changed, 49 insertions(+) diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index 5adf6bae444..5aca04a077b 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -5,11 +5,57 @@ import { describe, expect, it } from "vitest"; import { catalogueTarget, + catalogueTargetsForChangedFiles, E2E_TARGET_CATALOGUE, validateE2eTargetCatalogue, } from "../../../tools/e2e/target-catalogue.mts"; +import { buildE2eWorkflowPlan } from "../../../tools/e2e/workflow-plan.mts"; describe("inference-switch catalogue boundary", () => { + it.each([ + "src/lib/inference/native-provider/contract.ts", + "src/lib/inference/native-provider/custom-setup.ts", + "src/lib/inference/native-provider/custom.ts", + "src/lib/inference/native-provider/hosted.ts", + "src/lib/onboard/setup-inference.ts", + "src/lib/actions/inference-set/native.ts", + "src/lib/actions/inference-set.ts", + "test/e2e/live/openclaw-inference-switch-helpers.ts", + "test/e2e/live/openclaw-inference-switch.test.ts", + ])("selects native Anthropic switch coverage when %s changes (#13195)", (changedFile) => { + const targetId = "openclaw-compatible-anthropic-inference-switch"; + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + targetId, + ); + const plan = buildE2eWorkflowPlan( + {}, + { changedFiles: [changedFile], gatewayRuntimes: ["docker", "podman"] }, + ); + expect( + plan.catalogueMatrices.standard + .filter((row) => row.id === targetId) + .map((row) => row.execution_id) + .sort(), + ).toEqual([ + "openclaw-compatible-anthropic-inference-switch-anthropic-docker", + "openclaw-compatible-anthropic-inference-switch-anthropic-podman", + ]); + }); + + it("omits native Anthropic switch coverage for unrelated changes (#13195)", () => { + const changedFiles = ["src/lib/cli/public-display-defaults.ts"]; + const targetId = "openclaw-compatible-anthropic-inference-switch"; + expect(catalogueTargetsForChangedFiles(changedFiles).map((target) => target.id)).not.toContain( + targetId, + ); + const plan = buildE2eWorkflowPlan({}, { changedFiles, gatewayRuntimes: ["docker", "podman"] }); + expect( + Object.values(plan.catalogueMatrices) + .flat() + .map((row) => row.id), + ).not.toContain(targetId); + }); + it.each([{ scenario: "OpenClaw" }, { scenario: "Hermes" }])( "keeps both agents on their reviewed provider-switch contracts [$scenario]", ({ scenario }) => { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index d3f906286ce..387e48e8b19 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1294,6 +1294,9 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ shard: "anthropic", owningPaths: [ "src/lib/actions/inference-set.ts", + "src/lib/actions/inference-set/native.ts", + "src/lib/inference/native-provider/", + "src/lib/onboard/setup-inference.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", ], environment: { From 71a7901ddac132848a698afc74ec1fbd5bfbdb5c Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 15 Oct 2026 23:34:06 -0700 Subject: [PATCH 9/9] fix(config): verify native export endpoints against their receipt Signed-off-by: Prekshi Vyas --- .../config/live-export-source.test.ts | 44 ++++++++++++++++++- src/lib/domain/config/verify-export-source.ts | 11 ++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index 9911398ecd7..e9d10fcc8d8 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -13,6 +13,7 @@ import { type HostedProviderDefinition, } from "../../inference/native-provider/hosted"; import { nativeProviderLifecycle } from "../../inference/native-provider"; +import { BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL } from "../../inference/bedrock-runtime"; import { customNativeProvider, boundCustomNativeProfile, @@ -21,7 +22,7 @@ import { parseCheckedInProviderProfileContract } from "../openshell/provider-pro import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; import { getSandboxEntryInference } from "../../state/registry-entry-view"; import { createHash } from "node:crypto"; -import { describe, expect, it, vi } from "vitest"; +import { assert, describe, expect, it, vi } from "vitest"; import YAML from "yaml"; import { managedBraveProfile, @@ -827,6 +828,8 @@ describe("live export snapshot reader", () => { ["compatible-endpoint", "openai-completions", "https://custom.example/team/v1"], ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1"], ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example/team"], + ["compatible-anthropic-endpoint", "openai-completions", "https://custom.example/team"], + ["compatible-anthropic-endpoint", "openai-responses", "https://custom.example/team"], ].map(([provider, api, endpointUrl]) => customNativeProvider({ provider, @@ -836,6 +839,14 @@ describe("live export snapshot reader", () => { allowedIps: ["8.8.8.8"], }), ), + customNativeProvider({ + provider: "compatible-anthropic-endpoint", + api: "openai-completions", + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + credentialEnv: "TEAM_KEY", + allowedIps: [], + adapterEndpointUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, + }), ])( "exports native $label without reading shared routing or secret values", async (definition: HostedProviderDefinition) => { @@ -855,6 +866,37 @@ describe("live export snapshot reader", () => { }, ); + it.each(["selected", "runtime", "both"] as const)( + "rejects custom native export when the %s endpoint changes", + async (changed) => { + const definition = customNativeProvider({ + provider: "compatible-anthropic-endpoint", + api: "openai-completions", + endpointUrl: "https://custom.example/team", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + mockNativeHostedSource(definition); + const observed = await createLiveExportSnapshotReader().read("alpha"); + assert(observed.kind === "observed" && observed.inference.endpointEvidence); + const { endpointEvidence: evidence, ...inference } = observed.inference; + const result = await observeStableExportSource("alpha", { + read: async () => ({ + ...observed, + inference: { + ...inference, + endpoint: changed === "runtime" ? inference.endpoint : "https://drift.example/v1", + endpointEvidence: { + ...evidence, + endpoint: changed === "selected" ? evidence.endpoint : "https://drift.example/v1", + }, + }, + }), + }); + expect(result).toMatchObject({ ok: false }); + }, + ); + it("rejects native hosted export when the sandbox attaches an unrelated provider", async () => { mockNativeHostedSource(HOSTED_NATIVE_PROVIDERS[0]); raw.getSandbox.mockResolvedValue({ diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index f9317c75081..05e7ff996fd 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -1386,6 +1386,15 @@ function expectedEndpointProviderName(snapshot: QualifiedExportSnapshot): string return nativeExportReceipt(snapshot.registry)?.providerName ?? snapshot.inference.provider; } +function endpointEvidenceMatchesExportEndpoint(snapshot: QualifiedExportSnapshot): boolean { + const { inference } = snapshot; + // Managed profiles can transform the selected endpoint. Both endpoints must + // still match their independently verified receipt fields. + if (inference.endpointEvidence?.source.kind === "managed-profile") + return endpointEvidenceMatchesRoute(snapshot); + return inference.endpointEvidence?.endpoint === inference.endpoint; +} + function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFinding[] { const { inference, sandbox, gateway } = snapshot; const evidence = inference.endpointEvidence; @@ -1412,7 +1421,7 @@ function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFind "The live inference endpoint evidence is invalid or unsafe.", ), ); - if (evidence.endpoint !== inference.endpoint) + if (!endpointEvidenceMatchesExportEndpoint(snapshot)) findings.push( finding( "spec.inferenceProviders[].endpoint",