From 07d345dec238b6c2631d24c02915db51aeebb05b Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 16:25:14 +0700 Subject: [PATCH 01/12] fix(inference): resolve native NVIDIA agent credentials Fixes #12892 Signed-off-by: San Dang --- Dockerfile | 9 +++-- agents/hermes/Dockerfile | 4 +-- agents/hermes/managed_policy.py | 27 +++++++++++--- scripts/generate-openclaw-config.mts | 3 +- scripts/nemoclaw-start.sh | 7 ++-- ...rence-set-openclaw-gateway-restart.test.ts | 2 +- .../inference-set-openclaw-run.test.ts | 2 +- .../inference-set-patch-hermes.test.ts | 20 ++++++++++- .../inference-set-patch-openclaw.test.ts | 29 +++++++++++++-- src/lib/actions/inference-set.ts | 11 +++++- src/lib/hermes-managed-route.ts | 13 ++++--- src/lib/inference-credential.ts | 30 ++++++++++++++++ src/lib/inference/config.ts | 1 + .../hermes-portable-build-context-files.ts | 1 + .../hermes-portable-build-context.ts | 1 + src/lib/sandbox/build-context.ts | 1 + .../hermes/hermes-managed-policy.test.ts | 34 ++++++++++++++++++ .../runtime/auth-profile-boundary.test.ts | 28 +++++++++++++++ .../generation/generate-hermes-config.test.ts | 15 ++++++++ ...rate-openclaw-native-nvidia-config.test.ts | 36 +++++++++++++++++++ 20 files changed, 247 insertions(+), 27 deletions(-) create mode 100644 src/lib/inference-credential.ts create mode 100644 test/generation/generate-openclaw-native-nvidia-config.test.ts diff --git a/Dockerfile b/Dockerfile index 9d07be75ff2..35e5f333941 100644 --- a/Dockerfile +++ b/Dockerfile @@ -699,7 +699,7 @@ COPY scripts/codex-acp-wrapper.sh /usr/local/bin/nemoclaw-codex-acp COPY scripts/generate-openclaw-config.mts /scripts/ COPY scripts/validate-openclaw-tool-search.mts /scripts/ COPY --from=managed-startup-runtime-builder /out/managed-startup-image-runtime.cjs /usr/local/lib/nemoclaw/managed-startup-image-runtime.cjs -COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ +COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts src/lib/inference-credential.ts /src/lib/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ COPY --from=mcp-tool-discovery-runtime /opt/mcp-tool-discovery-runtime/dist/ /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/ @@ -1539,16 +1539,15 @@ RUN node /usr/local/lib/nemoclaw/patch-openclaw-tool-catalog.mts \ RUN node /usr/local/lib/nemoclaw/patch-openclaw-shared-state-permissions.mts \ /usr/local/lib/node_modules/openclaw/dist -# Set up blueprint for local resolution. -# Blueprints are immutable at runtime; DAC protection (root ownership) is applied -# later since /sandbox/.nemoclaw is Landlock read_write for plugin state (#804). +# Blueprint files stay immutable; apply root ownership after copying because +# /sandbox/.nemoclaw permits plugin writes (#804). RUN mkdir -p /sandbox/.nemoclaw/blueprints/0.1.0 \ && cp -r /opt/nemoclaw-blueprint/* /sandbox/.nemoclaw/blueprints/0.1.0/ # Copy configuration inputs before the cached non-messaging plugin install. COPY scripts/generate-openclaw-config.mts /scripts/ COPY scripts/validate-openclaw-tool-search.mts /scripts/ -COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ +COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts src/lib/inference-credential.ts /src/lib/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ RUN chmod 755 /scripts/generate-openclaw-config.mts \ diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index ea70cc1dc1f..14f0898b62e 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -62,7 +62,7 @@ COPY agents/hermes/patch-profile-policy-defaults.py /opt/nemoclaw-hermes-config/ COPY agents/hermes/managed_policy.py /opt/nemoclaw-hermes-config/managed_policy.py COPY agents/hermes/host/managed-tool-gateway-matrix.json /opt/nemoclaw-hermes-config/managed-tool-gateway-matrix.json COPY src/lib/hermes-managed-route.ts /src/lib/hermes-managed-route.ts -COPY src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ +COPY src/lib/tool-disclosure.ts src/lib/providerless-inference.ts src/lib/inference-credential.ts /src/lib/ COPY src/lib/messaging/ /src/lib/messaging/ COPY scripts/lib/openclaw-npm-remediation.mts /scripts/lib/openclaw-npm-remediation.mts @@ -377,7 +377,7 @@ RUN chmod -R a+rX /opt/nemoclaw-hermes-plugin/ # read-only. RUN find /opt/nemoclaw-hermes-config -type d -exec chmod 755 {} + \ && find /opt/nemoclaw-hermes-config -type f -exec chmod 444 {} + \ - && chmod 444 /src/lib/hermes-managed-route.ts /src/lib/tool-disclosure.ts /src/lib/providerless-inference.ts \ + && chmod 444 /src/lib/hermes-managed-route.ts /src/lib/tool-disclosure.ts /src/lib/providerless-inference.ts /src/lib/inference-credential.ts \ && chmod 444 /scripts/lib/reviewed-npm-archive.mts /scripts/lib/bundled-npm-package.mts \ /scripts/lib/openclaw-npm-remediation.mts /scripts/lib/reviewed-npm-audit.mts \ /scripts/lib/reviewed-npm-identity.mts \ diff --git a/agents/hermes/managed_policy.py b/agents/hermes/managed_policy.py index 37605b752dd..92bd5c5eb79 100644 --- a/agents/hermes/managed_policy.py +++ b/agents/hermes/managed_policy.py @@ -9,10 +9,12 @@ import os import stat from pathlib import Path +from urllib.parse import urlsplit MANAGED_POLICY_PATH = Path("/usr/local/share/nemoclaw/hermes-managed-policy.json") MANAGED_POLICY_SCHEMA_VERSION = 3 HERMES_PROXY_REWRITE_SENTINEL = "sk-OPENSHELL-PROXY-REWRITE" +NVIDIA_INFERENCE_PLACEHOLDER = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY" class ManagedPolicyError(Exception): @@ -92,10 +94,27 @@ def load_managed_policy(path: Path = MANAGED_POLICY_PATH) -> dict: has_routing = any( key in config for key in ("model", "providers", "custom_providers", "_nemoclaw_upstream") ) - if has_routing and policy_value(config, "model.api_key") != HERMES_PROXY_REWRITE_SENTINEL: - raise ManagedPolicyError( - "managed policy model.api_key must use the OpenShell proxy rewrite sentinel" - ) + if has_routing: + base_url = policy_value(config, "model.base_url") + if not isinstance(base_url, str): + raise ManagedPolicyError("managed policy model.base_url is invalid") + try: + url = urlsplit(base_url) + native_nvidia = ( + url.scheme == "https" + and url.hostname == "integrate.api.nvidia.com" + and url.port in (None, 443) + and url.path in ("/v1", "/v1/") + and not (url.username or url.password or url.query or url.fragment) + ) + except (TypeError, ValueError): + raise ManagedPolicyError("managed policy model.base_url is invalid") from None + expected_key = NVIDIA_INFERENCE_PLACEHOLDER if native_nvidia else HERMES_PROXY_REWRITE_SENTINEL + if policy_value(config, "model.api_key") != expected_key: + raise ManagedPolicyError( + "managed policy model.api_key must use the OpenShell proxy rewrite sentinel " + "or the native NVIDIA credential placeholder for its route" + ) for managed_path in managed_paths: policy_value(config, managed_path) return document diff --git a/scripts/generate-openclaw-config.mts b/scripts/generate-openclaw-config.mts index a915d7258f3..81748bef221 100755 --- a/scripts/generate-openclaw-config.mts +++ b/scripts/generate-openclaw-config.mts @@ -28,6 +28,7 @@ // NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION. import { hasProviderlessInferenceEnvironment } from "../src/lib/providerless-inference.ts"; +import { managedInferenceApiKey } from "../src/lib/inference-credential.ts"; import { chmodSync, @@ -973,7 +974,7 @@ export function buildConfig(env: Env = process.env): JsonObject { const providers = { [providerKey]: { baseUrl: inferenceBaseUrl, - apiKey: "unused", + apiKey: managedInferenceApiKey(inferenceBaseUrl, "unused"), api: inferenceApi, timeoutSeconds: agentTimeout, models: providerModels, diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 68d828acd05..a3e31563fb2 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -57,12 +57,13 @@ unset NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGC NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGV \ unset -f nemoclaw_normalize_entrypoint_env_wrapper # managed-entrypoint-env-wrapper end -# OpenShell owns inference.local authentication. Clear its credential aliases +# OpenShell owns managed inference authentication. Clear its credential aliases # after entrypoint overrides are normalized, before setup can launch children. # Direct inference routes retain their credentials. is_managed_inference_route() { # Match URL scheme and host case without spawning a credential-bearing child. - [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]\.[Ll][Oo][Cc][Aa][Ll](:443)?(/.*)?$ ]] + [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]\.[Ll][Oo][Cc][Aa][Ll](:443)?(/.*)?$ ]] \ + || [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Tt][Ee][Gg][Rr][Aa][Tt][Ee]\.[Aa][Pp][Ii]\.[Nn][Vv][Ii][Dd][Ii][Aa]\.[Cc][Oo][Mm](:443)?/v1/?$ ]] } clear_managed_inference_credentials() { @@ -1659,7 +1660,7 @@ prepare_gateway_token_for_current_command() { } # Reconcile this function's legacy generated auth profile for the selected provider. -# OpenShell authenticates managed inference.local routes on the host, so remove +# OpenShell authenticates managed inference routes on the host, so remove # that generated credential reference. Preserve other user-managed profiles. # Direct routes retain their existing profile-writing behavior. write_auth_profile() { diff --git a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts index 27f7077ad45..bfbf3940ba6 100644 --- a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts +++ b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts @@ -201,7 +201,7 @@ describe("runInferenceSet OpenClaw gateway restart", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", api: "openai-completions", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod", diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 75d1db2a966..006328c42b7 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -621,7 +621,7 @@ describe("runInferenceSet OpenClaw routing", () => { expect(providerUpdate?.value).toEqual({ api: "openai-completions", baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod" }, models: alreadyExists ? [otherModel, selectedModel] : [selectedModel, otherModel], }); diff --git a/src/lib/actions/inference-set-patch-hermes.test.ts b/src/lib/actions/inference-set-patch-hermes.test.ts index 61b47018703..dd0f703245b 100644 --- a/src/lib/actions/inference-set-patch-hermes.test.ts +++ b/src/lib/actions/inference-set-patch-hermes.test.ts @@ -7,6 +7,24 @@ import type { ConfigObject } from "../security/credential-filter"; import { patchHermesInferenceConfig } from "./inference-set"; describe("patchHermesInferenceConfig", () => { + it("replaces every credential when switching to native NVIDIA inference and back", () => { + const config: ConfigObject = {}; + patchHermesInferenceConfig(config, "vllm-local", "local-model"); + patchHermesInferenceConfig(config, "nvidia-prod", "nvidia/test-model"); + const placeholder = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"; + expect(config).toMatchObject({ + model: { api_key: placeholder }, + providers: { "nvidia-prod": { api_key: placeholder } }, + custom_providers: [{ api_key: placeholder }], + }); + patchHermesInferenceConfig(config, "vllm-local", "local-model"); + expect(config).toMatchObject({ + model: { base_url: "https://inference.local/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL }, + providers: { "vllm-local": { api_key: HERMES_PROXY_REWRITE_SENTINEL } }, + custom_providers: [{ api_key: HERMES_PROXY_REWRITE_SENTINEL }], + }); + }); + it("updates the complete Hermes route for the selected provider", () => { const config: ConfigObject = { model: { @@ -147,7 +165,7 @@ describe("patchHermesInferenceConfig", () => { default: "nvidia/nemotron-3-super-120b-a12b", provider: "custom", base_url: "https://integrate.api.nvidia.com/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", }); }); diff --git a/src/lib/actions/inference-set-patch-openclaw.test.ts b/src/lib/actions/inference-set-patch-openclaw.test.ts index 780684464e8..b1e45809489 100644 --- a/src/lib/actions/inference-set-patch-openclaw.test.ts +++ b/src/lib/actions/inference-set-patch-openclaw.test.ts @@ -13,6 +13,29 @@ function providerModels(config: ConfigObject, providerKey: string): ConfigObject } describe("patchOpenClawInferenceConfig", () => { + it("replaces the vLLM credential when switching to native NVIDIA inference", () => { + const config: ConfigObject = { + models: { providers: { inference: { apiKey: "unused", models: [] } } }, + }; + patchOpenClawInferenceConfig(config, "nvidia-prod", "nvidia/test-model"); + expect(config).toMatchObject({ + models: { + providers: { + inference: { + baseUrl: "https://integrate.api.nvidia.com/v1", + apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + }, + }, + }, + }); + patchOpenClawInferenceConfig(config, "vllm-local", "local-model"); + expect(config).toMatchObject({ + models: { + providers: { inference: { baseUrl: "https://inference.local/v1", apiKey: "unused" } }, + }, + }); + }); + it.each([undefined, null, 16384])( "updates only the selected model's context when the resolved window is %s", (contextWindow) => { @@ -82,7 +105,7 @@ describe("patchOpenClawInferenceConfig", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", api: "openai-completions", models: [ { @@ -152,7 +175,7 @@ describe("patchOpenClawInferenceConfig", () => { expect((config.models as ConfigObject).providers).toEqual({ inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", api: "openai-completions", models: [ { @@ -208,7 +231,7 @@ describe("patchOpenClawInferenceConfig", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", api: "openai-completions", models: [ { diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 9d50e1fb6bc..9d8bf430ad3 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -17,7 +17,9 @@ import { ensureNativeNvidiaProvider, ensureNativeNvidiaProviderAttached, isNativeNvidiaProvider, + managedInferenceApiKey, NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_INFERENCE_PLACEHOLDER, normalizeNativeNvidiaProviderAttachment, persistNativeNvidiaProviderAuthority, resolveGatewayNativeNvidiaProviderAuthority, @@ -690,7 +692,14 @@ function buildProviderConfig( const providerConfig: ConfigObject = { ...existing, baseUrl: route.inferenceBaseUrl, - apiKey: typeof existing.apiKey === "string" && existing.apiKey ? existing.apiKey : "unused", + apiKey: managedInferenceApiKey( + route.inferenceBaseUrl, + typeof existing.apiKey === "string" && + existing.apiKey && + existing.apiKey !== NVIDIA_INFERENCE_PLACEHOLDER + ? existing.apiKey + : "unused", + ), api: route.inferenceApi, models: selectedIndex < 0 diff --git a/src/lib/hermes-managed-route.ts b/src/lib/hermes-managed-route.ts index 30db5326d5c..fbcdede458d 100644 --- a/src/lib/hermes-managed-route.ts +++ b/src/lib/hermes-managed-route.ts @@ -1,13 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { managedInferenceApiKey, NVIDIA_INFERENCE_PLACEHOLDER } from "./inference-credential.ts"; + // Hermes requires an sk-prefixed value before it sends a request. OpenShell // removes this non-secret sentinel and injects the route credential at egress. export const HERMES_PROXY_REWRITE_SENTINEL = "sk-OPENSHELL-PROXY-REWRITE"; type HermesManagedProvider = { name: string; - api_key: typeof HERMES_PROXY_REWRITE_SENTINEL; + api_key: typeof HERMES_PROXY_REWRITE_SENTINEL | typeof NVIDIA_INFERENCE_PLACEHOLDER; discover_models: true; api?: string; base_url?: string; @@ -26,7 +28,7 @@ export type HermesManagedRouting = { default: string; provider: "custom"; base_url: string; - api_key: typeof HERMES_PROXY_REWRITE_SENTINEL; + api_key: typeof HERMES_PROXY_REWRITE_SENTINEL | typeof NVIDIA_INFERENCE_PLACEHOLDER; api_mode?: string; context_length?: number; }; @@ -79,6 +81,7 @@ export function applyHermesManagedRoute( const providerName = route.upstreamProvider || "nemoclaw-inference"; const providerKey = hermesProviderKey(providerName); const apiMode = hermesApiMode(route.inferenceApi); + const apiKey = managedInferenceApiKey(route.baseUrl, HERMES_PROXY_REWRITE_SENTINEL); const previousUpstream = isObjectRecord(config._nemoclaw_upstream) ? config._nemoclaw_upstream : {}; @@ -89,7 +92,7 @@ export function applyHermesManagedRoute( default: route.model, provider: "custom", base_url: route.baseUrl, - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: apiKey, }; if (apiMode) modelConfig.api_mode = apiMode; if (route.contextWindow !== null && route.contextWindow !== undefined) { @@ -100,7 +103,7 @@ export function applyHermesManagedRoute( const providerConfig: Record = { name: providerName, api: route.baseUrl, - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: apiKey, default_model: route.model, discover_models: true, }; @@ -109,7 +112,7 @@ export function applyHermesManagedRoute( const customProvider: Record = { name: providerName, base_url: route.baseUrl, - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: apiKey, discover_models: true, }; if (apiMode) customProvider.api_mode = apiMode; diff --git a/src/lib/inference-credential.ts b/src/lib/inference-credential.ts new file mode 100644 index 00000000000..baf19383f43 --- /dev/null +++ b/src/lib/inference-credential.ts @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// The native provider rewrites references to its host-held credential. The +// inference.local route instead replaces the client's authorization header. +export const NVIDIA_INFERENCE_PLACEHOLDER = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"; + +export function managedInferenceApiKey( + baseUrl: string, + fallback: T, +): T | typeof NVIDIA_INFERENCE_PLACEHOLDER { + try { + const url = new URL(baseUrl); + if ( + url.protocol === "https:" && + url.hostname === "integrate.api.nvidia.com" && + url.port === "" && + (url.pathname === "/v1" || url.pathname === "/v1/") && + !url.username && + !url.password && + !url.search && + !url.hash + ) { + return NVIDIA_INFERENCE_PLACEHOLDER; + } + } catch { + // URL validation belongs to the route owner. + } + return fallback; +} diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 7415409dde8..b34a207a0e9 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -22,6 +22,7 @@ import { VLLM_LOCAL_CREDENTIAL_ENV } from "./serving/vllm-credential-contract"; export { isSafeModelId }; export { OLLAMA_LOCAL_CREDENTIAL_ENV }; +export { managedInferenceApiKey, NVIDIA_INFERENCE_PLACEHOLDER } from "../inference-credential"; export { detachNativeNvidiaProvider, ensureNativeNvidiaProvider, diff --git a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts index 4e4d0edbc04..8a4db90fa04 100644 --- a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts +++ b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts @@ -144,6 +144,7 @@ export const HERMES_PORTABLE_BUILD_CONTEXT_FILES = [ mode: "100644", }, { path: "src/lib/hermes-managed-route.ts", mode: "100644" }, + { path: "src/lib/inference-credential.ts", mode: "100644" }, { path: "src/lib/messaging/AGENTS.md", mode: "100644" }, { path: "src/lib/messaging/applier/agent-config-remove.test.ts", mode: "100644" }, { path: "src/lib/messaging/applier/agent-config.ts", mode: "100644" }, diff --git a/src/lib/onboard/experimental/hermes-portable-build-context.ts b/src/lib/onboard/experimental/hermes-portable-build-context.ts index a8ad23bdb68..d1df3849ce3 100644 --- a/src/lib/onboard/experimental/hermes-portable-build-context.ts +++ b/src/lib/onboard/experimental/hermes-portable-build-context.ts @@ -87,6 +87,7 @@ const LOCAL_COPY_SOURCES = [ "ci/reviewed-npm-audit.json", "src/lib/actions/sandbox/openshell-child-visible-credentials.v0.0.116.json", "src/lib/hermes-managed-route.ts", + "src/lib/inference-credential.ts", "src/lib/messaging/", "src/lib/messaging/channels/googlechat/runtime/hermes-adapter.py", "src/lib/tool-disclosure.ts", diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 33bb4727e3d..9a87edd73e6 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -129,6 +129,7 @@ function stageMcpToolDiscoveryRuntime(rootDir: string, buildCtx: string): void { function stageManagedStartupRuntimeSources(rootDir: string, buildCtx: string): void { for (const relativePath of [ "extra-agents-validation.ts", + "inference-credential.ts", path.join("core", "json-types.ts"), path.join("core", "ports.ts"), path.join("security", "credential-hash.ts"), diff --git a/test/agents/hermes/hermes-managed-policy.test.ts b/test/agents/hermes/hermes-managed-policy.test.ts index cd8bcda4549..d1d31a68c32 100644 --- a/test/agents/hermes/hermes-managed-policy.test.ts +++ b/test/agents/hermes/hermes-managed-policy.test.ts @@ -77,6 +77,40 @@ function loadWithPython(document: unknown) { } describe("Hermes managed policy", () => { + it.each(["https://integrate.api.nvidia.com/v1", "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/"])( + "accepts the native NVIDIA inference placeholder at %s", + (baseUrl) => { + const policy = buildHermesManagedPolicy( + { ...SETTINGS, baseUrl, upstreamProvider: "nvidia-prod" }, + {}, + ); + expect(policy.config.model?.api_key).toBe( + "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + ); + const result = loadWithPython(policy); + expect(result.status, result.stderr).toBe(0); + }, + ); + + it.each([ + ["https://integrate.api.nvidia.com/v1", "sk-OPENSHELL-PROXY-REWRITE"], + ["https://inference.local/v1", "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"], + [ + "https://integrate.api.nvidia.com.example/v1", + "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + ], + ["https://integrate.api.nvidia.com/v1", "sk-raw-policy-credential"], + ])("rejects credentials outside the managed route contract at %s", (baseUrl, apiKey) => { + const policy = buildHermesManagedPolicy({ ...SETTINGS, baseUrl }, {}); + const malformedPolicy = { + ...policy, + config: { ...policy.config, model: { ...policy.config.model, api_key: apiKey } }, + }; + const result = loadWithPython(malformedPolicy); + expect(result.status).toBe(1); + expect(result.stderr).not.toContain(apiKey); + }); + it("accepts absent inference while retaining managed restrictions", () => { const policy = buildHermesManagedPolicy({ ...SETTINGS, model: null }, {}); const result = loadWithPython(policy); diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 7a21b10a89f..47cccf4a89c 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -171,6 +171,34 @@ describe("OpenClaw auth-profile boundary", () => { expect(fs.existsSync(fixture.authPath)).toBe(false); }); + it.each(["fresh", "legacy"] as const)( + "leaves no legacy auth profile for native NVIDIA inference in %s state", + (state) => { + const fixture = runBashAuthFixture( + { ...managedEnv, NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1" }, + state === "legacy" + ? seedAuthProfile({ "inference:manual": legacyManagedProfile }) + : undefined, + ); + expect(fixture.status, fixture.stderr).toBe(0); + expect(fs.existsSync(fixture.authPath)).toBe(false); + expect(fixture.stdout.trim()).toBe("unset\nunset"); + }, + ); + + it("preserves user profiles when removing the native NVIDIA generated profile", () => { + const custom = { ...legacyProfile("custom"), label: "user-managed" }; + const fixture = runBashAuthFixture( + { ...managedEnv, NEMOCLAW_INFERENCE_BASE_URL: "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/" }, + seedAuthProfile({ "inference:manual": legacyManagedProfile, "custom:manual": custom }), + ); + expect(fixture.status, fixture.stderr).toBe(0); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + "custom:manual": custom, + }); + expect(fixture.stdout.trim()).toBe("unset\nunset"); + }); + it.each([ ["fresh", "https://inference.local/v1"], ["legacy", "https://inference.local/v1"], diff --git a/test/generation/generate-hermes-config.test.ts b/test/generation/generate-hermes-config.test.ts index aa00de9c610..3daa2b3e373 100644 --- a/test/generation/generate-hermes-config.test.ts +++ b/test/generation/generate-hermes-config.test.ts @@ -61,6 +61,17 @@ const HERMES_STRUCTURED_TOOL_SEARCH = { max_search_limit: 20, }; +it("uses a resolvable credential in every native NVIDIA inference configuration", () => { + const { config } = runConfigScript({ + NEMOCLAW_UPSTREAM_PROVIDER: "nvidia-prod", + NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1", + }); + const placeholder = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"; + expect(config.model.api_key).toBe(placeholder); + expect(config.providers["nvidia-prod"].api_key).toBe(placeholder); + expect(config.custom_providers[0].api_key).toBe(placeholder); +}); + const REMOTE_PLATFORM_TOOLSETS = [ "web", "browser", @@ -249,6 +260,10 @@ function copyConfigGeneratorFixture(fixtureRoot: string): string { path.join(import.meta.dirname, "../..", "src", "lib", "hermes-managed-route.ts"), path.join(fixtureRoot, "src", "lib", "hermes-managed-route.ts"), ); + fs.copyFileSync( + path.join(import.meta.dirname, "../..", "src", "lib", "inference-credential.ts"), + path.join(fixtureRoot, "src", "lib", "inference-credential.ts"), + ); fs.copyFileSync( path.join(import.meta.dirname, "../..", "src", "lib", "providerless-inference.ts"), path.join(fixtureRoot, "src", "lib", "providerless-inference.ts"), diff --git a/test/generation/generate-openclaw-native-nvidia-config.test.ts b/test/generation/generate-openclaw-native-nvidia-config.test.ts new file mode 100644 index 00000000000..7aa51b17999 --- /dev/null +++ b/test/generation/generate-openclaw-native-nvidia-config.test.ts @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { expect, it } from "vitest"; + +import { buildConfig } from "../../scripts/generate-openclaw-config.mts"; +import { baseOpenClawGenerationEnv } from "../helpers/openclaw-env-fixture"; + +it.each(["https://integrate.api.nvidia.com/v1", "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/"])( + "uses a resolvable credential for native NVIDIA inference at %s", + (baseUrl) => { + const config = buildConfig({ + ...baseOpenClawGenerationEnv(), + NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", + NEMOCLAW_INFERENCE_BASE_URL: baseUrl, + }); + expect(config.models.providers.inference.apiKey).toBe( + "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + ); + }, +); + +it.each([ + "https://inference.local/v1", + "https://integrate.api.nvidia.com.example/v1", + "https://other.example/v1", + "http://integrate.api.nvidia.com/v1", + "https://integrate.api.nvidia.com:8443/v1", +])("retains the route sentinel outside native NVIDIA inference at %s", (baseUrl) => { + const config = buildConfig({ + ...baseOpenClawGenerationEnv(), + NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", + NEMOCLAW_INFERENCE_BASE_URL: baseUrl, + }); + expect(config.models.providers.inference.apiKey).toBe("unused"); +}); From 0e4e28437dd5cd3ae0c7b010f46ce43f34ece5e0 Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 16:26:58 +0700 Subject: [PATCH 02/12] test(inference): cover staged NVIDIA credential helper Signed-off-by: San Dang --- test/runtime/sandbox/sandbox-build-context.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/runtime/sandbox/sandbox-build-context.test.ts b/test/runtime/sandbox/sandbox-build-context.test.ts index cca13b95e9e..dec16f51321 100644 --- a/test/runtime/sandbox/sandbox-build-context.test.ts +++ b/test/runtime/sandbox/sandbox-build-context.test.ts @@ -265,6 +265,7 @@ describe("sandbox build context staging", () => { writeFixture(path.join("src", "lib", "providerless-inference.ts")); for (const relativePath of [ "extra-agents-validation.ts", + "inference-credential.ts", path.join("core", "json-types.ts"), path.join("core", "ports.ts"), path.join("onboard", "managed-startup", "image-runtime.ts"), @@ -513,6 +514,7 @@ describe("sandbox build context staging", () => { function expectStagedManagedStartupRuntimeSources(buildCtx: string, sourceRoot: string) { for (const relativePath of [ path.join("src", "lib", "extra-agents-validation.ts"), + path.join("src", "lib", "inference-credential.ts"), path.join("src", "lib", "core", "json-types.ts"), path.join("src", "lib", "core", "ports.ts"), path.join("src", "lib", "onboard", "managed-startup", "image-runtime.ts"), From cffcfef561f5c737f2d47c84bac79f3b5a05102e Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 17:08:08 +0700 Subject: [PATCH 03/12] fix(inference): use supervisor-scoped NVIDIA credential handles --- agents/hermes/hermes-wrapper.py | 13 ++++--- agents/hermes/managed_policy.py | 2 +- scripts/nemoclaw-start.sh | 11 +++--- ...rence-set-openclaw-gateway-restart.test.ts | 2 +- .../inference-set-openclaw-run.test.ts | 2 +- .../inference-set-patch-hermes.test.ts | 4 +-- .../inference-set-patch-openclaw.test.ts | 8 ++--- src/lib/hermes-managed-route.ts | 4 +-- src/lib/inference-credential.ts | 7 ++-- .../hermes/hermes-managed-policy.test.ts | 11 ++---- .../runtime/auth-profile-boundary.test.ts | 36 +++++++++++++++++++ .../generation/generate-hermes-config.test.ts | 2 +- ...rate-openclaw-native-nvidia-config.test.ts | 4 +-- .../providerless-agent-config.test.ts | 2 +- 14 files changed, 70 insertions(+), 38 deletions(-) diff --git a/agents/hermes/hermes-wrapper.py b/agents/hermes/hermes-wrapper.py index 9d584264b67..b81100d9eac 100755 --- a/agents/hermes/hermes-wrapper.py +++ b/agents/hermes/hermes-wrapper.py @@ -30,16 +30,15 @@ # looks like a real credential. # - Value being masked: for configs generated by # `agents/hermes/config/managed-policy.ts:buildHermesManagedPolicy`, the literal -# rewrite sentinel `sk-OPENSHELL-PROXY-REWRITE` is hard-coded for the `model`, -# `providers`, and `custom_providers` `api_key` fields; the user's real -# provider credential is never serialised into the rendered config +# inference.local rewrite sentinel or native NVIDIA environment reference +# is used for the `model`, `providers`, and `custom_providers` `api_key` fields; +# the user's real provider credential is never serialised into the rendered config # (requests are rewritten at the OpenShell egress boundary). The masker # also unconditionally redacts any `api_key`-shaped field, so no # `api_key` field value reaches the post-mask user-visible stream. -# - Source-fix constraint: removing the inline `api_key` would require -# either Hermes CLI native env-var reference support (an upstream -# change) or a redesigned dashboard/runtime contract that no longer -# needs an `sk-`-prefixed rewrite sentinel in the rendered config. +# - Hermes expands the native NVIDIA reference from the supervisor-issued +# OpenShell handle when it loads config. Masking still applies to resolved +# `api_key` fields and the inference.local rewrite sentinel. # - Regression test: `test/agents/hermes/hermes-gateway-wrapper.test.ts` — # `masks every api_key emitted by the managed policy ...` derives a # fixture from `buildHermesManagedPolicy()` and asserts no raw sentinel diff --git a/agents/hermes/managed_policy.py b/agents/hermes/managed_policy.py index 92bd5c5eb79..7d40a691b54 100644 --- a/agents/hermes/managed_policy.py +++ b/agents/hermes/managed_policy.py @@ -14,7 +14,7 @@ MANAGED_POLICY_PATH = Path("/usr/local/share/nemoclaw/hermes-managed-policy.json") MANAGED_POLICY_SCHEMA_VERSION = 3 HERMES_PROXY_REWRITE_SENTINEL = "sk-OPENSHELL-PROXY-REWRITE" -NVIDIA_INFERENCE_PLACEHOLDER = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY" +NVIDIA_INFERENCE_PLACEHOLDER = "${NVIDIA_INFERENCE_API_KEY}" class ManagedPolicyError(Exception): diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index a3e31563fb2..10955baf889 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -57,9 +57,9 @@ unset NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGC NEMOCLAW_ENTRYPOINT_NORMALIZED_ARGV \ unset -f nemoclaw_normalize_entrypoint_env_wrapper # managed-entrypoint-env-wrapper end -# OpenShell owns managed inference authentication. Clear its credential aliases -# after entrypoint overrides are normalized, before setup can launch children. -# Direct inference routes retain their credentials. +# OpenShell owns managed inference authentication. Keep only its scoped, +# non-secret runtime handle after entrypoint overrides are normalized; clear raw +# credentials before setup can launch children. Direct routes retain credentials. is_managed_inference_route() { # Match URL scheme and host case without spawning a credential-bearing child. [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]\.[Ll][Oo][Cc][Aa][Ll](:443)?(/.*)?$ ]] \ @@ -68,7 +68,10 @@ is_managed_inference_route() { clear_managed_inference_credentials() { if is_managed_inference_route; then - unset NVIDIA_INFERENCE_API_KEY NVIDIA_API_KEY + unset NVIDIA_API_KEY + if ! [[ "${NVIDIA_INFERENCE_API_KEY:-}" =~ ^openshell:resolve:env:(v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$ ]]; then + unset NVIDIA_INFERENCE_API_KEY + fi fi } clear_managed_inference_credentials diff --git a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts index bfbf3940ba6..b7e5858fc86 100644 --- a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts +++ b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts @@ -201,7 +201,7 @@ describe("runInferenceSet OpenClaw gateway restart", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod", diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 006328c42b7..d496558badd 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -621,7 +621,7 @@ describe("runInferenceSet OpenClaw routing", () => { expect(providerUpdate?.value).toEqual({ api: "openai-completions", baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod" }, models: alreadyExists ? [otherModel, selectedModel] : [selectedModel, otherModel], }); diff --git a/src/lib/actions/inference-set-patch-hermes.test.ts b/src/lib/actions/inference-set-patch-hermes.test.ts index dd0f703245b..e9675242d1c 100644 --- a/src/lib/actions/inference-set-patch-hermes.test.ts +++ b/src/lib/actions/inference-set-patch-hermes.test.ts @@ -11,7 +11,7 @@ describe("patchHermesInferenceConfig", () => { const config: ConfigObject = {}; patchHermesInferenceConfig(config, "vllm-local", "local-model"); patchHermesInferenceConfig(config, "nvidia-prod", "nvidia/test-model"); - const placeholder = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"; + const placeholder = "${NVIDIA_INFERENCE_API_KEY}"; expect(config).toMatchObject({ model: { api_key: placeholder }, providers: { "nvidia-prod": { api_key: placeholder } }, @@ -165,7 +165,7 @@ describe("patchHermesInferenceConfig", () => { default: "nvidia/nemotron-3-super-120b-a12b", provider: "custom", base_url: "https://integrate.api.nvidia.com/v1", - api_key: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + api_key: "${NVIDIA_INFERENCE_API_KEY}", }); }); diff --git a/src/lib/actions/inference-set-patch-openclaw.test.ts b/src/lib/actions/inference-set-patch-openclaw.test.ts index b1e45809489..9b6a6c8fb8e 100644 --- a/src/lib/actions/inference-set-patch-openclaw.test.ts +++ b/src/lib/actions/inference-set-patch-openclaw.test.ts @@ -23,7 +23,7 @@ describe("patchOpenClawInferenceConfig", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", }, }, }, @@ -105,7 +105,7 @@ describe("patchOpenClawInferenceConfig", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", models: [ { @@ -175,7 +175,7 @@ describe("patchOpenClawInferenceConfig", () => { expect((config.models as ConfigObject).providers).toEqual({ inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", models: [ { @@ -231,7 +231,7 @@ describe("patchOpenClawInferenceConfig", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", models: [ { diff --git a/src/lib/hermes-managed-route.ts b/src/lib/hermes-managed-route.ts index fbcdede458d..df5553fb94e 100644 --- a/src/lib/hermes-managed-route.ts +++ b/src/lib/hermes-managed-route.ts @@ -3,8 +3,8 @@ import { managedInferenceApiKey, NVIDIA_INFERENCE_PLACEHOLDER } from "./inference-credential.ts"; -// Hermes requires an sk-prefixed value before it sends a request. OpenShell -// removes this non-secret sentinel and injects the route credential at egress. +// The inference.local route replaces this non-secret sentinel at egress. +// Native NVIDIA routing instead expands the supervisor-issued environment handle. export const HERMES_PROXY_REWRITE_SENTINEL = "sk-OPENSHELL-PROXY-REWRITE"; type HermesManagedProvider = { diff --git a/src/lib/inference-credential.ts b/src/lib/inference-credential.ts index baf19383f43..57cc5fce933 100644 --- a/src/lib/inference-credential.ts +++ b/src/lib/inference-credential.ts @@ -1,9 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// The native provider rewrites references to its host-held credential. The -// inference.local route instead replaces the client's authorization header. -export const NVIDIA_INFERENCE_PLACEHOLDER = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"; +// Both agents expand this reference from the supervisor-issued, scoped +// OpenShell handle at config load. A static resolver alias has no provider +// identity and is rejected by the endpoint-bound native provider. +export const NVIDIA_INFERENCE_PLACEHOLDER = "${NVIDIA_INFERENCE_API_KEY}"; export function managedInferenceApiKey( baseUrl: string, diff --git a/test/agents/hermes/hermes-managed-policy.test.ts b/test/agents/hermes/hermes-managed-policy.test.ts index d1d31a68c32..c1da78e0ab9 100644 --- a/test/agents/hermes/hermes-managed-policy.test.ts +++ b/test/agents/hermes/hermes-managed-policy.test.ts @@ -84,9 +84,7 @@ describe("Hermes managed policy", () => { { ...SETTINGS, baseUrl, upstreamProvider: "nvidia-prod" }, {}, ); - expect(policy.config.model?.api_key).toBe( - "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", - ); + expect(policy.config.model?.api_key).toBe("${NVIDIA_INFERENCE_API_KEY}"); const result = loadWithPython(policy); expect(result.status, result.stderr).toBe(0); }, @@ -94,11 +92,8 @@ describe("Hermes managed policy", () => { it.each([ ["https://integrate.api.nvidia.com/v1", "sk-OPENSHELL-PROXY-REWRITE"], - ["https://inference.local/v1", "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"], - [ - "https://integrate.api.nvidia.com.example/v1", - "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", - ], + ["https://inference.local/v1", "${NVIDIA_INFERENCE_API_KEY}"], + ["https://integrate.api.nvidia.com.example/v1", "${NVIDIA_INFERENCE_API_KEY}"], ["https://integrate.api.nvidia.com/v1", "sk-raw-policy-credential"], ])("rejects credentials outside the managed route contract at %s", (baseUrl, apiKey) => { const policy = buildHermesManagedPolicy({ ...SETTINGS, baseUrl }, {}); diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 47cccf4a89c..417354dfa65 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -88,6 +88,7 @@ function runStartupCredentialBoundary( kind: "non-root" | "root", route = "managed", failCleanup = false, + credentialValue = managedEnv.NVIDIA_INFERENCE_API_KEY, ) { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auth-startup-")); homes.push(home); @@ -132,6 +133,10 @@ function runStartupCredentialBoundary( HOME: home, AUTH_TEST_COMMAND: command, ...managedEnv, + NVIDIA_INFERENCE_API_KEY: credentialValue, + ...(route === "native" + ? { NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1" } + : {}), ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), }, encoding: "utf-8", @@ -199,6 +204,37 @@ describe("OpenClaw auth-profile boundary", () => { expect(fixture.stdout.trim()).toBe("unset\nunset"); }); + it.each([ + "primary-secret", + "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", + "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", + "openshell:resolve:env:v1_OTHER_API_KEY", + "openshell:resolve:env:s123_NVIDIA_INFERENCE_API_KEY", + "openshell:resolve:env:v1_NVIDIA_INFERENCE_API_KEY trailing", + ])("removes an unscoped or invalid native inference credential: %s", (value) => { + const fixture = runBashAuthFixture({ + ...managedEnv, + NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1", + NVIDIA_INFERENCE_API_KEY: value, + }); + expect(fixture.status, fixture.stderr).toBe(0); + expect(fixture.stdout.trim()).toBe("unset\nunset"); + }); + + it.each([ + ["root", "v42"], + ["non-root", "v42"], + ["root", `s${"a".repeat(64)}`], + ["non-root", `s${"a".repeat(64)}`], + ] as const)("preserves the scoped %s runtime handle %s for command children", (kind, scope) => { + const reference = `openshell:resolve:env:${scope}_NVIDIA_INFERENCE_API_KEY`; + const result = runStartupCredentialBoundary(kind, "native", false, reference); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe( + [`${reference}\nunset`, `${reference}\nunset`, "command", `${reference}\nunset`].join("\n"), + ); + }); + it.each([ ["fresh", "https://inference.local/v1"], ["legacy", "https://inference.local/v1"], diff --git a/test/generation/generate-hermes-config.test.ts b/test/generation/generate-hermes-config.test.ts index 3daa2b3e373..ea68fef5bf0 100644 --- a/test/generation/generate-hermes-config.test.ts +++ b/test/generation/generate-hermes-config.test.ts @@ -66,7 +66,7 @@ it("uses a resolvable credential in every native NVIDIA inference configuration" NEMOCLAW_UPSTREAM_PROVIDER: "nvidia-prod", NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1", }); - const placeholder = "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY"; + const placeholder = "${NVIDIA_INFERENCE_API_KEY}"; expect(config.model.api_key).toBe(placeholder); expect(config.providers["nvidia-prod"].api_key).toBe(placeholder); expect(config.custom_providers[0].api_key).toBe(placeholder); diff --git a/test/generation/generate-openclaw-native-nvidia-config.test.ts b/test/generation/generate-openclaw-native-nvidia-config.test.ts index 7aa51b17999..cd0c2c3e2db 100644 --- a/test/generation/generate-openclaw-native-nvidia-config.test.ts +++ b/test/generation/generate-openclaw-native-nvidia-config.test.ts @@ -14,9 +14,7 @@ it.each(["https://integrate.api.nvidia.com/v1", "HTTPS://INTEGRATE.API.NVIDIA.CO NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", NEMOCLAW_INFERENCE_BASE_URL: baseUrl, }); - expect(config.models.providers.inference.apiKey).toBe( - "sk-OPENSHELL-RESOLVE-ENV-NVIDIA_INFERENCE_API_KEY", - ); + expect(config.models.providers.inference.apiKey).toBe("${NVIDIA_INFERENCE_API_KEY}"); }, ); diff --git a/test/generation/providerless-agent-config.test.ts b/test/generation/providerless-agent-config.test.ts index b7230219aac..dd6d7a6d49c 100644 --- a/test/generation/providerless-agent-config.test.ts +++ b/test/generation/providerless-agent-config.test.ts @@ -149,7 +149,7 @@ const expectConfigured: Record void> = { hermes(config) { expect(config.model.default).toBe("fixture/model"); expect(config.model.provider).toBe("custom"); - expect(config.model.api_key).toBe("sk-OPENSHELL-PROXY-REWRITE"); + expect(config.model.api_key).toBe("${NVIDIA_INFERENCE_API_KEY}"); }, }; type InferenceSetCalls = ReturnType["calls"]; From 9cf2dbf8aa0d89c2e1b22cf5d0f049a83209ff4b Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 18:32:27 +0700 Subject: [PATCH 04/12] fix(hermes): refresh wrapper integrity pin Signed-off-by: San Dang --- agents/hermes/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index 14f0898b62e..36f980534c3 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -756,7 +756,7 @@ RUN node \ # file has to also rewrite the Dockerfile-committed hash, which reviewers gate). # Regenerate with `sha256sum agents/hermes/{hermes-wrapper.py,hermes-cli-adapter-v1.json,validate-cli-adapter.py,validate-env-secret-boundary.py,finalize-tirith-marker.py,cron-restore-control.py}`. ARG NEMOCLAW_HERMES_CLI_ADAPTER_SHA256=d892e57585485880e41c9bd0afe5b851e131997ab6ac86956a58db0704147781 -ARG NEMOCLAW_HERMES_WRAPPER_SHA256=1d6e6e46de34ccd5904e1a1add45eca536790902e610a46303a1811bb926eb81 +ARG NEMOCLAW_HERMES_WRAPPER_SHA256=ca37193cfa1fd972f64db1e3feb77a0b605e2dec507ee8414310ce002aba6985 ARG NEMOCLAW_HERMES_CLI_ADAPTER_VALIDATOR_SHA256=5205a5446d0a509c5bc60f77fd97ec579449c2c7291dcc2878a788f25f078d6f ARG NEMOCLAW_HERMES_VALIDATOR_SHA256=8173abf39766a41afad3110622ce7dc78612a4cc96ea75e88150125e7dabc8b5 ARG NEMOCLAW_HERMES_TIRITH_FINALIZER_SHA256=a1e6b1c53ab297569abb87c29d15c294d729e46005bfd022136b4c447a791819 From d494e64b99e1357e6642c54d9a275b84930fa2b0 Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 19:22:51 +0700 Subject: [PATCH 05/12] fix(inference): recognize default-port NVIDIA routes Signed-off-by: San Dang --- scripts/nemoclaw-start.sh | 6 +- .../runtime/auth-profile-boundary.test.ts | 78 ++++++++++++++----- .../live/openclaw-inference-switch.test.ts | 14 +++- ...rate-openclaw-native-nvidia-config.test.ts | 24 +++--- 4 files changed, 87 insertions(+), 35 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 10955baf889..2063bb61f67 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -61,9 +61,9 @@ unset -f nemoclaw_normalize_entrypoint_env_wrapper # non-secret runtime handle after entrypoint overrides are normalized; clear raw # credentials before setup can launch children. Direct routes retain credentials. is_managed_inference_route() { - # Match URL scheme and host case without spawning a credential-bearing child. - [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]\.[Ll][Oo][Cc][Aa][Ll](:443)?(/.*)?$ ]] \ - || [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Tt][Ee][Gg][Rr][Aa][Tt][Ee]\.[Aa][Pp][Ii]\.[Nn][Vv][Ii][Dd][Ii][Aa]\.[Cc][Oo][Mm](:443)?/v1/?$ ]] + # Match scheme/host case and default-port leading zeros without spawning a child. + [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]\.[Ll][Oo][Cc][Aa][Ll](:0*443)?(/.*)?$ ]] \ + || [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Tt][Ee][Gg][Rr][Aa][Tt][Ee]\.[Aa][Pp][Ii]\.[Nn][Vv][Ii][Dd][Ii][Aa]\.[Cc][Oo][Mm](:0*443)?/v1/?$ ]] } clear_managed_inference_credentials() { diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 417354dfa65..628a95c1dfe 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -134,8 +134,11 @@ function runStartupCredentialBoundary( AUTH_TEST_COMMAND: command, ...managedEnv, NVIDIA_INFERENCE_API_KEY: credentialValue, - ...(route === "native" - ? { NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1" } + ...(route === "native" || route.startsWith("https://integrate.api.nvidia.com:") + ? { + NEMOCLAW_INFERENCE_BASE_URL: + route === "native" ? "https://integrate.api.nvidia.com/v1" : route, + } : {}), ...(route === "direct" ? { NEMOCLAW_INFERENCE_BASE_URL: "https://direct.example/v1" } : {}), }, @@ -170,17 +173,36 @@ describe("OpenClaw auth-profile boundary", () => { expect(fs.statSync(fixture.authPath).mode & 0o777).toBe(0o600); }); + it.each(["https://integrate.api.nvidia.com:0444/v1", "https://integrate.api.nvidia.com:4443/v1"])( + "retains direct-route credentials and profiles at %s", + (baseUrl) => { + const fixture = runBashAuthFixture({ ...managedEnv, NEMOCLAW_INFERENCE_BASE_URL: baseUrl }); + expect(fixture.status, fixture.stderr).toBe(0); + expect(fixture.stdout.trim()).toBe("primary-secret\nlegacy-secret"); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + "inference:manual": legacyManagedProfile, + }); + }, + ); + it("leaves direct auth state absent when no credential is supplied", () => { const fixture = runBashAuthFixture({}); expect(fixture.status, fixture.stderr).toBe(0); expect(fs.existsSync(fixture.authPath)).toBe(false); }); - it.each(["fresh", "legacy"] as const)( - "leaves no legacy auth profile for native NVIDIA inference in %s state", - (state) => { + it.each([ + ["fresh", "https://integrate.api.nvidia.com/v1"], + ["legacy", "https://integrate.api.nvidia.com/v1"], + ["fresh", "https://integrate.api.nvidia.com:0443/v1"], + ["legacy", "https://integrate.api.nvidia.com:0443/v1"], + ["fresh", "https://integrate.api.nvidia.com:000443/v1/"], + ["legacy", "https://integrate.api.nvidia.com:000443/v1/"], + ] as const)( + "leaves no legacy auth profile or raw credentials in %s state at %s", + (state, baseUrl) => { const fixture = runBashAuthFixture( - { ...managedEnv, NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1" }, + { ...managedEnv, NEMOCLAW_INFERENCE_BASE_URL: baseUrl }, state === "legacy" ? seedAuthProfile({ "inference:manual": legacyManagedProfile }) : undefined, @@ -204,6 +226,17 @@ describe("OpenClaw auth-profile boundary", () => { expect(fixture.stdout.trim()).toBe("unset\nunset"); }); + it.each(["root", "non-root"] as const)( + "removes raw credentials before %s command children at native NVIDIA port :0443", + (kind) => { + const result = runStartupCredentialBoundary(kind, "https://integrate.api.nvidia.com:0443/v1"); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("unset\nunset\nunset\nunset\ncommand\nunset\nunset"); + expect(result.stderr).not.toContain(managedEnv.NVIDIA_INFERENCE_API_KEY); + expect(result.stderr).not.toContain(managedEnv.NVIDIA_API_KEY); + }, + ); + it.each([ "primary-secret", "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", @@ -222,24 +255,33 @@ describe("OpenClaw auth-profile boundary", () => { }); it.each([ - ["root", "v42"], - ["non-root", "v42"], - ["root", `s${"a".repeat(64)}`], - ["non-root", `s${"a".repeat(64)}`], - ] as const)("preserves the scoped %s runtime handle %s for command children", (kind, scope) => { - const reference = `openshell:resolve:env:${scope}_NVIDIA_INFERENCE_API_KEY`; - const result = runStartupCredentialBoundary(kind, "native", false, reference); - expect(result.status, result.stderr).toBe(0); - expect(result.stdout.trim()).toBe( - [`${reference}\nunset`, `${reference}\nunset`, "command", `${reference}\nunset`].join("\n"), - ); - }); + ["root", "v42", "native"], + ["non-root", "v42", "native"], + ["root", `s${"a".repeat(64)}`, "native"], + ["non-root", `s${"a".repeat(64)}`, "native"], + ["root", "v42", "https://integrate.api.nvidia.com:0443/v1"], + ["non-root", "v42", "https://integrate.api.nvidia.com:0443/v1"], + ["root", `s${"a".repeat(64)}`, "https://integrate.api.nvidia.com:0443/v1"], + ["non-root", `s${"a".repeat(64)}`, "https://integrate.api.nvidia.com:0443/v1"], + ] as const)( + "preserves the scoped %s runtime handle %s at %s for command children", + (kind, scope, route) => { + const reference = `openshell:resolve:env:${scope}_NVIDIA_INFERENCE_API_KEY`; + const result = runStartupCredentialBoundary(kind, route, false, reference); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe( + [`${reference}\nunset`, `${reference}\nunset`, "command", `${reference}\nunset`].join("\n"), + ); + }, + ); it.each([ ["fresh", "https://inference.local/v1"], ["legacy", "https://inference.local/v1"], ["fresh", "HTTPS://inference.local:443/v1"], ["legacy", "https://INFERENCE.LOCAL:443"], + ["fresh", "https://inference.local:0443/v1"], + ["legacy", "https://inference.local:0443/v1"], ] as const)( "leaves no managed profile or inherited credentials in %s state at %s", (state, baseUrl) => { diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 055ad7f9cbe..27f910e2528 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -617,6 +617,7 @@ async function readAndAssertOpenClawConfig( model: string; inferenceApi: string; artifactName: string; + nativeNvidia?: boolean; }, ): Promise { const configResult = await sandbox.exec( @@ -638,13 +639,13 @@ async function readAndAssertOpenClawConfig( expect(config.agents?.defaults?.model?.primary).toBe(expectedPrimary); expect(provider?.baseUrl).toBe( - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER + expected.nativeNvidia ? NVIDIA_HOSTED_NATIVE_ENDPOINT : expected.inferenceApi === "anthropic-messages" ? "https://inference.local" : "https://inference.local/v1", ); - expect(provider?.apiKey).toBe("unused"); + expect(provider?.apiKey).toBe(expected.nativeNvidia ? "${NVIDIA_INFERENCE_API_KEY}" : "unused"); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; @@ -657,10 +658,15 @@ async function assertOpenClawConfig( model: string; inferenceApi: string; artifactName: string; + nativeNvidia?: boolean; }, ): Promise { const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); - expect(typeof selectedModel?.maxTokens === "number" && selectedModel.maxTokens > 0).toBe(true); + expect( + expected.inferenceApi === "anthropic-messages" + ? typeof selectedModel?.maxTokens === "number" && selectedModel.maxTokens > 0 + : selectedModel?.maxTokens === undefined, + ).toBe(true); } async function assertInitialOpenClawConfig( @@ -670,6 +676,7 @@ async function assertInitialOpenClawConfig( model: string; inferenceApi: string; artifactName: string; + nativeNvidia?: boolean; }, ): Promise { const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); @@ -1321,6 +1328,7 @@ test( model: SWITCH_MODEL, inferenceApi: SWITCH_INFERENCE_API, artifactName: "read-openclaw-config-after-inference-switch", + nativeNvidia: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, }); await assertRegistryAndSession(home, { mockProvider, sandbox }); diff --git a/test/generation/generate-openclaw-native-nvidia-config.test.ts b/test/generation/generate-openclaw-native-nvidia-config.test.ts index cd0c2c3e2db..f75d7f33f0d 100644 --- a/test/generation/generate-openclaw-native-nvidia-config.test.ts +++ b/test/generation/generate-openclaw-native-nvidia-config.test.ts @@ -6,17 +6,19 @@ import { expect, it } from "vitest"; import { buildConfig } from "../../scripts/generate-openclaw-config.mts"; import { baseOpenClawGenerationEnv } from "../helpers/openclaw-env-fixture"; -it.each(["https://integrate.api.nvidia.com/v1", "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/"])( - "uses a resolvable credential for native NVIDIA inference at %s", - (baseUrl) => { - const config = buildConfig({ - ...baseOpenClawGenerationEnv(), - NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", - NEMOCLAW_INFERENCE_BASE_URL: baseUrl, - }); - expect(config.models.providers.inference.apiKey).toBe("${NVIDIA_INFERENCE_API_KEY}"); - }, -); +it.each([ + "https://integrate.api.nvidia.com/v1", + "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/", + "https://integrate.api.nvidia.com:0443/v1", + "https://integrate.api.nvidia.com:000443/v1/", +])("uses a resolvable credential for native NVIDIA inference at %s", (baseUrl) => { + const config = buildConfig({ + ...baseOpenClawGenerationEnv(), + NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", + NEMOCLAW_INFERENCE_BASE_URL: baseUrl, + }); + expect(config.models.providers.inference.apiKey).toBe("${NVIDIA_INFERENCE_API_KEY}"); +}); it.each([ "https://inference.local/v1", From 4e8cdd800e1f0797b777a1b4720081280ec0c3a0 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 9 Oct 2026 11:44:41 -0400 Subject: [PATCH 06/12] test(e2e): align inference switch fixtures and assertions The native switch lanes paired public credentials with internal endpoints and expected an internal baseline model. OpenClaw also parsed padded terminal columns and applied destination configuration expectations to its baseline. Use an authenticated local OpenClaw baseline, derive the Hermes model from its installation environment, pair its later proxy route with the public endpoint, and assert JSON route fields and API-specific config limits. Observed four wiring regressions and one native reply-budget regression fail before repair. Focused support coverage passes 79 tests; test:changed passes 49 tests plus 7 growth checks. Native live validation still depends on the production credential fix tracked in PR #12895. Signed-off-by: Julie Yaunches --- test/e2e/README.md | 5 + .../live/hermes-inference-switch-helpers.ts | 17 ++- test/e2e/live/hermes-inference-switch.test.ts | 2 +- .../live/openclaw-inference-switch-helpers.ts | 5 +- .../live/openclaw-inference-switch.test.ts | 83 ++++-------- ...mes-inference-switch-command-shape.test.ts | 23 ++++ .../support/inference-switch-baseline.test.ts | 119 ++++++++++++++++++ 7 files changed, 190 insertions(+), 64 deletions(-) create mode 100644 test/e2e/support/inference-switch-baseline.test.ts diff --git a/test/e2e/README.md b/test/e2e/README.md index 8e85b6c8717..9c587fa4646 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -591,6 +591,11 @@ Changes to shared catalogue execution paths select every catalogue target. The `openclaw-inference-switch` target owns fresh custom-image route initialization. Its fixture contains only a different baked model and stale limits. The target requires onboarding to create the selected model without those limits, then preserves that native configuration through restart and rebuild. +Both switch variants start with an authenticated local OpenAI-compatible fixture. +The native NVIDIA destination uses the public endpoint and its public credential only after switching. +Route assertions use JSON fields so terminal column alignment does not affect the result. +The Hermes native switch derives its baseline model expectation from the environment passed to installation. +Its later proxy-resolution probe pairs the public NVIDIA credential with the public endpoint. Most entries use one ID for catalogue selection, evidence, and artifacts. Matrix-style targets use one target ID for evidence and artifacts, with separate catalogue IDs and shards for each concrete execution. diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index 608540e132e..63eb2fa5b4a 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -7,7 +7,10 @@ import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; -import { resolveAgentInferenceApi } from "../../../src/lib/inference/config.ts"; +import { + DEFAULT_CLOUD_MODEL, + resolveAgentInferenceApi, +} from "../../../src/lib/inference/config.ts"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts"; import { execTimeout } from "../../helpers/timeouts.ts"; @@ -182,7 +185,12 @@ export function env(apiKey?: string, extra: NodeJS.ProcessEnv = {}): NodeJS.Proc NEMOCLAW_SANDBOX_NAME: SANDBOX_NAME, OPENSHELL_GATEWAY: openshellGatewayName(), }; - apiKey && Object.assign(out, { NVIDIA_INFERENCE_API_KEY: apiKey }); + apiKey && + Object.assign(out, { + NVIDIA_INFERENCE_API_KEY: apiKey, + NEMOCLAW_PROVIDER: "build", + NEMOCLAW_MODEL: process.env.NEMOCLAW_MODEL ?? DEFAULT_CLOUD_MODEL, + }); USE_COMPATIBLE_HOSTED && apiKey && Object.assign(out, { @@ -231,7 +239,10 @@ export async function prepareProxyResolutionRoute({ redactionValues: string[]; }): Promise<{ model: string; requestOffset: number }> { const endpoint = - mockBaseline?.baseUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL; + mockBaseline?.baseUrl ?? + (USE_COMPATIBLE_HOSTED + ? (process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL) + : NVIDIA_HOSTED_NATIVE_ENDPOINT); const model = mockBaseline ? PROXY_RESOLUTION_MODEL : SWITCH_MODEL; const requestOffset = mockBaseline?.requests().length ?? 0; diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index c017315f0ad..d7b0673bc6a 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -184,7 +184,7 @@ test( expect(baselineRoute.exitCode, resultText(baselineRoute)).toBe(0); expect(parseInferenceRoute(resultText(baselineRoute))).toEqual({ provider: mockBaseline ? "compatible-endpoint" : PUBLIC_NVIDIA_SWITCH_PROVIDER, - model: hostedInstallModel(installEnv), + model: hostedInstallModel(env(apiKey, installEnv)), }); const baselineSession = structuredClone(registryState().session); const switchBinding = await prepareCompatibleAnthropicSwitchBinding(host, cleanup); diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index c6b8f3f4a69..af74d1a8676 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -144,9 +144,8 @@ export function parseOpenClawGatewayModelRun(raw: string): OpenClawGatewayModelR }; } -// Baseline (mock-Anthropic) inference config the live target builds when -// NEMOCLAW_SWITCH_MOCK_ANTHROPIC=1 points OpenClaw at a local fake OpenAI- -// compatible server. Extracted so the fast e2e-support project can assert the +// Both switch variants start OpenClaw against an authenticated local fake +// OpenAI-compatible server. Extracted so the fast e2e-support project can assert the // exact env wiring (credential, model, endpoint, preferred API, provider) // without gating on NEMOCLAW_RUN_LIVE_E2E=1. export const MOCK_BASELINE_API_KEY = "openclaw-switch-baseline-credential"; diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 055ad7f9cbe..64761e2c139 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -37,7 +37,6 @@ import { } from "../fixtures/compatible-anthropic-switch.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import type { FakeOpenAiCompatibleServer } from "../fixtures/fake-openai-compatible.ts"; -import { requireHostedInferenceConfig } from "../fixtures/hosted-inference.ts"; import { selectedE2eManagedImageReference } from "../fixtures/managed-image-receipt.ts"; import type { TestProgress } from "../fixtures/progress.ts"; import { @@ -55,7 +54,6 @@ import { anthropicToolCount, classifyExhaustedPostSwitchEvidence, classifyOpenClawPostSwitchInferenceAttempt, - classifyUnavailableInitialProviderEvidence, MOCK_BASELINE_MODEL, mockBaselineInference, parseOpenClawGatewayModelRun, @@ -227,10 +225,6 @@ async function proveSelectedMockBaselineAuthentication( ).toContainEqual(expectedRequest); } -function stripAnsi(value: string): string { - return value.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, ""); -} - function parsePortEnv(name: string, fallback: number): number { const raw = process.env[name]; if (!raw) return fallback; @@ -533,8 +527,8 @@ async function openclawGatewayPid(sandbox: SandboxClient, home: string): Promise return result.stdout.trim(); } -async function getRouteOutput(host: HostCliClient, home: string): Promise { - return runNemoclaw(host, home, ["inference", "get"], { +export async function getRouteOutput(host: HostCliClient, home: string): Promise { + return runNemoclaw(host, home, ["inference", "get", "--json"], { artifactName: "nemoclaw-inference-get-after-switch", timeoutMs: COMMAND_TIMEOUT_MS, }); @@ -617,6 +611,7 @@ async function readAndAssertOpenClawConfig( model: string; inferenceApi: string; artifactName: string; + baseUrl: string; }, ): Promise { const configResult = await sandbox.exec( @@ -637,30 +632,29 @@ async function readAndAssertOpenClawConfig( const selectedModel = provider?.models?.find((entry) => entry.id === expected.model); expect(config.agents?.defaults?.model?.primary).toBe(expectedPrimary); - expect(provider?.baseUrl).toBe( - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : expected.inferenceApi === "anthropic-messages" - ? "https://inference.local" - : "https://inference.local/v1", - ); + expect(provider?.baseUrl).toBe(expected.baseUrl); expect(provider?.apiKey).toBe("unused"); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; } -async function assertOpenClawConfig( +export async function assertOpenClawConfig( sandbox: SandboxClient, home: string, expected: { model: string; inferenceApi: string; artifactName: string; + baseUrl: string; }, ): Promise { const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); - expect(typeof selectedModel?.maxTokens === "number" && selectedModel.maxTokens > 0).toBe(true); + expect( + expected.inferenceApi === "anthropic-messages" + ? typeof selectedModel?.maxTokens === "number" && selectedModel.maxTokens > 0 + : selectedModel?.maxTokens === undefined, + ).toBe(true); } async function assertInitialOpenClawConfig( @@ -670,6 +664,7 @@ async function assertInitialOpenClawConfig( model: string; inferenceApi: string; artifactName: string; + baseUrl: string; }, ): Promise { const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); @@ -980,6 +975,7 @@ async function runInitialRouteLifecycle(options: { model: options.model, inferenceApi: "openai-completions", artifactName: `read-openclaw-initial-route-${artifactSuffix}`, + baseUrl: "https://inference.local/v1", }); await checkOpenClawGatewayInference( options.host, @@ -1028,13 +1024,6 @@ async function runInitialRouteLifecycle(options: { // are covered in the fast e2e-support project instead: // test/e2e/support/openclaw-inference-switch-helpers.test.ts. -function isExternalProviderValidationFailure(text: string): boolean { - return ( - /NVIDIA Endpoints endpoint validation failed/i.test(text) && - /HTTP 429|rate limit|quota|temporarily unavailable|timed out|timeout/i.test(text) - ); -} - async function runOpenClawInferenceSetWithRetry( host: HostCliClient, home: string, @@ -1148,22 +1137,14 @@ test( scenarioLabel: "OpenClaw inference switch", }); - const useMockBaseline = - 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 baselineProvider: FakeOpenAiCompatibleServer | undefined = useMockBaseline - ? await startMockOpenClawBaselineProvider(progress) - : undefined; + // The baseline uses its own authenticated fixture; the public key belongs only to the switch. + const baselineProvider = await startMockOpenClawBaselineProvider(progress); + cleanup.trackDisposable("close baseline inference provider", () => baselineProvider.close()); const publicApiKey = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) : null; - const baseline = baselineProvider - ? mockBaselineInference(baselineProvider.baseUrl) - : requireHostedInferenceConfig({ - required: (name) => publicApiKey ?? secrets.required(name), - }); + const baseline = mockBaselineInference(baselineProvider.baseUrl); const apiKey = baseline.apiKey; const redactionValues = [apiKey, publicApiKey].filter( (value): value is string => typeof value === "string", @@ -1180,9 +1161,6 @@ test( cleanup.trackDisposable("close switched Anthropic provider", async () => { await mockProvider?.close(); }); - cleanup.trackDisposable("close baseline inference provider", async () => { - await baselineProvider?.close(); - }); const customDockerfile = writeCustomOpenClawDockerfile(home); cleanup.trackGateway(host, "nemoclaw", { artifactName: "cleanup-openshell-gateway-destroy-openclaw-inference-switch", @@ -1219,21 +1197,6 @@ test( }, ); const onboardText = resultText(onboard); - const providerValidationUnavailable = - onboard.exitCode !== 0 && isExternalProviderValidationFailure(onboardText); - const unavailable = classifyUnavailableInitialProviderEvidence({ - required: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, - detail: onboardText, - }); - if (providerValidationUnavailable && unavailable.outcome === "skipped") { - await artifacts.target.complete({ - id: "openclaw-inference-switch", - status: "skipped", - reason: "external-provider-validation-unavailable-before-inference-switch", - onboardExitCode: onboard.exitCode, - }); - skip(unavailable.reason); - } expect(onboard.exitCode, onboardText).toBe(0); await proveMockBaselineAuthentication(baselineProvider, sandbox, home, artifacts); @@ -1314,13 +1277,19 @@ test( progress.phase("inspect route configuration and recorded state"); const route = await getRouteOutput(host, home); expect(route.exitCode, resultText(route)).toBe(0); - const plainRoute = stripAnsi(resultText(route)); - expect(plainRoute).toContain(`Provider: ${SWITCH_PROVIDER}`); - expect(plainRoute).toContain(`Model: ${SWITCH_MODEL}`); + const routeFields = JSON.parse(route.stdout) as { provider?: unknown; model?: unknown }; + expect(routeFields.provider).toBe(SWITCH_PROVIDER); + expect(routeFields.model).toBe(SWITCH_MODEL); await assertOpenClawConfig(sandbox, home, { model: SWITCH_MODEL, inferenceApi: SWITCH_INFERENCE_API, artifactName: "read-openclaw-config-after-inference-switch", + baseUrl: + SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER + ? NVIDIA_HOSTED_NATIVE_ENDPOINT + : SWITCH_INFERENCE_API === "anthropic-messages" + ? "https://inference.local" + : "https://inference.local/v1", }); await assertRegistryAndSession(home, { mockProvider, sandbox }); diff --git a/test/e2e/support/hermes-inference-switch-command-shape.test.ts b/test/e2e/support/hermes-inference-switch-command-shape.test.ts index 621a8ec39fb..8127ef05c2c 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -20,6 +20,7 @@ import { expectAuthenticatedProxyResolutionRequests, hasAuthenticatedProxyResolutionRequest, hostedInstallModel, + env, inferenceLocalMaxTokens, installHermes, mockAnthropicSwitchEnabled, @@ -190,6 +191,28 @@ describe("Hermes inference switch command shape", () => { ).toBe("initial-hosted-model"); }); + it("derives the native baseline model from the install environment", () => { + const installEnv = env("nvapi-public-fixture-key"); + expect(hostedInstallModel(installEnv)).toBe("nvidia/nemotron-3-super-120b-a12b"); + }); + + it("keeps the public proxy-resolution credential on the public NVIDIA endpoint", async () => { + const command = vi.fn().mockResolvedValue({ + exitCode: 0, + stderr: "", + stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n", + }); + await prepareProxyResolutionRoute({ + apiKey: "nvapi-public-fixture-key", + host: { command } as unknown as HostCliClient, + mockBaseline: undefined, + redactionValues: ["nvapi-public-fixture-key"], + }); + expect(command.mock.calls[0]?.[1]).toContain( + "OPENAI_BASE_URL=https://integrate.api.nvidia.com/v1", + ); + }); + it("keeps proxy-resolution evidence on a dedicated OpenAI provider", async () => { const command = vi .fn() diff --git a/test/e2e/support/inference-switch-baseline.test.ts b/test/e2e/support/inference-switch-baseline.test.ts new file mode 100644 index 00000000000..e8b8cb132c7 --- /dev/null +++ b/test/e2e/support/inference-switch-baseline.test.ts @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { afterEach, expect, it, vi } from "vitest"; +import { patchOpenClawInferenceConfig } from "../../../src/lib/actions/inference-set.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; + +const captured = vi.hoisted(() => ({ test: vi.fn() })); +vi.mock("../fixtures/e2e-test.ts", async () => ({ + expect: (await import("vitest")).expect, + test: captured.test, +})); +vi.mock("../fixtures/managed-image-receipt.ts", () => ({ + selectedE2eManagedImageReference: () => "example.invalid/openclaw@sha256:" + "a".repeat(64), +})); + +const disposables: Array<() => unknown> = []; +afterEach(async () => { + for (const dispose of disposables.splice(0).reverse()) await dispose(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +it("keeps the OpenClaw native switch credential out of the authenticated baseline", async () => { + vi.resetModules(); + captured.test.mockClear(); + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); + vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", "0"); + const exists = fs.existsSync; + vi.spyOn(fs, "existsSync").mockImplementation((file) => + String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), + ); + const result = { exitCode: 0, stdout: "", stderr: "" }; + const stop = new Error("onboarding captured"); + const nemoclaw = vi.fn(async (_args: string[], _options: { env: NodeJS.ProcessEnv }) => { + throw stop; + }); + await import("../live/openclaw-inference-switch.test.ts"); + const { startTestProgress } = await import("../fixtures/progress.ts"); + const progress = startTestProgress( + "baseline wiring", + captured.test.mock.calls[0]![1].meta.e2ePhases, + { logLine: () => undefined }, + ); + disposables.push(() => progress.stop()); + const run = captured.test.mock.calls[0]![2] as (input: object) => Promise; + 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 () => result) }, + progress, + runtimeProvider: { requireAvailable: vi.fn() }, + sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, + secrets: { required: vi.fn(() => "nvapi-public-fixture-key") }, + }), + ).rejects.toBe(stop); + const environment = nemoclaw.mock.calls[0]![1].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(); +}); + +it("requests structured route output instead of aligned terminal columns", async () => { + const { getRouteOutput } = await import("../live/openclaw-inference-switch.test.ts"); + const command = vi.fn(async (_command: string, args: string[]) => ({ + exitCode: 0, + stderr: "", + stdout: args.includes("--json") + ? JSON.stringify({ provider: "compatible-anthropic-endpoint", model: "mock-anthropic-model" }) + : "Provider: compatible-anthropic-endpoint\nModel: mock-anthropic-model\n", + })); + const result = await getRouteOutput( + { command } as unknown as HostCliClient, + "/tmp/switch-test-home", + ); + expect(JSON.parse(result.stdout)).toEqual({ + provider: "compatible-anthropic-endpoint", + model: "mock-anthropic-model", + }); +}); + +it.each([ + [ + "nvidia-prod", + "nvidia/nemotron-3-super-120b-a12b", + "openai-completions", + "https://integrate.api.nvidia.com/v1", + ], + [ + "compatible-anthropic-endpoint", + "mock-anthropic-model", + "anthropic-messages", + "https://inference.local", + ], +])( + "checks the actual switched model budget for %s", + async (provider, model, inferenceApi, baseUrl) => { + const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); + const config = {}; + patchOpenClawInferenceConfig(config, provider, model, inferenceApi); + const sandbox = { + exec: vi.fn(async () => ({ exitCode: 0, stdout: JSON.stringify(config), stderr: "" })), + }; + await assertOpenClawConfig(sandbox as never, "/tmp/switch-test-home", { + model, + inferenceApi, + baseUrl, + artifactName: "switched-config", + }); + }, +); From 4e290eba6e3f6baad94fd5a89014abe61e1ed82d Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 22:57:27 +0700 Subject: [PATCH 07/12] fix(inference): align native NVIDIA URL validation Signed-off-by: San Dang --- agents/hermes/managed_policy.py | 23 ++++++--- scripts/nemoclaw-start.sh | 7 +++ src/lib/inference-credential.ts | 24 ++++------ .../hermes/hermes-managed-policy.test.ts | 24 +++++++++- .../runtime/auth-profile-boundary.test.ts | 48 ++++++++++++++++++- test/e2e/mock-parity.json | 1 + test/fixtures/native-nvidia-inference-urls.ts | 22 +++++++++ ...rate-openclaw-native-nvidia-config.test.ts | 36 +++++++++----- 8 files changed, 148 insertions(+), 37 deletions(-) create mode 100644 test/fixtures/native-nvidia-inference-urls.ts diff --git a/agents/hermes/managed_policy.py b/agents/hermes/managed_policy.py index 7d40a691b54..3f2d9dfe22c 100644 --- a/agents/hermes/managed_policy.py +++ b/agents/hermes/managed_policy.py @@ -7,6 +7,7 @@ import errno import json import os +import re import stat from pathlib import Path from urllib.parse import urlsplit @@ -98,15 +99,23 @@ def load_managed_policy(path: Path = MANAGED_POLICY_PATH) -> dict: base_url = policy_value(config, "model.base_url") if not isinstance(base_url, str): raise ManagedPolicyError("managed policy model.base_url is invalid") + # Keep the raw URL contract identical to config generation and startup. + route = re.sub( + r"^[^/]+://[^/]+", lambda match: match.group().lower(), base_url, count=1 + ) + native_nvidia = re.fullmatch( + r"https://integrate\.api\.nvidia\.com(?::0*443)?/v1/?", route + ) is not None + if not native_nvidia and re.match( + r"https://integrate\.api\.nvidia\.com(?::(?:0*443)?)?(?:[/?#]|\Z)", route + ): + raise ManagedPolicyError( + "Native NVIDIA inference requires https://integrate.api.nvidia.com/v1." + ) try: url = urlsplit(base_url) - native_nvidia = ( - url.scheme == "https" - and url.hostname == "integrate.api.nvidia.com" - and url.port in (None, 443) - and url.path in ("/v1", "/v1/") - and not (url.username or url.password or url.query or url.fragment) - ) + # Preserve the reader's existing malformed-port validation for other routes. + _ = url.port except (TypeError, ValueError): raise ManagedPolicyError("managed policy model.base_url is invalid") from None expected_key = NVIDIA_INFERENCE_PLACEHOLDER if native_nvidia else HERMES_PROXY_REWRITE_SENTINEL diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index e4eaa5aa2b9..56b034bfd93 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -67,6 +67,13 @@ is_managed_inference_route() { } clear_managed_inference_credentials() { + # Refuse ambiguous native URLs before setup or a command can inherit secrets. + if [[ "${NEMOCLAW_INFERENCE_BASE_URL:-}" =~ ^[Hh][Tt][Tt][Pp][Ss]://[Ii][Nn][Tt][Ee][Gg][Rr][Aa][Tt][Ee]\.[Aa][Pp][Ii]\.[Nn][Vv][Ii][Dd][Ii][Aa]\.[Cc][Oo][Mm](:0*443|:)?([/?#]|$) ]] \ + && ! is_managed_inference_route; then + unset NVIDIA_API_KEY NVIDIA_INFERENCE_API_KEY + printf '%s\n' '[SECURITY] Native NVIDIA inference requires https://integrate.api.nvidia.com/v1.' >&2 + return 1 + fi if is_managed_inference_route; then unset NVIDIA_API_KEY if ! [[ "${NVIDIA_INFERENCE_API_KEY:-}" =~ ^openshell:resolve:env:(v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$ ]]; then diff --git a/src/lib/inference-credential.ts b/src/lib/inference-credential.ts index 57cc5fce933..3348d9706e5 100644 --- a/src/lib/inference-credential.ts +++ b/src/lib/inference-credential.ts @@ -10,22 +10,14 @@ export function managedInferenceApiKey( baseUrl: string, fallback: T, ): T | typeof NVIDIA_INFERENCE_PLACEHOLDER { - try { - const url = new URL(baseUrl); - if ( - url.protocol === "https:" && - url.hostname === "integrate.api.nvidia.com" && - url.port === "" && - (url.pathname === "/v1" || url.pathname === "/v1/") && - !url.username && - !url.password && - !url.search && - !url.hash - ) { - return NVIDIA_INFERENCE_PLACEHOLDER; - } - } catch { - // URL validation belongs to the route owner. + // Match the unnormalized URL, as startup and the Hermes policy reader do. + // URL parsing would silently accept empty ports, dot segments and encoded hosts. + const route = baseUrl.replace(/^[^/]+:\/\/[^/]+/u, (authority) => authority.toLowerCase()); + if (/^https:\/\/integrate\.api\.nvidia\.com(?::0*443)?\/v1\/?(?![\s\S])/u.test(route)) { + return NVIDIA_INFERENCE_PLACEHOLDER; + } + if (/^https:\/\/integrate\.api\.nvidia\.com(?::(?:0*443)?)?(?:[/?#]|(?![\s\S]))/u.test(route)) { + throw new Error("Native NVIDIA inference requires https://integrate.api.nvidia.com/v1."); } return fallback; } diff --git a/test/agents/hermes/hermes-managed-policy.test.ts b/test/agents/hermes/hermes-managed-policy.test.ts index c1da78e0ab9..1b165a37d96 100644 --- a/test/agents/hermes/hermes-managed-policy.test.ts +++ b/test/agents/hermes/hermes-managed-policy.test.ts @@ -6,6 +6,10 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; +import { + INVALID_NATIVE_NVIDIA_URLS, + NATIVE_NVIDIA_URLS, +} from "../../fixtures/native-nvidia-inference-urls"; import type { HermesBuildSettings } from "../../../agents/hermes/config/build-env.ts"; import { buildHermesManagedPolicy, @@ -77,7 +81,7 @@ function loadWithPython(document: unknown) { } describe("Hermes managed policy", () => { - it.each(["https://integrate.api.nvidia.com/v1", "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/"])( + it.each(NATIVE_NVIDIA_URLS)( "accepts the native NVIDIA inference placeholder at %s", (baseUrl) => { const policy = buildHermesManagedPolicy( @@ -90,6 +94,24 @@ describe("Hermes managed policy", () => { }, ); + it.each(INVALID_NATIVE_NVIDIA_URLS)( + "rejects ambiguous native NVIDIA routing at %j", + (baseUrl) => { + expect(() => buildHermesManagedPolicy({ ...SETTINGS, baseUrl }, {})).toThrow( + "Native NVIDIA inference requires https://integrate.api.nvidia.com/v1.", + ); + + const policy = buildHermesManagedPolicy({ ...SETTINGS, baseUrl: NATIVE_NVIDIA_URLS[0] }, {}); + const result = loadWithPython({ + ...policy, + config: { ...policy.config, model: { ...policy.config.model, base_url: baseUrl } }, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("Native NVIDIA inference requires"); + expect(result.stderr).not.toContain("do-not-echo"); + }, + ); + it.each([ ["https://integrate.api.nvidia.com/v1", "sk-OPENSHELL-PROXY-REWRITE"], ["https://inference.local/v1", "${NVIDIA_INFERENCE_API_KEY}"], diff --git a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts index 628a95c1dfe..48c2ca6c389 100644 --- a/test/agents/openclaw/runtime/auth-profile-boundary.test.ts +++ b/test/agents/openclaw/runtime/auth-profile-boundary.test.ts @@ -8,6 +8,7 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; +import { INVALID_NATIVE_NVIDIA_URLS } from "../../../fixtures/native-nvidia-inference-urls"; const START_SCRIPT = path.resolve(import.meta.dirname, "../../../../scripts/nemoclaw-start.sh"); const START_SOURCE = fs.readFileSync(START_SCRIPT, "utf-8"); @@ -134,7 +135,7 @@ function runStartupCredentialBoundary( AUTH_TEST_COMMAND: command, ...managedEnv, NVIDIA_INFERENCE_API_KEY: credentialValue, - ...(route === "native" || route.startsWith("https://integrate.api.nvidia.com:") + ...(route === "native" || route.includes("://") ? { NEMOCLAW_INFERENCE_BASE_URL: route === "native" ? "https://integrate.api.nvidia.com/v1" : route, @@ -157,6 +158,51 @@ function legacyProfile(provider = "inference", keyId = "NVIDIA_INFERENCE_API_KEY const legacyManagedProfile = legacyProfile(); describe("OpenClaw auth-profile boundary", () => { + it.each(INVALID_NATIVE_NVIDIA_URLS)("rejects %j before creating fresh auth state", (baseUrl) => { + const fixture = runBashAuthFixture({ ...managedEnv, NEMOCLAW_INFERENCE_BASE_URL: baseUrl }); + expect(fixture.status).toBe(1); + expect(fixture.stdout).toBe(""); + expect(fixture.stderr).toContain("Native NVIDIA inference requires"); + expect(fixture.stderr).not.toContain(managedEnv.NVIDIA_INFERENCE_API_KEY); + expect(fixture.stderr).not.toContain(managedEnv.NVIDIA_API_KEY); + expect(fixture.stderr).not.toContain("do-not-echo"); + expect(fs.existsSync(fixture.authPath)).toBe(false); + }); + + it.each(INVALID_NATIVE_NVIDIA_URLS)("rejects %j before changing legacy auth state", (baseUrl) => { + const fixture = runBashAuthFixture( + { ...managedEnv, NEMOCLAW_INFERENCE_BASE_URL: baseUrl }, + seedAuthProfile({ "inference:manual": legacyManagedProfile }), + ); + expect(fixture.status).toBe(1); + expect(fixture.stdout).toBe(""); + expect(fixture.stderr).toContain("Native NVIDIA inference requires"); + expect(fixture.stderr).not.toContain(managedEnv.NVIDIA_INFERENCE_API_KEY); + expect(fixture.stderr).not.toContain(managedEnv.NVIDIA_API_KEY); + expect(fixture.stderr).not.toContain("do-not-echo"); + expect(JSON.parse(fs.readFileSync(fixture.authPath, "utf-8"))).toEqual({ + "inference:manual": legacyManagedProfile, + }); + }); + + it.each( + INVALID_NATIVE_NVIDIA_URLS.flatMap( + (baseUrl) => + [ + [baseUrl, "root"], + [baseUrl, "non-root"], + ] as const, + ), + )("rejects %j before %s startup children", (baseUrl, kind) => { + const result = runStartupCredentialBoundary(kind, baseUrl); + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("Native NVIDIA inference requires"); + expect(result.stderr).not.toContain(managedEnv.NVIDIA_INFERENCE_API_KEY); + expect(result.stderr).not.toContain(managedEnv.NVIDIA_API_KEY); + expect(result.stderr).not.toContain("do-not-echo"); + }); + it.each([ ["default", undefined, "inference"], ["configured", "openai", "openai"], diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 00636d8d9a1..d0b2034e536 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -831,6 +831,7 @@ "test/e2e/fixtures/managed-image-receipt.ts" ], "fast": [ + "src/lib/actions/inference-set-patch-openclaw.test.ts", "src/lib/actions/inference-set-compatible-provider.test.ts", "test/e2e/support/retry-policy.test.ts", "test/e2e/support/compatible-anthropic-switch.test.ts", diff --git a/test/fixtures/native-nvidia-inference-urls.ts b/test/fixtures/native-nvidia-inference-urls.ts new file mode 100644 index 00000000000..af0303ac997 --- /dev/null +++ b/test/fixtures/native-nvidia-inference-urls.ts @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const NATIVE_NVIDIA_URLS = [ + "https://integrate.api.nvidia.com/v1", + "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/", + "https://integrate.api.nvidia.com:0443/v1", + "https://integrate.api.nvidia.com:000443/v1/", +]; + +export const INVALID_NATIVE_NVIDIA_URLS = [ + "https://integrate.api.nvidia.com:/v1", + "https://integrate.api.nvidia.com/./v1", + "https://integrate.api.nvidia.com/x/../v1", + "https://integrate.api.nvidia.com/%2e/v1", + "https://integrate.api.nvidia.com/V1", + "https://integrate.api.nvidia.com//v1", + "https://integrate.api.nvidia.com/v1?", + "https://integrate.api.nvidia.com/v1#", + "https://integrate.api.nvidia.com/v1?token=do-not-echo", + "https://integrate.api.nvidia.com/v1\n", +]; diff --git a/test/generation/generate-openclaw-native-nvidia-config.test.ts b/test/generation/generate-openclaw-native-nvidia-config.test.ts index f75d7f33f0d..940cbec3654 100644 --- a/test/generation/generate-openclaw-native-nvidia-config.test.ts +++ b/test/generation/generate-openclaw-native-nvidia-config.test.ts @@ -5,19 +5,31 @@ import { expect, it } from "vitest"; import { buildConfig } from "../../scripts/generate-openclaw-config.mts"; import { baseOpenClawGenerationEnv } from "../helpers/openclaw-env-fixture"; +import { + INVALID_NATIVE_NVIDIA_URLS, + NATIVE_NVIDIA_URLS, +} from "../fixtures/native-nvidia-inference-urls"; -it.each([ - "https://integrate.api.nvidia.com/v1", - "HTTPS://INTEGRATE.API.NVIDIA.COM:443/v1/", - "https://integrate.api.nvidia.com:0443/v1", - "https://integrate.api.nvidia.com:000443/v1/", -])("uses a resolvable credential for native NVIDIA inference at %s", (baseUrl) => { - const config = buildConfig({ - ...baseOpenClawGenerationEnv(), - NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", - NEMOCLAW_INFERENCE_BASE_URL: baseUrl, - }); - expect(config.models.providers.inference.apiKey).toBe("${NVIDIA_INFERENCE_API_KEY}"); +it.each(NATIVE_NVIDIA_URLS)( + "uses a resolvable credential for native NVIDIA inference at %s", + (baseUrl) => { + const config = buildConfig({ + ...baseOpenClawGenerationEnv(), + NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", + NEMOCLAW_INFERENCE_BASE_URL: baseUrl, + }); + expect(config.models.providers.inference.apiKey).toBe("${NVIDIA_INFERENCE_API_KEY}"); + }, +); + +it.each(INVALID_NATIVE_NVIDIA_URLS)("rejects an ambiguous native NVIDIA URL %j", (baseUrl) => { + expect(() => + buildConfig({ + ...baseOpenClawGenerationEnv(), + NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", + NEMOCLAW_INFERENCE_BASE_URL: baseUrl, + }), + ).toThrow("Native NVIDIA inference requires https://integrate.api.nvidia.com/v1."); }); it.each([ From 020c0ff9f5c3684573e7ab81edff1b20dfa6bd20 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 9 Oct 2026 13:24:58 -0400 Subject: [PATCH 08/12] test(e2e): isolate native switch regression fixtures Ambient provider, model, and hosted-mode settings caused three native-case assertions to fail without a product regression. Select the native provider explicitly and import environment-dependent helpers after controlling inputs. Assert the public credential and endpoint on the same provider registration. Observed all three failures before repair. The 50 focused tests and three ambient-override cases pass, along with formatting and CLI typechecking. Signed-off-by: Julie Yaunches --- ...mes-inference-switch-command-shape.test.ts | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/test/e2e/support/hermes-inference-switch-command-shape.test.ts b/test/e2e/support/hermes-inference-switch-command-shape.test.ts index b56365e237e..5245e06fd63 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -20,7 +20,6 @@ import { expectAuthenticatedProxyResolutionRequests, hasAuthenticatedProxyResolutionRequest, hostedInstallModel, - env, inferenceLocalMaxTokens, installHermes, mockAnthropicSwitchEnabled, @@ -44,6 +43,13 @@ import { describe("Hermes inference switch command shape", () => { afterEach(() => vi.unstubAllEnvs()); + async function nativeSwitchHelpers() { + vi.stubEnv("NEMOCLAW_E2E_USE_HOSTED_INFERENCE", "0"); + vi.stubEnv("NEMOCLAW_MODEL", undefined); + vi.resetModules(); + return import("../live/hermes-inference-switch-helpers.ts"); + } + function matchesApiKeyShape(line: string): boolean { return ( spawnSync("grep", ["-Eq", API_KEY_SHAPE_PATTERN], { @@ -164,7 +170,7 @@ describe("Hermes inference switch command shape", () => { }); it("accepts only the native NVIDIA credential reference on the native route", () => { - const [command, ...args] = apiKeyShapeCommand(); + const [command, ...args] = apiKeyShapeCommand(PUBLIC_NVIDIA_SWITCH_PROVIDER); const matches = (input: string) => spawnSync(command, args.slice(0, -1), { input, encoding: "utf8" }).status === 0; expect(matches(" api_key: ${NVIDIA_INFERENCE_API_KEY}\n")).toBe(true); @@ -203,12 +209,14 @@ describe("Hermes inference switch command shape", () => { ).toBe("initial-hosted-model"); }); - it("derives the native baseline model from the install environment", () => { + it("derives the native baseline model from the install environment", async () => { + const { env } = await nativeSwitchHelpers(); const installEnv = env("nvapi-public-fixture-key"); expect(hostedInstallModel(installEnv)).toBe("nvidia/nemotron-3-super-120b-a12b"); }); it("keeps the public proxy-resolution credential on the public NVIDIA endpoint", async () => { + const { prepareProxyResolutionRoute } = await nativeSwitchHelpers(); const command = vi.fn().mockResolvedValue({ exitCode: 0, stderr: "", @@ -220,9 +228,20 @@ describe("Hermes inference switch command shape", () => { mockBaseline: undefined, redactionValues: ["nvapi-public-fixture-key"], }); - expect(command.mock.calls[0]?.[1]).toContain( - "OPENAI_BASE_URL=https://integrate.api.nvidia.com/v1", - ); + expect(command.mock.calls[0]).toEqual([ + "openshell", + expect.arrayContaining([ + "provider", + "create", + "--credential", + "NVIDIA_INFERENCE_API_KEY", + "OPENAI_BASE_URL=https://integrate.api.nvidia.com/v1", + ]), + expect.objectContaining({ + env: expect.objectContaining({ NVIDIA_INFERENCE_API_KEY: "nvapi-public-fixture-key" }), + redactionValues: ["nvapi-public-fixture-key"], + }), + ]); }); it("keeps proxy-resolution evidence on a dedicated OpenAI provider", async () => { From f4273d6a3988eaf0ead02070e7c8e7aa166bfd51 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 9 Oct 2026 13:37:17 -0400 Subject: [PATCH 09/12] test(e2e): expect retained native Hermes route metadata The native baseline already uses nvidia-prod. Switching its model preserves endpoint and credential metadata and resolves the existing Hermes API mode; the E2E incorrectly expected all three fields to become null. Keep the four field assertions inline and use the native endpoint, scoped credential name, and runtime API as their expected values. A regression test reproduces the three null expectations before this repair and compares the corrected oracle against actual same-provider route preparation. A separate Anthropic case preserves its explicit metadata. The two focused support files pass 52 tests; the assertion census passes without a budget change. Live run 37958493753 attempt 2 established the endpoint mismatch and successful cleanup on published candidate 96057d206. Signed-off-by: Julie Yaunches --- test/e2e/live/hermes-inference-switch.test.ts | 38 +++++++++----- .../support/inference-switch-baseline.test.ts | 51 +++++++++++++++++++ 2 files changed, 75 insertions(+), 14 deletions(-) diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index d7b0673bc6a..1bf6fd3901b 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -67,6 +67,24 @@ function canonicalEndpoint(value: unknown): string | null { return typeof value === "string" ? new URL(value).toString() : null; } +export function expectedHermesRegistryMetadata(switchEndpointUrl: string | null) { + // Native installation already uses nvidia-prod; a model switch retains its metadata. + const publicSwitch = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER; + const durableEndpointUrl = publicSwitch + ? expectedBaseUrl() + : (switchEndpointUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL); + const durableCredentialEnv = publicSwitch + ? "NVIDIA_INFERENCE_API_KEY" + : switchEndpointUrl + ? "COMPATIBLE_ANTHROPIC_API_KEY" + : "COMPATIBLE_API_KEY"; + return { + endpointUrl: durableEndpointUrl, + credentialEnv: durableCredentialEnv, + preferredInferenceApi: RUNTIME_SWITCH_API, + }; +} + test( "Hermes inference set updates route/config and preserves live runtime", { @@ -336,23 +354,15 @@ test( .join("\n"), ); expect(state.session).toEqual(baselineSession); - const publicSwitch = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER; - const durableEndpointUrl = publicSwitch - ? null - : (switchEndpointUrl ?? - process.env.NEMOCLAW_ENDPOINT_URL ?? - DEFAULT_HOSTED_INFERENCE_BASE_URL); - const durableCredentialEnv = publicSwitch - ? null - : switchEndpointUrl - ? "COMPATIBLE_ANTHROPIC_API_KEY" - : "COMPATIBLE_API_KEY"; + const expectedMetadata = expectedHermesRegistryMetadata(switchEndpointUrl); expect(canonicalEndpoint(state.registry.sandboxes?.[SANDBOX_NAME]?.endpointUrl)).toBe( - canonicalEndpoint(durableEndpointUrl), + canonicalEndpoint(expectedMetadata.endpointUrl), + ); + expect(state.registry.sandboxes?.[SANDBOX_NAME]?.credentialEnv).toBe( + expectedMetadata.credentialEnv, ); - expect(state.registry.sandboxes?.[SANDBOX_NAME]?.credentialEnv).toBe(durableCredentialEnv); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.preferredInferenceApi).toBe( - publicSwitch ? null : RUNTIME_SWITCH_API, + expectedMetadata.preferredInferenceApi, ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.nimContainer).toBeNull(); progress.phase("exercise sandbox inference and Hermes API"); diff --git a/test/e2e/support/inference-switch-baseline.test.ts b/test/e2e/support/inference-switch-baseline.test.ts index 1c3d59427fd..bb39e8c6fe2 100644 --- a/test/e2e/support/inference-switch-baseline.test.ts +++ b/test/e2e/support/inference-switch-baseline.test.ts @@ -118,3 +118,54 @@ it.each([ }); }, ); + +it("matches retained native Hermes metadata from the real same-provider route preparation", async () => { + vi.resetModules(); + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); + vi.stubEnv("NEMOCLAW_SWITCH_INFERENCE_API", "openai-completions"); + const { expectedHermesRegistryMetadata } = + await import("../live/hermes-inference-switch.test.ts"); + const { prepareInferenceSetRoute } = + await import("../../../src/lib/actions/inference-set-route-containment.ts"); + const baseline = { + name: "hermes-switch", + agent: "hermes", + gatewayName: "nemoclaw", + gatewayPort: 8080, + provider: "nvidia-prod", + model: "nvidia/baseline", + endpointUrl: "https://integrate.api.nvidia.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + preferredInferenceApi: "openai-completions", + }; + const prepared = prepareInferenceSetRoute({ + entry: baseline, + sandboxName: baseline.name, + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + customRoute: {}, + session: null, + sandboxes: [baseline], + }); + const expected = expectedHermesRegistryMetadata(null); + expect(expected).toEqual({ + endpointUrl: "https://integrate.api.nvidia.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + preferredInferenceApi: "openai-completions", + }); + expect(prepared.preliminaryRegistryMetadata).toMatchObject(expected); +}); + +it("keeps explicit Hermes Anthropic metadata independent of the native baseline", async () => { + vi.resetModules(); + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "compatible-anthropic-endpoint"); + vi.stubEnv("NEMOCLAW_SWITCH_INFERENCE_API", "anthropic-messages"); + const { expectedHermesRegistryMetadata } = + await import("../live/hermes-inference-switch.test.ts"); + const endpoint = "http://host.openshell.internal:19120/v1"; + expect(expectedHermesRegistryMetadata(endpoint)).toEqual({ + endpointUrl: endpoint, + credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", + preferredInferenceApi: "openai-completions", + }); +}); From c69b4f86afb49722500653adb0d3c1aadab60edb Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 9 Oct 2026 13:56:07 -0400 Subject: [PATCH 10/12] test(e2e): verify OpenClaw credential references before redaction The live artifact boundary masks long apiKey values, including the native NVIDIA environment reference. The old config assertion compared this redacted value with the literal reference and failed after a valid switch. Classify the exact reference inside the sandbox before serialization and keep the existing strict config assertions and standard artifact redaction. Unexpected credentials produce an invalid classification, never a pass. Execute the real config probe on production-patched fixture JSON and apply the actual artifact redactor in support tests. This reproduces the live failure before the repair; 57 focused tests now pass, including five invalid credential cases. Assertion census passes without changing its budget. Run 37958493753 attempt 2 passed both Anthropic scenarios; native cleanup passed after the stale credential assertion. Final live rerun remains due. Signed-off-by: Julie Yaunches --- .../live/openclaw-inference-switch.test.ts | 19 ++++++- .../support/inference-switch-baseline.test.ts | 50 +++++++++++++++++-- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 2e573dfacda..7e1b986247b 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -615,9 +615,24 @@ async function readAndAssertOpenClawConfig( nativeNvidia?: boolean; }, ): Promise { + // Check the exact credential reference before artifact redaction masks apiKey values. + // Emit only classifications, never a configured credential or environment value. const configResult = await sandbox.exec( SANDBOX_NAME, - ["cat", "/sandbox/.openclaw/openclaw.json"], + [ + "node", + "-e", + [ + "const fs = require('node:fs');", + "const config = JSON.parse(fs.readFileSync(process.argv[1], 'utf8'));", + "for (const provider of Object.values(config.models?.providers ?? {})) {", + " const value = provider.apiKey;", + " provider.apiKey = value === '${NVIDIA_INFERENCE_API_KEY}' ? 'native' : value === 'unused' ? 'unused' : 'invalid';", + "}", + "console.log(JSON.stringify(config));", + ].join("\n"), + "/sandbox/.openclaw/openclaw.json", + ], { artifactName: expected.artifactName, env: commandEnv(home), @@ -634,7 +649,7 @@ async function readAndAssertOpenClawConfig( expect(config.agents?.defaults?.model?.primary).toBe(expectedPrimary); expect(provider?.baseUrl).toBe(expected.baseUrl); - expect(provider?.apiKey).toBe(expected.nativeNvidia ? "${NVIDIA_INFERENCE_API_KEY}" : "unused"); + expect(provider?.apiKey).toBe(expected.nativeNvidia ? "native" : "unused"); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; diff --git a/test/e2e/support/inference-switch-baseline.test.ts b/test/e2e/support/inference-switch-baseline.test.ts index bb39e8c6fe2..0f09dceb081 100644 --- a/test/e2e/support/inference-switch-baseline.test.ts +++ b/test/e2e/support/inference-switch-baseline.test.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { redactString } from "../fixtures/redaction.ts"; import { afterEach, expect, it, vi } from "vitest"; import { patchOpenClawInferenceConfig } from "../../../src/lib/actions/inference-set.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; @@ -87,6 +91,28 @@ it("requests structured route output instead of aligned terminal columns", async }); }); +function sandboxForOpenClawConfig(config: object) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "switch-config-probe-")); + disposables.push(() => fs.rmSync(directory, { recursive: true, force: true })); + const configPath = path.join(directory, "openclaw.json"); + fs.writeFileSync(configPath, JSON.stringify(config)); + return { + exec: vi.fn(async (_sandboxName: string, argv: string[]) => ({ + exitCode: 0, + stdout: redactString( + execFileSync( + argv[0]!, + argv + .slice(1) + .map((arg) => (arg === "/sandbox/.openclaw/openclaw.json" ? configPath : arg)), + { encoding: "utf8" }, + ), + ), + stderr: "", + })), + }; +} + it.each([ [ "nvidia-prod", @@ -106,9 +132,7 @@ it.each([ const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); const config = {}; patchOpenClawInferenceConfig(config, provider, model, inferenceApi); - const sandbox = { - exec: vi.fn(async () => ({ exitCode: 0, stdout: JSON.stringify(config), stderr: "" })), - }; + const sandbox = sandboxForOpenClawConfig(config); await assertOpenClawConfig(sandbox as never, "/tmp/switch-test-home", { model, inferenceApi, @@ -169,3 +193,23 @@ it("keeps explicit Hermes Anthropic metadata independent of the native baseline" preferredInferenceApi: "openai-completions", }); }); + +it.each(["unused", "nvapi-fixture-secret", "native", "${OTHER_API_KEY}", null])( + "rejects an incorrect native OpenClaw credential value after redaction: %s", + async (value) => { + const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); + const model = "nvidia/nemotron-3-super-120b-a12b"; + const config: any = {}; + patchOpenClawInferenceConfig(config, "nvidia-prod", model, "openai-completions"); + config.models.providers.inference.apiKey = value; + await expect( + assertOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { + model, + inferenceApi: "openai-completions", + baseUrl: "https://integrate.api.nvidia.com/v1", + artifactName: "invalid-native-credential", + nativeNvidia: true, + }), + ).rejects.toThrow(); + }, +); From 5e63fd0eca111abdcb8ede6806fd9d7cb08bbe99 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Fri, 9 Oct 2026 14:35:50 -0400 Subject: [PATCH 11/12] test(e2e): place OpenClaw switch regressions in mapped support tests The exact-head CI parity check failed because the new switch regressions were outside the existing live target's mapped fast-test owner. Move the OpenClaw cases into that owner, preserving each behavioral and negative credential assertion without changing the parity manifest or policy. Keep Hermes metadata regressions separate and load the production route helper before test execution so cold module setup does not consume the per-test timeout. The 30 affected support tests pass in isolation. The original committed diff reproduces the CI parity failure locally. Signed-off-by: Julie Yaunches --- .../support/inference-switch-baseline.test.ts | 160 +---------------- .../openclaw-inference-switch-helpers.test.ts | 162 +++++++++++++++++- 2 files changed, 164 insertions(+), 158 deletions(-) diff --git a/test/e2e/support/inference-switch-baseline.test.ts b/test/e2e/support/inference-switch-baseline.test.ts index 0f09dceb081..e397f7efd12 100644 --- a/test/e2e/support/inference-switch-baseline.test.ts +++ b/test/e2e/support/inference-switch-baseline.test.ts @@ -1,147 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { execFileSync } from "node:child_process"; -import { redactString } from "../fixtures/redaction.ts"; import { afterEach, expect, it, vi } from "vitest"; -import { patchOpenClawInferenceConfig } from "../../../src/lib/actions/inference-set.ts"; -import type { HostCliClient } from "../fixtures/clients/host.ts"; +import { prepareInferenceSetRoute } from "../../../src/lib/actions/inference-set-route-containment.ts"; -const captured = vi.hoisted(() => ({ test: vi.fn() })); vi.mock("../fixtures/e2e-test.ts", async () => ({ expect: (await import("vitest")).expect, - test: captured.test, + test: vi.fn(), })); -vi.mock("../fixtures/managed-image-receipt.ts", () => ({ - selectedE2eManagedImageReference: () => "example.invalid/openclaw@sha256:" + "a".repeat(64), -})); - -const disposables: Array<() => unknown> = []; -afterEach(async () => { - for (const dispose of disposables.splice(0).reverse()) await dispose(); - vi.restoreAllMocks(); - vi.unstubAllEnvs(); -}); - -it("keeps the OpenClaw native switch credential out of the authenticated baseline", async () => { - vi.resetModules(); - captured.test.mockClear(); - vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); - vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", "0"); - const exists = fs.existsSync; - vi.spyOn(fs, "existsSync").mockImplementation((file) => - String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), - ); - const result = { exitCode: 0, stdout: "", stderr: "" }; - const stop = new Error("onboarding captured"); - const nemoclaw = vi.fn(async (_args: string[], _options: { env: NodeJS.ProcessEnv }) => { - throw stop; - }); - await import("../live/openclaw-inference-switch.test.ts"); - const { startTestProgress } = await import("../fixtures/progress.ts"); - const progress = startTestProgress( - "baseline wiring", - captured.test.mock.calls[0]![1].meta.e2ePhases, - { logLine: () => undefined }, - ); - disposables.push(() => progress.stop()); - const run = captured.test.mock.calls[0]![2] as (input: object) => Promise; - 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 () => result) }, - progress, - runtimeProvider: { requireAvailable: vi.fn() }, - sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, - secrets: { required: vi.fn(() => "nvapi-public-fixture-key") }, - }), - ).rejects.toBe(stop); - const environment = nemoclaw.mock.calls[0]![1].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(); -}); -it("requests structured route output instead of aligned terminal columns", async () => { - const { getRouteOutput } = await import("../live/openclaw-inference-switch.test.ts"); - const command = vi.fn(async (_command: string, args: string[]) => ({ - exitCode: 0, - stderr: "", - stdout: args.includes("--json") - ? JSON.stringify({ provider: "compatible-anthropic-endpoint", model: "mock-anthropic-model" }) - : "Provider: compatible-anthropic-endpoint\nModel: mock-anthropic-model\n", - })); - const result = await getRouteOutput( - { command } as unknown as HostCliClient, - "/tmp/switch-test-home", - ); - expect(JSON.parse(result.stdout)).toEqual({ - provider: "compatible-anthropic-endpoint", - model: "mock-anthropic-model", - }); -}); - -function sandboxForOpenClawConfig(config: object) { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "switch-config-probe-")); - disposables.push(() => fs.rmSync(directory, { recursive: true, force: true })); - const configPath = path.join(directory, "openclaw.json"); - fs.writeFileSync(configPath, JSON.stringify(config)); - return { - exec: vi.fn(async (_sandboxName: string, argv: string[]) => ({ - exitCode: 0, - stdout: redactString( - execFileSync( - argv[0]!, - argv - .slice(1) - .map((arg) => (arg === "/sandbox/.openclaw/openclaw.json" ? configPath : arg)), - { encoding: "utf8" }, - ), - ), - stderr: "", - })), - }; -} - -it.each([ - [ - "nvidia-prod", - "nvidia/nemotron-3-super-120b-a12b", - "openai-completions", - "https://integrate.api.nvidia.com/v1", - ], - [ - "compatible-anthropic-endpoint", - "mock-anthropic-model", - "anthropic-messages", - "https://inference.local", - ], -])( - "checks the actual switched model budget for %s", - async (provider, model, inferenceApi, baseUrl) => { - const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); - const config = {}; - patchOpenClawInferenceConfig(config, provider, model, inferenceApi); - const sandbox = sandboxForOpenClawConfig(config); - await assertOpenClawConfig(sandbox as never, "/tmp/switch-test-home", { - model, - inferenceApi, - baseUrl, - artifactName: "switched-config", - nativeNvidia: provider === "nvidia-prod", - }); - }, -); +afterEach(() => vi.unstubAllEnvs()); it("matches retained native Hermes metadata from the real same-provider route preparation", async () => { vi.resetModules(); @@ -149,8 +17,6 @@ it("matches retained native Hermes metadata from the real same-provider route pr vi.stubEnv("NEMOCLAW_SWITCH_INFERENCE_API", "openai-completions"); const { expectedHermesRegistryMetadata } = await import("../live/hermes-inference-switch.test.ts"); - const { prepareInferenceSetRoute } = - await import("../../../src/lib/actions/inference-set-route-containment.ts"); const baseline = { name: "hermes-switch", agent: "hermes", @@ -193,23 +59,3 @@ it("keeps explicit Hermes Anthropic metadata independent of the native baseline" preferredInferenceApi: "openai-completions", }); }); - -it.each(["unused", "nvapi-fixture-secret", "native", "${OTHER_API_KEY}", null])( - "rejects an incorrect native OpenClaw credential value after redaction: %s", - async (value) => { - const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); - const model = "nvidia/nemotron-3-super-120b-a12b"; - const config: any = {}; - patchOpenClawInferenceConfig(config, "nvidia-prod", model, "openai-completions"); - config.models.providers.inference.apiKey = value; - await expect( - assertOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { - model, - inferenceApi: "openai-completions", - baseUrl: "https://integrate.api.nvidia.com/v1", - artifactName: "invalid-native-credential", - nativeNvidia: true, - }), - ).rejects.toThrow(); - }, -); diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index 2cdf8e0f5e6..3ea7009e23a 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -1,7 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { redactString } from "../fixtures/redaction.ts"; +import { patchOpenClawInferenceConfig } from "../../../src/lib/actions/inference-set.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; import { startTestProgress } from "../fixtures/progress.ts"; @@ -291,3 +298,156 @@ describe("openclaw-inference-switch mock-Anthropic baseline", () => { expect(baseline.env.NEMOCLAW_ENDPOINT_URL).toBe("http://10.0.0.5:9000/v1"); }); }); + +const captured = vi.hoisted(() => ({ test: vi.fn() })); +vi.mock("../fixtures/e2e-test.ts", async () => ({ + expect: (await import("vitest")).expect, + test: captured.test, +})); +vi.mock("../fixtures/managed-image-receipt.ts", () => ({ + selectedE2eManagedImageReference: () => "example.invalid/openclaw@sha256:" + "a".repeat(64), +})); + +const disposables: Array<() => unknown> = []; +afterEach(async () => { + for (const dispose of disposables.splice(0).reverse()) await dispose(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +it("keeps the OpenClaw native switch credential out of the authenticated baseline", async () => { + vi.resetModules(); + captured.test.mockClear(); + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); + vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", "0"); + const exists = fs.existsSync; + vi.spyOn(fs, "existsSync").mockImplementation((file) => + String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), + ); + const result = { exitCode: 0, stdout: "", stderr: "" }; + const stop = new Error("onboarding captured"); + const nemoclaw = vi.fn(async (_args: string[], _options: { env: NodeJS.ProcessEnv }) => { + throw stop; + }); + await import("../live/openclaw-inference-switch.test.ts"); + const { startTestProgress } = await import("../fixtures/progress.ts"); + const progress = startTestProgress( + "baseline wiring", + captured.test.mock.calls[0]![1].meta.e2ePhases, + { logLine: () => undefined }, + ); + disposables.push(() => progress.stop()); + const run = captured.test.mock.calls[0]![2] as (input: object) => Promise; + 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 () => result) }, + progress, + runtimeProvider: { requireAvailable: vi.fn() }, + sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, + secrets: { required: vi.fn(() => "nvapi-public-fixture-key") }, + }), + ).rejects.toBe(stop); + const environment = nemoclaw.mock.calls[0]![1].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(); +}); + +it("requests structured route output instead of aligned terminal columns", async () => { + const { getRouteOutput } = await import("../live/openclaw-inference-switch.test.ts"); + const command = vi.fn(async (_command: string, args: string[]) => ({ + exitCode: 0, + stderr: "", + stdout: args.includes("--json") + ? JSON.stringify({ provider: "compatible-anthropic-endpoint", model: "mock-anthropic-model" }) + : "Provider: compatible-anthropic-endpoint\nModel: mock-anthropic-model\n", + })); + const result = await getRouteOutput( + { command } as unknown as HostCliClient, + "/tmp/switch-test-home", + ); + expect(JSON.parse(result.stdout)).toEqual({ + provider: "compatible-anthropic-endpoint", + model: "mock-anthropic-model", + }); +}); + +function sandboxForOpenClawConfig(config: object) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "switch-config-probe-")); + disposables.push(() => fs.rmSync(directory, { recursive: true, force: true })); + const configPath = path.join(directory, "openclaw.json"); + fs.writeFileSync(configPath, JSON.stringify(config)); + return { + exec: vi.fn(async (_sandboxName: string, argv: string[]) => ({ + exitCode: 0, + stdout: redactString( + execFileSync( + argv[0]!, + argv + .slice(1) + .map((arg) => (arg === "/sandbox/.openclaw/openclaw.json" ? configPath : arg)), + { encoding: "utf8" }, + ), + ), + stderr: "", + })), + }; +} + +it.each([ + [ + "nvidia-prod", + "nvidia/nemotron-3-super-120b-a12b", + "openai-completions", + "https://integrate.api.nvidia.com/v1", + ], + [ + "compatible-anthropic-endpoint", + "mock-anthropic-model", + "anthropic-messages", + "https://inference.local", + ], +])( + "checks the actual switched model budget for %s", + async (provider, model, inferenceApi, baseUrl) => { + const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); + const config = {}; + patchOpenClawInferenceConfig(config, provider, model, inferenceApi); + const sandbox = sandboxForOpenClawConfig(config); + await assertOpenClawConfig(sandbox as never, "/tmp/switch-test-home", { + model, + inferenceApi, + baseUrl, + artifactName: "switched-config", + nativeNvidia: provider === "nvidia-prod", + }); + }, +); + +it.each(["unused", "nvapi-fixture-secret", "native", "${OTHER_API_KEY}", null])( + "rejects an incorrect native OpenClaw credential value after redaction: %s", + async (value) => { + const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); + const model = "nvidia/nemotron-3-super-120b-a12b"; + const config: any = {}; + patchOpenClawInferenceConfig(config, "nvidia-prod", model, "openai-completions"); + config.models.providers.inference.apiKey = value; + await expect( + assertOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { + model, + inferenceApi: "openai-completions", + baseUrl: "https://integrate.api.nvidia.com/v1", + artifactName: "invalid-native-credential", + nativeNvidia: true, + }), + ).rejects.toThrow(); + }, +); From 99e05872aee8de8cb53080ff6fbb6692b7557481 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Mon, 12 Oct 2026 10:37:24 -0400 Subject: [PATCH 12/12] test(e2e): isolate inference switch command probes Advisor identified support tests importing the executable live scenario. Move route and sandbox command producers to the existing helper with explicit inputs. Keep every live assertion inline and retain real command execution and artifact-redaction rejection coverage. Restore the Model Router diagnostic guidance lost during main integration. Observed three positive support cases fail before helper extraction; all 99 focused tests pass afterward. The assertion census remains unchanged at 1250 assertions across 77 files. --- test/e2e/README.md | 6 ++ .../live/openclaw-inference-switch-helpers.ts | 50 +++++++++++++++ .../live/openclaw-inference-switch.test.ts | 48 ++++---------- .../openclaw-inference-switch-helpers.test.ts | 63 ++++++++++++------- 4 files changed, 110 insertions(+), 57 deletions(-) diff --git a/test/e2e/README.md b/test/e2e/README.md index 2cdcf37aec6..b5aa7aa02fd 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -779,6 +779,12 @@ Failed targets still write a manifest for diagnosis, and the existing artifact u The manifest is secret-free diagnostic evidence. It does not replace the workflow job result or the strict `Release qualification` aggregate. +The `model-router-provider-routed-inference` target writes `router-diagnostics.json` before sandbox cleanup. +It summarizes the final 64 KiB of the router log as fixed status flags and a completion-response count. +It never copies log text, request content, or credentials into that file. +An unavailable log is recorded explicitly; a false flag does not prove that an unlogged event did not occur. +The cleanup registry captures diagnostics before destroying the sandbox and records capture failures separately from the test failure. + Run the planner locally to render the complete default selection as a Markdown table: ```bash diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index c6b8f3f4a69..a8fd0acb24a 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -4,6 +4,10 @@ // Fixture and response helpers shared by the openclaw-inference-switch live // target and fast e2e-support tests without gating on NEMOCLAW_RUN_LIVE_E2E=1. +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { CLI_ENTRYPOINT } from "../fixtures/paths.ts"; import type { RetryFailureClass } from "../../../tools/e2e/retry-evidence.mts"; import { startFakeOpenAiCompatibleServer, @@ -188,3 +192,49 @@ export function mockBaselineInference(endpointUrl: string): BaselineInferenceCon }, }; } + +/** Read the structured route through the same host CLI used by the live scenario. */ +export async function getRouteOutput( + host: HostCliClient, + options: { env: NodeJS.ProcessEnv; timeoutMs: number }, +): Promise { + return host.command("node", [CLI_ENTRYPOINT, "inference", "get", "--json"], { + ...options, + artifactName: "nemoclaw-inference-get-after-switch", + }); +} + +/** Validate the native handle inside the sandbox before artifact redaction. */ +export async function readOpenClawConfig( + sandbox: SandboxClient, + sandboxName: string, + options: { + env: NodeJS.ProcessEnv; + timeoutMs: number; + artifactName: string; + nativeNvidia?: boolean; + }, +): Promise { + return sandbox.exec( + sandboxName, + options.nativeNvidia + ? [ + "node", + "-e", + [ + 'const fs = require("node:fs");', + 'const config = JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', + "const provider = config.models?.providers?.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 handle = process.env.NVIDIA_INFERENCE_API_KEY;", + 'require("node:assert/strict").ok(/^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$/.test(handle ?? "") && provider?.apiKey === handle, "native credential reference mismatch");', + "delete provider.apiKey;", + "process.stdout.write(JSON.stringify(config));", + ].join(" "), + ] + : ["cat", "/sandbox/.openclaw/openclaw.json"], + { artifactName: options.artifactName, env: options.env, timeoutMs: options.timeoutMs }, + ); +} diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 600487b9aa7..bca85809f7a 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -51,6 +51,8 @@ import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; import { runBoundedRetry } from "../../../tools/e2e/retry-evidence.mts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { + getRouteOutput, + readOpenClawConfig, agentReplyContainsToken, anthropicToolCount, classifyExhaustedPostSwitchEvidence, @@ -530,13 +532,6 @@ async function openclawGatewayPid(sandbox: SandboxClient, home: string): Promise return result.stdout.trim(); } -export async function getRouteOutput(host: HostCliClient, home: string): Promise { - return runNemoclaw(host, home, ["inference", "get", "--json"], { - artifactName: "nemoclaw-inference-get-after-switch", - timeoutMs: COMMAND_TIMEOUT_MS, - }); -} - async function assertRegistryAndSession( home: string, options: { mockProvider?: MockAnthropicProvider; sandbox: SandboxClient }, @@ -617,32 +612,12 @@ async function readAndAssertOpenClawConfig( nativeNvidia?: boolean; }, ): Promise { - const configResult = await sandbox.exec( - SANDBOX_NAME, - expected.nativeNvidia - ? [ - "node", - "-e", - [ - 'const fs = require("node:fs");', - 'const config = JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', - "const provider = config.models?.providers?.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 handle = process.env.NVIDIA_INFERENCE_API_KEY;", - 'require("node:assert/strict").ok(/^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$/.test(handle ?? "") && provider?.apiKey === handle, "native credential reference mismatch");', - "delete provider.apiKey;", - "process.stdout.write(JSON.stringify(config));", - ].join(" "), - ] - : ["cat", "/sandbox/.openclaw/openclaw.json"], - { - artifactName: expected.artifactName, - env: commandEnv(home), - timeoutMs: COMMAND_TIMEOUT_MS, - }, - ); + const configResult = await readOpenClawConfig(sandbox, SANDBOX_NAME, { + nativeNvidia: expected.nativeNvidia, + artifactName: expected.artifactName, + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }); expect(configResult.exitCode, resultText(configResult)).toBe(0); const config = JSON.parse(configResult.stdout) as OpenClawConfig; const expectedProviderKey = @@ -665,7 +640,7 @@ async function readAndAssertOpenClawConfig( return selectedModel; } -export async function assertOpenClawConfig( +async function assertOpenClawConfig( sandbox: SandboxClient, home: string, expected: { @@ -1334,7 +1309,10 @@ test( } progress.phase("inspect route configuration and recorded state"); - const route = await getRouteOutput(host, home); + const route = await getRouteOutput(host, { + env: commandEnv(home), + timeoutMs: COMMAND_TIMEOUT_MS, + }); expect(route.exitCode, resultText(route)).toBe(0); const routeState = JSON.parse(route.stdout) as { provider?: unknown; model?: unknown }; expect(routeState.provider).toBe(SWITCH_PROVIDER); diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index fbf6c215577..5abcc20b46c 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -13,6 +13,8 @@ import type { HostCliClient } from "../fixtures/clients/host.ts"; import { startTestProgress } from "../fixtures/progress.ts"; import { + getRouteOutput, + readOpenClawConfig, agentReplyContainsToken, anthropicToolCount, classifyExhaustedPostSwitchEvidence, @@ -299,15 +301,6 @@ describe("openclaw-inference-switch mock-Anthropic baseline", () => { }); }); -const captured = vi.hoisted(() => ({ test: vi.fn() })); -vi.mock("../fixtures/e2e-test.ts", async () => ({ - expect: (await import("vitest")).expect, - test: captured.test, -})); -vi.mock("../fixtures/managed-image-receipt.ts", () => ({ - selectedE2eManagedImageReference: () => "example.invalid/openclaw@sha256:" + "a".repeat(64), -})); - const disposables: Array<() => unknown> = []; afterEach(async () => { for (const dispose of disposables.splice(0).reverse()) await dispose(); @@ -316,7 +309,6 @@ afterEach(async () => { }); it("requests structured route output instead of aligned terminal columns", async () => { - const { getRouteOutput } = await import("../live/openclaw-inference-switch.test.ts"); const command = vi.fn(async (_command: string, args: string[]) => ({ exitCode: 0, stderr: "", @@ -324,16 +316,47 @@ it("requests structured route output instead of aligned terminal columns", async ? JSON.stringify({ provider: "compatible-anthropic-endpoint", model: "mock-anthropic-model" }) : "Provider: compatible-anthropic-endpoint\nModel: mock-anthropic-model\n", })); - const result = await getRouteOutput( - { command } as unknown as HostCliClient, - "/tmp/switch-test-home", - ); + const result = await getRouteOutput({ command } as unknown as HostCliClient, { + env: { HOME: "/tmp/switch-test-home" }, + timeoutMs: 1000, + }); expect(JSON.parse(result.stdout)).toEqual({ provider: "compatible-anthropic-endpoint", model: "mock-anthropic-model", }); }); +async function probeOpenClawConfig( + sandbox: Parameters[0], + home: string, + expected: { + model: string; + inferenceApi: string; + artifactName: string; + nativeNvidia?: boolean; + }, +) { + const result = await readOpenClawConfig(sandbox, "switch-test", { + artifactName: expected.artifactName, + env: { HOME: home }, + timeoutMs: 1000, + nativeNvidia: expected.nativeNvidia, + }); + expect(result.exitCode).toBe(0); + const config = JSON.parse(result.stdout); + const providerKey = expected.inferenceApi === "anthropic-messages" ? "anthropic" : "inference"; + const provider = config.models.providers[providerKey]; + expect(config.agents.defaults.model.primary).toBe(`${providerKey}/${expected.model}`); + expect(provider.api).toBe(expected.inferenceApi); + expect(provider.apiKey).toBe(expected.nativeNvidia ? undefined : "unused"); + const model = provider.models.find((entry: { id: string }) => entry.id === expected.model); + expect( + expected.inferenceApi === "anthropic-messages" + ? model.maxTokens > 0 + : model.maxTokens === undefined, + ).toBe(true); +} + const scopedNativeHandle = "openshell:resolve:env:v1_NVIDIA_INFERENCE_API_KEY"; function sandboxForOpenClawConfig(config: object, handle = scopedNativeHandle) { @@ -363,12 +386,11 @@ function sandboxForOpenClawConfig(config: object, handle = scopedNativeHandle) { } it("checks the actual switched native model budget with a materialized handle", async () => { - const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); const model = "nvidia/nemotron-3-super-120b-a12b"; const config: any = {}; patchOpenClawInferenceConfig(config, "nvidia-prod", model, "openai-completions"); config.models.providers.inference.apiKey = scopedNativeHandle; - await assertOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { + await probeOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { model, inferenceApi: "openai-completions", artifactName: "switched-native-config", @@ -377,7 +399,6 @@ it("checks the actual switched native model budget with a materialized handle", }); it("checks the actual switched Anthropic model budget", async () => { - const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); const model = "mock-anthropic-model"; const config = {}; patchOpenClawInferenceConfig( @@ -386,7 +407,7 @@ it("checks the actual switched Anthropic model budget", async () => { model, "anthropic-messages", ); - await assertOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { + await probeOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { model, inferenceApi: "anthropic-messages", artifactName: "switched-anthropic-config", @@ -403,13 +424,12 @@ it.each([ "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", null, ])("rejects an incorrect native OpenClaw credential value after redaction: %s", async (value) => { - const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); const model = "nvidia/nemotron-3-super-120b-a12b"; const config: any = {}; patchOpenClawInferenceConfig(config, "nvidia-prod", model, "openai-completions"); config.models.providers.inference.apiKey = value; await expect( - assertOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { + probeOpenClawConfig(sandboxForOpenClawConfig(config) as never, "/tmp/switch-home", { model, inferenceApi: "openai-completions", artifactName: "invalid-native-credential", @@ -421,13 +441,12 @@ it.each([ it.each(["", "nvapi-fixture-secret", "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY"])( "rejects a missing or unscoped native handle even when config matches: %s", async (handle) => { - const { assertOpenClawConfig } = await import("../live/openclaw-inference-switch.test.ts"); const model = "nvidia/nemotron-3-super-120b-a12b"; const config: any = {}; patchOpenClawInferenceConfig(config, "nvidia-prod", model, "openai-completions"); config.models.providers.inference.apiKey = handle; await expect( - assertOpenClawConfig(sandboxForOpenClawConfig(config, handle) as never, "/tmp/switch-home", { + probeOpenClawConfig(sandboxForOpenClawConfig(config, handle) as never, "/tmp/switch-home", { model, inferenceApi: "openai-completions", artifactName: "invalid-native-handle",