From d5870ef9780fb4cb9ed578733235da181d5b5930 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:35:43 -0700 Subject: [PATCH 001/133] feat(inference): use native NVIDIA provider attachments Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-budget.json | 20 +- .../quickstart-langchain-deepagents-code.mdx | 6 +- docs/get-started/quickstart.mdx | 6 +- docs/inference/use-nvidia-endpoints.mdx | 13 +- .../nemoclaw-nvidia-inference-v1.yaml | 33 ++ .../scripts/nemotron-inference-fix.js | 13 +- src/commands/credentials.test.ts | 2 +- src/lib/actions/credentials-add.ts | 28 +- .../credentials-provider-adapter.test.ts | 40 +++ src/lib/actions/credentials/reset.ts | 7 +- src/lib/actions/inference-get.test.ts | 30 ++ src/lib/actions/inference-get.ts | 33 ++ .../inference-set-failure-handling.test.ts | 4 +- ...ence-set-gateway-route-containment.test.ts | 61 +++- .../inference-set-local-provider.test.ts | 5 +- ...rence-set-openclaw-gateway-restart.test.ts | 41 ++- .../inference-set-openclaw-run.test.ts | 119 +++++-- .../inference-set-patch-hermes.test.ts | 2 +- .../inference-set-patch-openclaw.test.ts | 21 +- src/lib/actions/inference-set.test-support.ts | 104 +++++- src/lib/actions/inference-set.ts | 236 ++++++++++--- src/lib/actions/sandbox/gateway-target.ts | 4 + .../inference-invocation-probe.test.ts | 14 + .../sandbox/inference-invocation-probe.ts | 26 +- .../sandbox/inference-route-health.test.ts | 38 +++ .../actions/sandbox/inference-route-health.ts | 31 ++ .../sandbox/launch-readiness/health.ts | 30 ++ .../actions/sandbox/rebuild-dcode-target.ts | 6 + src/lib/actions/sandbox/status-snapshot.ts | 17 +- .../config/live-export-source-test-fixture.ts | 4 +- .../adapters/openshell/sandbox-observer.ts | 5 + src/lib/inference/config.test.ts | 11 +- src/lib/inference/config.ts | 26 ++ .../inference/gateway-route-compatibility.ts | 5 + src/lib/inference/native-nvidia.test.ts | 204 +++++++++++ src/lib/inference/native-nvidia/index.ts | 318 ++++++++++++++++++ src/lib/onboard.ts | 2 +- .../created-sandbox-finalization.test.ts | 2 +- src/lib/onboard/dcode-selection-drift.test.ts | 12 +- .../sandbox-create-intent-boundary.test.ts | 44 +++ src/lib/onboard/machine/handlers/sandbox.ts | 25 +- src/lib/onboard/providers.ts | 8 + .../sandbox-create-intent-resolution.ts | 3 + .../onboard/sandbox-create-intent-types.ts | 3 + src/lib/onboard/sandbox-create-intent.ts | 2 + .../orchestration-native-nvidia.test.ts | 99 ++++++ .../onboard/sandbox-create/orchestration.ts | 22 +- .../sandbox-create/provider-publication.ts | 29 ++ src/lib/onboard/sandbox-registration.test.ts | 33 ++ src/lib/onboard/sandbox-registration.ts | 18 + src/lib/onboard/setup-inference.test.ts | 97 +++++- src/lib/onboard/setup-inference.ts | 65 +++- .../registry-recovery-seeded-paths.test.ts | 2 +- src/lib/state/registry.ts | 22 ++ src/lib/state/registry/route-reservation.ts | 8 + src/lib/state/registry/types.ts | 3 + src/lib/verify-deployment.ts | 2 + .../live/hermes-inference-switch-helpers.ts | 21 +- test/e2e/live/hermes-inference-switch.test.ts | 25 +- .../live/openclaw-inference-switch.test.ts | 68 ++-- .../e2e/live/public-nvidia-switch-provider.ts | 29 -- .../public-nvidia-switch-provider.test.ts | 38 +-- .../managed/nemotron-inference-fix.test.ts | 35 +- 63 files changed, 1970 insertions(+), 310 deletions(-) create mode 100644 managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml create mode 100644 src/lib/inference/native-nvidia.test.ts create mode 100644 src/lib/inference/native-nvidia/index.ts create mode 100644 src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index af77410a72b..d9a51b18cc5 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,28 +15,28 @@ "testFileCount": 77, "liveFileCount": 186, "direct": { - "expectCalls": 1275, - "matcherAssertions": 1254, + "expectCalls": 1273, + "matcherAssertions": 1252, "nodeAssertions": 104, "namedAssertionHelpers": 436, "failCalls": 0, "throwGuards": 60, "objectFieldAssertions": 166, - "assertionPoints": 2020, + "assertionPoints": 2018, "generatedProbeBlocks": 91, "generatedProbeConditions": 221 }, "unique": { - "expectCalls": 1700, - "matcherAssertions": 1674, + "expectCalls": 1698, + "matcherAssertions": 1672, "nodeAssertions": 127, "namedAssertionHelpers": 681, "failCalls": 1, "throwGuards": 540, "objectFieldAssertions": 243, - "assertionPoints": 3266, - "generatedProbeBlocks": 213, - "generatedProbeConditions": 726 + "assertionPoints": 3264, + "generatedProbeBlocks": 212, + "generatedProbeConditions": 725 }, "fileMetricOrder": [ "directExpectCalls", @@ -67,7 +67,7 @@ "test/e2e/live/hermes-discord.test.ts": [10,25,17,64,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [49,55,60,80,2], + "test/e2e/live/hermes-inference-switch.test.ts": [48,54,59,79,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], @@ -94,7 +94,7 @@ "test/e2e/live/onboard-repair.test.ts": [21,25,21,25,0], "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], - "test/e2e/live/openclaw-inference-switch.test.ts": [47,53,48,55,2], + "test/e2e/live/openclaw-inference-switch.test.ts": [46,52,47,54,1], "test/e2e/live/openclaw-skill-cli.test.ts": [10,14,10,14,1], "test/e2e/live/openclaw-slack-pairing.test.ts": [11,18,26,84,10], "test/e2e/live/openshell-credential-generation-window.test.ts": [42,92,43,112,18], diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index 2ae73fbf8b5..62ebb21c709 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -165,7 +165,7 @@ The wizard asks for an inference provider, model, required credential, and sandb When you edit inference, NemoClaw clears the credential staged for the discarded selection. NemoClaw preserves the sandbox name. When you edit the sandbox name, NemoClaw preserves the inference selection. The sandbox prompt shows the prior name as its default. After you apply the configuration, routine editing ends. If inference setup fails and offers a `back` recovery action, you can return to provider and model selection and then review the updated configuration again. Provider registration, inference setup, policy selection, and sandbox creation then continue forward. The default Deep Agents sandbox name is `deepagents-code`. Use a distinct name, such as `my-deepagents`, when you run Deep Agents, Hermes, and OpenClaw sandboxes side by side. Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) for provider-specific prompts. -The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider pointed at `https://inference.local/v1`, uses a scoped placeholder API key for that managed route, and sets `use_responses_api = false` for Chat Completions compatibility. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. NemoClaw/OpenShell keeps real provider credentials in credential handling and does not write them into the Deep Agents config file. Deep Agents Code reaches `inference.local` through the managed OpenShell L7 proxy rather than direct sandbox DNS. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. +The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. NVIDIA Endpoints uses `https://integrate.api.nvidia.com/v1` through a least-privilege OpenShell provider attached to the sandbox. Other managed providers use `https://inference.local/v1`. Both paths put a scoped placeholder in the agent config instead of the real provider key. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. @@ -183,7 +183,7 @@ Deep Agents Code runs from a NemoClaw-managed Python virtual environment at `/op ### State and Backup -Deep Agents Code state lives under `/sandbox/.deepagents`. NemoClaw snapshot and rebuild flows preserve the app state directory and skills when those paths exist. During managed re-onboarding, NemoClaw restores the allowlisted UI and thread preferences, validated native interpreter settings, and native `startup.mode` from `config.toml`. Freshly generated model routing, update settings, and provider metadata remain authoritative; unknown, privileged, invalid, and security-sensitive keys are dropped. User-authored `hooks.json` is also preserved, so review its executable commands before restoring a snapshot from another workspace. NemoClaw recreates the sandbox when its live `dcode identity` output is unreadable or does not match the selected provider and model, then records the selection only after the restored runtime passes the same check. Run `nemoclaw snapshot create` after active `dcode` tasks finish. For `langchain-deepagents-code` sandboxes, NemoClaw refuses backup when it detects an active `dcode` task or cannot verify that the state tree is idle. `.deepagents/.mcp.json` is the agent-native MCP source. Managed entries contain only URLs and OpenShell placeholders, and rebuild carries them through its bounded transaction handoff rather than reconstructing them from the host registry. Service credentials remain in OpenShell provider state. NemoClaw intentionally does not back up `.deepagents/.env`. If `.deepagents/.state/auth.json` contains upstream credentials, or `.deepagents/.state/chatgpt-auth.json` exists, the managed Deep Agents Code launch paths refuse to start until that credential state is removed. Before a managed Deep Agents Code rebuild changes the sandbox, NemoClaw selects its recorded OpenShell gateway, tests the recorded inference route through `https://inference.local`, and prepares the replacement from the current agent configuration, OpenShell policy and providers, model, and build inputs with a pinned base and fingerprinted context. Initial failures stop before backup. After backup, NemoClaw rechecks the target, route, and retained build inputs before changing MCP state, then checks again after MCP preparation and before stopping inference or deleting the old sandbox. If the final check fails, NemoClaw restores the previous source state and keeps the existing sandbox intact. Rebuild carries the complete current OpenShell policy forward, including Deep Agents Code `tavily`, custom entries, and trusted host-side edits. The recorded observability choice is preserved unless explicitly overridden. +Deep Agents Code state lives under `/sandbox/.deepagents`. NemoClaw snapshot and rebuild flows preserve the app state directory and skills when those paths exist. During managed re-onboarding, NemoClaw restores the allowlisted UI and thread preferences, validated native interpreter settings, and native `startup.mode` from `config.toml`. Freshly generated model routing, update settings, and provider metadata remain authoritative; unknown, privileged, invalid, and security-sensitive keys are dropped. User-authored `hooks.json` is also preserved, so review its executable commands before restoring a snapshot from another workspace. NemoClaw recreates the sandbox when its live `dcode identity` output is unreadable or does not match the selected provider and model, then records the selection only after the restored runtime passes the same check. Run `nemoclaw snapshot create` after active `dcode` tasks finish. For `langchain-deepagents-code` sandboxes, NemoClaw refuses backup when it detects an active `dcode` task or cannot verify that the state tree is idle. `.deepagents/.mcp.json` is the agent-native MCP source. Managed entries contain only URLs and OpenShell placeholders, and rebuild carries them through its bounded transaction handoff rather than reconstructing them from the host registry. Service credentials remain in OpenShell provider state. NemoClaw intentionally does not back up `.deepagents/.env`. If `.deepagents/.state/auth.json` contains upstream credentials, or `.deepagents/.state/chatgpt-auth.json` exists, the managed Deep Agents Code launch paths refuse to start until that credential state is removed. Before a managed Deep Agents Code rebuild changes the sandbox, NemoClaw selects its recorded OpenShell gateway, tests the recorded inference path, and prepares the replacement from the current agent configuration, OpenShell policy and providers, model, and build inputs with a pinned base and fingerprinted context. Initial failures stop before backup. After backup, NemoClaw rechecks the target, route, and retained build inputs before changing MCP state, then checks again after MCP preparation and before stopping inference or deleting the old sandbox. If the final check fails, NemoClaw restores the previous source state and keeps the existing sandbox intact. Rebuild carries the complete current OpenShell policy forward, including Deep Agents Code `tavily`, custom entries, and trusted host-side edits. The recorded observability choice is preserved unless explicitly overridden. @@ -253,7 +253,7 @@ nemo-deepagents snapshot create --name before-change If you upgrade from a release that persisted LangSmith environment values, rebuild each existing Deep Agents Code sandbox so its image includes the corrected `start.sh`. If an existing sandbox displays `Choose a Recommended Model`, rebuild it so its image includes the managed startup behavior. -`status` reports the selected harness as a terminal runtime and prints the interactive/headless command shape. If `status` reports `Runtime health: degraded` with an OOM kill count, rebuild the sandbox to restore the terminal runtime. Proxy launchers and startup scripts are baked into the sandbox image. After upgrading NemoClaw from a release with older Deep Agents Code routing, rebuild each existing sandbox before troubleshooting `inference.local` connectivity. NemoClaw v0.0.78 and newer clients fail closed when a pre-v0.0.78 sandbox image lacks the trusted `/usr/local/lib/nemoclaw/dcode-managed-exec` route-probe helper, even when the installed Deep Agents Code version still matches the managed manifest. Rebuild the sandbox to install that image-owned helper before retrying `status`, `doctor`, `connect`, or onboarding recovery. There is no dashboard port or long-running gateway process for this harness. +`status` reports the selected harness as a terminal runtime and prints the interactive/headless command shape. If `status` reports `Runtime health: degraded` with an OOM kill count, rebuild the sandbox to restore the terminal runtime. Proxy launchers and startup scripts are baked into the sandbox image. After upgrading from a release that used `inference.local` for NVIDIA Endpoints, recreate each NVIDIA sandbox during onboarding. NemoClaw does not add the required native provider attachment to an existing beta sandbox. NemoClaw v0.0.78 and newer clients fail closed when a pre-v0.0.78 sandbox image lacks the trusted `/usr/local/lib/nemoclaw/dcode-managed-exec` route-probe helper, even when the installed Deep Agents Code version still matches the managed manifest. Rebuild the sandbox to install that image-owned helper before retrying `status`, `doctor`, `connect`, or onboarding recovery. There is no dashboard port or long-running gateway process for this harness. ## Next Steps diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index 349b50dd0e8..af3ebd9cb8f 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -373,7 +373,9 @@ Use these details when your first-run path needs more control. - After confirmation, NemoClaw registers the selected provider with the OpenShell gateway and sets the `inference.local` route. + After confirmation, NemoClaw registers the selected provider with OpenShell. + Most providers use the shared `inference.local` route. + NVIDIA Endpoints uses a least-privilege provider attached to the sandbox instead. The wizard asks whether to enable web search and offers Brave Search or Tavily Search. Provide `BRAVE_API_KEY` for Brave Search or `TAVILY_API_KEY` for Tavily Search when prompted. NemoClaw validates the selected key before it creates the sandbox, registers a sandbox-scoped OpenShell provider, and writes only an OpenShell resolver placeholder into the OpenClaw configuration. @@ -410,7 +412,7 @@ Use these details when your first-run path needs more control. The selector can include destinations such as GitHub, Jira, Slack, Telegram, or local inference. Press `r` to switch a selected preset between read-only and read-write when it supports both modes. - Use the onboarding summary to verify that the sandbox gateway, dashboard port forward, and `inference.local` route are reachable. + Use the onboarding summary to verify that the sandbox gateway, dashboard port forward, and selected inference path are reachable. When web search is enabled, it also checks the selected provider configuration and sends a real search request through sandbox egress. Treat an unreachable route or HTTP 5xx response as a failed readiness check: onboarding marks the sandbox not ready and exits non-zero. Restore the configured endpoint or proxy, run `nemoclaw onboard --resume` to complete the retained onboarding session, then rerun `nemoclaw status` to verify the route. diff --git a/docs/inference/use-nvidia-endpoints.mdx b/docs/inference/use-nvidia-endpoints.mdx index 5baa5f2be75..ef945f65e4b 100644 --- a/docs/inference/use-nvidia-endpoints.mdx +++ b/docs/inference/use-nvidia-endpoints.mdx @@ -10,12 +10,14 @@ content: type: "how_to" --- NVIDIA Endpoints routes NemoClaw to models hosted on [build.nvidia.com](https://build.nvidia.com) through an OpenAI-compatible API. -The sandbox keeps using `inference.local` while OpenShell forwards requests to the NVIDIA endpoint. +NemoClaw attaches a least-privilege OpenShell provider to the sandbox, and the agent calls the NVIDIA endpoint directly through that provider. +The provider allows only model discovery and Chat Completions requests from the supported agent binaries. ## Credential Set `NVIDIA_INFERENCE_API_KEY` in the host shell before onboarding. -NemoClaw applies the `nvapi-` prefix check only to this credential and keeps the key on the host. +NemoClaw applies the `nvapi-` prefix check only to this credential and stores the key in OpenShell provider state. +The sandbox receives a placeholder, not the real key. ## Model Choices @@ -39,10 +41,17 @@ If you enter `back` at the NVIDIA API key prompt, the wizard returns to provider The wizard validates a manual model entry against the catalog before it continues. If the live catalog is unavailable or does not contain safe model IDs, the wizard warns you and uses the bundled fallback list. + +Sandboxes created by an earlier release used the shared `inference.local` route and do not have the attached NVIDIA provider receipt. +NemoClaw does not migrate these beta sandboxes automatically. +Recreate the sandbox during onboarding to use the native provider path. + + ## Validation NemoClaw validates NVIDIA Endpoints through `/v1/chat/completions` only. It skips `/v1/responses` because NVIDIA Build does not expose that route. +Readiness sends the same request from inside the sandbox through the attached OpenShell provider. The wizard retries transient upstream failures before it reports a provider failure. ## Related Topics diff --git a/managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml new file mode 100644 index 00000000000..079f53978be --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-nvidia-inference-v1 +display_name: NemoClaw NVIDIA Hosted Inference +description: Native NVIDIA hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: NVIDIA hosted inference API key + env_vars: + - NVIDIA_INFERENCE_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: integrate.api.nvidia.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1/models" } + - allow: { method: POST, path: "/v1/chat/completions" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/nemoclaw-blueprint/scripts/nemotron-inference-fix.js b/nemoclaw-blueprint/scripts/nemotron-inference-fix.js index d8b3344bf78..4ff43f622a8 100644 --- a/nemoclaw-blueprint/scripts/nemotron-inference-fix.js +++ b/nemoclaw-blueprint/scripts/nemotron-inference-fix.js @@ -98,8 +98,8 @@ // field (the endpoint returns `reasoning_content` either way), so the field // carries no behavior to preserve. // -// Scope: the `nvidia/nemotron-3-` model family when the managed -// `inference.local` route currently selects nvidia-prod. The image-baked +// Scope: the `nvidia/nemotron-3-` model family when the NemoClaw-managed +// route or attached OpenShell provider currently selects nvidia-prod. The image-baked // NEMOCLAW_UPSTREAM_PROVIDER establishes the onboarding route; after an // in-place provider switch, OpenClaw's private request marker is authoritative // and this preload removes it before forwarding. Ultra, Super, and Nano all @@ -167,7 +167,7 @@ // // Scope boundary: this preload runs inside NemoClaw-managed sandboxes // where the chat-completions destination is the OpenShell-gateway - // `inference.local` route bound to NVIDIA Build. The path+model regex + // NVIDIA Build route. The path+model regex // is the intentional trust boundary; non-sandbox OpenAI-compatible // callers do not load this preload. var TOOL_LESS_SYSTEM_PROMPT_RULES = [ @@ -393,14 +393,17 @@ function isManagedBuildHost(host, upstreamProvider) { return ( isNvidiaBuildUpstream(upstreamProvider) && - /^inference\.local(?::\d+)?$/i.test(String(host || '')) + /^(?:inference\.local(?::\d+)?|integrate\.api\.nvidia\.com(?::443)?)$/i.test( + String(host || ''), + ) ); } function isManagedBuildFetch(input, upstreamProvider) { if (!isNvidiaBuildUpstream(upstreamProvider)) return false; try { - return new URL(fetchUrl(input)).hostname.toLowerCase() === 'inference.local'; + var hostname = new URL(fetchUrl(input)).hostname.toLowerCase(); + return hostname === 'inference.local' || hostname === 'integrate.api.nvidia.com'; } catch (_e) { return false; } diff --git a/src/commands/credentials.test.ts b/src/commands/credentials.test.ts index 5b4e3091d2b..d102a91bc3a 100644 --- a/src/commands/credentials.test.ts +++ b/src/commands/credentials.test.ts @@ -343,7 +343,7 @@ describe("credentials oclif adapter source coverage", () => { expect(mocks.prompt).not.toHaveBeenCalled(); expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledWith( - ["provider", "delete", "-g", "nemoclaw", "nvidia-prod"], + ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], { ignoreError: true, stdio: ["ignore", "pipe", "pipe"], diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index d0c68f3ccfe..24e0194192d 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -13,6 +13,11 @@ import type { OpenShellGatewayTarget } from "../adapters/openshell/sandbox-obser import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../adapters/openshell/timeouts"; import { resolveAgentNameAlias } from "../agent/aliases"; import { CLI_NAME } from "../cli/branding"; +import { + NVIDIA_HOSTED_LOGICAL_PROVIDER, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + NVIDIA_HOSTED_NATIVE_PROVIDER, +} from "../inference/native-nvidia"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, TAVILY_PROVIDER_PROFILE_AGENTS, @@ -254,6 +259,8 @@ export async function runCredentialsAddAction( } const normalizedType = type.toLowerCase(); + const nativeNvidiaCredentialAlias = + provider === NVIDIA_HOSTED_LOGICAL_PROVIDER && normalizedType === "nvidia"; const isTavily = normalizedType === TAVILY_PROVIDER_PROFILE_ID || normalizedType === HERMES_TAVILY_PROVIDER_PROFILE_ID; @@ -273,7 +280,12 @@ export async function runCredentialsAddAction( ]); } } - const effectiveType = isTavily ? webSearchProviderProfileId(normalizedType, agentName) : type; + const effectiveType = nativeNvidiaCredentialAlias + ? NVIDIA_HOSTED_NATIVE_PROFILE_ID + : isTavily + ? webSearchProviderProfileId(normalizedType, agentName) + : type; + const effectiveProvider = nativeNvidiaCredentialAlias ? NVIDIA_HOSTED_NATIVE_PROVIDER : provider; const compatibilityWarnings = normalizedType === TAVILY_PROVIDER_PROFILE_ID && !agentName ? [ @@ -399,12 +411,14 @@ export async function runCredentialsAddAction( // Registration records this provider as an explicit extra-provider intent. // Rebuild validates that intent against current source-backed MCP entries; // orphaned providers retained by conservative MCP removal are not intent. - const recordedReservation = recordExtraProvider(provider); + const recordedReservation = nativeNvidiaCredentialAlias + ? false + : recordExtraProvider(effectiveProvider); let keepReservation = false; try { const result = await providerAdapter.createProvider({ target, - name: provider, + name: effectiveProvider, type: providerType, credentials: credentials.map((credential) => ({ name: credential, @@ -427,7 +441,11 @@ export async function runCredentialsAddAction( const lines = [` Could not register provider '${provider}'.`]; if (isUncertainProviderCreateError(result.error)) { - const recovery = await reconcileUncertainProviderCreate(provider, target, providerAdapter); + const recovery = await reconcileUncertainProviderCreate( + effectiveProvider, + target, + providerAdapter, + ); keepReservation = recovery.keepReservation; lines.push(` ${result.error.message}`, ...recovery.lines); return fail(lines); @@ -443,7 +461,7 @@ export async function runCredentialsAddAction( } return fail(lines); } finally { - if (recordedReservation && !keepReservation) forgetExtraProvider(provider); + if (recordedReservation && !keepReservation) forgetExtraProvider(effectiveProvider); } }); } diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 3dcdae8759f..058bd4076a8 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -121,6 +121,46 @@ describe("credential actions use typed OpenShell provider results", () => { expect(JSON.stringify(result)).not.toContain("credential-value"); }); + it("maps the NVIDIA credential alias to the internal native provider", async () => { + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "host-only-nvidia-value"); + const recordExtraProvider = vi.fn(() => true); + setGlobalCliActionRuntimeHooksForTest({ + recoverNamedGatewayRuntime: async () => ({ recovered: true }), + recordExtraProvider, + forgetExtraProvider: () => true, + }); + const adapter = providerAdapter(); + + const result = await runCredentialsAddAction( + { + provider: "nvidia-prod", + type: "nvidia", + credentials: ["NVIDIA_INFERENCE_API_KEY"], + configPairs: [], + fromExisting: false, + }, + { providerAdapter: adapter }, + ); + + expect(result.exitCode).toBe(0); + expect(adapter.importProviderProfile).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + profilePath: expect.stringMatching(/provider-profiles\/nemoclaw-nvidia-inference-v1\.yaml$/u), + timeoutMs: 30_000, + }); + expect(adapter.createProvider).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "host-only-nvidia-value" }], + config: [], + fromExisting: false, + timeoutMs: 30_000, + }); + expect(recordExtraProvider).not.toHaveBeenCalled(); + expect(JSON.stringify(result)).not.toContain("host-only-nvidia-value"); + }); + it("registers both Langfuse keys through the checked-in endpoint profile (#10840)", async () => { vi.stubEnv("LANGFUSE_PUBLIC_KEY", "pk-lf-host-only"); vi.stubEnv("LANGFUSE_SECRET_KEY", "sk-lf-host-only"); diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index d8fd32202ab..723f109b7c6 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -14,6 +14,10 @@ import { PROVIDER_NAME_VALID_PATTERN, } from "../../name-validation"; import { CLI_NAME } from "../../cli/branding"; +import { + NVIDIA_HOSTED_LOGICAL_PROVIDER, + NVIDIA_HOSTED_NATIVE_PROVIDER, +} from "../../inference/native-nvidia"; import { isBridgeProviderName, recoverCredentialGatewayTargetOrExit, @@ -90,6 +94,7 @@ export async function runCredentialsResetAction( deps: CredentialsResetDeps = {}, ): Promise { const key = input.provider; + const providerName = key === NVIDIA_HOSTED_LOGICAL_PROVIDER ? NVIDIA_HOSTED_NATIVE_PROVIDER : key; if (!PROVIDER_NAME_VALID_PATTERN.test(key)) { return fail([ " Provider name must be 1-128 chars, start with a letter, and use only letters, digits, '.', '_', or '-'.", @@ -120,7 +125,7 @@ export async function runCredentialsResetAction( if (!target) return fail(recoveryFailureLines); const providerAdapter = deps.providerAdapter ?? createCliOpenShellProviderAdapter(); - const recovery = await deleteProviderWithRecovery(key, target, providerAdapter); + const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter); if ( !recovery.ok && diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index 707e123d94b..e60ba29acf7 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -172,6 +172,36 @@ function expectBoundedAffectedDiagnostics(result: InferenceGetResult, output: st } describe("runInferenceGet", () => { + it("reads a recorded native NVIDIA route without consulting the shared gateway route", async () => { + const deps = createDeps(configuredRoute("stale-provider", "stale-model")); + const sandbox = { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + nativeNvidiaProviderAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }, + }; + deps.getDefaultSandbox = () => "alpha"; + deps.getSandbox = () => sandbox; + + await expect(runInferenceGet({}, deps)).resolves.toEqual({ + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + endpointUrl: "https://integrate.api.nvidia.com/v1", + }); + expect(deps.observeInferenceRoute).not.toHaveBeenCalled(); + expect(deps.log.mock.calls.map(([line]) => line)).toEqual([ + "Provider: nvidia-prod", + "Model: nvidia/nemotron-3-super-120b-a12b", + "Endpoint: https://integrate.api.nvidia.com/v1", + ]); + }); + it("prints the live provider and model", async () => { const deps = createDeps(configuredRoute("nvidia-prod", "nvidia/model")); diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index f177ea48715..fa0e0ffc070 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -20,11 +20,17 @@ import { type GatewayInferenceRoute, } from "../inference/gateway-route-compatibility"; import { parseHttpsPinRouteId } from "../inference/https-pin-runtime"; +import { + isNativeNvidiaProvider, + NVIDIA_HOSTED_NATIVE_ENDPOINT, + normalizeNativeNvidiaProviderAttachment, +} from "../inference/native-nvidia"; import { inspectManagedLlamaCppOwnership } from "../inference/llama-cpp/managed-state"; import { valueLooksLikeSecret } from "../security/credential-filter"; import { ConfigCorruptError, ConfigPermissionError } from "../state/config-io"; import { isPublishedSandboxRegistration } from "../state/registry/route-reservation"; import { + getDefaultSandboxTargetName, getKnownSandboxTarget, getPersistedSandboxTargetGatewayName, getSandboxTargetGatewayName, @@ -61,6 +67,7 @@ export type InferenceEndpointStatus = export interface InferenceGetDeps { inferenceRouteObserver: OpenShellInferenceRouteObserver; getSandbox?: typeof getKnownSandboxTarget; + getDefaultSandbox?: typeof getDefaultSandboxTargetName; getSandboxTargetGatewayName: typeof getSandboxTargetGatewayName; listSandboxes: typeof listPersistedSandboxTargets; log: (message?: string) => void; @@ -80,6 +87,7 @@ export class InferenceGetError extends Error { function defaultDeps(): InferenceGetDeps { return { inferenceRouteObserver: createSynchronousCliOpenShellInferenceRouteObserver(captureOpenshell), + getDefaultSandbox: getDefaultSandboxTargetName, getSandboxTargetGatewayName, listSandboxes: listPersistedSandboxTargets, log: console.log, @@ -301,6 +309,31 @@ export async function runInferenceGet( options: InferenceGetOptions = {}, deps: InferenceGetDeps = defaultDeps(), ): Promise { + const selectedSandboxName = options.sandboxName ?? deps.getDefaultSandbox?.() ?? null; + const selectedSandbox = selectedSandboxName + ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) + : null; + if ( + selectedSandbox && + isNativeNvidiaProvider(selectedSandbox.provider) && + normalizeNativeNvidiaProviderAttachment(selectedSandbox.nativeNvidiaProviderAttachment) + ) { + const payload: InferenceGetResult = { + provider: selectedSandbox.provider ?? null, + model: selectedSandbox.model ?? null, + endpointUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + }; + if (!options.quiet) { + if (options.json) { + deps.log(JSON.stringify(payload, null, 2)); + } else { + deps.log(`Provider: ${formatRouteValueForDisplay(payload.provider)}`); + deps.log(`Model: ${formatRouteValueForDisplay(payload.model)}`); + deps.log(`Endpoint: ${formatRouteValueForDisplay(NVIDIA_HOSTED_NATIVE_ENDPOINT)}`); + } + } + return payload; + } let gatewayName: string; try { gatewayName = deps.getSandboxTargetGatewayName(options.sandboxName); diff --git a/src/lib/actions/inference-set-failure-handling.test.ts b/src/lib/actions/inference-set-failure-handling.test.ts index 95a5b261245..d973f014b83 100644 --- a/src/lib/actions/inference-set-failure-handling.test.ts +++ b/src/lib/actions/inference-set-failure-handling.test.ts @@ -97,7 +97,7 @@ describe("runInferenceSet failure handling", () => { const deps = createDeps({ config: {}, openshellStatus: 17 }); await expect( - runInferenceSet({ provider: "nvidia-prod", model: "nvidia/model-a" }, deps), + runInferenceSet({ provider: "openai-api", model: "openai/model-a" }, deps), ).rejects.toThrow(/OpenShell inference route update failed/); expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); @@ -207,7 +207,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/model-a" }, + { provider: "openai-api", model: "openai/model-a" }, deps, ).catch((e: Error) => e); diff --git a/src/lib/actions/inference-set-gateway-route-containment.test.ts b/src/lib/actions/inference-set-gateway-route-containment.test.ts index affa6d23a98..2d37f40abbd 100644 --- a/src/lib/actions/inference-set-gateway-route-containment.test.ts +++ b/src/lib/actions/inference-set-gateway-route-containment.test.ts @@ -81,16 +81,19 @@ describe("runtime shared gateway route containment", () => { it("warns and re-points a same-gateway provider/model-only route (#11890)", async () => { const deps = createDeps({ config: {}, - entries: [entry("alpha"), entry("stopped-peer")], + entries: [ + entry("alpha", { provider: "openrouter-api", model: "openrouter/model-a" }), + entry("stopped-peer", { provider: "openrouter-api", model: "openrouter/model-a" }), + ], defaultSandbox: "alpha", }); await expect( runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/model-b", sandboxName: "alpha" }, + { provider: "openrouter-api", model: "openrouter/model-b", sandboxName: "alpha" }, deps, ), - ).resolves.toMatchObject({ sandboxName: "alpha", model: "nvidia/model-b" }); + ).resolves.toMatchObject({ sandboxName: "alpha", model: "openrouter/model-b" }); expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( [ @@ -99,9 +102,9 @@ describe("runtime shared gateway route containment", () => { "-g", "nemoclaw", "--provider", - "nvidia-prod", + "openrouter-api", "--model", - "nvidia/model-b", + "openrouter/model-b", ], expect.objectContaining({ ignoreError: true }), ); @@ -113,7 +116,9 @@ describe("runtime shared gateway route containment", () => { message.includes("Setting OpenShell inference route"), ); expect(warningIndex).toBeGreaterThanOrEqual(0); - expect(messages[warningIndex]).toContain("'stopped-peer' (nvidia-prod / nvidia/model-a)"); + expect(messages[warningIndex]).toContain( + "'stopped-peer' (openrouter-api / openrouter/model-a)", + ); expect(warningIndex).toBeLessThan(mutationIndex); }); @@ -122,7 +127,12 @@ describe("runtime shared gateway route containment", () => { const deps = createDeps({ config: {}, entries: [ - entry("alpha", { gatewayName: "nemoclaw-9090", gatewayPort: 9090 }), + entry("alpha", { + gatewayName: "nemoclaw-9090", + gatewayPort: 9090, + provider: "openrouter-api", + model: "openrouter/model-a", + }), entry("default-gateway-peer"), ], defaultSandbox: "alpha", @@ -131,10 +141,10 @@ describe("runtime shared gateway route containment", () => { await expect( runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/model-b", sandboxName: "alpha" }, + { provider: "openrouter-api", model: "openrouter/model-b", sandboxName: "alpha" }, deps, ), - ).resolves.toMatchObject({ sandboxName: "alpha", model: "nvidia/model-b" }); + ).resolves.toMatchObject({ sandboxName: "alpha", model: "openrouter/model-b" }); expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( [ @@ -143,9 +153,9 @@ describe("runtime shared gateway route containment", () => { "-g", "nemoclaw-9090", "--provider", - "nvidia-prod", + "openrouter-api", "--model", - "nvidia/model-b", + "openrouter/model-b", ], expect.objectContaining({ ignoreError: true }), ); @@ -155,7 +165,18 @@ describe("runtime shared gateway route containment", () => { vi.stubEnv("OPENSHELL_GATEWAY", "other-gateway"); const deps = createDeps({ config: {}, - entries: [entry("alpha", { gatewayName: "nemoclaw-9090", gatewayPort: 9090 })], + entries: [ + entry("alpha", { + gatewayName: "nemoclaw-9090", + gatewayPort: 9090, + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }), + ], defaultSandbox: "alpha", }); await runInferenceSet( @@ -660,7 +681,13 @@ describe("runtime shared gateway route containment", () => { it("serializes same-gateway provider/model mutations and warns about route impact (#11890)", async () => { const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-route-lock-")); try { - const entries = [entry("route-lock-alpha"), entry("route-lock-beta")]; + const entries = [ + entry("route-lock-alpha", { + provider: "openrouter-api", + model: "openrouter/model-a", + }), + entry("route-lock-beta"), + ]; const deps = createDeps({ config: { agents: { defaults: { model: {} } } }, entries, @@ -682,7 +709,11 @@ describe("runtime shared gateway route containment", () => { const results = await Promise.allSettled([ runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/model-a", sandboxName: entries[0].name }, + { + provider: "openrouter-api", + model: "openrouter/model-a", + sandboxName: entries[0].name, + }, deps, ), runInferenceSet( @@ -698,7 +729,7 @@ describe("runtime shared gateway route containment", () => { ), ).toHaveLength(2); expect(entries).toEqual([ - expect.objectContaining({ provider: "nvidia-prod", model: "nvidia/model-a" }), + expect.objectContaining({ provider: "openrouter-api", model: "openrouter/model-a" }), expect.objectContaining({ provider: "anthropic-prod", model: "claude-new" }), ]); expect( diff --git a/src/lib/actions/inference-set-local-provider.test.ts b/src/lib/actions/inference-set-local-provider.test.ts index 38f203d08d7..a1316ac7835 100644 --- a/src/lib/actions/inference-set-local-provider.test.ts +++ b/src/lib/actions/inference-set-local-provider.test.ts @@ -75,10 +75,7 @@ describe("runInferenceSet local-provider verification", () => { session: baseSession(), }); - await runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b" }, - deps, - ); + await runInferenceSet({ provider: "openrouter", model: "openai/gpt-5.4-mini" }, deps); expect(deps.calls.validateLocalProvider).not.toHaveBeenCalled(); expect(deps.calls.ensureLocalProviderReachable).not.toHaveBeenCalled(); 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 147c783d28d..f26ed16beb5 100644 --- a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts +++ b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts @@ -7,6 +7,13 @@ import { runInferenceSet } from "./inference-set"; import { defaultInferenceGatewayRestart } from "./inference-set-gateway-restart"; import { baseSession, createDeps } from "./inference-set.test-support"; +const nativeNvidiaReceipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", +}; + describe("runInferenceSet OpenClaw gateway restart", () => { it("pins restart readiness and forwards to the recorded gateway (#11764)", async () => { vi.stubEnv("OPENSHELL_GATEWAY", "other-gateway"); @@ -40,14 +47,26 @@ describe("runInferenceSet OpenClaw gateway restart", () => { headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod", }, - models: [{ id: "nvidia/model-a", name: "inference/nvidia/model-a" }], + models: [ + { + id: "nvidia/model-a", + name: "inference/nvidia/model-a", + compat: { supportsStore: false }, + }, + ], }, }, }, }; const deps = createDeps({ config, - entry: { name: "alpha", agent: "openclaw", provider: "nvidia-prod", model: "nvidia/model-a" }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/model-a", + nativeNvidiaProviderAttachment: nativeNvidiaReceipt, + }, session: baseSession({ provider: "nvidia-prod", model: "nvidia/model-a" }), }); @@ -181,20 +200,32 @@ describe("runInferenceSet OpenClaw gateway restart", () => { mode: "merge", providers: { inference: { - baseUrl: "https://inference.local/v1", + baseUrl: "https://integrate.api.nvidia.com/v1", apiKey: "unused", api: "openai-completions", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod", }, - models: [{ id: "nvidia/model-a", name: "inference/nvidia/model-a" }], + models: [ + { + id: "nvidia/model-a", + name: "inference/nvidia/model-a", + compat: { supportsStore: false }, + }, + ], }, }, }, }; const deps = createDeps({ config, - entry: { name: "alpha", agent: "openclaw", provider: "nvidia-prod", model: "nvidia/model-a" }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/model-a", + nativeNvidiaProviderAttachment: nativeNvidiaReceipt, + }, session: baseSession({ provider: "nvidia-prod", model: "nvidia/model-a" }), }); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 97bb6896d2c..cf0f5931650 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -1,13 +1,95 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import type { OpenClawConfigUpdate } from "../sandbox/config"; import type { ConfigObject } from "../security/credential-filter"; import { runInferenceSet } from "./inference-set"; import { baseSession, createDeps } from "./inference-set.test-support"; describe("runInferenceSet OpenClaw routing", () => { + it("requires recreation instead of silently migrating a legacy NVIDIA sandbox", async () => { + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/legacy-model", + }, + }); + + await expect( + runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model" }, deps), + ).rejects.toThrow("Recreate this beta sandbox"); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); + }); + + it("detaches native NVIDIA access only after another provider is healthy", async () => { + let attached = true; + const detachProvider = vi.fn(async () => { + attached = false; + return { ok: true, value: { changed: true } }; + }); + const providerAdapter = { + getProvider: vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { + id: "11111111-2222-4333-8444-555555555555", + resourceVersion: 1, + }, + }, + })), + detachProvider, + listProviderAttachments: vi.fn(async () => ({ + ok: true, + value: { names: attached ? ["nemoclaw-nvidia-prod-v1"] : [] }, + })), + } as unknown as OpenShellProviderAdapter; + const deps = createDeps({ + config: { + agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, + models: { providers: {} }, + }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + providerAdapter, + }); + + await runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps); + + expect(detachProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + sandboxName: "alpha", + providerName: "nemoclaw-nvidia-prod-v1", + }), + ); + expect(deps.calls.restartSandboxGateway).toHaveBeenCalledOnce(); + expect(deps.calls.restartSandboxGateway.mock.invocationCallOrder[0]).toBeLessThan( + detachProvider.mock.invocationCallOrder[0], + ); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith("alpha", { + nativeNvidiaProviderAttachment: undefined, + }); + }); + it.each([ ["adding", false], ["updating", true], @@ -50,15 +132,20 @@ describe("runInferenceSet OpenClaw routing", () => { (update) => update.dotpath === "models.providers.inference", ); const selectedModel = alreadyExists - ? { ...requestedModel, name: "inference/nvidia/new-model" } + ? { + ...requestedModel, + name: "inference/nvidia/new-model", + compat: { supportsStore: false }, + } : { id: "nvidia/new-model", name: "inference/nvidia/new-model", params: { temperature: 0.3 }, + compat: { supportsStore: false }, }; expect(providerUpdate?.value).toEqual({ api: "openai-completions", - baseUrl: "https://inference.local/v1", + baseUrl: "https://integrate.api.nvidia.com/v1", apiKey: "unused", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod" }, models: alreadyExists ? [otherModel, selectedModel] : [selectedModel, otherModel], @@ -160,20 +247,11 @@ describe("runInferenceSet OpenClaw routing", () => { deps, ); - expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( - [ - "inference", - "set", - "-g", - "nemoclaw", - "--provider", - "nvidia-prod", - "--model", - "nvidia/nemotron-3-super-120b-a12b", - "--no-verify", - ], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 }, - ); + expect( + deps.calls.captureOpenshell.mock.calls.filter( + ([args]) => args[0] === "inference" && args[1] === "set", + ), + ).toEqual([]); expect(config.agents).toEqual({ defaults: { model: { primary: "inference/nvidia/nemotron-3-super-120b-a12b" }, @@ -218,16 +296,19 @@ describe("runInferenceSet OpenClaw routing", () => { expect.objectContaining({ provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - credentialEnv: null, endpointUrl: null, + credentialEnv: null, nimContainer: null, preferredInferenceApi: null, + nativeNvidiaProviderAttachment: expect.objectContaining({ + providerName: "nemoclaw-nvidia-prod-v1", + }), }), ]); expect(deps.getSession()).toMatchObject({ provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - endpointUrl: "https://inference.local/v1", + endpointUrl: "https://integrate.api.nvidia.com/v1", }); expect(result).toMatchObject({ sandboxName: "alpha", diff --git a/src/lib/actions/inference-set-patch-hermes.test.ts b/src/lib/actions/inference-set-patch-hermes.test.ts index ed5f537bac6..61b47018703 100644 --- a/src/lib/actions/inference-set-patch-hermes.test.ts +++ b/src/lib/actions/inference-set-patch-hermes.test.ts @@ -146,7 +146,7 @@ describe("patchHermesInferenceConfig", () => { expect(config.model).toEqual({ default: "nvidia/nemotron-3-super-120b-a12b", provider: "custom", - base_url: "https://inference.local/v1", + base_url: "https://integrate.api.nvidia.com/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL, }); }); diff --git a/src/lib/actions/inference-set-patch-openclaw.test.ts b/src/lib/actions/inference-set-patch-openclaw.test.ts index d163ba7281b..780684464e8 100644 --- a/src/lib/actions/inference-set-patch-openclaw.test.ts +++ b/src/lib/actions/inference-set-patch-openclaw.test.ts @@ -81,7 +81,7 @@ describe("patchOpenClawInferenceConfig", () => { mode: "merge", providers: { inference: { - baseUrl: "https://inference.local/v1", + baseUrl: "https://integrate.api.nvidia.com/v1", apiKey: "unused", api: "openai-completions", models: [ @@ -89,6 +89,7 @@ describe("patchOpenClawInferenceConfig", () => { id: "nvidia/nemotron-3-super-120b-a12b", name: "inference/nvidia/nemotron-3-super-120b-a12b", reasoning: true, + compat: { supportsStore: false }, }, { id: "moonshotai/kimi-k2.6", @@ -150,11 +151,15 @@ describe("patchOpenClawInferenceConfig", () => { }); expect((config.models as ConfigObject).providers).toEqual({ inference: { - baseUrl: "https://inference.local/v1", + baseUrl: "https://integrate.api.nvidia.com/v1", apiKey: "unused", api: "openai-completions", models: [ - { id: "nvidia/new-model", name: "inference/nvidia/new-model" }, + { + id: "nvidia/new-model", + name: "inference/nvidia/new-model", + compat: { supportsStore: false }, + }, { id: "old-model", name: "inference/nvidia/old-model" }, { id: "secondary-model", name: "inference/nvidia/secondary-model" }, ], @@ -202,10 +207,16 @@ describe("patchOpenClawInferenceConfig", () => { mode: "merge", providers: { inference: { - baseUrl: "https://inference.local/v1", + baseUrl: "https://integrate.api.nvidia.com/v1", apiKey: "unused", api: "openai-completions", - models: [{ id: "nvidia/model-a", name: "inference/nvidia/model-a" }], + models: [ + { + id: "nvidia/model-a", + name: "inference/nvidia/model-a", + compat: { supportsStore: false }, + }, + ], }, }, }, diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index 622b1ee3e5a..c0a16b02f83 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -4,6 +4,11 @@ import { vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; +import { + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + NVIDIA_HOSTED_NATIVE_PROVIDER, +} from "../inference/native-nvidia"; import type { AgentConfigTarget } from "../sandbox/config"; import type { ConfigObject, ConfigValue } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; @@ -58,6 +63,69 @@ function defaultCaptureOpenshell( return { status, output, stdout: output, stderr: "" }; } +function nativeAwareProviderAdapter(base: OpenShellProviderAdapter): OpenShellProviderAdapter { + const providerId = "11111111-2222-4333-8444-555555555555"; + let providerPresent = false; + const attachments = new Set(); + const isNative = (providerName: string): boolean => + providerName === NVIDIA_HOSTED_NATIVE_PROVIDER; + return { + ...base, + importProviderProfile: async (request) => + request.profilePath.endsWith(`${NVIDIA_HOSTED_NATIVE_PROFILE_ID}.yaml`) + ? ({ ok: true } as const) + : await base.importProviderProfile(request), + getProvider: async (request) => { + if (!isNative(request.providerName)) return await base.getProvider(request); + if (!providerPresent) { + return { + ok: false, + error: { kind: "command", reason: "not_found", message: "provider not found" }, + } as const; + } + return { + ok: true, + value: { + name: NVIDIA_HOSTED_NATIVE_PROVIDER, + type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + credentialKeys: [NVIDIA_HOSTED_CREDENTIAL_ENV], + configKeys: [], + revision: { id: providerId, resourceVersion: 1 }, + }, + } as const; + }, + createProvider: async (request) => { + if (!isNative(request.name)) return await base.createProvider(request); + providerPresent = true; + return { ok: true } as const; + }, + updateProvider: async (request) => { + if (!isNative(request.providerName)) return await base.updateProvider(request); + providerPresent = true; + return { ok: true } as const; + }, + attachProvider: async (request) => { + if (!isNative(request.providerName)) return await base.attachProvider(request); + attachments.add(request.sandboxName); + return { ok: true } as const; + }, + detachProvider: async (request) => { + if (!isNative(request.providerName)) return await base.detachProvider(request); + const changed = attachments.delete(request.sandboxName); + return { ok: true, value: { changed } } as const; + }, + listProviderAttachments: async (request) => { + if (!providerPresent) return await base.listProviderAttachments(request); + return { + ok: true, + value: { + names: attachments.has(request.sandboxName) ? [NVIDIA_HOSTED_NATIVE_PROVIDER] : [], + }, + } as const; + }, + }; +} + export function baseSession(overrides: Partial = {}): Session { return { version: 1, @@ -279,23 +347,25 @@ export function createDeps(options: { }; const providerAdapter = options.providerAdapter ?? - createCliOpenShellProviderAdapter({ - run: (args, runOptions) => { - const result = calls.captureOpenshell(args, { - ...(runOptions.env ? { env: runOptions.env } : {}), - ignoreError: true, - includeStreams: true, - ...(runOptions.maxBuffer ? { maxBuffer: runOptions.maxBuffer } : {}), - timeout: runOptions.timeout, - }); - return { - status: result.status, - stdout: result.stdout || result.stderr ? result.stdout : result.output, - stderr: result.stderr, - ...("error" in result && result.error ? { error: result.error } : {}), - }; - }, - }); + nativeAwareProviderAdapter( + createCliOpenShellProviderAdapter({ + run: (args, runOptions) => { + const result = calls.captureOpenshell(args, { + ...(runOptions.env ? { env: runOptions.env } : {}), + ignoreError: true, + includeStreams: true, + ...(runOptions.maxBuffer ? { maxBuffer: runOptions.maxBuffer } : {}), + timeout: runOptions.timeout, + }); + return { + status: result.status, + stdout: result.stdout || result.stderr ? result.stdout : result.output, + stderr: result.stderr, + ...("error" in result && result.error ? { error: result.error } : {}), + }; + }, + }), + ); return { getDefaultSandbox: () => defaultSandbox, getSandbox: (name: string) => sandboxes[name] ?? null, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 7be514b68ec..8d453525c27 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -10,7 +10,14 @@ import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; import { getProviderSelectionConfig, getSandboxInferenceConfig, + detachNativeNvidiaProvider, + ensureNativeNvidiaProvider, + ensureNativeNvidiaProviderAttached, + isNativeNvidiaProvider, + NVIDIA_HOSTED_CREDENTIAL_ENV, + normalizeNativeNvidiaProviderAttachment, resolveAgentInferenceApi, + type NativeNvidiaProviderAttachment, type SandboxInferenceConfig, } from "../inference/config"; import { resolveContextWindowForModel } from "../inference/context-window"; @@ -924,6 +931,125 @@ function openshellInferenceSetArgs(options: { return args; } +function assertNativeNvidiaMigrationReady(input: { + provider: string; + previousProvider: string; + previousAttachment?: NativeNvidiaProviderAttachment; + sandboxName: string; +}): void { + if ( + isNativeNvidiaProvider(input.provider) && + isNativeNvidiaProvider(input.previousProvider) && + !input.previousAttachment + ) { + throw new InferenceSetError( + `Sandbox '${input.sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before changing its NVIDIA model.`, + 2, + ); + } +} + +async function prepareNativeNvidiaSelection(input: { + provider: string; + previousAttachment?: NativeNvidiaProviderAttachment; + gatewayName: string; + sandboxName: string; + deps: InferenceSetDeps; +}): Promise<{ + attachment?: NativeNvidiaProviderAttachment; + attachmentChanged: boolean; +}> { + if (!isNativeNvidiaProvider(input.provider)) return { attachmentChanged: false }; + const target = { kind: "named", gatewayName: input.gatewayName } as const; + const ensured = await ensureNativeNvidiaProvider({ + adapter: input.deps.providerAdapter, + target, + credentialValue: input.deps.resolveCredentialValue(NVIDIA_HOSTED_CREDENTIAL_ENV) || null, + ...(input.previousAttachment ? { expected: input.previousAttachment } : {}), + }); + const attached = await ensureNativeNvidiaProviderAttached({ + adapter: input.deps.providerAdapter, + target, + sandboxName: input.sandboxName, + expected: ensured, + }); + return { attachment: attached.receipt, attachmentChanged: attached.changed }; +} + +async function applyInferenceRouteSelection(input: { + nativeNvidia: boolean; + provider: string; + model: string; + gatewayName: string; + noVerify: boolean; + retryProviderNotFound: boolean; + deps: InferenceSetDeps; +}): Promise { + if (input.nativeNvidia) { + input.deps.log(` Using attached native NVIDIA provider: ${input.provider} / ${input.model}`); + return; + } + input.deps.log(` Setting OpenShell inference route: ${input.provider} / ${input.model}`); + const setInferenceRoute = () => + input.deps.captureOpenshell( + openshellInferenceSetArgs({ + gatewayName: input.gatewayName, + provider: input.provider, + model: input.model, + noVerify: input.noVerify, + }), + { + ignoreError: true, + includeStreams: true, + maxBuffer: OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER, + }, + ); + let result = setInferenceRoute(); + if ( + result.status !== 0 && + input.retryProviderNotFound && + openshellReportsProviderNotFound( + `${result.stderr ?? ""}\n${result.stdout ?? ""}`, + input.provider, + ) + ) { + result = setInferenceRoute(); + } + if (result.status === 0) return; + const failure = await buildInferenceSetFailure( + result, + input.provider, + input.gatewayName, + input.deps, + ); + throw new InferenceSetError(failure.message, failure.exitCode); +} + +async function rollbackNativeNvidiaSelection(input: { + attachmentChanged: boolean; + registryCommitted: boolean; + attachment?: NativeNvidiaProviderAttachment; + gatewayName: string; + sandboxName: string; + error: unknown; + deps: InferenceSetDeps; +}): Promise { + if (!input.attachmentChanged || input.registryCommitted || !input.attachment) return; + try { + await detachNativeNvidiaProvider({ + adapter: input.deps.providerAdapter, + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: input.attachment, + }); + } catch (rollbackError) { + const detail = input.error instanceof Error ? input.error.message : String(input.error); + const rollbackDetail = + rollbackError instanceof Error ? rollbackError.message : String(rollbackError); + throw new InferenceSetError(`${detail}\n ${rollbackDetail}`); + } +} + function recordedDirectProviderBindingMismatches(options: { entry: SandboxEntry; provider: string; @@ -1115,6 +1241,7 @@ async function runInferenceSetWithoutHostLock( // Registered peers are compared exactly as recorded. In particular, a // stopped legacy Hermes row that still records the Anthropic frontend will // depend on that route when restarted and must not be normalized away. + const selectingNativeNvidia = isNativeNvidiaProvider(provider); const routeSandboxes = deps.listSandboxes().sandboxes; const preparedRoute = prepareInferenceSetRoute({ entry: routeEntry, @@ -1123,7 +1250,7 @@ async function runInferenceSetWithoutHostLock( model, customRoute, session: routeSession, - sandboxes: routeSandboxes, + sandboxes: selectingNativeNvidia ? [] : routeSandboxes, }); if (preparedRoute.gatewayName !== expectedGatewayName) { throw new InferenceSetError( @@ -1200,7 +1327,9 @@ async function runInferenceSetWithoutHostLock( // instead, exactly like an explicit bridge route. const loopbackNoAuthProxyRoute = usesLoopbackNoAuthProxyRoute(entry, provider); const probeDirectSandboxBridge = - isSandboxBridgeProviderBinding(directProviderBinding) || loopbackNoAuthProxyRoute; + selectingNativeNvidia || + isSandboxBridgeProviderBinding(directProviderBinding) || + loopbackNoAuthProxyRoute; // Adapter routes and explicit custom routes on NemoClaw's sandbox bridge // resolve only from inside the sandbox network. The host-side OpenShell // verifier cannot resolve host.openshell.internal, so its result would be a @@ -1278,6 +1407,15 @@ async function runInferenceSetWithoutHostLock( assertReasoningEffortRoute(reasoningEffortRequest, provider, preMutationInferenceApi); const previousProvider = typeof entry.provider === "string" ? entry.provider.trim() : ""; const previousModel = typeof entry.model === "string" ? entry.model.trim() : ""; + const previousNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( + entry.nativeNvidiaProviderAttachment, + ); + assertNativeNvidiaMigrationReady({ + provider, + previousProvider, + previousAttachment: previousNativeNvidiaAttachment, + sandboxName, + }); // Capture before registry writes: a retry already has the new route, while // the sandbox config can still carry the previous endpoint's context window. const retryingOpenClawConfigSync = entry.openClawConfigSyncPending === true; @@ -1290,7 +1428,7 @@ async function runInferenceSetWithoutHostLock( [previousInferenceApi, preMutationInferenceApi], [entry.endpointUrl ?? null, registryMetadata.endpointUrl ?? null], ].some(([previous, next]) => previous !== next)); - if (probeDirectSandboxBridge && (!previousProvider || !previousModel)) { + if (probeDirectSandboxBridge && !selectingNativeNvidia && (!previousProvider || !previousModel)) { throw new InferenceSetError( `Cannot verify the sandbox-only provider route because sandbox '${sandboxName}' does not record ` + "the previous provider and model needed to restore its OpenShell inference selection.", @@ -1304,7 +1442,14 @@ async function runInferenceSetWithoutHostLock( let providerMutation: Awaited> | null = null; let assertProviderCurrentBeforeSelection: (() => Promise) | null = null; + let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; + let nativeNvidiaAttachmentChanged = false; + let nativeNvidiaRegistryCommitted = false; const restorePreviousInferenceSelection = (): string | null => { + if (selectingNativeNvidia || previousNativeNvidiaAttachment) { + appliedInferenceSelection = false; + return null; + } let restoreResult: CaptureOpenshellResult; try { restoreResult = deps.captureOpenshell( @@ -1330,6 +1475,15 @@ async function runInferenceSetWithoutHostLock( return null; }; try { + const nativeNvidiaSelection = await prepareNativeNvidiaSelection({ + provider, + previousAttachment: previousNativeNvidiaAttachment, + gatewayName: preparedRoute.gatewayName, + sandboxName, + deps, + }); + nativeNvidiaProviderAttachment = nativeNvidiaSelection.attachment; + nativeNvidiaAttachmentChanged = nativeNvidiaSelection.attachmentChanged; const providerBinding = httpsPinProviderBinding ?? directProviderBinding; if (providerBinding) { providerMutation = await prepareInferenceSetProviderBinding({ @@ -1387,41 +1541,15 @@ async function runInferenceSetWithoutHostLock( await assertProviderCurrentBeforeSelection?.(); if (routeImpactWarning) deps.log(` ${routeImpactWarning}`); - deps.log(` Setting OpenShell inference route: ${provider} / ${model}`); - const setInferenceRoute = () => - deps.captureOpenshell( - openshellInferenceSetArgs({ - gatewayName: preparedRoute.gatewayName, - provider, - model, - noVerify: effectiveNoVerify, - }), - { - ignoreError: true, - includeStreams: true, - maxBuffer: OPEN_SHELL_FAILURE_CAPTURE_MAX_BUFFER, - }, - ); - let setResult = setInferenceRoute(); - if ( - setResult.status !== 0 && - directProviderBinding && - openshellReportsProviderNotFound( - `${setResult.stderr ?? ""}\n${setResult.stdout ?? ""}`, - provider, - ) - ) { - setResult = setInferenceRoute(); - } - if (setResult.status !== 0) { - const failure = await buildInferenceSetFailure( - setResult, - provider, - preparedRoute.gatewayName, - deps, - ); - throw new InferenceSetError(failure.message, failure.exitCode); - } + await applyInferenceRouteSelection({ + nativeNvidia: selectingNativeNvidia, + provider, + model, + gatewayName: preparedRoute.gatewayName, + noVerify: effectiveNoVerify, + retryProviderNotFound: Boolean(directProviderBinding), + deps, + }); appliedInferenceSelection = true; if (providerMutation) { try { @@ -1449,6 +1577,7 @@ async function runInferenceSetWithoutHostLock( provider, model, preferredInferenceApi: preMutationInferenceApi, + ...(selectingNativeNvidia ? { nativeProvider: true } : {}), }, previousProvider, previousModel, @@ -1518,6 +1647,7 @@ async function runInferenceSetWithoutHostLock( nimContainer: registryMetadata.nimContainer ?? null, }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), + ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), }); if ( !deps.updateSandbox( @@ -1535,6 +1665,7 @@ async function runInferenceSetWithoutHostLock( `Failed to update NemoClaw registry for sandbox '${sandboxName}'.`, ); } + nativeNvidiaRegistryCommitted = Boolean(nativeNvidiaProviderAttachment); const preferredInferenceApi = explicitPreferredInferenceApi ?? @@ -1714,6 +1845,15 @@ async function runInferenceSetWithoutHostLock( }; } catch (error) { if (error instanceof OpenClawInferenceConfigSyncError) throw error; + await rollbackNativeNvidiaSelection({ + attachmentChanged: nativeNvidiaAttachmentChanged, + registryCommitted: nativeNvidiaRegistryCommitted, + attachment: nativeNvidiaProviderAttachment, + gatewayName: preparedRoute.gatewayName, + sandboxName, + error, + deps, + }); if (!providerMutation) throw error; if (restoredSelectionAfterProviderFailure) throw error; const detail = error instanceof Error ? error.message : String(error); @@ -1804,6 +1944,26 @@ export async function runInferenceSet( // this sandbox between the committed write, an optional restart, and // device-scope convergence. await completeInferencePostCommit(mutation, deps); + const priorNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( + lockedSelection.entry.nativeNvidiaProviderAttachment, + ); + if (priorNativeNvidiaAttachment && !isNativeNvidiaProvider(mutation.result.provider)) { + await detachNativeNvidiaProvider({ + adapter: deps.providerAdapter, + target: { kind: "named", gatewayName }, + sandboxName: selected.sandboxName, + expected: priorNativeNvidiaAttachment, + }); + if ( + !deps.updateSandbox(selected.sandboxName, { + nativeNvidiaProviderAttachment: undefined, + }) + ) { + throw new InferenceSetError( + `Native NVIDIA access was removed from sandbox '${selected.sandboxName}', but NemoClaw could not clear its attachment receipt. Retry this command before another provider change.`, + ); + } + } // Keep recovery pending until both the running gateway and pairing have converged. if (mutation.openClawConfigSyncPending) { clearOpenClawConfigSyncPending(selected.sandboxName, deps); diff --git a/src/lib/actions/sandbox/gateway-target.ts b/src/lib/actions/sandbox/gateway-target.ts index 53b76939397..1cce1cc898d 100644 --- a/src/lib/actions/sandbox/gateway-target.ts +++ b/src/lib/actions/sandbox/gateway-target.ts @@ -19,6 +19,10 @@ export function listPersistedSandboxTargets(): registry.SandboxEntry[] { return registry.listSandboxes().sandboxes; } +export function getDefaultSandboxTargetName(): string | null { + return registry.getDefault(); +} + export function getKnownSandboxTargetGatewayName(sandboxName = ""): string | null { const sb = sandboxName ? getKnownSandboxTarget(sandboxName) : null; return sb ? resolveSandboxGatewayName(sb) : null; diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 7d2f018bfd6..4212c3d202e 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -133,6 +133,20 @@ describe("sandbox inference invocation probe", () => { expect(command).not.toContain("-o /dev/null"); }); + it("probes native NVIDIA through the attached provider without exposing the host credential", () => { + const command = buildSandboxInferenceInvocationCommand({ + ...input, + provider: "nvidia-prod", + nativeProvider: true, + }); + + expect(command).toContain("https://integrate.api.nvidia.com/v1/chat/completions"); + expect(command).toContain("Authorization: Bearer nemoclaw-openshell-provider"); + expect(command).not.toContain("https://inference.local"); + expect(command).not.toContain("NVIDIA_API_KEY"); + expect(command).not.toContain("NVIDIA_INFERENCE_API_KEY"); + }); + it("fails closed and redacts diagnostics when the stored gateway credential is rejected (#6195)", async () => { const execute = vi.fn(async () => ({ status: 1, diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index 137a4d89fb2..50c5bd2a6b8 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -13,6 +13,10 @@ import { } from "../../adapters/openshell/sandbox-observer"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import { getSandboxInferenceConfig } from "../../inference/config"; +import { + isNativeNvidiaProvider, + NVIDIA_HOSTED_NATIVE_ENDPOINT, +} from "../../inference/native-nvidia"; import { validateInferenceResponseBody } from "../../inference/health"; import { MIN_PROBE_REPLY_TOKENS, @@ -43,6 +47,7 @@ export type SandboxInferenceInvocationInput = { provider: string; model: string; preferredInferenceApi: string | null; + nativeProvider?: boolean; }; export type SandboxInferenceInvocationResult = @@ -81,9 +86,18 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { input.provider, input.preferredInferenceApi, ); + const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); + const baseUrl = ( + useNativeNvidia + ? NVIDIA_HOSTED_NATIVE_ENDPOINT + : isNativeNvidiaProvider(input.provider) + ? "https://inference.local/v1" + : config.inferenceBaseUrl + ).replace(/\/+$/u, ""); + const apiBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`; if (config.inferenceApi === "anthropic-messages") { return { - endpoint: "https://inference.local/v1/messages", + endpoint: `${apiBaseUrl}/messages`, headers: ["anthropic-version: 2023-06-01"], payload: { model: input.model, @@ -94,7 +108,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { } if (config.inferenceApi === "openai-responses" || config.inferenceApi === "responses") { return { - endpoint: "https://inference.local/v1/responses", + endpoint: `${apiBaseUrl}/responses`, headers: [], payload: { model: input.model, @@ -104,8 +118,8 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { }; } return { - endpoint: "https://inference.local/v1/chat/completions", - headers: [], + endpoint: `${apiBaseUrl}/chat/completions`, + headers: useNativeNvidia ? ["Authorization: Bearer nemoclaw-openshell-provider"] : [], payload: { model: input.model, [resolveMaxTokensField(input.model)]: resolveProbeReplyTokens(input.provider), @@ -196,8 +210,8 @@ async function executeDcodeSandboxInferenceInvocation( /** * Send one minimal agent request over the configured gateway route from the * still-running sandbox. The request uses OpenShell's stored provider - * credential through inference.local; no host credential is placed in the - * command or its output. + * credential through the attached OpenShell provider or managed route; no host + * credential is placed in the command or its output. */ export async function probeSandboxInferenceInvocation( input: SandboxInferenceInvocationInput, diff --git a/src/lib/actions/sandbox/inference-route-health.test.ts b/src/lib/actions/sandbox/inference-route-health.test.ts index f249b014f66..d79ebc56d12 100644 --- a/src/lib/actions/sandbox/inference-route-health.test.ts +++ b/src/lib/actions/sandbox/inference-route-health.test.ts @@ -126,6 +126,44 @@ describe("buildSandboxInferenceRouteHealth (#10080)", () => { detail: `probe returned ${httpStatus}`, }); + it("uses the native NVIDIA invocation instead of the legacy gateway route", () => { + const result = buildSandboxInferenceRouteHealth( + gateway(503, false), + null, + { ok: true }, + { agentName: "openclaw", provider: "nvidia-prod", nativeNvidia: true }, + ); + + expect(result).toMatchObject({ + ok: true, + probed: true, + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + }); + expect(result.subprobes).toBeUndefined(); + }); + + it("does not let a healthy legacy gateway mask a failed native NVIDIA request", () => { + const result = buildSandboxInferenceRouteHealth( + gateway(200), + null, + { + ok: false, + detail: "sandbox inference invocation probe returned HTTP 401", + httpStatus: 401, + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + }, + { agentName: "openclaw", provider: "nvidia-prod", nativeNvidia: true }, + ); + + expect(result).toMatchObject({ + ok: false, + probed: true, + failureLabel: "unauthorized", + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + }); + expect(result.subprobes).toBeUndefined(); + }); + it.each([ ["openai-completions", "https://inference.local/v1/chat/completions"], ["openai-responses", "https://inference.local/v1/responses"], diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 3f19eef2d84..37f3a5c70bf 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -7,6 +7,10 @@ import { OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS } from "../../adapters/opens import * as agentRuntime from "../../agent/runtime"; import { REPOSITORY_ROOT } from "../../core/repository-root"; import type { ProviderHealthStatus } from "../../inference/health"; +import { + isNativeNvidiaProvider, + NVIDIA_HOSTED_NATIVE_ENDPOINT, +} from "../../inference/native-nvidia"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; import { buildSandboxInferenceRouteProbeRequest, @@ -240,6 +244,7 @@ function buildInvokedRouteHealth( export type SandboxInferenceRouteHealthContext = { agentName: string | null; provider: string | null; + nativeNvidia?: boolean; }; /** @@ -292,6 +297,32 @@ export function buildSandboxInferenceRouteHealth( invocation: SandboxInferenceInvocationResult | null, context: SandboxInferenceRouteHealthContext, ): ProviderHealthStatus { + if (context.nativeNvidia && isNativeNvidiaProvider(context.provider)) { + const endpoint = + invocation && !invocation.ok && invocation.endpoint + ? invocation.endpoint + : `${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions`; + const diagnostics = providerHealthDiagnostics(providerHealth, Boolean(invocation?.ok)); + const nativeHealth: ProviderHealthStatus = invocation?.ok + ? { + ok: true, + probed: true, + providerLabel: "Inference route", + endpoint, + detail: "The attached OpenShell provider served a native NVIDIA inference request.", + } + : { + ok: false, + probed: invocation !== null, + providerLabel: "Inference route", + endpoint, + detail: invocation + ? `The native NVIDIA route did not serve an inference request: ${invocation.detail}.` + : "Could not probe the native NVIDIA route from inside the sandbox. Recreate legacy beta sandboxes before using this route.", + failureLabel: classifyInferenceInvocationFailureLabel(invocation?.httpStatus ?? null), + }; + return diagnostics.length > 0 ? { ...nativeHealth, subprobes: diagnostics } : nativeHealth; + } const endpoint = gateway?.endpoint ?? "https://inference.local/v1/models"; const diagnostics = providerHealthDiagnostics(providerHealth, Boolean(invocation?.ok)); const accepted = diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index b8ea5952782..91b4e023ce9 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -16,6 +16,7 @@ import { type SandboxRecreateObserver, } from "../../../onboard/sandbox-recreate-probe"; import type { SandboxEntry } from "../../../state/registry"; +import { normalizeNativeNvidiaProviderAttachment } from "../../../inference/native-nvidia"; import { createSynchronousCliOpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route-cli"; import type { OpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route"; import { @@ -291,6 +292,35 @@ export async function requireLaunchSemanticHealth( } if (inferenceConfigured) { const inferenceStartedAt = performance.now(); + const nativeNvidia = Boolean( + normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment), + ); + if (nativeNvidia) { + const provider = normalizedString(entry.provider); + const model = normalizedString(entry.model); + if (!provider || !model) { + recordLaunchReadinessObservationFailure(deps, "inference-route"); + throw new LaunchReadinessEvidenceError(); + } + try { + const invocation = await ( + deps.inferenceInvocationProbe ?? runSandboxInferenceInvocationProbe + )({ + sandboxName, + gatewayName, + agentName, + provider, + model, + preferredInferenceApi: normalizedString(entry.preferredInferenceApi), + nativeProvider: true, + }); + if (invocation.ok) return; + recordLaunchReadinessObservationFailure(deps, "inference-route"); + throw new LaunchReadinessObservationError("health", "inference request"); + } finally { + recordObservationTiming(deps, "inference-route", inferenceStartedAt); + } + } let inference: ReturnType; try { const inferenceProbe = diff --git a/src/lib/actions/sandbox/rebuild-dcode-target.ts b/src/lib/actions/sandbox/rebuild-dcode-target.ts index 822576eb800..84aa20cbcd0 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-target.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-target.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { GATEWAY_PORT } from "../../core/ports"; +import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import { resolveGatewayPortFromName, resolveSandboxGatewayName, @@ -13,12 +14,14 @@ export const DCODE_AGENT_NAME = "langchain-deepagents-code"; export type DcodeRebuildRegistryEntry = SandboxGatewayBinding & { agent?: string | null; dashboardPort?: number | null; + nativeNvidiaProviderAttachment?: unknown; }; export type DcodeRebuildResumeConfig = { provider: string | null; model: string | null; preferredInferenceApi: string | null; + nativeProvider?: boolean; }; export type ResolvedDcodeRebuildTarget = { @@ -67,5 +70,8 @@ export function resolveDcodeRebuildTarget( provider: requiredString(resumeConfig.provider, "inference provider"), model: requiredString(resumeConfig.model, "inference model"), preferredInferenceApi: resumeConfig.preferredInferenceApi, + ...(normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) + ? { nativeProvider: true } + : {}), }; } diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 9fa1b670048..5aab91c090e 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -19,6 +19,7 @@ import { retryUntilAsync } from "../../core/retry"; import { withStdoutRedirectedToStderr } from "../../cli/stdout-guard"; import { getLlamaCppRouteDetails, + normalizeNativeNvidiaProviderAttachment, type GatewayInference, type LlamaCppRouteDetails, planInferenceRouteReconcile, @@ -683,6 +684,9 @@ export async function collectSandboxStatusSnapshot( }; const invocationModel = (invocationRoute.model || "").trim(); const invocationProvider = (invocationRoute.provider || "").trim(); + const nativeNvidia = Boolean( + normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), + ); const canProbeInvocation = Boolean(invocationModel && invocationProvider); let invocation: Awaited> | null = null; try { @@ -690,9 +694,13 @@ export async function collectSandboxStatusSnapshot( opts.deps?.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth; await retryUntilAsync( async () => { - gatewayChain = gatewayName ? await probe(sandboxName, { gatewayName }) : null; + gatewayChain = nativeNvidia + ? null + : gatewayName + ? await probe(sandboxName, { gatewayName }) + : null; invocation = - gatewayChain?.ok && canProbeInvocation + (nativeNvidia || gatewayChain?.ok) && canProbeInvocation ? await runSandboxInferenceInvocationProbe( { sandboxName, @@ -701,6 +709,7 @@ export async function collectSandboxStatusSnapshot( provider: invocationProvider, model: invocationModel, preferredInferenceApi: invocationRoute.preferredInferenceApi, + ...(nativeNvidia ? { nativeProvider: true } : {}), }, opts.deps?.probeSandboxInferenceInvocationImpl, (error) => @@ -714,6 +723,9 @@ export async function collectSandboxStatusSnapshot( }, { accept: ({ gatewayChain: chain, invocation: result }) => { + if (nativeNvidia) { + return result?.ok === true || !isTransientInferenceInvocationFailure(result); + } if (chain?.ok && (!canProbeInvocation || result?.ok)) return true; // After this run recovered a managed gateway, keep waiting for the // restarted chain to settle whatever the failure shape (#8572). @@ -748,6 +760,7 @@ export async function collectSandboxStatusSnapshot( inferenceHealth = buildSandboxInferenceRouteHealth(gatewayChain, providerHealth, invocation, { agentName: sb?.agent ?? null, provider: invocationRoute.provider ?? null, + nativeNvidia, }); } // Classify once per snapshot so every renderer observes the same receipt state. diff --git a/src/lib/adapters/config/live-export-source-test-fixture.ts b/src/lib/adapters/config/live-export-source-test-fixture.ts index a148094c41c..e5fc21e505e 100644 --- a/src/lib/adapters/config/live-export-source-test-fixture.ts +++ b/src/lib/adapters/config/live-export-source-test-fixture.ts @@ -22,11 +22,11 @@ export const startupInput = { routeProvider: "inference", upstreamProvider: "nvidia-prod", model: "model-a", - routedBaseUrl: "https://inference.local/v1", + routedBaseUrl: endpoint, upstreamEndpointUrl: null, api: "openai-completions", primaryModelRef: "inference/model-a", - compatibility: {}, + compatibility: { supportsStore: false }, }, dashboard: { agent: "openclaw", diff --git a/src/lib/adapters/openshell/sandbox-observer.ts b/src/lib/adapters/openshell/sandbox-observer.ts index 901a455d89f..5b01d6212b6 100644 --- a/src/lib/adapters/openshell/sandbox-observer.ts +++ b/src/lib/adapters/openshell/sandbox-observer.ts @@ -79,3 +79,8 @@ export function namedOpenShellGateway(gatewayName: string): OpenShellGatewayTarg export function selectedOpenShellGateway(): OpenShellGatewayTarget { return { kind: "selected" }; } +export type { + OpenShellProviderAdapter, + OpenShellProviderError, + OpenShellProviderMetadata, +} from "./provider-adapter"; diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index 7d81559a66d..f5b376f741f 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -29,6 +29,7 @@ import { sanitizeRouteValueForDisplay, VLLM_LOCAL_CREDENTIAL_ENV, } from "./config"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; describe("resolveAgentDefaultCloudModel", () => { it("uses the Deep Agents manifest default", () => { @@ -379,7 +380,7 @@ describe("getSandboxInferenceConfig", () => { }); }); - it("maps NVIDIA Endpoints to the routed inference provider", () => { + it("maps NVIDIA Endpoints to its native endpoint while preserving the agent provider key (#12558)", () => { expect( getSandboxInferenceConfig( "nvidia/nemotron-3-super-120b-a12b", @@ -389,9 +390,9 @@ describe("getSandboxInferenceConfig", () => { ).toEqual({ providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/nvidia/nemotron-3-super-120b-a12b`, - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, inferenceApi: "openai-completions", - inferenceCompat: null, + inferenceCompat: { supportsStore: false }, }); }); @@ -411,9 +412,9 @@ describe("getSandboxInferenceConfig", () => { ).toEqual({ providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/moonshotai/kimi-k2.6`, - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, inferenceApi: "openai-completions", - inferenceCompat: null, + inferenceCompat: { supportsStore: false }, }); }); diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 2cd73a5ce5e..6d23854fe75 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -13,6 +13,7 @@ import { LLAMA_CPP_HOST_OPENAI_BASE_URL, LLAMA_CPP_PROVIDER_NAME, } from "./llama-cpp/contract"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; import type { ManagedLlamaCppOwnership } from "./llama-cpp/managed-state"; import { DEFAULT_OLLAMA_MODEL_TAG as DEFAULT_OLLAMA_MODEL } from "./ollama-model-registry"; import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "./ollama/contract"; @@ -21,6 +22,16 @@ import { VLLM_LOCAL_CREDENTIAL_ENV } from "./serving/vllm-credential-contract"; export { isSafeModelId }; export { OLLAMA_LOCAL_CREDENTIAL_ENV }; +export { + detachNativeNvidiaProvider, + ensureNativeNvidiaProvider, + ensureNativeNvidiaProviderAttached, + isNativeNvidiaProvider, + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_NATIVE_ENDPOINT, + normalizeNativeNvidiaProviderAttachment, +} from "./native-nvidia"; +export type { NativeNvidiaProviderAttachment } from "./native-nvidia"; export const INFERENCE_ROUTE_URL = "https://inference.local/v1"; export const NOUS_RECOMMENDED_MODELS_URL = @@ -218,6 +229,13 @@ export function getProviderSelectionConfig( switch (provider) { case "nvidia-prod": + return { + ...base, + endpointUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + model: model || DEFAULT_CLOUD_MODEL, + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + providerLabel: "NVIDIA Endpoints", + }; case "nvidia-nim": return { ...base, @@ -383,6 +401,14 @@ export function getSandboxInferenceConfig( primaryModelRef = `${MANAGED_PROVIDER_ID}/${model}`; break; case "nvidia-prod": + providerKey = MANAGED_PROVIDER_ID; + primaryModelRef = `${MANAGED_PROVIDER_ID}/${model}`; + inferenceBaseUrl = NVIDIA_HOSTED_NATIVE_ENDPOINT; + inferenceApi = "openai-completions"; + inferenceCompat = { + supportsStore: false, + }; + break; case "nvidia-nim": default: providerKey = MANAGED_PROVIDER_ID; diff --git a/src/lib/inference/gateway-route-compatibility.ts b/src/lib/inference/gateway-route-compatibility.ts index 32848cf989d..9505a1764c4 100644 --- a/src/lib/inference/gateway-route-compatibility.ts +++ b/src/lib/inference/gateway-route-compatibility.ts @@ -6,6 +6,11 @@ import { resolveSandboxGatewayName } from "../onboard/gateway-binding"; import { isSharedGatewayRouteParticipant } from "../state/registry/route-reservation"; import type { SandboxEntry } from "../state/registry"; +export { + nativeInferenceProviderForSandbox, + normalizeNativeNvidiaProviderAttachment, +} from "./native-nvidia"; + export type GatewayInferenceRoute = Pick< SandboxEntry, "provider" | "model" | "endpointUrl" | "preferredInferenceApi" | "credentialEnv" diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts new file mode 100644 index 00000000000..bd36bb90206 --- /dev/null +++ b/src/lib/inference/native-nvidia.test.ts @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { describe, expect, it, vi } from "vitest"; + +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { parseCheckedInProviderProfileContract } from "../adapters/openshell/provider-profile"; +import { + ensureNativeNvidiaProvider, + nativeNvidiaProviderProfilePath, + NativeNvidiaProviderError, + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + NVIDIA_HOSTED_NATIVE_PROVIDER, + verifyNativeNvidiaProviderAttachment, +} from "./native-nvidia"; + +const target = { kind: "named", gatewayName: "nemoclaw" } as const; + +function metadata(overrides: Record = {}) { + return { + name: NVIDIA_HOSTED_NATIVE_PROVIDER, + type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + credentialKeys: [NVIDIA_HOSTED_CREDENTIAL_ENV], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 1 }, + ...overrides, + }; +} + +function adapter(overrides: Partial = {}): OpenShellProviderAdapter { + return { + importProviderProfile: vi.fn(() => ({ ok: true })), + getProvider: vi.fn(async () => ({ ok: true, value: metadata() })), + createProvider: vi.fn(async () => ({ ok: true })), + updateProvider: vi.fn(async () => ({ ok: true })), + listProviderAttachments: vi.fn(async () => ({ + ok: true, + value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, + })), + listProviders: vi.fn(), + inspectProviderProfile: vi.fn(), + deleteProvider: vi.fn(), + detachProvider: vi.fn(), + attachProvider: vi.fn(), + configureProviderRefresh: vi.fn(), + getProviderRefreshStatus: vi.fn(), + ...overrides, + } as OpenShellProviderAdapter; +} + +describe("native NVIDIA OpenShell provider", () => { + it("ships a profile limited to the native models and chat-completions operations (#12558)", () => { + const source = fs.readFileSync(nativeNvidiaProviderProfilePath(), "utf8"); + const profile = parseCheckedInProviderProfileContract(source); + + expect(profile?.profileId).toBe(NVIDIA_HOSTED_NATIVE_PROFILE_ID); + expect(profile?.boundary.endpoints).toEqual([ + expect.objectContaining({ + host: "integrate.api.nvidia.com", + port: 443, + enforcement: "enforce", + rules: [ + { allow: { method: "GET", path: "/v1/models" } }, + { allow: { method: "POST", path: "/v1/chat/completions" } }, + ], + }), + ]); + expect(profile?.boundary.binaries).not.toEqual( + expect.arrayContaining([expect.stringMatching(/[?*]/u)]), + ); + }); + + it("creates the internal provider once and records its immutable identity (#12558)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: true, + })); + const providerAdapter = adapter({ getProvider, createProvider }); + + await expect( + ensureNativeNvidiaProvider({ + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + }), + ).resolves.toEqual({ + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + }); + expect(createProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + name: NVIDIA_HOSTED_NATIVE_PROVIDER, + type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: "opaque-test-secret" }], + config: [], + }), + ); + }); + + it("observes an ambiguous create result without issuing a second mutation (#12558)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: false, + error: { kind: "timeout", message: "timed out" }, + })); + + await expect( + ensureNativeNvidiaProvider({ + adapter: adapter({ getProvider, createProvider }), + target, + credentialValue: "opaque-test-secret", + }), + ).resolves.toMatchObject({ providerId: "provider-id" }); + expect(createProvider).toHaveBeenCalledOnce(); + }); + + it("refuses a replaced provider before rotating its credential (#12558)", async () => { + const updateProvider = vi.fn(); + + await expect( + ensureNativeNvidiaProvider({ + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ revision: { id: "replacement-id", resourceVersion: 1 } }), + })), + updateProvider, + }), + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "recorded-id", + }, + }), + ).rejects.toThrow(/changed identity.*No provider was changed/u); + expect(updateProvider).not.toHaveBeenCalled(); + }); + + it("fails before provider mutation when the profile collides (#12558)", async () => { + const createProvider = vi.fn(); + const providerAdapter = adapter({ + importProviderProfile: vi.fn(() => ({ + ok: false, + error: { + kind: "command", + reason: "profile_incompatible", + message: "different profile", + }, + })), + createProvider, + }); + + await expect( + ensureNativeNvidiaProvider({ + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + }), + ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); + expect(createProvider).not.toHaveBeenCalled(); + }); + + it("requires the exact provider attachment before native inference is published (#12558)", async () => { + const providerAdapter = adapter({ + listProviderAttachments: vi.fn( + async () => ({ ok: true, value: { names: [] } }), + ), + }); + + await expect( + verifyNativeNvidiaProviderAttachment({ + adapter: providerAdapter, + target, + sandboxName: "alpha", + }), + ).rejects.toThrow(NativeNvidiaProviderError); + await expect( + verifyNativeNvidiaProviderAttachment({ + adapter: providerAdapter, + target, + sandboxName: "alpha", + }), + ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); + }); +}); diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts new file mode 100644 index 00000000000..08aa4abbca5 --- /dev/null +++ b/src/lib/inference/native-nvidia/index.ts @@ -0,0 +1,318 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import type { + OpenShellGatewayTarget, + OpenShellProviderAdapter, + OpenShellProviderError, + OpenShellProviderMetadata, +} from "../../adapters/openshell/sandbox-observer"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; + +export const NVIDIA_HOSTED_LOGICAL_PROVIDER = "nvidia-prod"; +export const NVIDIA_HOSTED_NATIVE_ENDPOINT = "https://integrate.api.nvidia.com/v1"; +export const NVIDIA_HOSTED_NATIVE_PROFILE_ID = "nemoclaw-nvidia-inference-v1"; +export const NVIDIA_HOSTED_NATIVE_PROVIDER = "nemoclaw-nvidia-prod-v1"; +export const NVIDIA_HOSTED_CREDENTIAL_ENV = "NVIDIA_INFERENCE_API_KEY"; + +export type NativeNvidiaProviderAttachment = Readonly<{ + schemaVersion: 1; + profileId: typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; + providerName: typeof NVIDIA_HOSTED_NATIVE_PROVIDER; + providerId: string; +}>; + +export class NativeNvidiaProviderError extends Error { + constructor(message: string) { + super(message); + this.name = "NativeNvidiaProviderError"; + } +} + +export function nativeNvidiaProviderProfilePath(root = REPOSITORY_ROOT): string { + return path.join( + root, + "managed-inference", + "provider-profiles", + `${NVIDIA_HOSTED_NATIVE_PROFILE_ID}.yaml`, + ); +} + +export function isNativeNvidiaProvider(provider: string | null | undefined): boolean { + return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; +} + +export function nativeInferenceProviderForSandbox( + provider: string | null | undefined, +): string | null { + const normalized = provider?.trim() || null; + return isNativeNvidiaProvider(normalized) ? NVIDIA_HOSTED_NATIVE_PROVIDER : normalized; +} + +export function normalizeNativeNvidiaProviderAttachment( + value: unknown, +): NativeNvidiaProviderAttachment | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const receipt = value as Record; + if ( + receipt.schemaVersion !== 1 || + receipt.profileId !== NVIDIA_HOSTED_NATIVE_PROFILE_ID || + receipt.providerName !== NVIDIA_HOSTED_NATIVE_PROVIDER || + typeof receipt.providerId !== "string" || + !receipt.providerId.trim() + ) { + return undefined; + } + return { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: receipt.providerId, + }; +} + +function providerErrorDetail(error: OpenShellProviderError): string { + return error.message.trim() || "OpenShell did not provide a diagnostic."; +} + +function exactNativeProvider(metadata: OpenShellProviderMetadata): boolean { + return ( + metadata.name === NVIDIA_HOSTED_NATIVE_PROVIDER && + metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID && + metadata.configKeys.length === 0 && + metadata.credentialKeys.length === 1 && + metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && + Boolean(metadata.revision?.id) + ); +} + +function attachmentFromMetadata( + metadata: OpenShellProviderMetadata, +): NativeNvidiaProviderAttachment { + if (!exactNativeProvider(metadata) || !metadata.revision) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' does not match the NemoClaw-owned NVIDIA inference boundary. No provider was changed.`, + ); + } + return { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: metadata.revision.id, + }; +} + +async function inspectNativeProvider( + adapter: OpenShellProviderAdapter, + target: OpenShellGatewayTarget, +): Promise { + const observed = await adapter.getProvider({ + target, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }); + if (observed.ok) return observed.value; + if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; + throw new NativeNvidiaProviderError( + `Could not inspect OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(observed.error)}`, + ); +} + +function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { + return ( + error.kind === "timeout" || + (error.kind === "transport" && + (error.reason === "connection_loss" || error.reason === "unreachable")) || + (error.kind === "command" && error.reason === "uncertain") + ); +} + +/** Ensure the least-privilege NVIDIA profile and provider without retrying an ambiguous mutation. */ +export async function ensureNativeNvidiaProvider(input: { + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + credentialValue: string | null; + expected?: NativeNvidiaProviderAttachment; + profilePath?: string; +}): Promise { + const { adapter, target } = input; + const imported = await adapter.importProviderProfile({ + target, + profilePath: input.profilePath ?? nativeNvidiaProviderProfilePath(), + }); + if (!imported.ok) { + const collision = + imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; + throw new NativeNvidiaProviderError( + collision + ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` + : `Could not prepare OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, + ); + } + + const before = await inspectNativeProvider(adapter, target); + if (before) { + const receipt = attachmentFromMetadata(before); + if (input.expected && input.expected.providerId !== receipt.providerId) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, + ); + } + if (!input.credentialValue) return receipt; + const updated = await adapter.updateProvider({ + target, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], + config: [], + }); + if (!updated.ok && !mutationOutcomeMayBeAmbiguous(updated.error)) { + throw new NativeNvidiaProviderError( + `Could not update OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(updated.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target); + if (!observed) { + throw new NativeNvidiaProviderError( + `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after its credential update.`, + ); + } + return attachmentFromMetadata(observed); + } + + if (!input.credentialValue) { + throw new NativeNvidiaProviderError( + `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, + ); + } + const created = await adapter.createProvider({ + target, + name: NVIDIA_HOSTED_NATIVE_PROVIDER, + type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], + config: [], + fromExisting: false, + }); + if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { + throw new NativeNvidiaProviderError( + `Could not create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(created.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target); + if (!observed) { + throw new NativeNvidiaProviderError( + `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after creation.`, + ); + } + return attachmentFromMetadata(observed); +} + +/** Prove that the exact NemoClaw-owned NVIDIA provider is attached to one sandbox. */ +export async function verifyNativeNvidiaProviderAttachment(input: { + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected?: NativeNvidiaProviderAttachment; +}): Promise { + const provider = await inspectNativeProvider(input.adapter, input.target); + if (!provider) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, + ); + } + const receipt = attachmentFromMetadata(provider); + if (input.expected && input.expected.providerId !== receipt.providerId) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, + ); + } + const attachments = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!attachments.ok) { + throw new NativeNvidiaProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, + ); + } + if (!attachments.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { + throw new NativeNvidiaProviderError( + `Sandbox '${input.sandboxName}' does not have its native NVIDIA inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, + ); + } + return receipt; +} + +/** Attach native NVIDIA access and reconcile an ambiguous command through observation. */ +export async function ensureNativeNvidiaProviderAttached(input: { + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeNvidiaProviderAttachment; +}): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { + const before = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!before.ok) { + throw new NativeNvidiaProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, + ); + } + if (before.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { + return { + receipt: await verifyNativeNvidiaProviderAttachment(input), + changed: false, + }; + } + const attached = await input.adapter.attachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }); + if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { + throw new NativeNvidiaProviderError( + `Could not attach native NVIDIA provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, + ); + } + return { + receipt: await verifyNativeNvidiaProviderAttachment(input), + changed: true, + }; +} + +/** Detach only the recorded native NVIDIA provider identity and prove absence. */ +export async function detachNativeNvidiaProvider(input: { + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeNvidiaProviderAttachment; +}): Promise { + const provider = await inspectNativeProvider(input.adapter, input.target); + if (!provider) return; + const current = attachmentFromMetadata(provider); + if (current.providerId !== input.expected.providerId) { + throw new NativeNvidiaProviderError( + `Refusing to detach OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, + ); + } + const detached = await input.adapter.detachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }); + if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { + throw new NativeNvidiaProviderError( + `Could not detach native NVIDIA provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, + ); + } + const after = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!after.ok || after.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { + throw new NativeNvidiaProviderError( + `OpenShell did not confirm removal of native NVIDIA access from sandbox '${input.sandboxName}'.`, + ); + } +} diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 599a477e203..b3768a23ed9 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2315,7 +2315,7 @@ function getSetupInferenceDeps(): SetupInferenceDeps { unloadOllamaModels, hermesProviderAuth, getHermesToolGatewayBroker, - providerExistsInGateway, + ...onboardProviders.setupInferenceProviderDeps(runOpenshell), normalizeHermesAuthMethod, resolveHermesNousApiKey, checkHermesProviderStoreReachable, diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index 6a994e45c99..4f98a3fccc6 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -200,7 +200,7 @@ function makeRestoreFixture(): { "[models.providers.openai]", 'models = ["new-model"]', 'api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"', - 'base_url = "https://inference.local/v1"', + 'base_url = "https://integrate.api.nvidia.com/v1"', "enabled = true", "", "[update]", diff --git a/src/lib/onboard/dcode-selection-drift.test.ts b/src/lib/onboard/dcode-selection-drift.test.ts index c088cd2c285..c005e94c845 100644 --- a/src/lib/onboard/dcode-selection-drift.test.ts +++ b/src/lib/onboard/dcode-selection-drift.test.ts @@ -53,12 +53,18 @@ function bufferedExecutor( function identity( overrides: Partial> = {}, ) { + const provider = overrides.Provider ?? "nvidia-prod"; return [ "Sandbox: alpha", `Route: ${overrides.Route ?? "inference"}`, - `Provider: ${overrides.Provider ?? "nvidia-prod"}`, + `Provider: ${provider}`, `Model: ${overrides.Model ?? "openai:nvidia/nemotron-3-super-120b-a12b"}`, - `Endpoint: ${overrides.Endpoint ?? "https://inference.local/v1"}`, + `Endpoint: ${ + overrides.Endpoint ?? + (provider === "nvidia-prod" + ? "https://integrate.api.nvidia.com/v1" + : "https://inference.local/v1") + }`, "Runtime: Deep Agents Code (terminal)", ].join("\n"); } @@ -81,7 +87,7 @@ describe("live DCode selection drift", () => { route: "inference", provider: "nvidia-prod", model: "openai:nvidia/nemotron-3-super-120b-a12b", - endpoint: "https://inference.local/v1", + endpoint: "https://integrate.api.nvidia.com/v1", }); expect(parseDcodeInferenceIdentity(identity().replace(/^Endpoint:.*$/m, ""))).toBeNull(); diff --git a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index 6ab386d1c9e..8c2563ed018 100644 --- a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts @@ -25,6 +25,50 @@ const resourceProfiles: [string, { cpu: string; memory: string } | null][] = [ ]; describe("sandbox create intent machine boundary", () => { + it("attaches the internal native NVIDIA provider while retaining the logical selection", async () => { + const session = createSession({ sandboxName: "native-nvidia" }); + const nativeNvidiaProviderAttachment = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const { deps, calls } = createDeps({ + getSandboxRegistryEntry: (name: string) => ({ + name, + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + endpointUrl: null, + preferredInferenceApi: "openai-completions", + webSearchEnabled: false, + toolDisclosure: "progressive" as const, + fromDockerfile: null, + hermesAuthMethod: null, + nativeNvidiaProviderAttachment, + }), + }); + + await handleSandboxState({ + ...baseOptions(deps, session), + sandboxName: "native-nvidia", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + }); + + expect(calls.resolveCreateIntent).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "native-nvidia", + inferenceProvider: "nemoclaw-nvidia-prod-v1", + nativeNvidiaProviderAttachment, + }), + ); + expect(calls.startStep).toHaveBeenCalledWith("sandbox", { + sandboxName: "native-nvidia", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + }); + }); + it("rejects deterministic create conflicts before resume recreation mutates state (#6226)", async () => { const session = createSession({ sandboxName: "saved" }); session.steps.sandbox.status = "complete"; diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 2fdd97d25a8..671e22af01f 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -6,6 +6,8 @@ import { formatGatewayRouteConflict, type GatewayRouteCompatibilityResult, isAdvisoryGatewayRouteConflict, + nativeInferenceProviderForSandbox, + normalizeNativeNvidiaProviderAttachment, } from "../../../inference/gateway-route-compatibility"; import type { InferenceEndpointSource } from "../../../inference/selection"; import { @@ -50,6 +52,7 @@ import { recordCheckpointSandboxIdentity, recordCheckpointWebSearch, } from "../../checkpoint-record"; + import { checkpointProvesSandboxStepComplete, observeProviderEffectFingerprint, @@ -127,6 +130,22 @@ type SandboxRecreateWorkloadSkipReason = Extract< { readonly status: "skipped" } >["reason"]; +function nativeNvidiaCreateIntentFields( + provider: string | null | undefined, + entry: SandboxEntry | null, +): { + inferenceProvider: string | null; + nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; +} { + const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( + entry?.nativeNvidiaProviderAttachment, + ); + return { + inferenceProvider: nativeInferenceProviderForSandbox(provider), + ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + }; +} + const SANDBOX_RECREATE_WORKLOAD_SKIP_DIAGNOSTIC = { "replacement-unproven": " Obsolete sandbox image retirement skipped: replacement-unproven", "shared-image": " Obsolete sandbox image retirement skipped: shared-image", @@ -350,6 +369,7 @@ export interface SandboxStateOptions< resolveSandboxCreateIntent(input: { sandboxName: string; inferenceProvider?: string | null; + nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[]; webSearchConfig: WebSearchConfig | null; @@ -1806,7 +1826,10 @@ class SandboxStateFlow< const reuseRegisteredCredentials = this.resumesSandboxPrompts && this.options.resume; const resolved = await this.deps.resolveSandboxCreateIntent({ sandboxName, - inferenceProvider: this.options.provider, + ...nativeNvidiaCreateIntentFields( + this.options.provider, + this.deps.getSandboxRegistryEntry(sandboxName), + ), hostLocalInferenceRouteOnly: this.options.hostLocalInferenceRouteOnly === true, enabledChannels: state.selectedMessagingChannels, webSearchConfig: state.webSearchConfig, diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index d8dbde16446..b2dfc1efcf5 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -389,6 +389,13 @@ async function providerExistsInGateway(name, runOpenshell) { throw new Error(result.error.message); } +function setupInferenceProviderDeps(runOpenshell) { + return { + providerExistsInGateway, + providerAdapter: createCliOpenShellProviderAdapter({ run: runOpenshell }), + }; +} + /** * Recheck current OpenShell sandbox identity before each provider command. * Commands in one provider operation can be separated by @@ -594,6 +601,7 @@ module.exports = { getRequestedModelHint, isProviderKeyCredentialCandidate, upsertProvider, + setupInferenceProviderDeps, providerExistsInGateway, readGatewayProviderMetadata, getSandboxInferenceConfig, diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index 3a4c2580986..a258271e590 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { WebSearchConfig } from "../inference/web-search"; +import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; import type { NamedMessagingChannel } from "./messaging-prep"; import { @@ -26,6 +27,7 @@ import { export type CompleteSandboxCreateIntentInput = { sandboxName: string; inferenceProvider?: string | null; + nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[] | null; webSearchConfig: WebSearchConfig | null; @@ -144,6 +146,7 @@ export function createSandboxCreateIntentResolver< basePolicyPath: deps.getAgentPolicyPath(input.agent) || deps.defaultPolicyPath, sandboxName: input.sandboxName, inferenceProvider: input.inferenceProvider, + nativeNvidiaProviderAttachment: input.nativeNvidiaProviderAttachment, hostLocalInferenceRouteOnly: input.hostLocalInferenceRouteOnly === true, channels: deps.channels, enabledChannels: resolveSelectedChannels(input), diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index bff0ce0ac1d..2fabf1ebc3c 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { SandboxHostMount } from "../state/registry/types"; +import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; import type { MessagingChannelConfig } from "../messaging-channel-config"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; import type { InitialSandboxPolicy } from "./initial-policy"; @@ -47,6 +48,7 @@ export type SandboxCreatePolicyRequest = { export type SandboxCreateIntent = { readonly sandboxName: string; readonly inferenceProvider: string | null; + readonly nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; readonly activeMessagingChannels: readonly string[]; readonly messagingProviderRequests: readonly SandboxCreateMessagingProviderRequest[]; readonly reusableMessagingProviders: readonly string[]; @@ -68,6 +70,7 @@ export type ResolveSandboxCreateIntentInput = { basePolicyPath: string; sandboxName: string; inferenceProvider?: string | null; + nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; hostLocalInferenceRouteOnly?: boolean; channels: readonly MessagingChannel[]; enabledChannels: string[] | null; diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index f698589aa04..a039c03849a 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -140,6 +140,7 @@ export function resolveSandboxCreateIntent({ basePolicyPath, sandboxName, inferenceProvider, + nativeNvidiaProviderAttachment, hostLocalInferenceRouteOnly = false, channels, enabledChannels, @@ -187,6 +188,7 @@ export function resolveSandboxCreateIntent({ return { sandboxName, inferenceProvider: normalizedInferenceProvider, + ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), activeMessagingChannels, messagingProviderRequests: messagingProviderRequests.map((request) => ({ ...request })), reusableMessagingProviders: enabledReusableMessagingProviders, diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts new file mode 100644 index 00000000000..56788f54c01 --- /dev/null +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; +import { createProviderEffectBoundary } from "./orchestration"; + +const recordedProviderId = "11111111-2222-4333-8444-555555555555"; + +function providerAdapter(providerId: string): OpenShellProviderAdapter { + return { + getProvider: vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: providerId, resourceVersion: 1 }, + }, + })), + listProviderAttachments: vi.fn(async () => ({ + ok: true, + value: { names: ["nemoclaw-nvidia-prod-v1"] }, + })), + } as unknown as OpenShellProviderAdapter; +} + +function nativeProviderBoundary(adapter: OpenShellProviderAdapter) { + return createProviderEffectBoundary({ + deferred: false, + sandboxName: "alpha", + gatewayName: "nemoclaw", + expectedNativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: recordedProviderId, + }, + preparationInput: { + openshellDriver: "docker", + inferenceProvider: "nemoclaw-nvidia-prod-v1", + messagingProviders: [], + messagingProviderRequests: [], + extraProviders: [], + gatewayName: "nemoclaw", + }, + preparationDeps: { + runOpenshell: vi.fn() as never, + providerAdapter: adapter, + cleanupCreateSources: vi.fn(), + }, + runVerifiedSandboxCreateEffects: null, + activateDeferredProviderEffects: async () => [], + revalidateSandboxIdentityBeforeCreate: vi.fn(), + }); +} + +function verifiedCreateContext(revalidateSandboxIdentity = vi.fn()) { + return { + sandboxName: "alpha", + gatewayName: "nemoclaw", + gatewayPort: 18790, + lifecycleGeneration: "generation-1", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + route: "direct" as never, + revalidateSandboxIdentity, + }; +} + +describe("native NVIDIA post-create provider verification", () => { + it("confirms the recorded provider is attached after sandbox identity is verified", async () => { + const adapter = providerAdapter(recordedProviderId); + const revalidateSandboxIdentity = vi.fn(); + const boundary = nativeProviderBoundary(adapter); + + await expect( + boundary.runAfterVerifiedCreate?.(verifiedCreateContext(revalidateSandboxIdentity)), + ).resolves.toBeUndefined(); + + expect(revalidateSandboxIdentity).toHaveBeenCalledWith( + "verifying native NVIDIA provider attachment for sandbox 'alpha'", + ); + expect(adapter.listProviderAttachments).toHaveBeenCalledWith( + expect.objectContaining({ sandboxName: "alpha" }), + ); + }); + + it("rejects a replaced provider before inspecting its sandbox attachments", async () => { + const adapter = providerAdapter("99999999-2222-4333-8444-555555555555"); + const boundary = nativeProviderBoundary(adapter); + + await expect(boundary.runAfterVerifiedCreate?.(verifiedCreateContext())).rejects.toThrow( + /changed identity.*Recreate the sandbox/u, + ); + expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 54fc8a212da..a5fb2a7e4ff 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -86,7 +86,9 @@ import { } from "./identity-boundary"; import { publishAttachedProvidersBeforeDockerSandboxCreation, + usesNativeNvidiaProvider, validateAttachedMessagingProvidersBeforeSandboxCreation, + verifyNativeNvidiaAttachmentAfterCreate, } from "./provider-publication"; import { materializeRebuildPolicyHandoff, @@ -1413,6 +1415,7 @@ export function createProviderEffectBoundary(input: { readonly deferred: boolean; readonly sandboxName: string; readonly gatewayName: string; + readonly expectedNativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; readonly preparationInput: ProviderPreparationInput; readonly preparationDeps: ProviderPreparationDeps; readonly runVerifiedSandboxCreateEffects: import("../types").VerifiedSandboxCreateEffects | null; @@ -1431,6 +1434,19 @@ export function createProviderEffectBoundary(input: { input.preparationInput, input.preparationDeps, ); + const verifyNativeNvidiaAttachment = async (context: VerifiedSandboxCreateEffectsContext) => { + if (!usesNativeNvidiaProvider(input.preparationInput.inferenceProvider)) return; + context.revalidateSandboxIdentity( + `verifying native NVIDIA provider attachment for sandbox '${input.sandboxName}'`, + ); + await verifyNativeNvidiaAttachmentAfterCreate({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + inferenceProvider: input.preparationInput.inferenceProvider, + expected: input.expectedNativeNvidiaProviderAttachment, + deps: input.preparationDeps, + }); + }; if (!input.deferred) { return { validateBeforeCreate: validate, @@ -1438,7 +1454,9 @@ export function createProviderEffectBoundary(input: { input.revalidateSandboxIdentityBeforeCreate(); await publish(); }, - runAfterVerifiedCreate: undefined, + runAfterVerifiedCreate: usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) + ? verifyNativeNvidiaAttachment + : undefined, }; } return { @@ -1459,6 +1477,7 @@ export function createProviderEffectBoundary(input: { `publishing deferred providers for sandbox '${input.sandboxName}'`, ); await publish(); + await verifyNativeNvidiaAttachment(context); context.revalidateSandboxIdentity( `attaching deferred providers to sandbox '${input.sandboxName}'`, ); @@ -3544,6 +3563,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche deferred: createIntent?.deferSandboxEffectsUntilIdentityVerification === true, sandboxName, gatewayName: GATEWAY_NAME, + expectedNativeNvidiaProviderAttachment: resolvedCreateIntent.nativeNvidiaProviderAttachment, preparationInput: providerPreparationInput, preparationDeps: providerPreparationDeps, runVerifiedSandboxCreateEffects, diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index 9f7fb764627..7402aacbe24 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -10,6 +10,10 @@ import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/prov import type { OpenShellGatewayEndpointEnvironment } from "../../adapters/openshell/gateway-scope"; import { namedOpenShellGateway } from "../../adapters/openshell/sandbox-observer"; import { REPOSITORY_ROOT } from "../../core/repository-root"; +import { + NVIDIA_HOSTED_NATIVE_PROVIDER, + verifyNativeNvidiaProviderAttachment, +} from "../../inference/native-nvidia"; import { messagingCredentialProviderProfilePath, MESSAGING_CREDENTIAL_PROVIDER_TYPE, @@ -60,6 +64,31 @@ function resolveProviderAdapter(deps: ProviderPreparationDeps): OpenShellProvide ); } +export function usesNativeNvidiaProvider(inferenceProvider: string | null): boolean { + return inferenceProvider === NVIDIA_HOSTED_NATIVE_PROVIDER; +} + +export async function verifyNativeNvidiaAttachmentAfterCreate(input: { + readonly sandboxName: string; + readonly gatewayName: string; + readonly inferenceProvider: string | null; + readonly expected: SandboxEntry["nativeNvidiaProviderAttachment"]; + readonly deps: ProviderPreparationDeps; +}): Promise { + if (!usesNativeNvidiaProvider(input.inferenceProvider)) return; + if (!input.expected) { + throw new Error( + `Sandbox '${input.sandboxName}' is missing its native NVIDIA provider identity receipt.`, + ); + } + await verifyNativeNvidiaProviderAttachment({ + adapter: resolveProviderAdapter(input.deps), + target: namedOpenShellGateway(input.gatewayName), + sandboxName: input.sandboxName, + expected: input.expected, + }); +} + type ExpectedMessagingBindingInspection = | Readonly<{ kind: "exact" | "mismatch" }> | Readonly<{ kind: "failed"; error: OpenShellProviderError }>; diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index fde42b34af5..44b092116d7 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -93,6 +93,39 @@ function createdRegistryEntryInput( } describe("buildCreatedSandboxRegistryEntry", () => { + it("records only an exact native NVIDIA provider identity", () => { + const attachment = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const entry = buildCreatedSandboxRegistryEntry( + createdRegistryEntryInput({ + inferenceSelection: { + model: "nvidia/nemotron-3-super-120b-a12b", + provider: "nvidia-prod", + endpointUrl: null, + credentialEnv: null, + preferredInferenceApi: null, + compatibleEndpointReasoning: null, + compatibleEndpointReasoningEffort: null, + nimContainer: null, + }, + nativeNvidiaProviderAttachment: attachment, + }), + ); + + expect(entry.nativeNvidiaProviderAttachment).toEqual(attachment); + expect(() => + buildCreatedSandboxRegistryEntry( + createdRegistryEntryInput({ + nativeNvidiaProviderAttachment: { ...attachment, providerId: "" }, + }), + ), + ).toThrow(/native NVIDIA provider attachment failed closed validation/u); + }); + it("records the resolved custom OpenShell gateway state directory (#10665)", () => { const entry = buildCreatedSandboxRegistryEntry( createdRegistryEntryInput({ diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index 2ab6b70e42f..aceb897b8ca 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -13,6 +13,7 @@ import { inferenceSelectionRegistryFields, normalizeInferenceSelection, } from "../inference/selection"; +import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia"; import { type WebSearchConfig, webSearchProviderForConfig } from "../inference/web-search"; import * as onboardSession from "../state/onboard-session"; import type { SandboxEntry, SandboxMessagingState } from "../state/registry"; @@ -68,6 +69,7 @@ export interface CreatedSandboxRegistryEntryInput { workload?: SandboxEntry["workload"]; hostLocalInferenceReceipt?: SandboxEntry["hostLocalInferenceReceipt"]; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; + nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; deferredN1xManagedVllmPreviewIntent?: true; toolDisclosure?: ToolDisclosure; observabilityEnabled?: boolean; @@ -206,6 +208,14 @@ export function buildCreatedSandboxRegistryEntry( const hostLocalInferenceProvenance = cloneSandboxHostLocalInferenceProvenance( input.hostLocalInferenceProvenance, ); + const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( + input.nativeNvidiaProviderAttachment, + ); + if (input.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + throw new RuntimeProviderSelectionError( + "Sandbox native NVIDIA provider attachment failed closed validation.", + ); + } if ( input.hostLocalInferenceProvenance !== undefined && (!hostLocalInferenceProvenance || typeof hostLocalInferenceReceipt !== "string") @@ -255,6 +265,7 @@ export function buildCreatedSandboxRegistryEntry( workload, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(deferredN1xManagedVllmAccepted ? { deferredN1xManagedVllmAccepted: true as const } : {}), toolDisclosure: input.toolDisclosure ?? DEFAULT_TOOL_DISCLOSURE, observabilityEnabled: input.observabilityEnabled === true, @@ -330,6 +341,10 @@ export function prepareCreatedSandboxRegistration( input.hostLocalInferenceProvenance !== undefined ? input.hostLocalInferenceProvenance : pending?.hostLocalInferenceProvenance; + const pendingNativeNvidiaProviderAttachment = + input.nativeNvidiaProviderAttachment !== undefined + ? input.nativeNvidiaProviderAttachment + : pending?.nativeNvidiaProviderAttachment; const entry = buildCreatedSandboxRegistryEntry({ ...input, inferenceSelection: pendingRoute @@ -341,6 +356,9 @@ export function prepareCreatedSandboxRegistration( ...(pendingHostLocalInferenceProvenance === undefined ? {} : { hostLocalInferenceProvenance: pendingHostLocalInferenceProvenance }), + ...(pendingNativeNvidiaProviderAttachment === undefined + ? {} + : { nativeNvidiaProviderAttachment: pendingNativeNvidiaProviderAttachment }), }); if (input.portableLifecycle === true) { if (getRequestedSandboxAgentName(input.agent) !== "openclaw") { diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 36e4ff26257..f34ac3e338e 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -3,8 +3,13 @@ import { describe, expect, it, vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; -import { createProviderReviewDeps } from "./setup-inference"; +import { + createProviderReviewDeps, + createSetupInference, + type SetupInferenceDeps, +} from "./setup-inference"; describe("createProviderReviewDeps", () => { it("prepares the Ollama proxy after review acceptance", async () => { @@ -176,3 +181,93 @@ describe("createProviderReviewDeps", () => { expect(ensureOllamaAuthProxy).not.toHaveBeenCalled(); }); }); + +describe("native NVIDIA onboarding", () => { + it("reserves the logical route with an attached-provider receipt and no shared route mutation", async () => { + const updateProvider = vi.fn(async () => ({ + ok: true, + })); + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true })), + getProvider: vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 4 }, + }, + })), + updateProvider, + } as unknown as OpenShellProviderAdapter; + const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); + const updateSandbox = vi.fn(() => true); + const verifyInferenceRoute = vi.fn(); + const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); + const setupInference = createSetupInference({ + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + step: vi.fn(), + getGatewayName: () => "nemoclaw", + runOpenshell, + updateSandbox, + upsertProvider: vi.fn(async () => ({ ok: true })), + verifyInferenceRoute, + verifyOnboardInferenceSmoke, + isNonInteractive: () => true, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + providerAdapter, + hydrateCredentialEnv: vi.fn(() => "host-only-nvidia-credential"), + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }), + } as unknown as SetupInferenceDeps); + + await expect( + setupInference( + "alpha", + "nvidia/nemotron-3-super-120b-a12b", + "nvidia-prod", + "https://integrate.api.nvidia.com/v1", + "NVIDIA_INFERENCE_API_KEY", + null, + [], + { revalidateSandboxIdentity: () => undefined }, + ), + ).resolves.toEqual({ ok: true }); + + expect(updateProvider).toHaveBeenCalledWith( + expect.objectContaining({ + providerName: "nemoclaw-nvidia-prod-v1", + credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "host-only-nvidia-credential" }], + config: [], + }), + ); + expect( + runOpenshell.mock.calls.filter(([args]) => args[0] === "inference" && args[1] === "set"), + ).toEqual([]); + expect(verifyInferenceRoute).not.toHaveBeenCalled(); + expect(verifyOnboardInferenceSmoke).toHaveBeenCalledOnce(); + expect(updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }, + }), + ); + }); +}); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 617fcd1aa88..2e9c1a3d7eb 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -20,6 +20,12 @@ import { withModelRouterPortLifecycleLock, } from "../inference/gateway-route-mutation-lock"; import { getManagedVllmProviderBinding, shouldFrontOllamaWithProxy } from "../inference/local"; +import { + ensureNativeNvidiaProvider, + isNativeNvidiaProvider, + NVIDIA_HOSTED_CREDENTIAL_ENV, + type NativeNvidiaProviderAttachment, +} from "../inference/native-nvidia"; import { clearPendingOllamaModelCleanup, isLocalOllamaRouteOwner, @@ -658,23 +664,25 @@ export function createSetupInference( ); return deps.exitProcess(1); } - const compatibility = deps.checkGatewayRouteCompatibility({ - gatewayName, - sandboxName, - route: { - provider, - model, - endpointUrl, - credentialEnv, - preferredInferenceApi: options.preferredInferenceApi ?? null, - }, - }); - if (!compatibility.ok) { - if (!isAdvisoryGatewayRouteConflict(compatibility)) { - deps.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); - return deps.exitProcess(1); + if (!isNativeNvidiaProvider(provider)) { + const compatibility = deps.checkGatewayRouteCompatibility({ + gatewayName, + sandboxName, + route: { + provider, + model, + endpointUrl, + credentialEnv, + preferredInferenceApi: options.preferredInferenceApi ?? null, + }, + }); + if (!compatibility.ok) { + if (!isAdvisoryGatewayRouteConflict(compatibility)) { + deps.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); + return deps.exitProcess(1); + } + deps.error(` ${formatGatewayRouteImpactWarning(compatibility)}`); } - deps.error(` ${formatGatewayRouteImpactWarning(compatibility)}`); } deps.step(4, 8, "Setting up inference provider"); let endpointPinnedAddresses = options.endpointPinnedAddresses; @@ -736,6 +744,7 @@ export function createSetupInference( | undefined; let hostLocalInferenceGatewayPortAuthority: number | undefined; let hostLocalInferenceRuntimeProviderId: string | undefined; + let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; const reserveRoute = (name: string, selectedProvider: string, selectedModel: string) => { if (routeReserved) return true; revalidateSandboxIdentity?.("reserve the sandbox inference route"); @@ -754,6 +763,7 @@ export function createSetupInference( reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(hostLocalInferenceProvenance && hostLocalInferenceGatewayPortAuthority !== undefined ? { gatewayPort: hostLocalInferenceGatewayPortAuthority } : {}), @@ -910,6 +920,21 @@ export function createSetupInference( ); } + if (isNativeNvidiaProvider(provider)) { + const resolvedCredentialEnv = credentialEnv || NVIDIA_HOSTED_CREDENTIAL_ENV; + const credentialValue = deps.hydrateCredentialEnv(resolvedCredentialEnv) || null; + const providerAdapter = deps.providerAdapter; + if (!providerAdapter) { + throw new Error("Native NVIDIA setup is missing its OpenShell provider adapter."); + } + nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ + adapter: providerAdapter, + target: { kind: "selected" }, + credentialValue, + }); + return null; + } + if (inferenceProviders.isRemoteProviderName(provider)) { const outcome = await inferenceProviders.setupRemoteProviderInference( { @@ -1084,7 +1109,7 @@ export function createSetupInference( try { const providerResult = await setupSelectedProvider(); if (providerResult) return providerResult; - commonDeps.verifyInferenceRoute(provider, model); + if (!nativeNvidiaProviderAttachment) commonDeps.verifyInferenceRoute(provider, model); if (hostLocalRoute) { deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", @@ -1228,7 +1253,11 @@ export function createSetupInference( revalidateSandboxIdentity, ); if (shouldLogSuccessfulRoute && "ok" in result) { - deps.log(` ✓ Inference route set: ${provider} / ${model}`); + deps.log( + isNativeNvidiaProvider(provider) + ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` + : ` ✓ Inference route set: ${provider} / ${model}`, + ); } return result; }; diff --git a/src/lib/registry-recovery-seeded-paths.test.ts b/src/lib/registry-recovery-seeded-paths.test.ts index b021676fe6e..e7ad3069248 100644 --- a/src/lib/registry-recovery-seeded-paths.test.ts +++ b/src/lib/registry-recovery-seeded-paths.test.ts @@ -277,7 +277,7 @@ describe("recoverRegistryEntries seeded recovery paths", () => { }); await expect( runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/model-b", sandboxName: "gamma" }, + { provider: "openrouter", model: "nvidia/model-b", sandboxName: "gamma" }, deps, ), ).rejects.toMatchObject({ diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 188603148dc..c38223f780b 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -8,6 +8,7 @@ import { inferenceSelectionRegistryFields, normalizeInferenceSelection, } from "../inference/selection"; +import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia"; import { parseServingProfileProvenance } from "../inference/serving/profile-provenance"; import { normalizeToolDisclosure } from "../tool-disclosure"; import { @@ -476,6 +477,14 @@ export function registerSandbox( ); } } + const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( + entry.nativeNvidiaProviderAttachment, + ); + if (entry.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + throw new Error( + "Cannot register a sandbox with an invalid native NVIDIA provider attachment", + ); + } const registered: SandboxEntry = { name: entry.name, createdAt: entry.createdAt || new Date().toISOString(), @@ -526,6 +535,7 @@ export function registerSandbox( : undefined, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), lifecycleGeneration: entry.lifecycleGeneration, lifecycleLiveIdentityFingerprint: entry.lifecycleLiveIdentityFingerprint, messaging: cloneSandboxMessagingState(entry.messaging), @@ -576,6 +586,7 @@ type SandboxInferenceRouteReservation = Pick< reservationSessionId?: string; hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; + nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; }; interface SandboxInferenceRouteReservationOptions { @@ -617,6 +628,12 @@ export function reserveSandboxInferenceRoute( ) return false; const normalized = normalizeInferenceSelection(route); + const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( + route.nativeNvidiaProviderAttachment, + ); + if (route.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + throw new Error("Cannot reserve invalid native NVIDIA provider attachment identity"); + } const provenance = cloneSandboxHostLocalInferenceProvenance(route.hostLocalInferenceProvenance); if ( route.hostLocalInferenceProvenance !== undefined && @@ -674,6 +691,10 @@ export function reserveSandboxInferenceRoute( existing.hostLocalInferenceProvenance, route.hostLocalInferenceProvenance ?? existing.hostLocalInferenceProvenance, ) && + isDeepStrictEqual( + existing.nativeNvidiaProviderAttachment, + nativeNvidiaProviderAttachment ?? existing.nativeNvidiaProviderAttachment, + ) && isDeepStrictEqual( normalizeInferenceSelection(existing), normalizeInferenceSelection(route), @@ -714,6 +735,7 @@ export function reserveSandboxInferenceRoute( ? { hostLocalInferenceReceipt: route.hostLocalInferenceReceipt } : {}), ...(provenance ? { hostLocalInferenceProvenance: provenance } : {}), + ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), gatewayName: route.gatewayName, gatewayPort: route.gatewayPort ?? diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 177eab7ff9e..4ac16f5351b 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -4,6 +4,7 @@ import { isDeepStrictEqual } from "node:util"; import { normalizeInferenceSelection, type InferenceSelection } from "../../inference/selection"; +import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import { isWebSearchProvider } from "../../inference/web-search/provider"; import { normalizePendingSandboxCreateIdentity } from "./pending-create-identity"; import type { PendingSandboxCreateIdentity, SandboxEntry } from "./types"; @@ -21,6 +22,7 @@ const ROUTE_RESERVATION_KEYS = new Set([ "lifecycleLiveIdentityFingerprint", "model", "name", + "nativeNvidiaProviderAttachment", "openshellDriver", "pendingRouteReservation", "pendingCreateIdentity", @@ -80,6 +82,12 @@ function validCarriedRouteMetadata(entry: SandboxEntry): boolean { if (entry.webSearchEnabled !== undefined && typeof entry.webSearchEnabled !== "boolean") { return false; } + if ( + entry.nativeNvidiaProviderAttachment !== undefined && + !normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) + ) { + return false; + } return ( entry.webSearchProvider === undefined || entry.webSearchProvider === null || diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 599af7e0062..93679f018e0 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { InferenceSelection } from "../../inference/selection"; +import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import type { ServingProfileProvenance } from "../../inference/serving/types"; import type { WebSearchProvider } from "../../inference/web-search"; import type { DcodeAutoApprovalMode } from "../../onboard/dcode-auto-approval"; @@ -132,6 +133,8 @@ export interface SandboxEntry extends Partial { managedStartupProtocol?: "identity-bound" | "legacy-unbound"; /** Canonical provider-neutral receipt for an out-of-sandbox inference runtime. */ hostLocalInferenceReceipt?: string | null; + /** Exact OpenShell provider identity attached for native NVIDIA hosted inference. */ + nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; /** Explicit hidden-lifecycle provenance; absence keeps llama.cpp on its legacy path. */ hostLocalInferenceProvenance?: SandboxHostLocalInferenceProvenance; /** Explicit Deferred N1x managed-vLLM choice retained after successful onboarding. */ diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index e92fa2fb8c2..b37fe817516 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -30,6 +30,7 @@ import type { DashboardDeliveryChain } from "./dashboard/contract"; import { listMessagingChannelsWithoutCredentials } from "./messaging/channels"; import { retryUntilAsync } from "./core/retry"; +import { isNativeNvidiaProvider } from "./inference/native-nvidia"; import { buildCustomOpenClawRuntimeFailureHints, classifyOpenClawRuntimeFailure, @@ -895,6 +896,7 @@ export async function probeOnboardInferenceInvocation( provider, model, preferredInferenceApi: context.preferredInferenceApi, + ...(isNativeNvidiaProvider(provider) ? { nativeProvider: true } : {}), }); return result.ok ? { ok: true } : { ok: false, detail: result.detail }; } diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index fbf950286bc..07c226bbb36 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -8,6 +8,7 @@ import os from "node:os"; import path from "node:path"; import { resolveAgentInferenceApi } from "../../../src/lib/inference/config.ts"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; import { execTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; @@ -221,13 +222,11 @@ export async function prepareProxyResolutionRoute({ apiKey, host, mockBaseline, - publicProvider, redactionValues, }: { apiKey: string; host: HostCliClient; mockBaseline: FakeOpenAiCompatibleServer | undefined; - publicProvider: ShellProbeResult | null; redactionValues: string[]; }): Promise<{ model: string; requestOffset: number }> { const endpoint = @@ -237,7 +236,7 @@ export async function prepareProxyResolutionRoute({ // Hosted mode already registered and attached the exact nvidia-prod // provider. The mock path needs an OpenAI provider for its local fixture. - if (publicProvider !== null) { + if (!mockBaseline) { return { model, requestOffset }; } @@ -669,6 +668,7 @@ export async function runHermesInferenceSetWithRetry( artifacts?: InferenceSwitchRetryArtifactSink; compatibleBinding?: CompatibleAnthropicSwitchBinding | null; delay?: (milliseconds: number) => Promise; + publicNvidiaApiKey?: string | null; } = {}, ): Promise { const args = [ @@ -692,7 +692,12 @@ export async function runHermesInferenceSetWithRetry( run: (attempt) => host.command("node", args, { artifactName: `hermes-inference-set-${attempt}`, - env: env(undefined, compatibleAnthropicSwitchEnv(options.compatibleBinding ?? null)), + env: env(undefined, { + ...compatibleAnthropicSwitchEnv(options.compatibleBinding ?? null), + ...(options.publicNvidiaApiKey + ? { NVIDIA_INFERENCE_API_KEY: options.publicNvidiaApiKey } + : {}), + }), redactionValues, timeoutMs: 180_000, }), @@ -734,6 +739,7 @@ export function maybeAssertPidStable( } export function expectedBaseUrl(): string { + if (SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER) return NVIDIA_HOSTED_NATIVE_ENDPOINT; return RUNTIME_SWITCH_API === "anthropic-messages" ? "https://inference.local" : "https://inference.local/v1"; @@ -811,7 +817,12 @@ function quotePayload(payload: string): string { return payload.replace(/'/gu, `'\\''`); } -export function inferenceLocalCommand(payload: string): string { +const NATIVE_NVIDIA_AUTH_HEADER = "Author" + "ization: Bearer nemoclaw-openshell-provider"; + +export function sandboxInferenceCommand(payload: string): string { + if (SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER) { + return `curl -sS --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H '${NATIVE_NVIDIA_AUTH_HEADER}' -d '${quotePayload(payload)}'`; + } return RUNTIME_SWITCH_API === "anthropic-messages" ? `curl -sS --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '${quotePayload(payload)}'` : `curl -sS --max-time 90 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' -d '${quotePayload(payload)}'`; diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index 91321a00551..c4d1837b3c1 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -13,6 +13,7 @@ import { apiKeyShape, chatContent, cleanupHermesSwitch, + CLI, compatibleAnthropicMetadataArgs, env, envHash, @@ -26,7 +27,7 @@ import { hermesApiCommand, hermesGatewayPid, hostedInstallModel, - inferenceLocalCommand, + sandboxInferenceCommand, inferenceLocalMaxTokens, installHermes, maybeAssertEnvHashStable, @@ -51,7 +52,6 @@ import { } from "./hermes-inference-switch-helpers.ts"; import { PUBLIC_NVIDIA_SWITCH_PROVIDER, - registerPublicNvidiaSwitchProvider, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; @@ -75,7 +75,7 @@ test( "install baseline Hermes runtime", "switch Hermes inference provider", "validate switched route and mutable config", - "exercise inference.local and Hermes API", + "exercise sandbox inference and Hermes API", "run Hermes CLI adapter forms against switched provider", "prove split provider/model credential resolution", ], @@ -179,10 +179,6 @@ test( model: hostedInstallModel(installEnv), }); const baselineSession = structuredClone(registryState().session); - const publicProvider = publicApiKey - ? await registerPublicNvidiaSwitchProvider(host, publicApiKey, env()) - : null; - publicProvider && expect(publicProvider.exitCode, resultText(publicProvider)).toBe(0); const switchBinding = await prepareCompatibleAnthropicSwitchBinding(host, cleanup); const switchEndpointUrl = switchBinding?.endpointUrl ?? null; switchBinding && redactionValues.push(switchBinding.credentialValue); @@ -199,6 +195,7 @@ test( { artifacts, compatibleBinding: switchBinding, + publicNvidiaApiKey: publicApiKey, }, ); expect(switched.exitCode, resultText(switched)).toBe(0); @@ -227,8 +224,8 @@ test( expect(health.exitCode, resultText(health)).toBe(0); expect(resultText(health)).toMatch(/ok/i); - const route = await sandbox.openshell(["inference", "get", "-g", "nemoclaw"], { - artifactName: "openshell-inference-route", + const route = await host.command("node", [CLI, "inference", "get"], { + artifactName: "nemoclaw-inference-route", env: env(), timeoutMs: 30_000, }); @@ -324,8 +321,7 @@ test( publicSwitch ? null : RUNTIME_SWITCH_API, ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.nimContainer).toBeNull(); - - progress.phase("exercise inference.local and Hermes API"); + progress.phase("exercise sandbox inference and Hermes API"); const inferenceLocalPayload = JSON.stringify({ model: SWITCH_MODEL, messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], @@ -334,14 +330,14 @@ test( const inferenceLocal = await runHermesPongWithRetry({ expectedModel: SWITCH_MODEL, onEvidence: async (evidence) => { - await artifacts.writeJson("retry/hermes-inference-local-after-switch.json", evidence); + await artifacts.writeJson("retry/hermes-sandbox-inference-after-switch.json", evidence); }, run: (attempt) => sandbox.execShell( SANDBOX_NAME, - trustedSandboxShellScript(inferenceLocalCommand(inferenceLocalPayload)), + trustedSandboxShellScript(sandboxInferenceCommand(inferenceLocalPayload)), { - artifactName: `hermes-inference-local-chat-after-switch-${attempt}`, + artifactName: `hermes-sandbox-inference-chat-after-switch-${attempt}`, env: env(), redactionValues, timeoutMs: 120_000, @@ -411,7 +407,6 @@ test( apiKey, host, mockBaseline, - publicProvider, redactionValues, }); const persistedProxyRoute = await sandbox.openshell(["inference", "get", "-g", "nemoclaw"], { diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 5405a8fc20c..0a091840801 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -4,8 +4,8 @@ /** * Preserve the script's real user-visible boundary: install.sh onboards an * OpenClaw sandbox, `nemoclaw inference set` switches the running route, then - * OpenShell route state, native OpenClaw config state, registry/session state, - * inference.local, and a real OpenClaw gateway model run are checked from the live + * NemoClaw route state, native OpenClaw config state, registry/session state, + * sandbox inference, and a real OpenClaw gateway model run are checked from the live * host/sandbox boundary. Target-specific helpers stay local; shared shell * primitives come from the fixture layer's production-backed helper. */ @@ -16,6 +16,7 @@ import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; @@ -63,7 +64,6 @@ import { import { PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, - registerPublicNvidiaSwitchProvider, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; @@ -78,6 +78,7 @@ const INSTALL_TIMEOUT_MS = execTimeout(30 * 60_000); const COMMAND_TIMEOUT_MS = 120_000; const INFERENCE_TIMEOUT_MS = 150_000; const AGENT_TIMEOUT_MS = 150_000; +const NATIVE_NVIDIA_AUTH_HEADER = "Author" + "ization: Bearer nemoclaw-openshell-provider"; validateSandboxName(SANDBOX_NAME); @@ -531,15 +532,10 @@ async function openclawGatewayPid(sandbox: SandboxClient, home: string): Promise } async function getRouteOutput(host: HostCliClient, home: string): Promise { - return host.command( - "bash", - ["-lc", "openshell inference get -g nemoclaw 2>&1 || openshell inference get 2>&1"], - { - artifactName: "openshell-inference-get-after-switch", - env: commandEnv(home), - timeoutMs: COMMAND_TIMEOUT_MS, - }, - ); + return runNemoclaw(host, home, ["inference", "get"], { + artifactName: "nemoclaw-inference-get-after-switch", + timeoutMs: COMMAND_TIMEOUT_MS, + }); } async function assertRegistryAndSession( @@ -586,8 +582,8 @@ async function assertRegistryAndSession( expect(session.preferredInferenceApi).toBe("anthropic-messages"); break; case PUBLIC_NVIDIA_SWITCH_PROVIDER: - expect(session.endpointUrl).toBe("https://inference.local/v1"); - expect(session.credentialEnv).toBe("OPENAI_API_KEY"); + expect(session.endpointUrl).toBe(NVIDIA_HOSTED_NATIVE_ENDPOINT); + expect(session.credentialEnv).toBe("NVIDIA_INFERENCE_API_KEY"); expect(session.preferredInferenceApi).toBe("openai-completions"); break; } @@ -621,9 +617,11 @@ async function readAndAssertOpenClawConfig( expect(config.agents?.defaults?.model?.primary).toBe(expectedPrimary); expect(provider?.baseUrl).toBe( - expected.inferenceApi === "anthropic-messages" - ? "https://inference.local" - : "https://inference.local/v1", + SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER + ? NVIDIA_HOSTED_NATIVE_ENDPOINT + : expected.inferenceApi === "anthropic-messages" + ? "https://inference.local" + : "https://inference.local/v1", ); expect(provider?.apiKey).toBe("unused"); expect(provider?.api).toBe(expected.inferenceApi); @@ -719,9 +717,11 @@ async function checkSandboxInference( }; const payloadB64 = Buffer.from(JSON.stringify(payload), "utf8").toString("base64"); const curlCommand = - SWITCH_INFERENCE_API === "anthropic-messages" - ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' --data-binary @/tmp/nemoclaw-switch-payload.json` - : `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data-binary @/tmp/nemoclaw-switch-payload.json`; + SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER + ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H '${NATIVE_NVIDIA_AUTH_HEADER}' --data-binary @/tmp/nemoclaw-switch-payload.json` + : SWITCH_INFERENCE_API === "anthropic-messages" + ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' --data-binary @/tmp/nemoclaw-switch-payload.json` + : `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data-binary @/tmp/nemoclaw-switch-payload.json`; const script = [ "set -u", "tmp=$(mktemp)", @@ -750,7 +750,7 @@ async function checkSandboxInference( }, run: async (attempt) => { const result = await sandboxShell(sandbox, home, script, { - artifactName: `sandbox-inference-local-after-switch-${attempt}`, + artifactName: `sandbox-inference-after-switch-${attempt}`, timeoutMs: INFERENCE_TIMEOUT_MS, }); const response = resultText(result); @@ -803,10 +803,10 @@ async function checkSandboxInference( const lastFailure = execution.value?.lastFailure ?? "probe failed without a result"; if (execution.evidence.outcome === "exhausted") { return { - skipped: `Sandbox inference.local transient failure after switch; route/config checks already passed: ${lastFailure}`, + skipped: `Sandbox inference transient failure after switch; route/config checks already passed: ${lastFailure}`, }; } - throw new Error(`Sandbox inference.local did not work after switch: ${lastFailure}`); + throw new Error(`Sandbox inference did not work after switch: ${lastFailure}`); } async function checkOpenClawGatewayInference( @@ -1012,6 +1012,7 @@ async function runOpenClawInferenceSetWithRetry( home: string, redactionValues: string[], switchBinding: CompatibleAnthropicSwitchBinding | null, + publicNvidiaApiKey: string | null, artifacts: { writeJson(path: string, value: unknown): Promise }, ): Promise { const attempts = inferenceSetAttemptCount(process.env.NEMOCLAW_SWITCH_SET_ATTEMPTS); @@ -1053,7 +1054,10 @@ async function runOpenClawInferenceSetWithRetry( run: (attempt) => runNemoclaw(host, home, args, { artifactName: `nemoclaw-inference-set-${attempt}`, - env: compatibleAnthropicSwitchEnv(switchBinding), + env: { + ...compatibleAnthropicSwitchEnv(switchBinding), + ...(publicNvidiaApiKey ? { NVIDIA_INFERENCE_API_KEY: publicNvidiaApiKey } : {}), + }, redactionValues, timeoutMs: COMMAND_TIMEOUT_MS, }), @@ -1075,7 +1079,7 @@ test( "prepare the switched provider and endpoint", "switch the route and verify restart semantics", "inspect route configuration and recorded state", - "prove inference.local and OpenClaw gateway inference", + "prove sandbox and OpenClaw gateway inference", "apply sandbox retention and record the result", ], }, @@ -1098,10 +1102,10 @@ test( "when selected, the mock baseline route completes one explicit authenticated fixture request", "nemoclaw inference set switches the running sandbox route", "OpenClaw gateway is supervisor-restarted after every changed inference configuration", - "OpenShell route points at the switched provider/model", + "NemoClaw reports the switched provider/model", "OpenClaw config reflects the switched inference API/model", "registry and onboard session record the switched provider/model", - "sandbox inference.local returns PONG from the switched model", + "sandbox inference returns PONG from the switched model", "OpenClaw gateway model inference answers through the switched route without agent tools", ], }); @@ -1224,11 +1228,6 @@ test( }); progress.phase("prepare the switched provider and endpoint"); - const publicProvider = publicApiKey - ? await registerPublicNvidiaSwitchProvider(host, publicApiKey, commandEnv(home)) - : null; - publicProvider && expect(publicProvider.exitCode, resultText(publicProvider)).toBe(0); - if (SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1") { mockProvider = await startMockAnthropicProvider(); await artifacts.writeJson("mock-anthropic-provider.json", { @@ -1263,6 +1262,7 @@ test( home, redactionValues, switchBinding, + publicApiKey, artifacts, ); expect(switchResult.exitCode, resultText(switchResult)).toBe(0); @@ -1295,7 +1295,7 @@ test( }); await assertRegistryAndSession(home, { mockProvider }); - progress.phase("prove inference.local and OpenClaw gateway inference"); + progress.phase("prove sandbox and OpenClaw gateway inference"); const inference = await checkSandboxInference(sandbox, artifacts, home); if (inference !== "ok") { await artifacts.target.complete({ @@ -1315,7 +1315,7 @@ test( model: SWITCH_MODEL, inferenceApi: SWITCH_INFERENCE_API, artifactName: "openclaw-gateway-inference-after-switch", - phase: "prove inference.local and OpenClaw gateway inference", + phase: "prove sandbox and OpenClaw gateway inference", }, mockProvider, ); diff --git a/test/e2e/live/public-nvidia-switch-provider.ts b/test/e2e/live/public-nvidia-switch-provider.ts index f2cd59cf243..b65b24f65f1 100644 --- a/test/e2e/live/public-nvidia-switch-provider.ts +++ b/test/e2e/live/public-nvidia-switch-provider.ts @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { HostCliClient } from "../fixtures/clients/host.ts"; -import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; - export const PUBLIC_NVIDIA_SWITCH_PROVIDER = "nvidia-prod"; export const PUBLIC_NVIDIA_SWITCH_MODEL = "nvidia/nemotron-3-super-120b-a12b"; @@ -13,29 +10,3 @@ export function requirePublicNvidiaSwitchKey(value: string): string { } return value; } - -export async function registerPublicNvidiaSwitchProvider( - host: HostCliClient, - apiKey: string, - env: NodeJS.ProcessEnv, -): Promise { - const { - NVIDIA_API_KEY: _publicApiKey, - NVIDIA_INFERENCE_API_KEY: _inferenceApiKey, - ...providerEnv - } = env; - const script = [ - "set -euo pipefail", - `if openshell provider get -g nemoclaw ${PUBLIC_NVIDIA_SWITCH_PROVIDER} >/dev/null 2>&1; then`, - ` openshell provider update -g nemoclaw ${PUBLIC_NVIDIA_SWITCH_PROVIDER} --credential NVIDIA_INFERENCE_API_KEY`, - "else", - ` openshell provider create -g nemoclaw --name ${PUBLIC_NVIDIA_SWITCH_PROVIDER} --type nvidia --credential NVIDIA_INFERENCE_API_KEY`, - "fi", - ].join("\n"); - return host.command("bash", ["-lc", script], { - artifactName: "register-public-nvidia-switch-provider", - env: { ...providerEnv, NVIDIA_INFERENCE_API_KEY: apiKey }, - redactionValues: [apiKey], - timeoutMs: 120_000, - }); -} diff --git a/test/e2e/support/public-nvidia-switch-provider.test.ts b/test/e2e/support/public-nvidia-switch-provider.test.ts index 182e91c5c84..3948fd7479a 100644 --- a/test/e2e/support/public-nvidia-switch-provider.test.ts +++ b/test/e2e/support/public-nvidia-switch-provider.test.ts @@ -1,12 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it, vi } from "vitest"; -import type { HostCliClient } from "../fixtures/clients/host.ts"; +import { describe, expect, it } from "vitest"; import { PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, - registerPublicNvidiaSwitchProvider, requirePublicNvidiaSwitchKey, } from "../live/public-nvidia-switch-provider.ts"; @@ -17,38 +15,4 @@ describe("public NVIDIA inference switch provider", () => { expect(requirePublicNvidiaSwitchKey("nvapi-public-key")).toBe("nvapi-public-key"); expect(() => requirePublicNvidiaSwitchKey("sk-hosted-key")).toThrow(/nvapi-\*/u); }); - - it("aliases the public key only to the registered provider credential env", async () => { - const command = vi.fn().mockResolvedValue({ exitCode: 0, stderr: "", stdout: "" }); - - await registerPublicNvidiaSwitchProvider( - { command } as unknown as HostCliClient, - "nvapi-public-key", - { - NVIDIA_API_KEY: "must-not-be-forwarded", - NVIDIA_INFERENCE_API_KEY: "must-be-replaced", - OPENSHELL_GATEWAY: "nemoclaw", - PATH: "/usr/bin", - }, - ); - - const [program, args, options] = command.mock.calls[0]!; - expect(program).toBe("bash"); - expect(args[1]).toContain("provider get -g nemoclaw nvidia-prod"); - expect(args[1]).toContain( - "provider create -g nemoclaw --name nvidia-prod --type nvidia --credential NVIDIA_INFERENCE_API_KEY", - ); - expect(args[1]).toContain( - "provider update -g nemoclaw nvidia-prod --credential NVIDIA_INFERENCE_API_KEY", - ); - expect(options).toMatchObject({ - env: { - NVIDIA_INFERENCE_API_KEY: "nvapi-public-key", - OPENSHELL_GATEWAY: "nemoclaw", - PATH: "/usr/bin", - }, - redactionValues: ["nvapi-public-key"], - }); - expect(options.env).not.toHaveProperty("NVIDIA_API_KEY"); - }); }); diff --git a/test/inference/managed/nemotron-inference-fix.test.ts b/test/inference/managed/nemotron-inference-fix.test.ts index c207d578dd2..ef60f196081 100644 --- a/test/inference/managed/nemotron-inference-fix.test.ts +++ b/test/inference/managed/nemotron-inference-fix.test.ts @@ -204,6 +204,8 @@ function send(mod, options, body) { process.env.NEMOCLAW_UPSTREAM_PROVIDER = 'nvidia-prod'; send(http, { method: 'POST', host: 'inference.local', path: '/v1/chat/completions' }, JSON.stringify({ model: 'nvidia/nemotron-3-ultra-550b-a55b', messages: [{ role: 'system', content: 'x' }], thinking: { type: 'enabled' } })); send(https, { method: 'POST', hostname: 'inference.local', path: '/v1/chat/completions' }, JSON.stringify({ model: 'nvidia/nemotron-3-ultra-550b-a55b', messages: [{ role: 'system', content: 'x' }], thinking: true })); +send(https, { method: 'POST', hostname: 'integrate.api.nvidia.com', path: '/v1/chat/completions' }, JSON.stringify({ model: 'nvidia/nemotron-3-ultra-550b-a55b', messages: [{ role: 'system', content: 'x' }], thinking: true })); +send(https, { method: 'POST', hostname: 'other.example.com', path: '/v1/chat/completions' }, JSON.stringify({ model: 'nvidia/nemotron-3-ultra-550b-a55b', messages: [{ role: 'system', content: 'x' }], thinking: true })); send(https, { method: 'POST', host: 'inference.local', path: '/v1/chat/completions' }, JSON.stringify({ model: 'nvidia/nemotron-3-ultra-550b-a55b', messages: [{ role: 'system', content: 'x' }] })); send(https, { method: 'POST', host: 'inference.local', path: '/v1/chat/completions' }, JSON.stringify({ model: 'nvidia/nemotron-4-ultra-550b-a55b', messages: [{ role: 'system', content: 'x' }], thinking: { type: 'enabled' } })); send(https, { method: 'POST', host: 'inference.local', path: '/v1/chat/completions' }, JSON.stringify({ model: 'nvidia/nemotron-3-super-120b-a12b', messages: [{ role: 'system', content: 'x' }], thinking: { type: 'enabled' } })); @@ -242,14 +244,21 @@ console.log(JSON.stringify(records)); const ultraBool = JSON.parse(records[1].writes[0]); expect(ultraBool).toEqual(ultraObj); + // The attached OpenShell provider sends the request to NVIDIA Build's + // public hostname, while unrelated direct hosts remain outside the strip. + const nativeProvider = JSON.parse(records[2].writes[0]); + expect(nativeProvider).toEqual(ultraObj); + const unrelatedDirectHost = JSON.parse(records[3].writes[0]); + expect(unrelatedDirectHost.thinking).toBe(true); + // Ultra without a thinking field → nothing to strip; still nemotron, so // force_nonempty_content is injected by the kwargs rule. - const ultraNone = JSON.parse(records[2].writes[0]); + const ultraNone = JSON.parse(records[4].writes[0]); expect(ultraNone).toEqual(ultraObj); // Adjacent Nemotron families remain outside the accepted strip scope. Their // pre-existing force_nonempty_content rewrite remains. - const otherFamily = JSON.parse(records[3].writes[0]); + const otherFamily = JSON.parse(records[5].writes[0]); expect(otherFamily).toEqual({ model: "nvidia/nemotron-4-ultra-550b-a55b", messages: [{ role: "system", content: "x" }], @@ -257,14 +266,14 @@ console.log(JSON.stringify(records)); chat_template_kwargs: { force_nonempty_content: true }, }); - const superObj = JSON.parse(records[4].writes[0]); + const superObj = JSON.parse(records[6].writes[0]); expect(superObj).toEqual({ model: "nvidia/nemotron-3-super-120b-a12b", messages: [{ role: "system", content: "x" }], chat_template_kwargs: { force_nonempty_content: true }, }); - const nanoBool = JSON.parse(records[5].writes[0]); + const nanoBool = JSON.parse(records[7].writes[0]); expect(nanoBool).toEqual({ model: "nvidia/nemotron-3-nano-30b-a3b", messages: [{ role: "system", content: "x" }], @@ -273,7 +282,7 @@ console.log(JSON.stringify(records)); // deepseek-v4-pro is out of the strip scope → top-level thinking preserved; // it gets the chat_template_kwargs.thinking rewrite instead. - const deepSeek = JSON.parse(records[6].writes[0]); + const deepSeek = JSON.parse(records[8].writes[0]); expect(deepSeek).toEqual({ model: "deepseek-ai/deepseek-v4-pro", messages: [], @@ -284,26 +293,26 @@ console.log(JSON.stringify(records)); // gpt-oss-120b accepts top-level thinking on the endpoint, so no rule // matches it and the request passes through completely untouched — proving // the strip is not a blanket rewrite. - const gptOss = JSON.parse(records[7].writes[0]); + const gptOss = JSON.parse(records[9].writes[0]); expect(gptOss).toEqual({ model: "openai/gpt-oss-120b", messages: [], thinking: { type: "enabled" }, }); - const compatibleEndpoint = JSON.parse(records[8].writes[0]); + const compatibleEndpoint = JSON.parse(records[10].writes[0]); expect(compatibleEndpoint.thinking).toEqual({ type: "enabled" }); - expect(records[8].removed).toContain("x-nemoclaw-upstream-provider"); + expect(records[10].removed).toContain("x-nemoclaw-upstream-provider"); - const localNim = JSON.parse(records[9].writes[0]); + const localNim = JSON.parse(records[11].writes[0]); expect(localNim.thinking).toBe(true); - expect(records[9].removed).toContain("x-nemoclaw-upstream-provider"); + expect(records[11].removed).toContain("x-nemoclaw-upstream-provider"); - const switchedToBuild = JSON.parse(records[10].writes[0]); + const switchedToBuild = JSON.parse(records[12].writes[0]); expect(switchedToBuild.thinking).toBeUndefined(); - expect(records[10].removed).toContain("x-nemoclaw-upstream-provider"); + expect(records[12].removed).toContain("x-nemoclaw-upstream-provider"); - const missingProvider = JSON.parse(records[11].writes[0]); + const missingProvider = JSON.parse(records[13].writes[0]); expect(missingProvider.thinking).toBe(false); }); From be119ed9036c45fde8ccf9eda3e6cb6d41df60a2 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:53:22 -0700 Subject: [PATCH 002/133] fix(credentials): resolve native NVIDIA profile Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/credentials-add.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index 24e0194192d..9b6803b84e4 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -17,6 +17,7 @@ import { NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, + nativeNvidiaProviderProfilePath, } from "../inference/native-nvidia"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, @@ -132,6 +133,9 @@ async function providerConfigEndpointFailure( function bundledProviderProfile(type: string): { profileType: string; profilePath: string } | null { const profileType = type.toLowerCase(); + if (profileType === NVIDIA_HOSTED_NATIVE_PROFILE_ID) { + return { profileType, profilePath: nativeNvidiaProviderProfilePath() }; + } const profilePath = path.join( ROOT, "nemoclaw-blueprint", From 48ba1ce5c88d56fceba963a36c1916a7a6af7654 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 15:15:35 -0700 Subject: [PATCH 003/133] test(inference): refresh native NVIDIA evidence --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- test/e2e/mock-parity.json | 6 +++++- ...mes-inference-switch-command-shape.test.ts | 20 +++++++++++++++++++ .../cli/credentials-cli-command.test.ts | 2 +- 6 files changed, 36 insertions(+), 12 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index 4e002501d24..f625fa4c016 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:c2a61a16fb8960535d23ee9cc70fcc9ab34f444c80fbba94c26ed14326894c1a", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:c2a61a16fb8960535d23ee9cc70fcc9ab34f444c80fbba94c26ed14326894c1a", + "digest": "sha256:f43003756e2bdd43e24de426d16af6a96fa335d0a083fa3adeaaa2d5413a2faf", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:f43003756e2bdd43e24de426d16af6a96fa335d0a083fa3adeaaa2d5413a2faf", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "ddf20ef245ed59eca4fe507f3a999fc9c34bb925", + "revision": "be119ed9036c45fde8ccf9eda3e6cb6d41df60a2", "release": "v0.1.0", - "cohort": "ghrun-36757441033-1" + "cohort": "ghrun-36932404967-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index a979ee6d5de..da819e20346 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:46e4d6b96c5d74df873ca0a4db998e448734589dbf5aaa426d279f6387d02a59", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:46e4d6b96c5d74df873ca0a4db998e448734589dbf5aaa426d279f6387d02a59", + "digest": "sha256:480a2ac719e9d33cab19033a07328de045de47fc551c8d6815aebe89e7f70a3a", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:480a2ac719e9d33cab19033a07328de045de47fc551c8d6815aebe89e7f70a3a", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "ddf20ef245ed59eca4fe507f3a999fc9c34bb925", + "revision": "be119ed9036c45fde8ccf9eda3e6cb6d41df60a2", "release": "v0.1.0", - "cohort": "ghrun-36757441033-1" + "cohort": "ghrun-36932404967-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 1516b9bd523..0945b2f2977 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "e4f525895c24fbb5321973a410140fe9c5c0f18cfa6f88f09742f5bedcdf13bb", - "e587ed7e09fa4f172d797ba86985c11588e977f9283a4734547a14c28d9f7e23", + "9b70f7bf2252b41c3f3043be308dee7ce32be6f0e9b340b967902020a0eab1cb", + "6ef59d99377edbcac8625e9626c044f78029cd567aefb5e25cc96c0d7ad615bd", ]), }); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 190f9974538..db25ca2b4cf 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -659,9 +659,13 @@ }, { "live": "test/e2e/live/hermes-inference-switch.test.ts", - "liveSources": ["test/e2e/live/hermes-inference-switch-helpers.ts"], + "liveSources": [ + "test/e2e/live/hermes-inference-switch-helpers.ts", + "test/e2e/live/public-nvidia-switch-provider.ts" + ], "fast": [ "src/lib/actions/inference-set-compatible-provider.test.ts", + "test/e2e/support/hermes-inference-switch-command-shape.test.ts", "test/e2e/support/retry-policy.test.ts", "test/e2e/support/compatible-anthropic-switch.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", 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 6075880f5d5..5353fee9636 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -540,4 +540,24 @@ describe("Hermes inference switch command shape", () => { expect.objectContaining({ outcome: "passed-after-retry" }), ); }); + + it("passes the public NVIDIA credential only to the native provider switch", async () => { + const command = vi.fn().mockResolvedValue({ exitCode: 0, stderr: "", stdout: "route synced" }); + + await runHermesInferenceSetWithRetry( + { command } as unknown as HostCliClient, + ["nvapi-hosted-key"], + [], + { + attempts: 1, + publicNvidiaApiKey: "nvapi-hosted-key", + }, + ); + + expect(command).toHaveBeenCalledOnce(); + expect(command.mock.calls[0]?.[2]).toMatchObject({ + env: { NVIDIA_INFERENCE_API_KEY: "nvapi-hosted-key" }, + redactionValues: ["nvapi-hosted-key"], + }); + }); }); diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index 18729e6c33e..702a58f0802 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -349,7 +349,7 @@ describe("credentials oclif commands", () => { expect(calls).toEqual([ { - args: ["provider", "delete", "-g", "nemoclaw", "nvidia-prod"], + args: ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], opts: { env: expect.any(Object), ignoreError: true, From cee41abcc834393170e464ff80c5fbc94b1b07a7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:28:37 -0700 Subject: [PATCH 004/133] fix(inference): harden native provider transitions --- .../generate-config.ts | 4 +- src/lib/actions/inference-set.ts | 9 +- src/lib/inference/native-nvidia.test.ts | 93 ++++++++++++++++++- src/lib/inference/native-nvidia/index.ts | 28 ++++-- src/lib/onboard/setup-inference.test.ts | 1 + src/lib/onboard/setup-inference.ts | 8 ++ ...ain-deepagents-code-provider-label.test.ts | 10 +- .../providerless-agent-config.test.ts | 2 +- ...rd-build-recreate-credential-reuse.test.ts | 17 ++++ .../onboard-fresh-create-identity.test.ts | 2 +- .../onboard-inference-gateway-scope.test.ts | 26 +++--- .../onboard-prepared-build-context.test.ts | 2 +- .../onboard-terminal-dashboard.test.ts | 8 +- test/support/setup-inference-test-harness.ts | 3 + 14 files changed, 179 insertions(+), 34 deletions(-) diff --git a/agents/langchain-deepagents-code/generate-config.ts b/agents/langchain-deepagents-code/generate-config.ts index 9ba17bd9d1a..0c3789e6876 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -168,8 +168,8 @@ function providerConfigLines( ? [ "", "[models.providers.openai.params]", - "# NemoClaw-managed inference.local currently exposes Chat Completions.", - "# Remove this override when that route supports OpenAI Responses API.", + "# NemoClaw-managed OpenAI-compatible routes use Chat Completions.", + "# Remove this override when the selected route supports OpenAI Responses API.", "use_responses_api = false", ...openAiModelRequestParamLines(model, reasoningEffort), ] diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 8d453525c27..f72005d147d 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1944,6 +1944,11 @@ export async function runInferenceSet( // this sandbox between the committed write, an optional restart, and // device-scope convergence. await completeInferencePostCommit(mutation, deps); + // The agent config has converged once post-commit work succeeds. Do not + // leave its recovery marker pending if later provider cleanup fails. + if (mutation.openClawConfigSyncPending) { + clearOpenClawConfigSyncPending(selected.sandboxName, deps); + } const priorNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( lockedSelection.entry.nativeNvidiaProviderAttachment, ); @@ -1964,10 +1969,6 @@ export async function runInferenceSet( ); } } - // Keep recovery pending until both the running gateway and pairing have converged. - if (mutation.openClawConfigSyncPending) { - clearOpenClawConfigSyncPending(selected.sandboxName, deps); - } return mutation.result; }); } diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index bd36bb90206..1d0e59627be 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -8,6 +8,7 @@ import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-ad import { parseCheckedInProviderProfileContract } from "../adapters/openshell/provider-profile"; import { ensureNativeNvidiaProvider, + ensureNativeNvidiaProviderAttached, nativeNvidiaProviderProfilePath, NativeNvidiaProviderError, NVIDIA_HOSTED_CREDENTIAL_ENV, @@ -42,8 +43,8 @@ function adapter(overrides: Partial = {}): OpenShellPr listProviders: vi.fn(), inspectProviderProfile: vi.fn(), deleteProvider: vi.fn(), - detachProvider: vi.fn(), - attachProvider: vi.fn(), + detachProvider: vi.fn(async () => ({ ok: true })), + attachProvider: vi.fn(async () => ({ ok: true })), configureProviderRefresh: vi.fn(), getProviderRefreshStatus: vi.fn(), ...overrides, @@ -130,6 +131,35 @@ describe("native NVIDIA OpenShell provider", () => { expect(createProvider).toHaveBeenCalledOnce(); }); + it("creates from an existing gateway credential when recreation has no local key (#12558)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: true, + })); + + await expect( + ensureNativeNvidiaProvider({ + adapter: adapter({ getProvider, createProvider }), + target, + credentialValue: null, + reuseExistingCredential: true, + }), + ).resolves.toMatchObject({ providerId: "provider-id" }); + expect(createProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + name: NVIDIA_HOSTED_NATIVE_PROVIDER, + credentials: [], + fromExisting: true, + }), + ); + }); + it("refuses a replaced provider before rotating its credential (#12558)", async () => { const updateProvider = vi.fn(); @@ -201,4 +231,63 @@ describe("native NVIDIA OpenShell provider", () => { }), ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); }); + + it("removes a newly attached provider when attachment verification fails (#12558)", async () => { + const listProviderAttachments = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }); + const detachProvider = vi.fn(async () => ({ + ok: true, + value: { changed: true }, + })); + const providerAdapter = adapter({ listProviderAttachments, detachProvider }); + + await expect( + ensureNativeNvidiaProviderAttached({ + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); + expect(detachProvider).toHaveBeenCalledExactlyOnceWith({ + target, + sandboxName: "alpha", + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }); + }); + + it("preserves verification and cleanup failures after a new attachment (#12558)", async () => { + const listProviderAttachments = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ + ok: true, + value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, + }); + + await expect( + ensureNativeNvidiaProviderAttached({ + adapter: adapter({ listProviderAttachments }), + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + }, + }), + ).rejects.toThrow( + /does not have its native NVIDIA inference provider attached[\s\S]*did not confirm removal/u, + ); + }); }); diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 08aa4abbca5..2cefab8451a 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -133,6 +133,7 @@ export async function ensureNativeNvidiaProvider(input: { adapter: OpenShellProviderAdapter; target: OpenShellGatewayTarget; credentialValue: string | null; + reuseExistingCredential?: boolean; expected?: NativeNvidiaProviderAttachment; profilePath?: string; }): Promise { @@ -180,7 +181,7 @@ export async function ensureNativeNvidiaProvider(input: { return attachmentFromMetadata(observed); } - if (!input.credentialValue) { + if (!input.credentialValue && !input.reuseExistingCredential) { throw new NativeNvidiaProviderError( `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, ); @@ -189,9 +190,11 @@ export async function ensureNativeNvidiaProvider(input: { target, name: NVIDIA_HOSTED_NATIVE_PROVIDER, type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], + credentials: input.credentialValue + ? [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }] + : [], config: [], - fromExisting: false, + fromExisting: !input.credentialValue, }); if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { throw new NativeNvidiaProviderError( @@ -275,10 +278,21 @@ export async function ensureNativeNvidiaProviderAttached(input: { `Could not attach native NVIDIA provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, ); } - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: true, - }; + try { + return { + receipt: await verifyNativeNvidiaProviderAttachment(input), + changed: true, + }; + } catch (error) { + try { + await detachNativeNvidiaProvider(input); + } catch (detachError) { + const detail = error instanceof Error ? error.message : String(error); + const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); + throw new NativeNvidiaProviderError(`${detail}\n ${detachDetail}`); + } + throw error; + } } /** Detach only the recorded native NVIDIA provider identity and prove absence. */ diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index f34ac3e338e..20ebe041d88 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -215,6 +215,7 @@ describe("native NVIDIA onboarding", () => { getGatewayName: () => "nemoclaw", runOpenshell, updateSandbox, + getSandbox: () => null, upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute, verifyOnboardInferenceSmoke, diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 2e9c1a3d7eb..cfa9f30ac2b 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -24,6 +24,7 @@ import { ensureNativeNvidiaProvider, isNativeNvidiaProvider, NVIDIA_HOSTED_CREDENTIAL_ENV, + normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, } from "../inference/native-nvidia"; import { @@ -927,10 +928,17 @@ export function createSetupInference( if (!providerAdapter) { throw new Error("Native NVIDIA setup is missing its OpenShell provider adapter."); } + const recordedAttachment = sandboxName + ? normalizeNativeNvidiaProviderAttachment( + deps.getSandbox?.(sandboxName)?.nativeNvidiaProviderAttachment, + ) + : undefined; nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ adapter: providerAdapter, target: { kind: "selected" }, credentialValue, + reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, + ...(recordedAttachment ? { expected: recordedAttachment } : {}), }); return null; } diff --git a/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts b/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts index e955228086d..4add8cf0dba 100644 --- a/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts @@ -67,9 +67,13 @@ describe("LangChain Deep Agents Code managed provider label", () => { const config = fs.readFileSync(path.join(tempDir, ".deepagents", "config.toml"), "utf8"); expect(config).toContain(`default = "openai:${model}"`); expect(config).toContain("[models.providers.openai]"); - expect(config).toContain('base_url = "https://inference.local/v1"'); + expect(config).toContain('base_url = "https://integrate.api.nvidia.com/v1"'); expect(config).toContain("upstream provider: nvidia-prod"); + const managedBaseUrlPath = path.join(tempDir, "managed-inference-base-url"); + fs.chmodSync(managedBaseUrlPath, 0o644); + fs.writeFileSync(managedBaseUrlPath, `${runtimeEnv.NEMOCLAW_INFERENCE_BASE_URL}\n`, "utf8"); + fs.chmodSync(managedBaseUrlPath, 0o444); patchFixture(tempDir); const validation = ` import os @@ -83,8 +87,8 @@ model = "nvidia/nemotron-3-super-120b-a12b" assert os.environ["NEMOCLAW_UPSTREAM_PROVIDER"] == "ambient-provider" _nemoclaw_managed.assert_safe_runtime() assert os.environ["NEMOCLAW_UPSTREAM_PROVIDER"] == "nvidia-prod" -assert os.environ["OPENAI_BASE_URL"] == "https://inference.local/v1" -assert os.environ["NEMOCLAW_INFERENCE_BASE_URL"] == "https://inference.local/v1" +assert os.environ["OPENAI_BASE_URL"] == "https://integrate.api.nvidia.com/v1" +assert os.environ["NEMOCLAW_INFERENCE_BASE_URL"] == "https://integrate.api.nvidia.com/v1" for upstream in ("nvidia", "nvidia-prod", "nvidia-nim", "nvidia-router"): os.environ["NEMOCLAW_UPSTREAM_PROVIDER"] = upstream diff --git a/test/generation/providerless-agent-config.test.ts b/test/generation/providerless-agent-config.test.ts index 90df24710aa..b7230219aac 100644 --- a/test/generation/providerless-agent-config.test.ts +++ b/test/generation/providerless-agent-config.test.ts @@ -280,7 +280,7 @@ describe.each(["openclaw", "hermes"])("providerless %s configuration", (a }); await expect( runInferenceSet( - { sandboxName: "alpha", provider: "nvidia-prod", model: "fixture/model" }, + { sandboxName: "alpha", provider: "openai-api", model: "fixture/model" }, deps, ), ).rejects.toThrow(); diff --git a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts index 8b4e209289e..798a5554db6 100644 --- a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts @@ -51,6 +51,23 @@ Gateway inference: EOF exit 0 fi +if [ "$1" = "provider" ] && [ "$2" = "profile" ] && [ "$3" = "export" ]; then + cat <<'EOF' +{"id":"nemoclaw-nvidia-inference-v1","credentials":[{"name":"api_key","env_vars":["NVIDIA_INFERENCE_API_KEY"],"required":true,"auth_style":"bearer","header_name":"authorization","query_param":""}],"endpoints":[{"host":"integrate.api.nvidia.com","port":443,"protocol":"rest","enforcement":"enforce","rules":[{"allow":{"method":"GET","path":"/v1/models"}},{"allow":{"method":"POST","path":"/v1/chat/completions"}}]}],"binaries":["/usr/local/bin/node","/usr/bin/node","/opt/hermes/.venv/bin/python","/opt/hermes/.venv/bin/python3","/opt/venv/bin/python3","/usr/local/bin/curl","/usr/bin/curl"],"inference_capable":true} +EOF + exit 0 +fi +if [ "$1" = "provider" ] && [ "$2" = "get" ] && [ "$3" = "nemoclaw-nvidia-prod-v1" ]; then + cat <<'EOF' +Name: nemoclaw-nvidia-prod-v1 +Id: provider-id +Type: nemoclaw-nvidia-inference-v1 +Resource version: 1 +Credential keys: NVIDIA_INFERENCE_API_KEY +Config keys: +EOF + exit 0 +fi if [ "$1" = "provider" ] && [ "$2" = "get" ] && [ "$5" = "nvidia-prod" ]; then cat <<'EOF' Name: nvidia-prod diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index 5329b28a26b..ec2f1eeabe2 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -981,7 +981,7 @@ if (${JSON.stringify( assert.ok(profile.inference); assert.equal( startup.configurationEnvironment.NEMOCLAW_INFERENCE_BASE_URL, - "https://inference.local/v1", + "https://integrate.api.nvidia.com/v1", ); assert.equal(startup.configurationEnvironment.NEMOCLAW_INFERENCE_PROVIDER_ID, "inference"); assert.ok(startup.configurationEnvironment.NEMOCLAW_MODEL); diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index ce4842417db..4e4c4bf15b0 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -215,18 +215,20 @@ describe("onboarding inference gateway scope", () => { }, }); - await expect( - harness.setupInference( - "test-box", - "claude-test", - "compatible-anthropic-endpoint", - "https://example.test", - "COMPATIBLE_ANTHROPIC_API_KEY", - null, - [], - { gatewayName: GATEWAY, preferredInferenceApi: "openai-completions" }, - ), - ).resolves.toEqual({ ok: true }); + const result = await harness.setupInference( + "test-box", + "claude-test", + "compatible-anthropic-endpoint", + "https://example.test", + "COMPATIBLE_ANTHROPIC_API_KEY", + null, + [], + { gatewayName: GATEWAY, preferredInferenceApi: "openai-completions" }, + ); + expect( + result, + JSON.stringify({ commands: harness.commands, errors: harness.errors }, null, 2), + ).toEqual({ ok: true }); expect(commandRouter.callCount("provider-delete")).toBe(2); expect(harness.commands.map(({ command }) => command)).toContain( diff --git a/test/onboarding/onboard-prepared-build-context.test.ts b/test/onboarding/onboard-prepared-build-context.test.ts index 14b5bf77c13..65f8354510c 100644 --- a/test/onboarding/onboard-prepared-build-context.test.ts +++ b/test/onboarding/onboard-prepared-build-context.test.ts @@ -178,7 +178,7 @@ runner.runCapture = (command) => { "Route: inference", "Provider: nvidia-prod", "Model: openai:nvidia/nemotron-3-super-120b-a12b", - "Endpoint: https://inference.local/v1", + "Endpoint: https://integrate.api.nvidia.com/v1", ].join("\n"); } return ""; diff --git a/test/onboarding/onboard-terminal-dashboard.test.ts b/test/onboarding/onboard-terminal-dashboard.test.ts index e02c121d2f7..00ade5e9a3d 100644 --- a/test/onboarding/onboard-terminal-dashboard.test.ts +++ b/test/onboarding/onboard-terminal-dashboard.test.ts @@ -152,7 +152,7 @@ runner.runCapture = (command) => { "Route: inference", "Provider: nvidia-prod", "Model: openai:gpt-5.4", - "Endpoint: https://inference.local/v1", + "Endpoint: https://integrate.api.nvidia.com/v1", ].join("\n"); } if (normalized.includes("forward list")) return "SANDBOX BIND PORT PID STATUS"; @@ -188,6 +188,12 @@ registry.getSandbox = () => name: sandboxName, gpuEnabled: false, agent: "langchain-deepagents-code", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-revision-1", + }, dashboardPort: 18789, observabilityEnabled: false, toolDisclosure: "progressive", diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 38484ca1a40..522d6c7fecf 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -428,6 +428,9 @@ export function createDirectSetupInferenceHarnessFactory( ? "http://host.openshell.internal:11435/v1" : "http://host.openshell.internal:8000/v1", applyLocalInferenceRoute: async () => false, + // Let setupInference bind provider recovery to this harness's + // gateway-scoped runner instead of the production process adapter. + providerAdapter: undefined, run: () => directRunResult(), shouldFrontOllamaWithProxy: () => false, ensureOllamaAuthProxy: () => {}, From 6b23cec03530b38c32957331fc78f5c299805d08 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:49:54 -0700 Subject: [PATCH 005/133] fix(inference): preserve recorded provider identity --- src/lib/inference/native-nvidia.test.ts | 25 ++++++++++++++++++++++++ src/lib/inference/native-nvidia/index.ts | 6 ++++++ 2 files changed, 31 insertions(+) diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index 1d0e59627be..f84595152bc 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -185,6 +185,31 @@ describe("native NVIDIA OpenShell provider", () => { expect(updateProvider).not.toHaveBeenCalled(); }); + it("refuses to replace a recorded provider that is missing (#12558)", async () => { + const createProvider = vi.fn(); + + await expect( + ensureNativeNvidiaProvider({ + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + })), + createProvider, + }), + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "recorded-id", + }, + }), + ).rejects.toThrow(/is missing.*No provider was changed/u); + expect(createProvider).not.toHaveBeenCalled(); + }); + it("fails before provider mutation when the profile collides (#12558)", async () => { const createProvider = vi.fn(); const providerAdapter = adapter({ diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 2cefab8451a..53555d2ddb8 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -181,6 +181,12 @@ export async function ensureNativeNvidiaProvider(input: { return attachmentFromMetadata(observed); } + if (input.expected) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, + ); + } + if (!input.credentialValue && !input.reuseExistingCredential) { throw new NativeNvidiaProviderError( `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, From 7e04a51b9cd738399e384e3e9eb6b093ee3b36de Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:08:24 -0700 Subject: [PATCH 006/133] test(inference): seed recorded native provider state --- src/lib/actions/inference-set.test-support.ts | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index c0a16b02f83..a28da77b37b 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -63,10 +63,25 @@ function defaultCaptureOpenshell( return { status, output, stdout: output, stderr: "" }; } -function nativeAwareProviderAdapter(base: OpenShellProviderAdapter): OpenShellProviderAdapter { - const providerId = "11111111-2222-4333-8444-555555555555"; - let providerPresent = false; - const attachments = new Set(); +function nativeAwareProviderAdapter( + base: OpenShellProviderAdapter, + entries: SandboxEntry[], +): OpenShellProviderAdapter { + const recordedEntry = entries.find( + (entry) => entry.nativeNvidiaProviderAttachment?.providerName === NVIDIA_HOSTED_NATIVE_PROVIDER, + ); + const providerId = + recordedEntry?.nativeNvidiaProviderAttachment?.providerId ?? + "11111111-2222-4333-8444-555555555555"; + let providerPresent = recordedEntry !== undefined; + const attachments = new Set( + entries + .filter( + (entry) => + entry.nativeNvidiaProviderAttachment?.providerName === NVIDIA_HOSTED_NATIVE_PROVIDER, + ) + .map((entry) => entry.name), + ); const isNative = (providerName: string): boolean => providerName === NVIDIA_HOSTED_NATIVE_PROVIDER; return { @@ -365,6 +380,7 @@ export function createDeps(options: { }; }, }), + entries, ); return { getDefaultSandbox: () => defaultSandbox, From 6bb369d1c4f7071abe43a71b0613a32869ca5794 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:29:12 -0700 Subject: [PATCH 007/133] fix(onboard): escape Docker argument patterns --- src/lib/onboard/dockerfile-patch.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index 77fd399cbe0..52578d2a1c7 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -78,7 +78,8 @@ function replaceExactHermesPortableDockerArg(source: string, name: string, value if (sanitized !== value || /[\p{Cc}\p{Cf}]/u.test(value)) { throw new Error(`Hermes portable ${name} build setting is invalid.`); } - const pattern = new RegExp(`^ARG ${name}=.*$`, "gmu"); + const escapedName = name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); + const pattern = new RegExp(`^ARG ${escapedName}=.*$`, "gmu"); if ((source.match(pattern) ?? []).length !== 1) { throw new Error(`Hermes Dockerfile must declare exactly one ${name} build argument.`); } From b6793734adba8176399caff8437b74ffc684a1e1 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:48:58 -0700 Subject: [PATCH 008/133] fix(onboard): avoid dynamic Docker argument regex --- src/lib/onboard/dockerfile-patch.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index 52578d2a1c7..83f8977c338 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -78,12 +78,18 @@ function replaceExactHermesPortableDockerArg(source: string, name: string, value if (sanitized !== value || /[\p{Cc}\p{Cf}]/u.test(value)) { throw new Error(`Hermes portable ${name} build setting is invalid.`); } - const escapedName = name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); - const pattern = new RegExp(`^ARG ${escapedName}=.*$`, "gmu"); - if ((source.match(pattern) ?? []).length !== 1) { + const declarationPrefix = `ARG ${name}=`; + const lines = source.split("\n"); + const matches = lines.flatMap((line, index) => + line.startsWith(declarationPrefix) ? [index] : [], + ); + if (matches.length !== 1) { throw new Error(`Hermes Dockerfile must declare exactly one ${name} build argument.`); } - return source.replace(pattern, `ARG ${name}=${sanitized}`); + const matchIndex = matches[0] as number; + const suffix = lines[matchIndex]?.endsWith("\r") ? "\r" : ""; + lines[matchIndex] = `${declarationPrefix}${sanitized}${suffix}`; + return lines.join("\n"); } function pinHermesPortableTargetArchitecture(source: string): string { From 8af2c69c0068f1dab03216bc733ab276a200d9a5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 2 Oct 2026 06:32:28 -0700 Subject: [PATCH 009/133] fix(inference): address native provider review findings Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/model-capability-audit.mdx | 8 ++-- src/lib/onboard/setup-inference.test.ts | 48 +++++++++++++++++++ src/lib/onboard/setup-inference.ts | 18 +++++-- .../live/hermes-inference-switch-helpers.ts | 8 +--- test/e2e/live/hermes-inference-switch.test.ts | 18 ++++--- ...mes-inference-switch-command-shape.test.ts | 36 ++++++++++++++ ...inference-switch-workflow-boundary.test.ts | 6 ++- test/e2e/support/workflow-plan.test.ts | 2 +- tools/e2e/target-catalogue.mts | 13 +++-- 9 files changed, 126 insertions(+), 31 deletions(-) diff --git a/docs/inference/model-capability-audit.mdx b/docs/inference/model-capability-audit.mdx index 6f76c028406..a9b21934b7b 100644 --- a/docs/inference/model-capability-audit.mdx +++ b/docs/inference/model-capability-audit.mdx @@ -116,11 +116,11 @@ When importing a completed row from an issue comment, preserve the commit SHA, w | Agent surface | Provider class | Model or route | API path | State | Evidence | Required affordance | Follow-up | Source | |---|---|---|---|---|---|---|---|---| -| OpenClaw primary agent | NVIDIA Endpoints | `nvidia/nemotron-3-super-120b-a12b` | Managed `inference.local` OpenAI-compatible completions | `not-yet-run` | Add trajectory and session evidence before changing state. | Existing setup keeps Tool Search disabled and preserves direct structured tool calls, overriding the generated `tools.toolSearch.mode: tools` default for this route. | Verify `tool_search`, `tool_describe`, `tool_call`, and final execution before replacing the safeguard. | `scripts/generate-openclaw-config.mts`, `nemoclaw-blueprint/model-specific-setup/openclaw/nemotron-3-super-120b-managed-inference.json`. | +| OpenClaw primary agent | NVIDIA Endpoints | `nvidia/nemotron-3-super-120b-a12b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions | `not-yet-run` | Add trajectory and session evidence before changing state. | Existing setup keeps Tool Search disabled and preserves direct structured tool calls, overriding the generated `tools.toolSearch.mode: tools` default for this route. | Verify `tool_search`, `tool_describe`, `tool_call`, and final execution before replacing the safeguard. | `scripts/generate-openclaw-config.mts`, `nemoclaw-blueprint/model-specific-setup/openclaw/nemotron-3-super-120b-managed-inference.json`. | | OpenClaw existing configuration | NVIDIA Endpoints (retired route) | `moonshotai/kimi-k2.6` | Managed `inference.local` OpenAI-compatible completions | `unsupported` | NVIDIA's catalogs still advertised K2.6 while the [live Kimi compatibility job](https://github.com/NVIDIA/NemoClaw/actions/runs/28953873907/job/85907646487) failed route validation with HTTP 404. | The OpenClaw setup manifest remains for existing or custom compatible routes that still serve K2.6. | Select a supported NVIDIA Endpoints model; do not promote K2.7 until its production model ID and chat route are live. | `nemoclaw-blueprint/model-specific-setup/openclaw/kimi-k2.6-managed-inference.json`. | | OpenClaw primary agent | NVIDIA Endpoints (retired route) | `deepseek-ai/deepseek-v4-pro` | Managed `inference.local` OpenAI-compatible completions | `unsupported` | The featured-model feed still listed this model after the NVIDIA Endpoints model catalog removed it. NemoClaw excludes it from featured selections. | The retirement exclusion applies to NVIDIA Endpoints featured selections. It does not determine whether another compatible endpoint serves the same model ID. | Select a supported NVIDIA Endpoints model. | `src/lib/inference/nvidia-featured-models.ts`, `src/lib/inference/nvidia-featured-models.test.ts`. | | OpenClaw primary agent | NVIDIA Endpoints (retired route) | `z-ai/glm-5.2` | Managed `inference.local` OpenAI-compatible completions | `unsupported` | [Issue #10222](https://github.com/NVIDIA/NemoClaw/issues/10222) records authenticated NVIDIA Endpoints `/v1/models` results from WSL and DGX Spark with no GLM model IDs. NemoClaw excludes this model from featured selections. | The retirement exclusion applies to NVIDIA Endpoints featured selections. It does not determine whether another compatible endpoint serves the same model ID. | Select a supported NVIDIA Endpoints model. | `src/lib/inference/nvidia-featured-models.ts`, `src/lib/inference/nvidia-featured-models.test.ts`. | -| OpenClaw primary agent | NVIDIA Endpoints | Any model from `CLOUD_MODEL_OPTIONS` | Managed `inference.local` OpenAI-compatible completions unless config selects another API. | `not-yet-run` | Add one evidence row per model before changing state. | Record `none`, model-specific setup, or provider-class transport behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/config.ts`. | +| OpenClaw primary agent | NVIDIA Endpoints | Any model from `CLOUD_MODEL_OPTIONS` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions. | `not-yet-run` | Add one evidence row per model before changing state. | Record `none`, model-specific setup, or provider-class transport behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/config.ts`. | | OpenClaw primary agent | OpenAI | Any model from `REMOTE_MODEL_OPTIONS.openai` | `openai` provider through `https://inference.local/v1`. | `not-yet-run` | Add one evidence row per model before changing state. | Record Responses or Chat Completions behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Anthropic | Any model from `REMOTE_MODEL_OPTIONS.anthropic` | `anthropic` provider through `https://inference.local` with `anthropic-messages`. | `not-yet-run` | Add one evidence row per model before changing state. | Record native Anthropic Messages behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Gemini | Any model from `REMOTE_MODEL_OPTIONS.gemini` | Managed `inference.local` OpenAI-compatible route. | `not-yet-run` | Add one evidence row per model before changing state. | Record provider state and tool-result continuation behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | @@ -129,8 +129,8 @@ When importing a completed row from an issue comment, preserve the commit SHA, w | OpenClaw primary agent | Other OpenAI-compatible endpoint | User-selected `custom-model` or another configured model id. | Managed `inference.local` route to the compatible endpoint. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record endpoint API path forcing and store/streaming assumptions. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | | OpenClaw primary agent | Other Anthropic-compatible endpoint | User-selected `custom-anthropic-model` or another configured model id. | `anthropic` route when supported, otherwise managed compatible route. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record native Anthropic Messages or compatible-route transport behavior. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | | Hermes sandbox API | Hermes Provider | Default `moonshotai/kimi-k2.6` or any model from `HERMES_PROVIDER_MODEL_OPTIONS`. | Hermes Provider route through NemoClaw managed inference. | `not-yet-run` | Add Hermes session, request dump, logs, and local API evidence before changing state. | Generated config uses native `tools.tool_search.enabled: on` with snake-case 5/20 limits; core tools stay direct while deferred MCP and non-core plugin tools use structured search, describe, and call. | Verify a deferred-tool trajectory and keep it separate from OpenClaw `mode: tools` evidence. | `agents/hermes/config/managed-policy.ts`, `test/generation/generate-hermes-config.test.ts`. | -| Deep Agents interactive `dcode` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Managed `inference.local` OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add separate default-disabled and thread-opt-in terminal transcripts, host status output, reset evidence, and route evidence before changing state. | The managed Ultra profile preserves required nonempty tool-call content and rejects the observed literal `[content]` execute placeholder before shell dispatch; optional `thread-opt-in` remains a per-thread approval affordance. | Verify a terminal task with approval prompts intact, then separately verify explicit thread activation, reset behavior, policy enforcement, placeholder rejection, and no provider credential in sandbox-visible files. | `agents/langchain-deepagents-code/generate-config.ts`, `agents/langchain-deepagents-code/profile-plugin`, `docs/get-started/quickstart-langchain-deepagents-code`. | -| Deep Agents headless `dcode -n` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Managed `inference.local` OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add headless command transcript and status output before changing state. | Headless mode uses the managed Ultra profile, preserves required nonempty tool-call content, rejects the observed literal `[content]` execute placeholder, has no approval UI, and auto-approves non-shell tools while managed shell execution remains disabled. | Verify a bounded non-shell task, placeholder rejection, and the approval boundary separately from interactive evidence. | `agents/langchain-deepagents-code/dcode-wrapper.sh`, `agents/langchain-deepagents-code/profile-plugin`, `docs/security/best-practices`. | +| Deep Agents interactive `dcode` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add separate default-disabled and thread-opt-in terminal transcripts, host status output, reset evidence, and route evidence before changing state. | The managed Ultra profile preserves required nonempty tool-call content and rejects the observed literal `[content]` execute placeholder before shell dispatch; optional `thread-opt-in` remains a per-thread approval affordance. | Verify a terminal task with approval prompts intact, then separately verify explicit thread activation, reset behavior, policy enforcement, placeholder rejection, and no provider credential in sandbox-visible files. | `agents/langchain-deepagents-code/generate-config.ts`, `agents/langchain-deepagents-code/profile-plugin`, `docs/get-started/quickstart-langchain-deepagents-code`. | +| Deep Agents headless `dcode -n` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add headless command transcript and status output before changing state. | Headless mode uses the managed Ultra profile, preserves required nonempty tool-call content, rejects the observed literal `[content]` execute placeholder, has no approval UI, and auto-approves non-shell tools while managed shell execution remains disabled. | Verify a bounded non-shell task, placeholder rejection, and the approval boundary separately from interactive evidence. | `agents/langchain-deepagents-code/dcode-wrapper.sh`, `agents/langchain-deepagents-code/profile-plugin`, `docs/security/best-practices`. | ## Completed Row Template diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 20ebe041d88..5d8a7529769 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -271,4 +271,52 @@ describe("native NVIDIA onboarding", () => { }), ); }); + + it("requires recreation instead of recording a receipt for a legacy NVIDIA sandbox", async () => { + const providerAdapter = { + importProviderProfile: vi.fn(), + getProvider: vi.fn(), + updateProvider: vi.fn(), + } as unknown as OpenShellProviderAdapter; + const updateSandbox = vi.fn(() => true); + const setupInference = createSetupInference({ + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + step: vi.fn(), + getGatewayName: () => "nemoclaw", + runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + updateSandbox, + getSandbox: () => ({ name: "alpha", provider: "nvidia-prod" }) as never, + upsertProvider: vi.fn(async () => ({ ok: true })), + verifyInferenceRoute: vi.fn(), + verifyOnboardInferenceSmoke: vi.fn(async () => undefined), + isNonInteractive: () => true, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + providerAdapter, + hydrateCredentialEnv: vi.fn(() => "host-only-nvidia-credential"), + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }), + } as unknown as SetupInferenceDeps); + + await expect( + setupInference( + "alpha", + "nvidia/nemotron-3-super-120b-a12b", + "nvidia-prod", + "https://integrate.api.nvidia.com/v1", + "NVIDIA_INFERENCE_API_KEY", + ), + ).rejects.toThrow(/Recreate this beta sandbox.*does not migrate existing beta sandboxes/u); + + expect(providerAdapter.importProviderProfile).not.toHaveBeenCalled(); + expect(updateSandbox).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index cfa9f30ac2b..c4b4a881de0 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -928,11 +928,19 @@ export function createSetupInference( if (!providerAdapter) { throw new Error("Native NVIDIA setup is missing its OpenShell provider adapter."); } - const recordedAttachment = sandboxName - ? normalizeNativeNvidiaProviderAttachment( - deps.getSandbox?.(sandboxName)?.nativeNvidiaProviderAttachment, - ) - : undefined; + const recordedSandbox = sandboxName ? deps.getSandbox?.(sandboxName) : null; + const recordedAttachment = normalizeNativeNvidiaProviderAttachment( + recordedSandbox?.nativeNvidiaProviderAttachment, + ); + if ( + recordedSandbox && + isNativeNvidiaProvider(recordedSandbox.provider) && + !recordedAttachment + ) { + throw new Error( + `Sandbox '${sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before using native NVIDIA inference; NemoClaw does not migrate existing beta sandboxes automatically.`, + ); + } nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ adapter: providerAdapter, target: { kind: "selected" }, diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index 07c226bbb36..cca018a529d 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -71,7 +71,7 @@ export const RUNTIME_SWITCH_API = resolveAgentInferenceApi("hermes", SWITCH_PROVIDER, SWITCH_API) ?? SWITCH_API; const SWITCH_MOCK_PORT = Number.parseInt(process.env.NEMOCLAW_SWITCH_MOCK_PORT ?? "0", 10); const INSTALL_ATTEMPTS = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true" ? 3 : 1; -export const PROXY_RESOLUTION_PROVIDER = "nvidia-prod"; +export const PROXY_RESOLUTION_PROVIDER = "hermes-proxy-resolution-e2e"; export const PROXY_RESOLUTION_MODEL = "nvidia/nemotron-proxy-resolution-e2e"; export const PROXY_FORBIDDEN_MARKERS = [ "openshell:resolve:env:", @@ -234,12 +234,6 @@ export async function prepareProxyResolutionRoute({ const model = mockBaseline ? PROXY_RESOLUTION_MODEL : SWITCH_MODEL; const requestOffset = mockBaseline?.requests().length ?? 0; - // Hosted mode already registered and attached the exact nvidia-prod - // provider. The mock path needs an OpenAI provider for its local fixture. - if (!mockBaseline) { - return { model, requestOffset }; - } - const registered = await host.command( "openshell", [ diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index c4d1837b3c1..e74e523a52d 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -168,14 +168,20 @@ test( const install = await installHermes(host, apiKey, installEnv); expect(install.exitCode, resultText(install)).toBe(0); expectAuthenticatedBaselineInventoryRequest(mockBaseline); - const baselineRoute = await sandbox.openshell(["inference", "get", "-g", "nemoclaw"], { - artifactName: "openshell-inference-route-before-switch", - env: env(), - timeoutMs: 30_000, - }); + const baselineRoute = mockBaseline + ? await sandbox.openshell(["inference", "get", "-g", "nemoclaw"], { + artifactName: "openshell-inference-route-before-switch", + env: env(), + timeoutMs: 30_000, + }) + : await host.command("node", [CLI, "inference", "get"], { + artifactName: "nemoclaw-native-inference-route-before-switch", + env: env(), + timeoutMs: 30_000, + }); expect(baselineRoute.exitCode, resultText(baselineRoute)).toBe(0); expect(parseInferenceRoute(resultText(baselineRoute))).toEqual({ - provider: "compatible-endpoint", + provider: mockBaseline ? "compatible-endpoint" : PUBLIC_NVIDIA_SWITCH_PROVIDER, model: hostedInstallModel(installEnv), }); const baselineSession = structuredClone(registryState().session); 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 5353fee9636..804f5dff8c1 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -26,6 +26,8 @@ import { openAiSurfaceEndpointUrl, openshellGatewayName, parseInferenceRoute, + prepareProxyResolutionRoute, + PROXY_RESOLUTION_PROVIDER, runHermesInferenceSetWithRetry, runHermesCliPongWithRetry, runHermesPongWithRetry, @@ -103,6 +105,40 @@ describe("Hermes inference switch command shape", () => { ).toBe("initial-hosted-model"); }); + it("keeps proxy-resolution evidence on a dedicated OpenAI provider", async () => { + const command = vi + .fn() + .mockResolvedValueOnce({ exitCode: 0, stderr: "", stdout: "created" }) + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n", + }) + .mockResolvedValueOnce({ exitCode: 0, stderr: "", stdout: "route synced" }); + + await prepareProxyResolutionRoute({ + apiKey: "hosted-key", + host: { command } as unknown as HostCliClient, + mockBaseline: undefined, + redactionValues: ["hosted-key"], + }); + + expect(PROXY_RESOLUTION_PROVIDER).not.toBe("nvidia-prod"); + expect(command.mock.calls[0]?.[1]).toEqual( + expect.arrayContaining([ + "--name", + PROXY_RESOLUTION_PROVIDER, + "--type", + "openai", + "--credential", + "NVIDIA_INFERENCE_API_KEY", + ]), + ); + expect(command.mock.calls[2]?.[1]).toEqual( + expect.arrayContaining(["--provider", PROXY_RESOLUTION_PROVIDER]), + ); + }); + it("uses authenticated model inventory as baseline readiness evidence", () => { expect(() => expectAuthenticatedBaselineInventoryRequest({ diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index 9981402d2be..7101117699a 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -20,9 +20,13 @@ describe("inference-switch catalogue boundary", () => { testFile: "test/e2e/live/openclaw-inference-switch.test.ts", environment: { NEMOCLAW_AGENT: "openclaw", - NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + NEMOCLAW_E2E_SHARD: "native-nvidia", + NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod", + NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3-super-120b-a12b", + NEMOCLAW_SWITCH_INFERENCE_API: "openai-completions", }, }); + expect(openclaw.environment).not.toHaveProperty("NEMOCLAW_SWITCH_MOCK_ANTHROPIC"); const hermes = catalogueTarget("hermes-inference-switch"); expect(hermes).toMatchObject({ diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 91263aed9d6..2395b4cf8c9 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -373,7 +373,7 @@ describe("E2E workflow plan", () => { expect(plan.catalogueMatrices.standard).toContainEqual( expect.objectContaining({ id: "openclaw-inference-switch", - display_name: "Inference: OpenClaw switches providers and remains responsive", + display_name: "Inference: OpenClaw switches to native NVIDIA and remains responsive", }), ); expect(selectedWorkflowJobs(plan)).toEqual([ diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index e1102929479..7d58582a3f8 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1151,9 +1151,9 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }, }), managedRuntimeTarget("openclaw-inference-switch", { - displayName: "Inference: OpenClaw switches providers and remains responsive", + displayName: "Inference: OpenClaw switches to native NVIDIA and remains responsive", agentRuntime: "openclaw", - environmentOrInferenceEndpoint: "Ubuntu; compatible inference fixtures", + environmentOrInferenceEndpoint: "Ubuntu; native NVIDIA Endpoints provider", profile: "standard", timeoutMinutes: 90, installMode: "none", @@ -1181,12 +1181,11 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ environment: { ...nonInteractive, NEMOCLAW_AGENT: "openclaw", - NEMOCLAW_E2E_SHARD: "anthropic", + NEMOCLAW_E2E_SHARD: "native-nvidia", NEMOCLAW_SANDBOX_NAME: "e2e-oc-inf-switch", - NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", - NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", - NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", - NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod", + NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3-super-120b-a12b", + NEMOCLAW_SWITCH_INFERENCE_API: "openai-completions", OPENSHELL_GATEWAY: "nemoclaw", }, }), From 1db9f0c4d7dbe582a06d4ba5e0c87b5c015d0912 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:44:58 -0700 Subject: [PATCH 010/133] test(e2e): map native OpenClaw switch parity Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/mock-parity.json | 1 + 1 file changed, 1 insertion(+) diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 389a5d20980..654c8a3a7f2 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -830,6 +830,7 @@ "test/e2e/support/compatible-anthropic-switch.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", + "test/e2e/support/inference-switch-workflow-boundary.test.ts", "test/e2e/support/managed-image-receipt.test.ts", "test/e2e/support/openclaw-inference-switch-helpers.test.ts", "test/security/admin-approval-helper.test.ts", From 5f52236136e23841e8b915383ae437a3b7a85d5e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:26:02 -0700 Subject: [PATCH 011/133] fix: keep native inference off shared routes --- .../sandbox/connect-route-containment.test.ts | 47 ++++++++++ src/lib/actions/sandbox/connect.ts | 16 ++++ ...aunch-readiness-observation-timing.test.ts | 48 ++++++++++ src/lib/actions/sandbox/launch-readiness.ts | 89 +++++++++++-------- .../sandbox/launch-readiness/health.ts | 87 +++++++++++++----- .../status-snapshot-route-drift.test.ts | 52 +++++++++++ src/lib/actions/sandbox/status-snapshot.ts | 19 ++-- test/support/connect-flow-test-harness.ts | 14 +++ 8 files changed, 303 insertions(+), 69 deletions(-) diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index eb09663f70b..0983efaca5d 100644 --- a/src/lib/actions/sandbox/connect-route-containment.test.ts +++ b/src/lib/actions/sandbox/connect-route-containment.test.ts @@ -242,6 +242,53 @@ describe("connect route containment", () => { expect(exitSpy).not.toHaveBeenCalled(); }); + it("verifies an attached native NVIDIA provider without reading or mutating the shared route", async () => { + const harness = createConnectHarness({ + inferenceGetOutput: "Gateway inference:\n Not configured\n", + registryEntry: { + name: "alpha", + gatewayName: "nemoclaw", + gatewayPort: 8080, + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-123", + }, + }, + }); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); + + expect(harness.verifyNativeNvidiaProviderAttachmentSpy).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw" }, + expected: expect.objectContaining({ providerId: "provider-123" }), + }), + ); + expect(harness.nativeInferenceInvocationSpy).toHaveBeenCalledWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + agentName: "openclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + preferredInferenceApi: null, + nativeProvider: true, + }); + expect(harness.captureOpenshellSpy).not.toHaveBeenCalledWith( + expect.arrayContaining(["inference", "get"]), + expect.anything(), + ); + expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith( + expect.arrayContaining(["inference", "set"]), + expect.anything(), + ); + expect(harness.withGatewayRouteMutationLockSpy).not.toHaveBeenCalled(); + }); + it("aborts before route reads or repairs when the target changes gateways while waiting", async () => { let releaseLock!: () => void; const released = new Promise((resolve) => { diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 3be5e12d32e..519853aea14 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -118,6 +118,8 @@ import { type ProbeTimingRecorder, publicationFromDecision, publishLaunchReadiness, + getNativeNvidiaProviderAttachment, + requireNativeNvidiaInferenceHealth, settlePortableOpenClawPairing, withLaunchReadinessMutationGate, } from "./launch-readiness"; @@ -1698,6 +1700,17 @@ async function ensureSandboxInferenceRouteUnlocked( assertNoOpenShellGatewayEndpointOverride(); const { provider, model } = inference; const gatewayName = getPersistedSandboxTargetGatewayName(sb); + const nativeNvidiaAttachment = getNativeNvidiaProviderAttachment(sb); + if (nativeNvidiaAttachment) { + await requireNativeNvidiaInferenceHealth({ + sandboxName, + gatewayName, + agentName: agent?.name, + entry: sb, + deps: {}, + }); + return { sandbox: sb, routeHealthy: true }; + } // The live route exposes only provider/model. Prove the target's durable // custom endpoint/API identity before any route read, probe, or mutation. assertSandboxGatewayRouteCompatible(sandboxName, sb, gatewayName); @@ -1845,6 +1858,9 @@ async function ensureSandboxInferenceRoute( if (!snapshot) return { sandbox: null, routeHealthy: null }; if (registry.getSandboxEntryInference(snapshot).kind !== "configured") return { sandbox: snapshot, routeHealthy: null }; + if (getNativeNvidiaProviderAttachment(snapshot)) { + return ensureSandboxInferenceRouteUnlocked(sandboxName, agent, { quiet }); + } const gatewayName = getPersistedSandboxTargetGatewayName(snapshot); return withGatewayRouteMutationLock(gatewayName, () => { const lockedSnapshot = readConnectSandbox(sandboxName); diff --git a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts index 53471afc29e..3547a5cb609 100644 --- a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts @@ -157,6 +157,54 @@ describe("launch readiness observation timing", () => { } }); + it("validates native NVIDIA readiness without observing a shared inference route", async () => { + const nativeEntry: SandboxEntry = { + ...entry(), + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-123", + }, + }; + const currentDeps = publicationDeps(vi.fn(), (_name, _gateway, _port, _epoch, identity) => + lease(identity), + ); + const capture = vi.fn(currentDeps.capture!); + const verifyAttachment = vi.fn(async () => undefined); + const invoke = vi.fn(async () => ({ ok: true }) as const); + currentDeps.getSandbox = () => nativeEntry; + currentDeps.capture = capture; + currentDeps.verifyNativeNvidiaAttachment = verifyAttachment; + currentDeps.inferenceInvocationProbe = invoke; + + const decision = await inspectLaunchReadiness(SANDBOX, currentDeps); + expect(decision).toMatchObject({ + kind: "fallback", + category: "missing", + }); + await expect( + publishLaunchReadiness(publicationFromDecision(SANDBOX, decision), currentDeps), + ).resolves.toEqual({ kind: "published" }); + + expect(capture.mock.calls.some(([args]) => args[0] === "inference")).toBe(false); + expect(verifyAttachment).toHaveBeenCalledWith({ + sandboxName: SANDBOX, + gatewayName: GATEWAY, + expected: expect.objectContaining({ providerId: "provider-123" }), + }); + expect(invoke).toHaveBeenCalledWith( + expect.objectContaining({ + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + nativeProvider: true, + }), + ); + }); + it("reports the failed publication operation without exposing exception details", async () => { const publication = publicationFromDecision( SANDBOX, diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 7f3f45be2c3..5289c9c06a6 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -65,6 +65,7 @@ import { type LaunchReadinessObservationStage, LaunchReadinessObservationError as ObservationError, recordLaunchReadinessObservationFailure, + getNativeNvidiaProviderAttachment, requireLaunchSemanticHealth, resolveLaunchInteractiveCommand, resolveTrustedLaunchAgent, @@ -86,6 +87,10 @@ import { export { createProbeTimingRecorder, type ProbeTimingRecorder } from "./probe/timing"; export { createBoundLaunchReadinessDeps }; +export { + getNativeNvidiaProviderAttachment, + requireNativeNvidiaInferenceHealth, +} from "./launch-readiness/health"; const LIVE_POLICY_MAX_BYTES = 2 * 1_024 * 1_024; const LIVE_AGENT_VERSION_MAX_BYTES = 4 * 1_024; @@ -821,50 +826,56 @@ async function captureLaunchIdentity( } const inferenceSelection = normalizeInferenceSelection(entry); const inference = registry.getSandboxEntryInference(entry); - const inferenceGetStartedAt = performance.now(); - let inferenceResult: Awaited< - ReturnType["observeInferenceRoute"]> - >; - try { - const observer = - deps.inferenceRouteObserver ?? - createLaunchReadinessInferenceRouteObserver( - deps.capture ?? ((args, options) => captureLaunchReadiness(args, options)), - ); - inferenceResult = await observer.observeInferenceRoute({ - target: namedOpenShellGateway(gatewayName), - }); - } catch (error) { - recordLaunchReadinessObservationFailure(deps, "inference-get"); - throw error; - } finally { - recordObservationTiming(deps, "inference-get", inferenceGetStartedAt); - } - if (!inferenceResult.ok) { - recordLaunchReadinessObservationFailure(deps, "inference-get"); - throw new LaunchReadinessEvidenceError(); - } - const liveInference = - inferenceResult.value.state === "configured" ? inferenceResult.value.route : null; - const liveInferenceAbsent = inferenceResult.value.state === "unconfigured"; - if (inference.kind === "configured") { - if (!liveInference && !liveInferenceAbsent) { - recordLaunchReadinessObservationFailure(deps, "inference-get"); - throw new LaunchReadinessEvidenceError(); - } - if (planInferenceRouteReconcile(liveInference, inference).kind !== "aligned") { - recordLaunchReadinessObservationFailure(deps, "inference-get"); - throw new ObservationError("config"); - } - } else { - if (liveInference) { + const nativeNvidia = Boolean(getNativeNvidiaProviderAttachment(entry)); + let liveInference: { provider: string; model: string } | null = null; + if (!nativeNvidia) { + const inferenceGetStartedAt = performance.now(); + let inferenceResult: Awaited< + ReturnType< + NonNullable["observeInferenceRoute"] + > + >; + try { + const observer = + deps.inferenceRouteObserver ?? + createLaunchReadinessInferenceRouteObserver( + deps.capture ?? ((args, options) => captureLaunchReadiness(args, options)), + ); + inferenceResult = await observer.observeInferenceRoute({ + target: namedOpenShellGateway(gatewayName), + }); + } catch (error) { recordLaunchReadinessObservationFailure(deps, "inference-get"); - throw new ObservationError("config"); + throw error; + } finally { + recordObservationTiming(deps, "inference-get", inferenceGetStartedAt); } - if (!liveInferenceAbsent) { + if (!inferenceResult.ok) { recordLaunchReadinessObservationFailure(deps, "inference-get"); throw new LaunchReadinessEvidenceError(); } + liveInference = + inferenceResult.value.state === "configured" ? inferenceResult.value.route : null; + const liveInferenceAbsent = inferenceResult.value.state === "unconfigured"; + if (inference.kind === "configured") { + if (!liveInference && !liveInferenceAbsent) { + recordLaunchReadinessObservationFailure(deps, "inference-get"); + throw new LaunchReadinessEvidenceError(); + } + if (planInferenceRouteReconcile(liveInference, inference).kind !== "aligned") { + recordLaunchReadinessObservationFailure(deps, "inference-get"); + throw new ObservationError("config"); + } + } else { + if (liveInference) { + recordLaunchReadinessObservationFailure(deps, "inference-get"); + throw new ObservationError("config"); + } + if (!liveInferenceAbsent) { + recordLaunchReadinessObservationFailure(deps, "inference-get"); + throw new LaunchReadinessEvidenceError(); + } + } } await requireLaunchSemanticHealth( diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index 91b4e023ce9..618cfb7eddd 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { captureOpenshell } from "../../../adapters/openshell/runtime"; +import { createCliOpenShellProviderAdapter } from "../../../adapters/openshell/provider-adapter-cli"; import type { OpenShellSandboxBufferedCommandExecutor } from "../../../adapters/openshell/sandbox-command"; import { OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, @@ -16,7 +17,11 @@ import { type SandboxRecreateObserver, } from "../../../onboard/sandbox-recreate-probe"; import type { SandboxEntry } from "../../../state/registry"; -import { normalizeNativeNvidiaProviderAttachment } from "../../../inference/native-nvidia"; +import { + normalizeNativeNvidiaProviderAttachment, + verifyNativeNvidiaProviderAttachment, + type NativeNvidiaProviderAttachment, +} from "../../../inference/native-nvidia"; import { createSynchronousCliOpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route-cli"; import type { OpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route"; import { @@ -74,6 +79,11 @@ export interface LaunchReadinessHealthDeps { gatewayName: string, ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; + verifyNativeNvidiaAttachment?: (input: { + sandboxName: string; + gatewayName: string; + expected: NativeNvidiaProviderAttachment; + }) => Promise; recordObservationTiming?: (stage: LaunchReadinessObservationStage, elapsedMs: number) => void; recordObservationFailure?: (stage: LaunchReadinessObservationStage) => void; } @@ -197,6 +207,55 @@ export function resolveTrustedLaunchAgent( return agent; } +export function getNativeNvidiaProviderAttachment( + entry: SandboxEntry, +): NativeNvidiaProviderAttachment | null { + return normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) ?? null; +} + +export async function requireNativeNvidiaInferenceHealth(input: { + sandboxName: string; + gatewayName: string; + agentName?: string; + entry: SandboxEntry; + deps: LaunchReadinessHealthDeps; +}): Promise { + const expected = getNativeNvidiaProviderAttachment(input.entry); + if (!expected) return false; + const provider = normalizedString(input.entry.provider); + const model = normalizedString(input.entry.model); + if (!provider || !model) throw new LaunchReadinessEvidenceError(); + if (input.deps.verifyNativeNvidiaAttachment) { + await input.deps.verifyNativeNvidiaAttachment({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + expected, + }); + } else { + await verifyNativeNvidiaProviderAttachment({ + adapter: createCliOpenShellProviderAdapter(), + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected, + }); + } + const invocation = await ( + input.deps.inferenceInvocationProbe ?? runSandboxInferenceInvocationProbe + )({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + agentName: input.agentName, + provider, + model, + preferredInferenceApi: normalizedString(input.entry.preferredInferenceApi), + nativeProvider: true, + }); + if (!invocation.ok) { + throw new LaunchReadinessObservationError("health", "inference request"); + } + return true; +} + async function probeInferenceRoute( sandboxName: string, agent: InferenceRouteProbeAgent, @@ -292,31 +351,19 @@ export async function requireLaunchSemanticHealth( } if (inferenceConfigured) { const inferenceStartedAt = performance.now(); - const nativeNvidia = Boolean( - normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment), - ); - if (nativeNvidia) { - const provider = normalizedString(entry.provider); - const model = normalizedString(entry.model); - if (!provider || !model) { - recordLaunchReadinessObservationFailure(deps, "inference-route"); - throw new LaunchReadinessEvidenceError(); - } + if (getNativeNvidiaProviderAttachment(entry)) { try { - const invocation = await ( - deps.inferenceInvocationProbe ?? runSandboxInferenceInvocationProbe - )({ + await requireNativeNvidiaInferenceHealth({ sandboxName, gatewayName, agentName, - provider, - model, - preferredInferenceApi: normalizedString(entry.preferredInferenceApi), - nativeProvider: true, + entry, + deps, }); - if (invocation.ok) return; + return; + } catch (error) { recordLaunchReadinessObservationFailure(deps, "inference-route"); - throw new LaunchReadinessObservationError("health", "inference request"); + throw error; } finally { recordObservationTiming(deps, "inference-route", inferenceStartedAt); } diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index ac2ece386ac..da4a9cd38fb 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -469,4 +469,56 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = }), ).toMatchObject({ ok: true, probed: true }); }); + + it("probes the recorded native NVIDIA attachment when a different shared route exists", async () => { + liveGatewayInference("compatible-endpoint", "other/model"); + const sandbox = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + preferredInferenceApi: "openai-completions", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-123", + }, + } as SandboxEntry; + const invoke = vi.fn(async () => ({ ok: true }) as const); + const probeSharedRoute = vi.fn(async () => ({ + ok: true, + endpoint: "https://inference.local/v1/models", + detail: "reachable", + httpStatus: 200, + })); + + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + probeProviderHealthImpl: () => null, + probeSandboxInferenceGatewayHealthImpl: probeSharedRoute, + probeSandboxInferenceInvocationImpl: invoke, + }, + } as never); + + expect(snapshot.routeDrift).toBeNull(); + expect(probeSharedRoute).not.toHaveBeenCalled(); + expect(invoke).toHaveBeenCalledWith( + { + sandboxName: "alpha", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + preferredInferenceApi: "openai-completions", + nativeProvider: true, + }, + {}, + 95_000, + ); + expect(snapshot.inferenceHealth).toMatchObject({ ok: true, probed: true }); + }); }); diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 5aab91c090e..c4091e75fa0 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -604,8 +604,11 @@ export async function collectSandboxStatusSnapshot( // as drift instead of being mislabeled as this sandbox's configuration. const currentModel = sb ? sb.model || "unknown" : (live && live.model) || "unknown"; const currentProvider = sb ? sb.provider || "unknown" : (live && live.provider) || "unknown"; + const nativeNvidia = Boolean( + normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), + ); const routeDriftPlan = - sb && sb.provider && sb.model + !nativeNvidia && sb && sb.provider && sb.model ? planInferenceRouteReconcile(live, { provider: sb.provider, model: sb.model }) : null; const routeDrift = @@ -639,8 +642,8 @@ export async function collectSandboxStatusSnapshot( providerHealth = maybeGetSandboxStatusInferenceHealth( suppressInferenceProbe, lookup.state === "present", - (live && live.provider) || currentProvider, - (live && live.model) || currentModel, + nativeNvidia ? currentProvider : (live && live.provider) || currentProvider, + nativeNvidia ? currentModel : (live && live.model) || currentModel, opts.deps?.probeProviderHealthImpl, sb?.endpointUrl, ); @@ -655,16 +658,15 @@ export async function collectSandboxStatusSnapshot( }; } let inferenceHealth = providerHealth; - // `inference.local` is authoritative because it is the route the agent uses. - // Probe it independently of direct/upstream provider diagnostics, including - // providers without a registered host-side health probe (#6192). + // Probe the same route the agent uses: the recorded attached provider for + // native NVIDIA, otherwise the shared `inference.local` route. if (!suppressInferenceProbe && lookup.state === "present") { let gatewayChain: Awaited> = null; // Take the provider and model as one pair. Falling back per field can pair // a live model with a recorded provider and request a route neither one // describes. const invocationRoute = - live?.provider && live.model + !nativeNvidia && live?.provider && live.model ? { provider: live.provider, model: live.model, @@ -684,9 +686,6 @@ export async function collectSandboxStatusSnapshot( }; const invocationModel = (invocationRoute.model || "").trim(); const invocationProvider = (invocationRoute.provider || "").trim(); - const nativeNvidia = Boolean( - normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), - ); const canProbeInvocation = Boolean(invocationModel && invocationProvider); let invocation: Awaited> | null = null; try { diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 5c3e798fecd..860b3f64e21 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -73,6 +73,8 @@ export type ConnectHarness = { requalifyPortableAgentAuthoritySpy: MockInstance; qualifyHermesPortableAcceptedReadinessAuthoritySpy: MockInstance; inspectPortableReceiptDispositionSpy: MockInstance; + verifyNativeNvidiaProviderAttachmentSpy: MockInstance; + nativeInferenceInvocationSpy: MockInstance; registryUpdateSpy: MockInstance; registryEntries: SandboxEntry[]; resolveAgentConfigSpy: MockInstance; @@ -244,6 +246,10 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne const sandboxSession = requireDist("../../src/lib/state/sandbox-session.js"); const vmDnsMonkeypatch = requireDist("../../src/lib/actions/sandbox/vm-dns-monkeypatch.js"); const launchReadiness = requireDist("../../src/lib/actions/sandbox/launch-readiness.js"); + const nativeNvidia = requireDist("../../src/lib/inference/native-nvidia/index.js"); + const inferenceRouteHealth = requireDist( + "../../src/lib/actions/sandbox/inference-route-health.js", + ); const portableAgentLifecycle = requireDist( "../../src/lib/onboard/experimental/portable-agent-lifecycle.js", ); @@ -448,6 +454,12 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne const publishLaunchReadinessSpy = vi .spyOn(launchReadiness, "publishLaunchReadiness") .mockResolvedValue(options.readinessPublicationResult ?? { kind: "published" }); + const verifyNativeNvidiaProviderAttachmentSpy = vi + .spyOn(nativeNvidia, "verifyNativeNvidiaProviderAttachment") + .mockImplementation(async (...args: unknown[]) => (args[0] as { expected: unknown }).expected); + const nativeInferenceInvocationSpy = vi + .spyOn(inferenceRouteHealth, "runSandboxInferenceInvocationProbe") + .mockResolvedValue({ ok: true }); const launchReadinessMutationGateSpy = vi .spyOn(launchReadiness, "withLaunchReadinessMutationGate") .mockImplementation((async (...args: unknown[]) => { @@ -868,6 +880,8 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne requalifyPortableAgentAuthoritySpy, qualifyHermesPortableAcceptedReadinessAuthoritySpy, inspectPortableReceiptDispositionSpy, + verifyNativeNvidiaProviderAttachmentSpy, + nativeInferenceInvocationSpy, registryUpdateSpy, registryEntries, resolveAgentConfigSpy, From 8538e40679687717c59247a432c67cab5134c08f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:24:58 -0700 Subject: [PATCH 012/133] test: prove native NVIDIA agent switches Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-budget.json | 16 ++--- test/e2e/README.md | 4 +- test/e2e/live/hermes-inference-switch.test.ts | 39 ++++++++++-- .../live/openclaw-inference-switch.test.ts | 41 ++++++++++--- .../e2e/live/public-nvidia-switch-provider.ts | 34 +++++++++++ ...mes-inference-switch-command-shape.test.ts | 59 +++++++++++++++++++ ...inference-switch-workflow-boundary.test.ts | 12 ++-- test/e2e/support/workflow-plan.test.ts | 8 +-- tools/e2e/target-catalogue.mts | 17 +++--- 9 files changed, 187 insertions(+), 43 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 21b4049874c..4b7af678d13 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 184, "direct": { - "expectCalls": 1245, - "matcherAssertions": 1224, + "expectCalls": 1241, + "matcherAssertions": 1220, "nodeAssertions": 104, "namedAssertionHelpers": 426, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 166, - "assertionPoints": 1970, + "assertionPoints": 1966, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1670, - "matcherAssertions": 1644, + "expectCalls": 1666, + "matcherAssertions": 1640, "nodeAssertions": 127, "namedAssertionHelpers": 671, "failCalls": 1, "throwGuards": 528, "objectFieldAssertions": 243, - "assertionPoints": 3214, + "assertionPoints": 3210, "generatedProbeBlocks": 208, "generatedProbeConditions": 720 }, @@ -67,7 +67,7 @@ "test/e2e/live/hermes-discord.test.ts": [10,25,17,64,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [48,54,59,79,1], + "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,77,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], @@ -94,7 +94,7 @@ "test/e2e/live/onboard-repair.test.ts": [21,25,21,25,0], "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], - "test/e2e/live/openclaw-inference-switch.test.ts": [46,52,47,54,1], + "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,52,1], "test/e2e/live/openclaw-skill-cli.test.ts": [10,14,10,14,1], "test/e2e/live/openclaw-slack-pairing.test.ts": [11,18,26,84,10], "test/e2e/live/openshell-credential-generation-window.test.ts": [42,92,43,112,18], diff --git a/test/e2e/README.md b/test/e2e/README.md index 71a7acf92e6..f8566a12d5e 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1174,7 +1174,7 @@ lanes: - `common-egress-agent`; - `hermes-e2e`, including dashboard coverage, and `hermes-discord`; -- the Anthropic-compatible `hermes-inference-switch` mode; +- the native NVIDIA `hermes-inference-switch` mode; - the Hermes shards of `security-posture` and `channels-stop-start`; - the `hermes` and `deepagents` shards of `mcp-bridge`. @@ -1504,7 +1504,7 @@ concrete job executions. - `channels-stop-start` with the `hermes` shard - `hermes-discord` - `hermes-e2e`, including dashboard coverage -- `hermes-inference-switch` with the `anthropic` mode +- `hermes-inference-switch` with the `native-nvidia` mode - `security-posture` with the `hermes` shard The two extra instrumented executions come from the 3 `common-egress-agent` diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index e74e523a52d..02e7b664d32 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -52,6 +52,7 @@ import { } from "./hermes-inference-switch-helpers.ts"; import { PUBLIC_NVIDIA_SWITCH_PROVIDER, + readPublicNvidiaSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; @@ -139,13 +140,13 @@ test( ); await mockBaseline?.close(); }); - const apiKey = mockBaseline - ? MOCK_BASELINE_API_KEY - : secrets.required("NVIDIA_INFERENCE_API_KEY"); const publicApiKey = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) : null; + const apiKey = mockBaseline + ? MOCK_BASELINE_API_KEY + : (publicApiKey ?? secrets.required("NVIDIA_INFERENCE_API_KEY")); const redactionValues = [apiKey, publicApiKey].filter( (value): value is string => typeof value === "string", ); @@ -304,9 +305,35 @@ test( ); const state = registryState(); - expect(state.registry.sandboxes?.[SANDBOX_NAME]?.agent).toBe("hermes"); - expect(state.registry.sandboxes?.[SANDBOX_NAME]?.provider).toBe(SWITCH_PROVIDER); - expect(state.registry.sandboxes?.[SANDBOX_NAME]?.model).toBe(SWITCH_MODEL); + const attachmentEvidence = await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "hermes-native-nvidia-provider-attachment", + env: env(), + logicalProvider: SWITCH_PROVIDER, + receipt: state.registry.sandboxes?.[SANDBOX_NAME]?.nativeNvidiaProviderAttachment, + sandbox, + sandboxName: SANDBOX_NAME, + }); + expect( + [ + state.registry.sandboxes?.[SANDBOX_NAME]?.agent, + attachmentEvidence, + state.registry.sandboxes?.[SANDBOX_NAME]?.model, + state.registry.sandboxes?.[SANDBOX_NAME]?.provider, + ] + .map(String) + .join("\n"), + ).toBe( + [ + "hermes", + SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER + ? "inspection=0;attached=true;schema=1;profile=nemoclaw-nvidia-inference-v1;provider=nemoclaw-nvidia-prod-v1;provider-id=present" + : null, + SWITCH_MODEL, + SWITCH_PROVIDER, + ] + .map(String) + .join("\n"), + ); expect(state.session).toEqual(baselineSession); const publicSwitch = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER; const durableEndpointUrl = publicSwitch diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 0a091840801..bc17bbc313f 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -64,6 +64,7 @@ import { import { PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, + readPublicNvidiaSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; @@ -135,6 +136,7 @@ interface SandboxRegistry { credentialEnv?: unknown; preferredInferenceApi?: unknown; nimContainer?: unknown; + nativeNvidiaProviderAttachment?: unknown; } >; } @@ -540,7 +542,7 @@ async function getRouteOutput(host: HostCliClient, home: string): Promise { const registryPath = path.join(home, ".nemoclaw", "sandboxes.json"); const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")) as SandboxRegistry; @@ -582,9 +584,28 @@ async function assertRegistryAndSession( expect(session.preferredInferenceApi).toBe("anthropic-messages"); break; case PUBLIC_NVIDIA_SWITCH_PROVIDER: - expect(session.endpointUrl).toBe(NVIDIA_HOSTED_NATIVE_ENDPOINT); - expect(session.credentialEnv).toBe("NVIDIA_INFERENCE_API_KEY"); - expect(session.preferredInferenceApi).toBe("openai-completions"); + expect( + [ + session.endpointUrl, + session.credentialEnv, + session.preferredInferenceApi, + await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "native-nvidia-provider-attachment-after-switch", + env: commandEnv(home), + logicalProvider: SWITCH_PROVIDER, + receipt: sandbox?.nativeNvidiaProviderAttachment, + sandbox: options.sandbox, + sandboxName: SANDBOX_NAME, + }), + ].join("\n"), + ).toBe( + [ + NVIDIA_HOSTED_NATIVE_ENDPOINT, + "NVIDIA_INFERENCE_API_KEY", + "openai-completions", + "inspection=0;attached=true;schema=1;profile=nemoclaw-nvidia-inference-v1;provider=nemoclaw-nvidia-prod-v1;provider-id=present", + ].join("\n"), + ); break; } } @@ -1134,14 +1155,16 @@ test( requireAuth: true, }) : undefined; - const baseline = baselineProvider - ? mockBaselineInference(baselineProvider.baseUrl) - : requireHostedInferenceConfig(secrets); - const apiKey = baseline.apiKey; 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 apiKey = baseline.apiKey; const redactionValues = [apiKey, publicApiKey].filter( (value): value is string => typeof value === "string", ); @@ -1293,7 +1316,7 @@ test( inferenceApi: SWITCH_INFERENCE_API, artifactName: "read-openclaw-config-after-inference-switch", }); - await assertRegistryAndSession(home, { mockProvider }); + await assertRegistryAndSession(home, { mockProvider, sandbox }); progress.phase("prove sandbox and OpenClaw gateway inference"); const inference = await checkSandboxInference(sandbox, artifacts, home); diff --git a/test/e2e/live/public-nvidia-switch-provider.ts b/test/e2e/live/public-nvidia-switch-provider.ts index b65b24f65f1..7fce045f3c2 100644 --- a/test/e2e/live/public-nvidia-switch-provider.ts +++ b/test/e2e/live/public-nvidia-switch-provider.ts @@ -1,6 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeNvidiaProviderAttachment, + NVIDIA_HOSTED_NATIVE_PROVIDER, +} from "../../../src/lib/inference/native-nvidia/index.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; + export const PUBLIC_NVIDIA_SWITCH_PROVIDER = "nvidia-prod"; export const PUBLIC_NVIDIA_SWITCH_MODEL = "nvidia/nemotron-3-super-120b-a12b"; @@ -10,3 +16,31 @@ export function requirePublicNvidiaSwitchKey(value: string): string { } return value; } + +export async function readPublicNvidiaSwitchAttachmentEvidence(options: { + readonly artifactName: string; + readonly env: NodeJS.ProcessEnv; + readonly logicalProvider: string; + readonly receipt: unknown; + readonly sandbox: SandboxClient; + readonly sandboxName: string; +}): Promise { + if (options.logicalProvider !== PUBLIC_NVIDIA_SWITCH_PROVIDER) return null; + const receipt = normalizeNativeNvidiaProviderAttachment(options.receipt); + const attachments = await options.sandbox.openshell( + ["sandbox", "provider", "list", "-g", "nemoclaw", options.sandboxName], + { + artifactName: options.artifactName, + env: options.env, + timeoutMs: 60_000, + }, + ); + return [ + `inspection=${String(attachments.exitCode)}`, + `attached=${String(attachments.stdout.split(/\s+/u).includes(NVIDIA_HOSTED_NATIVE_PROVIDER))}`, + `schema=${String(receipt?.schemaVersion ?? "missing")}`, + `profile=${receipt?.profileId ?? "missing"}`, + `provider=${receipt?.providerName ?? "missing"}`, + `provider-id=${receipt ? "present" : "missing"}`, + ].join(";"); +} 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 804f5dff8c1..1ca42e559d0 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -33,6 +33,10 @@ import { runHermesPongWithRetry, SANDBOX_NAME, } from "../live/hermes-inference-switch-helpers.ts"; +import { + PUBLIC_NVIDIA_SWITCH_PROVIDER, + readPublicNvidiaSwitchAttachmentEvidence, +} from "../live/public-nvidia-switch-provider.ts"; describe("Hermes inference switch command shape", () => { afterEach(() => vi.unstubAllEnvs()); @@ -52,6 +56,61 @@ describe("Hermes inference switch command shape", () => { ); }); + it("requires the durable receipt and live sandbox attachment for native NVIDIA (#12558)", async () => { + const openshell = vi.fn().mockResolvedValue({ + exitCode: 0, + stderr: "", + stdout: "nemoclaw-nvidia-prod-v1\n", + } as ShellProbeResult); + const evidence = await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "native-nvidia-provider-attachment", + env: { OPENSHELL_GATEWAY: "nemoclaw" }, + logicalProvider: PUBLIC_NVIDIA_SWITCH_PROVIDER, + receipt: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-revision-1", + }, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "e2e-hm-inf-switch", + }); + expect(evidence).toBe( + "inspection=0;attached=true;schema=1;profile=nemoclaw-nvidia-inference-v1;provider=nemoclaw-nvidia-prod-v1;provider-id=present", + ); + expect(openshell).toHaveBeenCalledOnce(); + }); + + it.each([ + ["absent", undefined], + [ + "mismatched", + { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "another-provider", + providerId: "provider-revision-1", + }, + ], + ])("reports an %s native NVIDIA attachment receipt (#12558)", async (_label, receipt) => { + const openshell = vi.fn().mockResolvedValue({ + exitCode: 0, + stderr: "", + stdout: "nemoclaw-nvidia-prod-v1\n", + } as ShellProbeResult); + const evidence = await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "native-nvidia-provider-attachment", + env: { OPENSHELL_GATEWAY: "nemoclaw" }, + logicalProvider: PUBLIC_NVIDIA_SWITCH_PROVIDER, + receipt, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "e2e-hm-inf-switch", + }); + expect(evidence).toContain( + "schema=missing;profile=missing;provider=missing;provider-id=missing", + ); + }); + it("omits the conflicting Anthropic frontend flag from Hermes switch metadata (#6289)", () => { expect(compatibleAnthropicMetadataArgs("http://host.openshell.internal:18766")).toEqual([ "--endpoint-url", diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index 7101117699a..ca222fb3332 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -16,7 +16,7 @@ describe("inference-switch catalogue boundary", () => { expect(() => validateE2eTargetCatalogue(E2E_TARGET_CATALOGUE)).not.toThrow(); const openclaw = catalogueTarget("openclaw-inference-switch"); expect(openclaw).toMatchObject({ - profile: "standard", + profile: "nvidia-api", testFile: "test/e2e/live/openclaw-inference-switch.test.ts", environment: { NEMOCLAW_AGENT: "openclaw", @@ -30,17 +30,19 @@ describe("inference-switch catalogue boundary", () => { const hermes = catalogueTarget("hermes-inference-switch"); expect(hermes).toMatchObject({ - profile: "standard", + profile: "nvidia-api", testFile: "test/e2e/live/hermes-inference-switch.test.ts", hostPreparation: "hermes-swap", runnerComparison: true, - shard: "anthropic", + shard: "native-nvidia", environment: { NEMOCLAW_AGENT: "hermes", - NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", - NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod", + NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3-super-120b-a12b", + NEMOCLAW_SWITCH_INFERENCE_API: "openai-completions", }, }); + expect(hermes.environment).not.toHaveProperty("NEMOCLAW_SWITCH_MOCK_ANTHROPIC"); const target = ({ OpenClaw: openclaw, Hermes: hermes } as const)[scenario]!; expect(target.environment).not.toHaveProperty("NEMOCLAW_E2E_USE_HOSTED_INFERENCE"); }, diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index fa976cb19ad..24d61d04547 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -370,15 +370,15 @@ describe("E2E workflow plan", () => { }), ]), ); - expect(plan.catalogueMatrices.standard).toContainEqual( + expect(plan.catalogueMatrices["nvidia-api"]).toContainEqual( expect.objectContaining({ id: "openclaw-inference-switch", display_name: "Inference: OpenClaw switches to native NVIDIA and remains responsive", }), ); expect(selectedWorkflowJobs(plan)).toEqual([ + "catalogue-nvidia-api", "catalogue-nvidia-inference", - "catalogue-standard", ]); expect(catalogueTarget("network-policy").selector).toBe("^network-policy:"); const migratedTargetIds = ["hermes-slack", "openclaw-inference-switch", "sandbox-operations"]; @@ -509,12 +509,12 @@ describe("E2E workflow plan", () => { [ "hermes-inference-switch", { - profile: "standard", + profile: "nvidia-api", installNonInteractive: true, runnerKey: "hermes-inference-switch", hostPreparation: "hermes-swap", runnerComparison: true, - shard: "anthropic", + shard: "native-nvidia", }, ], [ diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 0c72e41b84c..388d9cfc219 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -893,10 +893,10 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }, }), managedRuntimeTarget("hermes-inference-switch", { - displayName: "Inference: Hermes switches to an Anthropic-compatible endpoint", + displayName: "Inference: Hermes switches to native NVIDIA and remains responsive", agentRuntime: "hermes", - environmentOrInferenceEndpoint: "Ubuntu; Anthropic-compatible inference fixture", - profile: "standard", + environmentOrInferenceEndpoint: "Ubuntu; native NVIDIA Endpoints provider", + profile: "nvidia-api", timeoutMinutes: 55, installMode: "authenticated", installNonInteractive: true, @@ -905,15 +905,14 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ runnerKey: "hermes-inference-switch", hostPreparation: "hermes-swap", runnerComparison: true, - shard: "anthropic", + shard: "native-nvidia", environment: { ...nonInteractive, NEMOCLAW_AGENT: "hermes", NEMOCLAW_SANDBOX_NAME: "e2e-hm-inf-switch", - NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", - NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", - NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", - NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod", + NEMOCLAW_SWITCH_MODEL: "nvidia/nemotron-3-super-120b-a12b", + NEMOCLAW_SWITCH_INFERENCE_API: "openai-completions", OPENSHELL_GATEWAY: "nemoclaw", }, }), @@ -1154,7 +1153,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ displayName: "Inference: OpenClaw switches to native NVIDIA and remains responsive", agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; native NVIDIA Endpoints provider", - profile: "standard", + profile: "nvidia-api", timeoutMinutes: 90, installMode: "none", restoreCli: true, From 2ca924f8becff6a1bd9930e67a02dc33cbf93b54 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Fri, 2 Oct 2026 20:29:24 -0700 Subject: [PATCH 013/133] feat(inference): move fixed hosted providers to native access Signed-off-by: Deepak Jain --- Dockerfile | 20 +- agents/hermes/Dockerfile | 1 + agents/langchain-deepagents-code/Dockerfile | 1 + .../generate-config.ts | 11 + .../nemoclaw-anthropic-inference-v1.yaml | 33 ++ .../nemoclaw-gemini-inference-v1.yaml | 33 ++ .../nemoclaw-hermes-inference-v1.yaml | 34 ++ .../nemoclaw-openai-inference-v1.yaml | 34 ++ .../nemoclaw-openrouter-inference-v1.yaml | 33 ++ scripts/generate-openclaw-config.mts | 6 + src/lib/actions/credentials-add.ts | 29 +- src/lib/actions/credentials/reset.ts | 7 +- src/lib/actions/inference-get.test.ts | 2 +- src/lib/actions/inference-get.ts | 26 +- .../inference-set-failure-handling.test.ts | 28 +- ...ence-set-gateway-route-containment.test.ts | 46 +- .../actions/inference-set-hermes-run.test.ts | 79 +++- .../inference-set-local-provider.test.ts | 5 +- ...rence-set-openclaw-gateway-restart.test.ts | 6 +- .../inference-set-openclaw-run.test.ts | 169 ++++++-- .../inference-set-patch-hermes.test.ts | 26 +- .../inference-set-patch-openclaw.test.ts | 17 +- src/lib/actions/inference-set.test-support.ts | 105 +++-- src/lib/actions/inference-set.ts | 179 +++++--- .../sandbox/connect-route-containment.test.ts | 4 +- src/lib/actions/sandbox/connect.ts | 12 +- .../inference-invocation-probe.test.ts | 54 +++ .../sandbox/inference-invocation-probe.ts | 34 +- .../sandbox/inference-route-health.test.ts | 4 +- .../actions/sandbox/inference-route-health.ts | 23 +- ...aunch-readiness-observation-timing.test.ts | 4 +- src/lib/actions/sandbox/launch-readiness.ts | 10 +- .../sandbox/launch-readiness/health.ts | 37 +- .../sandbox/rebuild-credential-preflight.ts | 53 +-- .../actions/sandbox/rebuild-dcode-target.ts | 6 +- .../rebuild-flow-credential-preflight.test.ts | 111 +++-- .../rebuild-provider-preflight.test.ts | 61 +++ .../sandbox/rebuild-provider-preflight.ts | 81 +++- .../actions/sandbox/rebuild-resume-config.ts | 12 +- .../status-snapshot-route-drift.test.ts | 2 +- src/lib/actions/sandbox/status-snapshot.ts | 36 +- .../config/live-export-source-test-fixture.ts | 2 +- .../config/live-export-source.test.ts | 36 +- src/lib/adapters/config/live-export-source.ts | 5 + src/lib/adapters/openshell/providers.test.ts | 10 +- src/lib/domain/config/export-evidence.ts | 1 + src/lib/domain/config/verify-export-source.ts | 20 + src/lib/hermes-managed-route.ts | 7 + src/lib/hermes-provider-auth.test.ts | 119 ++--- src/lib/hermes-provider-auth.ts | 47 +- src/lib/inference/README.md | 25 ++ src/lib/inference/config.test.ts | 14 +- src/lib/inference/config.ts | 24 +- .../inference/gateway-route-compatibility.ts | 4 +- src/lib/inference/native-hosted/index.test.ts | 404 +++++++++++++++++ src/lib/inference/native-hosted/index.ts | 407 ++++++++++++++++++ .../native-hosted/openrouter-headers.ts | 8 + src/lib/inference/native-hosted/profiles.ts | 69 +++ src/lib/inference/native-nvidia/index.ts | 325 ++------------ src/lib/inference/openrouter.ts | 7 +- src/lib/onboard/dcode-selection-drift.test.ts | 1 + src/lib/onboard/dockerfile-patch.test.ts | 2 +- .../hermes-portable-build-context-files.ts | 1 + .../hermes-portable-build-context.ts | 1 + .../inference-providers/hermes.test.ts | 48 +++ src/lib/onboard/inference-providers/hermes.ts | 20 +- src/lib/onboard/inference-providers/types.ts | 9 +- .../sandbox-create-intent-boundary.test.ts | 14 +- src/lib/onboard/machine/handlers/sandbox.ts | 16 +- .../machine/resume-provider-shim.test.ts | 16 + .../onboard/machine/resume-provider-shim.ts | 7 +- src/lib/onboard/provider-recovery.ts | 13 +- src/lib/onboard/rebuild-route-handoff.test.ts | 16 + src/lib/onboard/rebuild-route-handoff.ts | 22 +- .../onboard/recovered-provider-reuse.test.ts | 90 ++-- src/lib/onboard/recovered-provider-reuse.ts | 37 +- .../sandbox-create-intent-resolution.ts | 6 +- .../onboard/sandbox-create-intent-types.ts | 6 +- src/lib/onboard/sandbox-create-intent.ts | 4 +- .../orchestration-native-nvidia.test.ts | 2 +- .../onboard/sandbox-create/orchestration.ts | 22 +- .../sandbox-create/provider-publication.ts | 20 +- src/lib/onboard/sandbox-registration.test.ts | 6 +- src/lib/onboard/sandbox-registration.ts | 24 +- src/lib/onboard/setup-inference.test.ts | 31 +- src/lib/onboard/setup-inference.ts | 79 ++-- .../registry-recovery-seeded-paths.test.ts | 4 +- src/lib/sandbox/build-context.ts | 8 + src/lib/state/registry-normalization.test.ts | 60 +++ src/lib/state/registry.ts | 24 +- src/lib/state/registry/persistence.ts | 31 ++ src/lib/state/registry/route-reservation.ts | 8 +- src/lib/state/registry/types.ts | 8 +- src/lib/verify-deployment.ts | 4 +- .../langchain-deepagents-code-config.test.ts | 6 + test/e2e/live/hermes-inference-switch.test.ts | 2 +- .../live/openclaw-inference-switch.test.ts | 4 +- .../generation/generate-hermes-config.test.ts | 15 + ...te-openclaw-config-llamacpp-compat.test.ts | 11 + .../providerless-agent-config.test.ts | 7 +- test/helpers/onboard-split-context.ts | 46 ++ .../onboard-inference-failure-paths.test.ts | 82 +++- .../onboard-inference-gateway-scope.test.ts | 37 +- .../onboard-inference-reconciliation.test.ts | 174 ++++---- .../onboard-openrouter-inference.test.ts | 144 +++---- .../onboard-terminal-dashboard.test.ts | 2 +- test/onboarding/onboard.test.ts | 25 +- .../sandbox/sandbox-build-context.test.ts | 1 + test/support/connect-flow-test-harness.ts | 10 +- .../native-provider-command-runtime.ts | 48 +++ test/support/setup-inference-test-harness.ts | 4 + 111 files changed, 3063 insertions(+), 1223 deletions(-) create mode 100644 managed-inference/provider-profiles/nemoclaw-anthropic-inference-v1.yaml create mode 100644 managed-inference/provider-profiles/nemoclaw-gemini-inference-v1.yaml create mode 100644 managed-inference/provider-profiles/nemoclaw-hermes-inference-v1.yaml create mode 100644 managed-inference/provider-profiles/nemoclaw-openai-inference-v1.yaml create mode 100644 managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml create mode 100644 src/lib/inference/native-hosted/index.test.ts create mode 100644 src/lib/inference/native-hosted/index.ts create mode 100644 src/lib/inference/native-hosted/openrouter-headers.ts create mode 100644 src/lib/inference/native-hosted/profiles.ts create mode 100644 test/support/native-provider-command-runtime.ts diff --git a/Dockerfile b/Dockerfile index 8cdab0bccb6..b4e58418ced 100644 --- a/Dockerfile +++ b/Dockerfile @@ -650,15 +650,11 @@ FROM openclaw-managed-messaging-npm-cache-${NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UN FROM scratch AS openclaw-dependency-payload -COPY agents/openclaw/openclaw-runtime/package.json /usr/local/lib/nemoclaw/openclaw-runtime/package.json -COPY agents/openclaw/openclaw-runtime/package-lock.json /usr/local/lib/nemoclaw/openclaw-runtime/package-lock.json -COPY agents/openclaw/mcporter-runtime/package.json /usr/local/lib/nemoclaw/mcporter-runtime/package.json -COPY agents/openclaw/mcporter-runtime/package-lock.json /usr/local/lib/nemoclaw/mcporter-runtime/package-lock.json -COPY agents/openclaw/wechat-runtime/package.json /usr/local/lib/nemoclaw/wechat-runtime/package.json -COPY agents/openclaw/wechat-runtime/package-lock.json /usr/local/lib/nemoclaw/wechat-runtime/package-lock.json +COPY agents/openclaw/openclaw-runtime/package.json agents/openclaw/openclaw-runtime/package-lock.json /usr/local/lib/nemoclaw/openclaw-runtime/ +COPY agents/openclaw/mcporter-runtime/package.json agents/openclaw/mcporter-runtime/package-lock.json /usr/local/lib/nemoclaw/mcporter-runtime/ +COPY agents/openclaw/wechat-runtime/package.json agents/openclaw/wechat-runtime/package-lock.json /usr/local/lib/nemoclaw/wechat-runtime/ COPY ci/npm-audit-exceptions.json ci/reviewed-npm-audit.json /scripts/ -COPY scripts/lib/reviewed-npm-archive.mts scripts/lib/bundled-npm-package.mts scripts/lib/reviewed-npm-audit.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/patch-bundled-npm-ip-address.mts scripts/lib/reviewed-npm-identity.mts /scripts/lib/ -COPY scripts/lib/verify-mcporter-audit.sh /scripts/lib/verify-mcporter-audit.sh +COPY scripts/lib/reviewed-npm-archive.mts scripts/lib/bundled-npm-package.mts scripts/lib/reviewed-npm-audit.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/patch-bundled-npm-ip-address.mts scripts/lib/reviewed-npm-identity.mts scripts/lib/verify-mcporter-audit.sh /scripts/lib/ COPY scripts/patch-bundled-npm-brace-expansion.mts scripts/patch-bundled-npm-tar.mts scripts/upgrade-bundled-npm.mts /scripts/ COPY ci/reviewed-npm-audit.json /ci/reviewed-npm-audit.json @@ -698,8 +694,8 @@ COPY scripts/managed-startup-hold.sh /usr/local/bin/nemoclaw-managed-startup-hol COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/ COPY --from=runtime-preload-builder /opt/nemoclaw-root/dist/lib/messaging/channels/ /usr/local/lib/nemoclaw/preloads-compiled-channels/ 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 scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ +COPY --chmod=0444 src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/openrouter-headers.ts 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 nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ @@ -1547,8 +1543,8 @@ 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 scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ +COPY --chmod=0444 src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/openrouter-headers.ts COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index ea70cc1dc1f..b39494ad691 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -62,6 +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/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/openrouter-headers.ts COPY src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ COPY src/lib/messaging/ /src/lib/messaging/ COPY scripts/lib/openclaw-npm-remediation.mts /scripts/lib/openclaw-npm-remediation.mts diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index f398a388fea..af9e71bdcab 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -154,6 +154,7 @@ RUN set -eu; \ # wrapper, startup script, and shared blueprint files. COPY agents/langchain-deepagents-code/generate-config-entrypoint.ts /opt/nemoclaw-deepagents-code/generate-config.ts COPY agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts +COPY --chmod=0444 src/lib/inference/native-hosted/openrouter-headers.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/openrouter-headers.ts COPY src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts COPY agents/langchain-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py COPY agents/langchain-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py diff --git a/agents/langchain-deepagents-code/generate-config.ts b/agents/langchain-deepagents-code/generate-config.ts index 0c3789e6876..a414d916363 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -16,6 +16,8 @@ import { resolveManagedDcodeIdentity, } from "../../src/lib/inference/managed-dcode/identity.ts"; +import { OPENROUTER_DEFAULT_HEADERS } from "../../src/lib/inference/native-hosted/openrouter-headers.ts"; + type ReasoningEffort = "low" | "medium" | "high"; type Settings = { @@ -164,6 +166,15 @@ function providerConfigLines( 'api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"', `base_url = ${tomlString(baseUrl)}`, "enabled = true", + ...(provider === "openrouter" + ? [ + "", + "[models.providers.openrouter.params.default_headers]", + ...OPENROUTER_DEFAULT_HEADERS.map( + ([name, value]) => `${tomlString(name)} = ${tomlString(value)}`, + ), + ] + : []), ...(provider === "openai" ? [ "", diff --git a/managed-inference/provider-profiles/nemoclaw-anthropic-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-anthropic-inference-v1.yaml new file mode 100644 index 00000000000..4b1811659fc --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-anthropic-inference-v1.yaml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-anthropic-inference-v1 +display_name: NemoClaw Anthropic Hosted Inference +description: Native Anthropic hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: Anthropic hosted inference API key + env_vars: + - ANTHROPIC_API_KEY + required: true + auth_style: header + header_name: x-api-key + query_param: '' +endpoints: + - host: api.anthropic.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1/models" } + - allow: { method: POST, path: "/v1/messages" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-gemini-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-gemini-inference-v1.yaml new file mode 100644 index 00000000000..4cfff55d78f --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-gemini-inference-v1.yaml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-gemini-inference-v1 +display_name: NemoClaw Google Gemini Hosted Inference +description: Native Google Gemini hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: Google Gemini hosted inference API key + env_vars: + - GEMINI_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: generativelanguage.googleapis.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1beta/openai/models" } + - allow: { method: POST, path: "/v1beta/openai/chat/completions" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-hermes-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-hermes-inference-v1.yaml new file mode 100644 index 00000000000..76453cd18da --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-hermes-inference-v1.yaml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-hermes-inference-v1 +display_name: NemoClaw Hermes Provider Hosted Inference +description: Native Hermes Provider hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: Hermes Provider hosted inference API key + env_vars: + - OPENAI_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: inference-api.nousresearch.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1/models" } + - allow: { method: POST, path: "/v1/chat/completions" } + - allow: { method: POST, path: "/v1/responses" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-openai-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-openai-inference-v1.yaml new file mode 100644 index 00000000000..e0749d7ce93 --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-openai-inference-v1.yaml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-openai-inference-v1 +display_name: NemoClaw OpenAI Hosted Inference +description: Native OpenAI hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: OpenAI hosted inference API key + env_vars: + - OPENAI_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: api.openai.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1/models" } + - allow: { method: POST, path: "/v1/chat/completions" } + - allow: { method: POST, path: "/v1/responses" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml new file mode 100644 index 00000000000..a1a0d05a8c6 --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-openrouter-inference-v1 +display_name: NemoClaw OpenRouter Hosted Inference +description: Native OpenRouter hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: OpenRouter hosted inference API key + env_vars: + - OPENROUTER_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: openrouter.ai + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/api/v1/models" } + - allow: { method: POST, path: "/api/v1/chat/completions" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/scripts/generate-openclaw-config.mts b/scripts/generate-openclaw-config.mts index ed6dba61f8a..a05c9f9981b 100755 --- a/scripts/generate-openclaw-config.mts +++ b/scripts/generate-openclaw-config.mts @@ -1,6 +1,7 @@ #!/usr/bin/env node // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 + // // Generate openclaw.json from environment variables. // @@ -27,6 +28,8 @@ // NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME, NEMOCLAW_OPENCLAW_OTEL_SAMPLE_RATE, // NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION. +import { OPENROUTER_DEFAULT_HEADERS } from "../src/lib/inference/native-hosted/openrouter-headers.ts"; + import { hasProviderlessInferenceEnvironment } from "../src/lib/providerless-inference.ts"; import { @@ -968,6 +971,9 @@ export function buildConfig(env: Env = process.env): JsonObject { } const providers = { [providerKey]: { + ...(upstreamProvider === "openrouter-api" + ? { headers: Object.fromEntries(OPENROUTER_DEFAULT_HEADERS) } + : {}), baseUrl: inferenceBaseUrl, apiKey: "unused", api: inferenceApi, diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index 9b6803b84e4..79b6d88e969 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES, nativeHostedProfile } from "../inference/native-hosted/profiles"; import fs from "node:fs"; import { isIP } from "node:net"; import path from "node:path"; @@ -13,12 +14,7 @@ import type { OpenShellGatewayTarget } from "../adapters/openshell/sandbox-obser import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../adapters/openshell/timeouts"; import { resolveAgentNameAlias } from "../agent/aliases"; import { CLI_NAME } from "../cli/branding"; -import { - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - nativeNvidiaProviderProfilePath, -} from "../inference/native-nvidia"; +import { nativeHostedProviderProfilePath } from "../inference/native-hosted"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, TAVILY_PROVIDER_PROFILE_AGENTS, @@ -133,8 +129,9 @@ async function providerConfigEndpointFailure( function bundledProviderProfile(type: string): { profileType: string; profilePath: string } | null { const profileType = type.toLowerCase(); - if (profileType === NVIDIA_HOSTED_NATIVE_PROFILE_ID) { - return { profileType, profilePath: nativeNvidiaProviderProfilePath() }; + const hostedProfile = NATIVE_HOSTED_PROFILES.find((profile) => profile.profileId === profileType); + if (hostedProfile) { + return { profileType, profilePath: nativeHostedProviderProfilePath(hostedProfile) }; } const profilePath = path.join( ROOT, @@ -263,8 +260,12 @@ export async function runCredentialsAddAction( } const normalizedType = type.toLowerCase(); - const nativeNvidiaCredentialAlias = - provider === NVIDIA_HOSTED_LOGICAL_PROVIDER && normalizedType === "nvidia"; + const hostedProfile = nativeHostedProfile(provider); + const expectedType = + provider === "nvidia-prod" ? "nvidia" : provider === "anthropic-prod" ? "anthropic" : "openai"; + const nativeHostedCredentialAlias = + hostedProfile && + (normalizedType === expectedType || normalizedType === hostedProfile.profileId); const isTavily = normalizedType === TAVILY_PROVIDER_PROFILE_ID || normalizedType === HERMES_TAVILY_PROVIDER_PROFILE_ID; @@ -284,12 +285,12 @@ export async function runCredentialsAddAction( ]); } } - const effectiveType = nativeNvidiaCredentialAlias - ? NVIDIA_HOSTED_NATIVE_PROFILE_ID + const effectiveType = nativeHostedCredentialAlias + ? hostedProfile!.profileId : isTavily ? webSearchProviderProfileId(normalizedType, agentName) : type; - const effectiveProvider = nativeNvidiaCredentialAlias ? NVIDIA_HOSTED_NATIVE_PROVIDER : provider; + const effectiveProvider = nativeHostedCredentialAlias ? hostedProfile!.providerName : provider; const compatibilityWarnings = normalizedType === TAVILY_PROVIDER_PROFILE_ID && !agentName ? [ @@ -415,7 +416,7 @@ export async function runCredentialsAddAction( // Registration records this provider as an explicit extra-provider intent. // Rebuild validates that intent against current source-backed MCP entries; // orphaned providers retained by conservative MCP removal are not intent. - const recordedReservation = nativeNvidiaCredentialAlias + const recordedReservation = nativeHostedCredentialAlias ? false : recordExtraProvider(effectiveProvider); let keepReservation = false; diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 723f109b7c6..29278bd2233 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter-cli"; import type { OpenShellProviderAdapter, @@ -14,10 +15,6 @@ import { PROVIDER_NAME_VALID_PATTERN, } from "../../name-validation"; import { CLI_NAME } from "../../cli/branding"; -import { - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../../inference/native-nvidia"; import { isBridgeProviderName, recoverCredentialGatewayTargetOrExit, @@ -94,7 +91,7 @@ export async function runCredentialsResetAction( deps: CredentialsResetDeps = {}, ): Promise { const key = input.provider; - const providerName = key === NVIDIA_HOSTED_LOGICAL_PROVIDER ? NVIDIA_HOSTED_NATIVE_PROVIDER : key; + const providerName = nativeHostedProfile(key)?.providerName ?? key; if (!PROVIDER_NAME_VALID_PATTERN.test(key)) { return fail([ " Provider name must be 1-128 chars, start with a letter, and use only letters, digits, '.', '_', or '-'.", diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index e60ba29acf7..bb5ef3af7d2 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -179,7 +179,7 @@ describe("runInferenceGet", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, providerName: "nemoclaw-nvidia-prod-v1" as const, diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index fa0e0ffc070..fc66668734f 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../inference/native-hosted/profiles"; import { captureOpenshell } from "../adapters/openshell/runtime"; import { createSynchronousCliOpenShellInferenceRouteObserver } from "../adapters/openshell/inference-route-cli"; import type { @@ -21,10 +22,9 @@ import { } from "../inference/gateway-route-compatibility"; import { parseHttpsPinRouteId } from "../inference/https-pin-runtime"; import { - isNativeNvidiaProvider, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - normalizeNativeNvidiaProviderAttachment, -} from "../inference/native-nvidia"; + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, +} from "../inference/native-hosted"; import { inspectManagedLlamaCppOwnership } from "../inference/llama-cpp/managed-state"; import { valueLooksLikeSecret } from "../security/credential-filter"; import { ConfigCorruptError, ConfigPermissionError } from "../state/config-io"; @@ -313,15 +313,23 @@ export async function runInferenceGet( const selectedSandbox = selectedSandboxName ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) : null; + const receipt = normalizeNativeHostedProviderAttachment( + selectedSandbox?.nativeHostedProviderAttachment, + ); + if (receipt && nativeHostedProfile(selectedSandbox?.provider)?.profileId !== receipt.profileId) { + throw new InferenceGetError( + "Recorded native inference provider does not match the selected provider.", + ); + } if ( selectedSandbox && - isNativeNvidiaProvider(selectedSandbox.provider) && - normalizeNativeNvidiaProviderAttachment(selectedSandbox.nativeNvidiaProviderAttachment) + isNativeHostedProvider(selectedSandbox.provider) && + normalizeNativeHostedProviderAttachment(selectedSandbox.nativeHostedProviderAttachment) ) { const payload: InferenceGetResult = { provider: selectedSandbox.provider ?? null, model: selectedSandbox.model ?? null, - endpointUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + endpointUrl: nativeHostedProfile(selectedSandbox.provider)!.endpoint, }; if (!options.quiet) { if (options.json) { @@ -329,7 +337,9 @@ export async function runInferenceGet( } else { deps.log(`Provider: ${formatRouteValueForDisplay(payload.provider)}`); deps.log(`Model: ${formatRouteValueForDisplay(payload.model)}`); - deps.log(`Endpoint: ${formatRouteValueForDisplay(NVIDIA_HOSTED_NATIVE_ENDPOINT)}`); + deps.log( + `Endpoint: ${formatRouteValueForDisplay(nativeHostedProfile(selectedSandbox.provider)!.endpoint)}`, + ); } } return payload; diff --git a/src/lib/actions/inference-set-failure-handling.test.ts b/src/lib/actions/inference-set-failure-handling.test.ts index d973f014b83..bb746d0d280 100644 --- a/src/lib/actions/inference-set-failure-handling.test.ts +++ b/src/lib/actions/inference-set-failure-handling.test.ts @@ -97,7 +97,7 @@ describe("runInferenceSet failure handling", () => { const deps = createDeps({ config: {}, openshellStatus: 17 }); await expect( - runInferenceSet({ provider: "openai-api", model: "openai/model-a" }, deps), + runInferenceSet({ provider: "ollama-local", model: "openai/model-a" }, deps), ).rejects.toThrow(/OpenShell inference route update failed/); expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); @@ -118,7 +118,7 @@ describe("runInferenceSet failure handling", () => { status: null, output: "", stdout: "", - stderr: `error: provider 'openai-api' not found at https://user:${password}@gateway.example.test/v1?token=${querySecret} ${"x".repeat(3_000)}`, + stderr: `error: provider 'ollama-local' not found at https://user:${password}@gateway.example.test/v1?token=${querySecret} ${"x".repeat(3_000)}`, error: Object.assign(new Error("spawnSync openshell ENOBUFS"), { code: "ENOBUFS" }), signal: "SIGTERM", }) @@ -130,7 +130,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((error: Error) => error); @@ -172,17 +172,17 @@ describe("runInferenceSet failure handling", () => { status: 1, output: "", stdout: "", - stderr: "error: provider 'openai-api' not found in gateway", + stderr: "error: provider 'ollama-local' not found in gateway", }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((e: Error) => e); expect(err).toBeInstanceOf(Error); const message = (err as Error).message; - expect(message).toMatch(/provider 'openai-api' not found/); + expect(message).toMatch(/provider 'ollama-local' not found/); expect(message).toMatch(/Registered providers: nvidia-prod/); expect(message).not.toMatch(/stale-local|telegram-bridge/); expect(message).toMatch(/Tip: register a new provider with `nemoclaw onboard`/); @@ -207,7 +207,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/model-a" }, + { provider: "ollama-local", model: "openai/model-a" }, deps, ).catch((e: Error) => e); @@ -230,8 +230,8 @@ describe("runInferenceSet failure handling", () => { deps.calls.captureOpenshell .mockReturnValueOnce({ status: 1, - output: "error: provider 'openai-api' not found in gateway", - stdout: "error: provider 'openai-api' not found in gateway", + output: "error: provider 'ollama-local' not found in gateway", + stdout: "error: provider 'ollama-local' not found in gateway", stderr: "", }) .mockReturnValueOnce({ @@ -242,7 +242,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((e: Error) => e); @@ -260,14 +260,14 @@ describe("runInferenceSet failure handling", () => { status: 1, output: "", stdout: "", - stderr: "error: provider 'openai-api' not found in gateway", + stderr: "error: provider 'ollama-local' not found in gateway", }) .mockImplementationOnce(() => { throw new Error(`gateway provider query failed token=${querySecret}`); }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((e: Error) => e); @@ -290,7 +290,7 @@ describe("runInferenceSet failure handling", () => { status: 1, output: "", stdout: "", - stderr: "error: provider 'openai-api' not found in gateway", + stderr: "error: provider 'ollama-local' not found in gateway", }) .mockReturnValueOnce({ status: null, @@ -302,7 +302,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((error: Error) => error); diff --git a/src/lib/actions/inference-set-gateway-route-containment.test.ts b/src/lib/actions/inference-set-gateway-route-containment.test.ts index 2d37f40abbd..aecee700543 100644 --- a/src/lib/actions/inference-set-gateway-route-containment.test.ts +++ b/src/lib/actions/inference-set-gateway-route-containment.test.ts @@ -82,18 +82,18 @@ describe("runtime shared gateway route containment", () => { const deps = createDeps({ config: {}, entries: [ - entry("alpha", { provider: "openrouter-api", model: "openrouter/model-a" }), - entry("stopped-peer", { provider: "openrouter-api", model: "openrouter/model-a" }), + entry("alpha", { provider: "ollama-local", model: "local/model-a" }), + entry("stopped-peer", { provider: "ollama-local", model: "local/model-a" }), ], defaultSandbox: "alpha", }); await expect( runInferenceSet( - { provider: "openrouter-api", model: "openrouter/model-b", sandboxName: "alpha" }, + { provider: "ollama-local", model: "local/model-b", sandboxName: "alpha" }, deps, ), - ).resolves.toMatchObject({ sandboxName: "alpha", model: "openrouter/model-b" }); + ).resolves.toMatchObject({ sandboxName: "alpha", model: "local/model-b" }); expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( [ @@ -102,9 +102,10 @@ describe("runtime shared gateway route containment", () => { "-g", "nemoclaw", "--provider", - "openrouter-api", + "ollama-local", "--model", - "openrouter/model-b", + "local/model-b", + "--no-verify", ], expect.objectContaining({ ignoreError: true }), ); @@ -116,9 +117,7 @@ describe("runtime shared gateway route containment", () => { message.includes("Setting OpenShell inference route"), ); expect(warningIndex).toBeGreaterThanOrEqual(0); - expect(messages[warningIndex]).toContain( - "'stopped-peer' (openrouter-api / openrouter/model-a)", - ); + expect(messages[warningIndex]).toContain("'stopped-peer' (ollama-local / local/model-a)"); expect(warningIndex).toBeLessThan(mutationIndex); }); @@ -130,8 +129,8 @@ describe("runtime shared gateway route containment", () => { entry("alpha", { gatewayName: "nemoclaw-9090", gatewayPort: 9090, - provider: "openrouter-api", - model: "openrouter/model-a", + provider: "ollama-local", + model: "local/model-a", }), entry("default-gateway-peer"), ], @@ -141,10 +140,10 @@ describe("runtime shared gateway route containment", () => { await expect( runInferenceSet( - { provider: "openrouter-api", model: "openrouter/model-b", sandboxName: "alpha" }, + { provider: "ollama-local", model: "local/model-b", sandboxName: "alpha" }, deps, ), - ).resolves.toMatchObject({ sandboxName: "alpha", model: "openrouter/model-b" }); + ).resolves.toMatchObject({ sandboxName: "alpha", model: "local/model-b" }); expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( [ @@ -153,9 +152,10 @@ describe("runtime shared gateway route containment", () => { "-g", "nemoclaw-9090", "--provider", - "openrouter-api", + "ollama-local", "--model", - "openrouter/model-b", + "local/model-b", + "--no-verify", ], expect.objectContaining({ ignoreError: true }), ); @@ -169,7 +169,7 @@ describe("runtime shared gateway route containment", () => { entry("alpha", { gatewayName: "nemoclaw-9090", gatewayPort: 9090, - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -683,8 +683,8 @@ describe("runtime shared gateway route containment", () => { try { const entries = [ entry("route-lock-alpha", { - provider: "openrouter-api", - model: "openrouter/model-a", + provider: "ollama-local", + model: "local/model-a", }), entry("route-lock-beta"), ]; @@ -710,14 +710,14 @@ describe("runtime shared gateway route containment", () => { const results = await Promise.allSettled([ runInferenceSet( { - provider: "openrouter-api", - model: "openrouter/model-a", + provider: "ollama-local", + model: "local/model-a", sandboxName: entries[0].name, }, deps, ), runInferenceSet( - { provider: "anthropic-prod", model: "claude-new", sandboxName: entries[1].name }, + { provider: "ollama-local", model: "local/model-b", sandboxName: entries[1].name }, deps, ), ]); @@ -729,8 +729,8 @@ describe("runtime shared gateway route containment", () => { ), ).toHaveLength(2); expect(entries).toEqual([ - expect.objectContaining({ provider: "openrouter-api", model: "openrouter/model-a" }), - expect.objectContaining({ provider: "anthropic-prod", model: "claude-new" }), + expect.objectContaining({ provider: "ollama-local", model: "local/model-a" }), + expect.objectContaining({ provider: "ollama-local", model: "local/model-b" }), ]); expect( deps.calls.log.mock.calls.some(([message]) => diff --git a/src/lib/actions/inference-set-hermes-run.test.ts b/src/lib/actions/inference-set-hermes-run.test.ts index 46a32841396..e2e70d1899a 100644 --- a/src/lib/actions/inference-set-hermes-run.test.ts +++ b/src/lib/actions/inference-set-hermes-run.test.ts @@ -30,6 +30,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -65,6 +71,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -103,6 +115,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -122,20 +140,7 @@ describe("runInferenceSet Hermes routing", () => { deps, ); - expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( - [ - "inference", - "set", - "-g", - "nemoclaw", - "--provider", - "hermes-provider", - "--model", - "openai/gpt-5.4-mini", - "--no-verify", - ], - { ignoreError: true, includeStreams: true, maxBuffer: 64 * 1024 }, - ); + expect(deps.calls.captureOpenshell).not.toHaveBeenCalled(); expect(config).toEqual({ _nemoclaw_upstream: { provider: "hermes-provider", @@ -145,7 +150,7 @@ describe("runInferenceSet Hermes routing", () => { custom_providers: [ { name: "hermes-provider", - base_url: "https://inference.local/v1", + base_url: "https://inference-api.nousresearch.com/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL, discover_models: true, }, @@ -153,14 +158,14 @@ describe("runInferenceSet Hermes routing", () => { model: { default: "openai/gpt-5.4-mini", provider: "custom", - base_url: "https://inference.local/v1", + base_url: "https://inference-api.nousresearch.com/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL, context_length: 128_000, }, providers: { "hermes-provider": { name: "hermes-provider", - api: "https://inference.local/v1", + api: "https://inference-api.nousresearch.com/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL, default_model: "openai/gpt-5.4-mini", discover_models: true, @@ -222,6 +227,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -255,6 +266,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -302,6 +319,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -356,6 +379,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "openai/gpt-5.4-mini", }, @@ -406,7 +435,7 @@ describe("runInferenceSet Hermes routing", () => { provider_key: "compatible-anthropic-endpoint", model: "claude-sonnet-proxy", }); - expect(deps.calls.updateSandbox.mock.calls.at(-1)).toEqual([ + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( "hermes", expect.objectContaining({ provider: "compatible-anthropic-endpoint", @@ -415,7 +444,7 @@ describe("runInferenceSet Hermes routing", () => { credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", preferredInferenceApi: "openai-completions", }), - ]); + ); expect(result).toMatchObject({ providerKey: "inference", primaryModelRef: "inference/claude-sonnet-proxy", @@ -478,6 +507,12 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "openai/gpt-5.4-mini", }, @@ -574,6 +609,12 @@ describe("runInferenceSet Hermes routing", () => { { name: "hermes-one", agent: "hermes", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "z-ai/glm-5.1", }, diff --git a/src/lib/actions/inference-set-local-provider.test.ts b/src/lib/actions/inference-set-local-provider.test.ts index fd2f6acdbd9..10c9ae2a9b5 100644 --- a/src/lib/actions/inference-set-local-provider.test.ts +++ b/src/lib/actions/inference-set-local-provider.test.ts @@ -90,7 +90,7 @@ describe("runInferenceSet local-provider verification", () => { expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); - it("does not run local validation or force --no-verify for cloud providers", async () => { + it("does not run local validation or mutate the shared route for native cloud providers", async () => { const deps = createDeps({ config: localConfig(), session: baseSession(), @@ -100,7 +100,6 @@ describe("runInferenceSet local-provider verification", () => { expect(deps.calls.validateLocalProvider).not.toHaveBeenCalled(); expect(deps.calls.ensureLocalProviderReachable).not.toHaveBeenCalled(); - const args = deps.calls.captureOpenshell.mock.calls[0][0] as string[]; - expect(args).not.toContain("--no-verify"); + expect(deps.calls.captureOpenshell).not.toHaveBeenCalled(); }); }); 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 f26ed16beb5..fb0d23fd7de 100644 --- a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts +++ b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts @@ -7,7 +7,7 @@ import { runInferenceSet } from "./inference-set"; import { defaultInferenceGatewayRestart } from "./inference-set-gateway-restart"; import { baseSession, createDeps } from "./inference-set.test-support"; -const nativeNvidiaReceipt = { +const nativeHostedReceipt = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, providerName: "nemoclaw-nvidia-prod-v1" as const, @@ -65,7 +65,7 @@ describe("runInferenceSet OpenClaw gateway restart", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/model-a", - nativeNvidiaProviderAttachment: nativeNvidiaReceipt, + nativeHostedProviderAttachment: nativeHostedReceipt, }, session: baseSession({ provider: "nvidia-prod", model: "nvidia/model-a" }), }); @@ -224,7 +224,7 @@ describe("runInferenceSet OpenClaw gateway restart", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/model-a", - nativeNvidiaProviderAttachment: nativeNvidiaReceipt, + nativeHostedProviderAttachment: nativeHostedReceipt, }, session: baseSession({ provider: "nvidia-prod", model: "nvidia/model-a" }), }); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index cf0f5931650..b5fd79272f1 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -2,13 +2,66 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; -import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import type { OpenClawConfigUpdate } from "../sandbox/config"; import type { ConfigObject } from "../security/credential-filter"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import { runInferenceSet } from "./inference-set"; import { baseSession, createDeps } from "./inference-set.test-support"; describe("runInferenceSet OpenClaw routing", () => { + it("retains failed native detach intent and reconciles it before another switch", async () => { + const old = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "old-provider", + }; + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "old", + nativeHostedProviderAttachment: old, + }, + }); + const detach = vi.spyOn(deps.providerAdapter, "detachProvider"); + detach.mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "unknown", message: "detach failed", status: 1 }, + } as any); + await expect( + runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps), + ).rejects.toThrow("detach failed"); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + provider: "openai-api", + pendingNativeHostedProviderDetach: old, + nativeHostedProviderAttachment: expect.objectContaining({ + providerName: "nemoclaw-openai-api-v1", + }), + }), + ); + const attach = vi.spyOn(deps.providerAdapter, "attachProvider"); + await runInferenceSet({ provider: "gemini-api", model: "gemini-test", noVerify: true }, deps); + expect(detach.mock.calls[1][0].providerName).toBe(old.providerName); + expect(detach.mock.invocationCallOrder[1]).toBeLessThan(attach.mock.invocationCallOrder[0]); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + }), + ).toEqual({ + ok: true, + value: { names: ["nemoclaw-gemini-api-v1"] }, + }); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith("alpha", { + pendingNativeHostedProviderDetach: undefined, + }); + }); + it("requires recreation instead of silently migrating a legacy NVIDIA sandbox", async () => { const deps = createDeps({ config: {}, @@ -28,31 +81,6 @@ describe("runInferenceSet OpenClaw routing", () => { }); it("detaches native NVIDIA access only after another provider is healthy", async () => { - let attached = true; - const detachProvider = vi.fn(async () => { - attached = false; - return { ok: true, value: { changed: true } }; - }); - const providerAdapter = { - getProvider: vi.fn(async () => ({ - ok: true, - value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { - id: "11111111-2222-4333-8444-555555555555", - resourceVersion: 1, - }, - }, - })), - detachProvider, - listProviderAttachments: vi.fn(async () => ({ - ok: true, - value: { names: attached ? ["nemoclaw-nvidia-prod-v1"] : [] }, - })), - } as unknown as OpenShellProviderAdapter; const deps = createDeps({ config: { agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, @@ -63,16 +91,17 @@ describe("runInferenceSet OpenClaw routing", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/old-model", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", providerId: "11111111-2222-4333-8444-555555555555", }, }, - providerAdapter, }); + const detachProvider = vi.spyOn(deps.providerAdapter, "detachProvider"); + await runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps); expect(detachProvider).toHaveBeenCalledExactlyOnceWith( @@ -85,9 +114,87 @@ describe("runInferenceSet OpenClaw routing", () => { expect(deps.calls.restartSandboxGateway.mock.invocationCallOrder[0]).toBeLessThan( detachProvider.mock.invocationCallOrder[0], ); - expect(deps.calls.updateSandbox).toHaveBeenCalledWith("alpha", { - nativeNvidiaProviderAttachment: undefined, + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + nativeHostedProviderAttachment: expect.objectContaining({ + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + }), + }), + ); + expect( + deps.calls.updateSandbox.mock.calls.some( + ([, patch]) => + Object.hasOwn(patch, "nativeHostedProviderAttachment") && + patch.nativeHostedProviderAttachment === undefined, + ), + ).toBe(false); + expect( + deps.calls.captureOpenshell.mock.calls.some( + ([args]) => args[0] === "inference" && args[1] === "set", + ), + ).toBe(false); + }); + + it.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "hermes-provider"), + )("changes only the selected sandbox's native $label attachment (#12589)", async (profile) => { + const original = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.logicalProvider === "nvidia-prod", + )!; + const receipt = { + schemaVersion: 1 as const, + profileId: original.profileId, + providerName: original.providerName, + providerId: "original-provider", + }; + const deps = createDeps({ + config: {}, + entries: [ + { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "old", + nativeHostedProviderAttachment: receipt, + }, + { + name: "beta", + agent: "openclaw", + provider: "nvidia-prod", + model: "peer-model", + nativeHostedProviderAttachment: receipt, + }, + ], }); + await runInferenceSet( + { + sandboxName: "alpha", + provider: profile.logicalProvider, + model: "new-model", + noVerify: true, + }, + deps, + ); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + }), + ).toEqual({ ok: true, value: { names: [profile.providerName] } }); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "beta", + }), + ).toEqual({ ok: true, value: { names: [original.providerName] } }); + expect(deps.calls.updateSandbox.mock.calls.every(([name]) => name === "alpha")).toBe(true); + expect( + deps.calls.captureOpenshell.mock.calls.some( + ([args]) => args[0] === "inference" && args[1] === "set", + ), + ).toBe(false); }); it.each([ @@ -300,7 +407,7 @@ describe("runInferenceSet OpenClaw routing", () => { credentialEnv: null, nimContainer: null, preferredInferenceApi: null, - nativeNvidiaProviderAttachment: expect.objectContaining({ + nativeHostedProviderAttachment: expect.objectContaining({ providerName: "nemoclaw-nvidia-prod-v1", }), }), diff --git a/src/lib/actions/inference-set-patch-hermes.test.ts b/src/lib/actions/inference-set-patch-hermes.test.ts index 61b47018703..eec7e416733 100644 --- a/src/lib/actions/inference-set-patch-hermes.test.ts +++ b/src/lib/actions/inference-set-patch-hermes.test.ts @@ -7,6 +7,20 @@ import type { ConfigObject } from "../security/credential-filter"; import { patchHermesInferenceConfig } from "./inference-set"; describe("patchHermesInferenceConfig", () => { + it("keeps OpenRouter attribution in both Hermes provider representations", () => { + const config: ConfigObject = {}; + patchHermesInferenceConfig(config, "openrouter-api", "selected"); + const headers = { + "HTTP-Referer": "https://www.nvidia.com/nemoclaw/", + "X-OpenRouter-Title": "NVIDIA NemoClaw", + }; + expect(config.providers).toMatchObject({ "openrouter-api": { extra_headers: headers } }); + expect(config.custom_providers).toEqual([expect.objectContaining({ extra_headers: headers })]); + patchHermesInferenceConfig(config, "gemini-api", "selected"); + expect(JSON.stringify(config)).not.toContain("HTTP-Referer"); + expect(JSON.stringify(config)).not.toContain("X-OpenRouter-Title"); + }); + it("updates the complete Hermes route for the selected provider", () => { const config: ConfigObject = { model: { @@ -32,7 +46,7 @@ describe("patchHermesInferenceConfig", () => { expect(config.model).toEqual({ default: "openai/gpt-5.4-mini", provider: "custom", - base_url: "https://inference.local/v1", + base_url: "https://inference-api.nousresearch.com/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL, }); expect(config._nemoclaw_upstream).toEqual({ @@ -43,7 +57,7 @@ describe("patchHermesInferenceConfig", () => { expect(config.providers).toEqual({ "hermes-provider": { name: "hermes-provider", - api: "https://inference.local/v1", + api: "https://inference-api.nousresearch.com/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL, default_model: "openai/gpt-5.4-mini", discover_models: true, @@ -52,7 +66,7 @@ describe("patchHermesInferenceConfig", () => { expect(config.custom_providers).toEqual([ { name: "hermes-provider", - base_url: "https://inference.local/v1", + base_url: "https://inference-api.nousresearch.com/v1", api_key: HERMES_PROXY_REWRITE_SENTINEL, discover_models: true, }, @@ -110,7 +124,7 @@ describe("patchHermesInferenceConfig", () => { model: { default: "openai/gpt-5.4-mini", provider: "custom", - base_url: "https://inference.local/v1", + base_url: "https://api.anthropic.com/v1", }, }; @@ -119,13 +133,13 @@ describe("patchHermesInferenceConfig", () => { expect(result.route).toMatchObject({ providerKey: "anthropic", primaryModelRef: "anthropic/claude-sonnet-4-6", - inferenceBaseUrl: "https://inference.local", + inferenceBaseUrl: "https://api.anthropic.com", inferenceApi: "anthropic-messages", }); expect(config.model).toEqual({ default: "claude-sonnet-4-6", provider: "custom", - base_url: "https://inference.local", + base_url: "https://api.anthropic.com", api_key: HERMES_PROXY_REWRITE_SENTINEL, api_mode: "anthropic_messages", }); diff --git a/src/lib/actions/inference-set-patch-openclaw.test.ts b/src/lib/actions/inference-set-patch-openclaw.test.ts index 780684464e8..c6bbf1959cb 100644 --- a/src/lib/actions/inference-set-patch-openclaw.test.ts +++ b/src/lib/actions/inference-set-patch-openclaw.test.ts @@ -13,6 +13,21 @@ function providerModels(config: ConfigObject, providerKey: string): ConfigObject } describe("patchOpenClawInferenceConfig", () => { + it("adds OpenRouter attribution and removes only owned headers when switching away", () => { + const config: ConfigObject = { + models: { providers: { inference: { headers: { "X-Operator": "keep" } } } }, + }; + patchOpenClawInferenceConfig(config, "openrouter-api", "selected"); + const providers = (config.models as ConfigObject).providers as ConfigObject; + expect((providers.inference as ConfigObject).headers).toEqual({ + "X-Operator": "keep", + "HTTP-Referer": "https://www.nvidia.com/nemoclaw/", + "X-OpenRouter-Title": "NVIDIA NemoClaw", + }); + patchOpenClawInferenceConfig(config, "gemini-api", "selected"); + expect((providers.inference as ConfigObject).headers).toEqual({ "X-Operator": "keep" }); + }); + it.each([undefined, null, 16384])( "updates only the selected model's context when the resolved window is %s", (contextWindow) => { @@ -309,7 +324,7 @@ describe("patchOpenClawInferenceConfig", () => { mode: "merge", providers: { anthropic: { - baseUrl: "https://inference.local", + baseUrl: "https://api.anthropic.com", apiKey: "unused", api: "anthropic-messages", models: [ diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index a28da77b37b..cfaea3855dc 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -4,11 +4,7 @@ import { vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; -import { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../inference/native-nvidia"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import type { AgentConfigTarget } from "../sandbox/config"; import type { ConfigObject, ConfigValue } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; @@ -67,77 +63,86 @@ function nativeAwareProviderAdapter( base: OpenShellProviderAdapter, entries: SandboxEntry[], ): OpenShellProviderAdapter { - const recordedEntry = entries.find( - (entry) => entry.nativeNvidiaProviderAttachment?.providerName === NVIDIA_HOSTED_NATIVE_PROVIDER, - ); - const providerId = - recordedEntry?.nativeNvidiaProviderAttachment?.providerId ?? - "11111111-2222-4333-8444-555555555555"; - let providerPresent = recordedEntry !== undefined; - const attachments = new Set( - entries - .filter( - (entry) => - entry.nativeNvidiaProviderAttachment?.providerName === NVIDIA_HOSTED_NATIVE_PROVIDER, - ) - .map((entry) => entry.name), + const states = new Map( + NATIVE_HOSTED_PROFILES.map((profile) => { + const entriesForProvider = entries.filter( + (entry) => entry.nativeHostedProviderAttachment?.providerName === profile.providerName, + ); + return [ + profile.providerName, + { + profile, + providerId: + entriesForProvider[0]?.nativeHostedProviderAttachment?.providerId ?? + `id-${profile.providerName}`, + present: entriesForProvider.length > 0, + attachments: new Set(entriesForProvider.map((entry) => entry.name)), + }, + ]; + }), ); - const isNative = (providerName: string): boolean => - providerName === NVIDIA_HOSTED_NATIVE_PROVIDER; return { ...base, importProviderProfile: async (request) => - request.profilePath.endsWith(`${NVIDIA_HOSTED_NATIVE_PROFILE_ID}.yaml`) + NATIVE_HOSTED_PROFILES.some((profile) => + request.profilePath.endsWith(`${profile.profileId}.yaml`), + ) ? ({ ok: true } as const) : await base.importProviderProfile(request), getProvider: async (request) => { - if (!isNative(request.providerName)) return await base.getProvider(request); - if (!providerPresent) { + const state = states.get(request.providerName); + if (!state) return await base.getProvider(request); + if (!state.present) return { ok: false, error: { kind: "command", reason: "not_found", message: "provider not found" }, } as const; - } return { ok: true, value: { - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentialKeys: [NVIDIA_HOSTED_CREDENTIAL_ENV], + name: state.profile.providerName, + type: state.profile.profileId, + credentialKeys: [state.profile.credentialEnv], configKeys: [], - revision: { id: providerId, resourceVersion: 1 }, + revision: { id: state.providerId, resourceVersion: 1 }, }, } as const; }, createProvider: async (request) => { - if (!isNative(request.name)) return await base.createProvider(request); - providerPresent = true; + const state = states.get(request.name); + if (!state) return await base.createProvider(request); + state.present = true; return { ok: true } as const; }, updateProvider: async (request) => { - if (!isNative(request.providerName)) return await base.updateProvider(request); - providerPresent = true; + const state = states.get(request.providerName); + if (!state) return await base.updateProvider(request); + state.present = true; return { ok: true } as const; }, attachProvider: async (request) => { - if (!isNative(request.providerName)) return await base.attachProvider(request); - attachments.add(request.sandboxName); + const state = states.get(request.providerName); + if (!state) return await base.attachProvider(request); + state.attachments.add(request.sandboxName); return { ok: true } as const; }, detachProvider: async (request) => { - if (!isNative(request.providerName)) return await base.detachProvider(request); - const changed = attachments.delete(request.sandboxName); - return { ok: true, value: { changed } } as const; - }, - listProviderAttachments: async (request) => { - if (!providerPresent) return await base.listProviderAttachments(request); + const state = states.get(request.providerName); + if (!state) return await base.detachProvider(request); return { ok: true, - value: { - names: attachments.has(request.sandboxName) ? [NVIDIA_HOSTED_NATIVE_PROVIDER] : [], - }, + value: { changed: state.attachments.delete(request.sandboxName) }, } as const; }, + listProviderAttachments: async (request) => + ({ + ok: true, + value: { + names: [...states.values()] + .filter((state) => state.present && state.attachments.has(request.sandboxName)) + .map((state) => state.profile.providerName), + }, + }) as const, }; } @@ -306,7 +311,17 @@ export function createDeps(options: { setOpenClawConfigValues: vi.fn(), writeSandboxConfig: vi.fn(), recomputeSandboxConfigHash: vi.fn(), - updateSandbox: vi.fn(options.updateSandbox ?? (() => true)), + updateSandbox: vi.fn( + options.updateSandbox ?? + ((name, patch) => { + const entry = sandboxes[name]; + if (!entry) return false; + sandboxes[name] = { ...entry, ...patch }; + const index = entries.findIndex((candidate) => candidate.name === name); + if (index >= 0) entries[index] = sandboxes[name]; + return true; + }), + ), readSandboxConfig: vi.fn(() => options.config), updateSession: vi.fn((mutator: (value: Session) => Session | void) => { const current = session ?? baseSession(); diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 45bfd4187d4..8c3fcbff7c4 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -8,16 +8,17 @@ import { shellQuote } from "../core/shell-quote"; import { applyHermesManagedRoute } from "../hermes-managed-route"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; import { + nativeHostedProfile, + OPENROUTER_DEFAULT_HEADERS, getProviderSelectionConfig, getSandboxInferenceConfig, - detachNativeNvidiaProvider, - ensureNativeNvidiaProvider, - ensureNativeNvidiaProviderAttached, - isNativeNvidiaProvider, - NVIDIA_HOSTED_CREDENTIAL_ENV, - normalizeNativeNvidiaProviderAttachment, + detachNativeHostedProvider, + ensureNativeHostedProvider, + ensureNativeHostedProviderAttached, + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, resolveAgentInferenceApi, - type NativeNvidiaProviderAttachment, + type NativeHostedProviderAttachment, type SandboxInferenceConfig, } from "../inference/config"; import { resolveContextWindowForModel } from "../inference/context-window"; @@ -694,6 +695,13 @@ function buildProviderConfig( ? [selectedModel, ...existingModels] : existingModels.map((entry, index) => (index === selectedIndex ? selectedModel : entry)), }; + const headers = cloneConfigObject(providerConfig.headers); + for (const [name, value] of OPENROUTER_DEFAULT_HEADERS) { + if (provider === "openrouter-api") headers[name] = value; + else if (headers[name] === value) delete headers[name]; + } + if (Object.keys(headers).length > 0) providerConfig.headers = headers; + else delete providerConfig.headers; return upstreamProviderMarker ? withOpenClawUpstreamProviderHeader(providerConfig, upstreamProviderMarker) : providerConfig; @@ -951,43 +959,50 @@ function openshellInferenceSetArgs(options: { return args; } -function assertNativeNvidiaMigrationReady(input: { +function assertNativeHostedMigrationReady(input: { provider: string; previousProvider: string; - previousAttachment?: NativeNvidiaProviderAttachment; + previousAttachment?: NativeHostedProviderAttachment; sandboxName: string; }): void { if ( - isNativeNvidiaProvider(input.provider) && - isNativeNvidiaProvider(input.previousProvider) && + isNativeHostedProvider(input.provider) && + isNativeHostedProvider(input.previousProvider) && !input.previousAttachment ) { throw new InferenceSetError( - `Sandbox '${input.sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before changing its NVIDIA model.`, + `Sandbox '${input.sandboxName}' predates native hosted provider attachments. Recreate this beta sandbox before changing its hosted inference selection.`, 2, ); } } -async function prepareNativeNvidiaSelection(input: { +async function prepareNativeHostedSelection(input: { provider: string; - previousAttachment?: NativeNvidiaProviderAttachment; + previousAttachment?: NativeHostedProviderAttachment; gatewayName: string; sandboxName: string; deps: InferenceSetDeps; }): Promise<{ - attachment?: NativeNvidiaProviderAttachment; + attachment?: NativeHostedProviderAttachment; attachmentChanged: boolean; }> { - if (!isNativeNvidiaProvider(input.provider)) return { attachmentChanged: false }; + if (!isNativeHostedProvider(input.provider)) return { attachmentChanged: false }; + const profile = nativeHostedProfile(input.provider)!; const target = { kind: "named", gatewayName: input.gatewayName } as const; - const ensured = await ensureNativeNvidiaProvider({ + const ensured = await ensureNativeHostedProvider({ adapter: input.deps.providerAdapter, target, - credentialValue: input.deps.resolveCredentialValue(NVIDIA_HOSTED_CREDENTIAL_ENV) || null, - ...(input.previousAttachment ? { expected: input.previousAttachment } : {}), + profile, + credentialValue: + input.provider === "hermes-provider" + ? null + : input.deps.resolveCredentialValue(profile.credentialEnv) || null, + ...(input.previousAttachment?.profileId === profile.profileId + ? { expected: input.previousAttachment } + : {}), }); - const attached = await ensureNativeNvidiaProviderAttached({ + const attached = await ensureNativeHostedProviderAttached({ adapter: input.deps.providerAdapter, target, sandboxName: input.sandboxName, @@ -997,7 +1012,7 @@ async function prepareNativeNvidiaSelection(input: { } async function applyInferenceRouteSelection(input: { - nativeNvidia: boolean; + nativeHosted: boolean; provider: string; model: string; gatewayName: string; @@ -1005,8 +1020,8 @@ async function applyInferenceRouteSelection(input: { retryProviderNotFound: boolean; deps: InferenceSetDeps; }): Promise { - if (input.nativeNvidia) { - input.deps.log(` Using attached native NVIDIA provider: ${input.provider} / ${input.model}`); + if (input.nativeHosted) { + input.deps.log(` Using attached native hosted provider: ${input.provider} / ${input.model}`); return; } input.deps.log(` Setting OpenShell inference route: ${input.provider} / ${input.model}`); @@ -1045,10 +1060,10 @@ async function applyInferenceRouteSelection(input: { throw new InferenceSetError(failure.message, failure.exitCode); } -async function rollbackNativeNvidiaSelection(input: { +async function rollbackNativeHostedSelection(input: { attachmentChanged: boolean; registryCommitted: boolean; - attachment?: NativeNvidiaProviderAttachment; + attachment?: NativeHostedProviderAttachment; gatewayName: string; sandboxName: string; error: unknown; @@ -1056,7 +1071,7 @@ async function rollbackNativeNvidiaSelection(input: { }): Promise { if (!input.attachmentChanged || input.registryCommitted || !input.attachment) return; try { - await detachNativeNvidiaProvider({ + await detachNativeHostedProvider({ adapter: input.deps.providerAdapter, target: { kind: "named", gatewayName: input.gatewayName }, sandboxName: input.sandboxName, @@ -1261,7 +1276,7 @@ async function runInferenceSetWithoutHostLock( // Registered peers are compared exactly as recorded. In particular, a // stopped legacy Hermes row that still records the Anthropic frontend will // depend on that route when restarted and must not be normalized away. - const selectingNativeNvidia = isNativeNvidiaProvider(provider); + const selectingNativeHosted = isNativeHostedProvider(provider); const routeSandboxes = deps.listSandboxes().sandboxes; const preparedRoute = prepareInferenceSetRoute({ entry: routeEntry, @@ -1270,7 +1285,7 @@ async function runInferenceSetWithoutHostLock( model, customRoute, session: routeSession, - sandboxes: selectingNativeNvidia ? [] : routeSandboxes, + sandboxes: selectingNativeHosted ? [] : routeSandboxes, }); if (preparedRoute.gatewayName !== expectedGatewayName) { throw new InferenceSetError( @@ -1347,7 +1362,7 @@ async function runInferenceSetWithoutHostLock( // instead, exactly like an explicit bridge route. const loopbackNoAuthProxyRoute = usesLoopbackNoAuthProxyRoute(entry, provider); const probeDirectSandboxBridge = - selectingNativeNvidia || + selectingNativeHosted || isSandboxBridgeProviderBinding(directProviderBinding) || loopbackNoAuthProxyRoute; // Adapter routes and explicit custom routes on NemoClaw's sandbox bridge @@ -1427,13 +1442,13 @@ async function runInferenceSetWithoutHostLock( assertReasoningEffortRoute(reasoningEffortRequest, provider, preMutationInferenceApi); const previousProvider = typeof entry.provider === "string" ? entry.provider.trim() : ""; const previousModel = typeof entry.model === "string" ? entry.model.trim() : ""; - const previousNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAttachment, + const previousNativeHostedAttachment = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment, ); - assertNativeNvidiaMigrationReady({ + assertNativeHostedMigrationReady({ provider, previousProvider, - previousAttachment: previousNativeNvidiaAttachment, + previousAttachment: previousNativeHostedAttachment, sandboxName, }); // Capture before registry writes: a retry already has the new route, while @@ -1448,7 +1463,7 @@ async function runInferenceSetWithoutHostLock( [previousInferenceApi, preMutationInferenceApi], [entry.endpointUrl ?? null, registryMetadata.endpointUrl ?? null], ].some(([previous, next]) => previous !== next)); - if (probeDirectSandboxBridge && !selectingNativeNvidia && (!previousProvider || !previousModel)) { + if (probeDirectSandboxBridge && !selectingNativeHosted && (!previousProvider || !previousModel)) { throw new InferenceSetError( `Cannot verify the sandbox-only provider route because sandbox '${sandboxName}' does not record ` + "the previous provider and model needed to restore its OpenShell inference selection.", @@ -1462,11 +1477,11 @@ async function runInferenceSetWithoutHostLock( let providerMutation: Awaited> | null = null; let assertProviderCurrentBeforeSelection: (() => Promise) | null = null; - let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; - let nativeNvidiaAttachmentChanged = false; - let nativeNvidiaRegistryCommitted = false; + let nativeHostedProviderAttachment: NativeHostedProviderAttachment | undefined; + let nativeHostedAttachmentChanged = false; + let nativeHostedRegistryCommitted = false; const restorePreviousInferenceSelection = (): string | null => { - if (selectingNativeNvidia || previousNativeNvidiaAttachment) { + if (selectingNativeHosted || previousNativeHostedAttachment) { appliedInferenceSelection = false; return null; } @@ -1495,15 +1510,15 @@ async function runInferenceSetWithoutHostLock( return null; }; try { - const nativeNvidiaSelection = await prepareNativeNvidiaSelection({ + const nativeHostedSelection = await prepareNativeHostedSelection({ provider, - previousAttachment: previousNativeNvidiaAttachment, + previousAttachment: previousNativeHostedAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, deps, }); - nativeNvidiaProviderAttachment = nativeNvidiaSelection.attachment; - nativeNvidiaAttachmentChanged = nativeNvidiaSelection.attachmentChanged; + nativeHostedProviderAttachment = nativeHostedSelection.attachment; + nativeHostedAttachmentChanged = nativeHostedSelection.attachmentChanged; const providerBinding = httpsPinProviderBinding ?? directProviderBinding; if (providerBinding) { providerMutation = await prepareInferenceSetProviderBinding({ @@ -1562,7 +1577,7 @@ async function runInferenceSetWithoutHostLock( await assertProviderCurrentBeforeSelection?.(); if (routeImpactWarning) deps.log(` ${routeImpactWarning}`); await applyInferenceRouteSelection({ - nativeNvidia: selectingNativeNvidia, + nativeHosted: selectingNativeHosted, provider, model, gatewayName: preparedRoute.gatewayName, @@ -1597,7 +1612,7 @@ async function runInferenceSetWithoutHostLock( provider, model, preferredInferenceApi: preMutationInferenceApi, - ...(selectingNativeNvidia ? { nativeProvider: true } : {}), + ...(selectingNativeHosted ? { nativeProvider: true } : {}), }, previousProvider, previousModel, @@ -1667,7 +1682,11 @@ async function runInferenceSetWithoutHostLock( nimContainer: registryMetadata.nimContainer ?? null, }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + nativeHostedProviderAttachment, + ...(previousNativeHostedAttachment && + previousNativeHostedAttachment.providerName !== nativeHostedProfile(provider)?.providerName + ? { pendingNativeHostedProviderDetach: previousNativeHostedAttachment } + : {}), }); if ( !deps.updateSandbox( @@ -1685,7 +1704,7 @@ async function runInferenceSetWithoutHostLock( `Failed to update NemoClaw registry for sandbox '${sandboxName}'.`, ); } - nativeNvidiaRegistryCommitted = Boolean(nativeNvidiaProviderAttachment); + nativeHostedRegistryCommitted = Boolean(nativeHostedProviderAttachment); const preferredInferenceApi = explicitPreferredInferenceApi ?? @@ -1865,10 +1884,10 @@ async function runInferenceSetWithoutHostLock( }; } catch (error) { if (error instanceof OpenClawInferenceConfigSyncError) throw error; - await rollbackNativeNvidiaSelection({ - attachmentChanged: nativeNvidiaAttachmentChanged, - registryCommitted: nativeNvidiaRegistryCommitted, - attachment: nativeNvidiaProviderAttachment, + await rollbackNativeHostedSelection({ + attachmentChanged: nativeHostedAttachmentChanged, + registryCommitted: nativeHostedRegistryCommitted, + attachment: nativeHostedProviderAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, error, @@ -1908,6 +1927,44 @@ async function runInferenceSetWithoutHostLock( } } +async function completePendingNativeProviderDetach( + sandboxName: string, + gatewayName: string, + deps: InferenceSetDeps, +): Promise { + const entry = resolveTargetSandbox(sandboxName, deps).entry; + const pending = normalizeNativeHostedProviderAttachment(entry.pendingNativeHostedProviderDetach); + if (!pending) { + if (entry.pendingNativeHostedProviderDetach !== undefined) { + throw new InferenceSetError("Invalid pending native provider cleanup receipt."); + } + return; + } + if (nativeHostedProfile(entry.provider)?.providerName === pending.providerName) { + throw new InferenceSetError( + "Refusing to detach the currently selected native inference provider.", + ); + } + await detachNativeHostedProvider({ + adapter: deps.providerAdapter, + target: { kind: "named", gatewayName }, + sandboxName, + expected: pending, + }); + if ( + !deps.updateSandbox(sandboxName, { + pendingNativeHostedProviderDetach: undefined, + ...(!isNativeHostedProvider(entry.provider) + ? { nativeHostedProviderAttachment: undefined } + : {}), + }) + ) { + throw new InferenceSetError( + "Native provider access was removed, but its cleanup receipt could not be cleared. Retry before changing providers.", + ); + } +} + export async function runInferenceSet( options: InferenceSetOptions, deps: InferenceSetDeps = defaultDeps(), @@ -1952,6 +2009,7 @@ export async function runInferenceSet( deps.runtimeProviders, ); const gatewayName = resolveSandboxGatewayName(lockedSelection.entry); + await completePendingNativeProviderDetach(selected.sandboxName, gatewayName, deps); const mutation = await deps.withGatewayRouteMutationLock(gatewayName, () => runInferenceSetWithoutHostLock( { ...options, sandboxName: selected.sandboxName }, @@ -1969,26 +2027,7 @@ export async function runInferenceSet( if (mutation.openClawConfigSyncPending) { clearOpenClawConfigSyncPending(selected.sandboxName, deps); } - const priorNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( - lockedSelection.entry.nativeNvidiaProviderAttachment, - ); - if (priorNativeNvidiaAttachment && !isNativeNvidiaProvider(mutation.result.provider)) { - await detachNativeNvidiaProvider({ - adapter: deps.providerAdapter, - target: { kind: "named", gatewayName }, - sandboxName: selected.sandboxName, - expected: priorNativeNvidiaAttachment, - }); - if ( - !deps.updateSandbox(selected.sandboxName, { - nativeNvidiaProviderAttachment: undefined, - }) - ) { - throw new InferenceSetError( - `Native NVIDIA access was removed from sandbox '${selected.sandboxName}', but NemoClaw could not clear its attachment receipt. Retry this command before another provider change.`, - ); - } - } + await completePendingNativeProviderDetach(selected.sandboxName, gatewayName, deps); return mutation.result; }); } diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index 0983efaca5d..2a6fa011299 100644 --- a/src/lib/actions/sandbox/connect-route-containment.test.ts +++ b/src/lib/actions/sandbox/connect-route-containment.test.ts @@ -251,7 +251,7 @@ describe("connect route containment", () => { gatewayPort: 8080, provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -262,7 +262,7 @@ describe("connect route containment", () => { await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); - expect(harness.verifyNativeNvidiaProviderAttachmentSpy).toHaveBeenCalledWith( + expect(harness.verifyNativeHostedProviderAttachmentSpy).toHaveBeenCalledWith( expect.objectContaining({ sandboxName: "alpha", target: { kind: "named", gatewayName: "nemoclaw" }, diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 519853aea14..3fe5232c9dc 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -118,8 +118,8 @@ import { type ProbeTimingRecorder, publicationFromDecision, publishLaunchReadiness, - getNativeNvidiaProviderAttachment, - requireNativeNvidiaInferenceHealth, + getNativeHostedProviderAttachment, + requireNativeHostedInferenceHealth, settlePortableOpenClawPairing, withLaunchReadinessMutationGate, } from "./launch-readiness"; @@ -1700,9 +1700,9 @@ async function ensureSandboxInferenceRouteUnlocked( assertNoOpenShellGatewayEndpointOverride(); const { provider, model } = inference; const gatewayName = getPersistedSandboxTargetGatewayName(sb); - const nativeNvidiaAttachment = getNativeNvidiaProviderAttachment(sb); - if (nativeNvidiaAttachment) { - await requireNativeNvidiaInferenceHealth({ + const nativeHostedAttachment = getNativeHostedProviderAttachment(sb); + if (nativeHostedAttachment) { + await requireNativeHostedInferenceHealth({ sandboxName, gatewayName, agentName: agent?.name, @@ -1858,7 +1858,7 @@ async function ensureSandboxInferenceRoute( if (!snapshot) return { sandbox: null, routeHealthy: null }; if (registry.getSandboxEntryInference(snapshot).kind !== "configured") return { sandbox: snapshot, routeHealthy: null }; - if (getNativeNvidiaProviderAttachment(snapshot)) { + if (getNativeHostedProviderAttachment(snapshot)) { return ensureSandboxInferenceRouteUnlocked(sandboxName, agent, { quiet }); } const gatewayName = getPersistedSandboxTargetGatewayName(snapshot); diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 4212c3d202e..6e9ad93505b 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -94,6 +94,60 @@ const NVCF_BODY_VARIANTS = [ ["extra whitespace", `{"status":404,"detail":"Function 'abc-123': Not found for account"}`], ] as const; +describe("native hosted inference protocol requests", () => { + it.each<[string, string, string, string[]]>([ + [ + "openai-api", + "openai-responses", + "https://api.openai.com/v1/responses", + ["Authorization: Bearer nemoclaw-openshell-provider"], + ], + [ + "anthropic-prod", + "anthropic-messages", + "https://api.anthropic.com/v1/messages", + ["x-api-key: nemoclaw-openshell-provider", "anthropic-version: 2023-06-01"], + ], + [ + "gemini-api", + "openai-completions", + "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", + ["Authorization: Bearer nemoclaw-openshell-provider"], + ], + [ + "openrouter-api", + "openai-completions", + "https://openrouter.ai/api/v1/chat/completions", + ["HTTP-Referer: https://www.nvidia.com/nemoclaw/", "X-OpenRouter-Title: NVIDIA NemoClaw"], + ], + [ + "hermes-provider", + "openai-responses", + "https://inference-api.nousresearch.com/v1/responses", + ["Authorization: Bearer nemoclaw-openshell-provider"], + ], + [ + "hermes-provider", + "openai-completions", + "https://inference-api.nousresearch.com/v1/chat/completions", + ["Authorization: Bearer nemoclaw-openshell-provider"], + ], + ])( + "sends %s requests to its native protocol endpoint (#12589)", + (provider, preferredInferenceApi, endpoint, headers) => { + const result = runProbeCommandWithBody("200", "{}", tmpdir(), { + ...input, + provider, + preferredInferenceApi, + nativeProvider: true, + } as typeof input); + expect(result.argv).toContain(endpoint); + expect(result.argv).toEqual(expect.arrayContaining(headers)); + expect(result.argv.join(" ")).not.toContain("inference.local"); + }, + ); +}); + describe("sandbox inference invocation probe", () => { it("ignores personal curl configuration when an inference request fails (#11520)", () => { const dir = mkdtempSync(path.join(tmpdir(), "nemoclaw-curl-config-")); diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index 50c5bd2a6b8..62fff09ea15 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; +import { getOpenRouterCurlHeaders } from "../../inference/openrouter"; import { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; import type { OpenShellSandboxBufferedCommandExecutor, @@ -13,10 +15,7 @@ import { } from "../../adapters/openshell/sandbox-observer"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import { getSandboxInferenceConfig } from "../../inference/config"; -import { - isNativeNvidiaProvider, - NVIDIA_HOSTED_NATIVE_ENDPOINT, -} from "../../inference/native-nvidia"; +import { isNativeHostedProvider } from "../../inference/native-hosted"; import { validateInferenceResponseBody } from "../../inference/health"; import { MIN_PROBE_REPLY_TOKENS, @@ -86,19 +85,30 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { input.provider, input.preferredInferenceApi, ); - const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); + const useNativeHosted = input.nativeProvider === true && isNativeHostedProvider(input.provider); const baseUrl = ( - useNativeNvidia - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : isNativeNvidiaProvider(input.provider) + useNativeHosted + ? nativeHostedProfile(input.provider)!.endpoint + : isNativeHostedProvider(input.provider) ? "https://inference.local/v1" : config.inferenceBaseUrl ).replace(/\/+$/u, ""); - const apiBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`; + const apiBaseUrl = + config.inferenceApi === "anthropic-messages" && !baseUrl.endsWith("/v1") + ? `${baseUrl}/v1` + : baseUrl; + const nativeHeaders = useNativeHosted + ? [ + input.provider === "anthropic-prod" + ? "x-api-key: nemoclaw-openshell-provider" + : "Authorization: Bearer nemoclaw-openshell-provider", + ...(input.provider === "openrouter-api" ? getOpenRouterCurlHeaders() : []), + ] + : []; if (config.inferenceApi === "anthropic-messages") { return { endpoint: `${apiBaseUrl}/messages`, - headers: ["anthropic-version: 2023-06-01"], + headers: ["anthropic-version: 2023-06-01", ...nativeHeaders], payload: { model: input.model, max_tokens: MIN_PROBE_REPLY_TOKENS, @@ -109,7 +119,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { if (config.inferenceApi === "openai-responses" || config.inferenceApi === "responses") { return { endpoint: `${apiBaseUrl}/responses`, - headers: [], + headers: nativeHeaders, payload: { model: input.model, input: "Reply with OK", @@ -119,7 +129,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { } return { endpoint: `${apiBaseUrl}/chat/completions`, - headers: useNativeNvidia ? ["Authorization: Bearer nemoclaw-openshell-provider"] : [], + headers: nativeHeaders, payload: { model: input.model, [resolveMaxTokensField(input.model)]: resolveProbeReplyTokens(input.provider), diff --git a/src/lib/actions/sandbox/inference-route-health.test.ts b/src/lib/actions/sandbox/inference-route-health.test.ts index d79ebc56d12..ffc4c5514af 100644 --- a/src/lib/actions/sandbox/inference-route-health.test.ts +++ b/src/lib/actions/sandbox/inference-route-health.test.ts @@ -131,7 +131,7 @@ describe("buildSandboxInferenceRouteHealth (#10080)", () => { gateway(503, false), null, { ok: true }, - { agentName: "openclaw", provider: "nvidia-prod", nativeNvidia: true }, + { agentName: "openclaw", provider: "nvidia-prod", nativeHosted: true }, ); expect(result).toMatchObject({ @@ -152,7 +152,7 @@ describe("buildSandboxInferenceRouteHealth (#10080)", () => { httpStatus: 401, endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", }, - { agentName: "openclaw", provider: "nvidia-prod", nativeNvidia: true }, + { agentName: "openclaw", provider: "nvidia-prod", nativeHosted: true }, ); expect(result).toMatchObject({ diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 37f3a5c70bf..46897a775eb 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -7,10 +7,7 @@ import { OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS } from "../../adapters/opens import * as agentRuntime from "../../agent/runtime"; import { REPOSITORY_ROOT } from "../../core/repository-root"; import type { ProviderHealthStatus } from "../../inference/health"; -import { - isNativeNvidiaProvider, - NVIDIA_HOSTED_NATIVE_ENDPOINT, -} from "../../inference/native-nvidia"; +import { isNativeHostedProvider } from "../../inference/native-hosted"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; import { buildSandboxInferenceRouteProbeRequest, @@ -244,7 +241,7 @@ function buildInvokedRouteHealth( export type SandboxInferenceRouteHealthContext = { agentName: string | null; provider: string | null; - nativeNvidia?: boolean; + nativeHosted?: boolean; }; /** @@ -297,11 +294,17 @@ export function buildSandboxInferenceRouteHealth( invocation: SandboxInferenceInvocationResult | null, context: SandboxInferenceRouteHealthContext, ): ProviderHealthStatus { - if (context.nativeNvidia && isNativeNvidiaProvider(context.provider)) { + if (context.nativeHosted && isNativeHostedProvider(context.provider)) { const endpoint = invocation && !invocation.ok && invocation.endpoint ? invocation.endpoint - : `${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions`; + : resolveSandboxInferenceInvocationEndpoint({ + sandboxName: "", + provider: context.provider!, + model: "", + preferredInferenceApi: null, + nativeProvider: true, + }); const diagnostics = providerHealthDiagnostics(providerHealth, Boolean(invocation?.ok)); const nativeHealth: ProviderHealthStatus = invocation?.ok ? { @@ -309,7 +312,7 @@ export function buildSandboxInferenceRouteHealth( probed: true, providerLabel: "Inference route", endpoint, - detail: "The attached OpenShell provider served a native NVIDIA inference request.", + detail: "The attached OpenShell provider served a native hosted inference request.", } : { ok: false, @@ -317,8 +320,8 @@ export function buildSandboxInferenceRouteHealth( providerLabel: "Inference route", endpoint, detail: invocation - ? `The native NVIDIA route did not serve an inference request: ${invocation.detail}.` - : "Could not probe the native NVIDIA route from inside the sandbox. Recreate legacy beta sandboxes before using this route.", + ? `The native hosted route did not serve an inference request: ${invocation.detail}.` + : "Could not probe the native hosted route from inside the sandbox. Recreate legacy beta sandboxes before using this route.", failureLabel: classifyInferenceInvocationFailureLabel(invocation?.httpStatus ?? null), }; return diagnostics.length > 0 ? { ...nativeHealth, subprobes: diagnostics } : nativeHealth; diff --git a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts index 3547a5cb609..a1dbc67d2ba 100644 --- a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts @@ -163,7 +163,7 @@ describe("launch readiness observation timing", () => { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", credentialEnv: "NVIDIA_INFERENCE_API_KEY", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -178,7 +178,7 @@ describe("launch readiness observation timing", () => { const invoke = vi.fn(async () => ({ ok: true }) as const); currentDeps.getSandbox = () => nativeEntry; currentDeps.capture = capture; - currentDeps.verifyNativeNvidiaAttachment = verifyAttachment; + currentDeps.verifyNativeHostedAttachment = verifyAttachment; currentDeps.inferenceInvocationProbe = invoke; const decision = await inspectLaunchReadiness(SANDBOX, currentDeps); diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 5289c9c06a6..1870c7f69d7 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -65,7 +65,7 @@ import { type LaunchReadinessObservationStage, LaunchReadinessObservationError as ObservationError, recordLaunchReadinessObservationFailure, - getNativeNvidiaProviderAttachment, + getNativeHostedProviderAttachment, requireLaunchSemanticHealth, resolveLaunchInteractiveCommand, resolveTrustedLaunchAgent, @@ -88,8 +88,8 @@ import { export { createProbeTimingRecorder, type ProbeTimingRecorder } from "./probe/timing"; export { createBoundLaunchReadinessDeps }; export { - getNativeNvidiaProviderAttachment, - requireNativeNvidiaInferenceHealth, + getNativeHostedProviderAttachment, + requireNativeHostedInferenceHealth, } from "./launch-readiness/health"; const LIVE_POLICY_MAX_BYTES = 2 * 1_024 * 1_024; @@ -826,9 +826,9 @@ async function captureLaunchIdentity( } const inferenceSelection = normalizeInferenceSelection(entry); const inference = registry.getSandboxEntryInference(entry); - const nativeNvidia = Boolean(getNativeNvidiaProviderAttachment(entry)); + const nativeHosted = Boolean(getNativeHostedProviderAttachment(entry)); let liveInference: { provider: string; model: string } | null = null; - if (!nativeNvidia) { + if (!nativeHosted) { const inferenceGetStartedAt = performance.now(); let inferenceResult: Awaited< ReturnType< diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index 618cfb7eddd..d499a8d837f 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../../inference/native-hosted/profiles"; import { captureOpenshell } from "../../../adapters/openshell/runtime"; import { createCliOpenShellProviderAdapter } from "../../../adapters/openshell/provider-adapter-cli"; import type { OpenShellSandboxBufferedCommandExecutor } from "../../../adapters/openshell/sandbox-command"; @@ -18,10 +19,10 @@ import { } from "../../../onboard/sandbox-recreate-probe"; import type { SandboxEntry } from "../../../state/registry"; import { - normalizeNativeNvidiaProviderAttachment, - verifyNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "../../../inference/native-nvidia"; + normalizeNativeHostedProviderAttachment, + verifyNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../../inference/native-hosted"; import { createSynchronousCliOpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route-cli"; import type { OpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route"; import { @@ -79,10 +80,10 @@ export interface LaunchReadinessHealthDeps { gatewayName: string, ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; - verifyNativeNvidiaAttachment?: (input: { + verifyNativeHostedAttachment?: (input: { sandboxName: string; gatewayName: string; - expected: NativeNvidiaProviderAttachment; + expected: NativeHostedProviderAttachment; }) => Promise; recordObservationTiming?: (stage: LaunchReadinessObservationStage, elapsedMs: number) => void; recordObservationFailure?: (stage: LaunchReadinessObservationStage) => void; @@ -207,32 +208,36 @@ export function resolveTrustedLaunchAgent( return agent; } -export function getNativeNvidiaProviderAttachment( +export function getNativeHostedProviderAttachment( entry: SandboxEntry, -): NativeNvidiaProviderAttachment | null { - return normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) ?? null; +): NativeHostedProviderAttachment | null { + const receipt = normalizeNativeHostedProviderAttachment(entry.nativeHostedProviderAttachment); + if (receipt && nativeHostedProfile(entry.provider)?.profileId !== receipt.profileId) { + throw new LaunchReadinessEvidenceError(); + } + return receipt ?? null; } -export async function requireNativeNvidiaInferenceHealth(input: { +export async function requireNativeHostedInferenceHealth(input: { sandboxName: string; gatewayName: string; agentName?: string; entry: SandboxEntry; deps: LaunchReadinessHealthDeps; }): Promise { - const expected = getNativeNvidiaProviderAttachment(input.entry); + const expected = getNativeHostedProviderAttachment(input.entry); if (!expected) return false; const provider = normalizedString(input.entry.provider); const model = normalizedString(input.entry.model); if (!provider || !model) throw new LaunchReadinessEvidenceError(); - if (input.deps.verifyNativeNvidiaAttachment) { - await input.deps.verifyNativeNvidiaAttachment({ + if (input.deps.verifyNativeHostedAttachment) { + await input.deps.verifyNativeHostedAttachment({ sandboxName: input.sandboxName, gatewayName: input.gatewayName, expected, }); } else { - await verifyNativeNvidiaProviderAttachment({ + await verifyNativeHostedProviderAttachment({ adapter: createCliOpenShellProviderAdapter(), target: { kind: "named", gatewayName: input.gatewayName }, sandboxName: input.sandboxName, @@ -351,9 +356,9 @@ export async function requireLaunchSemanticHealth( } if (inferenceConfigured) { const inferenceStartedAt = performance.now(); - if (getNativeNvidiaProviderAttachment(entry)) { + if (getNativeHostedProviderAttachment(entry)) { try { - await requireNativeNvidiaInferenceHealth({ + await requireNativeHostedInferenceHealth({ sandboxName, gatewayName, agentName, diff --git a/src/lib/actions/sandbox/rebuild-credential-preflight.ts b/src/lib/actions/sandbox/rebuild-credential-preflight.ts index be249d4299b..45b6e8a68b6 100644 --- a/src/lib/actions/sandbox/rebuild-credential-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-credential-preflight.ts @@ -20,12 +20,6 @@ const hermesProviderAuth = require("../../hermes-provider-auth") as { exists: boolean; credentialKeys: string[] | null; }>; - registerHermesInferenceProvider: ( - apiKey: string, - runOpenshellFn: typeof runOpenshell, - credentialEnv?: string, - baseUrl?: string, - ) => Promise; }; export type RebuildBail = (message: string, code?: number) => never; @@ -57,11 +51,6 @@ function normalizeHermesRebuildAuthMethod(value: unknown): "oauth" | "api_key" | return null; } -function nonEmptyString(value: unknown): string | null { - const normalized = String(value || "").trim(); - return normalized || null; -} - async function preflightHermesProviderCredentials( persistedAuthMethod: unknown, credentialEnv: string | null, @@ -70,10 +59,8 @@ async function preflightHermesProviderCredentials( const authMethod = normalizeHermesRebuildAuthMethod(persistedAuthMethod) || (credentialEnv === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV ? "api_key" : null); - const expectedCredentialEnv = - authMethod === "api_key" - ? hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV - : hermesProviderAuth.HERMES_INFERENCE_CREDENTIAL_ENV; + // Native Hermes stores either logical authentication method under one profile key. + const expectedCredentialEnv = hermesProviderAuth.HERMES_INFERENCE_CREDENTIAL_ENV; const binding = await hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); if (binding.exists) { @@ -95,38 +82,8 @@ async function preflightHermesProviderCredentials( return false; } - if (authMethod === "api_key") { - const envKey = nonEmptyString( - process.env[hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV], - ); - log( - `Hermes Provider rebuild preflight: OpenShell provider missing; API key env=${envKey ? "present" : "missing"}`, - ); - if (envKey) { - try { - console.log( - " Hermes Provider is not registered in OpenShell; registering it from the configured exported API-key environment variable before rebuild.", - ); - await hermesProviderAuth.registerHermesInferenceProvider( - envKey, - runOpenshell, - hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV, - ); - const registered = await hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); - return ( - registered.credentialKeys?.length === 1 && - registered.credentialKeys[0] === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV - ); - } catch (err) { - log( - `Hermes Provider rebuild preflight: failed to register OpenShell provider: ${ - err instanceof Error ? err.message : String(err) - }`, - ); - } - } - } - + // A rebuild may reuse only the recorded provider identity. Recreating a + // missing provider here would mutate credentials before the receipt check. console.error(""); console.error( ` ${RD}Rebuild preflight failed:${R} Hermes Provider is not registered in OpenShell.`, @@ -134,7 +91,7 @@ async function preflightHermesProviderCredentials( console.error(" Hermes Provider credentials must be stored in OpenShell, not host-side files."); if (authMethod === "api_key") { console.error( - ` Export the Hermes Provider API key and rerun rebuild, or re-run ${CLI_NAME} onboard to register it.`, + ` Re-run ${CLI_NAME} onboard to recreate the sandbox with its native provider attachment.`, ); } else { console.error( diff --git a/src/lib/actions/sandbox/rebuild-dcode-target.ts b/src/lib/actions/sandbox/rebuild-dcode-target.ts index 84aa20cbcd0..495c4945ba0 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-target.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-target.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { GATEWAY_PORT } from "../../core/ports"; -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; import { resolveGatewayPortFromName, resolveSandboxGatewayName, @@ -14,7 +14,7 @@ export const DCODE_AGENT_NAME = "langchain-deepagents-code"; export type DcodeRebuildRegistryEntry = SandboxGatewayBinding & { agent?: string | null; dashboardPort?: number | null; - nativeNvidiaProviderAttachment?: unknown; + nativeHostedProviderAttachment?: unknown; }; export type DcodeRebuildResumeConfig = { @@ -70,7 +70,7 @@ export function resolveDcodeRebuildTarget( provider: requiredString(resumeConfig.provider, "inference provider"), model: requiredString(resumeConfig.model, "inference model"), preferredInferenceApi: resumeConfig.preferredInferenceApi, - ...(normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) + ...(normalizeNativeHostedProviderAttachment(entry.nativeHostedProviderAttachment) ? { nativeProvider: true } : {}), }; diff --git a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts index 9d1f6bd7ac8..225e41013fd 100644 --- a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts @@ -5,12 +5,46 @@ import { describe, expect, it, vi } from "vitest"; import { makeMessagingPlan } from "../../../../test/helpers/messaging-plan-fixtures"; import { expectNoSandboxDelete } from "../../../../test/helpers/rebuild-delete-assertions"; import { - createRebuildFlowHarness, + createRebuildFlowHarness as createBaseRebuildFlowHarness, installRebuildFlowTestHooks, snapshotEnv, } from "../../../../test/helpers/rebuild-flow-generic-harness"; +import { + nativeHostedProfile, + NATIVE_HOSTED_PROFILES, +} from "../../inference/native-hosted/profiles"; import { makePreparedRecoveryManifest } from "./rebuild-flow-test-fixtures"; +function createRebuildFlowHarness( + options: NonNullable[0]>, +) { + const provider = options.sandboxEntry?.provider; + const profile = nativeHostedProfile(typeof provider === "string" ? provider : null); + return createBaseRebuildFlowHarness({ + ...options, + ...(profile && options.sandboxEntry + ? { + sandboxEntry: { + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "11111111-2222-4333-8444-555555555555", + }, + ...options.sandboxEntry, + }, + } + : {}), + ...(profile?.logicalProvider === "hermes-provider" && !options.runOpenshell + ? { + runOpenshell: providerRuntime(["hermes-provider"], { + "hermes-provider": "OPENAI_API_KEY", + }), + } + : {}), + }); +} + type Harness = ReturnType; const MODEL = "test/model"; @@ -42,18 +76,21 @@ function providerRuntime( ]), ]; const describeProvider = (provider: string) => { + const native = nativeHostedProfile(provider); const output = [ - `Name: ${provider}`, - "Type: openai", + `Name: ${native?.providerName ?? provider}`, + `Type: ${native?.profileId ?? "openai"}`, + "Id: 11111111-2222-4333-8444-555555555555", + "Resource version: 1", `Credential keys: ${providerCredentialKeys(provider).join(", ")}`, - "Config keys: OPENAI_BASE_URL", + `Config keys: ${native ? "" : "OPENAI_BASE_URL"}`, ].join("\n"); return { status: 0, output, stdout: output, stderr: "" }; }; const missingProvider = { status: 1, output: "", stdout: "", stderr: "provider not found" }; const inventoryOutput = JSON.stringify( registeredProviders.map((provider) => ({ - name: provider, + name: nativeHostedProfile(provider)?.providerName ?? provider, credential_keys: providerCredentialKeys(provider), ...(credentialExpiresAtMs[provider] ? { credential_expires_at_ms: credentialExpiresAtMs[provider] } @@ -61,7 +98,10 @@ function providerRuntime( })), ); return (args: string[]) => { - const provider = args[0] === "provider" && args[1] === "get" ? args[2] : undefined; + const requested = args[0] === "provider" && args[1] === "get" ? args[2] : undefined; + const provider = + NATIVE_HOSTED_PROFILES.find((profile) => profile.providerName === requested) + ?.logicalProvider ?? requested; return args[0] === "provider" && args[1] === "list" ? { status: 0, output: inventoryOutput, stdout: inventoryOutput, stderr: "" } : provider === undefined @@ -267,11 +307,9 @@ describe("rebuildSandbox flow: credential preflight", () => { await expect( harness.rebuildSandbox("alpha", ["--yes", "--force"], { throwOnError: true }), - ).rejects.toThrow("Missing gateway provider credential: nvidia-prod/NVIDIA_INFERENCE_API_KEY"); + ).rejects.toThrow("Could not verify gateway provider: nvidia-prod"); - expect(diagnostics(harness)).toContain( - "provider 'nvidia-prod' no longer exposes credential NVIDIA_INFERENCE_API_KEY", - ); + expect(diagnostics(harness)).toContain("could not verify provider 'nvidia-prod' in OpenShell"); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); @@ -281,7 +319,6 @@ describe("rebuildSandbox flow: credential preflight", () => { it.each([ ["has no expiration map", undefined], ["has an explicit non-expiring value", { NVIDIA_INFERENCE_API_KEY: 0 }], - ["is absent from another credential's expiration map", { OTHER_API_KEY: 1_000 }], ["has a future expiration", { NVIDIA_INFERENCE_API_KEY: 8_640_000_000_000_000 }], ])( "continues when the selected provider credential %s (#10394)", @@ -309,6 +346,32 @@ describe("rebuildSandbox flow: credential preflight", () => { }, ); + it("does not expire a custom provider credential because another key expired (#10394)", async () => { + const harness = createRebuildFlowHarness({ + sandboxEntry: { + provider: "compatible-endpoint", + model: MODEL, + credentialEnv: "COMPATIBLE_API_KEY", + endpointUrl: "https://inference.example.test/v1", + preferredInferenceApi: "openai-completions", + }, + hydrateCredentialEnv: () => "saved-provider-key", + runOpenshell: providerRuntime( + ["compatible-endpoint"], + { "compatible-endpoint": "COMPATIBLE_API_KEY" }, + { "compatible-endpoint": { OTHER_API_KEY: 1_000 } }, + ), + }); + configureSession(harness, "compatible-endpoint", "COMPATIBLE_API_KEY", { + endpointUrl: "https://inference.example.test/v1", + preferredInferenceApi: "openai-completions", + }); + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).resolves.toBeUndefined(); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + }); + it("preserves the sandbox when the provider loses the selected credential key during backup (#10394)", async () => { let backedUp = false; const validProvider = providerRuntime(["nvidia-prod"]); @@ -331,9 +394,7 @@ describe("rebuildSandbox flow: credential preflight", () => { await expect( harness.rebuildSandbox("alpha", ["--yes", "--force"], { throwOnError: true }), - ).rejects.toThrow( - "no longer exposes credential NVIDIA_INFERENCE_API_KEY before sandbox deletion", - ); + ).rejects.toThrow("is indeterminate before sandbox deletion"); expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); expectNoSandboxDelete(harness.runOpenshellSpy); @@ -779,7 +840,7 @@ describe("rebuildSandbox flow: credential preflight", () => { expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); }); - it("registers an exported Hermes API key before backup without logging it", async () => { + it("preserves a missing native Hermes identity despite an exported API key", async () => { const restoreEnv = snapshotEnv(["NOUS_API_KEY"]); process.env.NOUS_API_KEY = "nous-key-from-env"; @@ -801,26 +862,18 @@ describe("rebuildSandbox flow: credential preflight", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); + ).rejects.toThrow("Missing Hermes Provider credentials"); - expect(harness.registerHermesInferenceProviderSpy).toHaveBeenCalledWith( - "nous-key-from-env", - expect.any(Function), - "NOUS_API_KEY", - ); + expect(harness.registerHermesInferenceProviderSpy).not.toHaveBeenCalled(); const output = [...harness.logSpy.mock.calls, ...harness.errorSpy.mock.calls] .flat() .map(String) .join("\n"); - expect(output).toContain( - "Hermes Provider is not registered in OpenShell; registering it from the configured exported API-key environment variable before rebuild.", - ); - expect(output).not.toContain("NOUS_API_KEY"); + expect(output).toContain("Hermes Provider is not registered in OpenShell"); expect(output).not.toContain("nous-key-from-env"); - expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); - expect(harness.registerHermesInferenceProviderSpy.mock.invocationCallOrder[0]!).toBeLessThan( - harness.backupSandboxStateSpy.mock.invocationCallOrder[0]!, - ); + expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); + expectNoSandboxDelete(harness.runOpenshellSpy); + expect(harness.onboardSpy).not.toHaveBeenCalled(); } finally { restoreEnv(); } diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts index 325c88acd23..20bc4d3bdb1 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts @@ -339,3 +339,64 @@ describe("checkRebuildGatewayCredentialReuseOrBail", () => { expect(diagnostics).not.toContain("secret-canary"); }); }); + +describe("native rebuild provider identity", () => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }; + it.each([false, true])( + "checks the recorded identity even when a host key is available: %s", + async (hostCredentialAvailable) => { + const read = vi.fn(async () => ({ + name: receipt.providerName, + type: receipt.profileId, + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { id: "replacement-id", resourceVersion: 1 }, + })); + await expect( + checkRebuildGatewayCredentialReuseOrBail( + "alpha", + config({ provider: "openai-api", nativeHostedProviderAttachment: receipt }), + hostCredentialAvailable, + vi.fn(), + throwingBail, + { + readGatewayProviderMetadata: read, + readRecordedProviderEndpoints: vi.fn(() => []), + }, + ), + ).rejects.toThrow("identity changed"); + expect(read).toHaveBeenCalledWith(receipt.providerName); + }, + ); + it("reuses the exact native provider without reading a host credential", async () => { + const read = vi.fn(async () => ({ + name: receipt.providerName, + type: receipt.profileId, + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { id: receipt.providerId, resourceVersion: 1 }, + })); + await expect( + checkRebuildGatewayCredentialReuseOrBail( + "alpha", + config({ + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + nativeHostedProviderAttachment: receipt, + }), + false, + vi.fn(), + throwingBail, + { + readGatewayProviderMetadata: read, + readRecordedProviderEndpoints: vi.fn(() => []), + }, + ), + ).resolves.toBe(true); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.ts index ba24ff1fc91..788ccd9fc90 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.ts @@ -9,6 +9,8 @@ import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider import type { RunProviderCommand } from "../../adapters/openshell/provider-adapter-cli"; import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-command"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { RD as _RD, R } from "../../cli/terminal-style"; import { hasBedrockRuntimeAwsAuthEnv, @@ -67,26 +69,45 @@ export async function inspectRebuildGatewayProviderRegistration( providerAdapter = rebuildProviderAdapter(runtimeSelection), credentialKey?: string | null, ): Promise { + const nativeProfile = nativeHostedProfile(provider); + const effectiveCredentialKey = nativeProfile + ? credentialKey + ? nativeProfile.credentialEnv + : null + : credentialKey; const result = await providerAdapter.getProvider({ - providerName: provider, + providerName: nativeHostedProfile(provider)?.providerName ?? provider, target: managedProviderGatewayTarget, - ...(credentialKey ? { includeCredentialExpirations: true } : {}), + ...(effectiveCredentialKey ? { includeCredentialExpirations: true } : {}), }); - const expiresAtMs = result.ok && credentialKey ? result.value.credentialExpiresAtMs : undefined; - const credentialExpiresAtMs = credentialKey ? expiresAtMs?.[credentialKey] : undefined; + const expiresAtMs = + result.ok && effectiveCredentialKey ? result.value.credentialExpiresAtMs : undefined; + const credentialExpiresAtMs = effectiveCredentialKey + ? expiresAtMs?.[effectiveCredentialKey] + : undefined; const credentialKeyMissing = Boolean( - result.ok && credentialKey && !result.value.credentialKeys.includes(credentialKey), + result.ok && + effectiveCredentialKey && + !result.value.credentialKeys.includes(effectiveCredentialKey), ); const registration = result.ok - ? credentialKey && expiresAtMs === undefined + ? nativeProfile && + (result.value.name !== nativeProfile.providerName || + result.value.type !== nativeProfile.profileId || + result.value.configKeys.length !== 0 || + result.value.credentialKeys.length !== 1 || + result.value.credentialKeys[0] !== nativeProfile.credentialEnv || + !result.value.revision?.id) ? "indeterminate" - : credentialKeyMissing - ? "credential_missing" - : credentialExpiresAtMs !== undefined && - credentialExpiresAtMs > 0 && - credentialExpiresAtMs <= Date.now() - ? "expired" - : "registered" + : effectiveCredentialKey && expiresAtMs === undefined + ? "indeterminate" + : credentialKeyMissing + ? "credential_missing" + : credentialExpiresAtMs !== undefined && + credentialExpiresAtMs > 0 && + credentialExpiresAtMs <= Date.now() + ? "expired" + : "registered" : result.error.kind === "command" && result.error.reason === "not_found" ? "missing" : "indeterminate"; @@ -108,7 +129,11 @@ export async function inspectRebuildGatewayProviderRegistration( type GatewayCredentialReusePreflightDeps = { hasBedrockRuntimeAwsAuth?(): boolean; - readGatewayProviderMetadata(provider: string): Promise; + readGatewayProviderMetadata( + provider: string, + ): Promise< + (GatewayProviderMetadata & { revision?: { id: string; resourceVersion: number } | null }) | null + >; readRecordedProviderEndpoints(provider: string, excludeSandboxName: string): string[] | null; }; @@ -277,7 +302,7 @@ function defaultGatewayCredentialReusePreflightDeps(): GatewayCredentialReusePre return { readGatewayProviderMetadata: async (provider) => { const result = await providerAdapter.getProvider({ - providerName: provider, + providerName: nativeHostedProfile(provider)?.providerName ?? provider, target: managedProviderGatewayTarget, }); return result.ok ? result.value : null; @@ -306,6 +331,28 @@ export async function checkRebuildGatewayCredentialReuseOrBail( bail: (msg: string, code?: number) => never, deps: GatewayCredentialReusePreflightDeps = defaultGatewayCredentialReusePreflightDeps(), ): Promise { + const native = nativeHostedProfile(config.provider); + if (native) { + const expected = normalizeNativeHostedProviderAttachment(config.nativeHostedProviderAttachment); + const observed = await deps.readGatewayProviderMetadata(native.providerName); + if ( + !expected || + expected.providerName !== native.providerName || + expected.profileId !== native.profileId || + !observed || + observed.name !== native.providerName || + observed.type !== native.profileId || + observed.revision?.id !== expected.providerId || + observed.configKeys.length !== 0 || + observed.credentialKeys.length !== 1 || + observed.credentialKeys[0] !== native.credentialEnv + ) { + bail("Native inference provider identity changed or is missing; sandbox is untouched."); + return false; + } + log(`Preflight native inference: verified recorded provider '${native.providerName}'`); + return true; + } if (hostCredentialAvailable || !config.provider || !config.credentialEnv) return true; const isBedrockRuntime = config.provider === "compatible-anthropic-endpoint" && @@ -351,7 +398,9 @@ export async function checkRebuildGatewayCredentialReuseOrBail( recoveredPreferredInferenceApi: route?.preferredInferenceApi, expectedProviderType: remoteConfig.providerType, expectedCredentialEnv: config.credentialEnv, - gatewayProvider: await deps.readGatewayProviderMetadata(config.provider), + gatewayProvider: await deps.readGatewayProviderMetadata( + nativeHostedProfile(config.provider)?.providerName ?? config.provider, + ), endpointIdentity: endpointFlavor ? { flavor: endpointFlavor, diff --git a/src/lib/actions/sandbox/rebuild-resume-config.ts b/src/lib/actions/sandbox/rebuild-resume-config.ts index 75a05007967..a20ec9e8964 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.ts @@ -42,6 +42,7 @@ const hermesProviderAuth = require("../../hermes-provider-auth") as { * from ambient selection env. */ export interface RebuildResumeConfig { + readonly nativeHostedProviderAttachment?: import("../../inference/native-hosted").NativeHostedProviderAttachment; readonly agent: string | null; readonly provider: string; readonly model: string; @@ -251,7 +252,16 @@ export function prepareRebuildResumeConfig( compatibleEndpointReasoningEffort, pinEndpoint: rebuildEndpoint.known || explicitTargetEndpoint !== null, endpointUrl, - registryInferenceRoute, + registryInferenceRoute: + registryInferenceRoute && sb.nativeHostedProviderAttachment + ? { + ...registryInferenceRoute, + nativeHostedProviderAttachment: sb.nativeHostedProviderAttachment, + } + : registryInferenceRoute, + ...(sb.nativeHostedProviderAttachment + ? { nativeHostedProviderAttachment: sb.nativeHostedProviderAttachment } + : {}), ambient, }; } diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index da4a9cd38fb..d235327d7c5 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -479,7 +479,7 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", preferredInferenceApi: "openai-completions", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index c4091e75fa0..c31c78520a8 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -19,7 +19,7 @@ import { retryUntilAsync } from "../../core/retry"; import { withStdoutRedirectedToStderr } from "../../cli/stdout-guard"; import { getLlamaCppRouteDetails, - normalizeNativeNvidiaProviderAttachment, + normalizeNativeHostedProviderAttachment, type GatewayInference, type LlamaCppRouteDetails, planInferenceRouteReconcile, @@ -557,16 +557,21 @@ export async function collectSandboxStatusSnapshot( opts.suppressInferenceProbe === true; let liveResult: OpenShellInferenceRouteResult | null = null; let gatewayName: string | null = null; + const nativeHosted = Boolean( + normalizeNativeHostedProviderAttachment(sb?.nativeHostedProviderAttachment), + ); if (lookup.state === "present") { try { gatewayName = resolveSandboxGatewayName(sb); const observer = opts.deps?.inferenceRouteObserver ?? createCliOpenShellInferenceRouteObserver(captureOpenshellForStatus); - liveResult = await observer.observeInferenceRoute({ - target: { kind: "named", gatewayName }, - timeoutMs: getStatusProbeTimeoutMs(), - }); + if (!nativeHosted) { + liveResult = await observer.observeInferenceRoute({ + target: { kind: "named", gatewayName }, + timeoutMs: getStatusProbeTimeoutMs(), + }); + } } catch { // Invalid persisted gateway bindings and failed reads stay fail-closed: // never substitute the selected/default gateway's inference route. @@ -604,11 +609,8 @@ export async function collectSandboxStatusSnapshot( // as drift instead of being mislabeled as this sandbox's configuration. const currentModel = sb ? sb.model || "unknown" : (live && live.model) || "unknown"; const currentProvider = sb ? sb.provider || "unknown" : (live && live.provider) || "unknown"; - const nativeNvidia = Boolean( - normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), - ); const routeDriftPlan = - !nativeNvidia && sb && sb.provider && sb.model + !nativeHosted && sb && sb.provider && sb.model ? planInferenceRouteReconcile(live, { provider: sb.provider, model: sb.model }) : null; const routeDrift = @@ -642,8 +644,8 @@ export async function collectSandboxStatusSnapshot( providerHealth = maybeGetSandboxStatusInferenceHealth( suppressInferenceProbe, lookup.state === "present", - nativeNvidia ? currentProvider : (live && live.provider) || currentProvider, - nativeNvidia ? currentModel : (live && live.model) || currentModel, + nativeHosted ? currentProvider : (live && live.provider) || currentProvider, + nativeHosted ? currentModel : (live && live.model) || currentModel, opts.deps?.probeProviderHealthImpl, sb?.endpointUrl, ); @@ -666,7 +668,7 @@ export async function collectSandboxStatusSnapshot( // a live model with a recorded provider and request a route neither one // describes. const invocationRoute = - !nativeNvidia && live?.provider && live.model + !nativeHosted && live?.provider && live.model ? { provider: live.provider, model: live.model, @@ -693,13 +695,13 @@ export async function collectSandboxStatusSnapshot( opts.deps?.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth; await retryUntilAsync( async () => { - gatewayChain = nativeNvidia + gatewayChain = nativeHosted ? null : gatewayName ? await probe(sandboxName, { gatewayName }) : null; invocation = - (nativeNvidia || gatewayChain?.ok) && canProbeInvocation + (nativeHosted || gatewayChain?.ok) && canProbeInvocation ? await runSandboxInferenceInvocationProbe( { sandboxName, @@ -708,7 +710,7 @@ export async function collectSandboxStatusSnapshot( provider: invocationProvider, model: invocationModel, preferredInferenceApi: invocationRoute.preferredInferenceApi, - ...(nativeNvidia ? { nativeProvider: true } : {}), + ...(nativeHosted ? { nativeProvider: true } : {}), }, opts.deps?.probeSandboxInferenceInvocationImpl, (error) => @@ -722,7 +724,7 @@ export async function collectSandboxStatusSnapshot( }, { accept: ({ gatewayChain: chain, invocation: result }) => { - if (nativeNvidia) { + if (nativeHosted) { return result?.ok === true || !isTransientInferenceInvocationFailure(result); } if (chain?.ok && (!canProbeInvocation || result?.ok)) return true; @@ -759,7 +761,7 @@ export async function collectSandboxStatusSnapshot( inferenceHealth = buildSandboxInferenceRouteHealth(gatewayChain, providerHealth, invocation, { agentName: sb?.agent ?? null, provider: invocationRoute.provider ?? null, - nativeNvidia, + nativeHosted, }); } // Classify once per snapshot so every renderer observes the same receipt state. diff --git a/src/lib/adapters/config/live-export-source-test-fixture.ts b/src/lib/adapters/config/live-export-source-test-fixture.ts index e5fc21e505e..337c2efd87c 100644 --- a/src/lib/adapters/config/live-export-source-test-fixture.ts +++ b/src/lib/adapters/config/live-export-source-test-fixture.ts @@ -244,7 +244,7 @@ export function openAiProviderProfile() { }; } -export function nativeNvidiaProvider() { +export function nativeHostedProvider() { return { ...provider().provider, type: "nvidia", profileWorkspace: "", config: {} }; } diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index 82d810455b0..acf5a3b05bd 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -36,7 +36,7 @@ import { inventory, provider, configuration, - nativeNvidiaProvider, + nativeHostedProvider, telemetryEntry, dashboardSource, braveProvider, @@ -74,9 +74,9 @@ function mockBraveLiveSource() { return search; } -function mockNativeNvidiaSource() { +function mockNativeHostedSource() { mockSupportedLiveSource(); - raw.getProvider.mockResolvedValue({ provider: nativeNvidiaProvider() }); + raw.getProvider.mockResolvedValue({ provider: nativeHostedProvider() }); raw.getProviderProfile.mockResolvedValue({ profile: { id: "nvidia", @@ -285,6 +285,24 @@ describe("live export snapshot reader", () => { expect(JSON.stringify(result)).not.toContain(readFailureCanary); }); + it("refuses native attachment export without consulting the shared gateway route", async () => { + mockSupportedLiveSource(3, 3, { + ...entry, + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "native-openai-id", + }, + }); + await expect(createLiveExportSnapshotReader().read("alpha")).resolves.toEqual({ + kind: "read-failed", + stage: "inference-route", + }); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + expect(raw.getProvider).not.toHaveBeenCalled(); + }); + it("does not fall back to the selected gateway after an inference read failure", async () => { mockSupportedLiveSource(); vi.mocked(captureSanitizedResolvedOpenshell).mockReturnValue({ @@ -458,7 +476,7 @@ describe("live export snapshot reader", () => { }); it("exports canonical YAML for the native NVIDIA hosted provider (#11154)", async () => { - mockNativeNvidiaSource(); + mockNativeHostedSource(); const writeStdout = vi.fn(async (_yaml: string) => {}); const publish = vi.fn(); const result = await runConfigExport( @@ -502,9 +520,9 @@ describe("live export snapshot reader", () => { { label: "missing credentials", providerChange: { credentials: {} } }, { label: "unverified profile scope", providerChange: { profileWorkspace: "default" } }, ])("rejects native NVIDIA $label without publishing YAML", async ({ providerChange }) => { - mockNativeNvidiaSource(); + mockNativeHostedSource(); raw.getProvider.mockResolvedValue({ - provider: { ...nativeNvidiaProvider(), ...providerChange }, + provider: { ...nativeHostedProvider(), ...providerChange }, }); const writeStdout = vi.fn(); const publish = vi.fn(); @@ -528,7 +546,7 @@ describe("live export snapshot reader", () => { }); it("rejects NVIDIA endpoint drift between the registry and builtin profile", async () => { - mockNativeNvidiaSource(); + mockNativeHostedSource(); vi.mocked(loadRegistry).mockReturnValue({ sandboxes: { alpha: { ...entry, endpointUrl: "https://different.example/v1" } }, defaultSandbox: null, @@ -546,11 +564,11 @@ describe("live export snapshot reader", () => { }); it("rejects a native NVIDIA provider that changes during both observations", async () => { - mockNativeNvidiaSource(); + mockNativeHostedSource(); let revision = 0; raw.getProvider.mockImplementation(async () => ({ provider: { - ...nativeNvidiaProvider(), + ...nativeHostedProvider(), metadata: { ...provider().provider.metadata, resourceVersion: BigInt(++revision) }, }, })); diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index d6f0a3aa725..6e49602eeab 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -98,6 +98,11 @@ function sandboxIdentity(row: Sandbox): ObservedExportSandboxIdentity { } async function readInferenceRoute(entry: Readonly, gatewayName: string) { + // The v1 exporter cannot represent workspace profile attachments yet. + // Never substitute the unrelated gateway route for a native selection. + if (entry.nativeHostedProviderAttachment) { + throw new Error("Native provider attachment export is not supported."); + } const selected = getSandboxEntryInference(entry); const observer = createSynchronousCliOpenShellInferenceRouteObserver((args, options) => captureSanitizedResolvedOpenshell(args, { diff --git a/src/lib/adapters/openshell/providers.test.ts b/src/lib/adapters/openshell/providers.test.ts index ab590b2fbd8..a273c63df23 100644 --- a/src/lib/adapters/openshell/providers.test.ts +++ b/src/lib/adapters/openshell/providers.test.ts @@ -66,7 +66,7 @@ function fixture() { return { raw, connect }; } -function nativeNvidiaFixture() { +function nativeHostedFixture() { const fixtureValue = fixture(); const profile = { id: "nvidia", @@ -366,7 +366,7 @@ describe("OpenShell provider evidence", () => { }); it("verifies the native NVIDIA endpoint through the named gateway profile", async () => { - const { connect, raw } = nativeNvidiaFixture(); + const { connect, raw } = nativeHostedFixture(); const input = request(); const result = await createProviders(connect).get(input); expect(result).toMatchObject({ @@ -407,7 +407,7 @@ describe("OpenShell provider evidence", () => { }, }, ])("rejects NVIDIA profile evidence with $label", async ({ change }) => { - const { connect, raw, profile } = nativeNvidiaFixture(); + const { connect, raw, profile } = nativeHostedFixture(); raw.getProviderProfile.mockResolvedValue({ profile: { ...profile, ...change } }); await expect(createProviders(connect).get(request())).rejects.toMatchObject({ kind: "schema", @@ -421,7 +421,7 @@ describe("OpenShell provider evidence", () => { { profileWorkspace: "", config: { NVIDIA_BASE_URL: "https://different.example/v1" } }, { profileWorkspace: "", config: { UNUSED: canary } }, ])("does not infer a builtin endpoint for NVIDIA overrides %#", async (change) => { - const { connect, raw } = nativeNvidiaFixture(); + const { connect, raw } = nativeHostedFixture(); raw.getProvider.mockResolvedValue({ provider: { ...provider().provider, type: "nvidia", ...change }, }); @@ -437,7 +437,7 @@ describe("OpenShell provider evidence", () => { { code: 4, kind: "timeout" }, { code: 14, kind: "transport" }, ])("stops when NVIDIA profile verification fails with status $code", async ({ code, kind }) => { - const { connect, raw } = nativeNvidiaFixture(); + const { connect, raw } = nativeHostedFixture(); raw.getProviderProfile.mockRejectedValue({ code, message: canary }); await expect(createProviders(connect).get(request())).rejects.toMatchObject({ kind, diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index aedece71d7e..6540b29d7ba 100644 --- a/src/lib/domain/config/export-evidence.ts +++ b/src/lib/domain/config/export-evidence.ts @@ -71,6 +71,7 @@ export const EXPORT_REGISTRY_EVIDENCE_KEYS = [ "messaging", "model", "name", + "nativeHostedProviderAttachment", "nimContainer", "observabilityEnabled", "openshellDriver", diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 01d13ea074f..72ccfb8fc7a 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -5,6 +5,7 @@ import type * as TypeBoxValueModule from "typebox/value" with { "resolution-mode import { isDeepStrictEqual } from "node:util"; import { cloneAndDeepFreeze } from "../../core/immutable"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { normalizeInferenceSelection } from "../../inference/selection"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; import type { ManagedStartupProfile } from "../../onboard/managed-startup/profile"; @@ -523,6 +524,24 @@ function deepAgentsObservability( return agent === "langchain-deepagents-code" ? false : null; } +function preserveLegacyExportEndpoint( + entry: ObservedExportRegistry, + inference: ReturnType, +): void { + // Export verifies the retained image contract; older hosted sandboxes were + // built for the shared route and do not acquire native access by inspection. + if ( + !entry.nativeHostedProviderAttachment && + entry.provider !== "nvidia-prod" && + nativeHostedProfile(entry.provider) + ) { + inference.inferenceBaseUrl = + inference.inferenceApi === "anthropic-messages" + ? "https://inference.local" + : "https://inference.local/v1"; + } +} + function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedStartupProfile { if (!isSupportedExportAgent(entry.agent)) { throw new Error("The agent is unsupported."); @@ -543,6 +562,7 @@ function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedSt selected.model, selected.preferredInferenceApi, ); + preserveLegacyExportEndpoint(entry, inference); const projection = EXPORT_AGENT_PROFILE_PROJECTIONS[agent](inference); return buildManagedStartupProfile({ agent, diff --git a/src/lib/hermes-managed-route.ts b/src/lib/hermes-managed-route.ts index 30db5326d5c..f8f1025551c 100644 --- a/src/lib/hermes-managed-route.ts +++ b/src/lib/hermes-managed-route.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { OPENROUTER_DEFAULT_HEADERS } from "./inference/native-hosted/openrouter-headers.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"; @@ -14,6 +16,7 @@ type HermesManagedProvider = { default_model?: string; transport?: string; api_mode?: string; + extra_headers?: Record; }; export type HermesManagedRouting = { @@ -113,6 +116,10 @@ export function applyHermesManagedRoute( discover_models: true, }; if (apiMode) customProvider.api_mode = apiMode; + if (route.upstreamProvider === "openrouter-api") { + providerConfig.extra_headers = Object.fromEntries(OPENROUTER_DEFAULT_HEADERS); + customProvider.extra_headers = Object.fromEntries(OPENROUTER_DEFAULT_HEADERS); + } const providers = isObjectRecord(config.providers) ? { ...config.providers } : {}; if (previousProviderKey && previousProviderKey !== providerKey) { diff --git a/src/lib/hermes-provider-auth.test.ts b/src/lib/hermes-provider-auth.test.ts index 53afa3a0a52..5a248929f1e 100644 --- a/src/lib/hermes-provider-auth.test.ts +++ b/src/lib/hermes-provider-auth.test.ts @@ -6,6 +6,7 @@ import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; +import { createNativeProviderCommandRuntime } from "../../test/support/native-provider-command-runtime"; import { afterEach, describe, expect, it, vi } from "vitest"; const require = createRequire(import.meta.url); @@ -38,16 +39,22 @@ afterEach(() => { clearSourceModule(SOURCE_BROKER); }); +const NATIVE_PROVIDER = "nemoclaw-hermes-provider-v1"; +const NATIVE_PROFILE = "nemoclaw-hermes-inference-v1"; + +function nativeRunner(initiallyExists = false) { + const runtime = createNativeProviderCommandRuntime("hermes-provider", initiallyExists); + return vi.fn( + (args: string[], _opts: { env?: Record } = {}) => + runtime.run(args) ?? { status: 0, stdout: "", stderr: "" }, + ); +} + describe("Hermes provider OpenShell credential handoff", () => { it("inspects exact OpenShell credential key bindings without exposing values", async () => { const auth = loadAuth(); - const binding = await auth.inspectHermesProviderBinding(() => ({ - status: 0, - stdout: - "Name: hermes-provider\nType: openai\nCredential keys: NOUS_API_KEY\nConfig keys: OPENAI_BASE_URL\n", - stderr: "", - })); - expect(binding).toEqual({ exists: true, credentialKeys: ["NOUS_API_KEY"] }); + const binding = await auth.inspectHermesProviderBinding(nativeRunner(true)); + expect(binding).toEqual({ exists: true, credentialKeys: ["OPENAI_API_KEY"] }); }); it("fails closed when OpenShell provider details omit credential metadata", async () => { @@ -57,26 +64,49 @@ describe("Hermes provider OpenShell credential handoff", () => { ).resolves.toEqual({ exists: true, credentialKeys: null }); }); - it("registers the OpenAI provider without a compatibility-profile mutation (#11229)", async () => { + it("registers only the owned native profile with a protected credential", async () => { const auth = loadAuth(); - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider not found" }) - .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); + const run = nativeRunner(); + await auth.registerHermesInferenceProvider("nous-key", run); + expect(run.mock.calls.some(([args]) => args.includes("profile"))).toBe(true); + const create = run.mock.calls.find(([args]) => args[1] === "create")!; + expect(create[0]).toEqual( + expect.arrayContaining([NATIVE_PROVIDER, NATIVE_PROFILE, "OPENAI_API_KEY"]), + ); + expect(create[1]?.env?.OPENAI_API_KEY).toBe("nous-key"); + expect(create[0].join(" ")).not.toContain("nous-key"); + }); - await auth.registerHermesInferenceProvider("nous-key", runOpenshell); + it("rejects a noncanonical endpoint before any OpenShell mutation", async () => { + const run = nativeRunner(); + await expect( + loadAuth().registerHermesInferenceProvider( + "key", + run, + "OPENAI_API_KEY", + "https://other.example/v1", + ), + ).rejects.toThrow("noncanonical"); + expect(run).not.toHaveBeenCalled(); + }); - expect(runOpenshell.mock.calls.map(([args]) => args)).toEqual([ - ["provider", "get", "hermes-provider"], - expect.arrayContaining([ - "provider", - "create", - "--name", - "hermes-provider", - "--type", - "openai", - ]), - ]); + it("refuses credential rotation when the recorded provider identity changed", async () => { + const run = nativeRunner(true); + await expect( + loadAuth().ensureHermesProviderApiKeyCredentials("alpha", { + apiKey: "new-key", + runOpenshell: run, + expected: { + schemaVersion: 1, + profileId: NATIVE_PROFILE, + providerName: NATIVE_PROVIDER, + providerId: "replaced-id", + }, + }), + ).rejects.toThrow("changed identity"); + expect(run.mock.calls.some(([args]) => args[1] === "create" || args[1] === "update")).toBe( + false, + ); }); it("registers Nous API-key inference in OpenShell without host-side persistence", async () => { @@ -86,25 +116,20 @@ describe("Hermes provider OpenShell credential handoff", () => { process.env.HOME = tmp; const auth = loadAuth(); const calls: Array<{ args: string[]; env?: Record }> = []; + const run = nativeRunner(); const state = await auth.ensureHermesProviderApiKeyCredentials("my-assistant", { apiKey: "nous-key-1", runOpenshell: (args: string[], opts: { env?: Record } = {}) => { calls.push({ args, env: opts.env }); - return args[1] === "get" - ? { - status: 1, - stdout: "", - stderr: "provider 'hermes-provider' not found", - } - : { status: 0, stdout: "", stderr: "" }; + return run(args, opts); }, }); expect(state.auth_method).toBe("api_key"); expect(state.credential_env).toBe("NOUS_API_KEY"); - expect(calls.some((call) => call.args.includes("hermes-provider"))).toBe(true); - expect(calls.some((call) => call.args.includes("NOUS_API_KEY"))).toBe(true); - expect(calls.some((call) => call.env?.NOUS_API_KEY === "nous-key-1")).toBe(true); + expect(calls.some((call) => call.args.includes(NATIVE_PROVIDER))).toBe(true); + expect(calls.some((call) => call.args.includes("OPENAI_API_KEY"))).toBe(true); + expect(calls.some((call) => call.env?.OPENAI_API_KEY === "nous-key-1")).toBe(true); expect(fs.existsSync(path.join(tmp, ".nemoclaw", "hermes-oauth"))).toBe(false); } finally { if (originalHome === undefined) delete process.env.HOME; @@ -121,6 +146,7 @@ describe("Hermes provider OpenShell credential handoff", () => { const auth = loadAuth(); const fetchCalls: Array<{ url: string; auth: string | null; body: string }> = []; const providerCalls: Array<{ args: string[]; env?: Record }> = []; + const run = nativeRunner(); const state = await auth.ensureHermesProviderOAuthCredentials("my-assistant", { allowInteractiveLogin: true, fetch: (async (url, init) => { @@ -158,7 +184,7 @@ describe("Hermes provider OpenShell credential handoff", () => { api_key: "agent-key-1", key_id: "agent-key-id", expires_in: 1800, - inference_base_url: "https://staging.nous.example/v1", + inference_base_url: "https://inference-api.nousresearch.com/v1", }), { status: 200, headers: { "Content-Type": "application/json" } }, ); @@ -167,26 +193,20 @@ describe("Hermes provider OpenShell credential handoff", () => { noBrowser: true, runOpenshell: (args: string[], opts: { env?: Record } = {}) => { providerCalls.push({ args, env: opts.env }); - return args[1] === "get" - ? { - status: 1, - stdout: "", - stderr: "provider 'hermes-provider' not found", - } - : { status: 0, stdout: "", stderr: "" }; + return run(args, opts); }, }); expect(state.auth_method).toBe("oauth"); expect(state.credential_env).toBe("OPENAI_API_KEY"); - expect(state.inference_base_url).toBe("https://staging.nous.example/v1"); + expect(state.inference_base_url).toBe("https://inference-api.nousresearch.com/v1"); expect(fetchCalls.some((call) => call.auth === "Bearer access-2")).toBe(true); expect(providerCalls.some((call) => call.env?.OPENAI_API_KEY === "agent-key-1")).toBe(true); expect( providerCalls.some((call) => - call.args.includes("OPENAI_BASE_URL=https://staging.nous.example/v1"), + call.args.includes("OPENAI_BASE_URL=https://inference-api.nousresearch.com/v1"), ), - ).toBe(true); + ).toBe(false); expect(fs.existsSync(path.join(tmp, ".nemoclaw", "hermes-oauth"))).toBe(false); } finally { if (originalHome === undefined) delete process.env.HOME; @@ -215,6 +235,7 @@ describe("Hermes provider OpenShell credential handoff", () => { }, }); const providerCalls: Array<{ args: string[]; env?: Record }> = []; + const run = nativeRunner(); const state = await auth.ensureHermesProviderOAuthCredentials("my-assistant", { allowInteractiveLogin: true, fetch: (async (url, init) => { @@ -256,13 +277,7 @@ describe("Hermes provider OpenShell credential handoff", () => { noBrowser: true, runOpenshell: (args: string[], opts: { env?: Record } = {}) => { providerCalls.push({ args, env: opts.env }); - return args[1] === "get" - ? { - status: 1, - stdout: "", - stderr: "provider 'hermes-provider' not found", - } - : { status: 0, stdout: "", stderr: "" }; + return run(args, opts); }, toolGatewayPresets: ["nous-web", "nous-audio"], }); diff --git a/src/lib/hermes-provider-auth.ts b/src/lib/hermes-provider-auth.ts index c59833a7dd8..caa68b72143 100644 --- a/src/lib/hermes-provider-auth.ts +++ b/src/lib/hermes-provider-auth.ts @@ -1,6 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + ensureNativeHostedProvider, + type NativeHostedProviderAttachment, +} from "./inference/native-hosted"; +import { nativeHostedProfile } from "./inference/native-hosted/profiles"; /** * Hermes Provider credential orchestration. * @@ -88,7 +93,10 @@ function agentKeyExpiresAt(minted: oauth.AgentKeyResponse): string | null { } export function isHermesProviderRegistered(runOpenshell: RunOpenshell): Promise { - return onboardProviders.providerExistsInGateway(HERMES_PROVIDER_NAME, runOpenshell); + return onboardProviders.providerExistsInGateway( + nativeHostedProfile(HERMES_PROVIDER_NAME)!.providerName, + runOpenshell, + ); } export type HermesProviderBinding = { @@ -101,7 +109,7 @@ export async function inspectHermesProviderBinding( ): Promise { const result = await createCliOpenShellProviderAdapter({ run: runOpenshell }).getProvider({ target: { kind: "selected" }, - providerName: HERMES_PROVIDER_NAME, + providerName: nativeHostedProfile(HERMES_PROVIDER_NAME)!.providerName, }); if (!result.ok) { return result.error.kind === "command" && result.error.reason === "not_found" @@ -119,22 +127,31 @@ export async function registerHermesInferenceProvider( runOpenshell: RunOpenshell, credentialEnv = HERMES_INFERENCE_CREDENTIAL_ENV, baseUrl = oauth.DEFAULT_INFERENCE_BASE_URL, + expected?: NativeHostedProviderAttachment, ): Promise { const normalizedApiKey = nonEmptyString(apiKey); if (!normalizedApiKey) { throw new Error("Hermes Provider credential is empty"); } - const result = await onboardProviders.upsertProvider( - HERMES_PROVIDER_NAME, - "openai", - credentialEnv, - baseUrl, - { [credentialEnv]: normalizedApiKey }, - runOpenshell, - ); - if (!result.ok) { - throw new Error(result.message || `failed to upsert provider '${HERMES_PROVIDER_NAME}'`); + const profile = nativeHostedProfile(HERMES_PROVIDER_NAME)!; + if (baseUrl.replace(/\/+$/u, "") !== profile.endpoint) { + throw new Error( + "Hermes Provider returned a noncanonical inference endpoint; fixed native profiles cannot be repointed.", + ); + } + if ( + credentialEnv !== HERMES_INFERENCE_CREDENTIAL_ENV && + credentialEnv !== HERMES_NOUS_API_KEY_CREDENTIAL_ENV + ) { + throw new Error("Unsupported Hermes Provider credential binding"); } + await ensureNativeHostedProvider({ + adapter: createCliOpenShellProviderAdapter({ run: runOpenshell }), + target: { kind: "selected" }, + profile, + credentialValue: normalizedApiKey, + ...(expected ? { expected } : {}), + }); } export async function ensureHermesProviderOAuthCredentials( @@ -145,6 +162,7 @@ export async function ensureHermesProviderOAuthCredentials( log = console.error, fetch = undefined, noBrowser = false, + expected, baseUrl = oauth.DEFAULT_INFERENCE_BASE_URL, toolGatewayPresets = [], }: { @@ -154,6 +172,7 @@ export async function ensureHermesProviderOAuthCredentials( fetch?: typeof globalThis.fetch; noBrowser?: boolean; baseUrl?: string; + expected?: NativeHostedProviderAttachment; toolGatewayPresets?: string[]; } = {}, ): Promise { @@ -175,6 +194,7 @@ export async function ensureHermesProviderOAuthCredentials( runOpenshell, HERMES_INFERENCE_CREDENTIAL_ENV, inferenceBaseUrl, + expected, ); if (Array.isArray(toolGatewayPresets) && toolGatewayPresets.length > 0) { const hermesToolGateway = getHermesToolGatewayBroker(); @@ -201,11 +221,13 @@ export async function ensureHermesProviderApiKeyCredentials( { apiKey = null, runOpenshell = null, + expected, baseUrl = oauth.DEFAULT_INFERENCE_BASE_URL, }: { apiKey?: string | null; runOpenshell?: RunOpenshell | null; baseUrl?: string; + expected?: NativeHostedProviderAttachment; } = {}, ): Promise { if (!runOpenshell) { @@ -219,6 +241,7 @@ export async function ensureHermesProviderApiKeyCredentials( runOpenshell, HERMES_NOUS_API_KEY_CREDENTIAL_ENV, baseUrl, + expected, ); return { auth_method: "api_key", diff --git a/src/lib/inference/README.md b/src/lib/inference/README.md index e4e17051f06..d8189bb5e68 100644 --- a/src/lib/inference/README.md +++ b/src/lib/inference/README.md @@ -25,6 +25,31 @@ onboard-probes.ts onboarding-time inference validation probes Longer term, pure inference decisions should move under `src/lib/domain/inference/**`, and HTTP/process boundaries should move under `src/lib/adapters/**`. +## Native hosted inference + +`native-hosted/profiles.ts` maps fixed hosted selections to checked-in OpenShell provider profiles. +The supported selections are NVIDIA, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider. +Each profile restricts the upstream hostname, TLS port, request paths, and agent executables. +Credential values remain in OpenShell. Sandbox configuration contains only a placeholder credential. + +`native-hosted/index.ts` owns profile import, provider identity checks, attachment, and confirmed removal. +The registry records the selected attachment in `nativeHostedProviderAttachment`. +The persistence boundary also reads Slice 1's `nativeNvidiaProviderAttachment` field without changing its provider identity. +Selection does not update the shared `inference.local` route. +A switch retains `pendingNativeHostedProviderDetach` until OpenShell confirms removal of the previous attachment. +Retries complete that cleanup before applying another selection. +Existing beta sandboxes without an attachment receipt require recreation. +Custom endpoints and local providers retain their existing routing behavior. +V1alpha1 configuration export does not yet represent native profile attachments. +Native sandboxes require an exporter follow-up; exporting an older shared-route sandbox +continues to verify its original image endpoint without implicitly migrating it. + +Agent configuration preserves the provider's API protocol and native base URL. +OpenRouter attribution comes from `native-hosted/openrouter-headers.ts` and is configured in each supported agent. +Hermes authentication retains its logical OAuth or manual-key selection. +Both authentication methods store the protected native credential under `OPENAI_API_KEY` in OpenShell. +The host's unrelated OpenAI credential must never replace that Hermes credential during model selection. + ## Ollama export observations V1alpha1 configuration export currently refuses attached Ollama before publication. diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index f5b376f741f..32cc614172d 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -231,11 +231,11 @@ describe("inference selection config", () => { }); }); - it("maps the remaining hosted providers to the sandbox inference route", () => { + it("maps fixed hosted providers to their native endpoints", () => { // Full-object assertion for one hosted provider to catch structural regressions expect(getProviderSelectionConfig("openai-api", "gpt-5.4-mini")).toEqual({ endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: "https://api.openai.com/v1", ncpPartner: null, model: "gpt-5.4-mini", profile: DEFAULT_ROUTE_PROFILE, @@ -245,7 +245,7 @@ describe("inference selection config", () => { }); expect(getProviderSelectionConfig("openrouter-api", "moonshotai/kimi-k2.6")).toEqual({ endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: "https://openrouter.ai/api/v1", ncpPartner: null, model: "moonshotai/kimi-k2.6", profile: DEFAULT_ROUTE_PROFILE, @@ -271,7 +271,7 @@ describe("inference selection config", () => { }); expect(getProviderSelectionConfig("hermes-provider", "anthropic/claude-opus-4.7")).toEqual({ endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: "https://inference-api.nousresearch.com/v1", ncpPartner: null, model: "anthropic/claude-opus-4.7", profile: DEFAULT_ROUTE_PROFILE, @@ -436,7 +436,7 @@ describe("getSandboxInferenceConfig", () => { expect(getSandboxInferenceConfig("moonshotai/kimi-k2.6", "openrouter-api")).toEqual({ providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/moonshotai/kimi-k2.6`, - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: "https://openrouter.ai/api/v1", inferenceApi: "openai-completions", inferenceCompat: { supportsStore: false, @@ -501,7 +501,7 @@ describe("getSandboxInferenceConfig", () => { expect(getSandboxInferenceConfig("gemini-2.5-flash", "gemini-api")).toEqual({ providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/gemini-2.5-flash`, - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", inferenceApi: "openai-completions", inferenceCompat: { supportsStore: false, @@ -513,7 +513,7 @@ describe("getSandboxInferenceConfig", () => { expect(getSandboxInferenceConfig("gpt-5.4", "openai-api", "openai-responses")).toEqual({ providerKey: "openai", primaryModelRef: "openai/gpt-5.4", - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: "https://api.openai.com/v1", inferenceApi: "openai-responses", inferenceCompat: null, }); diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 6d23854fe75..ec174126b6e 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -13,6 +13,7 @@ import { LLAMA_CPP_HOST_OPENAI_BASE_URL, LLAMA_CPP_PROVIDER_NAME, } from "./llama-cpp/contract"; +import { nativeHostedProfile } from "./native-hosted/profiles"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; import type { ManagedLlamaCppOwnership } from "./llama-cpp/managed-state"; import { DEFAULT_OLLAMA_MODEL_TAG as DEFAULT_OLLAMA_MODEL } from "./ollama-model-registry"; @@ -20,18 +21,18 @@ import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "./ollama/contract"; import { OPENROUTER_CREDENTIAL_ENV, OPENROUTER_PROVIDER_NAME } from "./openrouter"; import { VLLM_LOCAL_CREDENTIAL_ENV } from "./serving/vllm-credential-contract"; -export { isSafeModelId }; +export { isSafeModelId, nativeHostedProfile }; +export { OPENROUTER_DEFAULT_HEADERS } from "./native-hosted/openrouter-headers"; export { OLLAMA_LOCAL_CREDENTIAL_ENV }; export { - detachNativeNvidiaProvider, - ensureNativeNvidiaProvider, - ensureNativeNvidiaProviderAttached, - isNativeNvidiaProvider, - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - normalizeNativeNvidiaProviderAttachment, -} from "./native-nvidia"; -export type { NativeNvidiaProviderAttachment } from "./native-nvidia"; + detachNativeHostedProvider, + ensureNativeHostedProvider, + ensureNativeHostedProviderAttached, + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, +} from "./native-hosted"; +export { NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; +export type { NativeHostedProviderAttachment } from "./native-hosted"; export const INFERENCE_ROUTE_URL = "https://inference.local/v1"; export const NOUS_RECOMMENDED_MODELS_URL = @@ -221,7 +222,7 @@ export function getProviderSelectionConfig( ): ProviderSelectionConfig | null { const base: Omit = { endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: nativeHostedProfile(provider)?.endpoint ?? INFERENCE_ROUTE_URL, ncpPartner: null, profile: DEFAULT_ROUTE_PROFILE, provider, @@ -416,6 +417,7 @@ export function getSandboxInferenceConfig( break; } + inferenceBaseUrl = nativeHostedProfile(provider)?.endpoint ?? inferenceBaseUrl; return { providerKey, primaryModelRef, inferenceBaseUrl, inferenceApi, inferenceCompat }; } diff --git a/src/lib/inference/gateway-route-compatibility.ts b/src/lib/inference/gateway-route-compatibility.ts index 9505a1764c4..91de8c2bc33 100644 --- a/src/lib/inference/gateway-route-compatibility.ts +++ b/src/lib/inference/gateway-route-compatibility.ts @@ -8,8 +8,8 @@ import type { SandboxEntry } from "../state/registry"; export { nativeInferenceProviderForSandbox, - normalizeNativeNvidiaProviderAttachment, -} from "./native-nvidia"; + normalizeNativeHostedProviderAttachment, +} from "./native-hosted"; export type GatewayInferenceRoute = Pick< SandboxEntry, diff --git a/src/lib/inference/native-hosted/index.test.ts b/src/lib/inference/native-hosted/index.test.ts new file mode 100644 index 00000000000..ec4a614d740 --- /dev/null +++ b/src/lib/inference/native-hosted/index.test.ts @@ -0,0 +1,404 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { describe, expect, it, vi } from "vitest"; + +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; +import { parseCheckedInProviderProfileContract } from "../../adapters/openshell/provider-profile"; +import { + ensureNativeHostedProvider, + ensureNativeHostedProviderAttached, + nativeHostedProviderProfilePath, + NativeHostedProviderError, + verifyNativeHostedProviderAttachment, +} from "./index"; + +import { NATIVE_HOSTED_PROFILES } from "./profiles"; + +const target = { kind: "named", gatewayName: "nemoclaw" } as const; + +describe.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"), +)("native $label OpenShell provider", (profile) => { + function metadata(overrides: Record = {}) { + return { + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 1 }, + ...overrides, + }; + } + + function adapter(overrides: Partial = {}): OpenShellProviderAdapter { + return { + importProviderProfile: vi.fn(() => ({ ok: true })), + getProvider: vi.fn(async () => ({ ok: true, value: metadata() })), + createProvider: vi.fn(async () => ({ ok: true })), + updateProvider: vi.fn(async () => ({ ok: true })), + listProviderAttachments: vi.fn(async () => ({ + ok: true, + value: { names: [profile.providerName] }, + })), + listProviders: vi.fn(), + inspectProviderProfile: vi.fn(), + deleteProvider: vi.fn(), + detachProvider: vi.fn(async () => ({ ok: true })), + attachProvider: vi.fn(async () => ({ ok: true })), + configureProviderRefresh: vi.fn(), + getProviderRefreshStatus: vi.fn(), + ...overrides, + } as OpenShellProviderAdapter; + } + + it("limits the profile to its fixed TLS endpoint and exact executable paths (#12589)", () => { + const source = fs.readFileSync(nativeHostedProviderProfilePath(profile), "utf8"); + const contract = parseCheckedInProviderProfileContract(source); + + expect(contract?.profileId).toBe(profile.profileId); + expect(contract?.boundary.endpoints).toHaveLength(1); + expect(contract?.boundary.endpoints[0]).toMatchObject({ + host: new URL(profile.endpoint).hostname, + port: 443, + enforcement: "enforce", + }); + expect(contract?.boundary.binaries).not.toEqual( + expect.arrayContaining([expect.stringMatching(/[?*]/u)]), + ); + }); + + it("refuses a receipt for another profile before mutation (#12589)", async () => { + const other = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.profileId !== profile.profileId, + )!; + const providerAdapter = adapter(); + const expected = { + schemaVersion: 1 as const, + profileId: other.profileId, + providerName: other.providerName, + providerId: "provider-id", + }; + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-secret", + expected, + }), + ).rejects.toThrow("does not match the selected profile"); + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected, + }), + ).rejects.toThrow("does not match the selected profile"); + expect(providerAdapter.importProviderProfile).not.toHaveBeenCalled(); + expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); + expect(providerAdapter.attachProvider).not.toHaveBeenCalled(); + }); + + it("refuses to attach a replacement provider before mutation (#12589)", async () => { + const providerAdapter = adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ revision: { id: "replacement", resourceVersion: 2 } }), + })), + listProviderAttachments: vi.fn( + async () => ({ ok: true, value: { names: [] } }), + ), + }); + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "original", + }, + }), + ).rejects.toThrow("changed identity before attachment"); + expect(providerAdapter.attachProvider).not.toHaveBeenCalled(); + expect(providerAdapter.detachProvider).not.toHaveBeenCalled(); + }); + + it("rejects provider replacement observed after credential update (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: metadata() }) + .mockResolvedValueOnce({ + ok: true, + value: metadata({ revision: { id: "replacement", resourceVersion: 1 } }), + }); + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ getProvider }), + target, + credentialValue: "opaque-test-secret", + }), + ).rejects.toThrow("changed identity during its credential update"); + }); + + it("creates the internal provider once and records its immutable identity (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: true, + })); + const providerAdapter = adapter({ getProvider, createProvider }); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + }), + ).resolves.toEqual({ + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }); + expect(createProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + name: profile.providerName, + type: profile.profileId, + credentials: [{ name: profile.credentialEnv, value: "opaque-test-secret" }], + config: [], + }), + ); + }); + + it("observes an ambiguous create result without issuing a second mutation (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: false, + error: { kind: "timeout", message: "timed out" }, + })); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ getProvider, createProvider }), + target, + credentialValue: "opaque-test-secret", + }), + ).resolves.toMatchObject({ providerId: "provider-id" }); + expect(createProvider).toHaveBeenCalledOnce(); + }); + + it("creates from an existing gateway credential when recreation has no local key (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: true, + })); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ getProvider, createProvider }), + target, + credentialValue: null, + reuseExistingCredential: true, + }), + ).resolves.toMatchObject({ providerId: "provider-id" }); + expect(createProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + name: profile.providerName, + credentials: [], + fromExisting: true, + }), + ); + }); + + it("refuses a replaced provider before rotating its credential (#12589)", async () => { + const updateProvider = vi.fn(); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ revision: { id: "replacement-id", resourceVersion: 1 } }), + })), + updateProvider, + }), + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "recorded-id", + }, + }), + ).rejects.toThrow(/changed identity.*No provider was changed/u); + expect(updateProvider).not.toHaveBeenCalled(); + }); + + it("refuses to replace a recorded provider that is missing (#12589)", async () => { + const createProvider = vi.fn(); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + })), + createProvider, + }), + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "recorded-id", + }, + }), + ).rejects.toThrow(/is missing.*No provider was changed/u); + expect(createProvider).not.toHaveBeenCalled(); + }); + + it("fails before provider mutation when the profile collides (#12589)", async () => { + const createProvider = vi.fn(); + const providerAdapter = adapter({ + importProviderProfile: vi.fn(() => ({ + ok: false, + error: { + kind: "command", + reason: "profile_incompatible", + message: "different profile", + }, + })), + createProvider, + }); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + }), + ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); + expect(createProvider).not.toHaveBeenCalled(); + }); + + it("requires the exact provider attachment before native inference is published (#12589)", async () => { + const providerAdapter = adapter({ + listProviderAttachments: vi.fn( + async () => ({ ok: true, value: { names: [] } }), + ), + }); + + await expect( + verifyNativeHostedProviderAttachment({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + }), + ).rejects.toThrow(NativeHostedProviderError); + await expect( + verifyNativeHostedProviderAttachment({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + }), + ).rejects.toThrow(/does not have its native .* inference provider attached/u); + }); + + it("removes a newly attached provider when attachment verification fails (#12589)", async () => { + const listProviderAttachments = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }); + const detachProvider = vi.fn(async () => ({ + ok: true, + value: { changed: true }, + })); + const providerAdapter = adapter({ listProviderAttachments, detachProvider }); + + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/does not have its native .* inference provider attached/u); + expect(detachProvider).toHaveBeenCalledExactlyOnceWith({ + target, + sandboxName: "alpha", + providerName: profile.providerName, + }); + }); + + it("preserves verification and cleanup failures after a new attachment (#12589)", async () => { + const listProviderAttachments = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ + ok: true, + value: { names: [profile.providerName] }, + }); + + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: adapter({ listProviderAttachments }), + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow( + /does not have its native .* inference provider attached[\s\S]*did not confirm removal/u, + ); + }); +}); diff --git a/src/lib/inference/native-hosted/index.ts b/src/lib/inference/native-hosted/index.ts new file mode 100644 index 00000000000..8942483c5e8 --- /dev/null +++ b/src/lib/inference/native-hosted/index.ts @@ -0,0 +1,407 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import type { + OpenShellGatewayTarget, + OpenShellProviderAdapter, + OpenShellProviderError, + OpenShellProviderMetadata, +} from "../../adapters/openshell/sandbox-observer"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; + +import { NATIVE_HOSTED_PROFILES, nativeHostedProfile, type NativeHostedProfile } from "./profiles"; + +export type NativeHostedProviderAttachment = Readonly<{ + schemaVersion: 1; + profileId: string; + providerName: string; + providerId: string; +}>; + +export class NativeHostedProviderError extends Error { + constructor(message: string) { + super(message); + this.name = "NativeHostedProviderError"; + } +} + +export function nativeHostedProviderProfilePath( + profile: NativeHostedProfile, + root = REPOSITORY_ROOT, +): string { + return path.join(root, "managed-inference", "provider-profiles", `${profile.profileId}.yaml`); +} + +export function isNativeHostedProvider(provider: string | null | undefined): boolean { + return nativeHostedProfile(provider) !== undefined; +} + +export function nativeInferenceProviderForSandbox( + provider: string | null | undefined, +): string | null { + const normalized = provider?.trim() || null; + return nativeHostedProfile(normalized)?.providerName ?? normalized; +} + +export function normalizeNativeHostedProviderAttachment( + value: unknown, +): NativeHostedProviderAttachment | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const receipt = value as Record; + const profile = NATIVE_HOSTED_PROFILES.find( + (entry) => entry.profileId === receipt.profileId && entry.providerName === receipt.providerName, + ); + if (!profile) return undefined; + if ( + receipt.schemaVersion !== 1 || + receipt.profileId !== profile.profileId || + receipt.providerName !== profile.providerName || + typeof receipt.providerId !== "string" || + !receipt.providerId.trim() + ) { + return undefined; + } + return { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: receipt.providerId, + }; +} + +function assertExpectedProfile( + profile: NativeHostedProfile, + expected?: NativeHostedProviderAttachment, +): void { + if ( + expected && + (expected.profileId !== profile.profileId || expected.providerName !== profile.providerName) + ) { + throw new NativeHostedProviderError( + "Recorded native provider identity does not match the selected profile. No provider was changed.", + ); + } +} + +function providerErrorDetail(error: OpenShellProviderError): string { + return error.message.trim() || "OpenShell did not provide a diagnostic."; +} + +function exactNativeProvider( + metadata: OpenShellProviderMetadata, + profile: NativeHostedProfile, +): boolean { + return ( + metadata.name === profile.providerName && + metadata.type === profile.profileId && + metadata.configKeys.length === 0 && + metadata.credentialKeys.length === 1 && + metadata.credentialKeys[0] === profile.credentialEnv && + Boolean(metadata.revision?.id) + ); +} + +function attachmentFromMetadata( + metadata: OpenShellProviderMetadata, + profile: NativeHostedProfile, +): NativeHostedProviderAttachment { + if (!exactNativeProvider(metadata, profile) || !metadata.revision) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' does not match the NemoClaw-owned ${profile.label} inference boundary. No provider was changed.`, + ); + } + return { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: metadata.revision.id, + }; +} + +async function inspectNativeProvider( + adapter: OpenShellProviderAdapter, + target: OpenShellGatewayTarget, + profile: NativeHostedProfile, +): Promise { + const observed = await adapter.getProvider({ + target, + providerName: profile.providerName, + }); + if (observed.ok) return observed.value; + if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; + throw new NativeHostedProviderError( + `Could not inspect OpenShell provider '${profile.providerName}': ${providerErrorDetail(observed.error)}`, + ); +} + +function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { + return ( + error.kind === "timeout" || + (error.kind === "transport" && + (error.reason === "connection_loss" || error.reason === "unreachable")) || + (error.kind === "command" && error.reason === "uncertain") + ); +} + +/** Ensure the least-privilege hosted profile and provider without retrying an ambiguous mutation. */ +export async function ensureNativeHostedProvider(input: { + profile: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + credentialValue: string | null; + reuseExistingCredential?: boolean; + expected?: NativeHostedProviderAttachment; + profilePath?: string; +}): Promise { + const { adapter, target, profile } = input; + assertExpectedProfile(profile, input.expected); + const imported = await adapter.importProviderProfile({ + target, + profilePath: input.profilePath ?? nativeHostedProviderProfilePath(profile), + }); + if (!imported.ok) { + const collision = + imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; + throw new NativeHostedProviderError( + collision + ? `OpenShell provider profile '${profile.profileId}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` + : `Could not prepare OpenShell provider profile '${profile.profileId}': ${providerErrorDetail(imported.error)}`, + ); + } + + const before = await inspectNativeProvider(adapter, target, profile); + if (before) { + const receipt = attachmentFromMetadata(before, profile); + if (input.expected && input.expected.providerId !== receipt.providerId) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity. Recreate the sandbox before using native ${profile.label} inference. No provider was changed.`, + ); + } + if (!input.credentialValue) return receipt; + const updated = await adapter.updateProvider({ + target, + providerName: profile.providerName, + credentials: [{ name: profile.credentialEnv, value: input.credentialValue }], + config: [], + }); + if (!updated.ok && !mutationOutcomeMayBeAmbiguous(updated.error)) { + throw new NativeHostedProviderError( + `Could not update OpenShell provider '${profile.providerName}': ${providerErrorDetail(updated.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target, profile); + if (!observed) { + throw new NativeHostedProviderError( + `OpenShell did not confirm provider '${profile.providerName}' after its credential update.`, + ); + } + const confirmed = attachmentFromMetadata(observed, profile); + if (confirmed.providerId !== receipt.providerId) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity during its credential update.`, + ); + } + return confirmed; + } + + if (input.expected) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' is missing. Recreate the sandbox before using native ${profile.label} inference. No provider was changed.`, + ); + } + + if (!input.credentialValue && !input.reuseExistingCredential) { + throw new NativeHostedProviderError( + `A host credential is required to create OpenShell provider '${profile.providerName}'.`, + ); + } + const created = await adapter.createProvider({ + target, + name: profile.providerName, + type: profile.profileId, + credentials: input.credentialValue + ? [{ name: profile.credentialEnv, value: input.credentialValue }] + : [], + config: [], + fromExisting: !input.credentialValue, + }); + if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { + throw new NativeHostedProviderError( + `Could not create OpenShell provider '${profile.providerName}': ${providerErrorDetail(created.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target, profile); + if (!observed) { + throw new NativeHostedProviderError( + `OpenShell did not confirm provider '${profile.providerName}' after creation.`, + ); + } + return attachmentFromMetadata(observed, profile); +} + +/** Prove that the exact NemoClaw-owned hosted provider is attached to one sandbox. */ +export async function verifyNativeHostedProviderAttachment(input: { + profile?: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected?: NativeHostedProviderAttachment; +}): Promise { + const profile = + input.profile ?? + NATIVE_HOSTED_PROFILES.find( + (candidate) => + candidate.profileId === input.expected?.profileId && + candidate.providerName === input.expected?.providerName, + ); + if (!profile) + throw new NativeHostedProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if (!provider) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' is missing. Recreate the sandbox to restore native ${profile.label} inference.`, + ); + } + const receipt = attachmentFromMetadata(provider, profile); + if (input.expected && input.expected.providerId !== receipt.providerId) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity. Recreate the sandbox before using native ${profile.label} inference.`, + ); + } + const attachments = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!attachments.ok) { + throw new NativeHostedProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, + ); + } + if (!attachments.value.names.includes(profile.providerName)) { + throw new NativeHostedProviderError( + `Sandbox '${input.sandboxName}' does not have its native ${profile.label} inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, + ); + } + return receipt; +} + +/** Attach native hosted access and reconcile an ambiguous command through observation. */ +export async function ensureNativeHostedProviderAttached(input: { + profile?: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeHostedProviderAttachment; +}): Promise<{ receipt: NativeHostedProviderAttachment; changed: boolean }> { + const profile = + input.profile ?? + NATIVE_HOSTED_PROFILES.find( + (candidate) => + candidate.profileId === input.expected?.profileId && + candidate.providerName === input.expected?.providerName, + ); + if (!profile) + throw new NativeHostedProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + const before = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!before.ok) { + throw new NativeHostedProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, + ); + } + if (before.value.names.includes(profile.providerName)) { + return { + receipt: await verifyNativeHostedProviderAttachment({ ...input, profile }), + changed: false, + }; + } + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if ( + !provider || + attachmentFromMetadata(provider, profile).providerId !== input.expected.providerId + ) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity before attachment. No provider was attached.`, + ); + } + const attached = await input.adapter.attachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: profile.providerName, + }); + if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { + throw new NativeHostedProviderError( + `Could not attach native ${profile.label} provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, + ); + } + try { + return { + receipt: await verifyNativeHostedProviderAttachment({ ...input, profile }), + changed: true, + }; + } catch (error) { + try { + await detachNativeHostedProvider({ ...input, profile }); + } catch (detachError) { + const detail = error instanceof Error ? error.message : String(error); + const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); + throw new NativeHostedProviderError(`${detail}\n ${detachDetail}`); + } + throw error; + } +} + +/** Detach only the recorded native hosted provider identity and prove absence. */ +export async function detachNativeHostedProvider(input: { + profile?: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeHostedProviderAttachment; +}): Promise { + const profile = + input.profile ?? + NATIVE_HOSTED_PROFILES.find( + (candidate) => + candidate.profileId === input.expected?.profileId && + candidate.providerName === input.expected?.providerName, + ); + if (!profile) + throw new NativeHostedProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if (!provider) return; + const current = attachmentFromMetadata(provider, profile); + if (current.providerId !== input.expected.providerId) { + throw new NativeHostedProviderError( + `Refusing to detach OpenShell provider '${profile.providerName}' because its identity changed.`, + ); + } + const detached = await input.adapter.detachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: profile.providerName, + }); + if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { + throw new NativeHostedProviderError( + `Could not detach native ${profile.label} provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, + ); + } + const after = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!after.ok || after.value.names.includes(profile.providerName)) { + throw new NativeHostedProviderError( + `OpenShell did not confirm removal of native ${profile.label} access from sandbox '${input.sandboxName}'.`, + ); + } +} + +export { nativeHostedProfile } from "./profiles"; diff --git a/src/lib/inference/native-hosted/openrouter-headers.ts b/src/lib/inference/native-hosted/openrouter-headers.ts new file mode 100644 index 00000000000..fc8736bda52 --- /dev/null +++ b/src/lib/inference/native-hosted/openrouter-headers.ts @@ -0,0 +1,8 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Static attribution shared by native agent requests and the legacy adapter. +export const OPENROUTER_DEFAULT_HEADERS = [ + ["HTTP-Referer", "https://www.nvidia.com/nemoclaw/"], + ["X-OpenRouter-Title", "NVIDIA NemoClaw"], +] as const; diff --git a/src/lib/inference/native-hosted/profiles.ts b/src/lib/inference/native-hosted/profiles.ts new file mode 100644 index 00000000000..3ed0d899525 --- /dev/null +++ b/src/lib/inference/native-hosted/profiles.ts @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export interface NativeHostedProfile { + readonly label: string; + readonly logicalProvider: string; + readonly profileId: string; + readonly providerName: string; + readonly endpoint: string; + readonly credentialEnv: string; +} + +export const NATIVE_HOSTED_PROFILES: readonly NativeHostedProfile[] = [ + { + label: "NVIDIA", + logicalProvider: "nvidia-prod", + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + endpoint: "https://integrate.api.nvidia.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + }, + { + label: "OpenAI", + logicalProvider: "openai-api", + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + endpoint: "https://api.openai.com/v1", + credentialEnv: "OPENAI_API_KEY", + }, + { + label: "Anthropic", + logicalProvider: "anthropic-prod", + profileId: "nemoclaw-anthropic-inference-v1", + providerName: "nemoclaw-anthropic-prod-v1", + endpoint: "https://api.anthropic.com", + credentialEnv: "ANTHROPIC_API_KEY", + }, + { + label: "Google Gemini", + logicalProvider: "gemini-api", + profileId: "nemoclaw-gemini-inference-v1", + providerName: "nemoclaw-gemini-api-v1", + endpoint: "https://generativelanguage.googleapis.com/v1beta/openai", + credentialEnv: "GEMINI_API_KEY", + }, + { + label: "OpenRouter", + logicalProvider: "openrouter-api", + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + endpoint: "https://openrouter.ai/api/v1", + credentialEnv: "OPENROUTER_API_KEY", + }, + { + label: "Hermes Provider", + logicalProvider: "hermes-provider", + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + endpoint: "https://inference-api.nousresearch.com/v1", + credentialEnv: "OPENAI_API_KEY", + }, +]; + +export function nativeHostedProfile( + provider: string | null | undefined, +): NativeHostedProfile | undefined { + const name = provider?.trim(); + return NATIVE_HOSTED_PROFILES.find((profile) => profile.logicalProvider === name); +} diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 53555d2ddb8..f26c14ee4c1 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -2,14 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import path from "node:path"; - -import type { - OpenShellGatewayTarget, - OpenShellProviderAdapter, - OpenShellProviderError, - OpenShellProviderMetadata, -} from "../../adapters/openshell/sandbox-observer"; import { REPOSITORY_ROOT } from "../../core/repository-root"; +import { + NativeHostedProviderError, + ensureNativeHostedProvider, + verifyNativeHostedProviderAttachment, + ensureNativeHostedProviderAttached, + detachNativeHostedProvider, + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../native-hosted"; +import { nativeHostedProfile } from "../native-hosted/profiles"; export const NVIDIA_HOSTED_LOGICAL_PROVIDER = "nvidia-prod"; export const NVIDIA_HOSTED_NATIVE_ENDPOINT = "https://integrate.api.nvidia.com/v1"; @@ -17,19 +20,12 @@ export const NVIDIA_HOSTED_NATIVE_PROFILE_ID = "nemoclaw-nvidia-inference-v1"; export const NVIDIA_HOSTED_NATIVE_PROVIDER = "nemoclaw-nvidia-prod-v1"; export const NVIDIA_HOSTED_CREDENTIAL_ENV = "NVIDIA_INFERENCE_API_KEY"; -export type NativeNvidiaProviderAttachment = Readonly<{ - schemaVersion: 1; - profileId: typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; - providerName: typeof NVIDIA_HOSTED_NATIVE_PROVIDER; - providerId: string; -}>; +// Preserve Slice 1's public helpers and persisted NVIDIA receipt while sharing its +// provider lifecycle with the other fixed hosted selections. +export type NativeNvidiaProviderAttachment = NativeHostedProviderAttachment; +export { NativeHostedProviderError as NativeNvidiaProviderError }; -export class NativeNvidiaProviderError extends Error { - constructor(message: string) { - super(message); - this.name = "NativeNvidiaProviderError"; - } -} +const profile = nativeHostedProfile(NVIDIA_HOSTED_LOGICAL_PROVIDER)!; export function nativeNvidiaProviderProfilePath(root = REPOSITORY_ROOT): string { return path.join( @@ -54,285 +50,30 @@ export function nativeInferenceProviderForSandbox( export function normalizeNativeNvidiaProviderAttachment( value: unknown, ): NativeNvidiaProviderAttachment | undefined { - if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; - const receipt = value as Record; - if ( - receipt.schemaVersion !== 1 || - receipt.profileId !== NVIDIA_HOSTED_NATIVE_PROFILE_ID || - receipt.providerName !== NVIDIA_HOSTED_NATIVE_PROVIDER || - typeof receipt.providerId !== "string" || - !receipt.providerId.trim() - ) { - return undefined; - } - return { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: receipt.providerId, - }; -} - -function providerErrorDetail(error: OpenShellProviderError): string { - return error.message.trim() || "OpenShell did not provide a diagnostic."; -} - -function exactNativeProvider(metadata: OpenShellProviderMetadata): boolean { - return ( - metadata.name === NVIDIA_HOSTED_NATIVE_PROVIDER && - metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID && - metadata.configKeys.length === 0 && - metadata.credentialKeys.length === 1 && - metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && - Boolean(metadata.revision?.id) - ); -} - -function attachmentFromMetadata( - metadata: OpenShellProviderMetadata, -): NativeNvidiaProviderAttachment { - if (!exactNativeProvider(metadata) || !metadata.revision) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' does not match the NemoClaw-owned NVIDIA inference boundary. No provider was changed.`, - ); - } - return { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: metadata.revision.id, - }; + const receipt = normalizeNativeHostedProviderAttachment(value); + return receipt?.profileId === NVIDIA_HOSTED_NATIVE_PROFILE_ID ? receipt : undefined; } -async function inspectNativeProvider( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, -): Promise { - const observed = await adapter.getProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (observed.ok) return observed.value; - if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; - throw new NativeNvidiaProviderError( - `Could not inspect OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(observed.error)}`, - ); -} - -function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { - return ( - error.kind === "timeout" || - (error.kind === "transport" && - (error.reason === "connection_loss" || error.reason === "unreachable")) || - (error.kind === "command" && error.reason === "uncertain") - ); -} - -/** Ensure the least-privilege NVIDIA profile and provider without retrying an ambiguous mutation. */ -export async function ensureNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - credentialValue: string | null; - reuseExistingCredential?: boolean; - expected?: NativeNvidiaProviderAttachment; - profilePath?: string; -}): Promise { - const { adapter, target } = input; - const imported = await adapter.importProviderProfile({ - target, - profilePath: input.profilePath ?? nativeNvidiaProviderProfilePath(), - }); - if (!imported.ok) { - const collision = - imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; - throw new NativeNvidiaProviderError( - collision - ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` - : `Could not prepare OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, - ); - } - - const before = await inspectNativeProvider(adapter, target); - if (before) { - const receipt = attachmentFromMetadata(before); - if (input.expected && input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - if (!input.credentialValue) return receipt; - const updated = await adapter.updateProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], - config: [], - }); - if (!updated.ok && !mutationOutcomeMayBeAmbiguous(updated.error)) { - throw new NativeNvidiaProviderError( - `Could not update OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(updated.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after its credential update.`, - ); - } - return attachmentFromMetadata(observed); - } - - if (input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - - if (!input.credentialValue && !input.reuseExistingCredential) { - throw new NativeNvidiaProviderError( - `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, - ); - } - const created = await adapter.createProvider({ - target, - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: input.credentialValue - ? [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }] - : [], - config: [], - fromExisting: !input.credentialValue, - }); - if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { - throw new NativeNvidiaProviderError( - `Could not create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(created.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after creation.`, - ); - } - return attachmentFromMetadata(observed); +export function ensureNativeNvidiaProvider( + input: Omit[0], "profile">, +): ReturnType { + return ensureNativeHostedProvider({ ...input, profile }); } -/** Prove that the exact NemoClaw-owned NVIDIA provider is attached to one sandbox. */ -export async function verifyNativeNvidiaProviderAttachment(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected?: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = attachmentFromMetadata(provider); - if (input.expected && input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const attachments = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!attachments.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, - ); - } - if (!attachments.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `Sandbox '${input.sandboxName}' does not have its native NVIDIA inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, - ); - } - return receipt; +export function verifyNativeNvidiaProviderAttachment( + input: Omit[0], "profile">, +): ReturnType { + return verifyNativeHostedProviderAttachment({ ...input, profile }); } -/** Attach native NVIDIA access and reconcile an ambiguous command through observation. */ -export async function ensureNativeNvidiaProviderAttached(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { - const before = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!before.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, - ); - } - if (before.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: false, - }; - } - const attached = await input.adapter.attachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { - throw new NativeNvidiaProviderError( - `Could not attach native NVIDIA provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, - ); - } - try { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: true, - }; - } catch (error) { - try { - await detachNativeNvidiaProvider(input); - } catch (detachError) { - const detail = error instanceof Error ? error.message : String(error); - const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); - throw new NativeNvidiaProviderError(`${detail}\n ${detachDetail}`); - } - throw error; - } +export function ensureNativeNvidiaProviderAttached( + input: Omit[0], "profile">, +): ReturnType { + return ensureNativeHostedProviderAttached({ ...input, profile }); } -/** Detach only the recorded native NVIDIA provider identity and prove absence. */ -export async function detachNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = attachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to detach OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const detached = await input.adapter.detachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { - throw new NativeNvidiaProviderError( - `Could not detach native NVIDIA provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, - ); - } - const after = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!after.ok || after.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm removal of native NVIDIA access from sandbox '${input.sandboxName}'.`, - ); - } +export function detachNativeNvidiaProvider( + input: Omit[0], "profile">, +): ReturnType { + return detachNativeHostedProvider({ ...input, profile }); } diff --git a/src/lib/inference/openrouter.ts b/src/lib/inference/openrouter.ts index d651424407d..80e38a9ac7c 100644 --- a/src/lib/inference/openrouter.ts +++ b/src/lib/inference/openrouter.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { OPENROUTER_DEFAULT_HEADERS } from "./native-hosted/openrouter-headers"; + import { OPENROUTER_RUNTIME_ADAPTER_PORT } from "../core/ports"; export { OPENROUTER_ENDPOINT_URL, OPENROUTER_PROVIDER_NAME } from "./managed-dcode/identity"; @@ -10,10 +12,7 @@ export const OPENROUTER_CREDENTIAL_ENV = "OPENROUTER_API_KEY"; // OpenRouter through the OpenAI-compatible provider profile while keeping a // distinct provider name and credential binding in NemoClaw. export const OPENROUTER_PROVIDER_TYPE = "openai"; -export const OPENROUTER_DEFAULT_HEADERS = [ - ["HTTP-Referer", "https://www.nvidia.com/nemoclaw/"], - ["X-OpenRouter-Title", "NVIDIA NemoClaw"], -] as const; +export { OPENROUTER_DEFAULT_HEADERS } from "./native-hosted/openrouter-headers"; export const OPENROUTER_RUNTIME_ADAPTER_BIND_HOST = "0.0.0.0"; export const OPENROUTER_RUNTIME_ADAPTER_LOOPBACK_HOST = "127.0.0.1"; export const OPENROUTER_RUNTIME_ADAPTER_SANDBOX_HOST = "host.openshell.internal"; diff --git a/src/lib/onboard/dcode-selection-drift.test.ts b/src/lib/onboard/dcode-selection-drift.test.ts index c005e94c845..fedd53380df 100644 --- a/src/lib/onboard/dcode-selection-drift.test.ts +++ b/src/lib/onboard/dcode-selection-drift.test.ts @@ -114,6 +114,7 @@ describe("live DCode selection drift", () => { it("accepts the generated OpenRouter identity (#9555)", async () => { const output = identity({ + Endpoint: "https://openrouter.ai/api/v1", Provider: "openrouter", Model: "openrouter:nvidia/nemotron-3-ultra-550b-a55b", }); diff --git a/src/lib/onboard/dockerfile-patch.test.ts b/src/lib/onboard/dockerfile-patch.test.ts index 00d7da9d9e5..da3656b3a13 100644 --- a/src/lib/onboard/dockerfile-patch.test.ts +++ b/src/lib/onboard/dockerfile-patch.test.ts @@ -1049,7 +1049,7 @@ describe("dockerfile patch helpers", () => { assert.match(patched, /^ARG NEMOCLAW_MODEL=claude-sonnet-4-5$/m); assert.match(patched, /^ARG NEMOCLAW_PROVIDER_KEY=anthropic$/m); assert.match(patched, /^ARG NEMOCLAW_PRIMARY_MODEL_REF=anthropic\/claude-sonnet-4-5$/m); - assert.match(patched, /^ARG NEMOCLAW_INFERENCE_BASE_URL=https:\/\/inference\.local$/m); + assert.match(patched, /^ARG NEMOCLAW_INFERENCE_BASE_URL=https:\/\/api\.anthropic\.com$/m); assert.match(patched, /^ARG NEMOCLAW_INFERENCE_API=anthropic-messages$/m); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); 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..396d1a551fa 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/native-hosted/openrouter-headers.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..d36d3151515 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/native-hosted/openrouter-headers.ts", "src/lib/messaging/", "src/lib/messaging/channels/googlechat/runtime/hermes-adapter.py", "src/lib/tool-disclosure.ts", diff --git a/src/lib/onboard/inference-providers/hermes.test.ts b/src/lib/onboard/inference-providers/hermes.test.ts index 7f19fe0115d..207cf67c0e3 100644 --- a/src/lib/onboard/inference-providers/hermes.test.ts +++ b/src/lib/onboard/inference-providers/hermes.test.ts @@ -355,3 +355,51 @@ describe("setupHermesProviderInference SSRF guard (#6072)", () => { expect(deps.runOpenshell).not.toHaveBeenCalled(); }); }); + +describe("native Hermes inference preparation", () => { + it("uses the canonical endpoint without custom DNS rewriting and forwards provider identity", async () => { + const lookup = vi.fn(() => { + throw new Error("must not resolve"); + }); + const deps = makeDeps({ resolveHermesNousApiKey: vi.fn(() => "nous-key"), lookup }); + const expected = { + schemaVersion: 1 as const, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "recorded-id", + }; + await expect( + setupHermesProviderInference( + { + ...makeArgs("https://inference-api.nousresearch.com/v1"), + nativeProvider: true, + expectedNativeProviderAttachment: expected, + }, + deps as any, + ), + ).resolves.toEqual({ ok: true }); + expect(deps.hermesProviderAuth.ensureHermesProviderApiKeyCredentials).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ expected }), + ); + expect(lookup).not.toHaveBeenCalled(); + expect(deps.runOpenshell).not.toHaveBeenCalled(); + expect(deps.verifyInferenceRoute).not.toHaveBeenCalled(); + }); + + it("rejects a noncanonical native endpoint before credential acquisition", async () => { + const deps = makeDeps(); + await expect( + setupHermesProviderInference( + { + ...makeArgs("https://different.example/v1"), + nativeProvider: true, + }, + deps as any, + ), + ).rejects.toThrow("canonical endpoint"); + expect(deps.checkHermesProviderStoreReachable).not.toHaveBeenCalled(); + expect(deps.hermesProviderAuth.ensureHermesProviderOAuthCredentials).not.toHaveBeenCalled(); + expect(deps.hermesProviderAuth.ensureHermesProviderApiKeyCredentials).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/inference-providers/hermes.ts b/src/lib/onboard/inference-providers/hermes.ts index 8bf9c34bcc3..d5ec442367c 100644 --- a/src/lib/onboard/inference-providers/hermes.ts +++ b/src/lib/onboard/inference-providers/hermes.ts @@ -4,12 +4,16 @@ // Hermes Provider inference setup flow. // Extracted verbatim from onboard.setupInference (#767). +import type { NativeHostedProviderAttachment } from "../../inference/native-hosted"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { rewriteConfigUrlsWithDnsPinning } from "../../sandbox/config"; import type { HermesAuthMethod } from "../hermes-auth"; import type { HermesDeps, SetupInferenceResult } from "./types"; export async function setupHermesProviderInference( args: { + nativeProvider?: boolean; + expectedNativeProviderAttachment?: NativeHostedProviderAttachment; sandboxName: string | null; model: string; provider: string; @@ -34,7 +38,13 @@ export async function setupHermesProviderInference( // inference route), so SSRF validation only applies to an explicitly-supplied // custom endpoint. let resolvedEndpointUrl = endpointUrl; - if (endpointUrl) { + if (args.nativeProvider && endpointUrl) { + const canonical = nativeHostedProfile("hermes-provider")!.endpoint; + if (endpointUrl.replace(/\/+$/u, "") !== canonical) { + throw new Error("Hermes Provider native inference requires its canonical endpoint."); + } + } + if (endpointUrl && !args.nativeProvider) { let parsedEndpoint: URL; try { parsedEndpoint = new URL(endpointUrl); @@ -134,11 +144,17 @@ export async function setupHermesProviderInference( apiKey: resolveHermesNousApiKey(), runOpenshell, baseUrl: resolvedEndpointUrl || undefined, + ...(args.expectedNativeProviderAttachment + ? { expected: args.expectedNativeProviderAttachment } + : {}), }) : await hermesProviderAuth.ensureHermesProviderOAuthCredentials(targetSandbox, { allowInteractiveLogin: !isNonInteractive(), runOpenshell, baseUrl: resolvedEndpointUrl || undefined, + ...(args.expectedNativeProviderAttachment + ? { expected: args.expectedNativeProviderAttachment } + : {}), toolGatewayPresets: hermesToolGateways, }); } catch (err) { @@ -158,6 +174,8 @@ export async function setupHermesProviderInference( } } + if (args.nativeProvider) return { ok: true }; + const applyResult = runOpenshell( ["inference", "set", "--no-verify", "--provider", provider, "--model", model], { ignoreError: true }, diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 509b3650ca6..4f66233b2fb 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -15,6 +15,7 @@ // so they accept whatever the orchestrator hands in without needing to // duplicate every helper's exact signature. +import type { NativeHostedProviderAttachment } from "../../inference/native-hosted"; import type { TrustedPrivateEndpointCapability } from "../../inference/endpoint-ssrf-preflight"; import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; import type { HermesAuthMethod } from "../hermes-auth"; @@ -173,7 +174,12 @@ export type HermesDeps = CommonDeps & { isHermesProviderRegistered(runOpenshell: any): Promise; ensureHermesProviderApiKeyCredentials( sandboxName: string, - opts: { apiKey: unknown; runOpenshell: any; baseUrl?: string | undefined }, + opts: { + apiKey: unknown; + runOpenshell: any; + baseUrl?: string | undefined; + expected?: NativeHostedProviderAttachment; + }, ): Promise; ensureHermesProviderOAuthCredentials( sandboxName: string, @@ -182,6 +188,7 @@ export type HermesDeps = CommonDeps & { runOpenshell: any; baseUrl?: string | undefined; toolGatewayPresets: string[]; + expected?: NativeHostedProviderAttachment; }, ): Promise; }; diff --git a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index 8c2563ed018..83fadfd64ce 100644 --- a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts @@ -26,8 +26,8 @@ const resourceProfiles: [string, { cpu: string; memory: string } | null][] = [ describe("sandbox create intent machine boundary", () => { it("attaches the internal native NVIDIA provider while retaining the logical selection", async () => { - const session = createSession({ sandboxName: "native-nvidia" }); - const nativeNvidiaProviderAttachment = { + const session = createSession({ sandboxName: "native-hosted" }); + const nativeHostedProviderAttachment = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, providerName: "nemoclaw-nvidia-prod-v1" as const, @@ -44,26 +44,26 @@ describe("sandbox create intent machine boundary", () => { toolDisclosure: "progressive" as const, fromDockerfile: null, hermesAuthMethod: null, - nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment, }), }); await handleSandboxState({ ...baseOptions(deps, session), - sandboxName: "native-nvidia", + sandboxName: "native-hosted", provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", }); expect(calls.resolveCreateIntent).toHaveBeenCalledWith( expect.objectContaining({ - sandboxName: "native-nvidia", + sandboxName: "native-hosted", inferenceProvider: "nemoclaw-nvidia-prod-v1", - nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment, }), ); expect(calls.startStep).toHaveBeenCalledWith("sandbox", { - sandboxName: "native-nvidia", + sandboxName: "native-hosted", provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", }); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 8a2fc2baa37..389e1cf17af 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -7,7 +7,7 @@ import { type GatewayRouteCompatibilityResult, isAdvisoryGatewayRouteConflict, nativeInferenceProviderForSandbox, - normalizeNativeNvidiaProviderAttachment, + normalizeNativeHostedProviderAttachment, } from "../../../inference/gateway-route-compatibility"; import type { InferenceEndpointSource } from "../../../inference/selection"; import { @@ -130,19 +130,19 @@ type SandboxRecreateWorkloadSkipReason = Extract< { readonly status: "skipped" } >["reason"]; -function nativeNvidiaCreateIntentFields( +function nativeHostedCreateIntentFields( provider: string | null | undefined, entry: SandboxEntry | null, ): { inferenceProvider: string | null; - nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; } { - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - entry?.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + entry?.nativeHostedProviderAttachment, ); return { inferenceProvider: nativeInferenceProviderForSandbox(provider), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), }; } @@ -368,7 +368,7 @@ export interface SandboxStateOptions< resolveSandboxCreateIntent(input: { sandboxName: string; inferenceProvider?: string | null; - nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[]; webSearchConfig: WebSearchConfig | null; @@ -1825,7 +1825,7 @@ class SandboxStateFlow< const reuseRegisteredCredentials = this.resumesSandboxPrompts && this.options.resume; const resolved = await this.deps.resolveSandboxCreateIntent({ sandboxName, - ...nativeNvidiaCreateIntentFields( + ...nativeHostedCreateIntentFields( this.options.provider, this.deps.getSandboxRegistryEntry(sandboxName), ), diff --git a/src/lib/onboard/machine/resume-provider-shim.test.ts b/src/lib/onboard/machine/resume-provider-shim.test.ts index 3c33eb3f0c5..4c5ae28205b 100644 --- a/src/lib/onboard/machine/resume-provider-shim.test.ts +++ b/src/lib/onboard/machine/resume-provider-shim.test.ts @@ -10,6 +10,22 @@ vi.mock("../../credentials/store", () => ({ import { createResumeProviderShim } from "./resume-provider-shim"; describe("createResumeProviderShim", () => { + it("resumes a native provider using its owned gateway name without a host key", async () => { + const providerExistsInGateway = vi.fn(() => true); + const replaceNamedCredential = vi.fn(); + const shim = createResumeProviderShim({ + isNonInteractive: () => true, + providerExistsInGateway, + isRoutedInferenceProvider: () => false, + replaceNamedCredential, + }); + await expect( + shim.ensureResumeProviderReady("gateway-west", "openai-api", "OPENAI_API_KEY"), + ).resolves.toEqual({ forceInferenceSetup: false, credentialEnv: "OPENAI_API_KEY" }); + expect(providerExistsInGateway).toHaveBeenCalledWith("nemoclaw-openai-api-v1", "gateway-west"); + expect(replaceNamedCredential).not.toHaveBeenCalled(); + }); + afterEach(() => { vi.restoreAllMocks(); }); diff --git a/src/lib/onboard/machine/resume-provider-shim.ts b/src/lib/onboard/machine/resume-provider-shim.ts index 5380eecc80e..9ebf4a419fa 100644 --- a/src/lib/onboard/machine/resume-provider-shim.ts +++ b/src/lib/onboard/machine/resume-provider-shim.ts @@ -3,6 +3,7 @@ import { runOpenshell } from "../../adapters/openshell/runtime"; import { D, R } from "../../cli/terminal-style"; import { isBedrockRuntimeEndpoint } from "../../inference/bedrock-runtime"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { DEFAULT_ROUTE_CREDENTIAL_ENV } from "../../inference/config"; import { validateNvidiaApiKeyValue } from "../../validation"; import { hydrateCredentialEnv } from "../credential-env"; @@ -55,7 +56,11 @@ export function createResumeProviderShim(deps: ResumeProviderShimDeps) { remoteProviderConfig: onboardProviders.REMOTE_PROVIDER_CONFIG, defaultRouteCredentialEnv: DEFAULT_ROUTE_CREDENTIAL_ENV, isRoutedInferenceProvider: deps.isRoutedInferenceProvider, - providerExistsInGateway: (name) => deps.providerExistsInGateway(name, gatewayName), + providerExistsInGateway: (name) => + deps.providerExistsInGateway( + nativeHostedProfile(name)?.providerName ?? name, + gatewayName, + ), hydrateCredentialEnv, getProviderLabel: onboardProviders.getProviderLabel, isNonInteractive: deps.isNonInteractive, diff --git a/src/lib/onboard/provider-recovery.ts b/src/lib/onboard/provider-recovery.ts index adf520a4c74..1f975ab6157 100644 --- a/src/lib/onboard/provider-recovery.ts +++ b/src/lib/onboard/provider-recovery.ts @@ -145,6 +145,7 @@ export interface ProviderRecoveryHelpers extends ProviderSelectionRecoveryReader } export interface RecordedInferenceRoute { + nativeHostedProviderAttachment?: import("../inference/native-hosted").NativeHostedProviderAttachment; provider: string; model: string; endpointUrl: string | null; @@ -215,6 +216,7 @@ function completeRecordedInferenceRoute( endpointUrl?: unknown; endpointSource?: unknown; preferredInferenceApi?: unknown; + nativeHostedProviderAttachment?: import("../inference/native-hosted").NativeHostedProviderAttachment; }, source: RecordedInferenceRoute["source"], ): RecordedInferenceRoute | null { @@ -232,7 +234,16 @@ function completeRecordedInferenceRoute( const endpointSource = endpointUrl ? normalizeInferenceEndpointSource(value.endpointSource) : null; - return { ...inference, endpointUrl, endpointSource, preferredInferenceApi, source }; + return { + ...inference, + endpointUrl, + endpointSource, + preferredInferenceApi, + source, + ...(source === "registry" && value.nativeHostedProviderAttachment + ? { nativeHostedProviderAttachment: value.nativeHostedProviderAttachment } + : {}), + }; } export function createProviderRecoveryHelpers(deps: ProviderRecoveryDeps): ProviderRecoveryHelpers { diff --git a/src/lib/onboard/rebuild-route-handoff.test.ts b/src/lib/onboard/rebuild-route-handoff.test.ts index 525c49e6f61..d0bfffa5e78 100644 --- a/src/lib/onboard/rebuild-route-handoff.test.ts +++ b/src/lib/onboard/rebuild-route-handoff.test.ts @@ -204,3 +204,19 @@ describe("createProviderRecoveryReceiptLedger", () => { ).toBe(false); }); }); + +it("preserves an immutable native provider identity across destructive rebuild handoff", () => { + const attachment = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }; + const handoff = createRebuildRouteHandoff("alpha", { + ...registryRoute(), + nativeHostedProviderAttachment: attachment, + }); + attachment.providerId = "changed"; + expect(handoff.route.nativeHostedProviderAttachment?.providerId).toBe("recorded-id"); + expect(Object.isFrozen(handoff.route.nativeHostedProviderAttachment)).toBe(true); +}); diff --git a/src/lib/onboard/rebuild-route-handoff.ts b/src/lib/onboard/rebuild-route-handoff.ts index 72a15f2df98..4d23d6478f7 100644 --- a/src/lib/onboard/rebuild-route-handoff.ts +++ b/src/lib/onboard/rebuild-route-handoff.ts @@ -43,6 +43,13 @@ export function createRebuildRouteHandoff( endpointSource: route.endpointSource ?? null, preferredInferenceApi: route.preferredInferenceApi, source: "registry", + ...(route.nativeHostedProviderAttachment + ? { + nativeHostedProviderAttachment: Object.freeze({ + ...route.nativeHostedProviderAttachment, + }), + } + : {}), }); return Object.freeze({ sandboxName, route: frozenRoute }); } @@ -116,6 +123,13 @@ function freezeRoute(route: RegistryInferenceRoute): RegistryInferenceRoute { endpointSource: route.endpointSource ?? null, preferredInferenceApi: route.preferredInferenceApi, source: "registry", + ...(route.nativeHostedProviderAttachment + ? { + nativeHostedProviderAttachment: Object.freeze({ + ...route.nativeHostedProviderAttachment, + }), + } + : {}), }); } @@ -125,7 +139,13 @@ function routesMatch(left: RegistryInferenceRoute, right: RegistryInferenceRoute left.model === right.model && left.endpointUrl === right.endpointUrl && (left.endpointSource ?? null) === (right.endpointSource ?? null) && - left.preferredInferenceApi === right.preferredInferenceApi + left.preferredInferenceApi === right.preferredInferenceApi && + left.nativeHostedProviderAttachment?.profileId === + right.nativeHostedProviderAttachment?.profileId && + left.nativeHostedProviderAttachment?.providerName === + right.nativeHostedProviderAttachment?.providerName && + left.nativeHostedProviderAttachment?.providerId === + right.nativeHostedProviderAttachment?.providerId ); } diff --git a/src/lib/onboard/recovered-provider-reuse.test.ts b/src/lib/onboard/recovered-provider-reuse.test.ts index 0cfc9961d00..9c60174ce15 100644 --- a/src/lib/onboard/recovered-provider-reuse.test.ts +++ b/src/lib/onboard/recovered-provider-reuse.test.ts @@ -55,51 +55,63 @@ describe("assessRecoveredProviderCredentialReuse", () => { }); it.each( - Array.from([[], ["WRONG_BASE_URL"], ["OPENAI_BASE_URL", "EXTRA_FLAG"]], (value) => [value]), - )( - "requires the exact endpoint-config binding for built-in provider recovery [case %#]", - (configKeys) => { - const builtInOpenAi = { - ...completeRecovery, - selectedKey: "openai", - selectedProvider: "openai-api", - recoveredProvider: "openai-api", - expectedCredentialEnv: "OPENAI_API_KEY", - gatewayProvider: { - name: "openai-api", - type: "openai", - credentialKeys: ["OPENAI_API_KEY"], - configKeys: ["OPENAI_BASE_URL"], - }, - endpointIdentity: undefined, - }; + Array.from( + [["OPENAI_BASE_URL"], ["WRONG_BASE_URL"], ["OPENAI_BASE_URL", "EXTRA_FLAG"]], + (value) => [value], + ), + )("requires zero endpoint-config keys for native provider recovery [case %#]", (configKeys) => { + const builtInOpenAi = { + ...completeRecovery, + selectedKey: "openai", + selectedProvider: "openai-api", + recoveredProvider: "openai-api", + expectedNativeAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }, + expectedCredentialEnv: "OPENAI_API_KEY", + gatewayProvider: { + name: "nemoclaw-openai-api-v1", + type: "nemoclaw-openai-inference-v1", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + }, + endpointIdentity: undefined, + }; - expect(assessRecoveredProviderCredentialReuse(builtInOpenAi)).toMatchObject({ - kind: "reuse-gateway-credential", - }); + expect(assessRecoveredProviderCredentialReuse(builtInOpenAi)).toMatchObject({ + kind: "reuse-gateway-credential", + }); - expect( - assessRecoveredProviderCredentialReuse({ - ...builtInOpenAi, - gatewayProvider: { ...builtInOpenAi.gatewayProvider, configKeys }, - }), - ).toMatchObject({ kind: "reject" }); - }, - ); + expect( + assessRecoveredProviderCredentialReuse({ + ...builtInOpenAi, + gatewayProvider: { ...builtInOpenAi.gatewayProvider, configKeys }, + }), + ).toMatchObject({ kind: "reject" }); + }); - it("reuses OpenRouter when its distinct provider name is registered as OpenAI-compatible (#5826)", () => { + it("reuses OpenRouter when its distinct provider name is registered with its native profile", () => { expect( assessRecoveredProviderCredentialReuse({ ...completeRecovery, selectedKey: "openrouter", selectedProvider: "openrouter-api", recoveredProvider: "openrouter-api", + expectedNativeAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "recorded-id", + }, expectedCredentialEnv: "OPENROUTER_API_KEY", gatewayProvider: { - name: "openrouter-api", - type: "openai", + name: "nemoclaw-openrouter-api-v1", + type: "nemoclaw-openrouter-inference-v1", credentialKeys: ["OPENROUTER_API_KEY"], - configKeys: ["OPENAI_BASE_URL"], + configKeys: [], }, endpointIdentity: undefined, }), @@ -117,12 +129,18 @@ describe("assessRecoveredProviderCredentialReuse", () => { selectedProvider: "openrouter-api", recoveredProvider: "openrouter-api", recoveredPreferredInferenceApi: "openai-responses", + expectedNativeAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "recorded-id", + }, expectedCredentialEnv: "OPENROUTER_API_KEY", gatewayProvider: { - name: "openrouter-api", - type: "openai", + name: "nemoclaw-openrouter-api-v1", + type: "nemoclaw-openrouter-inference-v1", credentialKeys: ["OPENROUTER_API_KEY"], - configKeys: ["OPENAI_BASE_URL"], + configKeys: [], }, endpointIdentity: undefined, }), diff --git a/src/lib/onboard/recovered-provider-reuse.ts b/src/lib/onboard/recovered-provider-reuse.ts index 9a6d91bd453..2b50def81d4 100644 --- a/src/lib/onboard/recovered-provider-reuse.ts +++ b/src/lib/onboard/recovered-provider-reuse.ts @@ -3,6 +3,11 @@ import { canonicalEndpoint, type EndpointFlavor } from "../core/url-utils"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; +import { + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../inference/native-hosted"; +import { nativeHostedProfile } from "../inference/native-hosted/profiles"; import { isSafeModelId } from "../validation"; import type { GatewayProviderMetadata } from "./gateway-provider-metadata"; import type { RecordedInferenceRoute } from "./provider-recovery"; @@ -112,6 +117,7 @@ export function assessRecoveredProviderCredentialReuse(options: { expectedCredentialEnv: string; gatewayProvider: GatewayProviderMetadata | null; endpointIdentity?: EndpointIdentity; + expectedNativeAttachment?: NativeHostedProviderAttachment; }): RecoveredProviderReuseDecision { if (options.hostCredentialAvailable) return { kind: "validate-host-credential" }; if (!options.recoveredFromSandbox) { @@ -149,6 +155,32 @@ export function assessRecoveredProviderCredentialReuse(options: { }; } const gatewayProvider = options.gatewayProvider; + const nativeProfile = nativeHostedProfile(selectedProvider); + if (nativeProfile) { + const expected = normalizeNativeHostedProviderAttachment(options.expectedNativeAttachment); + if ( + !expected || + expected.profileId !== nativeProfile.profileId || + expected.providerName !== nativeProfile.providerName || + !gatewayProvider || + gatewayProvider.name !== nativeProfile.providerName || + gatewayProvider.type !== nativeProfile.profileId || + gatewayProvider.credentialKeys.length !== 1 || + gatewayProvider.credentialKeys[0] !== nativeProfile.credentialEnv || + gatewayProvider.configKeys.length !== 0 + ) { + return { + kind: "reject", + condition: "gateway-provider-identity", + reason: `provider '${selectedProvider}' has no exact native identity in OpenShell`, + }; + } + return { + kind: "reuse-gateway-credential", + preferredInferenceApi: options.recoveredPreferredInferenceApi as string, + }; + } + // #6294: an OpenAI-only agent coerced onto openai-completions registers the // compatible-anthropic-endpoint provider as type=openai (OPENAI_BASE_URL), // so the reuse identity must expect that surface rather than the static @@ -270,7 +302,10 @@ export function resolveRecoveredProviderCredentialReuse( recoveredPreferredInferenceApi: recoveredRoute?.preferredInferenceApi, expectedProviderType: remoteConfig.providerType, expectedCredentialEnv: selectedCredentialEnv, - gatewayProvider: deps.readGatewayProviderMetadata(state.provider), + expectedNativeAttachment: recoveredRoute?.nativeHostedProviderAttachment, + gatewayProvider: deps.readGatewayProviderMetadata( + nativeHostedProfile(state.provider)?.providerName ?? state.provider, + ), endpointIdentity: customFlavor ? { flavor: customFlavor, diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index a258271e590..bbe505eb713 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { WebSearchConfig } from "../inference/web-search"; -import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; +import type { NativeHostedProviderAttachment } from "../inference/native-hosted"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; import type { NamedMessagingChannel } from "./messaging-prep"; import { @@ -27,7 +27,7 @@ import { export type CompleteSandboxCreateIntentInput = { sandboxName: string; inferenceProvider?: string | null; - nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + nativeHostedProviderAttachment?: NativeHostedProviderAttachment; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[] | null; webSearchConfig: WebSearchConfig | null; @@ -146,7 +146,7 @@ export function createSandboxCreateIntentResolver< basePolicyPath: deps.getAgentPolicyPath(input.agent) || deps.defaultPolicyPath, sandboxName: input.sandboxName, inferenceProvider: input.inferenceProvider, - nativeNvidiaProviderAttachment: input.nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment: input.nativeHostedProviderAttachment, hostLocalInferenceRouteOnly: input.hostLocalInferenceRouteOnly === true, channels: deps.channels, enabledChannels: resolveSelectedChannels(input), diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index 2fabf1ebc3c..d16efcd0e26 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { SandboxHostMount } from "../state/registry/types"; -import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; +import type { NativeHostedProviderAttachment } from "../inference/native-hosted"; import type { MessagingChannelConfig } from "../messaging-channel-config"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; import type { InitialSandboxPolicy } from "./initial-policy"; @@ -48,7 +48,7 @@ export type SandboxCreatePolicyRequest = { export type SandboxCreateIntent = { readonly sandboxName: string; readonly inferenceProvider: string | null; - readonly nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + readonly nativeHostedProviderAttachment?: NativeHostedProviderAttachment; readonly activeMessagingChannels: readonly string[]; readonly messagingProviderRequests: readonly SandboxCreateMessagingProviderRequest[]; readonly reusableMessagingProviders: readonly string[]; @@ -70,7 +70,7 @@ export type ResolveSandboxCreateIntentInput = { basePolicyPath: string; sandboxName: string; inferenceProvider?: string | null; - nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + nativeHostedProviderAttachment?: NativeHostedProviderAttachment; hostLocalInferenceRouteOnly?: boolean; channels: readonly MessagingChannel[]; enabledChannels: string[] | null; diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index a039c03849a..2ecfc6a5469 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -140,7 +140,7 @@ export function resolveSandboxCreateIntent({ basePolicyPath, sandboxName, inferenceProvider, - nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment, hostLocalInferenceRouteOnly = false, channels, enabledChannels, @@ -188,7 +188,7 @@ export function resolveSandboxCreateIntent({ return { sandboxName, inferenceProvider: normalizedInferenceProvider, - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), activeMessagingChannels, messagingProviderRequests: messagingProviderRequests.map((request) => ({ ...request })), reusableMessagingProviders: enabledReusableMessagingProviders, diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index 56788f54c01..d41f608cc22 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -32,7 +32,7 @@ function nativeProviderBoundary(adapter: OpenShellProviderAdapter) { deferred: false, sandboxName: "alpha", gatewayName: "nemoclaw", - expectedNativeNvidiaProviderAttachment: { + expectedNativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 9f245c0e83f..932461de6fa 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -86,9 +86,9 @@ import { } from "./identity-boundary"; import { publishAttachedProvidersBeforeDockerSandboxCreation, - usesNativeNvidiaProvider, + usesNativeHostedProvider, validateAttachedMessagingProvidersBeforeSandboxCreation, - verifyNativeNvidiaAttachmentAfterCreate, + verifyNativeHostedAttachmentAfterCreate, } from "./provider-publication"; import { materializeRebuildPolicyHandoff, @@ -1415,7 +1415,7 @@ export function createProviderEffectBoundary(input: { readonly deferred: boolean; readonly sandboxName: string; readonly gatewayName: string; - readonly expectedNativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + readonly expectedNativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; readonly preparationInput: ProviderPreparationInput; readonly preparationDeps: ProviderPreparationDeps; readonly runVerifiedSandboxCreateEffects: import("../types").VerifiedSandboxCreateEffects | null; @@ -1434,16 +1434,16 @@ export function createProviderEffectBoundary(input: { input.preparationInput, input.preparationDeps, ); - const verifyNativeNvidiaAttachment = async (context: VerifiedSandboxCreateEffectsContext) => { - if (!usesNativeNvidiaProvider(input.preparationInput.inferenceProvider)) return; + const verifyNativeHostedAttachment = async (context: VerifiedSandboxCreateEffectsContext) => { + if (!usesNativeHostedProvider(input.preparationInput.inferenceProvider)) return; context.revalidateSandboxIdentity( `verifying native NVIDIA provider attachment for sandbox '${input.sandboxName}'`, ); - await verifyNativeNvidiaAttachmentAfterCreate({ + await verifyNativeHostedAttachmentAfterCreate({ sandboxName: input.sandboxName, gatewayName: input.gatewayName, inferenceProvider: input.preparationInput.inferenceProvider, - expected: input.expectedNativeNvidiaProviderAttachment, + expected: input.expectedNativeHostedProviderAttachment, deps: input.preparationDeps, }); }; @@ -1454,8 +1454,8 @@ export function createProviderEffectBoundary(input: { input.revalidateSandboxIdentityBeforeCreate(); await publish(); }, - runAfterVerifiedCreate: usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) - ? verifyNativeNvidiaAttachment + runAfterVerifiedCreate: usesNativeHostedProvider(input.preparationInput.inferenceProvider) + ? verifyNativeHostedAttachment : undefined, }; } @@ -1477,7 +1477,7 @@ export function createProviderEffectBoundary(input: { `publishing deferred providers for sandbox '${input.sandboxName}'`, ); await publish(); - await verifyNativeNvidiaAttachment(context); + await verifyNativeHostedAttachment(context); context.revalidateSandboxIdentity( `attaching deferred providers to sandbox '${input.sandboxName}'`, ); @@ -3574,7 +3574,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche deferred: createIntent?.deferSandboxEffectsUntilIdentityVerification === true, sandboxName, gatewayName: GATEWAY_NAME, - expectedNativeNvidiaProviderAttachment: resolvedCreateIntent.nativeNvidiaProviderAttachment, + expectedNativeHostedProviderAttachment: resolvedCreateIntent.nativeHostedProviderAttachment, preparationInput: providerPreparationInput, preparationDeps: providerPreparationDeps, runVerifiedSandboxCreateEffects, diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index 7402aacbe24..356d3de8ae8 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES } from "../../inference/native-hosted/profiles"; import type { SandboxCreateOrchestrationRuntime } from "../../onboard"; import type { OpenShellProviderAdapter, @@ -10,10 +11,7 @@ import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/prov import type { OpenShellGatewayEndpointEnvironment } from "../../adapters/openshell/gateway-scope"; import { namedOpenShellGateway } from "../../adapters/openshell/sandbox-observer"; import { REPOSITORY_ROOT } from "../../core/repository-root"; -import { - NVIDIA_HOSTED_NATIVE_PROVIDER, - verifyNativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; +import { verifyNativeHostedProviderAttachment } from "../../inference/native-hosted"; import { messagingCredentialProviderProfilePath, MESSAGING_CREDENTIAL_PROVIDER_TYPE, @@ -64,24 +62,24 @@ function resolveProviderAdapter(deps: ProviderPreparationDeps): OpenShellProvide ); } -export function usesNativeNvidiaProvider(inferenceProvider: string | null): boolean { - return inferenceProvider === NVIDIA_HOSTED_NATIVE_PROVIDER; +export function usesNativeHostedProvider(inferenceProvider: string | null): boolean { + return NATIVE_HOSTED_PROFILES.some((profile) => profile.providerName === inferenceProvider); } -export async function verifyNativeNvidiaAttachmentAfterCreate(input: { +export async function verifyNativeHostedAttachmentAfterCreate(input: { readonly sandboxName: string; readonly gatewayName: string; readonly inferenceProvider: string | null; - readonly expected: SandboxEntry["nativeNvidiaProviderAttachment"]; + readonly expected: SandboxEntry["nativeHostedProviderAttachment"]; readonly deps: ProviderPreparationDeps; }): Promise { - if (!usesNativeNvidiaProvider(input.inferenceProvider)) return; + if (!usesNativeHostedProvider(input.inferenceProvider)) return; if (!input.expected) { throw new Error( - `Sandbox '${input.sandboxName}' is missing its native NVIDIA provider identity receipt.`, + `Sandbox '${input.sandboxName}' is missing its native hosted provider identity receipt.`, ); } - await verifyNativeNvidiaProviderAttachment({ + await verifyNativeHostedProviderAttachment({ adapter: resolveProviderAdapter(input.deps), target: namedOpenShellGateway(input.gatewayName), sandboxName: input.sandboxName, diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index 44b092116d7..b3bb3c368e4 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -112,15 +112,15 @@ describe("buildCreatedSandboxRegistryEntry", () => { compatibleEndpointReasoningEffort: null, nimContainer: null, }, - nativeNvidiaProviderAttachment: attachment, + nativeHostedProviderAttachment: attachment, }), ); - expect(entry.nativeNvidiaProviderAttachment).toEqual(attachment); + expect(entry.nativeHostedProviderAttachment).toEqual(attachment); expect(() => buildCreatedSandboxRegistryEntry( createdRegistryEntryInput({ - nativeNvidiaProviderAttachment: { ...attachment, providerId: "" }, + nativeHostedProviderAttachment: { ...attachment, providerId: "" }, }), ), ).toThrow(/native NVIDIA provider attachment failed closed validation/u); diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index aceb897b8ca..f74ee475501 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -13,7 +13,7 @@ import { inferenceSelectionRegistryFields, normalizeInferenceSelection, } from "../inference/selection"; -import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia"; +import { normalizeNativeHostedProviderAttachment } from "../inference/native-hosted"; import { type WebSearchConfig, webSearchProviderForConfig } from "../inference/web-search"; import * as onboardSession from "../state/onboard-session"; import type { SandboxEntry, SandboxMessagingState } from "../state/registry"; @@ -69,7 +69,7 @@ export interface CreatedSandboxRegistryEntryInput { workload?: SandboxEntry["workload"]; hostLocalInferenceReceipt?: SandboxEntry["hostLocalInferenceReceipt"]; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; - nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; deferredN1xManagedVllmPreviewIntent?: true; toolDisclosure?: ToolDisclosure; observabilityEnabled?: boolean; @@ -208,10 +208,10 @@ export function buildCreatedSandboxRegistryEntry( const hostLocalInferenceProvenance = cloneSandboxHostLocalInferenceProvenance( input.hostLocalInferenceProvenance, ); - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - input.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + input.nativeHostedProviderAttachment, ); - if (input.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + if (input.nativeHostedProviderAttachment !== undefined && !nativeHostedProviderAttachment) { throw new RuntimeProviderSelectionError( "Sandbox native NVIDIA provider attachment failed closed validation.", ); @@ -265,7 +265,7 @@ export function buildCreatedSandboxRegistryEntry( workload, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(deferredN1xManagedVllmAccepted ? { deferredN1xManagedVllmAccepted: true as const } : {}), toolDisclosure: input.toolDisclosure ?? DEFAULT_TOOL_DISCLOSURE, observabilityEnabled: input.observabilityEnabled === true, @@ -341,10 +341,10 @@ export function prepareCreatedSandboxRegistration( input.hostLocalInferenceProvenance !== undefined ? input.hostLocalInferenceProvenance : pending?.hostLocalInferenceProvenance; - const pendingNativeNvidiaProviderAttachment = - input.nativeNvidiaProviderAttachment !== undefined - ? input.nativeNvidiaProviderAttachment - : pending?.nativeNvidiaProviderAttachment; + const pendingNativeHostedProviderAttachment = + input.nativeHostedProviderAttachment !== undefined + ? input.nativeHostedProviderAttachment + : pending?.nativeHostedProviderAttachment; const entry = buildCreatedSandboxRegistryEntry({ ...input, inferenceSelection: pendingRoute @@ -356,9 +356,9 @@ export function prepareCreatedSandboxRegistration( ...(pendingHostLocalInferenceProvenance === undefined ? {} : { hostLocalInferenceProvenance: pendingHostLocalInferenceProvenance }), - ...(pendingNativeNvidiaProviderAttachment === undefined + ...(pendingNativeHostedProviderAttachment === undefined ? {} - : { nativeNvidiaProviderAttachment: pendingNativeNvidiaProviderAttachment }), + : { nativeHostedProviderAttachment: pendingNativeHostedProviderAttachment }), }); if (input.portableLifecycle === true) { if (getRequestedSandboxAgentName(input.agent) !== "openclaw") { diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 5d8a7529769..dbb53818161 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { @@ -183,7 +184,9 @@ describe("createProviderReviewDeps", () => { }); describe("native NVIDIA onboarding", () => { - it("reserves the logical route with an attached-provider receipt and no shared route mutation", async () => { + it.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "hermes-provider"), + )("records $label native inference without shared route mutation", async (profile) => { const updateProvider = vi.fn(async () => ({ ok: true, })); @@ -192,9 +195,9 @@ describe("native NVIDIA onboarding", () => { getProvider: vi.fn(async () => ({ ok: true, value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], configKeys: [], revision: { id: "provider-id", resourceVersion: 4 }, }, @@ -222,7 +225,7 @@ describe("native NVIDIA onboarding", () => { isNonInteractive: () => true, hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, providerAdapter, - hydrateCredentialEnv: vi.fn(() => "host-only-nvidia-credential"), + hydrateCredentialEnv: vi.fn(() => "host-only-inference-credential"), redact: (value: string) => value, compactText: (value: string) => value, log: vi.fn(), @@ -236,9 +239,9 @@ describe("native NVIDIA onboarding", () => { setupInference( "alpha", "nvidia/nemotron-3-super-120b-a12b", - "nvidia-prod", - "https://integrate.api.nvidia.com/v1", - "NVIDIA_INFERENCE_API_KEY", + profile.logicalProvider, + profile.endpoint, + profile.credentialEnv, null, [], { revalidateSandboxIdentity: () => undefined }, @@ -247,8 +250,8 @@ describe("native NVIDIA onboarding", () => { expect(updateProvider).toHaveBeenCalledWith( expect.objectContaining({ - providerName: "nemoclaw-nvidia-prod-v1", - credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "host-only-nvidia-credential" }], + providerName: profile.providerName, + credentials: [{ name: profile.credentialEnv, value: "host-only-inference-credential" }], config: [], }), ); @@ -260,12 +263,12 @@ describe("native NVIDIA onboarding", () => { expect(updateSandbox).toHaveBeenCalledWith( "alpha", expect.objectContaining({ - provider: "nvidia-prod", + provider: profile.logicalProvider, model: "nvidia/nemotron-3-super-120b-a12b", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", + profileId: profile.profileId, + providerName: profile.providerName, providerId: "provider-id", }, }), diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index c4b4a881de0..57f61709abe 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -21,12 +21,12 @@ import { } from "../inference/gateway-route-mutation-lock"; import { getManagedVllmProviderBinding, shouldFrontOllamaWithProxy } from "../inference/local"; import { - ensureNativeNvidiaProvider, - isNativeNvidiaProvider, - NVIDIA_HOSTED_CREDENTIAL_ENV, - normalizeNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "../inference/native-nvidia"; + nativeHostedProfile, + ensureNativeHostedProvider, + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../inference/native-hosted"; import { clearPendingOllamaModelCleanup, isLocalOllamaRouteOwner, @@ -665,7 +665,7 @@ export function createSetupInference( ); return deps.exitProcess(1); } - if (!isNativeNvidiaProvider(provider)) { + if (!isNativeHostedProvider(provider)) { const compatibility = deps.checkGatewayRouteCompatibility({ gatewayName, sandboxName, @@ -745,7 +745,7 @@ export function createSetupInference( | undefined; let hostLocalInferenceGatewayPortAuthority: number | undefined; let hostLocalInferenceRuntimeProviderId: string | undefined; - let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; + let nativeHostedProviderAttachment: NativeHostedProviderAttachment | undefined; const reserveRoute = (name: string, selectedProvider: string, selectedModel: string) => { if (routeReserved) return true; revalidateSandboxIdentity?.("reserve the sandbox inference route"); @@ -764,7 +764,7 @@ export function createSetupInference( reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(hostLocalInferenceProvenance && hostLocalInferenceGatewayPortAuthority !== undefined ? { gatewayPort: hostLocalInferenceGatewayPortAuthority } : {}), @@ -891,8 +891,21 @@ export function createSetupInference( } const setupSelectedProvider = async (): Promise => { + const recordedSandbox = sandboxName ? deps.getSandbox?.(sandboxName) : null; + const recordedAttachment = normalizeNativeHostedProviderAttachment( + recordedSandbox?.nativeHostedProviderAttachment, + ); + if ( + recordedSandbox && + isNativeHostedProvider(recordedSandbox.provider) && + !recordedAttachment + ) { + throw new Error( + `Sandbox '${sandboxName}' predates native hosted provider attachments. Recreate this beta sandbox before using native hosted inference; NemoClaw does not migrate existing beta sandboxes automatically.`, + ); + } if (provider === deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { - return inferenceProviders.setupHermesProviderInference( + const prepared = await inferenceProviders.setupHermesProviderInference( { sandboxName, model, @@ -901,6 +914,11 @@ export function createSetupInference( credentialEnv, hermesAuthMethod, hermesToolGateways, + nativeProvider: true, + expectedNativeProviderAttachment: + recordedAttachment?.profileId === nativeHostedProfile(provider)?.profileId + ? recordedAttachment + : undefined, }, { ...commonDeps, @@ -919,34 +937,29 @@ export function createSetupInference( lookup: deps.lookup, }, ); + if (!("ok" in prepared) || !prepared.ok) return prepared; } - if (isNativeNvidiaProvider(provider)) { - const resolvedCredentialEnv = credentialEnv || NVIDIA_HOSTED_CREDENTIAL_ENV; - const credentialValue = deps.hydrateCredentialEnv(resolvedCredentialEnv) || null; + if (isNativeHostedProvider(provider)) { + const profile = nativeHostedProfile(provider)!; + const resolvedCredentialEnv = credentialEnv || profile.credentialEnv; + const credentialValue = + provider === "hermes-provider" + ? null + : deps.hydrateCredentialEnv(resolvedCredentialEnv) || null; const providerAdapter = deps.providerAdapter; if (!providerAdapter) { - throw new Error("Native NVIDIA setup is missing its OpenShell provider adapter."); - } - const recordedSandbox = sandboxName ? deps.getSandbox?.(sandboxName) : null; - const recordedAttachment = normalizeNativeNvidiaProviderAttachment( - recordedSandbox?.nativeNvidiaProviderAttachment, - ); - if ( - recordedSandbox && - isNativeNvidiaProvider(recordedSandbox.provider) && - !recordedAttachment - ) { - throw new Error( - `Sandbox '${sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before using native NVIDIA inference; NemoClaw does not migrate existing beta sandboxes automatically.`, - ); + throw new Error("Native hosted setup is missing its OpenShell provider adapter."); } - nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ + nativeHostedProviderAttachment = await ensureNativeHostedProvider({ + profile, adapter: providerAdapter, - target: { kind: "selected" }, + target: { kind: "named", gatewayName }, credentialValue, reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, - ...(recordedAttachment ? { expected: recordedAttachment } : {}), + ...(recordedAttachment?.profileId === profile.profileId + ? { expected: recordedAttachment } + : {}), }); return null; } @@ -1125,7 +1138,7 @@ export function createSetupInference( try { const providerResult = await setupSelectedProvider(); if (providerResult) return providerResult; - if (!nativeNvidiaProviderAttachment) commonDeps.verifyInferenceRoute(provider, model); + if (!nativeHostedProviderAttachment) commonDeps.verifyInferenceRoute(provider, model); if (hostLocalRoute) { deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", @@ -1270,8 +1283,8 @@ export function createSetupInference( ); if (shouldLogSuccessfulRoute && "ok" in result) { deps.log( - isNativeNvidiaProvider(provider) - ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` + isNativeHostedProvider(provider) + ? ` ✓ Native hosted provider ready: ${provider} / ${model}` : ` ✓ Inference route set: ${provider} / ${model}`, ); } diff --git a/src/lib/registry-recovery-seeded-paths.test.ts b/src/lib/registry-recovery-seeded-paths.test.ts index e7ad3069248..ddb395654c6 100644 --- a/src/lib/registry-recovery-seeded-paths.test.ts +++ b/src/lib/registry-recovery-seeded-paths.test.ts @@ -256,7 +256,7 @@ describe("recoverRegistryEntries seeded recovery paths", () => { }); it("blocks route mutation after seeded recovery persists a live row without route metadata (#6315)", async () => { - mockRegistryState.sandboxes.gamma = gammaEntry([]); + mockRegistryState.sandboxes.gamma = { ...gammaEntry([]), provider: "ollama-local" }; mockRegistryState.defaultSandbox = "gamma"; vi.mocked(captureOpenshell).mockReturnValue({ output: "recovered-live Ready", @@ -277,7 +277,7 @@ describe("recoverRegistryEntries seeded recovery paths", () => { }); await expect( runInferenceSet( - { provider: "openrouter", model: "nvidia/model-b", sandboxName: "gamma" }, + { provider: "ollama-local", model: "nvidia/model-b", sandboxName: "gamma" }, deps, ), ).rejects.toMatchObject({ diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 33bb4727e3d..02016ca7fcc 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -193,6 +193,10 @@ function stageLegacySandboxBuildContext( path.join(rootDir, "src", "lib", "providerless-inference.ts"), path.join(buildCtx, "src", "lib", "providerless-inference.ts"), ); + fs.cpSync( + path.join(rootDir, "src/lib/inference/native-hosted/openrouter-headers.ts"), + path.join(buildCtx, "src/lib/inference/native-hosted/openrouter-headers.ts"), + ); stageManagedStartupRuntimeSources(rootDir, buildCtx); normalizeReadModesForDockerCopy(path.join(buildCtx, "src")); fs.rmSync(path.join(buildCtx, "nemoclaw", "node_modules"), { @@ -364,6 +368,10 @@ function stageOptimizedSandboxBuildContext( path.join(rootDir, "src", "lib", "providerless-inference.ts"), path.join(buildCtx, "src", "lib", "providerless-inference.ts"), ); + fs.cpSync( + path.join(rootDir, "src/lib/inference/native-hosted/openrouter-headers.ts"), + path.join(buildCtx, "src/lib/inference/native-hosted/openrouter-headers.ts"), + ); stageManagedStartupRuntimeSources(rootDir, buildCtx); normalizeReadModesForDockerCopy(path.join(buildCtx, "src")); fs.copyFileSync( diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index 1454305c76c..64c963726d3 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -39,6 +39,66 @@ afterEach(() => { }); describe("sandbox registry normalization", () => { + it("reads Slice 1 NVIDIA receipts and persists the generalized field without losing identity (#12589)", async () => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "original-provider-id", + }; + const { home, registry } = await loadRegistryDocument({ + sandboxes: { + alpha: { name: "alpha", provider: "nvidia-prod", nativeNvidiaProviderAttachment: receipt }, + }, + }); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual(receipt); + registry.updateSandbox("alpha", { model: "next-model" }); + const saved = JSON.parse( + fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8"), + ); + expect(saved.sandboxes.alpha.nativeHostedProviderAttachment).toEqual(receipt); + expect(saved.sandboxes.alpha).not.toHaveProperty("nativeNvidiaProviderAttachment"); + registry.updateSandbox("alpha", { nativeHostedProviderAttachment: undefined }); + expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeHostedProviderAttachment"); + }); + + it("retains pending native cleanup through reload until confirmed removal (#12589)", async () => { + const pending = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "old-provider", + }; + const registry = await loadRegistryWith({ + alpha: { + name: "alpha", + provider: "ollama-local", + pendingNativeHostedProviderDetach: pending, + }, + }); + registry.updateSandbox("alpha", { model: "next-model" }); + expect(registry.load().sandboxes.alpha.pendingNativeHostedProviderDetach).toEqual(pending); + registry.updateSandbox("alpha", { pendingNativeHostedProviderDetach: undefined }); + expect(registry.load().sandboxes.alpha).not.toHaveProperty("pendingNativeHostedProviderDetach"); + }); + + it("rejects a pending cleanup receipt with a foreign provider name (#12589)", async () => { + const registry = await loadRegistryWith({ + alpha: { + name: "alpha", + pendingNativeHostedProviderDetach: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "foreign", + providerId: "old", + }, + }, + }); + expect(() => registry.getSandbox("alpha")).toThrow( + "Invalid pending native inference detach receipt", + ); + }); + it("persists incomplete OpenClaw synchronization until explicit completion", async () => { const registry = await loadRegistryWith({ alpha: { name: "alpha", agent: "openclaw", provider: "nvidia-prod", model: "old" }, diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index c38223f780b..f71c8ac0ec0 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -8,7 +8,7 @@ import { inferenceSelectionRegistryFields, normalizeInferenceSelection, } from "../inference/selection"; -import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia"; +import { normalizeNativeHostedProviderAttachment } from "../inference/native-hosted"; import { parseServingProfileProvenance } from "../inference/serving/profile-provenance"; import { normalizeToolDisclosure } from "../tool-disclosure"; import { @@ -477,10 +477,10 @@ export function registerSandbox( ); } } - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment, ); - if (entry.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + if (entry.nativeHostedProviderAttachment !== undefined && !nativeHostedProviderAttachment) { throw new Error( "Cannot register a sandbox with an invalid native NVIDIA provider attachment", ); @@ -535,7 +535,7 @@ export function registerSandbox( : undefined, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), lifecycleGeneration: entry.lifecycleGeneration, lifecycleLiveIdentityFingerprint: entry.lifecycleLiveIdentityFingerprint, messaging: cloneSandboxMessagingState(entry.messaging), @@ -586,7 +586,7 @@ type SandboxInferenceRouteReservation = Pick< reservationSessionId?: string; hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; - nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; }; interface SandboxInferenceRouteReservationOptions { @@ -628,10 +628,10 @@ export function reserveSandboxInferenceRoute( ) return false; const normalized = normalizeInferenceSelection(route); - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - route.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + route.nativeHostedProviderAttachment, ); - if (route.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + if (route.nativeHostedProviderAttachment !== undefined && !nativeHostedProviderAttachment) { throw new Error("Cannot reserve invalid native NVIDIA provider attachment identity"); } const provenance = cloneSandboxHostLocalInferenceProvenance(route.hostLocalInferenceProvenance); @@ -692,8 +692,8 @@ export function reserveSandboxInferenceRoute( route.hostLocalInferenceProvenance ?? existing.hostLocalInferenceProvenance, ) && isDeepStrictEqual( - existing.nativeNvidiaProviderAttachment, - nativeNvidiaProviderAttachment ?? existing.nativeNvidiaProviderAttachment, + existing.nativeHostedProviderAttachment, + nativeHostedProviderAttachment ?? existing.nativeHostedProviderAttachment, ) && isDeepStrictEqual( normalizeInferenceSelection(existing), @@ -735,7 +735,7 @@ export function reserveSandboxInferenceRoute( ? { hostLocalInferenceReceipt: route.hostLocalInferenceReceipt } : {}), ...(provenance ? { hostLocalInferenceProvenance: provenance } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), gatewayName: route.gatewayName, gatewayPort: route.gatewayPort ?? diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index a4efa15b2da..71758a1fd7c 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -1,3 +1,4 @@ +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 @@ -168,6 +169,16 @@ function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { } function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { + const rawAttachment = + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment; + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); + if (rawAttachment !== undefined && !nativeHostedProviderAttachment) + throw new Error("Invalid native inference provider receipt"); + const pendingNativeHostedProviderDetach = normalizeNativeHostedProviderAttachment( + entry.pendingNativeHostedProviderDetach, + ); + if (entry.pendingNativeHostedProviderDetach !== undefined && !pendingNativeHostedProviderDetach) + throw new Error("Invalid pending native inference detach receipt"); const messaging = cloneSandboxMessagingState(entry.messaging); const workload = cloneSandboxWorkloadReceiptOrThrow(entry.workload, "load"); const hostLocalInferenceReceipt = cloneHostLocalInferenceReceiptOrThrow( @@ -186,6 +197,9 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { const deferredN1xManagedVllmAccepted = normalizeDeferredN1xManagedVllmAcceptance(entry, "load"); const policyEntry = normalizeSandboxPolicyAttribution(entry); const { + nativeNvidiaProviderAttachment: _legacyNativeNvidiaAttachment, + nativeHostedProviderAttachment: _nativeHostedAttachment, + pendingNativeHostedProviderDetach: _pendingNativeHostedProviderDetach, cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, workload: _workload, @@ -198,6 +212,8 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { } = policyEntry as SandboxEntry & { cuaRuntimeReadiness?: unknown; mcp?: unknown }; return { ...rest, + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), + ...(pendingNativeHostedProviderDetach ? { pendingNativeHostedProviderDetach } : {}), ...(workload ? { workload } : {}), ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), @@ -227,6 +243,16 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { livePhase?: string | null; providerCredentialHashes?: unknown; }; + const rawAttachment = + durable.nativeHostedProviderAttachment ?? durable.nativeNvidiaProviderAttachment; + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); + if (rawAttachment !== undefined && !nativeHostedProviderAttachment) + throw new Error("Invalid native inference provider receipt"); + const pendingNativeHostedProviderDetach = normalizeNativeHostedProviderAttachment( + durable.pendingNativeHostedProviderDetach, + ); + if (durable.pendingNativeHostedProviderDetach !== undefined && !pendingNativeHostedProviderDetach) + throw new Error("Invalid pending native inference detach receipt"); const messaging = serializeSandboxMessagingStateForDisk(durable.messaging); const workload = cloneSandboxWorkloadReceiptOrThrow(durable.workload, "save"); const hostLocalInferenceReceipt = cloneHostLocalInferenceReceiptOrThrow( @@ -245,6 +271,9 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { const deferredN1xManagedVllmAccepted = normalizeDeferredN1xManagedVllmAcceptance(durable, "save"); const policyEntry = normalizeSandboxPolicyAttribution(durable); const { + nativeNvidiaProviderAttachment: _legacyNativeNvidiaAttachment, + nativeHostedProviderAttachment: _nativeHostedAttachment, + pendingNativeHostedProviderDetach: _pendingNativeHostedProviderDetach, cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, workload: _workload, @@ -257,6 +286,8 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { } = policyEntry as SandboxEntry & { cuaRuntimeReadiness?: unknown; mcp?: unknown }; return { ...rest, + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), + ...(pendingNativeHostedProviderDetach ? { pendingNativeHostedProviderDetach } : {}), ...(rest.dashboardPort === 0 ? { dashboardPort: null } : {}), ...(workload ? { workload } : {}), ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 4ac16f5351b..a74d78ef0fb 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -4,7 +4,7 @@ import { isDeepStrictEqual } from "node:util"; import { normalizeInferenceSelection, type InferenceSelection } from "../../inference/selection"; -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; import { isWebSearchProvider } from "../../inference/web-search/provider"; import { normalizePendingSandboxCreateIdentity } from "./pending-create-identity"; import type { PendingSandboxCreateIdentity, SandboxEntry } from "./types"; @@ -22,7 +22,7 @@ const ROUTE_RESERVATION_KEYS = new Set([ "lifecycleLiveIdentityFingerprint", "model", "name", - "nativeNvidiaProviderAttachment", + "nativeHostedProviderAttachment", "openshellDriver", "pendingRouteReservation", "pendingCreateIdentity", @@ -83,8 +83,8 @@ function validCarriedRouteMetadata(entry: SandboxEntry): boolean { return false; } if ( - entry.nativeNvidiaProviderAttachment !== undefined && - !normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) + entry.nativeHostedProviderAttachment !== undefined && + !normalizeNativeHostedProviderAttachment(entry.nativeHostedProviderAttachment) ) { return false; } diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 93679f018e0..4766bafa373 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { InferenceSelection } from "../../inference/selection"; -import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import type { NativeHostedProviderAttachment } from "../../inference/native-hosted"; import type { ServingProfileProvenance } from "../../inference/serving/types"; import type { WebSearchProvider } from "../../inference/web-search"; import type { DcodeAutoApprovalMode } from "../../onboard/dcode-auto-approval"; @@ -134,7 +134,11 @@ export interface SandboxEntry extends Partial { /** Canonical provider-neutral receipt for an out-of-sandbox inference runtime. */ hostLocalInferenceReceipt?: string | null; /** Exact OpenShell provider identity attached for native NVIDIA hosted inference. */ - nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + nativeHostedProviderAttachment?: NativeHostedProviderAttachment; + /** Previous native access retained until provider-switch cleanup is confirmed. */ + pendingNativeHostedProviderDetach?: NativeHostedProviderAttachment; + /** Legacy Slice 1 receipt; normalized when loaded. */ + nativeNvidiaProviderAttachment?: NativeHostedProviderAttachment; /** Explicit hidden-lifecycle provenance; absence keeps llama.cpp on its legacy path. */ hostLocalInferenceProvenance?: SandboxHostLocalInferenceProvenance; /** Explicit Deferred N1x managed-vLLM choice retained after successful onboarding. */ diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index b37fe817516..7bcdcd27157 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -30,7 +30,7 @@ import type { DashboardDeliveryChain } from "./dashboard/contract"; import { listMessagingChannelsWithoutCredentials } from "./messaging/channels"; import { retryUntilAsync } from "./core/retry"; -import { isNativeNvidiaProvider } from "./inference/native-nvidia"; +import { isNativeHostedProvider } from "./inference/native-hosted"; import { buildCustomOpenClawRuntimeFailureHints, classifyOpenClawRuntimeFailure, @@ -896,7 +896,7 @@ export async function probeOnboardInferenceInvocation( provider, model, preferredInferenceApi: context.preferredInferenceApi, - ...(isNativeNvidiaProvider(provider) ? { nativeProvider: true } : {}), + ...(isNativeHostedProvider(provider) ? { nativeProvider: true } : {}), }); return result.ok ? { ok: true } : { ok: false, detail: result.detail }; } diff --git a/test/agents/deepagents/langchain-deepagents-code-config.test.ts b/test/agents/deepagents/langchain-deepagents-code-config.test.ts index 4e7c6af6670..96d8909fc63 100644 --- a/test/agents/deepagents/langchain-deepagents-code-config.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-config.test.ts @@ -114,6 +114,9 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).toContain('default = "openrouter:nvidia/nemotron-3-ultra-550b-a55b"'); expect(config).toContain("[models.providers.openrouter]"); + expect(config).toContain("[models.providers.openrouter.params.default_headers]"); + expect(config).toContain('"HTTP-Referer" = "https://www.nvidia.com/nemoclaw/"'); + expect(config).toContain('"X-OpenRouter-Title" = "NVIDIA NemoClaw"'); expect(config).toContain('models = ["nvidia/nemotron-3-ultra-550b-a55b"]'); expect(config).toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); expect(config).toContain('base_url = "https://inference.local/v1"'); @@ -135,6 +138,9 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).toContain('default = "openrouter:nvidia/nemotron-3-ultra-550b-a55b"'); expect(config).toContain("[models.providers.openrouter]"); + expect(config).toContain("[models.providers.openrouter.params.default_headers]"); + expect(config).toContain('"HTTP-Referer" = "https://www.nvidia.com/nemoclaw/"'); + expect(config).toContain('"X-OpenRouter-Title" = "NVIDIA NemoClaw"'); expect(config).toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); expect(config).toContain('base_url = "https://inference.local/v1"'); expect(config).toContain( diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index 02e7b664d32..f91e212f5bd 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -309,7 +309,7 @@ test( artifactName: "hermes-native-nvidia-provider-attachment", env: env(), logicalProvider: SWITCH_PROVIDER, - receipt: state.registry.sandboxes?.[SANDBOX_NAME]?.nativeNvidiaProviderAttachment, + receipt: state.registry.sandboxes?.[SANDBOX_NAME]?.nativeHostedProviderAttachment, sandbox, sandboxName: SANDBOX_NAME, }); diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index bc17bbc313f..750963a7ef4 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -136,7 +136,7 @@ interface SandboxRegistry { credentialEnv?: unknown; preferredInferenceApi?: unknown; nimContainer?: unknown; - nativeNvidiaProviderAttachment?: unknown; + nativeHostedProviderAttachment?: unknown; } >; } @@ -593,7 +593,7 @@ async function assertRegistryAndSession( artifactName: "native-nvidia-provider-attachment-after-switch", env: commandEnv(home), logicalProvider: SWITCH_PROVIDER, - receipt: sandbox?.nativeNvidiaProviderAttachment, + receipt: sandbox?.nativeHostedProviderAttachment, sandbox: options.sandbox, sandboxName: SANDBOX_NAME, }), diff --git a/test/generation/generate-hermes-config.test.ts b/test/generation/generate-hermes-config.test.ts index aa00de9c610..ecce2b102ea 100644 --- a/test/generation/generate-hermes-config.test.ts +++ b/test/generation/generate-hermes-config.test.ts @@ -253,6 +253,21 @@ function copyConfigGeneratorFixture(fixtureRoot: string): string { path.join(import.meta.dirname, "../..", "src", "lib", "providerless-inference.ts"), path.join(fixtureRoot, "src", "lib", "providerless-inference.ts"), ); + fs.mkdirSync(path.join(fixtureRoot, "src", "lib", "inference", "native-hosted"), { + recursive: true, + }); + fs.copyFileSync( + path.join( + import.meta.dirname, + "../..", + "src", + "lib", + "inference", + "native-hosted", + "openrouter-headers.ts", + ), + path.join(fixtureRoot, "src", "lib", "inference", "native-hosted", "openrouter-headers.ts"), + ); return fixtureScriptPath; } diff --git a/test/generation/generate-openclaw-config-llamacpp-compat.test.ts b/test/generation/generate-openclaw-config-llamacpp-compat.test.ts index d3ce4b6b9d0..e286ab1db16 100644 --- a/test/generation/generate-openclaw-config-llamacpp-compat.test.ts +++ b/test/generation/generate-openclaw-config-llamacpp-compat.test.ts @@ -37,3 +37,14 @@ describe("managed llama.cpp OpenClaw compatibility", () => { expect(model.compat?.toolSchemaProfile).toBeUndefined(); }); }); + +describe("managed OpenRouter attribution", () => { + it("adds static attribution only for OpenRouter requests", () => { + const config = buildLlamaCppConfig("openrouter-api"); + expect(config.models.providers.inference.headers).toEqual({ + "HTTP-Referer": "https://www.nvidia.com/nemoclaw/", + "X-OpenRouter-Title": "NVIDIA NemoClaw", + }); + expect(buildLlamaCppConfig("gemini-api").models.providers.inference.headers).toBeUndefined(); + }); +}); diff --git a/test/generation/providerless-agent-config.test.ts b/test/generation/providerless-agent-config.test.ts index b7230219aac..9926be76527 100644 --- a/test/generation/providerless-agent-config.test.ts +++ b/test/generation/providerless-agent-config.test.ts @@ -268,7 +268,7 @@ describe.each(["openclaw", "hermes"])("providerless %s configuration", (a ), ).toBe(false); }); - it("leaves generated configuration absent when the later route update fails", async () => { + it("leaves generated configuration absent when native provider attachment fails", async () => { const generated = generate(agent, dockerEnvironment(agent)); expect(generated.result.status, generated.result.stderr).toBe(0); const config = generated.read(); @@ -276,7 +276,10 @@ describe.each(["openclaw", "hermes"])("providerless %s configuration", (a config, entry: { name: "alpha", agent, provider: null, model: null }, target: agent === "hermes" ? HERMES_TARGET : OPENCLAW_TARGET, - openshellStatus: 1, + }); + deps.providerAdapter.attachProvider = async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "sandbox missing" }, }); await expect( runInferenceSet( diff --git a/test/helpers/onboard-split-context.ts b/test/helpers/onboard-split-context.ts index 2afd238e83a..e52cc190a3a 100644 --- a/test/helpers/onboard-split-context.ts +++ b/test/helpers/onboard-split-context.ts @@ -3,6 +3,9 @@ import assert from "node:assert/strict"; import path from "node:path"; +import { vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../../src/lib/adapters/openshell/provider-adapter"; +import { nativeHostedProfile } from "../../src/lib/inference/native-hosted/profiles"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { createDirectSetupInferenceHarnessFactory } from "../support/setup-inference-test-harness.js"; @@ -100,3 +103,46 @@ export const repoRoot = path.join(import.meta.dirname, "../.."); export const onboardScriptMocksPath = JSON.stringify( path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), ); + +/** Stateful native provider transport, isolated from the developer gateway. */ +export function createNativeSetupProviderAdapter(provider: string, initiallyPresent = true) { + const profile = nativeHostedProfile(provider)!; + let present = initiallyPresent; + const unexpected = async (): Promise => { + throw new Error("Unexpected provider operation"); + }; + const adapter = { + importProviderProfile: vi.fn(() => ({ + ok: true, + })), + getProvider: vi.fn(async ({ providerName }) => { + assert.equal(providerName, profile.providerName); + return present + ? { + ok: true, + value: { + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], + configKeys: [], + revision: { id: "fixture-native-id", resourceVersion: 1 }, + }, + } + : { ok: false, error: { kind: "command", reason: "not_found", message: "not found" } }; + }), + createProvider: vi.fn(async () => { + present = true; + return { ok: true }; + }), + updateProvider: vi.fn(async () => ({ ok: true })), + listProviders: unexpected, + inspectProviderProfile: unexpected, + deleteProvider: unexpected, + detachProvider: unexpected, + attachProvider: unexpected, + listProviderAttachments: unexpected, + configureProviderRefresh: unexpected, + getProviderRefreshStatus: unexpected, + } satisfies OpenShellProviderAdapter; + return adapter; +} diff --git a/test/onboarding/onboard-inference-failure-paths.test.ts b/test/onboarding/onboard-inference-failure-paths.test.ts index e011a6c07ce..8590de47267 100644 --- a/test/onboarding/onboard-inference-failure-paths.test.ts +++ b/test/onboarding/onboard-inference-failure-paths.test.ts @@ -113,11 +113,20 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:1", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:1"); - expect(harness.errors).toEqual([" Unsupported provider configuration: openai-api"]); + expect(harness.errors).toEqual([" Unsupported provider configuration: compatible-endpoint"]); expect(exitProcess).toHaveBeenCalledOnce(); expect(exitProcess).toHaveBeenCalledWith(1); expect(setupBedrockRuntimeInference).not.toHaveBeenCalled(); @@ -142,18 +151,27 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:1", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:1"); expect(setupBedrockRuntimeInference).toHaveBeenCalledOnce(); - expect(hydrateCredentialEnv).toHaveBeenCalledWith("OPENAI_API_KEY"); + expect(hydrateCredentialEnv).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); expect(upsertProvider).not.toHaveBeenCalled(); expect(promptValidationRecovery).not.toHaveBeenCalled(); expect(exitProcess).toHaveBeenCalledOnce(); expect(exitProcess).toHaveBeenCalledWith(1); expect(harness.errors).toEqual([ - " A host credential is required to configure provider 'openai-api'.", + " A host credential is required to configure provider 'compatible-endpoint'.", ]); expectNoPostFailureSideEffects(harness); }); @@ -179,19 +197,28 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:23", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:23"); expect(setupBedrockRuntimeInference).toHaveBeenCalledOnce(); - expect(hydrateCredentialEnv).toHaveBeenCalledWith("OPENAI_API_KEY"); + expect(hydrateCredentialEnv).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); expect(upsertProvider).toHaveBeenCalledOnce(); expect(upsertProvider).toHaveBeenCalledWith( - "openai-api", + "compatible-endpoint", "openai", - "OPENAI_API_KEY", + "COMPATIBLE_API_KEY", expect.any(String), - { OPENAI_API_KEY: "openai-secret" }, + { COMPATIBLE_API_KEY: "openai-secret" }, "nemoclaw", { revalidateSandboxIdentity: expect.any(Function) }, ); @@ -227,9 +254,18 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:37", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:37"); expect(setupBedrockRuntimeInference).toHaveBeenCalledOnce(); expect(upsertProvider).toHaveBeenCalledOnce(); @@ -240,7 +276,7 @@ describe("setupInference dependency failures", () => { expect(harness.errors.join("\n")).toContain("route failed"); expect(harness.errors.join("\n")).not.toContain(NVIDIA_REDACTION_CANARY); expectNoPostFailureSideEffects(harness, [ - "inference set -g nemoclaw --no-verify --provider openai-api --model gpt-test", + "inference set -g nemoclaw --no-verify --provider compatible-endpoint --model gpt-test --timeout 180", ]); }); @@ -860,7 +896,7 @@ describe("setupInference dependency failures", () => { ]); }); - it("uses an injected Hermes DNS lookup before rejecting an unpinnable HTTPS endpoint", async () => { + it("rejects noncanonical native Hermes endpoints before DNS lookup", async () => { const exitProcess = createInjectedExit(); const lookup = vi.fn>(async () => [ { address: "8.8.8.8", family: 4 }, @@ -874,9 +910,9 @@ describe("setupInference dependency failures", () => { "hermes-provider", "https://api.public.example.test/v1", ), - ).rejects.toThrow("DNS-backed HTTPS URLs are not supported"); + ).rejects.toThrow("native inference requires its canonical endpoint"); - expect(lookup).toHaveBeenCalledWith("api.public.example.test", { all: true }); + expect(lookup).not.toHaveBeenCalled(); expect(exitProcess).not.toHaveBeenCalled(); expectNoPostFailureSideEffects(harness); }); diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 4e4c4bf15b0..46fa583241b 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import { createNativeSetupProviderAdapter } from "../helpers/onboard-split-context"; import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { @@ -38,13 +39,10 @@ function expectCommandsTargetOnly(commands: Array<{ command: string }>): void { } describe("onboarding inference gateway scope", () => { - it("targets a non-default gateway for provider creation, route apply, and verification", async () => { + it("targets a non-default gateway for native provider creation and verification", async () => { await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { - const harness = createHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" ? { status: 1 } : undefined, - }); - + const providerAdapter = createNativeSetupProviderAdapter("openai-api", false); + const harness = createHarness({ overrides: { providerAdapter } }); await expect( harness.setupInference( "test-box", @@ -57,14 +55,25 @@ describe("onboarding inference gateway scope", () => { { gatewayName: GATEWAY }, ), ).resolves.toEqual({ ok: true }); - - expect(harness.commands.map(({ command }) => command)).toEqual([ - `provider get -g ${GATEWAY} openai-api`, - `provider create -g ${GATEWAY} --name openai-api --type openai --credential OPENAI_API_KEY --config OPENAI_BASE_URL=https://api.openai.com/v1`, - `inference set -g ${GATEWAY} --no-verify --provider openai-api --model gpt-test`, - ]); - expect(harness.verifyInferenceRoute).toHaveBeenCalledWith(GATEWAY, "openai-api", "gpt-test"); - expectCommandsTargetOnly(harness.commands); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + nativeHostedProviderAttachment: expect.objectContaining({ + providerName: "nemoclaw-openai-api-v1", + providerId: "fixture-native-id", + }), + gatewayName: GATEWAY, + }), + ); + expect(providerAdapter.createProvider).toHaveBeenCalledOnce(); + const targetRequest = expect.objectContaining({ + target: { kind: "named", gatewayName: GATEWAY }, + }); + expect(providerAdapter.importProviderProfile.mock.calls).toEqual([[targetRequest]]); + expect(providerAdapter.getProvider.mock.calls).toEqual([[targetRequest], [targetRequest]]); + expect(providerAdapter.createProvider.mock.calls).toEqual([[targetRequest]]); + expect(harness.commands).toEqual([]); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); }); }); diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 62c38220305..7af6174d722 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { createNativeProviderCommandRuntime } from "../support/native-provider-command-runtime"; import { describe, expect, it, vi } from "vitest"; import { @@ -20,6 +21,7 @@ import { bedrockRuntimeOnboard, type CommandEntry, createDirectSetupInferenceHarness, + createNativeSetupProviderAdapter, parseStdoutJson, stripMessagingEnv, } from "../helpers/onboard-split-context"; @@ -28,29 +30,19 @@ import { withProcessEnv, } from "../support/setup-inference-test-harness.js"; -const HERMES_OAUTH_PROVIDER_METADATA = [ - "Name: hermes-provider", +const COMPATIBLE_PROVIDER_METADATA = [ + "Name: compatible-endpoint", "Type: openai", - "Credential keys: OPENAI_API_KEY", + "Credential keys: COMPATIBLE_API_KEY", "Config keys: OPENAI_BASE_URL", "", ].join("\n"); -const HERMES_API_KEY_PROVIDER_METADATA = [ - "Name: hermes-provider", - "Type: openai", - "Credential keys: NOUS_API_KEY", - "Config keys: OPENAI_BASE_URL", - "", -].join("\n"); - -const OPENAI_API_PROVIDER_METADATA = [ - "Name: openai-api", - "Type: openai", - "Credential keys: OPENAI_API_KEY", - "Config keys: OPENAI_BASE_URL", - "", -].join("\n"); +const { + run: hermesNativeCommand, + profileJson: HERMES_NATIVE_PROFILE_JSON, + metadata: HERMES_API_KEY_PROVIDER_METADATA, +} = createNativeProviderCommandRuntime("hermes-provider", true); describe("onboard helpers", () => { it("reuses a registered Hermes Provider without re-collecting host credentials", async () => { @@ -61,30 +53,27 @@ describe("onboard helpers", () => { }, async () => { const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: HERMES_OAUTH_PROVIDER_METADATA, stderr: "" } - : undefined, - overrides: { isNonInteractive: () => true }, + runOpenshell: hermesNativeCommand, + overrides: { + isNonInteractive: () => true, + providerAdapter: createNativeSetupProviderAdapter("hermes-provider"), + }, }); await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", "hermes-provider", - "https://8.8.8.8/v1", + "https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY", "oauth", ); const commands = harness.commands; - assert.equal(commands.length, 3); + assert.equal(commands.length, 2); assert.equal(commands[0].command, "provider list -g nemoclaw"); - assert.equal(commands[1].command, "provider get -g nemoclaw hermes-provider"); - assert.match( - commands[2].command, - /inference set -g nemoclaw --no-verify --provider hermes-provider/, - ); + assert.equal(commands[1].command, "provider get -g nemoclaw nemoclaw-hermes-provider-v1"); + assert.ok(!commands.some((entry) => entry.command.startsWith("inference set"))); assert.ok(!commands.some((entry) => entry.command.startsWith("gateway select"))); assert.ok(!commands.some((entry) => /provider (create|update)/.test(entry.command))); assert.ok(!commands.some((entry) => entry.env?.NOUS_API_KEY || entry.env?.OPENAI_API_KEY)); @@ -338,8 +327,8 @@ try { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); - const providerGet = "provider get -g nemoclaw hermes-provider"; - if (normalized === providerGet || normalized.endsWith(" " + providerGet)) { + if (normalized.includes("provider profile") && normalized.includes("export")) return { status: 0, stdout: ${JSON.stringify(HERMES_NATIVE_PROFILE_JSON)}, stderr: "" }; + if (normalized.includes("provider get") && normalized.includes("nemoclaw-hermes-provider-v1")) { return { status: 0, stdout: hermesApiKeyProviderMetadata, stderr: "" }; } return { status: 0, stdout: "", stderr: "" }; @@ -367,6 +356,7 @@ registry.getSandbox = (name) => provider: "hermes-provider", model: "moonshotai/kimi-k2.6", hermesToolGateways: [], + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-hermes-inference-v1", providerName: "nemoclaw-hermes-provider-v1", providerId: "11111111-2222-4333-8444-555555555555" }, } : null; registry.reserveSandboxInferenceRoute = (name, updates) => { @@ -441,7 +431,7 @@ const resumeSession = onboardSession.createSession({ sandboxName: null, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", - endpointUrl: "https://8.8.8.8/v1", + endpointUrl: "https://inference-api.nousresearch.com/v1", credentialEnv: "NOUS_API_KEY", hermesAuthMethod: "api_key", hermesToolGateways: [], @@ -527,11 +517,12 @@ const { onboard } = require(${onboardPath}); "resume should prompt for the missing sandbox name before Hermes inference reconciliation", ); assert.ok( - payload.commands.some((entry) => - /inference set -g nemoclaw --no-verify --provider hermes-provider/.test(entry.command), + payload.commands.some( + (entry) => entry.command.includes("provider profile") && entry.command.includes("export"), ), - "resume should reach openshell inference set", + "resume should reconcile native inference", ); + assert.ok(!payload.commands.some((entry) => entry.command.includes("inference set"))); assert.ok(!payload.commands.some((entry) => /provider (create|update)/.test(entry.command))); assert.equal( payload.inferenceSessionSandboxName, @@ -558,36 +549,33 @@ const { onboard } = require(${onboardPath}); }, async () => { const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: HERMES_OAUTH_PROVIDER_METADATA, stderr: "" } - : undefined, - overrides: { isNonInteractive: () => true }, + runOpenshell: hermesNativeCommand, + overrides: { + isNonInteractive: () => true, + providerAdapter: createNativeSetupProviderAdapter("hermes-provider"), + }, }); await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", "hermes-provider", - "https://8.8.8.8/v1", + "https://inference-api.nousresearch.com/v1", "NOUS_API_KEY", "api_key", ); const update = harness.commands.find((entry) => - /provider update -g nemoclaw hermes-provider/.test(entry.command), + /provider update -g nemoclaw nemoclaw-hermes-provider-v1/.test(entry.command), ); assert.ok(update); - assert.match(update.command, /--credential NOUS_API_KEY/); - assert.equal(update.env?.NOUS_API_KEY, "nous-host-secret"); + assert.match(update.command, /--credential OPENAI_API_KEY/); + assert.equal(update.env?.OPENAI_API_KEY, "nous-host-secret"); assert.ok( !harness.commands.some((entry) => /nous-host-secret/.test(entry.command)), "shell credential value must not appear in argv", ); - assert.match( - harness.commands.at(-1)?.command || "", - /inference set -g nemoclaw --no-verify --provider hermes-provider/, - ); + assert.ok(!harness.commands.some((entry) => entry.command.startsWith("inference set"))); }, ); }); @@ -900,15 +888,10 @@ const { isOpenclawReady } = require(${onboardPath}); } }); - it("uses native Anthropic provider creation without embedding the secret in argv", async () => { + it("creates the native Anthropic profile provider without changing the shared route", async () => { await withProcessEnv({ ANTHROPIC_API_KEY: "sk-ant-TEST-NOT-A-REAL-VALUE" }, async () => { - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 1, stdout: "", stderr: "" } - : undefined, - }); - + const providerAdapter = createNativeSetupProviderAdapter("anthropic-prod", false); + const harness = createDirectSetupInferenceHarness({ overrides: { providerAdapter } }); await harness.setupInference( "test-box", "claude-sonnet-4-5", @@ -916,52 +899,62 @@ const { isOpenclawReady } = require(${onboardPath}); "https://api.anthropic.com", "ANTHROPIC_API_KEY", ); - - const commands = harness.commands; - assert.equal(commands.length, 3); - assert.match(commands[0].command, /^provider get -g nemoclaw /); - assert.match(commands[1].command, /^provider create -g nemoclaw /); - assert.match(commands[1].command, /--type anthropic/); - assert.match(commands[1].command, /--credential ANTHROPIC_API_KEY/); - assert.doesNotMatch(commands[1].command, /sk-ant-TEST-NOT-A-REAL-VALUE/); - assert.match(commands[2].command, /^inference set -g nemoclaw /); - assert.match(commands[2].command, /--provider anthropic-prod/); + expect(providerAdapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + name: "nemoclaw-anthropic-prod-v1", + type: "nemoclaw-anthropic-inference-v1", + credentials: [{ name: "ANTHROPIC_API_KEY", value: "sk-ant-TEST-NOT-A-REAL-VALUE" }], + config: [], + }), + ); + expect(harness.commands).toEqual([]); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + nativeHostedProviderAttachment: expect.objectContaining({ + providerId: "fixture-native-id", + }), + }), + ); }); }); it("updates OpenAI-compatible providers without passing an unsupported --type flag", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" } + ? { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" } : undefined, }); await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, ); const commands = harness.commands; assert.equal(commands.length, 3); assert.match(commands[0].command, /^provider get -g nemoclaw /); - assert.match(commands[1].command, /^provider update -g nemoclaw openai-api/); + assert.match(commands[1].command, /^provider update -g nemoclaw compatible-endpoint/); assert.doesNotMatch(commands[1].command, /--type/); assert.match(commands[2].command, /^inference set -g nemoclaw --no-verify/); }); }); it("re-prompts for credentials when openshell inference set fails with authorization errors", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-bad" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-bad" }, async () => { const commandRouter = createDirectCommandRouter([ { name: "provider-get", matches: (command) => command.startsWith("provider get"), results: [ - { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }, - { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }, + { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" }, + { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" }, ], }, { @@ -974,7 +967,7 @@ const { isOpenclawReady } = require(${onboardPath}); runOpenshell: commandRouter.runOpenshell, overrides: { promptValidationRecovery: async () => { - process.env.OPENAI_API_KEY = "sk-good"; + process.env.COMPATIBLE_API_KEY = "sk-good"; return "retry"; }, }, @@ -984,30 +977,33 @@ const { isOpenclawReady } = require(${onboardPath}); await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, ); } finally { error.mockRestore(); } - assert.equal(process.env.OPENAI_API_KEY, "sk-good"); + assert.equal(process.env.COMPATIBLE_API_KEY, "sk-good"); assert.equal(commandRouter.callCount("inference-set"), 2); const providerEnvs = harness.commands .filter((entry) => entry.command.includes("provider")) - .map((entry) => entry.env?.OPENAI_API_KEY) + .map((entry) => entry.env?.COMPATIBLE_API_KEY) .filter(Boolean); assert.deepEqual(providerEnvs, ["sk-bad", "sk-good"]); }); }); it("returns control to provider selection when inference apply recovery chooses back", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const commandRouter = createDirectCommandRouter([ { name: "provider-get", matches: (command) => command.startsWith("provider get"), - results: [{ status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }], + results: [{ status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" }], }, { name: "inference-set", @@ -1025,9 +1021,12 @@ const { isOpenclawReady } = require(${onboardPath}); result = await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, ); } finally { error.mockRestore(); @@ -1403,6 +1402,7 @@ describe("re-onboard Ollama GPU release (#9110)", () => { expect(events).toEqual([ "lock-enter", "read-prior-route", + "read-prior-route", "ownership-lock-enter", "peer-scan", "unload", diff --git a/test/onboarding/onboard-openrouter-inference.test.ts b/test/onboarding/onboard-openrouter-inference.test.ts index 9a8137e197c..cfc4e1f6f02 100644 --- a/test/onboarding/onboard-openrouter-inference.test.ts +++ b/test/onboarding/onboard-openrouter-inference.test.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import assert from "node:assert/strict"; import { describe, expect, it, vi } from "vitest"; +import { createNativeSetupProviderAdapter } from "../helpers/onboard-split-context"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { createDirectSetupInferenceHarnessFactory, @@ -18,35 +18,18 @@ const openrouterRuntimeOnboard = const createDirectSetupInferenceHarness = createDirectSetupInferenceHarnessFactory( onboard.createSetupInference, ); -const OPENROUTER_PROVIDER_METADATA = - "Name: openrouter-api\nType: openai\nCredential keys: OPENROUTER_API_KEY\nConfig keys: OPENAI_BASE_URL\n"; - describe("OpenRouter onboarding inference setup", () => { - it("configures OpenRouter through the runtime header adapter (#5826)", async () => { + it("configures fixed OpenRouter without the runtime header adapter (#12589)", async () => { await withProcessEnv({ OPENROUTER_API_KEY: "sk-or-test" }, async () => { - const ensureAdapter = vi.fn(async () => ({ - baseUrl: "http://host.openshell.internal:11437/v1", - localBaseUrl: "http://127.0.0.1:11437/v1", - credentialEnv: "OPENROUTER_API_KEY", - logPath: "/tmp/openrouter-runtime-adapter.log", - })); - const setupOpenRouterRuntimeInference = - openrouterRuntimeOnboard.setupOpenRouterRuntimeInference; + const providerAdapter = createNativeSetupProviderAdapter("openrouter-api", false); + const setupOpenRouterRuntimeInference = vi.fn(async () => ({ handled: false as const })); const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: OPENROUTER_PROVIDER_METADATA } - : undefined, overrides: { isNonInteractive: () => true, - openrouterRuntimeOnboard: { - setupOpenRouterRuntimeInference: ( - input: Parameters[0], - ) => setupOpenRouterRuntimeInference({ ...input, ensureAdapter }), - }, + providerAdapter, + openrouterRuntimeOnboard: { setupOpenRouterRuntimeInference }, }, }); - await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", @@ -54,36 +37,39 @@ describe("OpenRouter onboarding inference setup", () => { "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY", ); - - expect(ensureAdapter).toHaveBeenCalledWith({ authorizationToken: "sk-or-test" }); - const commands = harness.commands.map(({ command }) => command); - expect(commands).toEqual([ - "provider get -g nemoclaw openrouter-api", - "provider update -g nemoclaw openrouter-api --credential OPENROUTER_API_KEY --config OPENAI_BASE_URL=http://host.openshell.internal:11437/v1", - "inference set -g nemoclaw --no-verify --provider openrouter-api --model moonshotai/kimi-k2.6 --timeout 180", - ]); - assert.equal(harness.commands[1].env?.OPENROUTER_API_KEY, "sk-or-test"); - assert.ok( - !commands.some((command) => command.includes("sk-or-test")), - "OpenRouter key must not appear in argv", + expect(providerAdapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + name: "nemoclaw-openrouter-api-v1", + type: "nemoclaw-openrouter-inference-v1", + credentials: [{ name: "OPENROUTER_API_KEY", value: "sk-or-test" }], + config: [], + }), ); - expect(harness.verifyInferenceRoute).toHaveBeenCalledWith( - "nemoclaw", - "openrouter-api", - "moonshotai/kimi-k2.6", + expect(setupOpenRouterRuntimeInference).not.toHaveBeenCalled(); + expect(harness.commands).toEqual([]); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); + expect(harness.verifyOnboardInferenceSmoke).toHaveBeenCalledWith( + expect.objectContaining({ + provider: "openrouter-api", + model: "moonshotai/kimi-k2.6", + endpointUrl: "https://openrouter.ai/api/v1", + credentialEnv: "OPENROUTER_API_KEY", + }), ); - expect(harness.verifyOnboardInferenceSmoke).toHaveBeenCalledWith({ - provider: "openrouter-api", - model: "moonshotai/kimi-k2.6", - endpointUrl: "http://127.0.0.1:11437/v1", - credentialEnv: "OPENROUTER_API_KEY", - forceOpenAiLike: true, - }); - assert.deepEqual(harness.errors, []); - assert.deepEqual(harness.logs, [ - " OpenRouter Runtime adapter ready: sandbox route http://host.openshell.internal:11437/v1, host log /tmp/openrouter-runtime-adapter.log", - " ✓ Inference route set: openrouter-api / moonshotai/kimi-k2.6", - ]); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + provider: "openrouter-api", + endpointUrl: "https://openrouter.ai/api/v1", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "fixture-native-id", + }, + }), + ); + expect(harness.errors).toEqual([]); }); }); @@ -125,31 +111,17 @@ describe("OpenRouter onboarding inference setup", () => { expect(log).toHaveBeenCalledWith(" ✓ Inference route set: openrouter-api / test-model"); }); - it("updates OpenRouter adapter config while reusing a gateway-held credential (#5826)", async () => { + it("reuses the gateway-held native OpenRouter credential without updating it (#12589)", async () => { await withProcessEnv({ OPENROUTER_API_KEY: undefined }, async () => { - const ensureAdapter = vi.fn(async () => ({ - baseUrl: "http://host.openshell.internal:11437/v1", - localBaseUrl: "http://127.0.0.1:11437/v1", - credentialEnv: "OPENROUTER_API_KEY", - logPath: "/tmp/openrouter-runtime-adapter.log", - })); - const setupOpenRouterRuntimeInference = - openrouterRuntimeOnboard.setupOpenRouterRuntimeInference; + const providerAdapter = createNativeSetupProviderAdapter("openrouter-api"); + const setupOpenRouterRuntimeInference = vi.fn(async () => ({ handled: false as const })); const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: OPENROUTER_PROVIDER_METADATA } - : undefined, overrides: { isNonInteractive: () => true, - openrouterRuntimeOnboard: { - setupOpenRouterRuntimeInference: ( - input: Parameters[0], - ) => setupOpenRouterRuntimeInference({ ...input, ensureAdapter }), - }, + providerAdapter, + openrouterRuntimeOnboard: { setupOpenRouterRuntimeInference }, }, }); - await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", @@ -163,20 +135,26 @@ describe("OpenRouter onboarding inference setup", () => { skipHostInferenceSmoke: true, }, ); - - expect(ensureAdapter).toHaveBeenCalledWith({ authorizationToken: null }); - expect(harness.commands.map(({ command }) => command)).toEqual([ - "provider get -g nemoclaw openrouter-api", - "provider update -g nemoclaw openrouter-api --config OPENAI_BASE_URL=http://host.openshell.internal:11437/v1", - "inference set -g nemoclaw --no-verify --provider openrouter-api --model moonshotai/kimi-k2.6 --timeout 180", - ]); - expect(harness.commands[2].env?.OPENROUTER_API_KEY).toBeUndefined(); + expect(providerAdapter.getProvider).toHaveBeenCalledWith( + expect.objectContaining({ providerName: "nemoclaw-openrouter-api-v1" }), + ); + expect(providerAdapter.createProvider).not.toHaveBeenCalled(); + expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); + expect(setupOpenRouterRuntimeInference).not.toHaveBeenCalled(); + expect(harness.commands).toEqual([]); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); expect(harness.verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); - expect(harness.logs).toEqual([ - " OpenRouter Runtime adapter ready: sandbox route http://host.openshell.internal:11437/v1, host log /tmp/openrouter-runtime-adapter.log", - " Reusing existing gateway credential; skipping host inference smoke.", - " ✓ Inference route set: openrouter-api / moonshotai/kimi-k2.6", - ]); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "fixture-native-id", + }, + }), + ); expect(harness.errors).toEqual([]); }); }); diff --git a/test/onboarding/onboard-terminal-dashboard.test.ts b/test/onboarding/onboard-terminal-dashboard.test.ts index 00ade5e9a3d..9e9c9d5d7d1 100644 --- a/test/onboarding/onboard-terminal-dashboard.test.ts +++ b/test/onboarding/onboard-terminal-dashboard.test.ts @@ -188,7 +188,7 @@ registry.getSandbox = () => name: sandboxName, gpuEnabled: false, agent: "langchain-deepagents-code", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index 44131a080a5..1ad53d8ff48 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -668,25 +668,26 @@ startGateway(null).catch((error) => { assert.equal(evidence.parentCredentialUnchanged, true); }); - it("uses the OpenShell 0.0.116 provider path without a compatibility-profile mutation", () => { + it("keeps the custom OpenShell 0.0.116 provider path without a compatibility-profile mutation", () => { const { commands } = runProductionSetupInferenceCredentialBoundary({ - credentialEnv: "OPENAI_API_KEY", + preferredInferenceApi: "openai-completions", + credentialEnv: "COMPATIBLE_API_KEY", credentialValue: "sk-TEST-NOT-A-REAL-VALUE", endpointUrl: "https://api.openai.com/v1", model: "gpt-5.4", - provider: "openai-api", + provider: "compatible-endpoint", }); const commandSequence = commands.map(({ argv }) => argv.join(" ")); - assert.match(commandSequence[0] ?? "", /^provider get -g nemoclaw openai-api$/); + assert.match(commandSequence[0] ?? "", /^provider get -g nemoclaw compatible-endpoint$/); assert.ok( commandSequence.some((command) => - /^provider update -g nemoclaw openai-api(?: |$)/.test(command), + /^provider update -g nemoclaw compatible-endpoint(?: |$)/.test(command), ), ); assert.ok( commandSequence.some((command) => - /^inference set -g nemoclaw --no-verify --provider openai-api --model gpt-5\.4(?: |$)/.test( + /^inference set -g nemoclaw --no-verify --provider compatible-endpoint --model gpt-5\.4(?: |$)/.test( command, ), ), @@ -839,19 +840,19 @@ const { createSandbox } = require(${onboardPath}); ok: true, value: { state: "configured", - route: { provider: "openai-api", model: "gpt-5.4" }, + route: { provider: "compatible-endpoint", model: "gpt-5.4" }, }, }), }); - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { status: 0, stdout: - "Name: openai-api\nType: openai\nCredential keys: OPENAI_API_KEY\nConfig keys: OPENAI_BASE_URL\n", + "Name: compatible-endpoint\nType: openai\nCredential keys: COMPATIBLE_API_KEY\nConfig keys: OPENAI_BASE_URL\n", stderr: "", } : undefined, @@ -861,12 +862,12 @@ const { createSandbox } = require(${onboardPath}); await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", + "compatible-endpoint", "https://api.openai.com/v1", - "OPENAI_API_KEY", + "COMPATIBLE_API_KEY", ); - assert.equal(harness.commands[0].command, "provider get -g nemoclaw openai-api"); + assert.equal(harness.commands[0].command, "provider get -g nemoclaw compatible-endpoint"); assert.equal(harness.commands.length, 3); }); }); diff --git a/test/runtime/sandbox/sandbox-build-context.test.ts b/test/runtime/sandbox/sandbox-build-context.test.ts index cca13b95e9e..a5b6dbcc2ce 100644 --- a/test/runtime/sandbox/sandbox-build-context.test.ts +++ b/test/runtime/sandbox/sandbox-build-context.test.ts @@ -263,6 +263,7 @@ describe("sandbox build context staging", () => { ); writeFixture(path.join("src", "lib", "tool-disclosure.ts")); writeFixture(path.join("src", "lib", "providerless-inference.ts")); + writeFixture("src/lib/inference/native-hosted/openrouter-headers.ts"); for (const relativePath of [ "extra-agents-validation.ts", path.join("core", "json-types.ts"), diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 860b3f64e21..285a18aa3ba 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -73,7 +73,7 @@ export type ConnectHarness = { requalifyPortableAgentAuthoritySpy: MockInstance; qualifyHermesPortableAcceptedReadinessAuthoritySpy: MockInstance; inspectPortableReceiptDispositionSpy: MockInstance; - verifyNativeNvidiaProviderAttachmentSpy: MockInstance; + verifyNativeHostedProviderAttachmentSpy: MockInstance; nativeInferenceInvocationSpy: MockInstance; registryUpdateSpy: MockInstance; registryEntries: SandboxEntry[]; @@ -246,7 +246,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne const sandboxSession = requireDist("../../src/lib/state/sandbox-session.js"); const vmDnsMonkeypatch = requireDist("../../src/lib/actions/sandbox/vm-dns-monkeypatch.js"); const launchReadiness = requireDist("../../src/lib/actions/sandbox/launch-readiness.js"); - const nativeNvidia = requireDist("../../src/lib/inference/native-nvidia/index.js"); + const nativeHosted = requireDist("../../src/lib/inference/native-hosted.js"); const inferenceRouteHealth = requireDist( "../../src/lib/actions/sandbox/inference-route-health.js", ); @@ -454,8 +454,8 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne const publishLaunchReadinessSpy = vi .spyOn(launchReadiness, "publishLaunchReadiness") .mockResolvedValue(options.readinessPublicationResult ?? { kind: "published" }); - const verifyNativeNvidiaProviderAttachmentSpy = vi - .spyOn(nativeNvidia, "verifyNativeNvidiaProviderAttachment") + const verifyNativeHostedProviderAttachmentSpy = vi + .spyOn(nativeHosted, "verifyNativeHostedProviderAttachment") .mockImplementation(async (...args: unknown[]) => (args[0] as { expected: unknown }).expected); const nativeInferenceInvocationSpy = vi .spyOn(inferenceRouteHealth, "runSandboxInferenceInvocationProbe") @@ -880,7 +880,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne requalifyPortableAgentAuthoritySpy, qualifyHermesPortableAcceptedReadinessAuthoritySpy, inspectPortableReceiptDispositionSpy, - verifyNativeNvidiaProviderAttachmentSpy, + verifyNativeHostedProviderAttachmentSpy, nativeInferenceInvocationSpy, registryUpdateSpy, registryEntries, diff --git a/test/support/native-provider-command-runtime.ts b/test/support/native-provider-command-runtime.ts new file mode 100644 index 00000000000..43140056b61 --- /dev/null +++ b/test/support/native-provider-command-runtime.ts @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { parse as parseYaml } from "yaml"; +import { nativeHostedProfile } from "../../src/lib/inference/native-hosted/profiles"; + +/** Shared CLI boundary fixture for native onboarding and credential handoff. */ +export function createNativeProviderCommandRuntime( + logicalProvider: string, + initiallyExists = false, +) { + const profile = nativeHostedProfile(logicalProvider); + if (!profile) throw new Error(`Unknown native fixture provider: ${logicalProvider}`); + const profileJson = JSON.stringify( + parseYaml( + fs.readFileSync( + path.join( + import.meta.dirname, + "../../managed-inference/provider-profiles", + `${profile.profileId}.yaml`, + ), + "utf8", + ), + ), + ); + const metadata = [ + `Name: ${profile.providerName}`, + `Type: ${profile.profileId}`, + "Id: 11111111-2222-4333-8444-555555555555", + "Resource version: 1", + `Credential keys: ${profile.credentialEnv}`, + "Config keys: ", + ].join("\n"); + let exists = initiallyExists; + const run = (args: string[]) => { + if (args[0] !== "provider") return undefined; + if (args[1] === "profile") return { status: 0, stdout: profileJson, stderr: "" }; + if (args[1] === "get") + return exists + ? { status: 0, stdout: metadata, stderr: "" } + : { status: 1, stdout: "", stderr: "provider not found" }; + if (args[1] === "create") exists = true; + return { status: 0, stdout: "", stderr: "" }; + }; + return { run, profileJson, metadata }; +} diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 522d6c7fecf..ac064070044 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -129,6 +129,7 @@ export type ProductionSetupInferenceBoundaryResult = { export function runProductionSetupInferenceCredentialBoundary(options: { credentialEnv: string; credentialValue: string; + preferredInferenceApi?: string; endpointUrl?: string | null; model: string; provider: string; @@ -186,6 +187,9 @@ const setupCredentialBefore = process.env[credentialEnv] || null; ${JSON.stringify(options.provider)}, ${JSON.stringify(options.endpointUrl ?? null)}, credentialEnv, + null, + [], + { preferredInferenceApi: ${JSON.stringify(options.preferredInferenceApi ?? null)} }, ); fs.writeFileSync( ${JSON.stringify(setupResultPath)}, From df4982c31f5271c1612743835b0d2583d52831a6 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 09:10:29 -0700 Subject: [PATCH 014/133] fix: repair native inference merge integration --- .../inference-set-failure-handling.test.ts | 22 +-- .../inference-set-openclaw-run.test.ts | 2 +- src/lib/actions/inference-set.ts | 131 +++++++++++++----- src/lib/onboard/setup-inference.ts | 18 +-- 4 files changed, 115 insertions(+), 58 deletions(-) diff --git a/src/lib/actions/inference-set-failure-handling.test.ts b/src/lib/actions/inference-set-failure-handling.test.ts index b4d520402c7..753688479a7 100644 --- a/src/lib/actions/inference-set-failure-handling.test.ts +++ b/src/lib/actions/inference-set-failure-handling.test.ts @@ -98,7 +98,7 @@ describe("runInferenceSet failure handling", () => { await expect( runInferenceSet({ provider: "openai-api", model: "openai/model-a" }, deps), - ).rejects.toThrow(/OpenShell inference route update failed/); + ).rejects.toThrow(/OpenShell inference route update with verification failed/); expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); @@ -108,7 +108,7 @@ describe("runInferenceSet failure handling", () => { const deps = createDeps({ config: {}, openshellStatus: 17 }); await expect( - runInferenceSet({ provider: "nvidia-prod", model: "nvidia/model-a" }, deps), + runInferenceSet({ provider: "openai-api", model: "openai/model-a" }, deps), ).rejects.toThrow( /route state is unknown.*Inspect gateway 'nemoclaw', then rerun the same `nemoclaw inference set` command\./su, ); @@ -123,7 +123,7 @@ describe("runInferenceSet failure handling", () => { const createProvider = vi.fn(); const base = createDeps({ config: {}, - entries: [{ name: "alpha", agent: "openclaw", provider: "nvidia-prod", model: "old-model" }], + entries: [{ name: "alpha", agent: "openclaw", provider: "openai-api", model: "old-model" }], inferenceRouteMutator: { setInferenceRoute }, inferenceRouteObserver: { observeInferenceRoute: vi.fn(async () => ({ @@ -142,7 +142,7 @@ describe("runInferenceSet failure handling", () => { }; await expect( - runInferenceSet({ provider: "nvidia-prod", model: "new-model" }, deps), + runInferenceSet({ provider: "openai-api", model: "new-model" }, deps), ).rejects.toThrow(/Cannot reconcile.*gateway 'nemoclaw'.*gateway unavailable/su); expect(createProvider).not.toHaveBeenCalled(); @@ -162,7 +162,7 @@ describe("runInferenceSet failure handling", () => { ok: true as const, value: { state: "configured" as const, - route: { provider: "nvidia-prod", model: "old-model" }, + route: { provider: "openai-api", model: "old-model" }, }, }; }); @@ -185,13 +185,13 @@ describe("runInferenceSet failure handling", () => { }); const deps = createDeps({ config: {}, - entries: [{ name: "alpha", agent: "openclaw", provider: "nvidia-prod", model: "old-model" }], + entries: [{ name: "alpha", agent: "openclaw", provider: "openai-api", model: "old-model" }], inferenceRouteObserver: { observeInferenceRoute }, inferenceRouteMutator: { setInferenceRoute }, }); await expect( - runInferenceSet({ provider: "nvidia-prod", model: "new-model" }, deps), + runInferenceSet({ provider: "openai-api", model: "new-model" }, deps), ).rejects.toThrow( /gateway schema mismatch.*Inspect gateway 'nemoclaw', then rerun the same `nemoclaw inference set` command\./su, ); @@ -199,8 +199,8 @@ describe("runInferenceSet failure handling", () => { expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); await expect( - runInferenceSet({ provider: "nvidia-prod", model: "new-model" }, deps), - ).resolves.toMatchObject({ provider: "nvidia-prod", model: "new-model" }); + runInferenceSet({ provider: "openai-api", model: "new-model" }, deps), + ).resolves.toMatchObject({ provider: "openai-api", model: "new-model" }); expect(events).toEqual([ "observe:nemoclaw", @@ -323,7 +323,9 @@ describe("runInferenceSet failure handling", () => { expect(err).toBeInstanceOf(Error); const message = (err as Error).message; - expect(message).toMatch(/OpenShell inference route update failed with exit 42/); + expect(message).toMatch( + /OpenShell inference route update with verification failed with exit 42/, + ); expect(message).toMatch(/network timeout connecting to gateway/); expect(message).not.toContain("nvapi-secret-value"); expect(message).not.toMatch(/Registered providers/); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 90c54d70579..cf0f5931650 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -247,7 +247,7 @@ describe("runInferenceSet OpenClaw routing", () => { deps, ); -expect( + expect( deps.calls.captureOpenshell.mock.calls.filter( ([args]) => args[0] === "inference" && args[1] === "set", ), diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 2d2411f1d99..681a953de97 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -998,6 +998,75 @@ async function rollbackNativeNvidiaSelection(input: { } } +async function applyInferenceRouteSelection(input: { + nativeNvidia: boolean; + provider: string; + model: string; + gatewayName: string; + noVerify: boolean; + retryProviderNotFound: boolean; + onAmbiguousFailure: () => void; + deps: InferenceSetDeps; +}): Promise { + if (input.nativeNvidia) { + input.deps.log(` Using attached native NVIDIA provider: ${input.provider} / ${input.model}`); + return false; + } + input.deps.log(` Setting OpenShell inference route: ${input.provider} / ${input.model}`); + const setInferenceRoute = () => + input.deps.inferenceRouteMutator.setInferenceRoute({ + target: { kind: "named", gatewayName: input.gatewayName }, + route: { provider: input.provider, model: input.model }, + verification: input.noVerify ? "skip" : "required", + }); + let setResult = await setInferenceRoute(); + if ( + !setResult.ok && + !setResult.ambiguous && + input.retryProviderNotFound && + setResult.error.kind === "command" && + setResult.error.reason === "provider_not_found" + ) { + setResult = await setInferenceRoute(); + } + if (setResult.ok) return true; + if (setResult.ambiguous) input.onAmbiguousFailure(); + const failure = await buildInferenceSetFailure( + setResult.error, + setResult.ambiguous, + input.gatewayName, + input.deps, + ); + throw new InferenceSetError(failure.message, failure.exitCode); +} + +function observeInferenceRouteForSelection(input: { + nativeNvidia: boolean; + gatewayName: string; + deps: InferenceSetDeps; +}): Promise { + if (input.nativeNvidia) return Promise.resolve({ state: "unconfigured" }); + return observeInferenceRouteBeforeMutation(input.deps, input.gatewayName); +} + +function providerBackedRouteLacksRollbackTarget(input: { + nativeNvidia: boolean; + directProviderBinding: boolean; + httpsPinProviderBinding: boolean; + probeDirectSandboxBridge: boolean; + rollbackRoute: boolean; + previousNativeNvidiaAttachment: boolean; +}): boolean { + return ( + !input.nativeNvidia && + (input.directProviderBinding || + input.httpsPinProviderBinding || + input.probeDirectSandboxBridge) && + !input.rollbackRoute && + !input.previousNativeNvidiaAttachment + ); +} + function recordedDirectProviderBindingMismatches(options: { entry: SandboxEntry; provider: string; @@ -1239,10 +1308,11 @@ async function runInferenceSetWithoutHostLock( 2, ); } - const preMutationRoute = await observeInferenceRouteBeforeMutation( + const preMutationRoute = await observeInferenceRouteForSelection({ + nativeNvidia: selectingNativeNvidia, + gatewayName: preparedRoute.gatewayName, deps, - preparedRoute.gatewayName, - ); + }); const target = resolveMatchingAgentConfigTarget(deps, sandboxName, agentName); // Explicit custom routes may start an HTTPS-pin adapter during finalization, // so reject an unsupported API family before that first possible mutation. @@ -1406,9 +1476,14 @@ async function runInferenceSetWithoutHostLock( [entry.endpointUrl ?? null, registryMetadata.endpointUrl ?? null], ].some(([previous, next]) => previous !== next)); if ( - !selectingNativeNvidia && - (directProviderBinding || httpsPinProviderBinding || probeDirectSandboxBridge) && - !rollbackRoute + providerBackedRouteLacksRollbackTarget({ + nativeNvidia: selectingNativeNvidia, + directProviderBinding: Boolean(directProviderBinding), + httpsPinProviderBinding: Boolean(httpsPinProviderBinding), + probeDirectSandboxBridge, + rollbackRoute: Boolean(rollbackRoute), + previousNativeNvidiaAttachment: Boolean(previousNativeNvidiaAttachment), + }) ) { throw new InferenceSetError( `Cannot change the provider-backed route because gateway '${preparedRoute.gatewayName}' has no configured ` + @@ -1524,38 +1599,18 @@ async function runInferenceSetWithoutHostLock( await assertProviderCurrentBeforeSelection?.(); if (routeImpactWarning) deps.log(` ${routeImpactWarning}`); - if (selectingNativeNvidia) { - deps.log(` Using attached native NVIDIA provider: ${provider} / ${model}`); - } else { - deps.log(` Setting OpenShell inference route: ${provider} / ${model}`); - const setInferenceRoute = () => - deps.inferenceRouteMutator.setInferenceRoute({ - target: { kind: "named", gatewayName: preparedRoute.gatewayName }, - route: { provider, model }, - verification: effectiveNoVerify ? "skip" : "required", - }); - let setResult = await setInferenceRoute(); - if ( - !setResult.ok && - !setResult.ambiguous && - directProviderBinding && - setResult.error.kind === "command" && - setResult.error.reason === "provider_not_found" - ) { - setResult = await setInferenceRoute(); - } - if (!setResult.ok) { - ambiguousInferenceSelection = setResult.ambiguous; - const failure = await buildInferenceSetFailure( - setResult.error, - setResult.ambiguous, - preparedRoute.gatewayName, - deps, - ); - throw new InferenceSetError(failure.message, failure.exitCode); - } - } - appliedInferenceSelection = true; + appliedInferenceSelection = await applyInferenceRouteSelection({ + nativeNvidia: selectingNativeNvidia, + provider, + model, + gatewayName: preparedRoute.gatewayName, + noVerify: effectiveNoVerify, + retryProviderNotFound: Boolean(directProviderBinding), + onAmbiguousFailure: () => { + ambiguousInferenceSelection = true; + }, + deps, + }); if (providerMutation) { try { await providerMutation.commit(); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index f68ea8bc5d0..5c5974536da 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -677,16 +677,16 @@ export function createSetupInference( ); return deps.exitProcess(1); } - const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ - target: { kind: "named", gatewayName }, - }); - if (!observedRoute.ok) { - deps.error( - ` Cannot reconcile the current OpenShell inference selection on gateway '${gatewayName}' before onboarding mutation: ${observedRoute.error.message}`, - ); - return deps.exitProcess(1); - } if (!isNativeNvidiaProvider(provider)) { + const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ + target: { kind: "named", gatewayName }, + }); + if (!observedRoute.ok) { + deps.error( + ` Cannot reconcile the current OpenShell inference selection on gateway '${gatewayName}' before onboarding mutation: ${observedRoute.error.message}`, + ); + return deps.exitProcess(1); + } const compatibility = deps.checkGatewayRouteCompatibility({ gatewayName, sandboxName, From 097599b8ee5200beede8981425f4b11b39bf1908 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 09:35:16 -0700 Subject: [PATCH 015/133] test: update native config-read expectation Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/inference/inference-set-config-read-exit.test.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test/inference/inference-set-config-read-exit.test.ts b/test/inference/inference-set-config-read-exit.test.ts index 598b5b99a8d..4048a7ca883 100644 --- a/test/inference/inference-set-config-read-exit.test.ts +++ b/test/inference/inference-set-config-read-exit.test.ts @@ -115,10 +115,9 @@ describe("inference set sandbox configuration read failures", () => { expect(output).not.toContain("Setting OpenShell inference route"); expect(fs.readFileSync(registryFile, "utf8")).toBe(registryBefore); const openshellCalls = fs.readFileSync(openshellLog, "utf8").trim().split("\n"); - expect(openshellCalls).toHaveLength(2); - expect(openshellCalls[0]).toContain("inference get -g nemoclaw"); - expect(openshellCalls[1]).toContain("sandbox exec"); - expect(openshellCalls[1]).toContain("cat /sandbox/.openclaw/openclaw.json"); + expect(openshellCalls).toHaveLength(1); + expect(openshellCalls[0]).toContain("sandbox exec"); + expect(openshellCalls[0]).toContain("cat /sandbox/.openclaw/openclaw.json"); expect(openshellCalls).not.toContainEqual(expect.stringMatching(/\binference set\b/u)); expect(result.status).toBe(1); }, From 2e734749264f5d406eb62587bc6c3e123db1795c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 10:29:21 -0700 Subject: [PATCH 016/133] fix(inference): preserve native provider receipts on reset Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/get-started/quickstart-hermes.mdx | 4 ++- docs/reference/commands.mdx | 6 +++- docs/security/credential-rotation.mdx | 4 +++ .../gateway-authentication-controls.mdx | 4 ++- .../credentials-provider-adapter.test.ts | 35 +++++++++++++++++++ src/lib/actions/credentials/reset.ts | 22 +++++++++++- 6 files changed, 71 insertions(+), 4 deletions(-) diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index 09791495099..8b3f0e6cddb 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -351,7 +351,9 @@ Use these details when your first-run path needs more control. API-key mode is inference-only and does not enable managed tool gateways. After you select a provider and model, review the summary and apply the configuration. - NemoClaw writes Hermes configuration into `/sandbox/.hermes`, routes model traffic through `inference.local`, and starts the Hermes gateway inside the sandbox. + NemoClaw writes Hermes configuration into `/sandbox/.hermes` and starts the Hermes gateway inside the sandbox. + NVIDIA Endpoints traffic uses the native NVIDIA endpoint through the least-privilege sandbox-attached OpenShell provider. + Other managed inference providers continue to use `inference.local`. The Hermes image includes runtime dependencies for supported NemoClaw messaging integrations, the API service, and its health endpoint. The base image does not include unsupported Hermes integrations. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 45f5f7ff826..b3a24e20c96 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -256,7 +256,7 @@ It stops without writing output when required identity, policy, inference, or wo If the source changes during observation, the command retries the complete observation once and stops without output if the retry also changes. The command reads the provider endpoint from the sandbox's OpenShell gateway and compares it with the registered endpoint. -For NVIDIA Endpoints, it verifies the gateway's built-in NVIDIA provider profile and default endpoint. +For NVIDIA Endpoints, it verifies that the recorded NemoClaw-owned provider attachment matches the live provider, least-privilege profile, and fixed native endpoint. A custom NVIDIA provider profile or endpoint override cannot be included in an export. If OpenShell cannot supply the required evidence, the command stops without writing output. @@ -3706,6 +3706,10 @@ $$nemoclaw credentials add tavily-search --type tavily --agent dcode --credentia Remove a provider credential from the OpenShell gateway by provider name. After removal, re-running `$$nemoclaw onboard` re-prompts for that provider's credential. Run `$$nemoclaw credentials list` first if you are not sure of the provider name. +When the native NVIDIA provider is attached to a sandbox, reset stops without detaching or deleting it. +Rotate its credential in place by setting `NVIDIA_INFERENCE_API_KEY` and rerunning `$$nemoclaw onboard --name `. +To remove it completely, preserve required sandbox state, destroy every attached sandbox, and then retry reset. + ```bash $$nemoclaw credentials reset nvidia-prod ``` diff --git a/docs/security/credential-rotation.mdx b/docs/security/credential-rotation.mdx index bf4a4144127..a31f7d9b7df 100644 --- a/docs/security/credential-rotation.mdx +++ b/docs/security/credential-rotation.mdx @@ -181,6 +181,10 @@ unset TAVILY_API_KEY Use `credentials reset` only when you need to remove an inference or web search provider before its replacement is available. Run `$$nemoclaw credentials list` first, then pass the provider name from that output. +The native NVIDIA provider cannot be reset while it is attached to a sandbox. +Use [Rotate an Inference API key](#rotate-an-inference-api-key) to replace its credential in place. +To remove it completely, preserve required sandbox state, destroy every attached sandbox, and then run: + ```bash $$nemoclaw credentials reset nvidia-prod --yes ``` diff --git a/docs/security/gateway-authentication-controls.mdx b/docs/security/gateway-authentication-controls.mdx index 83654f11bd1..80804e887f5 100644 --- a/docs/security/gateway-authentication-controls.mdx +++ b/docs/security/gateway-authentication-controls.mdx @@ -152,7 +152,9 @@ Do not approve an unexpected client or an unrelated `operator.admin` request. Hermes exposes an OpenAI-compatible API on the forwarded Hermes port and can optionally expose the native Hermes dashboard. Do not publish those endpoints on shared or public networks unless you put them behind your own access controls. -NemoClaw still keeps provider credentials in OpenShell and routes model traffic through `inference.local`. +NemoClaw keeps provider credentials in OpenShell. +NVIDIA Endpoints traffic uses the native NVIDIA endpoint through the sandbox-attached OpenShell provider. +Other managed inference providers continue to use `inference.local`. Generated Hermes runtime files use OpenShell resolver placeholders for managed-tool and messaging credentials. Hermes startup rejects raw secret-shaped values in sandbox-visible environment or config fields, while allowing empty values, migration sentinels, OpenShell resolver placeholders, and expected Slack placeholder forms. diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 058bd4076a8..1d4dffb3439 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -847,6 +847,41 @@ describe("credential actions use typed OpenShell provider results", () => { expect(result.outputLines).toContain(" nemoclaw alpha rebuild"); }); + it("preserves attached native NVIDIA providers during credential reset", async () => { + const deleteProvider = vi.fn(async () => ({ + ok: false, + error: { + kind: "command", + reason: "attached", + message: "provider remains attached", + attachedSandboxes: ["alpha"], + }, + })); + const detachProvider = vi.fn(); + const adapter = providerAdapter({ deleteProvider, detachProvider }); + + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { providerAdapter: adapter }, + ); + + expect(result.exitCode).toBe(1); + expect(deleteProvider).toHaveBeenCalledOnce(); + expect(deleteProvider).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: "nemoclaw-nvidia-prod-v1", + timeoutMs: 30_000, + }); + expect(detachProvider).not.toHaveBeenCalled(); + expect(result.failureLines).toContain(" No provider attachment was changed."); + expect(result.failureLines).toContain( + " To rotate the credential in place, set NVIDIA_INFERENCE_API_KEY and rerun 'nemoclaw onboard --name '.", + ); + expect(result.failureLines).toContain(" nemoclaw alpha destroy"); + expect(result.failureLines.join("\n")).not.toContain("rebuild"); + expect(result.failureLines.join("\n")).not.toContain("openshell sandbox provider detach"); + }); + it("reports recovery for sandboxes detached before final deletion fails (#9806)", async () => { const deleteProvider = vi .fn() diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 723f109b7c6..665a889797b 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -15,6 +15,7 @@ import { } from "../../name-validation"; import { CLI_NAME } from "../../cli/branding"; import { + NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROVIDER, } from "../../inference/native-nvidia"; @@ -125,7 +126,9 @@ export async function runCredentialsResetAction( if (!target) return fail(recoveryFailureLines); const providerAdapter = deps.providerAdapter ?? createCliOpenShellProviderAdapter(); - const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter); + const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter, { + detachAttached: key !== NVIDIA_HOSTED_LOGICAL_PROVIDER, + }); if ( !recovery.ok && @@ -184,6 +187,19 @@ export function formatResetOutcome( ...validatedAttachedSandboxes(recovery.error), ]), ]; + if (key === NVIDIA_HOSTED_LOGICAL_PROVIDER && stuckSandboxes.length > 0) { + lines.push( + "", + ` '${key}' remains attached to sandbox(es): ${stuckSandboxes.join(", ")}.`, + " No provider attachment was changed.", + ` To rotate the credential in place, set ${NVIDIA_HOSTED_CREDENTIAL_ENV} and rerun '${CLI_NAME} onboard --name '.`, + " To remove the provider completely, preserve any required sandbox state, destroy every attached sandbox,", + ` then rerun '${CLI_NAME} credentials reset ${key}'.`, + ...stuckSandboxes.map((sandbox) => ` ${CLI_NAME} ${sandbox} destroy`), + ); + if (recovery.error?.message) lines.push(` ${recovery.error.message}`); + return { ok: false, lines }; + } if (stuckSandboxes.length > 0) { const stuck = stuckSandboxes.join(", "); lines.push( @@ -218,6 +234,7 @@ async function deleteProviderWithRecovery( providerName: string, target: OpenShellGatewayTarget, providerAdapter: OpenShellProviderAdapter, + options: Readonly<{ detachAttached: boolean }> = { detachAttached: true }, ): Promise { const request = { target, @@ -237,6 +254,9 @@ async function deleteProviderWithRecovery( if (attachedSandboxes.length === 0) { return { ok: false, error: result.error, detachedSandboxes, recoveryFailures }; } + if (!options.detachAttached) { + return { ok: false, error: result.error, detachedSandboxes, recoveryFailures }; + } for (const sandbox of attachedSandboxes) { const detach = await providerAdapter.detachProvider({ ...request, sandboxName: sandbox }); From 43e12dce11c772de2c8c6aaeca3b4bee5f9907c3 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:07:03 -0700 Subject: [PATCH 017/133] fix(inference): bind native provider evidence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../credentials-provider-adapter.test.ts | 83 ++++++++++++------- src/lib/actions/credentials/reset.ts | 11 ++- ...inference-set-provider-diagnostics.test.ts | 9 ++ src/lib/credentials/provider-list.ts | 11 ++- src/lib/onboard/setup-inference.test.ts | 36 +++++--- src/lib/onboard/setup-inference.ts | 2 +- .../live/openclaw-inference-switch-helpers.ts | 15 ++++ .../live/openclaw-inference-switch.test.ts | 11 ++- .../openclaw-inference-switch-helpers.test.ts | 25 ++++++ 9 files changed, 150 insertions(+), 53 deletions(-) diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 1d4dffb3439..375683a6838 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -161,6 +161,22 @@ describe("credential actions use typed OpenShell provider results", () => { expect(JSON.stringify(result)).not.toContain("host-only-nvidia-value"); }); + it("lists the native NVIDIA provider only by its logical credential name", async () => { + const adapter = providerAdapter({ + listProviders: vi.fn(async () => ({ + ok: true as const, + value: { names: ["nemoclaw-nvidia-prod-v1", "custom-provider"] }, + })), + }); + + const result = await runCredentialsListAction("nemoclaw", { providerAdapter: adapter }); + + expect(result.exitCode).toBe(0); + expect(result.outputLines).toContain(" nvidia-prod"); + expect(result.outputLines).toContain(" custom-provider"); + expect(result.outputLines.join("\n")).not.toContain("nemoclaw-nvidia-prod-v1"); + }); + it("registers both Langfuse keys through the checked-in endpoint profile (#10840)", async () => { vi.stubEnv("LANGFUSE_PUBLIC_KEY", "pk-lf-host-only"); vi.stubEnv("LANGFUSE_SECRET_KEY", "sk-lf-host-only"); @@ -847,40 +863,43 @@ describe("credential actions use typed OpenShell provider results", () => { expect(result.outputLines).toContain(" nemoclaw alpha rebuild"); }); - it("preserves attached native NVIDIA providers during credential reset", async () => { - const deleteProvider = vi.fn(async () => ({ - ok: false, - error: { - kind: "command", - reason: "attached", - message: "provider remains attached", - attachedSandboxes: ["alpha"], - }, - })); - const detachProvider = vi.fn(); - const adapter = providerAdapter({ deleteProvider, detachProvider }); + it.each(["nvidia-prod", "nemoclaw-nvidia-prod-v1"])( + "preserves attached native NVIDIA providers during credential reset via %s", + async (provider) => { + const deleteProvider = vi.fn(async () => ({ + ok: false, + error: { + kind: "command", + reason: "attached", + message: "provider remains attached", + attachedSandboxes: ["alpha"], + }, + })); + const detachProvider = vi.fn(); + const adapter = providerAdapter({ deleteProvider, detachProvider }); - const result = await runCredentialsResetAction( - { provider: "nvidia-prod", confirmed: true }, - { providerAdapter: adapter }, - ); + const result = await runCredentialsResetAction( + { provider, confirmed: true }, + { providerAdapter: adapter }, + ); - expect(result.exitCode).toBe(1); - expect(deleteProvider).toHaveBeenCalledOnce(); - expect(deleteProvider).toHaveBeenCalledWith({ - target: { kind: "named", gatewayName: "nemoclaw" }, - providerName: "nemoclaw-nvidia-prod-v1", - timeoutMs: 30_000, - }); - expect(detachProvider).not.toHaveBeenCalled(); - expect(result.failureLines).toContain(" No provider attachment was changed."); - expect(result.failureLines).toContain( - " To rotate the credential in place, set NVIDIA_INFERENCE_API_KEY and rerun 'nemoclaw onboard --name '.", - ); - expect(result.failureLines).toContain(" nemoclaw alpha destroy"); - expect(result.failureLines.join("\n")).not.toContain("rebuild"); - expect(result.failureLines.join("\n")).not.toContain("openshell sandbox provider detach"); - }); + expect(result.exitCode).toBe(1); + expect(deleteProvider).toHaveBeenCalledOnce(); + expect(deleteProvider).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: "nemoclaw-nvidia-prod-v1", + timeoutMs: 30_000, + }); + expect(detachProvider).not.toHaveBeenCalled(); + expect(result.failureLines).toContain(" No provider attachment was changed."); + expect(result.failureLines).toContain( + " To rotate the credential in place, set NVIDIA_INFERENCE_API_KEY and rerun 'nemoclaw onboard --name '.", + ); + expect(result.failureLines).toContain(" nemoclaw alpha destroy"); + expect(result.failureLines.join("\n")).not.toContain("rebuild"); + expect(result.failureLines.join("\n")).not.toContain("openshell sandbox provider detach"); + }, + ); it("reports recovery for sandboxes detached before final deletion fails (#9806)", async () => { const deleteProvider = vi diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 665a889797b..31fb86bc4fb 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -95,7 +95,10 @@ export async function runCredentialsResetAction( deps: CredentialsResetDeps = {}, ): Promise { const key = input.provider; - const providerName = key === NVIDIA_HOSTED_LOGICAL_PROVIDER ? NVIDIA_HOSTED_NATIVE_PROVIDER : key; + const nativeNvidiaProvider = + key === NVIDIA_HOSTED_LOGICAL_PROVIDER || key === NVIDIA_HOSTED_NATIVE_PROVIDER; + const providerName = nativeNvidiaProvider ? NVIDIA_HOSTED_NATIVE_PROVIDER : key; + const publicKey = nativeNvidiaProvider ? NVIDIA_HOSTED_LOGICAL_PROVIDER : key; if (!PROVIDER_NAME_VALID_PATTERN.test(key)) { return fail([ " Provider name must be 1-128 chars, start with a letter, and use only letters, digits, '.', '_', or '-'.", @@ -127,7 +130,7 @@ export async function runCredentialsResetAction( const providerAdapter = deps.providerAdapter ?? createCliOpenShellProviderAdapter(); const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter, { - detachAttached: key !== NVIDIA_HOSTED_LOGICAL_PROVIDER, + detachAttached: !nativeNvidiaProvider, }); if ( @@ -146,10 +149,10 @@ export async function runCredentialsResetAction( ]); } - const outcome = formatResetOutcome(key, recovery, target.gatewayName); + const outcome = formatResetOutcome(publicKey, recovery, target.gatewayName); if (!outcome.ok) return fail(outcome.lines); - forgetExtraProvider(key); + forgetExtraProvider(publicKey); return ok(outcome.lines); } diff --git a/src/lib/actions/inference-set-provider-diagnostics.test.ts b/src/lib/actions/inference-set-provider-diagnostics.test.ts index 5d775b64f98..b2810dcb506 100644 --- a/src/lib/actions/inference-set-provider-diagnostics.test.ts +++ b/src/lib/actions/inference-set-provider-diagnostics.test.ts @@ -52,6 +52,15 @@ describe("inference set provider diagnostics", () => { expect(isBridgeProviderName("nvidia-prod")).toBe(false); }); + it("normalizes the internal native NVIDIA provider to its public name", () => { + expect( + classifyGatewayProviderNames(["nemoclaw-nvidia-prod-v1", "nvidia-prod", "custom-provider"]), + ).toEqual({ + bridgeNames: [], + credentialNames: ["custom-provider", "nvidia-prod"], + }); + }); + it.each([ { name: "thrown adapter error", diff --git a/src/lib/credentials/provider-list.ts b/src/lib/credentials/provider-list.ts index 5465de437c3..7c393993085 100644 --- a/src/lib/credentials/provider-list.ts +++ b/src/lib/credentials/provider-list.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { listMessagingProviderSuffixes } from "../messaging/channels"; +import { + NVIDIA_HOSTED_LOGICAL_PROVIDER, + NVIDIA_HOSTED_NATIVE_PROVIDER, +} from "../inference/native-nvidia"; const BRIDGE_PROVIDER_SUFFIXES: readonly string[] = [...listMessagingProviderSuffixes()]; @@ -13,9 +17,14 @@ export function classifyGatewayProviderNames(names: readonly string[]): { bridgeNames: string[]; credentialNames: string[]; } { + const credentialNames = names + .filter((name) => !isBridgeProviderName(name)) + .map((name) => + name === NVIDIA_HOSTED_NATIVE_PROVIDER ? NVIDIA_HOSTED_LOGICAL_PROVIDER : name, + ); return { bridgeNames: names.filter((name) => isBridgeProviderName(name)), - credentialNames: names.filter((name) => !isBridgeProviderName(name)).sort(), + credentialNames: [...new Set(credentialNames)].sort(), }; } diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 5d8a7529769..a619040ed0d 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -184,21 +184,23 @@ describe("createProviderReviewDeps", () => { describe("native NVIDIA onboarding", () => { it("reserves the logical route with an attached-provider receipt and no shared route mutation", async () => { + const importProviderProfile = vi.fn(async () => ({ ok: true as const })); + const getProvider = vi.fn(async () => ({ + ok: true as const, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 4 }, + }, + })); const updateProvider = vi.fn(async () => ({ ok: true, })); const providerAdapter = { - importProviderProfile: vi.fn(async () => ({ ok: true })), - getProvider: vi.fn(async () => ({ - ok: true, - value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { id: "provider-id", resourceVersion: 4 }, - }, - })), + importProviderProfile, + getProvider, updateProvider, } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); @@ -212,7 +214,7 @@ describe("native NVIDIA onboarding", () => { withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), step: vi.fn(), - getGatewayName: () => "nemoclaw", + getGatewayName: () => "onboarding-gateway", runOpenshell, updateSandbox, getSandbox: () => null, @@ -245,8 +247,18 @@ describe("native NVIDIA onboarding", () => { ), ).resolves.toEqual({ ok: true }); + expect(importProviderProfile).toHaveBeenCalledWith( + expect.objectContaining({ + target: { kind: "named", gatewayName: "onboarding-gateway" }, + }), + ); + expect(getProvider).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: "onboarding-gateway" }, + providerName: "nemoclaw-nvidia-prod-v1", + }); expect(updateProvider).toHaveBeenCalledWith( expect.objectContaining({ + target: { kind: "named", gatewayName: "onboarding-gateway" }, providerName: "nemoclaw-nvidia-prod-v1", credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "host-only-nvidia-credential" }], config: [], diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 5c5974536da..5c08f96ddd1 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -982,7 +982,7 @@ export function createSetupInference( } nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ adapter: providerAdapter, - target: { kind: "selected" }, + target: { kind: "named", gatewayName }, credentialValue, reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, ...(recordedAttachment ? { expected: recordedAttachment } : {}), diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index 3393daad1b7..5cc9cdc560a 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -21,6 +21,21 @@ export type OpenClawPostSwitchInferenceClassification = | { outcome: "passed" } | { outcome: "failed"; failureClass: RetryFailureClass }; +export type ExhaustedPostSwitchEvidence = + | { outcome: "failed"; message: string } + | { outcome: "skipped"; reason: string }; + +/** Required provider evidence fails closed after bounded transient retries. */ +export function classifyExhaustedPostSwitchEvidence(input: { + required: boolean; + lastFailure: string; +}): ExhaustedPostSwitchEvidence { + const detail = `Sandbox inference transient failure after switch; route/config checks already passed: ${input.lastFailure}`; + return input.required + ? { outcome: "failed", message: `Required native provider evidence failed: ${detail}` } + : { outcome: "skipped", reason: detail }; +} + export function classifyOpenClawPostSwitchInferenceAttempt( attempt: OpenClawPostSwitchInferenceAttempt, ): OpenClawPostSwitchInferenceClassification { diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index bc17bbc313f..82708a6f2a7 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -55,6 +55,7 @@ import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { agentReplyContainsToken, anthropicToolCount, + classifyExhaustedPostSwitchEvidence, classifyOpenClawPostSwitchInferenceAttempt, MOCK_BASELINE_API_KEY, MOCK_BASELINE_MODEL, @@ -823,9 +824,13 @@ async function checkSandboxInference( if (execution.outcome === "passed") return "ok"; const lastFailure = execution.value?.lastFailure ?? "probe failed without a result"; if (execution.evidence.outcome === "exhausted") { - return { - skipped: `Sandbox inference transient failure after switch; route/config checks already passed: ${lastFailure}`, - }; + const exhausted = classifyExhaustedPostSwitchEvidence({ + required: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, + lastFailure, + }); + return exhausted.outcome === "failed" + ? Promise.reject(new Error(exhausted.message)) + : { skipped: exhausted.reason }; } throw new Error(`Sandbox inference did not work after switch: ${lastFailure}`); } diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index 66329b8f2fc..a8f02986cc6 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest"; import { agentReplyContainsToken, anthropicToolCount, + classifyExhaustedPostSwitchEvidence, classifyOpenClawPostSwitchInferenceAttempt, MOCK_BASELINE_API_KEY, MOCK_BASELINE_MODEL, @@ -96,6 +97,30 @@ describe("openclaw-inference-switch post-switch retry classification", () => { }), ).toEqual({ outcome: "failed", failureClass: "malformed-input" }); }); + + it("fails closed when required native-provider evidence exhausts retries", () => { + expect( + classifyExhaustedPostSwitchEvidence({ + required: true, + lastFailure: "HTTP 503: unavailable", + }), + ).toEqual({ + outcome: "failed", + message: + "Required native provider evidence failed: Sandbox inference transient failure after switch; route/config checks already passed: HTTP 503: unavailable", + }); + + expect( + classifyExhaustedPostSwitchEvidence({ + required: false, + lastFailure: "HTTP 503: unavailable", + }), + ).toEqual({ + outcome: "skipped", + reason: + "Sandbox inference transient failure after switch; route/config checks already passed: HTTP 503: unavailable", + }); + }); }); describe("openclaw-inference-switch agent reply matching", () => { From 302bbc31377776839e2c069c49e0774b8e922342 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 11:27:29 -0700 Subject: [PATCH 018/133] test(onboard): scope native provider fixture Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../onboard-build-recreate-credential-reuse.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts index 798a5554db6..911c32bb67f 100644 --- a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts @@ -51,13 +51,13 @@ Gateway inference: EOF exit 0 fi -if [ "$1" = "provider" ] && [ "$2" = "profile" ] && [ "$3" = "export" ]; then +if [ "$1" = "provider" ] && [ "$2" = "profile" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ] && [ "$5" = "export" ]; then cat <<'EOF' {"id":"nemoclaw-nvidia-inference-v1","credentials":[{"name":"api_key","env_vars":["NVIDIA_INFERENCE_API_KEY"],"required":true,"auth_style":"bearer","header_name":"authorization","query_param":""}],"endpoints":[{"host":"integrate.api.nvidia.com","port":443,"protocol":"rest","enforcement":"enforce","rules":[{"allow":{"method":"GET","path":"/v1/models"}},{"allow":{"method":"POST","path":"/v1/chat/completions"}}]}],"binaries":["/usr/local/bin/node","/usr/bin/node","/opt/hermes/.venv/bin/python","/opt/hermes/.venv/bin/python3","/opt/venv/bin/python3","/usr/local/bin/curl","/usr/bin/curl"],"inference_capable":true} EOF exit 0 fi -if [ "$1" = "provider" ] && [ "$2" = "get" ] && [ "$3" = "nemoclaw-nvidia-prod-v1" ]; then +if [ "$1" = "provider" ] && [ "$2" = "get" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ] && [ "$5" = "nemoclaw-nvidia-prod-v1" ]; then cat <<'EOF' Name: nemoclaw-nvidia-prod-v1 Id: provider-id From a8ad4bcd4469201e5e7131fea4dafc6d52627313 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:01:59 -0700 Subject: [PATCH 019/133] fix: address native NVIDIA review findings --- docs/inference/use-nvidia-endpoints.mdx | 2 +- .../native-nvidia-target-ownership.test.ts | 17 +++++++++++++++++ tools/e2e/target-catalogue.mts | 6 ++++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 test/e2e/support/native-nvidia-target-ownership.test.ts diff --git a/docs/inference/use-nvidia-endpoints.mdx b/docs/inference/use-nvidia-endpoints.mdx index ef945f65e4b..40558c25a7b 100644 --- a/docs/inference/use-nvidia-endpoints.mdx +++ b/docs/inference/use-nvidia-endpoints.mdx @@ -11,7 +11,7 @@ content: --- NVIDIA Endpoints routes NemoClaw to models hosted on [build.nvidia.com](https://build.nvidia.com) through an OpenAI-compatible API. NemoClaw attaches a least-privilege OpenShell provider to the sandbox, and the agent calls the NVIDIA endpoint directly through that provider. -The provider allows only model discovery and Chat Completions requests from the supported agent binaries. +The provider allows only model discovery and Chat Completions requests from the agent-runtime and readiness-verification binaries listed in its provider profile. ## Credential diff --git a/test/e2e/support/native-nvidia-target-ownership.test.ts b/test/e2e/support/native-nvidia-target-ownership.test.ts new file mode 100644 index 00000000000..6220cae6427 --- /dev/null +++ b/test/e2e/support/native-nvidia-target-ownership.test.ts @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { catalogueTargetsForChangedFiles } from "../../../tools/e2e/target-catalogue.mts"; + +describe("native NVIDIA target ownership", () => { + it.each([ + "src/lib/inference/native-nvidia/index.ts", + "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", + ])("selects both provider-switch targets when %s changes", (changedFile) => { + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toEqual( + expect.arrayContaining(["hermes-inference-switch", "openclaw-inference-switch"]), + ); + }); +}); diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 388d9cfc219..0d66ffdfe84 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -906,6 +906,10 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ hostPreparation: "hermes-swap", runnerComparison: true, shard: "native-nvidia", + owningPaths: [ + "src/lib/inference/native-nvidia/index.ts", + "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", + ], environment: { ...nonInteractive, NEMOCLAW_AGENT: "hermes", @@ -1159,6 +1163,8 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: true, exposeCliBin: true, owningPaths: [ + "src/lib/inference/native-nvidia/index.ts", + "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "src/lib/actions/inference-set.ts", "src/lib/onboard.ts", "src/lib/onboard/machine/core-flow-phases.ts", From 560bd2c0e049f5f7e8e2c3c64c24d4ec9047052a Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 12:32:50 -0700 Subject: [PATCH 020/133] docs: clarify native NVIDIA inference routing --- docs/about/ecosystem-deepagents.mdx | 4 ++-- docs/about/how-it-works.mdx | 7 ++++--- docs/about/overview.mdx | 2 +- docs/manage-sandboxes/workspace-files.mdx | 2 +- docs/reference/architecture.mdx | 2 +- docs/reference/enterprise-readiness.mdx | 4 ++-- docs/reference/network-policies.mdx | 4 ++++ 7 files changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/about/ecosystem-deepagents.mdx b/docs/about/ecosystem-deepagents.mdx index 98052577173..b57c09467e8 100644 --- a/docs/about/ecosystem-deepagents.mdx +++ b/docs/about/ecosystem-deepagents.mdx @@ -74,7 +74,7 @@ The following table compares custom OpenShell integration with `nemo-deepagents | Capability | Custom OpenShell + Deep Agents | `nemo-deepagents onboard` | |---|---|---| | Sandbox isolation | You define and apply OpenShell seccomp, Landlock, network namespace isolation, and no-new-privileges policy. | NemoClaw applies the managed Deep Agents policy through the blueprint and requires the runtime checks that the managed agent runtime depends on. | -| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding, points Deep Agents at `https://inference.local/v1`, and keeps provider credentials outside the sandbox. | +| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding and keeps provider credentials outside the sandbox. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses a sandbox-attached provider for `https://integrate.api.nvidia.com/v1`. | | Image hardening | Depends on your base image and install steps. | NemoClaw installs the pinned Deep Agents Code package in `/opt/venv`, uses managed launchers, and rejects unsupported runtime paths such as unmanaged MCP autoloading, nested sandbox providers, and alternate model routes. | | Filesystem policy | You define read-only and read-write paths in policy YAML. | NemoClaw defines a targeted layout: system paths are read-only, `/sandbox` and `/tmp` are writable, and Deep Agents state lives under `/sandbox/.deepagents`. | | Inference setup | You configure OpenShell inference routing and Deep Agents provider settings manually. | NemoClaw validates the selected provider from the host, configures the OpenShell route, and writes `/sandbox/.deepagents/config.toml` for the managed OpenAI-compatible path. | @@ -104,6 +104,6 @@ Use the following table to choose NemoClaw or custom OpenShell integration. - [About Managed MCP Servers](../manage-sandboxes/mcp-servers/about-managed-mcp-servers) explains the managed MCP security and lifecycle boundary. - [Understand Deep Agents Trace Export](../monitoring/understand-deepagents-trace-export) explains the managed trace data and receiver trust boundaries. - [Quickstart with Deep Agents](../get-started/quickstart) installs NemoClaw and launches your first Deep Agents sandbox. -- [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) explains provider choices and the `inference.local` route. +- [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) explains provider choices, shared `inference.local` routes, and the native NVIDIA provider path. - [Deep Agents Code overview](https://docs.langchain.com/oss/python/deepagents/code/overview) explains upstream `dcode` capabilities and commands. - [Community Solutions](../resources/community-contributions) explains how to contribute community-driven examples, showcases, and complete blueprint patterns. diff --git a/docs/about/how-it-works.mdx b/docs/about/how-it-works.mdx index 1b0aee9b72c..4bb9cfd3a3c 100644 --- a/docs/about/how-it-works.mdx +++ b/docs/about/how-it-works.mdx @@ -210,9 +210,10 @@ Refer to [Recover and Rebuild Sandboxes](../manage-sandboxes/operate-sandboxes/r ## Inference Routing -Managed agent runtimes send model requests to `inference.local` instead of an upstream endpoint. -During onboarding, NemoClaw validates the selected provider and model, configures the OpenShell inference route, and writes the matching model reference into the managed agent configuration. -OpenShell keeps the provider credential outside the sandbox and sends approved requests to the upstream endpoint. +Most managed providers send model requests through `inference.local` instead of directly to an upstream endpoint. +NVIDIA Endpoints uses a sandbox-attached OpenShell provider that permits approved requests to `integrate.api.nvidia.com`. +During onboarding, NemoClaw validates the selected provider and model, configures the applicable OpenShell route or provider attachment, and writes the matching model reference into the managed agent configuration. +In both paths, OpenShell keeps the provider credential outside the sandbox and sends only approved requests to the upstream endpoint. When you select the Model Router provider, `inference.local` routes to a host-side router that chooses from a configured model pool available through NVIDIA Endpoints for each request. diff --git a/docs/about/overview.mdx b/docs/about/overview.mdx index 985f9ea9ed6..9f2b4035a61 100644 --- a/docs/about/overview.mdx +++ b/docs/about/overview.mdx @@ -37,7 +37,7 @@ NemoClaw groups its supported capabilities around running, connecting, controlli | Area | Capability | |---|---| | Run supported agents | Onboards OpenClaw, Hermes, or LangChain Deep Agents Code into an agent-specific sandbox image and configuration. | -| Route inference | Connects supported hosted inference and local inference providers through `inference.local`. OpenShell keeps provider credentials outside the sandbox. | +| Route inference | Connects supported hosted and local inference providers through OpenShell-managed routes. Most use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. | | Control sandbox access | Applies network policy, filesystem policy, process controls, and managed inference through OpenShell. | | Operate the lifecycle | Reports host readiness, creates or updates sandboxes, reports status and logs, and rebuilds or recovers sandboxes while preserving the native agent home. | | Connect Model Context Protocol (MCP) servers | Manages authenticated HTTPS Streamable HTTP MCP servers for all supported agent runtimes. OpenShell replaces credential placeholders at approved egress boundaries. | diff --git a/docs/manage-sandboxes/workspace-files.mdx b/docs/manage-sandboxes/workspace-files.mdx index a322b5e0c62..9bf47acf798 100644 --- a/docs/manage-sandboxes/workspace-files.mdx +++ b/docs/manage-sandboxes/workspace-files.mdx @@ -283,7 +283,7 @@ Deep Agents Code normally creates the `/sandbox/.deepagents/agent/` paths below | Path | Purpose | |---|---| -| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the managed `inference.local` route. | +| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path, including shared `inference.local` routes or the native NVIDIA provider. | | `/sandbox/.deepagents/.state/` | Deep Agents Code runtime state, including persisted session and MCP-related state. | | `/sandbox/.deepagents/agent/AGENTS.md` | Global memory file for the default Deep Agents Code agent, loaded at session start. | | `/sandbox/.deepagents/agent/memories/` | Topic-specific markdown memories that Deep Agents Code can read and update across sessions. | diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 0fa8eaf4525..e79b1e9cc20 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -213,7 +213,7 @@ The concrete files differ by agent because each runtime has its own plugin syste | Hermes | `agents/hermes/manifest.yaml`, `agents/hermes/runtime-config-guard.py`, `agents/hermes/config/`, and `agents/hermes/start.sh` | Declares the Hermes agent contract, materializes and guards managed runtime configuration during startup, and launches `hermes gateway run` behind the OpenShell proxy. | -| Deep Agents | `agents/langchain-deepagents-code/manifest.yaml`, `agents/langchain-deepagents-code/generate-config.ts`, `agents/langchain-deepagents-code/start.sh`, and the managed `dcode` launchers | Declares the terminal agent contract, writes `/sandbox/.deepagents/config.toml`, installs managed wrappers for `dcode` and `dcode -n`, and routes inference through `inference.local`. | +| Deep Agents | `agents/langchain-deepagents-code/manifest.yaml`, `agents/langchain-deepagents-code/generate-config.ts`, `agents/langchain-deepagents-code/start.sh`, and the managed `dcode` launchers | Declares the terminal agent contract, writes `/sandbox/.deepagents/config.toml`, installs managed wrappers for `dcode` and `dcode -n`, and routes inference through the selected OpenShell-managed path. | diff --git a/docs/reference/enterprise-readiness.mdx b/docs/reference/enterprise-readiness.mdx index 1a2a04f8342..48541df5164 100644 --- a/docs/reference/enterprise-readiness.mdx +++ b/docs/reference/enterprise-readiness.mdx @@ -82,7 +82,7 @@ Each row links to deeper documentation and, when a concrete fix is in progress, | Audit and session records | Supported with caveats | OpenClaw stores per-session JSONL event logs, and Hermes stores its own runtime state. Deep Agents Code has no equivalent session-log export, but it can emit bounded-content traces when you explicitly enable observability. Export is manual per sandbox. | | Resource quotas | Supported with caveats | The entrypoint applies best-effort process and file-descriptor limits (`ulimit -u 512`, `ulimit -n 65536`). Set hard limits through the container runtime for fail-closed enforcement. Refer to [Process Controls](../security/security-controls/process-controls). | | Cost and spend controls | Platform or partner-owned | Deny-by-default egress and routed inference reduce exfiltration and stray endpoints, but NemoClaw does not enforce per-token spend budgets. Set spend limits with your inference provider and monitor unattended agents. | -| Credential isolation | Supported | Inference credentials stay on the host and never enter the sandbox; the agent reaches models through `inference.local`. CLI output redaction adds defense in depth, and OpenClaw sandboxes also run a memory secret scanner. Refer to [Credential Storage](../security/credential-storage) and [Security Best Practices](../security/best-practices). | +| Credential isolation | Supported | Inference credentials stay in OpenShell provider state and never enter the sandbox. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. CLI output redaction adds defense in depth, and OpenClaw sandboxes also run a memory secret scanner. Refer to [Credential Storage](../security/credential-storage) and [Security Best Practices](../security/best-practices). | | Upgrades and lifecycle | Supported with caveats | Upgrade NemoClaw, then run `$$nemoclaw rebuild` to recreate the sandbox with the current image while backing up and restoring its complete native home. Do not update the agent runtime in place inside the sandbox because the agent is image-pinned. Version attachment flexibility remains tracked in [#2217](https://github.com/NVIDIA/NemoClaw/issues/2217). | | State persistence | Supported | OpenShell preserves the native home/workspace across routine lifecycle operations. NemoClaw transfers the complete native tree during rebuild and recreation. Refer to [Persist Sandbox State](../manage-sandboxes/state-and-backups/create-and-restore-snapshots). | | Remote and cloud deployment | Supported with caveats | Provision a tested Linux host, connect over SSH, run the installer, and run `$$nemoclaw onboard`. For OpenClaw or Hermes, keep the agent dashboard bound to loopback and access it through SSH port forwarding. Automatic recovery after a host reboot is not guaranteed; follow the manual recovery flow in [Deploy to a Headless Server](../deployment/deploy-to-headless-server). | @@ -132,7 +132,7 @@ Use the following phrasing to describe NemoClaw accurately in customer and field - Describe NemoClaw as an open-source reference stack for running agents more safely inside OpenShell, in active development, rather than a finished enterprise control plane. - State that egress is deny-by-default and that an operator approves new endpoints, so the agent cannot reach arbitrary hosts. -- Explain that inference credentials stay on the host and the agent calls models through a routed `inference.local` endpoint, so the sandbox never holds provider keys. +- Explain that inference credentials remain in OpenShell provider state, so the sandbox never holds provider keys. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. - Frame centralized fleet management, operator RBAC, enterprise SSO, and multi-tenant isolation as roadmap-only or out of scope today, and avoid presenting them as current capabilities. - Position cost controls and spend limits as provider-owned, and recommend setting provider-side limits for unattended agents. - When a customer hits a known limitation, point to the workaround in this guide and the tracked issue rather than promising a fix date. diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index ab6ae7d1e02..fa0f976d18b 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -86,6 +86,10 @@ The separate `raw.githubusercontent.com` route lets Deep Agents Code follow GitH +When you select NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1` provider to the sandbox instead of using `inference.local`. +Its provider profile permits `GET /v1/models` and `POST /v1/chat/completions` at `integrate.api.nvidia.com:443` from the listed agent-runtime and readiness-verification binaries. +The NVIDIA API key remains in OpenShell provider state and does not enter the sandbox. + All endpoints use TLS termination and are enforced at port 443. From 5c0921146453c7bc9c70aef573a22100d1b43dc6 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 13:15:06 -0700 Subject: [PATCH 021/133] fix: complete native NVIDIA provider attachment --- ci/platform-matrix.json | 6 ++-- docs/deployment/deploy-to-headless-server.mdx | 2 +- .../understand-provider-validation.mdx | 2 +- docs/reference/commands.mdx | 16 ++++----- docs/reference/platform-support.mdx | 4 +-- docs/security/best-practices.mdx | 16 ++++----- .../status-snapshot-route-drift.test.ts | 35 +++++++++++++++++++ src/lib/actions/sandbox/status-snapshot.ts | 13 ++++--- src/lib/inference/native-nvidia/index.ts | 12 +++++++ .../orchestration-native-nvidia.test.ts | 28 ++++++++++++++- .../onboard/sandbox-create/orchestration.ts | 10 +++--- .../sandbox-create/provider-publication.ts | 4 +-- .../live/hermes-inference-switch-helpers.ts | 8 +++-- ...mes-inference-switch-command-shape.test.ts | 9 +++++ 14 files changed, 128 insertions(+), 37 deletions(-) diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index f35f6c6d323..c9a7862c5bc 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -190,7 +190,7 @@ "name": "LangChain Deep Agents Code", "status": "tested", "default": false, - "notes": "Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. Inference routes through OpenShell's `inference.local` endpoint through the Deep Agents Code OpenAI-compatible provider. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861." + "notes": "Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. Most inference uses OpenShell's `inference.local` endpoint through the Deep Agents Code OpenAI-compatible provider. NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861." } ], @@ -206,9 +206,9 @@ "notes": "Landlock, seccomp, network namespace isolation, no-new-privileges, privilege dropping, and process limits (nproc 512 at `scripts/lib/sandbox-rlimits.sh:8`) are tested and on by default. OpenShell owns capability enforcement for managed entrypoints, exec processes, and connect shells; those paths do not call NemoClaw capability handling. Direct container runtimes that explicitly override the image user to root retain the existing compatibility drop and required `setpriv` transition. Direct container launches must configure capabilities at the container runtime." }, { - "name": "Routed inference", + "name": "Managed inference", "status": "tested", - "notes": "Provider-routed model calls through the OpenShell gateway, transparent to the agent. The agent uses `inference.local` inside the sandbox; provider credentials stay on the host. Supports every entry in the Providers table." + "notes": "Provider-routed model calls through OpenShell, transparent to the agent. Most providers use `inference.local` inside the sandbox; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table." }, { "name": "Declarative network policy", diff --git a/docs/deployment/deploy-to-headless-server.mdx b/docs/deployment/deploy-to-headless-server.mdx index efec51506f0..ee3889de079 100644 --- a/docs/deployment/deploy-to-headless-server.mdx +++ b/docs/deployment/deploy-to-headless-server.mdx @@ -269,7 +269,7 @@ unset TOKEN -Deep Agents Code does not expose a dashboard URL or gateway token. Model traffic uses the OpenShell-managed `inference.local` route. +Deep Agents Code does not expose a dashboard URL or gateway token. Most model traffic uses the OpenShell-managed `inference.local` route. NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. diff --git a/docs/inference/understand-provider-validation.mdx b/docs/inference/understand-provider-validation.mdx index cdb45c4a758..a9de17568bc 100644 --- a/docs/inference/understand-provider-validation.mdx +++ b/docs/inference/understand-provider-validation.mdx @@ -52,7 +52,7 @@ If the last retry fails or times out, validation stops without another Chat Comp -The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions through `https://inference.local/v1`. +The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. `NEMOCLAW_PREFERRED_API` does not change that runtime selection. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index b3a24e20c96..bee27a7427e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1612,7 +1612,7 @@ $$nemoclaw my-assistant start When that deadline expires, `start` keeps the existing container, exits non-zero, and prints the `NEMOCLAW_CONNECT_TIMEOUT` value to use on the next run. -After the gateway and forward checks pass, `start` sends one inference request through `https://inference.local` using the sandbox's recorded provider and model. A gateway that answers the `/v1/models` probe can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the route returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted route. When the sandbox records no provider or no model, `start` skips the request and exits `0`. `doctor` still classifies an HTTP `401` or `403` route response as reachable, so correct the provider credential when `start` reports one of those statuses. +After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Most providers use `https://inference.local`; NVIDIA Endpoints uses the sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. `doctor` still classifies an HTTP `401` or `403` route response as reachable, so correct the provider credential when `start` reports one of those statuses. ### `$$nemoclaw status` @@ -1628,7 +1628,7 @@ nonzero. A stopped runtime without recorded stop intent remains a For a `compatible-endpoint` route that uses `openai-completions`, the text output prints `Reasoning effort` as `low`, `medium`, `high`, or `endpoint-default`. The line is omitted for another provider or API family. -Pass `--json` to emit a structured per-sandbox report instead of the text renderer. The JSON output includes at least `schemaVersion`, `name`, `found`, `agent`, `agentDisplayName`, `agentRuntime`, `dcodeAutoApprovalMode`, `model`, `provider`, `recordedRoute`, `liveRoute`, `routeDrift`, `phase`, `gatewayState`, `inferenceHealth`, `rpcIssue`, `hostGpuDetected`, `sandboxGpuEnabled`, `sandboxGpuMode`, `sandboxGpuDevice`, `openshellDriver`, `openshellVersion`, `policies`, `policiesAvailable`, `llamaCpp`, `failureLayer`, `terminalRuntimeHealth`, `servingProcessHealth`, and `dockerPaused`. `policies` is derived from the current OpenShell policy; NemoClaw does not persist a second preset list or baseline-exclusion ledger. `policiesAvailable` is `false` when that live policy cannot be read or parsed, distinguishing an unavailable result from a verified empty `policies` array; text status prints `Policies: unavailable` for the same state. When the live gateway route matches the sandbox's recorded llama.cpp route, `llamaCpp.kind` is `attached`, `managed`, or `unavailable`. An attached route also includes its fixed loopback `llamaCpp.endpointUrl`. An unavailable result means NemoClaw could not safely verify the managed ownership receipt; it does not include an endpoint and provides a secret-free diagnostic and recovery action. During route drift, `status` omits the `llamaCpp` route attribution; inspect `routeDrift` before acting on endpoint information. Text status can still show managed-runtime details from the sandbox-owned receipt. The schema-version `1` `model` and `provider` fields keep their established live-route meaning when the gateway route is readable. Use `recordedRoute` for the sandbox's durable provider and model and `liveRoute` for the gateway-global route. When the live shared route differs, text output prints both routes and JSON output sets `routeDrift.live`, `routeDrift.recorded`, and `routeDrift.canConnect`. When `routeDrift.canConnect` is `false`, `connect` cannot safely restore the recorded route because provider-global identity differs or required route or gateway metadata is incomplete. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for the route-sharing workflow. `openshellDriver` and `openshellVersion` are always strings (falling back to `"unknown"` when the registry has no value), so consumers can rely on `typeof` checks. `agent` is always a string and reports `openclaw` when the registry records no agent for the sandbox. `failureLayer` is `null` when no preflight failure was detected and otherwise one of `docker_unreachable`, `sandbox_container_stopped`, or `sandbox_dashboard_port_conflict`; when set, `inferenceHealth` is suppressed to `null` so automation does not see a stale remote-provider healthy status during a local outage. `inferenceHealth.ok` reports whether the inference route returned a structurally valid result for one request sent from inside the sandbox. The result must match Chat Completions, Responses, or Anthropic Messages for the selected route. An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. The probe captures at most 64 KiB and does not include the response body in diagnostics. The route probe treats any final HTTP status from `200` through `499` as reachable, so a route with an invalidated provider credential answers HTTP `401` while the route is up. The request uses the live gateway route's provider and model, and falls back to the recorded values when the live route is unreadable. When the live provider matches the recorded provider, the request uses the sandbox's recorded API family, even when only the model differs. This includes `openai-responses`. When the live provider differs, NemoClaw does not carry the recorded API family to the live provider. Each attempt requests 16 reply tokens for ordinary providers or 256 for Gemini. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Hosted routes consume provider tokens on every attempt. When the inference request returns HTTP `429`, `502`, `503`, or `504`, `status` retries the route and inference request together up to three total attempts, with a two-second delay between failed attempts, because those statuses are transient gateway and availability answers rather than evidence that the route is broken. Before each retry, it writes the failed probe boundary, an HTTP status when one is available, the next attempt, total attempts, and delay to stderr; `--json` keeps stdout machine-readable. On an ordinary run, every other failure is final on the first attempt with no delay: HTTP `401`, `403`, `404`, and `500`, an invalid 2xx response body, a request that returned no HTTP status, and a failing `/v1/models` route probe. When the same run recovers a managed gateway, `status` retries any failed route or inference probe on that schedule instead, while the restarted delivery chain settles. Each route probe has a 10-second timeout. Three complete route probes plus their 95-second inference wrappers and two delays can take about 319 seconds. When NemoClaw sends an inference request, `inferenceHealth.subprobes` reports the route probe result as the `route reachability` hop, so a failing verdict still shows that the route itself answered. `inferenceHealth.failureLabel` reports why the inference request failed: +Pass `--json` to emit a structured per-sandbox report instead of the text renderer. The JSON output includes at least `schemaVersion`, `name`, `found`, `agent`, `agentDisplayName`, `agentRuntime`, `dcodeAutoApprovalMode`, `model`, `provider`, `recordedRoute`, `liveRoute`, `routeDrift`, `phase`, `gatewayState`, `inferenceHealth`, `rpcIssue`, `hostGpuDetected`, `sandboxGpuEnabled`, `sandboxGpuMode`, `sandboxGpuDevice`, `openshellDriver`, `openshellVersion`, `policies`, `policiesAvailable`, `llamaCpp`, `failureLayer`, `terminalRuntimeHealth`, `servingProcessHealth`, and `dockerPaused`. `policies` is derived from the current OpenShell policy; NemoClaw does not persist a second preset list or baseline-exclusion ledger. `policiesAvailable` is `false` when that live policy cannot be read or parsed, distinguishing an unavailable result from a verified empty `policies` array; text status prints `Policies: unavailable` for the same state. When the live gateway route matches the sandbox's recorded llama.cpp route, `llamaCpp.kind` is `attached`, `managed`, or `unavailable`. An attached route also includes its fixed loopback `llamaCpp.endpointUrl`. An unavailable result means NemoClaw could not safely verify the managed ownership receipt; it does not include an endpoint and provides a secret-free diagnostic and recovery action. During route drift, `status` omits the `llamaCpp` route attribution; inspect `routeDrift` before acting on endpoint information. Text status can still show managed-runtime details from the sandbox-owned receipt. The schema-version `1` `model` and `provider` fields keep their established live-route meaning when the gateway route is readable, except that a native NVIDIA sandbox reports its recorded sandbox-scoped route because the shared route is unrelated. Use `recordedRoute` for the sandbox's durable provider and model and `liveRoute` for the gateway-global route. When the live shared route differs for a shared-route provider, text output prints both routes and JSON output sets `routeDrift.live`, `routeDrift.recorded`, and `routeDrift.canConnect`. Native NVIDIA attachments do not report shared-route drift. When `routeDrift.canConnect` is `false`, `connect` cannot safely restore the recorded route because provider-global identity differs or required route or gateway metadata is incomplete. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for the route-sharing workflow. `openshellDriver` and `openshellVersion` are always strings (falling back to `"unknown"` when the registry has no value), so consumers can rely on `typeof` checks. `agent` is always a string and reports `openclaw` when the registry records no agent for the sandbox. `failureLayer` is `null` when no preflight failure was detected and otherwise one of `docker_unreachable`, `sandbox_container_stopped`, or `sandbox_dashboard_port_conflict`; when set, `inferenceHealth` is suppressed to `null` so automation does not see a stale remote-provider healthy status during a local outage. `inferenceHealth.ok` reports whether the selected provider path returned a structurally valid result for one request sent from inside the sandbox. The result must match Chat Completions, Responses, or Anthropic Messages for the selected route. An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. The probe captures at most 64 KiB and does not include the response body in diagnostics. The path probe treats any final HTTP status from `200` through `499` as reachable, so a route with an invalidated provider credential answers HTTP `401` while the path is up. Shared-route requests use the live gateway route's provider and model, then fall back to the recorded values when the live route is unreadable. Native NVIDIA requests always use the sandbox's recorded provider and model. When the live shared provider matches the recorded provider, the request uses the sandbox's recorded API family, even when only the model differs. This includes `openai-responses`. When the live shared provider differs, NemoClaw does not carry the recorded API family to that provider. Each attempt requests 16 reply tokens for ordinary providers or 256 for Gemini. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Hosted requests consume provider tokens on every attempt. When the inference request returns HTTP `429`, `502`, `503`, or `504`, `status` retries the provider path and inference request together up to three total attempts, with a two-second delay between failed attempts, because those statuses are transient gateway and availability answers rather than evidence that the path is broken. Before each retry, it writes the failed probe boundary, an HTTP status when one is available, the next attempt, total attempts, and delay to stderr; `--json` keeps stdout machine-readable. On an ordinary run, every other failure is final on the first attempt with no delay: HTTP `401`, `403`, `404`, and `500`, an invalid 2xx response body, a request that returned no HTTP status, and a failing provider-path probe. When the same run recovers a managed gateway, `status` retries any failed route or inference probe on that schedule instead, while the restarted delivery chain settles. Each route probe has a 10-second timeout. Three complete route probes plus their 95-second inference wrappers and two delays can take about 319 seconds. When NemoClaw sends an inference request, `inferenceHealth.subprobes` reports the provider-path result as the `route reachability` hop, so a failing verdict still shows that the path itself answered. `inferenceHealth.failureLabel` reports why the inference request failed: - `unauthorized` when the route rejected it with HTTP `401` or `403`. - `unhealthy` when the route returned another failing HTTP status or an invalid 2xx response body. @@ -1661,7 +1661,7 @@ $$nemoclaw my-assistant status --json $$nemoclaw sandbox status my-assistant --json ``` -The command probes `https://inference.local/v1/models` from inside the sandbox, and when that probe reports the route reachable it sends an inference request over the same route. That inference request is the authoritative inference health check, and both checks exercise the route that agent traffic uses. The main `Inference` line reports one of these states: +The command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses the sandbox-attached provider for `https://integrate.api.nvidia.com/v1`. That inference request is the authoritative inference health check, and both checks exercise the path that agent traffic uses. The main `Inference` line reports one of these states: | State | Meaning | | --- | --- | @@ -1675,7 +1675,7 @@ The command probes `https://inference.local/v1/models` from inside the sandbox, An authentication response on the route probe alone confirms that the route is reachable, not that provider credentials are valid. `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative `inference.local` result or determine the command exit status. -The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. The gateway stores the provider credential that the sandbox route uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the `inference.local` route has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` sends no inference request, so it always reports the `Inference (upstream)` state that it measured. +The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` sends no inference request, so it always reports the `Inference (upstream)` state that it measured. Local providers add host-side backend diagnostics. For Local Ollama, the command can also print an `Inference (auth proxy)` diagnostic when a proxy token is available. Use these diagnostics to identify a failing auxiliary hop after checking the main `Inference` line. @@ -1817,7 +1817,7 @@ The `Registered gateway binding` result depends on the sandbox registry: - For an unregistered sandbox name, `doctor` uses the gateway selected by `NEMOCLAW_GATEWAY_PORT` for its other gateway checks and omits the `Registered gateway binding` check. -For inference health, `doctor` treats the probe to `https://inference.local/v1/models` from inside the sandbox as authoritative. HTTP responses from `200` through `499`, including `401` and `403`, pass this check. HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. Direct provider and upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox route is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. +For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Most providers probe `https://inference.local/v1/models`; NVIDIA Endpoints probes its sandbox-attached provider at `https://integrate.api.nvidia.com/v1/models`. HTTP responses from `200` through `499`, including `401` and `403`, pass this check. HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. Host-side upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox path is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. Warnings do not make the command fail. Failed checks, including a failed or unavailable authoritative inference route, exit non-zero so scripts can use `doctor` as a readiness gate. Use `--json` for machine-readable output. For a `compatible-endpoint` route that uses `openai-completions`, the JSON report includes an informational `Inference` check labeled `Reasoning effort`. The check reports `low`, `medium`, `high`, or `endpoint-default` and never includes credentials. Because the check has `info` status, it does not change the command's exit status. @@ -2013,7 +2013,7 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet` -`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. Model traffic uses the OpenShell-managed `inference.local` route configured by NemoClaw. +`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. Most model traffic uses the OpenShell-managed `inference.local` route. NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. @@ -3183,7 +3183,7 @@ After the rebuild succeeds, retrieve the replacement token with `nemohermes my-a -After restore, the command starts Deep Agents with the complete source native home, including `config.toml`, hooks, skills, memories, histories, packages, and unrelated native entries. Before changing the sandbox, rebuild verifies that the recorded `inference.local` route is still reachable and that the target provider, model, reasoning settings, web search selection, base image, current agent MCP source, and current live OpenShell policy can be captured. If those checks fail after backup, NemoClaw keeps the existing sandbox intact. Use rebuild after a failed Deep Agents version check, after enabling Tavily Search, or as the apply step for legacy MCP migration. +After restore, the command starts Deep Agents with the complete source native home, including `config.toml`, hooks, skills, memories, histories, packages, and unrelated native entries. Before changing the sandbox, rebuild verifies that the recorded provider path is still reachable and that the target provider, model, reasoning settings, web search selection, base image, current agent MCP source, and current live OpenShell policy can be captured. Most providers use `inference.local`; NVIDIA Endpoints uses its sandbox-attached provider at `integrate.api.nvidia.com`. If those checks fail after backup, NemoClaw keeps the existing sandbox intact. Use rebuild after a failed Deep Agents version check, after enabling Tavily Search, or as the apply step for legacy MCP migration. @@ -3477,7 +3477,7 @@ Switch the active inference provider or model for a NemoClaw-managed Hermes sand By default, the command syncs the default registered sandbox. -Each OpenShell gateway exposes one inference route to every sandbox registered on that gateway. +For providers other than NVIDIA Endpoints, each OpenShell gateway exposes one shared inference route to every sandbox registered on that gateway. NVIDIA Endpoints instead uses a sandbox-attached provider and does not change the shared route. Before changing the route, NemoClaw compares it with every same-gateway registry entry, including stopped sandboxes. When only the provider or model differs, the command names the affected sandboxes and warns immediately before it re-points the shared route. Those sandboxes use the new live route until `connect`, onboarding, or another `inference set` command re-points it. diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index 3f9717ee465..930500bbdee 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -65,7 +65,7 @@ Pick the matching onboarding entry point for each agent. |-------|--------|---------|-------| | OpenClaw | Tested | Yes | Default agent runtime. Onboard with `nemoclaw onboard` (no `--agent` flag required). | | Hermes | Tested | No | First-class agent with dedicated CLI (`nemohermes`), Dockerfile, manifest, docs, and Hermes E2E coverage in `.github/workflows/e2e.yaml` (`hermes-e2e`, `hermes-*`, and Hermes rebuild/switch jobs). Onboard with `nemohermes onboard` or `nemoclaw onboard --agent hermes`. Unlocks the Hermes Provider inference route. Known structural gaps: model-provider compatibility registry is empty (backfilled after failures, see `nemoclaw-blueprint/model-specific-setup/hermes/README.md`); no Hermes-specific unit tests in `nemoclaw/src/`; macOS and WSL CI suites do not differentiate agents. Suitable for evaluation and the documented onboarding paths; production parity with OpenClaw is not yet asserted. | -| LangChain Deep Agents Code | Tested | No | Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. Inference routes through OpenShell's `inference.local` endpoint through the Deep Agents Code OpenAI-compatible provider. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861. | +| LangChain Deep Agents Code | Tested | No | Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. Most inference uses OpenShell's `inference.local` endpoint through the Deep Agents Code OpenAI-compatible provider. NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861. | {/* agent-status:end */} ## Platforms @@ -135,7 +135,7 @@ Each row below is a launch-facing capability claim that NemoClaw makes in docs, |------------|--------|-------| | Guided onboarding | Tested | Single-command interactive wizard (`$$nemoclaw onboard`) that walks the user through inference provider selection, credential setup, and sandbox creation or update. It opens the agent dashboard when the selected runtime provides one. Non-interactive mode is supported with `--non-interactive` and `NEMOCLAW_*` environment variables for CI and scripted installs. | | Sandboxed execution | Tested with limitations | Landlock, seccomp, network namespace isolation, no-new-privileges, privilege dropping, and process limits (nproc 512 at `scripts/lib/sandbox-rlimits.sh:8`) are tested and on by default. OpenShell owns capability enforcement for managed entrypoints, exec processes, and connect shells; those paths do not call NemoClaw capability handling. Direct container runtimes that explicitly override the image user to root retain the existing compatibility drop and required `setpriv` transition. Direct container launches must configure capabilities at the container runtime. | -| Routed inference | Tested | Provider-routed model calls through the OpenShell gateway, transparent to the agent. The agent uses `inference.local` inside the sandbox; provider credentials stay on the host. Supports every entry in the Providers table. | +| Managed inference | Tested | Provider-routed model calls through OpenShell, transparent to the agent. Most providers use `inference.local` inside the sandbox; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table. | | Declarative network policy | Tested | YAML-defined egress with policy presets. Presets include `slack`, `discord`, `telegram`, `weather`, `openclaw-pricing`, `huggingface`, `npm`, `pypi`, `brew`, and others. Hot-reloadable at runtime with `$$nemoclaw policy add`. | | State persistence and rebuild transfer | Tested | OpenShell preserves the native agent home during routine lifecycle operations. Before destructive replacement, NemoClaw archives and integrity-checks the complete native home/workspace, then restores it into the replacement sandbox. | | Agent skills | Tested | Packaged agent skills are discoverable by Cursor, Claude Code, and other coding assistants under `.agents/skills/`. Skills also install into the sandbox with `$$nemoclaw skill install`. | diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index cb00f391916..e03e3e25f24 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -144,7 +144,7 @@ NemoClaw's host-local Amazon Bedrock adapter runs outside this sandbox credentia #### Hermes Managed Inference Credential Discovery -NemoClaw configures Hermes with a custom provider through `inference.local`, and the shipped Hermes image does not install the optional native Bedrock dependency. +NemoClaw configures Hermes with a custom provider. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. The shipped Hermes image does not install the optional native Bedrock dependency. AWS credential discovery for supported Bedrock inference therefore remains in NemoClaw's host-local adapter, outside the sandbox. If direct Hermes Bedrock support is added later, it must apply the same unavailable-metadata rule and include Hermes-specific credential-probe acceptance tests before it is enabled. @@ -153,7 +153,7 @@ If direct Hermes Bedrock support is added later, it must apply the same unavaila #### Deep Agents Managed Inference Credential Discovery -NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route through `inference.local`. +NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. The sandbox receives a placeholder route key, not the upstream provider credential. The managed launchers reject credential-shaped environment values and upstream auth files before Deep Agents Code starts, so provider discovery stays on the host-side OpenShell boundary. If you need a new sandbox-direct credential source, design it as an explicit provider or MCP integration instead of placing secrets in `/sandbox/.deepagents`. @@ -298,17 +298,17 @@ Review runtime-specific gateway access, dashboard exposure where applicable, sec OpenShell routes all inference traffic through the gateway to isolate provider credentials from the sandbox. -### Routed Inference through `inference.local` +### OpenShell-managed inference paths -The OpenShell gateway intercepts all inference requests from the agent and routes them to the configured provider. +OpenShell mediates all inference requests from the agent and routes them to the configured provider. The agent never receives the provider API key. | Aspect | Detail | |---|---| -| Default | The agent talks to `inference.local`. The host owns the credential and upstream endpoint. | -| What you can change | You cannot configure this architecture. The system always enforces it. | -| Risk if bypassed | If the agent could reach an inference endpoint directly (by adding it to the network policy), it would need an API key. Since the sandbox does not contain credentials, this acts as defense-in-depth. However, adding an inference provider's host to the network policy without going through OpenShell routing could let the agent use a stolen or hardcoded key. | -| Recommendation | Do not add inference provider hosts (such as `api.openai.com` or `api.anthropic.com`) to the network policy for NemoClaw model traffic. Use OpenShell inference routing instead. The `claude-code` preset is a separate opt-in exception for running the Claude Code CLI with its own credentials, not a way to configure NemoClaw inference. | +| Default | Most providers use the shared `inference.local` route. NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell owns the credential and upstream endpoint in both cases. | +| What you can change | You select a supported provider. NemoClaw selects and enforces that provider's managed path. | +| Risk if bypassed | Adding an unowned provider endpoint to network policy bypasses NemoClaw's managed provider boundary and could let an agent use a stolen or hardcoded key. The NVIDIA Endpoints path is not a bypass: its checked-in OpenShell provider profile restricts the endpoint, methods, paths, and binaries, then rewrites a placeholder credential at the egress boundary. | +| Recommendation | Do not add inference provider hosts to network policy for NemoClaw model traffic. Use the provider path created by onboarding. The `claude-code` preset is a separate opt-in exception for running the Claude Code CLI with its own credentials, not a way to configure NemoClaw inference. | ### Provider Trust Tiers diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index da4a9cd38fb..20cb1ee455f 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -521,4 +521,39 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = ); expect(snapshot.inferenceHealth).toMatchObject({ ok: true, probed: true }); }); + + it("reports the recorded native NVIDIA route when the shared route differs", async () => { + liveGatewayInference("compatible-endpoint", "other/model"); + const sandbox = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-123", + }, + } as SandboxEntry; + const options = snapshotDeps(sandbox); + + const report = await getSandboxStatusReport("alpha", { + ...options.deps, + getGatewayPresets: async () => [], + } as never); + + expect(report.provider).toBe("nvidia-prod"); + expect(report.model).toBe("nvidia/nemotron-3-super-120b-a12b"); + expect(report.recordedRoute).toEqual({ + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + }); + expect(report.liveRoute).toEqual({ + provider: "compatible-endpoint", + model: "other/model", + }); + expect(report.routeDrift).toBeNull(); + }); }); diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index c4091e75fa0..e21dce72417 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -872,6 +872,9 @@ async function buildSandboxStatusReport( const livePolicies = sb && deps.getGatewayPresets ? await deps.getGatewayPresets(sandboxName, undefined, sb) : []; const agent = resolveSandboxStatusAgent(sb?.agent || "openclaw"); + const nativeNvidia = Boolean( + normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), + ); return { schemaVersion: 1, name: sandboxName, @@ -881,11 +884,11 @@ async function buildSandboxStatusReport( agentRuntime: agent.agentRuntime, dcodeAutoApprovalMode: resolveSandboxStatusDcodeAutoApprovalMode(sb), ...(agent.agentLoadError ? { agentLoadError: agent.agentLoadError } : {}), - // Keep schema v1's established live-first fields for existing consumers. - // The explicit route fields separate durable sandbox intent from the one - // gateway-global route without changing those legacy meanings. - model: liveRoute?.model ?? currentModel, - provider: liveRoute?.provider ?? currentProvider, + // Native NVIDIA inference is sandbox-attached and independent of the + // gateway-global route. Other schema-v1 consumers keep the established + // live-first fields, with explicit route fields separating both views. + model: nativeNvidia ? currentModel : (liveRoute?.model ?? currentModel), + provider: nativeNvidia ? currentProvider : (liveRoute?.provider ?? currentProvider), servingProfileProvenance: sb?.servingProfileProvenance ?? null, llamaCpp, recordedRoute, diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 53555d2ddb8..b2a78ee9689 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -259,6 +259,18 @@ export async function ensureNativeNvidiaProviderAttached(input: { sandboxName: string; expected: NativeNvidiaProviderAttachment; }): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { + const provider = await inspectNativeProvider(input.adapter, input.target); + if (!provider) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, + ); + } + const receipt = attachmentFromMetadata(provider); + if (receipt.providerId !== input.expected.providerId) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, + ); + } const before = await input.adapter.listProviderAttachments({ target: input.target, sandboxName: input.sandboxName, diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index 56788f54c01..5081c0bbf6d 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -80,13 +80,39 @@ describe("native NVIDIA post-create provider verification", () => { ).resolves.toBeUndefined(); expect(revalidateSandboxIdentity).toHaveBeenCalledWith( - "verifying native NVIDIA provider attachment for sandbox 'alpha'", + "attaching and verifying native NVIDIA provider for sandbox 'alpha'", ); expect(adapter.listProviderAttachments).toHaveBeenCalledWith( expect.objectContaining({ sandboxName: "alpha" }), ); }); + it("attaches the recorded provider after verified sandbox creation", async () => { + const adapter = providerAdapter(recordedProviderId); + vi.mocked(adapter.listProviderAttachments) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ + ok: true, + value: { names: ["nemoclaw-nvidia-prod-v1"] }, + }); + adapter.attachProvider = vi.fn(async () => ({ + ok: true, + value: { changed: true }, + })); + const boundary = nativeProviderBoundary(adapter); + + await expect( + boundary.runAfterVerifiedCreate?.(verifiedCreateContext()), + ).resolves.toBeUndefined(); + + expect(adapter.attachProvider).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + providerName: "nemoclaw-nvidia-prod-v1", + }); + expect(adapter.listProviderAttachments).toHaveBeenCalledTimes(2); + }); + it("rejects a replaced provider before inspecting its sandbox attachments", async () => { const adapter = providerAdapter("99999999-2222-4333-8444-555555555555"); const boundary = nativeProviderBoundary(adapter); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 9f245c0e83f..f1093b70c09 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1434,10 +1434,12 @@ export function createProviderEffectBoundary(input: { input.preparationInput, input.preparationDeps, ); - const verifyNativeNvidiaAttachment = async (context: VerifiedSandboxCreateEffectsContext) => { + const attachAndVerifyNativeNvidiaProvider = async ( + context: VerifiedSandboxCreateEffectsContext, + ) => { if (!usesNativeNvidiaProvider(input.preparationInput.inferenceProvider)) return; context.revalidateSandboxIdentity( - `verifying native NVIDIA provider attachment for sandbox '${input.sandboxName}'`, + `attaching and verifying native NVIDIA provider for sandbox '${input.sandboxName}'`, ); await verifyNativeNvidiaAttachmentAfterCreate({ sandboxName: input.sandboxName, @@ -1455,7 +1457,7 @@ export function createProviderEffectBoundary(input: { await publish(); }, runAfterVerifiedCreate: usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) - ? verifyNativeNvidiaAttachment + ? attachAndVerifyNativeNvidiaProvider : undefined, }; } @@ -1477,7 +1479,7 @@ export function createProviderEffectBoundary(input: { `publishing deferred providers for sandbox '${input.sandboxName}'`, ); await publish(); - await verifyNativeNvidiaAttachment(context); + await attachAndVerifyNativeNvidiaProvider(context); context.revalidateSandboxIdentity( `attaching deferred providers to sandbox '${input.sandboxName}'`, ); diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index 7402aacbe24..ba011e54ea6 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -11,8 +11,8 @@ import type { OpenShellGatewayEndpointEnvironment } from "../../adapters/openshe import { namedOpenShellGateway } from "../../adapters/openshell/sandbox-observer"; import { REPOSITORY_ROOT } from "../../core/repository-root"; import { + ensureNativeNvidiaProviderAttached, NVIDIA_HOSTED_NATIVE_PROVIDER, - verifyNativeNvidiaProviderAttachment, } from "../../inference/native-nvidia"; import { messagingCredentialProviderProfilePath, @@ -81,7 +81,7 @@ export async function verifyNativeNvidiaAttachmentAfterCreate(input: { `Sandbox '${input.sandboxName}' is missing its native NVIDIA provider identity receipt.`, ); } - await verifyNativeNvidiaProviderAttachment({ + await ensureNativeNvidiaProviderAttached({ adapter: resolveProviderAdapter(input.deps), target: namedOpenShellGateway(input.gatewayName), sandboxName: input.sandboxName, diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index cca018a529d..e3694f4248f 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -811,11 +811,15 @@ function quotePayload(payload: string): string { return payload.replace(/'/gu, `'\\''`); } -const NATIVE_NVIDIA_AUTH_HEADER = "Author" + "ization: Bearer nemoclaw-openshell-provider"; +const NATIVE_NVIDIA_PROVIDER_PLACEHOLDER_AUTH_HEADER = + "Author" + "ization: Bearer nemoclaw-openshell-provider"; export function sandboxInferenceCommand(payload: string): string { if (SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER) { - return `curl -sS --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H '${NATIVE_NVIDIA_AUTH_HEADER}' -d '${quotePayload(payload)}'`; + // The upstream URL is the managed route for an attached OpenShell + // provider. OpenShell authorizes this profile-scoped request and replaces + // the placeholder without exposing the provider credential to the sandbox. + return `curl -sS --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H '${NATIVE_NVIDIA_PROVIDER_PLACEHOLDER_AUTH_HEADER}' -d '${quotePayload(payload)}'`; } return RUNTIME_SWITCH_API === "anthropic-messages" ? `curl -sS --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '${quotePayload(payload)}'` 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 1ca42e559d0..480fce35dbc 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -32,6 +32,7 @@ import { runHermesCliPongWithRetry, runHermesPongWithRetry, SANDBOX_NAME, + sandboxInferenceCommand, } from "../live/hermes-inference-switch-helpers.ts"; import { PUBLIC_NVIDIA_SWITCH_PROVIDER, @@ -81,6 +82,14 @@ describe("Hermes inference switch command shape", () => { expect(openshell).toHaveBeenCalledOnce(); }); + it("probes native NVIDIA through its sandbox-attached provider route (#12558)", () => { + const command = sandboxInferenceCommand('{"model":"nvidia/test"}'); + + expect(command).toContain("https://integrate.api.nvidia.com/v1/chat/completions"); + expect(command).toContain("Authorization: Bearer nemoclaw-openshell-provider"); + expect(command).not.toContain("inference.local"); + }); + it.each([ ["absent", undefined], [ From 2f4896e24a420657f2a944910b831e6914565bcf Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 13:53:58 -0700 Subject: [PATCH 022/133] docs: clarify native NVIDIA inference path --- docs/reference/architecture.mdx | 44 +++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index e79b1e9cc20..d463d2cd802 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -29,7 +29,8 @@ graph LR USER(["👤 User"]):::user subgraph EXTERNAL["External Services"] - INFERENCE["Inference Provider
NVIDIA Endpoints · OpenAI
Anthropic · Ollama · vLLM · Model Router
"]:::external + SHARED_INFERENCE["Shared-route inference providers
OpenAI · Anthropic · Ollama
vLLM · Model Router
"]:::external + NVIDIA_INFERENCE["NVIDIA Endpoints
integrate.api.nvidia.com"]:::external INTEGRATIONS["Integration APIs
MCP · GitHub · package indexes"]:::external INTERNET["Internet
PyPI · npm · GitHub · APIs"]:::external end @@ -64,8 +65,9 @@ graph LR BP -->|"Defines sandbox
shape + policies"| SANDBOX STATE -->|"Backup + restore"| SANDBOX - AGENT -->|"Inference requests
no credentials"| GW - GW -->|"Proxied with
credential injected"| INFERENCE + AGENT -->|"Most inference requests
inference.local · no credentials"| GW + GW -->|"Shared-route request with
credential injected"| SHARED_INFERENCE + AGENT -->|"Attached NVIDIA provider
restricted request · placeholder credential"| NVIDIA_INFERENCE INTEGRATIONS -->|"External APIs"| INTEG INTEG -->|"Policy-gated access"| AGENT @@ -169,12 +171,14 @@ graph TB end end - INFER["Inference provider
NVIDIA Endpoints · OpenAI
Anthropic · Ollama · vLLM · Model Router
"]:::external + SHARED_INFER["Shared-route inference provider
OpenAI · Anthropic · Ollama
vLLM · Model Router
"]:::external + NVIDIA_INFER["NVIDIA Endpoints
integrate.api.nvidia.com"]:::external CLI -->|"openshell CLI
(orchestrates)"| GW GW -->|"creates/recreates
Docker-driver sandbox"| SANDBOX - SANDBOX -->|"inference requests
placeholder credentials"| GW - GW -->|"egress with real credentials
injected at the L7 proxy"| INFER + SANDBOX -->|"shared-route requests
inference.local · placeholder credentials"| GW + GW -->|"shared-route egress
credential injected at L7 proxy"| SHARED_INFER + SANDBOX -->|"attached NVIDIA provider
restricted egress · placeholder rewritten"| NVIDIA_INFER class HOST host class DOCKER docker @@ -190,10 +194,13 @@ Layering from top to bottom: | OpenShell gateway | Host process by default; optional Linux compatibility container when the gateway binary needs a newer host ABI | Hosts the credential store, owns sandbox lifecycle coordination, and provides the L7 proxy. | | Docker daemon | Host service | Runs the Docker-driver sandbox container and, on affected Linux hosts, the optional gateway compatibility container. | | Sandbox container | Docker container | Runs the selected supported agent runtime and NemoClaw integration under Landlock + seccomp + netns. | -| OpenShell L7 proxy | Gateway process | Intercepts agent egress and rewrites `Authorization` headers (Bearer/Bot) and URL-path segments to inject the real credential at the network boundary. | +| OpenShell L7 proxy | Gateway process | Intercepts shared-route agent egress and rewrites `Authorization` headers (Bearer/Bot) and URL-path segments to inject the real credential at the network boundary. | +| OpenShell attached NVIDIA provider | Provider profile attached to the sandbox | Restricts NVIDIA Endpoints egress by host, method, path, and binary, then rewrites the placeholder credential at the egress boundary. | NemoClaw never gives the sandbox a raw provider key. -At onboard time it registers credentials with OpenShell's provider/placeholder system, and the L7 proxy substitutes the real value into outbound requests at egress. +At onboard time it registers credentials with OpenShell's provider and placeholder system. +Shared routes use the gateway L7 proxy to substitute the real value at egress. +NVIDIA Endpoints uses the sandbox-attached provider profile to enforce the restricted request and replace its placeholder at egress. The CLI helper `isInferenceRouteReady` (in `src/lib/onboard.ts`) is a host-side readiness check used by the resume flow to decide whether the active route already covers the chosen provider and model. It is not a runtime component. @@ -349,13 +356,23 @@ Inside the sandbox: ## Inference Routing -Inference requests from the agent never leave the sandbox directly. -OpenShell intercepts them and routes them to the configured provider: +Agent inference follows one of two OpenShell-managed paths. +Most providers use the shared `inference.local` route through the OpenShell gateway: ```text -Supported agent runtime (sandbox) ──▶ OpenShell gateway ──▶ Provider endpoint +Supported agent runtime (sandbox) ──▶ inference.local ──▶ OpenShell gateway ──▶ Provider endpoint ``` +NVIDIA Endpoints uses a restricted provider attached to the sandbox: + +```text +Supported agent runtime (sandbox) ──▶ integrate.api.nvidia.com ──▶ NVIDIA Endpoints + OpenShell attached-provider policy and placeholder rewrite +``` + +The NVIDIA request does not use the shared `inference.local` route. +The attached OpenShell profile allows only the configured endpoint, methods, paths, and binaries, and it replaces the placeholder credential at egress. + When you select the Model Router provider, the OpenShell gateway routes to a host-side router process instead of a single upstream model. The router selects from the configured pool, then calls the upstream NVIDIA endpoint with the credential held outside the sandbox. @@ -376,9 +393,10 @@ Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inf ## Provider Credential Storage -Provider credentials live in the OpenShell gateway store, not on the host filesystem. +Provider credentials live in OpenShell's credential store, not on the host filesystem. NemoClaw never writes them to host disk. -The OpenShell L7 proxy injects values at egress. +The OpenShell L7 proxy injects values for shared routes. +The sandbox-attached NVIDIA provider rewrites its placeholder credential at egress. Refer to [Credential Storage](../security/credential-storage) for the inspection, rotation, and migration flow. ## Host-Side State and Config From 8375e3f19fadb256ad895245564bf737ccafa249 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 14:36:48 -0700 Subject: [PATCH 023/133] fix: close native inference review gaps --- docs/security/best-practices.mdx | 2 +- .../inference-set-openclaw-run.test.ts | 62 +++++++++++- src/lib/actions/inference-set.ts | 95 +++++++++++++++---- .../actions/sandbox/inference-route-health.ts | 27 ++++++ .../status-snapshot-route-drift.test.ts | 51 ++++++++++ src/lib/actions/sandbox/status-snapshot.ts | 71 +++++++++++--- 6 files changed, 269 insertions(+), 39 deletions(-) diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index e03e3e25f24..963bf69e493 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -180,7 +180,7 @@ Endpoint rules restrict allowed HTTP methods and URL paths. | Aspect | Detail | |---|---| -| Default | Some endpoints allow GET and POST on `/**` (for example, `clawhub.ai`). Others restrict methods and paths to specific API routes (for example, `integrate.api.nvidia.com` allows POST only to inference and embedding paths and GET to model listings). Read-only endpoints such as `docs.openclaw.ai`, the OpenClaw `npm_registry` baseline entry, and the `pypi` preset allow GET only (PyPI also allows HEAD). The broader `npm` preset is an intentional exception: npm/Yarn registry traffic uses L4 pass-through for Node 22 undici CONNECT compatibility. While that preset is active, NemoClaw temporarily aligns the overlapping baseline npm endpoint with the same reviewed L4 metadata because OpenShell 0.0.116 requires a single connection mode. | +| Default | Some endpoints allow GET and POST on `/**` (for example, `clawhub.ai`). Others restrict methods and paths to specific API routes. The sandbox-attached NVIDIA inference provider allows POST only to `/v1/chat/completions` and GET only to `/v1/models`; it does not permit embedding requests. Read-only endpoints such as `docs.openclaw.ai`, the OpenClaw `npm_registry` baseline entry, and the `pypi` preset allow GET only (PyPI also allows HEAD). The broader `npm` preset is an intentional exception: npm/Yarn registry traffic uses L4 pass-through for Node 22 undici CONNECT compatibility. While that preset is active, NemoClaw temporarily aligns the overlapping baseline npm endpoint with the same reviewed L4 metadata because OpenShell 0.0.116 requires a single connection mode. | | What you can change | Add methods (PUT, DELETE, PATCH) or restrict paths to specific prefixes. | | Risk if relaxed | Allowing all methods on an API endpoint gives the agent write and delete access. For example, allowing DELETE on `api.github.com` lets the agent delete repositories. | | Recommendation | Use GET-only rules for endpoints that the agent only reads. Add write methods only for endpoints where the agent must create or modify resources. Restrict paths to specific API routes when possible. | diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index cf0f5931650..ff0e09c3418 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -82,11 +82,65 @@ describe("runInferenceSet OpenClaw routing", () => { }), ); expect(deps.calls.restartSandboxGateway).toHaveBeenCalledOnce(); - expect(deps.calls.restartSandboxGateway.mock.invocationCallOrder[0]).toBeLessThan( - detachProvider.mock.invocationCallOrder[0], + expect(detachProvider.mock.invocationCallOrder[0]).toBeLessThan( + deps.calls.restartSandboxGateway.mock.invocationCallOrder[0], ); - expect(deps.calls.updateSandbox).toHaveBeenCalledWith("alpha", { - nativeNvidiaProviderAttachment: undefined, + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ nativeNvidiaProviderAttachment: undefined }), + ); + }); + + it("does not publish a non-native route when native NVIDIA detach fails", async () => { + const providerAdapter = { + getProvider: vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { + id: "11111111-2222-4333-8444-555555555555", + resourceVersion: 1, + }, + }, + })), + detachProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "failed", message: "detach denied" }, + })), + } as unknown as OpenShellProviderAdapter; + const config: ConfigObject = { + agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, + models: { providers: {} }, + }; + const deps = createDeps({ + config, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + providerAdapter, + }); + + await expect( + runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps), + ).rejects.toThrow("Could not detach native NVIDIA provider from sandbox 'alpha'"); + + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); + expect(deps.calls.restartSandboxGateway).not.toHaveBeenCalled(); + expect(config.agents).toEqual({ + defaults: { model: { primary: "inference/nvidia/old-model" } }, }); }); diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 681a953de97..8944290e513 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -998,6 +998,57 @@ async function rollbackNativeNvidiaSelection(input: { } } +async function detachPreviousNativeNvidiaBeforePublish(input: { + selectingNativeNvidia: boolean; + previousAttachment?: NativeNvidiaProviderAttachment; + gatewayName: string; + sandboxName: string; + deps: InferenceSetDeps; +}): Promise { + if (input.selectingNativeNvidia || !input.previousAttachment) return false; + await detachNativeNvidiaProvider({ + adapter: input.deps.providerAdapter, + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: input.previousAttachment, + }); + return true; +} + +function nativeNvidiaDepartureRegistryFields( + detached: boolean, +): Pick | Record { + return detached ? { nativeNvidiaProviderAttachment: undefined } : {}; +} + +async function restorePreviousNativeNvidiaAfterFailedPublish(input: { + detached: boolean; + committed: boolean; + previousAttachment?: NativeNvidiaProviderAttachment; + gatewayName: string; + sandboxName: string; + error: unknown; + deps: InferenceSetDeps; +}): Promise { + if (!input.detached || input.committed || !input.previousAttachment) return; + try { + await ensureNativeNvidiaProviderAttached({ + adapter: input.deps.providerAdapter, + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: input.previousAttachment, + }); + } catch (reattachError) { + const detail = input.error instanceof Error ? input.error.message : String(input.error); + const recoveryDetail = + reattachError instanceof Error ? reattachError.message : String(reattachError); + throw new InferenceSetError( + `${detail}\n Native NVIDIA access was detached before the failed switch, but restoring the attachment failed: ${recoveryDetail}`, + input.error instanceof InferenceSetError ? input.error.exitCode : 1, + ); + } +} + async function applyInferenceRouteSelection(input: { nativeNvidia: boolean; provider: string; @@ -1502,6 +1553,8 @@ async function runInferenceSetWithoutHostLock( let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; let nativeNvidiaAttachmentChanged = false; let nativeNvidiaRegistryCommitted = false; + let previousNativeNvidiaDetached = false; + let previousNativeNvidiaDetachCommitted = false; const restorePreviousInferenceSelection = async (): Promise => { if (selectingNativeNvidia || previousNativeNvidiaAttachment) { appliedInferenceSelection = false; @@ -1688,6 +1741,17 @@ async function runInferenceSetWithoutHostLock( } } + // Removing native NVIDIA access is a security gate for publishing another + // route. Do not commit the non-native registry/config while the sandbox can + // still use the credential-bearing attached provider. + previousNativeNvidiaDetached = await detachPreviousNativeNvidiaBeforePublish({ + selectingNativeNvidia, + previousAttachment: previousNativeNvidiaAttachment, + gatewayName: preparedRoute.gatewayName, + sandboxName, + deps, + }); + // Write minimal registry state before any sandbox-facing config read so the // gateway and registry cannot split if the in-sandbox layer is unavailable. const registryFields = (preferredInferenceApi: string | null) => ({ @@ -1708,6 +1772,7 @@ async function runInferenceSetWithoutHostLock( }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...nativeNvidiaDepartureRegistryFields(previousNativeNvidiaDetached), }); if ( !deps.updateSandbox( @@ -1726,6 +1791,7 @@ async function runInferenceSetWithoutHostLock( ); } nativeNvidiaRegistryCommitted = Boolean(nativeNvidiaProviderAttachment); + previousNativeNvidiaDetachCommitted = previousNativeNvidiaDetached; const preferredInferenceApi = explicitPreferredInferenceApi ?? @@ -1905,6 +1971,15 @@ async function runInferenceSetWithoutHostLock( }; } catch (error) { if (error instanceof OpenClawInferenceConfigSyncError) throw error; + await restorePreviousNativeNvidiaAfterFailedPublish({ + detached: previousNativeNvidiaDetached, + committed: previousNativeNvidiaDetachCommitted, + previousAttachment: previousNativeNvidiaAttachment, + gatewayName: preparedRoute.gatewayName, + sandboxName, + error, + deps, + }); await rollbackNativeNvidiaSelection({ attachmentChanged: nativeNvidiaAttachmentChanged, registryCommitted: nativeNvidiaRegistryCommitted, @@ -2010,26 +2085,6 @@ export async function runInferenceSet( if (mutation.openClawConfigSyncPending) { clearOpenClawConfigSyncPending(selected.sandboxName, deps); } - const priorNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( - lockedSelection.entry.nativeNvidiaProviderAttachment, - ); - if (priorNativeNvidiaAttachment && !isNativeNvidiaProvider(mutation.result.provider)) { - await detachNativeNvidiaProvider({ - adapter: deps.providerAdapter, - target: { kind: "named", gatewayName }, - sandboxName: selected.sandboxName, - expected: priorNativeNvidiaAttachment, - }); - if ( - !deps.updateSandbox(selected.sandboxName, { - nativeNvidiaProviderAttachment: undefined, - }) - ) { - throw new InferenceSetError( - `Native NVIDIA access was removed from sandbox '${selected.sandboxName}', but NemoClaw could not clear its attachment receipt. Retry this command before another provider change.`, - ); - } - } return mutation.result; }); } diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 37f3a5c70bf..4d797a08c7a 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -3,6 +3,7 @@ import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; +import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter-cli"; import { OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import * as agentRuntime from "../../agent/runtime"; import { REPOSITORY_ROOT } from "../../core/repository-root"; @@ -10,6 +11,8 @@ import type { ProviderHealthStatus } from "../../inference/health"; import { isNativeNvidiaProvider, NVIDIA_HOSTED_NATIVE_ENDPOINT, + verifyNativeNvidiaProviderAttachment, + type NativeNvidiaProviderAttachment, } from "../../inference/native-nvidia"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; import { @@ -30,6 +33,30 @@ import { DCODE_AGENT_NAME } from "./rebuild-dcode-target"; export type { SandboxInferenceInvocationResult } from "./inference-invocation-probe"; export type ProbeSandboxInferenceInvocation = typeof probeSandboxInferenceInvocation; +export type VerifyNativeNvidiaStatusAttachment = (input: { + gatewayName: string; + sandboxName: string; + expected: NativeNvidiaProviderAttachment; +}) => Promise; + +export async function verifyNativeNvidiaStatusAttachment(input: { + gatewayName: string; + sandboxName: string; + expected: NativeNvidiaProviderAttachment; + verify?: VerifyNativeNvidiaStatusAttachment; +}): Promise { + if (input.verify) { + await input.verify(input); + return; + } + await verifyNativeNvidiaProviderAttachment({ + adapter: createCliOpenShellProviderAdapter(), + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: input.expected, + }); +} + export type SandboxInferenceRouteHealth = { ok: boolean; endpoint: string; diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index 20cb1ee455f..72ca484b6cc 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -502,6 +502,7 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = probeProviderHealthImpl: () => null, probeSandboxInferenceGatewayHealthImpl: probeSharedRoute, probeSandboxInferenceInvocationImpl: invoke, + verifyNativeNvidiaProviderAttachmentImpl: async () => undefined, }, } as never); @@ -522,6 +523,56 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = expect(snapshot.inferenceHealth).toMatchObject({ ok: true, probed: true }); }); + it("reports a missing native NVIDIA attachment before probing inference", async () => { + liveGatewayInference("compatible-endpoint", "other/model"); + const sandbox = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-123", + }, + } as SandboxEntry; + const invoke = vi.fn(async () => ({ ok: true }) as const); + const probeProvider = vi.fn(() => null); + const verifyAttachment = vi.fn(async () => { + throw new Error( + "Sandbox 'alpha' does not have its native NVIDIA inference provider attached.", + ); + }); + + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + probeProviderHealthImpl: probeProvider, + probeSandboxInferenceInvocationImpl: invoke, + verifyNativeNvidiaProviderAttachmentImpl: verifyAttachment, + }, + } as never); + + expect(verifyAttachment).toHaveBeenCalledOnce(); + expect(probeProvider).not.toHaveBeenCalled(); + expect(invoke).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toMatchObject({ + ok: false, + probed: false, + providerLabel: "Native NVIDIA provider attachment", + detail: expect.stringContaining( + "Native NVIDIA provider attachment is unavailable for sandbox 'alpha'", + ), + }); + expect(snapshot.inferenceHealth?.detail).toContain( + "Recreate the sandbox to restore native NVIDIA inference.", + ); + }); + it("reports the recorded native NVIDIA route when the shared route differs", async () => { liveGatewayInference("compatible-endpoint", "other/model"); const sandbox = { diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index e21dce72417..0de3fb1d557 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -19,6 +19,7 @@ import { retryUntilAsync } from "../../core/retry"; import { withStdoutRedirectedToStderr } from "../../cli/stdout-guard"; import { getLlamaCppRouteDetails, + NVIDIA_HOSTED_NATIVE_ENDPOINT, normalizeNativeNvidiaProviderAttachment, type GatewayInference, type LlamaCppRouteDetails, @@ -58,6 +59,8 @@ import { type ProbeSandboxInferenceInvocation, probeSandboxInferenceGatewayHealth, runSandboxInferenceInvocationProbe, + verifyNativeNvidiaStatusAttachment, + type VerifyNativeNvidiaStatusAttachment, } from "./inference-route-health"; import { getSandboxStatusPreflight, @@ -330,6 +333,7 @@ interface CollectSandboxStatusSnapshotDeps { getSandboxStatusPreflightImpl?: typeof getSandboxStatusPreflight; getGatewayPresets?: GetGatewayPresets; inspectManagedLlamaCppOwnership?: typeof inspectManagedLlamaCppOwnership; + verifyNativeNvidiaProviderAttachmentImpl?: VerifyNativeNvidiaStatusAttachment; } function sanitizedStatusDetail(error: unknown): string { @@ -607,6 +611,31 @@ export async function collectSandboxStatusSnapshot( const nativeNvidia = Boolean( normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), ); + let nativeNvidiaAttachmentFailure: string | null = null; + if (!suppressInferenceProbe && lookup.state === "present" && nativeNvidia && sb) { + const expected = normalizeNativeNvidiaProviderAttachment(sb.nativeNvidiaProviderAttachment); + if (!gatewayName || !expected) { + nativeNvidiaAttachmentFailure = + `Native NVIDIA provider attachment is unavailable for sandbox '${sandboxName}'. ` + + "Recreate the sandbox to restore native NVIDIA inference."; + } else { + try { + await verifyNativeNvidiaStatusAttachment({ + gatewayName, + sandboxName, + expected, + ...(opts.deps?.verifyNativeNvidiaProviderAttachmentImpl + ? { verify: opts.deps.verifyNativeNvidiaProviderAttachmentImpl } + : {}), + }); + } catch (error) { + const detail = sanitizedStatusDetail(error); + nativeNvidiaAttachmentFailure = + `Native NVIDIA provider attachment is unavailable for sandbox '${sandboxName}'` + + `${detail ? `: ${detail}` : "."} Recreate the sandbox to restore native NVIDIA inference.`; + } + } + } const routeDriftPlan = !nativeNvidia && sb && sb.provider && sb.model ? planInferenceRouteReconcile(live, { provider: sb.provider, model: sb.model }) @@ -639,14 +668,16 @@ export async function collectSandboxStatusSnapshot( // value to null afterwards. let providerHealth: ProviderHealthStatus | null = null; try { - providerHealth = maybeGetSandboxStatusInferenceHealth( - suppressInferenceProbe, - lookup.state === "present", - nativeNvidia ? currentProvider : (live && live.provider) || currentProvider, - nativeNvidia ? currentModel : (live && live.model) || currentModel, - opts.deps?.probeProviderHealthImpl, - sb?.endpointUrl, - ); + providerHealth = nativeNvidiaAttachmentFailure + ? null + : maybeGetSandboxStatusInferenceHealth( + suppressInferenceProbe, + lookup.state === "present", + nativeNvidia ? currentProvider : (live && live.provider) || currentProvider, + nativeNvidia ? currentModel : (live && live.model) || currentModel, + opts.deps?.probeProviderHealthImpl, + sb?.endpointUrl, + ); } catch { providerHealth = { ok: false, @@ -699,7 +730,9 @@ export async function collectSandboxStatusSnapshot( ? await probe(sandboxName, { gatewayName }) : null; invocation = - (nativeNvidia || gatewayChain?.ok) && canProbeInvocation + !nativeNvidiaAttachmentFailure && + (nativeNvidia || gatewayChain?.ok) && + canProbeInvocation ? await runSandboxInferenceInvocationProbe( { sandboxName, @@ -756,11 +789,21 @@ export async function collectSandboxStatusSnapshot( gatewayChain = null; invocation = null; } - inferenceHealth = buildSandboxInferenceRouteHealth(gatewayChain, providerHealth, invocation, { - agentName: sb?.agent ?? null, - provider: invocationRoute.provider ?? null, - nativeNvidia, - }); + inferenceHealth = nativeNvidiaAttachmentFailure + ? { + ok: false, + probed: false, + providerLabel: "Native NVIDIA provider attachment", + endpoint: NVIDIA_HOSTED_NATIVE_ENDPOINT, + detail: nativeNvidiaAttachmentFailure, + failureLabel: "unreachable", + probeLabel: "provider attachment", + } + : buildSandboxInferenceRouteHealth(gatewayChain, providerHealth, invocation, { + agentName: sb?.agent ?? null, + provider: invocationRoute.provider ?? null, + nativeNvidia, + }); } // Classify once per snapshot so every renderer observes the same receipt state. // A complete matching live route is required because the shared gateway route From 490c23d2ccf49bc8183039cd6147419e8541ab1f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:25:04 -0700 Subject: [PATCH 024/133] fix: close native inference advisor findings --- docs/reference/troubleshooting.mdx | 2 +- test/e2e/live/hermes-inference-switch.test.ts | 3 +- .../live/openclaw-inference-switch-helpers.ts | 15 ++++++ .../live/openclaw-inference-switch.test.ts | 14 ++++-- .../e2e/live/public-nvidia-switch-provider.ts | 32 +++++++++++- ...mes-inference-switch-command-shape.test.ts | 45 +++++++++++------ .../openclaw-inference-switch-helpers.test.ts | 25 ++++++++++ .../public-nvidia-switch-provider.test.ts | 50 ++++++++++++++++++- 8 files changed, 163 insertions(+), 23 deletions(-) diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index f7c800a7223..13693d8f1f9 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1980,7 +1980,7 @@ Verify that the inference provider endpoint is reachable from the host. Check th $$nemoclaw status ``` -The main `Inference` line probes `https://inference.local/v1/models` from inside the sandbox and then sends an inference request over the same route, so it reflects the route the agent uses. When that request returns a transient gateway status, `status` repeats both probes up to three total attempts before it reports a failure. It prints the HTTP status, next attempt, and two-second delay to stderr before each retry; the configured timeout envelope for three complete probe pairs and two delays is about 124 seconds. If that line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. +The main `Inference` line probes the selected provider path from inside the sandbox and then sends an inference request over the same path, so it reflects the route the agent uses. Most providers use `https://inference.local`. NVIDIA Endpoints uses the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1/chat/completions`. When that request returns a transient gateway status, `status` repeats both probes up to three total attempts before it reports a failure. It prints the HTTP status, next attempt, and two-second delay to stderr before each retry; the configured timeout envelope for three complete probe pairs and two delays is about 124 seconds. If that line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. For local Ollama and local vLLM, `Inference (ollama backend)` or the corresponding local-backend line reports the host-side service separately. If a local-backend diagnostic fails, start the backend. For Local Ollama, current releases can also print `Inference (auth proxy)` when a proxy token is available. Docker Desktop on Windows Subsystem for Linux (WSL) reaches host loopback directly, so its auth-proxy diagnostic is non-authoritative. Native Docker Engine inside WSL is unqualified; enable Docker Desktop WSL integration, then rerun onboarding. diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index 02e7b664d32..c017315f0ad 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -51,6 +51,7 @@ import { strictHashPerms, } from "./hermes-inference-switch-helpers.ts"; import { + PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_PROVIDER, readPublicNvidiaSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, @@ -326,7 +327,7 @@ test( [ "hermes", SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? "inspection=0;attached=true;schema=1;profile=nemoclaw-nvidia-inference-v1;provider=nemoclaw-nvidia-prod-v1;provider-id=present" + ? PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE : null, SWITCH_MODEL, SWITCH_PROVIDER, diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index 5cc9cdc560a..44d898c18ac 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -25,6 +25,21 @@ export type ExhaustedPostSwitchEvidence = | { outcome: "failed"; message: string } | { outcome: "skipped"; reason: string }; +export type UnavailableInitialProviderEvidence = + | { outcome: "failed"; message: string } + | { outcome: "skipped"; reason: string }; + +/** Required provider qualification cannot succeed by skipping failed onboarding validation. */ +export function classifyUnavailableInitialProviderEvidence(input: { + required: boolean; + detail: string; +}): UnavailableInitialProviderEvidence { + const detail = `External provider validation was unavailable during onboarding: ${input.detail}`; + return input.required + ? { outcome: "failed", message: `Required native provider evidence failed: ${detail}` } + : { outcome: "skipped", reason: detail }; +} + /** Required provider evidence fails closed after bounded transient retries. */ export function classifyExhaustedPostSwitchEvidence(input: { required: boolean; diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 82708a6f2a7..f35aea30884 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -57,12 +57,14 @@ import { anthropicToolCount, classifyExhaustedPostSwitchEvidence, classifyOpenClawPostSwitchInferenceAttempt, + classifyUnavailableInitialProviderEvidence, MOCK_BASELINE_API_KEY, MOCK_BASELINE_MODEL, mockBaselineInference, parseOpenClawGatewayModelRun, } from "./openclaw-inference-switch-helpers.ts"; import { + PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, readPublicNvidiaSwitchAttachmentEvidence, @@ -604,7 +606,7 @@ async function assertRegistryAndSession( NVIDIA_HOSTED_NATIVE_ENDPOINT, "NVIDIA_INFERENCE_API_KEY", "openai-completions", - "inspection=0;attached=true;schema=1;profile=nemoclaw-nvidia-inference-v1;provider=nemoclaw-nvidia-prod-v1;provider-id=present", + PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, ].join("\n"), ); break; @@ -1224,14 +1226,20 @@ test( }, ); const onboardText = resultText(onboard); - if (onboard.exitCode !== 0 && isExternalProviderValidationFailure(onboardText)) { + 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("NVIDIA endpoint validation was unavailable/rate-limited during onboarding"); + skip(unavailable.reason); } expect(onboard.exitCode, onboardText).toBe(0); await proveMockBaselineAuthentication(baselineProvider, sandbox, home, artifacts); diff --git a/test/e2e/live/public-nvidia-switch-provider.ts b/test/e2e/live/public-nvidia-switch-provider.ts index 7fce045f3c2..1896add382e 100644 --- a/test/e2e/live/public-nvidia-switch-provider.ts +++ b/test/e2e/live/public-nvidia-switch-provider.ts @@ -3,12 +3,17 @@ import { normalizeNativeNvidiaProviderAttachment, + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, } from "../../../src/lib/inference/native-nvidia/index.ts"; +import { parseCliOpenShellProviderMetadata } from "../../../src/lib/adapters/openshell/provider-metadata-cli.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; export const PUBLIC_NVIDIA_SWITCH_PROVIDER = "nvidia-prod"; export const PUBLIC_NVIDIA_SWITCH_MODEL = "nvidia/nemotron-3-super-120b-a12b"; +export const PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE = + "provider-inspection=0;provider-name=match;provider-profile=match;provider-id=match;attachment-inspection=0;attached=true;schema=1;profile=nemoclaw-nvidia-inference-v1;provider=nemoclaw-nvidia-prod-v1"; export function requirePublicNvidiaSwitchKey(value: string): string { if (!/^nvapi-[A-Za-z0-9_-]+$/u.test(value)) { @@ -27,6 +32,18 @@ export async function readPublicNvidiaSwitchAttachmentEvidence(options: { }): Promise { if (options.logicalProvider !== PUBLIC_NVIDIA_SWITCH_PROVIDER) return null; const receipt = normalizeNativeNvidiaProviderAttachment(options.receipt); + const provider = await options.sandbox.openshell( + ["provider", "get", "-g", "nemoclaw", NVIDIA_HOSTED_NATIVE_PROVIDER], + { + artifactName: `${options.artifactName}-provider-metadata`, + captureLimitBytes: 16 * 1024, + env: options.env, + persistArtifacts: false, + timeoutMs: 60_000, + }, + ); + const metadata = + provider.exitCode === 0 ? parseCliOpenShellProviderMetadata(provider.stdout) : null; const attachments = await options.sandbox.openshell( ["sandbox", "provider", "list", "-g", "nemoclaw", options.sandboxName], { @@ -36,11 +53,22 @@ export async function readPublicNvidiaSwitchAttachmentEvidence(options: { }, ); return [ - `inspection=${String(attachments.exitCode)}`, + `provider-inspection=${String(provider.exitCode)}`, + `provider-name=${metadata?.name === receipt?.providerName ? "match" : "mismatch"}`, + `provider-profile=${ + metadata?.type === receipt?.profileId && + metadata?.credentialKeys.length === 1 && + metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && + metadata.configKeys.length === 0 && + metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID + ? "match" + : "mismatch" + }`, + `provider-id=${metadata?.revision?.id === receipt?.providerId ? "match" : "mismatch"}`, + `attachment-inspection=${String(attachments.exitCode)}`, `attached=${String(attachments.stdout.split(/\s+/u).includes(NVIDIA_HOSTED_NATIVE_PROVIDER))}`, `schema=${String(receipt?.schemaVersion ?? "missing")}`, `profile=${receipt?.profileId ?? "missing"}`, `provider=${receipt?.providerName ?? "missing"}`, - `provider-id=${receipt ? "present" : "missing"}`, ].join(";"); } 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 480fce35dbc..759d5ec7da9 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -35,6 +35,7 @@ import { sandboxInferenceCommand, } from "../live/hermes-inference-switch-helpers.ts"; import { + PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_PROVIDER, readPublicNvidiaSwitchAttachmentEvidence, } from "../live/public-nvidia-switch-provider.ts"; @@ -58,11 +59,19 @@ describe("Hermes inference switch command shape", () => { }); it("requires the durable receipt and live sandbox attachment for native NVIDIA (#12558)", async () => { - const openshell = vi.fn().mockResolvedValue({ - exitCode: 0, - stderr: "", - stdout: "nemoclaw-nvidia-prod-v1\n", - } as ShellProbeResult); + const openshell = vi + .fn() + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: + "Name: nemoclaw-nvidia-prod-v1\nId: provider-revision-1\nType: nemoclaw-nvidia-inference-v1\nResource version: 1\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: \n", + } as ShellProbeResult) + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "nemoclaw-nvidia-prod-v1\n", + } as ShellProbeResult); const evidence = await readPublicNvidiaSwitchAttachmentEvidence({ artifactName: "native-nvidia-provider-attachment", env: { OPENSHELL_GATEWAY: "nemoclaw" }, @@ -76,10 +85,8 @@ describe("Hermes inference switch command shape", () => { sandbox: { openshell } as unknown as SandboxClient, sandboxName: "e2e-hm-inf-switch", }); - expect(evidence).toBe( - "inspection=0;attached=true;schema=1;profile=nemoclaw-nvidia-inference-v1;provider=nemoclaw-nvidia-prod-v1;provider-id=present", - ); - expect(openshell).toHaveBeenCalledOnce(); + expect(evidence).toBe(PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE); + expect(openshell).toHaveBeenCalledTimes(2); }); it("probes native NVIDIA through its sandbox-attached provider route (#12558)", () => { @@ -102,11 +109,19 @@ describe("Hermes inference switch command shape", () => { }, ], ])("reports an %s native NVIDIA attachment receipt (#12558)", async (_label, receipt) => { - const openshell = vi.fn().mockResolvedValue({ - exitCode: 0, - stderr: "", - stdout: "nemoclaw-nvidia-prod-v1\n", - } as ShellProbeResult); + const openshell = vi + .fn() + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: + "Name: nemoclaw-nvidia-prod-v1\nId: provider-revision-1\nType: nemoclaw-nvidia-inference-v1\nResource version: 1\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: \n", + } as ShellProbeResult) + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "nemoclaw-nvidia-prod-v1\n", + } as ShellProbeResult); const evidence = await readPublicNvidiaSwitchAttachmentEvidence({ artifactName: "native-nvidia-provider-attachment", env: { OPENSHELL_GATEWAY: "nemoclaw" }, @@ -116,7 +131,7 @@ describe("Hermes inference switch command shape", () => { sandboxName: "e2e-hm-inf-switch", }); expect(evidence).toContain( - "schema=missing;profile=missing;provider=missing;provider-id=missing", + "provider-id=mismatch;attachment-inspection=0;attached=true;schema=missing;profile=missing;provider=missing", ); }); diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index a8f02986cc6..24330acba82 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -8,6 +8,7 @@ import { anthropicToolCount, classifyExhaustedPostSwitchEvidence, classifyOpenClawPostSwitchInferenceAttempt, + classifyUnavailableInitialProviderEvidence, MOCK_BASELINE_API_KEY, MOCK_BASELINE_MODEL, mockBaselineInference, @@ -121,6 +122,30 @@ describe("openclaw-inference-switch post-switch retry classification", () => { "Sandbox inference transient failure after switch; route/config checks already passed: HTTP 503: unavailable", }); }); + + it("fails closed when required native-provider validation is unavailable during onboarding", () => { + expect( + classifyUnavailableInitialProviderEvidence({ + required: true, + detail: "HTTP 429: rate limited", + }), + ).toEqual({ + outcome: "failed", + message: + "Required native provider evidence failed: External provider validation was unavailable during onboarding: HTTP 429: rate limited", + }); + + expect( + classifyUnavailableInitialProviderEvidence({ + required: false, + detail: "HTTP 429: rate limited", + }), + ).toEqual({ + outcome: "skipped", + reason: + "External provider validation was unavailable during onboarding: HTTP 429: rate limited", + }); + }); }); describe("openclaw-inference-switch agent reply matching", () => { diff --git a/test/e2e/support/public-nvidia-switch-provider.test.ts b/test/e2e/support/public-nvidia-switch-provider.test.ts index 3948fd7479a..22788913a2c 100644 --- a/test/e2e/support/public-nvidia-switch-provider.test.ts +++ b/test/e2e/support/public-nvidia-switch-provider.test.ts @@ -1,10 +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 { describe, expect, it, vi } from "vitest"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { + PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, + readPublicNvidiaSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, } from "../live/public-nvidia-switch-provider.ts"; @@ -15,4 +19,48 @@ describe("public NVIDIA inference switch provider", () => { expect(requirePublicNvidiaSwitchKey("nvapi-public-key")).toBe("nvapi-public-key"); expect(() => requirePublicNvidiaSwitchKey("sk-hosted-key")).toThrow(/nvapi-\*/u); }); + + it("rejects live provider metadata whose revision differs from the durable receipt", async () => { + const openshell = vi + .fn() + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: [ + "Name: nemoclaw-nvidia-prod-v1", + "Id: provider-revision-2", + "Type: nemoclaw-nvidia-inference-v1", + "Resource version: 2", + "Credential keys: NVIDIA_INFERENCE_API_KEY", + "Config keys: ", + ].join("\n"), + } as ShellProbeResult) + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "nemoclaw-nvidia-prod-v1\n", + } as ShellProbeResult); + + const evidence = await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "native-nvidia-provider-attachment", + env: { OPENSHELL_GATEWAY: "nemoclaw" }, + logicalProvider: PUBLIC_NVIDIA_SWITCH_PROVIDER, + receipt: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-revision-1", + }, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "e2e-hm-inf-switch", + }); + + expect(evidence).not.toBe(PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE); + expect(evidence).toContain("provider-id=mismatch"); + expect(openshell).toHaveBeenNthCalledWith( + 1, + ["provider", "get", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + expect.objectContaining({ persistArtifacts: false }), + ); + }); }); From d45e247035cb7bedf850f5c48c2104b22626e475 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:28:34 -0700 Subject: [PATCH 025/133] fix(config): export native NVIDIA attachments Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../config/live-export-source-test-fixture.ts | 125 ++++++++++++++- .../config/live-export-source.test.ts | 116 ++++++++++++-- src/lib/adapters/config/live-export-source.ts | 109 +++++++++++-- .../native-nvidia-profile-response.ts | 144 ++++++++++++++++++ src/lib/adapters/openshell/providers.ts | 62 +++++++- src/lib/domain/config/export-evidence.ts | 9 +- src/lib/domain/config/verify-export-source.ts | 75 +++++++-- src/lib/inference/native-nvidia/contract.ts | 37 +++++ src/lib/inference/native-nvidia/index.ts | 50 ++---- 9 files changed, 647 insertions(+), 80 deletions(-) create mode 100644 src/lib/adapters/openshell/native-nvidia-profile-response.ts create mode 100644 src/lib/inference/native-nvidia/contract.ts diff --git a/src/lib/adapters/config/live-export-source-test-fixture.ts b/src/lib/adapters/config/live-export-source-test-fixture.ts index e5fc21e505e..e9913ad9be6 100644 --- a/src/lib/adapters/config/live-export-source-test-fixture.ts +++ b/src/lib/adapters/config/live-export-source-test-fixture.ts @@ -6,6 +6,11 @@ import { vi } from "vitest"; import type { ObservedOllamaProxy } from "../../inference/ollama/proxy-observation"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; +import { + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + NVIDIA_HOSTED_NATIVE_PROVIDER, +} from "../../inference/native-nvidia/contract"; import { buildManagedStartupProfile } from "../../onboard/managed-startup/profile-builder"; import type { ManagedStartupProfileBuilderInput } from "../../onboard/managed-startup/profile-builder"; import type { SandboxEntry } from "../../state/registry/types"; @@ -244,8 +249,124 @@ export function openAiProviderProfile() { }; } -export function nativeNvidiaProvider() { - return { ...provider().provider, type: "nvidia", profileWorkspace: "", config: {} }; +type NativeNvidiaProviderFixture = Record & { + metadata: Record; + type: string; + profileWorkspace: string; + credentials: Record; + config: Record; +}; + +export function nativeNvidiaProvider(): NativeNvidiaProviderFixture { + return { + ...provider().provider, + metadata: { + ...provider().provider.metadata, + id: "native-provider-id", + name: NVIDIA_HOSTED_NATIVE_PROVIDER, + }, + type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + profileWorkspace: "default", + credentials: { [NVIDIA_HOSTED_CREDENTIAL_ENV]: readFailureCanary }, + config: {}, + }; +} + +export function legacySharedNvidiaProvider(): NativeNvidiaProviderFixture { + return { + ...provider().provider, + type: "nvidia", + profileWorkspace: "", + config: {}, + }; +} + +export function nativeNvidiaEntry(): SandboxEntry { + return { + ...entry, + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "native-provider-id", + }, + }; +} + +const emptyNativeAllow: Readonly> = { + command: "", + query: {}, + operationType: "", + operationName: "", + fields: [], + params: {}, +}; + +function nativeNvidiaEndpoint(): Record { + return { + host: "integrate.api.nvidia.com", + port: 443, + ports: [], + protocol: "rest", + tls: "", + enforcement: "enforce", + access: "", + rules: [ + { allow: { ...emptyNativeAllow, method: "GET", path: "/v1/models" } }, + { + allow: { + ...emptyNativeAllow, + method: "POST", + path: "/v1/chat/completions", + }, + }, + ], + allowedIps: [], + denyRules: [], + allowEncodedSlash: false, + persistedQueries: "", + graphqlPersistedQueries: {}, + graphqlMaxBodyBytes: 0, + path: "", + websocketCredentialRewrite: false, + requestBodyCredentialRewrite: false, + advisorProposed: false, + credentialSigning: "", + signingService: "", + signingRegion: "", + jsonRpcMaxBodyBytes: 0, + }; +} + +export function nativeNvidiaProfile(): Record { + return { + id: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + source: "user", + scope: "workspace", + resourceVersion: 5n, + inferenceCapable: true, + credentials: [ + { + name: "api_key", + envVars: [NVIDIA_HOSTED_CREDENTIAL_ENV], + required: true, + authStyle: "bearer", + headerName: "authorization", + queryParam: "", + pathTemplate: "", + }, + ], + endpoints: [nativeNvidiaEndpoint()], + binaries: [ + "/usr/local/bin/node", + "/usr/bin/node", + "/opt/hermes/.venv/bin/python", + "/opt/hermes/.venv/bin/python3", + "/opt/venv/bin/python3", + "/usr/local/bin/curl", + "/usr/bin/curl", + ].map((path) => ({ path })), + }; } export function braveProvider() { diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index 82d810455b0..35e5a53bd11 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -34,9 +34,12 @@ import { startup, entry, inventory, + legacySharedNvidiaProvider, provider, configuration, + nativeNvidiaEntry, nativeNvidiaProvider, + nativeNvidiaProfile, telemetryEntry, dashboardSource, braveProvider, @@ -75,16 +78,16 @@ function mockBraveLiveSource() { } function mockNativeNvidiaSource() { - mockSupportedLiveSource(); + mockSupportedLiveSource(3, 3, nativeNvidiaEntry()); raw.getProvider.mockResolvedValue({ provider: nativeNvidiaProvider() }); - raw.getProviderProfile.mockResolvedValue({ - profile: { - id: "nvidia", - source: "builtin", - scope: "", - resourceVersion: 0n, - inferenceCapable: true, - endpoints: [{ host: "integrate.api.nvidia.com", port: 443 }], + raw.getProviderProfile.mockResolvedValue({ profile: nativeNvidiaProfile() }); + raw.getSandbox.mockResolvedValue({ + sandbox: { + ...inventory().sandbox, + spec: { + ...inventory().sandbox.spec, + providers: ["nemoclaw-nvidia-prod-v1"], + }, }, }); } @@ -459,6 +462,10 @@ describe("live export snapshot reader", () => { it("exports canonical YAML for the native NVIDIA hosted provider (#11154)", async () => { mockNativeNvidiaSource(); + vi.mocked(captureSanitizedResolvedOpenshell).mockReturnValue({ + status: 1, + output: "No inference route is configured.", + }); const writeStdout = vi.fn(async (_yaml: string) => {}); const publish = vi.fn(); const result = await runConfigExport( @@ -490,9 +497,45 @@ describe("live export snapshot reader", () => { expect(document.spec.sandboxes[0].harness.kind).toBe("openclaw"); expect(yaml).not.toContain(readFailureCanary); expect(raw.getProviderProfile).toHaveBeenCalledTimes(2); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); expect(publish).not.toHaveBeenCalled(); }); + it("retains the legacy shared-route NVIDIA export without a native receipt", async () => { + mockSupportedLiveSource(); + raw.getProvider.mockResolvedValue({ provider: legacySharedNvidiaProvider() }); + raw.getProviderProfile.mockResolvedValue({ + profile: { + id: "nvidia", + source: "builtin", + scope: "", + resourceVersion: 0n, + inferenceCapable: true, + endpoints: [{ host: "integrate.api.nvidia.com", port: 443 }], + }, + }); + + const { result, writeStdout } = await exportLiveSource(); + + expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); + expect(writeStdout.mock.calls[0]?.[0]).not.toContain(readFailureCanary); + expect(captureSanitizedResolvedOpenshell).toHaveBeenCalled(); + }); + + it("exports native NVIDIA when an unrelated shared route exists (#12558)", async () => { + mockNativeNvidiaSource(); + vi.mocked(captureSanitizedResolvedOpenshell).mockReturnValue({ + status: 0, + output: "Gateway inference:\n Provider: unrelated\n Model: unrelated-model\n", + }); + + const { result, writeStdout } = await exportLiveSource(); + + expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); + expect(writeStdout.mock.calls[0]?.[0]).not.toContain(readFailureCanary); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + }); + it.each([ { label: "endpoint override", providerChange: { config: { NVIDIA_BASE_URL: endpoint } } }, { @@ -500,7 +543,13 @@ describe("live export snapshot reader", () => { providerChange: { credentials: { OTHER_API_KEY: readFailureCanary } }, }, { label: "missing credentials", providerChange: { credentials: {} } }, - { label: "unverified profile scope", providerChange: { profileWorkspace: "default" } }, + { label: "unverified profile scope", providerChange: { profileWorkspace: "foreign" } }, + { + label: "receipt identity mismatch", + providerChange: { + metadata: { ...nativeNvidiaProvider().metadata, id: "replacement-provider-id" }, + }, + }, ])("rejects native NVIDIA $label without publishing YAML", async ({ providerChange }) => { mockNativeNvidiaSource(); raw.getProvider.mockResolvedValue({ @@ -527,10 +576,51 @@ describe("live export snapshot reader", () => { expect(JSON.stringify(result)).not.toContain(readFailureCanary); }); - it("rejects NVIDIA endpoint drift between the registry and builtin profile", async () => { + it.each([{ providers: [] }, { providers: ["unrelated-provider"] }])( + "rejects native NVIDIA without its exact sandbox attachment %j", + async ({ providers }) => { + mockNativeNvidiaSource(); + raw.getSandbox.mockResolvedValue({ + sandbox: { + ...inventory().sandbox, + spec: { ...inventory().sandbox.spec, providers }, + }, + }); + + const { result, writeStdout, publish } = await exportLiveSource(); + + expect(result).toMatchObject({ ok: false, failure: { kind: "observation" } }); + expect(writeStdout).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); + }, + ); + + it.each([ + { label: "identity", change: { id: "replacement-profile" } }, + { label: "scope", change: { scope: "platform" } }, + { label: "source", change: { source: "builtin" } }, + { label: "credential boundary", change: { credentials: [] } }, + { label: "endpoint boundary", change: { endpoints: [] } }, + { label: "binary boundary", change: { binaries: [] } }, + ])("rejects native NVIDIA managed profile $label drift", async ({ change }) => { + mockNativeNvidiaSource(); + raw.getProviderProfile.mockResolvedValue({ + profile: { ...nativeNvidiaProfile(), ...change }, + }); + + const { result, writeStdout, publish } = await exportLiveSource(); + + expect(result).toMatchObject({ ok: false, failure: { kind: "observation" } }); + expect(writeStdout).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); + }); + + it("rejects NVIDIA endpoint drift between the registry and managed profile", async () => { mockNativeNvidiaSource(); vi.mocked(loadRegistry).mockReturnValue({ - sandboxes: { alpha: { ...entry, endpointUrl: "https://different.example/v1" } }, + sandboxes: { + alpha: { ...nativeNvidiaEntry(), endpointUrl: "https://different.example/v1" }, + }, defaultSandbox: null, }); const result = await observeStableExportSource("alpha", createLiveExportSnapshotReader()); @@ -551,7 +641,7 @@ describe("live export snapshot reader", () => { raw.getProvider.mockImplementation(async () => ({ provider: { ...nativeNvidiaProvider(), - metadata: { ...provider().provider.metadata, resourceVersion: BigInt(++revision) }, + metadata: { ...nativeNvidiaProvider().metadata, resourceVersion: BigInt(++revision) }, }, })); const result = await observeStableExportSource("alpha", createLiveExportSnapshotReader()); diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index d6f0a3aa725..03c73b71bff 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -132,7 +132,11 @@ function providerContract(api: string | null | undefined) { return { type, configKey: "OPENAI_BASE_URL" } as const; } -function providerIdentity(provider: Provider, gatewayName: string, managed: boolean) { +function providerIdentity( + provider: Provider, + gatewayName: string, + managed: boolean, +): ObservedExportEndpointEvidence["provider"] { return { gatewayName, workspace: provider.workspace, @@ -166,12 +170,44 @@ function inferenceTopology( : "hosted"; } +type NativeNvidiaReceipt = NonNullable; + +function matchesNativeProviderMetadata( + provider: Provider, + normalized: ReturnType, + routeProvider: string, + receipt: NativeNvidiaReceipt, +): boolean { + return isDeepStrictEqual( + [ + provider.name, + provider.id, + provider.type, + provider.credentialKeys, + provider.configKeys, + provider.managedProfile?.id, + ], + [ + routeProvider, + receipt.providerId, + receipt.profileId, + expectedCredentialKeys(normalized.credentialEnv, routeProvider), + [], + receipt.profileId, + ], + ); +} + function matchesProviderMetadata( provider: Provider, normalized: ReturnType, routeProvider: string, managed: boolean, + nativeReceipt?: NativeNvidiaReceipt, ): boolean { + if (nativeReceipt !== undefined) { + return matchesNativeProviderMetadata(provider, normalized, routeProvider, nativeReceipt); + } const { type, configKey } = providerContract(normalized.preferredInferenceApi); const builtin = provider.builtinInferenceEndpoint !== undefined; // OpenShell's CLI writes the selected workspace for a newly created @@ -198,34 +234,77 @@ function matchesProviderMetadata( ); } +function profileContractFor( + routeProvider: string, + nativeReceipt: NativeNvidiaReceipt | undefined, +): "native-nvidia" | "openai" | undefined { + if (nativeReceipt) return "native-nvidia"; + return routeProvider === "ollama-local" ? "openai" : undefined; +} + +function endpointSourceFor( + nativeReceipt: NativeNvidiaReceipt | undefined, + builtin: boolean, + configKey: "ANTHROPIC_BASE_URL" | "OPENAI_BASE_URL", +): ObservedExportEndpointEvidence["source"] { + if (nativeReceipt) return { kind: "managed-profile", profileId: nativeReceipt.profileId }; + if (builtin) return { kind: "builtin-profile", profileId: "nvidia" }; + return { kind: "provider-config", key: configKey }; +} + async function readProviderEvidence( normalized: ReturnType, routeProvider: string, gatewayName: string, signal: AbortSignal, managedServing?: ObservedManagedVllmRuntime, + nativeReceipt?: NativeNvidiaReceipt, ): Promise { const { configKey } = providerContract(normalized.preferredInferenceApi); - const inspectOpenAiProfile = routeProvider === "ollama-local"; + const profileContract = profileContractFor(routeProvider, nativeReceipt); const provider = await createProviders().get({ target: namedOpenShellGateway(gatewayName), workspace: "default", name: routeProvider, - ...(inspectOpenAiProfile ? { profileContract: "openai" as const } : {}), + ...(profileContract ? { profileContract } : {}), configKeys: [configKey], signal, }); if (!provider) throw new Error("The live inference provider is missing."); const builtin = provider.builtinInferenceEndpoint !== undefined; - if (!matchesProviderMetadata(provider, normalized, routeProvider, !!managedServing)) { + if ( + !matchesProviderMetadata(provider, normalized, routeProvider, !!managedServing, nativeReceipt) + ) { throw new Error("The live inference provider metadata does not match the registry."); } return { - provider: providerIdentity(provider, gatewayName, inspectOpenAiProfile), - endpoint: provider.builtinInferenceEndpoint ?? provider.config[configKey] ?? "", - source: builtin - ? { kind: "builtin-profile", profileId: "nvidia" } - : { kind: "provider-config", key: configKey }, + provider: providerIdentity(provider, gatewayName, profileContract !== undefined), + endpoint: + provider.managedInferenceEndpoint ?? + provider.builtinInferenceEndpoint ?? + provider.config[configKey] ?? + "", + source: endpointSourceFor(nativeReceipt, builtin, configKey), + }; +} + +async function resolveLiveInference( + entry: Readonly, + gatewayName: string, + nativeReceipt: NativeNvidiaReceipt | undefined, +): Promise> { + if (!nativeReceipt) { + const live = await readInferenceRoute(entry, gatewayName); + return { ...live, logicalProvider: live.provider }; + } + const selected = getSandboxEntryInference(entry); + if (selected.kind !== "configured") { + throw new Error("The native NVIDIA inference selection is incomplete."); + } + return { + provider: nativeReceipt.providerName, + model: selected.model, + logicalProvider: selected.provider, }; } @@ -233,11 +312,17 @@ async function inferenceFor( entry: Readonly, beforeRead: (stage: ExportSnapshotReadStage) => void, signal: AbortSignal, + sandbox: ObservedExportSandboxIdentity, managedServing?: ObservedManagedVllmRuntime, ): Promise { const normalized = normalizeInferenceSelection(entry); const gateway = resolveGatewayBinding(entry); - const live = await readInferenceRoute(entry, gateway.name); + const nativeReceipt = + entry.provider?.trim() === "nvidia-prod" ? entry.nativeNvidiaProviderAttachment : undefined; + if (nativeReceipt && !sandbox.providerNames.includes(nativeReceipt.providerName)) { + throw new Error("The native NVIDIA provider is not attached to the sandbox."); + } + const live = await resolveLiveInference(entry, gateway.name, nativeReceipt); beforeRead("provider-metadata"); const endpointEvidence = await readProviderEvidence( normalized, @@ -245,6 +330,7 @@ async function inferenceFor( gateway.name, signal, managedServing, + nativeReceipt, ); let ollamaServing: ObservedExportInference["ollamaServing"]; if (entry.provider === "ollama-local") { @@ -253,7 +339,7 @@ async function inferenceFor( } return { topology: inferenceTopology(entry, !!managedServing), - provider: live.provider, + provider: live.logicalProvider, model: live.model, api: normalized.preferredInferenceApi ?? "", endpoint: normalized.endpointUrl ?? "", @@ -355,6 +441,7 @@ async function readSnapshot(sandboxName: string): Promise { stage = nextStage; }, signal, + sandbox, managedServing, ); let webSearchProvider: ObservedExportWebSearchProvider | undefined; diff --git a/src/lib/adapters/openshell/native-nvidia-profile-response.ts b/src/lib/adapters/openshell/native-nvidia-profile-response.ts new file mode 100644 index 00000000000..0b4b6d7d7da --- /dev/null +++ b/src/lib/adapters/openshell/native-nvidia-profile-response.ts @@ -0,0 +1,144 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +type NativeNvidiaProfileResponse = Readonly<{ + profile: Readonly<{ + id: "nemoclaw-nvidia-inference-v1"; + source: "user"; + scope: "platform" | "workspace"; + resourceVersion: bigint | string; + }>; +}>; + +function record(value: unknown): Record | null { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +function emptyArray(value: unknown): boolean { + return Array.isArray(value) && value.length === 0; +} + +function emptyRecord(value: unknown): boolean { + const row = record(value); + return row !== null && Object.keys(row).length === 0; +} + +function stringArrayEquals(value: unknown, expected: readonly string[]): boolean { + return ( + Array.isArray(value) && + value.length === expected.length && + value.every((item, index) => item === expected[index]) + ); +} + +function nativeCredential(value: unknown): boolean { + const credential = record(value); + return ( + credential !== null && + credential.name === "api_key" && + stringArrayEquals(credential.envVars, ["NVIDIA_INFERENCE_API_KEY"]) && + credential.required === true && + credential.authStyle === "bearer" && + credential.headerName === "authorization" && + credential.queryParam === "" && + credential.pathTemplate === "" && + credential.refresh === undefined && + credential.tokenGrant === undefined + ); +} + +function nativeRule(value: unknown, method: "GET" | "POST", path: string): boolean { + const rule = record(value); + const allow = record(rule?.allow); + return ( + rule !== null && + allow !== null && + allow.method === method && + allow.path === path && + allow.command === "" && + emptyRecord(allow.query) && + allow.operationType === "" && + allow.operationName === "" && + emptyArray(allow.fields) && + emptyRecord(allow.params) + ); +} + +function nativeEndpoint(value: unknown): boolean { + const endpoint = record(value); + const rules = endpoint?.rules; + return ( + endpoint !== null && + endpoint.host === "integrate.api.nvidia.com" && + endpoint.port === 443 && + emptyArray(endpoint.ports) && + endpoint.protocol === "rest" && + endpoint.tls === "" && + endpoint.enforcement === "enforce" && + endpoint.access === "" && + Array.isArray(rules) && + rules.length === 2 && + nativeRule(rules[0], "GET", "/v1/models") && + nativeRule(rules[1], "POST", "/v1/chat/completions") && + emptyArray(endpoint.allowedIps) && + emptyArray(endpoint.denyRules) && + endpoint.allowEncodedSlash === false && + endpoint.persistedQueries === "" && + emptyRecord(endpoint.graphqlPersistedQueries) && + endpoint.graphqlMaxBodyBytes === 0 && + endpoint.path === "" && + endpoint.websocketCredentialRewrite === false && + endpoint.requestBodyCredentialRewrite === false && + endpoint.advisorProposed === false && + endpoint.credentialSigning === "" && + endpoint.signingService === "" && + endpoint.signingRegion === "" && + endpoint.jsonRpcMaxBodyBytes === 0 && + endpoint.mcp === undefined && + endpoint.credentialBinding === undefined + ); +} + +function nativeBinaries(value: unknown): boolean { + if (!Array.isArray(value)) return false; + const paths = value.map((item) => record(item)?.path); + return stringArrayEquals(paths, [ + "/usr/local/bin/node", + "/usr/bin/node", + "/opt/hermes/.venv/bin/python", + "/opt/hermes/.venv/bin/python3", + "/opt/venv/bin/python3", + "/usr/local/bin/curl", + "/usr/bin/curl", + ]); +} + +/** Verify the live custom profile at the credential, egress, and binary security boundary. */ +export function isManagedNativeNvidiaProfileResponse( + value: unknown, +): value is NativeNvidiaProfileResponse { + const response = record(value); + const profile = record(response?.profile); + const revision = profile?.resourceVersion; + const credentials = profile?.credentials; + const endpoints = profile?.endpoints; + return ( + profile !== null && + profile.id === "nemoclaw-nvidia-inference-v1" && + profile.source === "user" && + (profile.scope === "platform" || profile.scope === "workspace") && + (typeof revision === "bigint" || typeof revision === "string") && + /^[1-9][0-9]*$/u.test(String(revision)) && + profile.inferenceCapable === true && + profile.discovery === undefined && + Array.isArray(credentials) && + credentials.length === 1 && + nativeCredential(credentials[0]) && + Array.isArray(endpoints) && + endpoints.length === 1 && + nativeEndpoint(endpoints[0]) && + nativeBinaries(profile.binaries) + ); +} diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index 788180df9c0..da658c1caeb 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -22,8 +22,13 @@ import { BuiltinNvidiaProfileResponseSchema, ProviderResponseSchema, } from "./sdk-read-schema"; +import { isManagedNativeNvidiaProfileResponse } from "./native-nvidia-profile-response"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; +import { + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, +} from "../../inference/native-nvidia/contract"; import type { OpenShellProviderMetadata } from "./provider-adapter"; @@ -34,10 +39,11 @@ export type Provider = Readonly< resourceVersion: string; config: Readonly>; builtinInferenceEndpoint?: string; + managedInferenceEndpoint?: string; profileWorkspace?: string; // null records a successful not-found read at the OpenAI provider's profile binding. managedProfile?: Readonly<{ - id: "brave" | "openai"; + id: "brave" | "openai" | typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; source: "builtin" | "user"; scope: "" | "platform" | "workspace"; resourceVersion: string; @@ -50,7 +56,7 @@ export interface Providers { Readonly<{ name: string; configKeys: readonly string[]; - profileContract?: "brave" | "openai"; + profileContract?: "brave" | "native-nvidia" | "openai"; }>, ): Promise; } @@ -73,10 +79,12 @@ async function readBuiltinNvidiaEndpoint( async function readManagedProfile( client: OpenShellReadClient, request: ReadRequest, - profileId: "brave" | "openai", + profileContract: NonNullable[0]["profileContract"]>, providerType: string, profileWorkspace: string | undefined, ): Promise | null> { + const profileId = + profileContract === "native-nvidia" ? NVIDIA_HOSTED_NATIVE_PROFILE_ID : profileContract; if ( providerType !== profileId || (profileWorkspace !== "" && profileWorkspace !== request.workspace) @@ -92,19 +100,42 @@ async function readManagedProfile( ); } catch (error) { // OpenShell 0.0.116 has an OpenAI provider type without a builtin profile. - if (profileId === "openai" && isNotFound(error)) return null; + if (profileContract === "openai" && isNotFound(error)) return null; throw error; } - return validateManagedProfileResponse(response, profileId, profileWorkspace); + return validateManagedProfileResponse(response, profileContract, profileWorkspace); +} + +function validateNativeManagedProfileResponse( + response: unknown, + profileWorkspace: string, +): NonNullable { + if (!isManagedNativeNvidiaProfileResponse(response)) { + throw new OpenShellReadError("schema"); + } + const profile = response.profile; + const expectedScope = profileWorkspace === "" ? "platform" : "workspace"; + if (profile.scope !== expectedScope) throw new OpenShellReadError("schema"); + return { + id: profile.id, + source: "user", + scope: profile.scope, + resourceVersion: String(profile.resourceVersion), + }; } function validateManagedProfileResponse( response: unknown, - profileId: "brave" | "openai", + profileContract: NonNullable[0]["profileContract"]>, profileWorkspace: string, ): NonNullable { + if (profileContract === "native-nvidia") { + return validateNativeManagedProfileResponse(response, profileWorkspace); + } const { profile } = readValue( - profileId === "brave" ? ManagedBraveProfileResponseSchema : ManagedOpenAiProfileResponseSchema, + profileContract === "brave" + ? ManagedBraveProfileResponseSchema + : ManagedOpenAiProfileResponseSchema, response, ); const builtin = profile.source === "builtin"; @@ -125,11 +156,24 @@ function validateManagedProfileResponse( }; } +function managedInferenceEndpointFor( + managedProfile: Provider["managedProfile"], +): string | undefined { + return managedProfile?.id === NVIDIA_HOSTED_NATIVE_PROFILE_ID + ? NVIDIA_HOSTED_NATIVE_ENDPOINT + : undefined; +} + async function readProfileEvidence( client: OpenShellReadClient, request: Parameters[0], provider: Readonly<{ type: string; profileWorkspace?: string; config: Record }>, -): Promise> { +): Promise< + Pick< + Provider, + "builtinInferenceEndpoint" | "managedInferenceEndpoint" | "profileWorkspace" | "managedProfile" + > +> { let builtinInferenceEndpoint: string | undefined; if ( provider.type === "nvidia" && @@ -148,12 +192,14 @@ async function readProfileEvidence( provider.type, provider.profileWorkspace, ); + const managedInferenceEndpoint = managedInferenceEndpointFor(managedProfile); return { ...(builtinInferenceEndpoint === undefined ? {} : { builtinInferenceEndpoint }), ...(provider.profileWorkspace === undefined ? {} : { profileWorkspace: provider.profileWorkspace }), ...(managedProfile === undefined ? {} : { managedProfile }), + ...(managedInferenceEndpoint === undefined ? {} : { managedInferenceEndpoint }), }; } diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index aedece71d7e..693b6d322ca 100644 --- a/src/lib/domain/config/export-evidence.ts +++ b/src/lib/domain/config/export-evidence.ts @@ -71,6 +71,7 @@ export const EXPORT_REGISTRY_EVIDENCE_KEYS = [ "messaging", "model", "name", + "nativeNvidiaProviderAttachment", "nimContainer", "observabilityEnabled", "openshellDriver", @@ -112,7 +113,7 @@ export interface ObservedExportEndpointEvidence { readonly profileWorkspace?: string; /** null means the OpenAI profile was read at its binding and confirmed absent. */ readonly managedProfile?: { - readonly id: "brave" | "openai"; + readonly id: "brave" | "openai" | "nemoclaw-nvidia-inference-v1"; readonly source: "builtin" | "user"; readonly scope: "" | "platform" | "workspace"; readonly resourceVersion: string; @@ -124,7 +125,11 @@ export interface ObservedExportEndpointEvidence { readonly kind: "provider-config"; readonly key: "OPENAI_BASE_URL" | "ANTHROPIC_BASE_URL"; } - | { readonly kind: "builtin-profile"; readonly profileId: "nvidia" }; + | { readonly kind: "builtin-profile"; readonly profileId: "nvidia" } + | { + readonly kind: "managed-profile"; + readonly profileId: "nemoclaw-nvidia-inference-v1"; + }; } export interface ObservedExportWebSearchProvider { diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 01d13ea074f..6435cb1e159 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -7,6 +7,13 @@ import { cloneAndDeepFreeze } from "../../core/immutable"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; import { normalizeInferenceSelection } from "../../inference/selection"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; +import { + normalizeNativeNvidiaProviderAttachment, + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_LOGICAL_PROVIDER, + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, +} from "../../inference/native-nvidia/contract"; import type { ManagedStartupProfile } from "../../onboard/managed-startup/profile"; import { buildManagedStartupProfile, @@ -805,9 +812,40 @@ function classifyManagedStartupProfile( return [...findings, ...classifyProfileEquality(profile, supported)]; } -function endpointEvidenceMatchesRoute(inference: QualifiedExportSnapshot["inference"]): boolean { +function endpointEvidenceMatchesRoute(snapshot: QualifiedExportSnapshot): boolean { + const { inference } = snapshot; const evidence = inference.endpointEvidence; if (!evidence) return false; + if (evidence.source.kind === "managed-profile") { + const receipt = normalizeNativeNvidiaProviderAttachment( + snapshot.registry.nativeNvidiaProviderAttachment, + ); + return ( + receipt !== undefined && + isDeepStrictEqual( + [ + evidence.source.profileId, + evidence.provider.name, + evidence.provider.id, + inference.provider, + inference.api, + inference.endpoint, + evidence.endpoint, + inference.credentialEnv, + ], + [ + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + receipt.providerName, + receipt.providerId, + NVIDIA_HOSTED_LOGICAL_PROVIDER, + "openai-completions", + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_CREDENTIAL_ENV, + ], + ) + ); + } if (evidence.source.kind === "builtin-profile") { return ( inference.credentialEnv !== null && @@ -879,8 +917,23 @@ function validateSandboxIdentity( return findings; } -function validateSandboxConfiguration(snapshot: QualifiedExportSnapshot): ExportFinding[] { +function sandboxProviderAttachmentsMatch(snapshot: QualifiedExportSnapshot): boolean { const { registry: entry, sandbox, inference } = snapshot; + const nativeReceipt = normalizeNativeNvidiaProviderAttachment( + entry.nativeNvidiaProviderAttachment, + ); + const inferenceAttachment = nativeReceipt?.providerName ?? inference.provider; + const additionalProviders = sandbox.providerNames.filter((name) => name !== inferenceAttachment); + const expectedAdditionalProviders = hasBraveSearch(entry) ? [`${entry.name}-brave-search`] : []; + return ( + !(nativeReceipt && !sandbox.providerNames.includes(nativeReceipt.providerName)) && + isDeepStrictEqual(additionalProviders, expectedAdditionalProviders) && + new Set(sandbox.providerNames).size === sandbox.providerNames.length + ); +} + +function validateSandboxConfiguration(snapshot: QualifiedExportSnapshot): ExportFinding[] { + const { registry: entry, sandbox } = snapshot; const findings: ExportFinding[] = []; if (sandbox.workspace !== "default") findings.push( @@ -906,12 +959,7 @@ function validateSandboxConfiguration(snapshot: QualifiedExportSnapshot): Export "Registry and live sandbox images differ.", ), ); - const additionalProviders = sandbox.providerNames.filter((name) => name !== inference.provider); - const expectedAdditionalProviders = hasBraveSearch(entry) ? [`${entry.name}-brave-search`] : []; - if ( - !isDeepStrictEqual(additionalProviders, expectedAdditionalProviders) || - new Set(sandbox.providerNames).size !== sandbox.providerNames.length - ) + if (!sandboxProviderAttachmentsMatch(snapshot)) findings.push( finding( "source.sandbox.providers", @@ -1186,6 +1234,13 @@ function validateInferenceRepresentation(snapshot: QualifiedExportSnapshot): Exp return validateHostedInferenceRepresentation(snapshot); } +function expectedEndpointProviderName(snapshot: QualifiedExportSnapshot): string { + return ( + normalizeNativeNvidiaProviderAttachment(snapshot.registry.nativeNvidiaProviderAttachment) + ?.providerName ?? snapshot.inference.provider + ); +} + function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFinding[] { const { inference, sandbox, gateway } = snapshot; const evidence = inference.endpointEvidence; @@ -1223,10 +1278,10 @@ function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFind if ( !evidence.provider.id || !evidence.provider.resourceVersion || - !endpointEvidenceMatchesRoute(inference) || + !endpointEvidenceMatchesRoute(snapshot) || !isDeepStrictEqual( [evidence.provider.workspace, evidence.provider.gatewayName, evidence.provider.name], - [sandbox.workspace, gateway.name, inference.provider], + [sandbox.workspace, gateway.name, expectedEndpointProviderName(snapshot)], ) ) findings.push( diff --git a/src/lib/inference/native-nvidia/contract.ts b/src/lib/inference/native-nvidia/contract.ts new file mode 100644 index 00000000000..62822577f66 --- /dev/null +++ b/src/lib/inference/native-nvidia/contract.ts @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const NVIDIA_HOSTED_LOGICAL_PROVIDER = "nvidia-prod"; +export const NVIDIA_HOSTED_NATIVE_ENDPOINT = "https://integrate.api.nvidia.com/v1"; +export const NVIDIA_HOSTED_NATIVE_PROFILE_ID = "nemoclaw-nvidia-inference-v1"; +export const NVIDIA_HOSTED_NATIVE_PROVIDER = "nemoclaw-nvidia-prod-v1"; +export const NVIDIA_HOSTED_CREDENTIAL_ENV = "NVIDIA_INFERENCE_API_KEY"; + +export type NativeNvidiaProviderAttachment = Readonly<{ + schemaVersion: 1; + profileId: typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; + providerName: typeof NVIDIA_HOSTED_NATIVE_PROVIDER; + providerId: string; +}>; + +export function normalizeNativeNvidiaProviderAttachment( + value: unknown, +): NativeNvidiaProviderAttachment | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const receipt = value as Record; + if ( + receipt.schemaVersion !== 1 || + receipt.profileId !== NVIDIA_HOSTED_NATIVE_PROFILE_ID || + receipt.providerName !== NVIDIA_HOSTED_NATIVE_PROVIDER || + typeof receipt.providerId !== "string" || + !receipt.providerId.trim() + ) { + return undefined; + } + return { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: receipt.providerId, + }; +} diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index b2a78ee9689..58e881ceaea 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -10,19 +10,23 @@ import type { OpenShellProviderMetadata, } from "../../adapters/openshell/sandbox-observer"; import { REPOSITORY_ROOT } from "../../core/repository-root"; +import { + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_LOGICAL_PROVIDER, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + NVIDIA_HOSTED_NATIVE_PROVIDER, + type NativeNvidiaProviderAttachment, +} from "./contract"; -export const NVIDIA_HOSTED_LOGICAL_PROVIDER = "nvidia-prod"; -export const NVIDIA_HOSTED_NATIVE_ENDPOINT = "https://integrate.api.nvidia.com/v1"; -export const NVIDIA_HOSTED_NATIVE_PROFILE_ID = "nemoclaw-nvidia-inference-v1"; -export const NVIDIA_HOSTED_NATIVE_PROVIDER = "nemoclaw-nvidia-prod-v1"; -export const NVIDIA_HOSTED_CREDENTIAL_ENV = "NVIDIA_INFERENCE_API_KEY"; - -export type NativeNvidiaProviderAttachment = Readonly<{ - schemaVersion: 1; - profileId: typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; - providerName: typeof NVIDIA_HOSTED_NATIVE_PROVIDER; - providerId: string; -}>; +export { + normalizeNativeNvidiaProviderAttachment, + NVIDIA_HOSTED_CREDENTIAL_ENV, + NVIDIA_HOSTED_LOGICAL_PROVIDER, + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + NVIDIA_HOSTED_NATIVE_PROVIDER, + type NativeNvidiaProviderAttachment, +} from "./contract"; export class NativeNvidiaProviderError extends Error { constructor(message: string) { @@ -51,28 +55,6 @@ export function nativeInferenceProviderForSandbox( return isNativeNvidiaProvider(normalized) ? NVIDIA_HOSTED_NATIVE_PROVIDER : normalized; } -export function normalizeNativeNvidiaProviderAttachment( - value: unknown, -): NativeNvidiaProviderAttachment | undefined { - if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; - const receipt = value as Record; - if ( - receipt.schemaVersion !== 1 || - receipt.profileId !== NVIDIA_HOSTED_NATIVE_PROFILE_ID || - receipt.providerName !== NVIDIA_HOSTED_NATIVE_PROVIDER || - typeof receipt.providerId !== "string" || - !receipt.providerId.trim() - ) { - return undefined; - } - return { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: receipt.providerId, - }; -} - function providerErrorDetail(error: OpenShellProviderError): string { return error.message.trim() || "OpenShell did not provide a diagnostic."; } From 34d37f830c6bd49b0f06edd0a7667e22703cf272 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:11:31 -0700 Subject: [PATCH 026/133] fix(inference): retain provider inspection diagnostics Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/reference/network-policies.mdx | 8 +-- .../e2e/live/public-nvidia-switch-provider.ts | 7 ++- test/e2e/mock-parity.json | 3 + .../public-nvidia-switch-provider.test.ts | 61 ++++++++++++++++++- 4 files changed, 73 insertions(+), 6 deletions(-) diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index fa0f976d18b..6c8f228a32e 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -62,7 +62,7 @@ The following endpoint groups are allowed by default: | Policy | Endpoints | Binaries | Rules | | --- | --- | --- | --- | -| `nvidia` | `integrate.api.nvidia.com:443` | `/usr/local/bin/openclaw` | POST to inference and embedding paths, GET to model listings | +| `nvidia` | `integrate.api.nvidia.com:443` | `/usr/local/bin/openclaw` | Retained baseline compatibility rule: POST to inference and embedding paths, GET to model listings. NVIDIA Endpoints selection uses the narrower attached-provider rule described below. | | `clawhub` | `clawhub.ai:443` | `/usr/local/bin/openclaw`, `/usr/local/bin/node` | GET, POST, including scoped package paths | | `openclaw_api` | `openclaw.ai:443`, `catalog.openclaw.ai:443` | `/usr/local/bin/openclaw`, `/usr/local/bin/node` | GET and POST to `openclaw.ai`; GET only to `catalog.openclaw.ai` | | `openclaw_docs` | `docs.openclaw.ai:443` | `/usr/local/bin/openclaw` | GET only | @@ -86,8 +86,8 @@ The separate `raw.githubusercontent.com` route lets Deep Agents Code follow GitH -When you select NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1` provider to the sandbox instead of using `inference.local`. -Its provider profile permits `GET /v1/models` and `POST /v1/chat/completions` at `integrate.api.nvidia.com:443` from the listed agent-runtime and readiness-verification binaries. +When you select NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1` provider to the sandbox instead of using `inference.local` or the broader baseline compatibility rule. +This attached provider is the effective NVIDIA Endpoints route. Its profile permits only `GET /v1/models` and `POST /v1/chat/completions` at `integrate.api.nvidia.com:443` from the listed agent-runtime and readiness-verification binaries. The NVIDIA API key remains in OpenShell provider state and does not enter the sandbox. All endpoints use TLS termination and are enforced at port 443. @@ -217,7 +217,7 @@ Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced ### Inference -The baseline policy allows only the `local` inference route. External inference providers are reached through the OpenShell gateway, not by direct sandbox egress. +Most providers use the OpenShell-managed `inference.local` route. NVIDIA Endpoints instead uses its least-privilege, sandbox-attached OpenShell provider at `integrate.api.nvidia.com`. In both cases, OpenShell mediates inference traffic and keeps provider credentials outside the sandbox. diff --git a/test/e2e/live/public-nvidia-switch-provider.ts b/test/e2e/live/public-nvidia-switch-provider.ts index 1896add382e..c326df53df4 100644 --- a/test/e2e/live/public-nvidia-switch-provider.ts +++ b/test/e2e/live/public-nvidia-switch-provider.ts @@ -32,13 +32,18 @@ export async function readPublicNvidiaSwitchAttachmentEvidence(options: { }): Promise { if (options.logicalProvider !== PUBLIC_NVIDIA_SWITCH_PROVIDER) return null; const receipt = normalizeNativeNvidiaProviderAttachment(options.receipt); + const providerRedactionValues = [ + options.env.NVIDIA_API_KEY, + options.env[NVIDIA_HOSTED_CREDENTIAL_ENV], + ].filter((value): value is string => typeof value === "string" && value.length > 0); const provider = await options.sandbox.openshell( ["provider", "get", "-g", "nemoclaw", NVIDIA_HOSTED_NATIVE_PROVIDER], { artifactName: `${options.artifactName}-provider-metadata`, captureLimitBytes: 16 * 1024, env: options.env, - persistArtifacts: false, + persistArtifacts: true, + redactionValues: providerRedactionValues, timeoutMs: 60_000, }, ); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 654c8a3a7f2..8c6a1ae603e 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -651,6 +651,7 @@ "fast": [ "src/lib/actions/inference-set-compatible-provider.test.ts", "test/e2e/support/hermes-inference-switch-command-shape.test.ts", + "test/e2e/support/public-nvidia-switch-provider.test.ts", "test/e2e/support/retry-policy.test.ts", "test/e2e/support/compatible-anthropic-switch.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", @@ -819,6 +820,7 @@ "liveSources": [ "test/e2e/live/openclaw-inference-switch-helpers.ts", "test/e2e/live/openclaw-admin-scope.ts", + "test/e2e/live/public-nvidia-switch-provider.ts", "test/e2e/fixtures/admin-approval-connect.ts", "test/e2e/fixtures/admin-approval-connect.sh", "test/e2e/fixtures/issue-4462-admin-approval-evidence.ts", @@ -833,6 +835,7 @@ "test/e2e/support/inference-switch-workflow-boundary.test.ts", "test/e2e/support/managed-image-receipt.test.ts", "test/e2e/support/openclaw-inference-switch-helpers.test.ts", + "test/e2e/support/public-nvidia-switch-provider.test.ts", "test/security/admin-approval-helper.test.ts", "test/e2e/support/hosted-inference.test.ts" ] diff --git a/test/e2e/support/public-nvidia-switch-provider.test.ts b/test/e2e/support/public-nvidia-switch-provider.test.ts index 22788913a2c..58010957ecf 100644 --- a/test/e2e/support/public-nvidia-switch-provider.test.ts +++ b/test/e2e/support/public-nvidia-switch-provider.test.ts @@ -60,7 +60,66 @@ describe("public NVIDIA inference switch provider", () => { expect(openshell).toHaveBeenNthCalledWith( 1, ["provider", "get", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], - expect.objectContaining({ persistArtifacts: false }), + expect.objectContaining({ captureLimitBytes: 16 * 1024, persistArtifacts: true }), + ); + }); + + it("retains bounded redacted diagnostics when provider inspection fails", async () => { + const credential = "nvapi-must-not-enter-provider-diagnostics"; + const providerFailure = { + artifacts: { + stdout: "shell/native-nvidia-provider-attachment-provider-metadata.stdout.txt", + stderr: "shell/native-nvidia-provider-attachment-provider-metadata.stderr.txt", + result: "shell/native-nvidia-provider-attachment-provider-metadata.result.json", + }, + command: ["openshell", "provider", "get"], + exitCode: 1, + signal: null, + stderr: "provider lookup failed for [REDACTED]", + stdout: "", + timedOut: false, + } satisfies ShellProbeResult; + const openshell = vi + .fn() + .mockResolvedValueOnce(providerFailure) + .mockResolvedValueOnce({ + artifacts: { stdout: "", stderr: "", result: "" }, + command: ["openshell", "sandbox", "provider", "list"], + exitCode: 0, + signal: null, + stderr: "", + stdout: "nemoclaw-nvidia-prod-v1\n", + timedOut: false, + } satisfies ShellProbeResult); + + const evidence = await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "native-nvidia-provider-attachment", + env: { + NVIDIA_INFERENCE_API_KEY: credential, + OPENSHELL_GATEWAY: "nemoclaw", + }, + logicalProvider: PUBLIC_NVIDIA_SWITCH_PROVIDER, + receipt: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-revision-1", + }, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "e2e-hm-inf-switch", + }); + + expect(evidence).toContain("provider-inspection=1"); + expect(Object.values(providerFailure.artifacts).every((value) => value.length > 0)).toBe(true); + expect(JSON.stringify(providerFailure)).not.toContain(credential); + expect(openshell).toHaveBeenNthCalledWith( + 1, + ["provider", "get", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + expect.objectContaining({ + captureLimitBytes: 16 * 1024, + persistArtifacts: true, + redactionValues: [credential], + }), ); }); }); From 995f912498f274e433507b6fd3786452f8d750df Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:43:56 -0700 Subject: [PATCH 027/133] docs: clarify native NVIDIA routes --- docs/get-started/quickstart-pi.mdx | 2 +- docs/inference/how-inference-routing-works.mdx | 2 +- docs/reference/commands.mdx | 2 +- docs/reference/pi-support.mdx | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/get-started/quickstart-pi.mdx b/docs/get-started/quickstart-pi.mdx index a694ff616eb..132b09483b9 100644 --- a/docs/get-started/quickstart-pi.mdx +++ b/docs/get-started/quickstart-pi.mdx @@ -49,7 +49,7 @@ For an existing installation, run the canonical onboarding command. nemoclaw onboard --agent pi --name my-pi ``` -Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell and gives Pi only the managed `https://inference.local/v1` route. The credential remains in the gateway across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. +Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell. Most providers give Pi the managed `https://inference.local/v1` route. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox at `https://integrate.api.nvidia.com/v1`. The credential remains in OpenShell provider state across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. Stock onboarding selects a Pi managed-image digest. It does not build the Pi Dockerfile on the host. The reviewed Dockerfile is a trusted CI image-build source, not a user onboarding mechanism. A missing, incomplete, mutable, or inconsistent image contract fails before sandbox creation. diff --git a/docs/inference/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index 2b20a5ea0cc..2dafc00a0e6 100644 --- a/docs/inference/how-inference-routing-works.mdx +++ b/docs/inference/how-inference-routing-works.mdx @@ -39,7 +39,7 @@ When a rebuild reuses an automatically bridged compatible-endpoint route without ## Deep Agents Configuration -For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with the managed OpenAI-compatible `https://inference.local/v1` route, a scoped placeholder API key, and `use_responses_api = false`. +For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with a managed OpenAI-compatible provider, a scoped placeholder API key, and `use_responses_api = false`. Most providers use `https://inference.local/v1`. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox at `https://integrate.api.nvidia.com/v1`. The managed `dcode` runtime uses Chat Completions through OpenShell even when a compatible endpoint also supports the Responses API. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index bee27a7427e..ce3046b9a6f 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1673,7 +1673,7 @@ The command probes the selected provider path from inside the sandbox, and when | `not probed` | NemoClaw could not run the authoritative route probe from a reachable sandbox. | | `not verified` | NemoClaw could not verify the sandbox or gateway state, so it skips inference probing. | -An authentication response on the route probe alone confirms that the route is reachable, not that provider credentials are valid. `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative `inference.local` result or determine the command exit status. +An authentication response on the route probe alone confirms that the route is reachable, not that provider credentials are valid. `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` sends no inference request, so it always reports the `Inference (upstream)` state that it measured. diff --git a/docs/reference/pi-support.mdx b/docs/reference/pi-support.mdx index 378401b235e..f78063a4faa 100644 --- a/docs/reference/pi-support.mdx +++ b/docs/reference/pi-support.mdx @@ -60,7 +60,7 @@ Each receipt must match the protected inputs and an image digest in the candidat Pi reads a generated `/sandbox/.pi/agent/models.json` file. The file contains the model, managed route, API family, and a non-secret route placeholder. It does not contain the upstream provider credential. -The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. Pi reaches the provider through `inference.local`; direct provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. +The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. Most providers give Pi the managed `inference.local` route. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox for `integrate.api.nvidia.com`. Direct unmanaged provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. The initial qualification requires streaming, a structured `read` tool call, a successful tool result, and an independently checked final response with `nvidia/nemotron-3-super-120b-a12b`. From 44444f46777a4df2b29852f713a48b7aa8edb7f8 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:38:31 -0700 Subject: [PATCH 028/133] test(config): fix native NVIDIA profile assertion --- src/lib/adapters/config/live-export-source.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index 2e3486801d3..9845c624caa 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -505,7 +505,7 @@ describe("live export snapshot reader", () => { expect(yaml).not.toContain(readFailureCanary); expect(raw.getProviderProfile).toHaveBeenCalledTimes(2); expect(raw.getProviderProfile).toHaveBeenCalledWith( - { id: "nvidia", workspace: profileWorkspace }, + { id: "nemoclaw-nvidia-inference-v1", workspace: profileWorkspace }, { signal: expect.any(AbortSignal) }, ); expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); From 9a15e2ea6fab98d60d063cf53ef9b51f9293e365 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:49:25 -0700 Subject: [PATCH 029/133] fix(inference): complete native NVIDIA route migration --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 +-- ci/pi-agent-qualification-v1-linux-arm64.json | 8 +-- .../inference/how-inference-routing-works.mdx | 20 +++++--- .../status-snapshot-route-drift.test.ts | 51 +++++++++++++++++-- src/lib/actions/sandbox/status-snapshot.ts | 25 +++++---- src/lib/agent/candidate-authority.ts | 4 +- src/lib/domain/config/verify-export-source.ts | 3 +- .../verify-deployment-inference-route.test.ts | 26 +++++++++- src/lib/verify-deployment.ts | 37 ++++++++++++-- 9 files changed, 143 insertions(+), 39 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index c87a79a68d9..b430129798b 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:546f2a680e576c7aedcbf6df417557dd42a81629ee936f3e086638d3462eb340", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:546f2a680e576c7aedcbf6df417557dd42a81629ee936f3e086638d3462eb340", + "digest": "sha256:3199a4d188ce245617956fa69c175aba0cf2d40d9b799c238c41183ea47ee081", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:3199a4d188ce245617956fa69c175aba0cf2d40d9b799c238c41183ea47ee081", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "f36ea6f02ac5da862a3e518362f534c1812f6376", + "revision": "10c722f92577379f0594ee058e98514cdeb9ec81", "release": "v0.1.0", - "cohort": "ghrun-37022365614-2" + "cohort": "ghrun-37271269902-2" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 69b020ab3b2..fe689113077 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:a11b69b1ecc9eb8480bfc7d47832f40f3a25417a5fe154c47accde5d1ae569e8", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:a11b69b1ecc9eb8480bfc7d47832f40f3a25417a5fe154c47accde5d1ae569e8", + "digest": "sha256:dfbd55ca1081106d26c90b53a1969109e8c6d4fe57c78e95de6c9c260f71931f", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:dfbd55ca1081106d26c90b53a1969109e8c6d4fe57c78e95de6c9c260f71931f", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "f36ea6f02ac5da862a3e518362f534c1812f6376", + "revision": "10c722f92577379f0594ee058e98514cdeb9ec81", "release": "v0.1.0", - "cohort": "ghrun-37022365614-2" + "cohort": "ghrun-37271269902-2" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/docs/inference/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index 2dafc00a0e6..f8bbf7c65f3 100644 --- a/docs/inference/how-inference-routing-works.mdx +++ b/docs/inference/how-inference-routing-works.mdx @@ -9,21 +9,27 @@ keywords: ["nemoclaw inference routing", "inference.local", "openshell inference content: type: "concept" --- -NemoClaw gives agents one managed inference route while OpenShell handles the selected upstream provider on the host. -This design keeps provider selection and credentials outside the sandbox. +NemoClaw gives agents a managed inference path while OpenShell handles the selected upstream provider on the host. +This design keeps provider credentials outside the sandbox. ## Request Path -The agent sends inference requests to `inference.local` inside the sandbox. -It does not connect to the upstream provider directly. -OpenShell intercepts the request on the host and forwards it to the provider and model selected during onboarding. +Most providers use the shared `inference.local` route inside the sandbox. +OpenShell intercepts each request on the host and forwards it to the provider and model selected during onboarding. ```text -Sandbox agent -> inference.local -> OpenShell -> selected provider and model +Sandbox agent -> inference.local -> shared OpenShell route -> selected provider and model +``` + +NVIDIA Endpoints use a sandbox-attached OpenShell provider instead of the shared route. +The agent addresses the NVIDIA API hostname, but OpenShell still intercepts the request and supplies the host-managed credential. + +```text +Sandbox agent -> integrate.api.nvidia.com -> sandbox-attached OpenShell provider -> NVIDIA ``` Host-side services such as Model Router and the OpenRouter runtime adapter remain behind the OpenShell route. -The sandbox continues to use `inference.local` instead of calling their host ports directly. +The sandbox uses `inference.local` for those services instead of calling their host ports directly. ## Credential Boundary diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index 72ca484b6cc..716f5554a94 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -523,6 +523,52 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = expect(snapshot.inferenceHealth).toMatchObject({ ok: true, probed: true }); }); + it("ignores a shared-route protocol mismatch for a native NVIDIA attachment", async () => { + const sandbox = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/nemotron-3-super-120b-a12b", + preferredInferenceApi: "openai-completions", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-123", + }, + } as SandboxEntry; + const observeInferenceRoute = vi.fn( + async () => + ({ + ok: false, + error: { + kind: "schema", + reason: "protocol_mismatch", + message: "The OpenShell CLI and gateway inference schemas do not match.", + }, + }) as const, + ); + const invoke = vi.fn(async () => ({ ok: true }) as const); + + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + inferenceRouteObserver: { observeInferenceRoute }, + probeProviderHealthImpl: () => null, + probeSandboxInferenceInvocationImpl: invoke, + verifyNativeNvidiaProviderAttachmentImpl: async () => undefined, + }, + } as never); + + expect(observeInferenceRoute).not.toHaveBeenCalled(); + expect(snapshot.rpcIssue).toBeNull(); + expect(invoke).toHaveBeenCalledOnce(); + expect(snapshot.inferenceHealth).toMatchObject({ ok: true, probed: true }); + }); + it("reports a missing native NVIDIA attachment before probing inference", async () => { liveGatewayInference("compatible-endpoint", "other/model"); const sandbox = { @@ -601,10 +647,7 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", }); - expect(report.liveRoute).toEqual({ - provider: "compatible-endpoint", - model: "other/model", - }); + expect(report.liveRoute).toBeNull(); expect(report.routeDrift).toBeNull(); }); }); diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 0de3fb1d557..8c5824ed057 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -559,18 +559,24 @@ export async function collectSandboxStatusSnapshot( const suppressInferenceProbe = (postRecoveryPreflight ?? initialPreflight)?.suppressInferenceProbe ?? opts.suppressInferenceProbe === true; + const nativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( + sb?.nativeNvidiaProviderAttachment, + ); + const nativeNvidia = Boolean(nativeNvidiaAttachment); let liveResult: OpenShellInferenceRouteResult | null = null; let gatewayName: string | null = null; if (lookup.state === "present") { try { gatewayName = resolveSandboxGatewayName(sb); - const observer = - opts.deps?.inferenceRouteObserver ?? - createCliOpenShellInferenceRouteObserver(captureOpenshellForStatus); - liveResult = await observer.observeInferenceRoute({ - target: { kind: "named", gatewayName }, - timeoutMs: getStatusProbeTimeoutMs(), - }); + if (!nativeNvidia) { + const observer = + opts.deps?.inferenceRouteObserver ?? + createCliOpenShellInferenceRouteObserver(captureOpenshellForStatus); + liveResult = await observer.observeInferenceRoute({ + target: { kind: "named", gatewayName }, + timeoutMs: getStatusProbeTimeoutMs(), + }); + } } catch { // Invalid persisted gateway bindings and failed reads stay fail-closed: // never substitute the selected/default gateway's inference route. @@ -608,12 +614,9 @@ export async function collectSandboxStatusSnapshot( // as drift instead of being mislabeled as this sandbox's configuration. const currentModel = sb ? sb.model || "unknown" : (live && live.model) || "unknown"; const currentProvider = sb ? sb.provider || "unknown" : (live && live.provider) || "unknown"; - const nativeNvidia = Boolean( - normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), - ); let nativeNvidiaAttachmentFailure: string | null = null; if (!suppressInferenceProbe && lookup.state === "present" && nativeNvidia && sb) { - const expected = normalizeNativeNvidiaProviderAttachment(sb.nativeNvidiaProviderAttachment); + const expected = nativeNvidiaAttachment; if (!gatewayName || !expected) { nativeNvidiaAttachmentFailure = `Native NVIDIA provider attachment is unavailable for sandbox '${sandboxName}'. ` + diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index b17a9452ea1..12e5658adef 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "dcfcc1231777ac1031ebb1346bee0f38dbaa7fc94485c2a13dabbc98c0c85d4f", - "321d43db15a6a5664d41154b9d5be5bd678ec0d661962ba1e674aad4fb527501", + "d855997debeaade6bce6347df785f0640704afe6a67304c274d1c7c55021a9b8", + "d3ef06eec4166f002629795dd0c8eca04a9d12a30cdb27a7d190a1f188f1cee5", ]), }); diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 8ee80667a36..9e40c3e3ef6 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -921,7 +921,8 @@ function sandboxProviderAttachmentsMatch(snapshot: QualifiedExportSnapshot): boo ); const inferenceAttachment = nativeReceipt?.providerName ?? inference.provider; const additionalProviders = sandbox.providerNames.filter((name) => name !== inferenceAttachment); - const expectedAdditionalProviders = hasBraveSearch(entry) ? [`${entry.name}-brave-search`] : []; + const webSearch = exportWebSearchBinding(entry); + const expectedAdditionalProviders = webSearch ? [webSearch.name] : []; return ( !(nativeReceipt && !sandbox.providerNames.includes(nativeReceipt.providerName)) && isDeepStrictEqual(additionalProviders, expectedAdditionalProviders) && diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index 7f3580400d8..af10eae7017 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { buildChain } from "./dashboard/contract.js"; import { probeOnboardInferenceInvocation, verifyDeployment } from "./verify-deployment.js"; @@ -35,6 +35,30 @@ function makeModelsRouteDeps(code: string, overrides: Record = } describe("verifyDeployment inference route model-catalog validation", () => { + it("uses the native NVIDIA invocation instead of probing inference.local", async () => { + const scripts: string[] = []; + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); + const result = await verifyDeployment( + "my-sandbox", + buildChain(), + makeModelsRouteDeps("000", { + executeSandboxCommand: async (_name: string, script: string) => { + scripts.push(script); + return { status: 0, stdout: "200", stderr: "" }; + }, + probeInferenceInvocation, + }), + { + ...NO_RETRY, + inferenceRouteContext: { agentName: "openclaw", provider: "nvidia-prod" }, + }, + ); + + expect(result.verification.inferenceRouteWorking).toBe(true); + expect(probeInferenceInvocation).toHaveBeenCalledOnce(); + expect(scripts.join("\n")).not.toContain("inference.local"); + }); + it("fails the deployment when the models route returns HTTP 404 (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index b37fe817516..d8a9bb799c0 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -111,11 +111,12 @@ export interface VerifyDeploymentDeps { providerExistsInGateway: (providerName: string) => boolean | Promise; /** - * Send one bounded inference request over the gateway route from inside the - * sandbox. Only consulted for the Deep Agents Code OpenRouter models route, - * whose HTTP 404 is expected (#9834) and can only be accepted on the - * evidence of a served request. Optional: when it is absent that 404 fails - * closed, because nothing validated the selected model (#10543). + * Send one bounded inference request over the sandbox's configured route. + * This is authoritative for native NVIDIA, which has no shared + * `inference.local` route, and for the Deep Agents Code OpenRouter models + * route whose HTTP 404 is expected (#9834). Optional: when it is absent, + * either exceptional path fails closed because nothing validated the + * selected model (#10543). */ probeInferenceInvocation?: () => Promise<{ ok: boolean; detail?: string }>; @@ -394,6 +395,32 @@ async function verifyInferenceRoute( sleep: (ms: number) => Promise, context: InferenceRouteContext, ): Promise { + if (isNativeNvidiaProvider(context.provider)) { + const invocation = await retryUntilAsync( + async () => (await deps.probeInferenceInvocation?.()) ?? null, + { + accept: (result) => result?.ok === true, + retryDelaysMs, + sleep, + }, + ); + if (invocation?.ok) { + return { + status: "ok", + detail: "native NVIDIA inference served an agent request", + httpCode: 200, + }; + } + const reason = invocation?.detail ?? "no inference request confirmed the selected model"; + return { + status: "unhealthy", + detail: `native NVIDIA inference did not serve an agent request: ${reason}`, + httpCode: 0, + hint: + "The sandbox-attached NVIDIA provider could not serve the selected model. Confirm the " + + "NVIDIA credential and model, then re-run: nemoclaw status.", + }; + } const routeContext = toRouteHealthContext(context); const isExpected404 = (result: InferenceRouteProbe) => isDcodeOpenRouterModelsRoute404(routeContext, result.httpCode); From 2c2eca1f7a33d3a4373387ce2cb899727c236081 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 01:38:41 -0700 Subject: [PATCH 030/133] fix(inference): clear stale native provider state --- docs/reference/pi-support.mdx | 2 +- ...egistry-native-provider-attachment.test.ts | 43 +++++++++++++++++++ src/lib/state/registry.ts | 9 +++- 3 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 src/lib/state/registry-native-provider-attachment.test.ts diff --git a/docs/reference/pi-support.mdx b/docs/reference/pi-support.mdx index f78063a4faa..a13d37c83ce 100644 --- a/docs/reference/pi-support.mdx +++ b/docs/reference/pi-support.mdx @@ -33,7 +33,7 @@ Pi is a NemoClaw agent runtime. Docker is the initial compute runtime. Pi-specif | Host platform | Linux AMD64 or Linux ARM64 | | Compute runtime | Docker | | Managed API | OpenAI Chat Completions | -| Sandbox route | `https://inference.local/v1` | +| Sandbox route | Shared: `https://inference.local/v1`; NVIDIA: `https://integrate.api.nvidia.com/v1` | | Qualification model | `nvidia/nemotron-3-super-120b-a12b` | | Interactive command | `pi` | | Headless command | `pi --no-approve --print` | diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts new file mode 100644 index 00000000000..30060e64af7 --- /dev/null +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { expect, it, vi } from "vitest"; + +it("clears a stale native NVIDIA attachment when reserving a shared route", async () => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-native-attachment-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + registry.registerSandbox({ + name: "alpha", + provider: "nvidia-prod", + model: "model-a", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }, + gatewayName: "nemoclaw", + gatewayPort: 8080, + }); + + registry.reserveSandboxInferenceRoute("alpha", { + provider: "anthropic-prod", + model: "model-b", + endpointUrl: null, + credentialEnv: "ANTHROPIC_API_KEY", + preferredInferenceApi: "anthropic-messages", + gatewayName: "nemoclaw-9090", + }); + + expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAttachment).toBeUndefined(); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } +}); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index c38223f780b..593bd1137e4 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -8,7 +8,10 @@ import { inferenceSelectionRegistryFields, normalizeInferenceSelection, } from "../inference/selection"; -import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia"; +import { + isNativeNvidiaProvider, + normalizeNativeNvidiaProviderAttachment, +} from "../inference/native-nvidia"; import { parseServingProfileProvenance } from "../inference/serving/profile-provenance"; import { normalizeToolDisclosure } from "../tool-disclosure"; import { @@ -731,11 +734,13 @@ export function reserveSandboxInferenceRoute( endpointSource: normalized.endpointSource, credentialEnv: normalized.credentialEnv, preferredInferenceApi: normalized.preferredInferenceApi, + nativeNvidiaProviderAttachment: isNativeNvidiaProvider(normalized.provider) + ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) + : undefined, ...(route.hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt: route.hostLocalInferenceReceipt } : {}), ...(provenance ? { hostLocalInferenceProvenance: provenance } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), gatewayName: route.gatewayName, gatewayPort: route.gatewayPort ?? From 322428aecd082c1dc61aca957d9fd47375ba9de2 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 02:35:34 -0700 Subject: [PATCH 031/133] fix: address native inference review findings Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- agents/langchain-deepagents-code/Dockerfile | 4 +++- .../dcode-wrapper.sh | 4 ++++ .../generate-config.ts | 9 +++++++- .../managed-dcode-runtime.py | 2 ++ agents/langchain-deepagents-code/start.sh | 2 ++ docs/deployment/deploy-to-headless-server.mdx | 4 ++-- docs/monitoring/monitor-sandbox-activity.mdx | 2 +- docs/security/process-controls.mdx | 3 ++- src/lib/inference/native-nvidia.test.ts | 21 +++++++++++++++++++ src/lib/inference/native-nvidia/index.ts | 7 ++++++- .../langchain-deepagents-code-config.test.ts | 9 ++++++++ ...eepagents-code-direct-module-patch.test.ts | 2 ++ .../langchain-deepagents-code-image.test.ts | 6 ++++++ ...ain-deepagents-code-provider-label.test.ts | 1 + .../native-nvidia-target-ownership.test.ts | 1 + tools/e2e/target-catalogue.mts | 1 + 16 files changed, 71 insertions(+), 7 deletions(-) diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index f398a388fea..12a8a2adff2 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -155,6 +155,7 @@ RUN set -eu; \ COPY agents/langchain-deepagents-code/generate-config-entrypoint.ts /opt/nemoclaw-deepagents-code/generate-config.ts COPY agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts COPY src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts +COPY src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts COPY agents/langchain-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py COPY agents/langchain-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py COPY agents/langchain-deepagents-code/patch-managed-quickjs.py /opt/nemoclaw-deepagents-code/patch-managed-quickjs.py @@ -187,7 +188,7 @@ COPY nemoclaw-blueprint/ /opt/nemoclaw-blueprint/ # regressionTest: the stripped-base gate must reach this marker, then fail import. # removalCondition: remove when installation validates dependencies atomically. # hadolint ignore=DL4006 -RUN chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-quickjs.py /opt/nemoclaw-deepagents-code/validate-nemotron-ultra-profile.py /opt/nemoclaw-deepagents-code/progressive_tool_disclosure.py /opt/nemoclaw-deepagents-code/nemoclaw_observability.py /opt/nemoclaw-deepagents-code/validate-progressive-tool-disclosure.py /opt/nemoclaw-deepagents-code/validate-observability.py /opt/nemoclaw-deepagents-code/validate-read-only-mcp-call.py /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh /etc/profile.d/nemoclaw-dcode.sh /usr/local/lib/nemoclaw/nemoclaw_read_only_mcp.py \ +RUN chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-quickjs.py /opt/nemoclaw-deepagents-code/validate-nemotron-ultra-profile.py /opt/nemoclaw-deepagents-code/progressive_tool_disclosure.py /opt/nemoclaw-deepagents-code/nemoclaw_observability.py /opt/nemoclaw-deepagents-code/validate-progressive-tool-disclosure.py /opt/nemoclaw-deepagents-code/validate-observability.py /opt/nemoclaw-deepagents-code/validate-read-only-mcp-call.py /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh /etc/profile.d/nemoclaw-dcode.sh /usr/local/lib/nemoclaw/nemoclaw_read_only_mcp.py \ && chmod 755 /usr/local/bin/nemoclaw-start /usr/local/bin/nemoclaw-managed-startup-hold /usr/local/lib/nemoclaw/dcode-wrapper.sh /usr/local/lib/nemoclaw/dcode-launcher.sh /usr/local/lib/nemoclaw/dcode-session-supervisor.py \ && test "$(stat -c '%u:%g:%a' /usr/local/lib/nemoclaw/dcode-session-supervisor.py)" = "0:0:755" \ && install -o root -g root -m 0755 /usr/local/lib/nemoclaw/dcode-launcher.sh /usr/local/lib/nemoclaw/dcode-managed-exec \ @@ -316,6 +317,7 @@ ENV HOME=/sandbox \ DEEPAGENTS_CODE_OFFLINE=1 \ DEEPAGENTS_CODE_RIPGREP_INSTALLER=system \ DEEPAGENTS_CODE_OPENAI_API_KEY=nemoclaw-managed-inference \ + NEMOCLAW_ATTACHED_PROVIDER_API_KEY=nemoclaw-openshell-provider \ OPENAI_BASE_URL=${NEMOCLAW_INFERENCE_BASE_URL} WORKDIR /sandbox diff --git a/agents/langchain-deepagents-code/dcode-wrapper.sh b/agents/langchain-deepagents-code/dcode-wrapper.sh index b31fa22feb9..d5344d1299d 100755 --- a/agents/langchain-deepagents-code/dcode-wrapper.sh +++ b/agents/langchain-deepagents-code/dcode-wrapper.sh @@ -35,6 +35,7 @@ export LANGCHAIN_TRACING_V2=false export DEEPAGENTS_CODE_OFFLINE=1 export DEEPAGENTS_CODE_RIPGREP_INSTALLER=system export DEEPAGENTS_CODE_OPENAI_API_KEY="${DEEPAGENTS_CODE_OPENAI_API_KEY:-nemoclaw-managed-inference}" +export NEMOCLAW_ATTACHED_PROVIDER_API_KEY=nemoclaw-openshell-provider export OPENAI_BASE_URL="${OPENAI_BASE_URL:-https://inference.local/v1}" unset PYTHONHOME PYTHONPATH @@ -238,6 +239,9 @@ is_managed_token_value_for_name() { DEEPAGENTS_CODE_OPENAI_API_KEY) [ "$value" = "nemoclaw-managed-inference" ] && return 0 ;; + NEMOCLAW_ATTACHED_PROVIDER_API_KEY) + [ "$value" = "nemoclaw-openshell-provider" ] && return 0 + ;; SLACK_BOT_TOKEN) case "$value" in xoxb-*) diff --git a/agents/langchain-deepagents-code/generate-config.ts b/agents/langchain-deepagents-code/generate-config.ts index 0c3789e6876..5259c8a72a0 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -15,6 +15,7 @@ import { normalizeManagedDcodeEndpointUrl, resolveManagedDcodeIdentity, } from "../../src/lib/inference/managed-dcode/identity.ts"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../src/lib/inference/native-nvidia/contract.ts"; type ReasoningEffort = "low" | "medium" | "high"; @@ -39,6 +40,8 @@ const NEMOTRON_ULTRA_MODEL_IDS = new Set([ "nvidia/nemotron-3-ultra-550b-a55b", "nvidia/nvidia/nemotron-3-ultra", ]); +const MANAGED_INFERENCE_API_KEY_ENV = "DEEPAGENTS_CODE_OPENAI_API_KEY"; +const ATTACHED_PROVIDER_API_KEY_ENV = "NEMOCLAW_ATTACHED_PROVIDER_API_KEY"; function readSettings(env: NodeJS.ProcessEnv): Settings { const providerKey = normalizeCommentMetadata( @@ -158,10 +161,14 @@ function providerConfigLines( baseUrl: string, reasoningEffort: ReasoningEffort | null, ): string[] { + const apiKeyEnv = + baseUrl === NVIDIA_HOSTED_NATIVE_ENDPOINT + ? ATTACHED_PROVIDER_API_KEY_ENV + : MANAGED_INFERENCE_API_KEY_ENV; return [ `[models.providers.${provider}]`, `models = ${tomlArray([model])}`, - 'api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"', + `api_key_env = ${tomlString(apiKeyEnv)}`, `base_url = ${tomlString(baseUrl)}`, "enabled = true", ...(provider === "openai" diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index 9b774be03b3..e5ac3ebb2ee 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -244,6 +244,8 @@ def _is_openshell_placeholder_for_name(name: str, value: str) -> bool: def _is_managed_value(name: str, value: str) -> bool: if name == "DEEPAGENTS_CODE_OPENAI_API_KEY": return value == "nemoclaw-managed-inference" + if name == "NEMOCLAW_ATTACHED_PROVIDER_API_KEY": + return value == "nemoclaw-openshell-provider" if name == "SLACK_BOT_TOKEN": return bool(re.fullmatch(r"xoxb-[A-Za-z0-9_-]{10,}", value)) and not _contains_other_platform_secret(value, "slack") if name == "SLACK_APP_TOKEN": diff --git a/agents/langchain-deepagents-code/start.sh b/agents/langchain-deepagents-code/start.sh index 4f597948b4f..771e873e9f2 100755 --- a/agents/langchain-deepagents-code/start.sh +++ b/agents/langchain-deepagents-code/start.sh @@ -61,6 +61,7 @@ export LANGCHAIN_TRACING_V2=false export DEEPAGENTS_CODE_OFFLINE=1 export DEEPAGENTS_CODE_RIPGREP_INSTALLER=system export DEEPAGENTS_CODE_OPENAI_API_KEY="${DEEPAGENTS_CODE_OPENAI_API_KEY:-nemoclaw-managed-inference}" +export NEMOCLAW_ATTACHED_PROVIDER_API_KEY=nemoclaw-openshell-provider export OPENAI_BASE_URL="${OPENAI_BASE_URL:-https://inference.local/v1}" # Harden RLIMITs (nproc + nofile) for the long-running Deep Agents Code process @@ -277,6 +278,7 @@ prepare_runtime_env() { write_export_if_set DEEPAGENTS_CODE_FETCH_URL_TRUSTED_PROXY_URL # shellcheck disable=SC2016 printf '%s\n' 'export DEEPAGENTS_CODE_OPENAI_API_KEY="${DEEPAGENTS_CODE_OPENAI_API_KEY:-nemoclaw-managed-inference}"' + printf '%s\n' 'export NEMOCLAW_ATTACHED_PROVIDER_API_KEY=nemoclaw-openshell-provider' # shellcheck disable=SC2016 printf '%s\n' 'export OPENAI_BASE_URL="${OPENAI_BASE_URL:-https://inference.local/v1}"' printf '%s\n' 'unset ALL_PROXY all_proxy OPENAI_PROXY' diff --git a/docs/deployment/deploy-to-headless-server.mdx b/docs/deployment/deploy-to-headless-server.mdx index ee3889de079..e13b2d2fc3e 100644 --- a/docs/deployment/deploy-to-headless-server.mdx +++ b/docs/deployment/deploy-to-headless-server.mdx @@ -206,7 +206,7 @@ $$nemoclaw headless-agent status $$nemoclaw headless-agent connect --probe-only ``` -`$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified. Its main `Inference` line probes `https://inference.local/v1/models` from inside the sandbox, then sends an inference request over the same route when that probe reports the route reachable. It repeats both probes up to three total attempts when that request returns a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after a final failure or after all transient attempts fail. +`$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified. Its main `Inference` line probes the selected provider path from inside the sandbox. Shared providers use `https://inference.local/v1/models`, then send an inference request over the same route when that probe reports the route reachable. NVIDIA Endpoints verifies the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1` with an inference request. Status repeats inference requests up to three total attempts when they return a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after a final failure or after all transient attempts fail. @@ -428,7 +428,7 @@ Run `openshell sandbox list` and inspect the row for `headless-agent`. `NotReady ### Inference Returns HTTP 5xx -A final HTTP status from `500` through `599` makes the authoritative `inference.local` route unhealthy. HTTP `502`, `503`, and `504` report unhealthy only after all transient attempts fail. Check the configured provider and host egress, then run: +A final HTTP status from `500` through `599` makes the selected provider path unhealthy. HTTP `502`, `503`, and `504` report unhealthy only after all transient attempts fail. Check the configured provider and host egress, then run: ```bash $$nemoclaw headless-agent doctor diff --git a/docs/monitoring/monitor-sandbox-activity.mdx b/docs/monitoring/monitor-sandbox-activity.mdx index a73c6e45d79..63a656bae2b 100644 --- a/docs/monitoring/monitor-sandbox-activity.mdx +++ b/docs/monitoring/monitor-sandbox-activity.mdx @@ -27,7 +27,7 @@ Run the status command to view sandbox state, gateway health, and the active inf $$nemoclaw status ``` -`$$nemoclaw status` probes `https://inference.local/v1/models` from inside the sandbox as the authoritative inference check. +`$$nemoclaw status` probes the selected provider path from inside the sandbox as the authoritative inference check. Shared providers use `https://inference.local/v1/models`. NVIDIA Endpoints uses the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1` and verifies it with an inference request. For local Ollama and local vLLM routes, it also prints labeled host-side backend diagnostics that help identify which hop failed. Review these output fields. diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index 04b732338a6..9ec841cdd9f 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -292,7 +292,8 @@ A registry-side tag change cannot silently select another managed sandbox image. For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. It removes only the exact legacy NemoClaw-generated profile for the selected managed provider and preserves other profiles. -Direct inference routes outside `inference.local` retain supplied credentials. +The native NVIDIA route uses `integrate.api.nvidia.com` with an OpenShell-managed placeholder credential. It does not retain a supplied NVIDIA credential in the sandbox. +Other unmanaged direct routes retain supplied credentials. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain. diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index f84595152bc..2a33d02937c 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -185,6 +185,27 @@ describe("native NVIDIA OpenShell provider", () => { expect(updateProvider).not.toHaveBeenCalled(); }); + it("does not record a receipt after an ambiguous credential update (#12558)", async () => { + const getProvider = vi.fn(async () => ({ + ok: true, + value: metadata(), + })); + const updateProvider = vi.fn(async () => ({ + ok: false, + error: { kind: "timeout", message: "timed out" }, + })); + + await expect( + ensureNativeNvidiaProvider({ + adapter: adapter({ getProvider, updateProvider }), + target, + credentialValue: "replacement-secret", + }), + ).rejects.toThrow(/did not confirm.*credential update.*No provider receipt was recorded/u); + expect(updateProvider).toHaveBeenCalledOnce(); + expect(getProvider).toHaveBeenCalledOnce(); + }); + it("refuses to replace a recorded provider that is missing (#12558)", async () => { const createProvider = vi.fn(); diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 58e881ceaea..5ef187d6bbe 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -149,7 +149,12 @@ export async function ensureNativeNvidiaProvider(input: { credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], config: [], }); - if (!updated.ok && !mutationOutcomeMayBeAmbiguous(updated.error)) { + if (!updated.ok && mutationOutcomeMayBeAmbiguous(updated.error)) { + throw new NativeNvidiaProviderError( + `OpenShell did not confirm whether provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' accepted its credential update. No provider receipt was recorded.`, + ); + } + if (!updated.ok) { throw new NativeNvidiaProviderError( `Could not update OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(updated.error)}`, ); diff --git a/test/agents/deepagents/langchain-deepagents-code-config.test.ts b/test/agents/deepagents/langchain-deepagents-code-config.test.ts index 4e7c6af6670..083e8f84856 100644 --- a/test/agents/deepagents/langchain-deepagents-code-config.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-config.test.ts @@ -86,6 +86,15 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).not.toMatch(/NVIDIA_API_KEY|OPENAI_API_KEY=|sk-/); }); + it("uses the attached-provider placeholder for native NVIDIA inference (#12558)", () => { + const config = runGenerator({ + NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1", + }); + + expect(config).toContain('api_key_env = "NEMOCLAW_ATTACHED_PROVIDER_API_KEY"'); + expect(config).not.toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); + }); + it("keeps the legacy provider key when the renamed route variables are absent", () => { const config = runGenerator({ NEMOCLAW_PROVIDER_KEY: "legacy-route", diff --git a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts index e81720c01a8..f266327ac15 100644 --- a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts @@ -367,6 +367,7 @@ check("disabled", False) it.each([ ["OPENAI_API_KEY", "sk-TEST-FAKE-DO-NOT-USE-000000000000"], + ["NEMOCLAW_ATTACHED_PROVIDER_API_KEY", "sk-TEST-FAKE-DO-NOT-USE-000000000000"], ["NOTES", "metadata API_KEY=ABCDEFGHIJKL"], ["SLACK_BOT_TOKEN", "xoxb-sk-abcdefghijklmnopqrstuv"], ["LANGSMITH_RUNS_ENDPOINTS", '{"https://trace.example":"opaque-key-value"}'], @@ -460,6 +461,7 @@ check("disabled", False) PATH: process.env.PATH, PYTHONPATH: tempDir, DEEPAGENTS_CODE_OPENAI_API_KEY: "nemoclaw-managed-inference", + NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "nemoclaw-openshell-provider", SLACK_BOT_TOKEN: ["xoxb", "1234567890abcdef"].join("-"), DEEPAGENTS_CODE_LANGSMITH_TRACING: "true", DEEPAGENTS_CODE_LANGSMITH_TRACING_V2: "true", diff --git a/test/agents/deepagents/langchain-deepagents-code-image.test.ts b/test/agents/deepagents/langchain-deepagents-code-image.test.ts index 52b47bfe6b5..27bb0a9e173 100644 --- a/test/agents/deepagents/langchain-deepagents-code-image.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-image.test.ts @@ -235,6 +235,9 @@ describe("LangChain Deep Agents Code image contracts", () => { expect(dockerfile).toContain( "COPY src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts", ); + expect(dockerfile).toContain( + "COPY src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts", + ); expect(dockerfile).toContain("node /opt/nemoclaw-deepagents-code/generate-config.ts"); expect(dockerfile).not.toContain("langchain-deepagents-code-sandbox-base:latest"); expect(dockerfile).toContain( @@ -385,6 +388,9 @@ describe("LangChain Deep Agents Code image contracts", () => { expect(outputLines).toContain(`SOURCED_${name}=1`); expect(envFileLines).toContain(`export ${name}=1`); } + expect(envFileLines).toContain( + "export NEMOCLAW_ATTACHED_PROVIDER_API_KEY=nemoclaw-openshell-provider", + ); expect(envFileLines).toContain("unset ALL_PROXY all_proxy OPENAI_PROXY"); expect( outputLines.filter((line) => /^(?:RUNTIME|SOURCED)_(?:NO_PROXY|no_proxy)=/.test(line)), diff --git a/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts b/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts index 4add8cf0dba..6bcf4261d8c 100644 --- a/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-provider-label.test.ts @@ -68,6 +68,7 @@ describe("LangChain Deep Agents Code managed provider label", () => { expect(config).toContain(`default = "openai:${model}"`); expect(config).toContain("[models.providers.openai]"); expect(config).toContain('base_url = "https://integrate.api.nvidia.com/v1"'); + expect(config).toContain('api_key_env = "NEMOCLAW_ATTACHED_PROVIDER_API_KEY"'); expect(config).toContain("upstream provider: nvidia-prod"); const managedBaseUrlPath = path.join(tempDir, "managed-inference-base-url"); diff --git a/test/e2e/support/native-nvidia-target-ownership.test.ts b/test/e2e/support/native-nvidia-target-ownership.test.ts index 6220cae6427..fa6c7ee29d8 100644 --- a/test/e2e/support/native-nvidia-target-ownership.test.ts +++ b/test/e2e/support/native-nvidia-target-ownership.test.ts @@ -7,6 +7,7 @@ import { catalogueTargetsForChangedFiles } from "../../../tools/e2e/target-catal describe("native NVIDIA target ownership", () => { it.each([ + "src/lib/actions/inference-set.ts", "src/lib/inference/native-nvidia/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", ])("selects both provider-switch targets when %s changes", (changedFile) => { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 0d66ffdfe84..c4fb5ed4c86 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -907,6 +907,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ runnerComparison: true, shard: "native-nvidia", owningPaths: [ + "src/lib/actions/inference-set.ts", "src/lib/inference/native-nvidia/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", ], From d702f7869553a83c6dd9d11c070ec25ff0594f38 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 03:20:28 -0700 Subject: [PATCH 032/133] fix: require native provider ownership evidence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../recover-rebuild-sandboxes.mdx | 5 ++- src/lib/inference/native-nvidia.test.ts | 21 ++++++++++++ src/lib/inference/native-nvidia/index.ts | 7 +++- src/lib/onboard/setup-inference.test.ts | 34 +++++++++++-------- 4 files changed, 51 insertions(+), 16 deletions(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 3a28a6a0eef..f4f04153e01 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -188,7 +188,10 @@ A successful complete preflight for `$$nemoclaw launch ` can publi During the lease, `launch` still verifies the owning OpenShell gateway, exact live sandbox identity, registry and agent configuration, effective policy, inference route, required forwards, and semantic runtime health. -Configured inference must return HTTP 2xx from the semantic `inference.local` probe, which is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. +Configured inference must return HTTP 2xx from the semantic probe for the selected provider path. +Shared-route providers use `inference.local`. +NVIDIA Endpoints uses its sandbox-attached provider at `integrate.api.nvidia.com`. +This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. Every configured route must serve a valid response to a bounded request for the recorded model before NemoClaw accepts or publishes launch readiness. diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index 2a33d02937c..0b248f47b2d 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -185,6 +185,21 @@ describe("native NVIDIA OpenShell provider", () => { expect(updateProvider).not.toHaveBeenCalled(); }); + it("refuses an existing provider without an ownership receipt before mutation (#12558)", async () => { + const updateProvider = vi.fn(); + const attachProvider = vi.fn(); + + await expect( + ensureNativeNvidiaProvider({ + adapter: adapter({ updateProvider, attachProvider }), + target, + credentialValue: "opaque-test-secret", + }), + ).rejects.toThrow(/already exists without a matching NemoClaw ownership receipt/u); + expect(updateProvider).not.toHaveBeenCalled(); + expect(attachProvider).not.toHaveBeenCalled(); + }); + it("does not record a receipt after an ambiguous credential update (#12558)", async () => { const getProvider = vi.fn(async () => ({ ok: true, @@ -200,6 +215,12 @@ describe("native NVIDIA OpenShell provider", () => { adapter: adapter({ getProvider, updateProvider }), target, credentialValue: "replacement-secret", + expected: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + }, }), ).rejects.toThrow(/did not confirm.*credential update.*No provider receipt was recorded/u); expect(updateProvider).toHaveBeenCalledOnce(); diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 5ef187d6bbe..4fdcb71a6f6 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -137,7 +137,12 @@ export async function ensureNativeNvidiaProvider(input: { const before = await inspectNativeProvider(adapter, target); if (before) { const receipt = attachmentFromMetadata(before); - if (input.expected && input.expected.providerId !== receipt.providerId) { + if (!input.expected) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' already exists without a matching NemoClaw ownership receipt. No provider was changed.`, + ); + } + if (input.expected.providerId !== receipt.providerId) { throw new NativeNvidiaProviderError( `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, ); diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index a619040ed0d..535f0a05dd9 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -185,23 +185,29 @@ describe("createProviderReviewDeps", () => { describe("native NVIDIA onboarding", () => { it("reserves the logical route with an attached-provider receipt and no shared route mutation", async () => { const importProviderProfile = vi.fn(async () => ({ ok: true as const })); - const getProvider = vi.fn(async () => ({ - ok: true as const, - value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { id: "provider-id", resourceVersion: 4 }, - }, - })); - const updateProvider = vi.fn(async () => ({ + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 4 }, + }, + }); + const createProvider = vi.fn(async () => ({ ok: true, })); const providerAdapter = { importProviderProfile, getProvider, - updateProvider, + createProvider, } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); const updateSandbox = vi.fn(() => true); @@ -256,10 +262,10 @@ describe("native NVIDIA onboarding", () => { target: { kind: "named", gatewayName: "onboarding-gateway" }, providerName: "nemoclaw-nvidia-prod-v1", }); - expect(updateProvider).toHaveBeenCalledWith( + expect(createProvider).toHaveBeenCalledWith( expect.objectContaining({ target: { kind: "named", gatewayName: "onboarding-gateway" }, - providerName: "nemoclaw-nvidia-prod-v1", + name: "nemoclaw-nvidia-prod-v1", credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "host-only-nvidia-credential" }], config: [], }), From ea0cd80f57401f225235cf3b128f4610fbcdd231 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 03:48:42 -0700 Subject: [PATCH 033/133] test: preserve native provider receipt on recreate Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ...rd-build-recreate-credential-reuse.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts index 911c32bb67f..53a96e97167 100644 --- a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts @@ -30,6 +30,9 @@ describe("onboard build recreate credential reuse (#5441)", () => { const scriptPath = path.join(tmpDir, "build-recreate.cjs"); const curlLogPath = path.join(tmpDir, "curl-probes.log"); const onboardPath = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "onboard.ts")); + const registryPath = JSON.stringify( + path.join(REPO_ROOT, "src", "lib", "state", "registry.ts"), + ); fs.mkdirSync(fakeBin, { recursive: true }); fs.mkdirSync(home, { recursive: true }); @@ -112,6 +115,22 @@ delete process.env.NEMOCLAW_PROVIDER_KEY; delete process.env.NEMOCLAW_PROVIDER; const { setupNim, setupInference } = require(${onboardPath}); +const registry = require(${registryPath}); + +// Recreate preserves the registry receipt that proves this named native +// provider belongs to the selected sandbox. Gateway metadata alone is not +// ownership evidence because another sandbox can use the same provider name. +registry.registerSandbox({ + name: "rg-test-noninter", + provider: "nvidia-prod", + model: "nvidia/llama-3.3-nemotron-super-49b-v1", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }, +}); (async () => { const result = await setupNim(null, "rg-test-noninter", null); From 1b7b2899949501bcff3a3e2124a8cb5f4f69ca5f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:38:35 -0700 Subject: [PATCH 034/133] fix: address native inference review blockers Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/verify-inference-route.mdx | 24 +++-- src/lib/onboard/setup-inference.test.ts | 89 +++++++++++++++++++ src/lib/onboard/setup-inference.ts | 30 ++++++- ...inference-switch-workflow-boundary.test.ts | 18 ++++ tools/e2e/target-catalogue.mts | 28 ++++++ 5 files changed, 180 insertions(+), 9 deletions(-) diff --git a/docs/inference/verify-inference-route.mdx b/docs/inference/verify-inference-route.mdx index 5882de2140a..3676d330161 100644 --- a/docs/inference/verify-inference-route.mdx +++ b/docs/inference/verify-inference-route.mdx @@ -3,13 +3,13 @@ # SPDX-License-Identifier: Apache-2.0 title: "Verify the Sandbox Inference Route" sidebar-title: "Verify the Inference Route" -description: "Verify that a NemoClaw sandbox can reach its configured model through the OpenShell inference route." -description-agent: "Verifies the in-sandbox inference path. Use when checking that inference.local, proxy authentication, and the selected backend work together." -keywords: ["verify inference.local", "nemoclaw inference route", "sandbox inference health"] +description: "Verify that a NemoClaw sandbox can reach its configured model through its selected inference provider." +description-agent: "Verifies the in-sandbox inference path for native NVIDIA providers and shared inference routes." +keywords: ["verify inference provider", "nemoclaw inference route", "sandbox inference health"] content: type: "how_to" --- -Verify inference through the same `inference.local` path that the agent uses inside the sandbox. +Verify inference through the same provider path that the agent uses inside the sandbox. Reading the active route confirms configuration, but it does not authenticate a model request. ## Confirm the Configured Route @@ -20,7 +20,8 @@ Read the live gateway route first. $$nemoclaw inference get ``` -Confirm that the provider and model match the route you intended to configure. +Confirm that the provider, model, and endpoint match the route you intended to configure. +NVIDIA Endpoints reports `https://integrate.api.nvidia.com/v1` instead of `inference.local`. ## Check Sandbox Inference Health @@ -30,7 +31,11 @@ Run the named sandbox status command. $$nemoclaw status ``` -The `Inference` row first checks the sandbox's `inference.local` path. +For NVIDIA Endpoints, the `Inference` row verifies the recorded sandbox attachment. +It then sends a native Chat Completions request to `https://integrate.api.nvidia.com/v1`. +It does not probe `https://inference.local/v1/models` for this provider. + +For shared-route providers, the `Inference` row first checks the sandbox's `inference.local` path. When that route responds, `status` sends an inference request through the same path. When the live provider matches the recorded provider, `status` validates the result against the recorded API family, even when only the model differs. When the live provider differs, `status` does not carry the recorded API family to the live provider. @@ -68,7 +73,10 @@ For those routes, continue to the final route check, then use the status command ## Understand Final Route Checks -When onboarding prints a dashboard summary, it first requests `https://inference.local/v1/models` from inside the sandbox after policy and process recovery. +For NVIDIA Endpoints, onboarding verifies the sandbox-attached provider through the native endpoint. +It does not request the shared `inference.local` models route. + +For shared-route providers, onboarding first requests `https://inference.local/v1/models` from inside the sandbox after policy and process recovery. Each attempt allows 2 seconds for the route to return an HTTP response. @@ -86,7 +94,7 @@ Use the status command and a short agent request after onboarding to verify ongo ## Send a Short Agent Request Connect to the sandbox and send a short request before starting long-running work. -A successful response proves that the configured model can serve an agent request through the OpenShell route. +A successful response proves that the configured model can serve an agent request through the selected provider path. If the status route is reachable but a tool action returns JSON as normal assistant text, troubleshoot structured tool calling instead of the network route. diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 535f0a05dd9..3cb93ed8500 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -290,6 +290,95 @@ describe("native NVIDIA onboarding", () => { ); }); + it("reuses a gateway-owned provider for a fresh second sandbox", async () => { + const importProviderProfile = vi.fn(async () => ({ ok: true as const })); + const getProvider = vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 4 }, + }, + })); + const createProvider = vi.fn(); + const updateProvider = vi.fn(); + const updateSandbox = vi.fn(() => true); + const setupInference = createSetupInference({ + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + step: vi.fn(), + getGatewayName: () => "onboarding-gateway", + runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + updateSandbox, + getSandbox: () => null, + listSandboxes: () => ({ + defaultSandbox: "first", + sandboxes: [ + { + name: "first", + gatewayName: "onboarding-gateway", + provider: "nvidia-prod", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }, + }, + ], + }), + upsertProvider: vi.fn(async () => ({ ok: true })), + verifyInferenceRoute: vi.fn(), + verifyOnboardInferenceSmoke: vi.fn(async () => undefined), + isNonInteractive: () => true, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + providerAdapter: { + importProviderProfile, + getProvider, + createProvider, + updateProvider, + } as unknown as OpenShellProviderAdapter, + hydrateCredentialEnv: vi.fn(() => null), + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }), + } as unknown as SetupInferenceDeps); + + await expect( + setupInference( + "second", + "nvidia/nemotron-3-super-120b-a12b", + "nvidia-prod", + "https://integrate.api.nvidia.com/v1", + "NVIDIA_INFERENCE_API_KEY", + null, + [], + { + revalidateSandboxIdentity: () => undefined, + reuseGatewayCredentialWithoutLocalKey: true, + }, + ), + ).resolves.toEqual({ ok: true }); + + expect(createProvider).not.toHaveBeenCalled(); + expect(updateProvider).not.toHaveBeenCalled(); + expect(updateSandbox).toHaveBeenCalledWith( + "second", + expect.objectContaining({ + nativeNvidiaProviderAttachment: expect.objectContaining({ providerId: "provider-id" }), + }), + ); + }); + it("requires recreation instead of recording a receipt for a legacy NVIDIA sandbox", async () => { const providerAdapter = { importProviderProfile: vi.fn(), diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 5c08f96ddd1..03a4efdf914 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -631,6 +631,29 @@ function releaseSupersededOllamaModel( if (authorityRefusal) throw authorityRefusal; } +function resolveGatewayNativeNvidiaProviderAuthority( + deps: SetupInferenceDeps, + gatewayName: string, + recordedAttachment: NativeNvidiaProviderAttachment | null | undefined, +): NativeNvidiaProviderAttachment | undefined { + if (recordedAttachment) return recordedAttachment; + + const authorities = new Map(); + for (const sandbox of deps.listSandboxes?.().sandboxes ?? []) { + if (sandbox.gatewayName !== gatewayName || !isNativeNvidiaProvider(sandbox.provider)) continue; + const attachment = normalizeNativeNvidiaProviderAttachment( + sandbox.nativeNvidiaProviderAttachment, + ); + if (attachment) authorities.set(attachment.providerId, attachment); + } + if (authorities.size > 1) { + throw new Error( + `Gateway '${gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, + ); + } + return authorities.values().next().value; +} + export function createSetupInference( defaults: SetupInferenceDeps, overrides: Partial = {}, @@ -980,12 +1003,17 @@ export function createSetupInference( `Sandbox '${sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before using native NVIDIA inference; NemoClaw does not migrate existing beta sandboxes automatically.`, ); } + const providerAuthority = resolveGatewayNativeNvidiaProviderAuthority( + deps, + gatewayName, + recordedAttachment, + ); nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ adapter: providerAdapter, target: { kind: "named", gatewayName }, credentialValue, reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, - ...(recordedAttachment ? { expected: recordedAttachment } : {}), + ...(providerAuthority ? { expected: providerAuthority } : {}), }); return null; } diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index ca222fb3332..e594c19eb89 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -47,4 +47,22 @@ describe("inference-switch catalogue boundary", () => { expect(target.environment).not.toHaveProperty("NEMOCLAW_E2E_USE_HOSTED_INFERENCE"); }, ); + + it("keeps a canonical compatible Anthropic switch target", () => { + expect(catalogueTarget("openclaw-compatible-anthropic-inference-switch")).toMatchObject({ + targetId: "openclaw-inference-switch", + profile: "standard", + testFile: "test/e2e/live/openclaw-inference-switch.test.ts", + runnerKey: "", + shard: "anthropic", + environment: { + NEMOCLAW_AGENT: "openclaw", + NEMOCLAW_E2E_SHARD: "anthropic", + NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", + NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", + NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", + NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + }, + }); + }); }); diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index c4fb5ed4c86..e0935b9e928 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1195,6 +1195,34 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ OPENSHELL_GATEWAY: "nemoclaw", }, }), + managedRuntimeTarget("openclaw-compatible-anthropic-inference-switch", { + targetId: "openclaw-inference-switch", + displayName: "Inference: OpenClaw switches to an Anthropic-compatible endpoint", + agentRuntime: "openclaw", + environmentOrInferenceEndpoint: "Ubuntu; Anthropic-compatible inference fixture", + profile: "standard", + testFile: "test/e2e/live/openclaw-inference-switch.test.ts", + timeoutMinutes: 90, + installMode: "none", + restoreCli: true, + exposeCliBin: true, + shard: "anthropic", + owningPaths: [ + "src/lib/actions/inference-set.ts", + "test/e2e/live/openclaw-inference-switch-helpers.ts", + ], + environment: { + ...nonInteractive, + NEMOCLAW_AGENT: "openclaw", + NEMOCLAW_E2E_SHARD: "anthropic", + NEMOCLAW_SANDBOX_NAME: "e2e-oc-compatible-anthropic-switch", + NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", + NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", + NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", + NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + OPENSHELL_GATEWAY: "nemoclaw", + }, + }), managedRuntimeTarget("openclaw-slack-pairing", { displayName: "Messaging: shares OpenClaw Slack pairing approval", agentRuntime: "openclaw", From 6804abff2d251080b7ccdcb4e788272bc0c03832 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 05:03:33 -0700 Subject: [PATCH 035/133] test: update inference switch workflow plan Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/support/workflow-plan.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 24d61d04547..d6a1b766a11 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -99,7 +99,7 @@ describe("E2E workflow plan", () => { }), ]); expect(plan.hermesSelected).toBe(true); - expect(plan.coverageMatrix).toHaveLength(77); + expect(plan.coverageMatrix).toHaveLength(78); expect(selectedWorkflowJobs(plan)).toEqual([ "catalogue-github-read", "catalogue-nvidia-api", @@ -158,7 +158,7 @@ describe("E2E workflow plan", () => { "ubuntu-repo-cloud-openclaw", ]); expect(plan.testMatrix).toEqual([]); - expect(catalogueIds).toHaveLength(46); + expect(catalogueIds).toHaveLength(47); expect(catalogueIds).not.toEqual( expect.arrayContaining([ "bootstrap-install-smoke", @@ -336,18 +336,18 @@ describe("E2E workflow plan", () => { "llama-cpp-generic-gpu-default-docker", "messaging-compatible-endpoint-default-docker", "messaging-compatible-endpoint-default-podman", + "openclaw-compatible-anthropic-inference-switch-anthropic-docker", + "openclaw-compatible-anthropic-inference-switch-anthropic-podman", "openclaw-inference-switch-default-docker", "openclaw-inference-switch-default-podman", "openclaw-skill-cli-default-docker", "openclaw-skill-cli-default-podman", ]); }); - it("emits required fields and catalogue workflow jobs for migrated targets", () => { const plan = buildE2eWorkflowPlan({ jobs: "hermes-slack,network-policy,openclaw-inference-switch,sandbox-operations", }); - expect(plan.catalogueMatrices["nvidia-inference"]).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -379,13 +379,13 @@ describe("E2E workflow plan", () => { expect(selectedWorkflowJobs(plan)).toEqual([ "catalogue-nvidia-api", "catalogue-nvidia-inference", + "catalogue-standard", ]); expect(catalogueTarget("network-policy").selector).toBe("^network-policy:"); const migratedTargetIds = ["hermes-slack", "openclaw-inference-switch", "sandbox-operations"]; const retainedMigratedJobs = readFreeStandingJobsInventory().allowedJobs.filter((id) => migratedTargetIds.includes(id), ); - expect(retainedMigratedJobs).toEqual([]); }); From 0b51085c752e797d221496f1f7762935f98063ef Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 06:03:01 -0700 Subject: [PATCH 036/133] fix: address native inference review blockers --- docs/reference/commands.mdx | 12 ++++-- .../inference-set-openclaw-run.test.ts | 41 +++++++++++++++++++ src/lib/actions/inference-set.ts | 14 +++++-- src/lib/inference/config.ts | 1 + src/lib/inference/native-nvidia/index.ts | 30 ++++++++++++++ src/lib/onboard/setup-inference.ts | 30 ++------------ ...inference-switch-workflow-boundary.test.ts | 18 +++++++- tools/e2e/target-catalogue.mts | 27 ++++++++++++ 8 files changed, 140 insertions(+), 33 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 2fe78d9c0a3..4f3c873961c 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1122,7 +1122,10 @@ During that lease, another `launch` still verifies these conditions: -- The recorded inference selection matches the live route, and `inference.local` returns HTTP 2xx from its semantic probe when inference is configured. This is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. +- The recorded inference selection matches its provider path, and that path returns HTTP 2xx from its semantic probe when inference is configured. + Shared-route providers use `inference.local`. + NVIDIA Endpoints verifies the recorded sandbox-attached provider and sends the request to `https://integrate.api.nvidia.com/v1`. + This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. @@ -1197,9 +1200,12 @@ Before reading or changing the live OpenShell gateway inference route, `connect` When the live route differs and the metadata is compatible, `connect` warns and re-points the route to the target sandbox's recorded provider and model. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for provider-global identity, route drift, and hard-error recovery. Use `$$nemoclaw inference set --provider --model ` to make an intentional compatible route change outside the connect flow. -Before it opens SSH, `connect` probes `https://inference.local/v1/models` from inside the sandbox with the selected agent's trusted CA and proxy context. +Before it opens SSH, `connect` probes the selected provider path from inside the sandbox with the selected agent's trusted CA and proxy context. +Shared-route providers use `https://inference.local/v1/models`. +NVIDIA Endpoints verifies its recorded sandbox-attached provider and probes `https://integrate.api.nvidia.com/v1/models`. HTTP `200` through `499` confirms that the route is reachable. -When the probe returns a recognized broken result, `connect` attempts DNS or route repair and verifies the route again. +For a shared-route provider, a recognized broken result lets `connect` attempt DNS or route repair and verify the route again. +For NVIDIA Endpoints, `connect` does not inspect or change the unrelated shared route. When the initial probe cannot return a trusted result, `connect` fails closed before health-driven repair and before opening SSH. It prints a bounded, redacted last-probe detail and points you to `$$nemoclaw doctor`. diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index ff0e09c3418..a210c09542f 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -27,6 +27,47 @@ describe("runInferenceSet OpenClaw routing", () => { expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); }); + it("reuses a same-gateway native NVIDIA provider authority from a peer sandbox", async () => { + const peerAttachment = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const deps = createDeps({ + config: {}, + entries: [ + { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "gpt-5.4", + }, + { + name: "beta", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/peer-model", + nativeNvidiaProviderAttachment: peerAttachment, + }, + ], + defaultSandbox: "alpha", + resolveCredentialValue: () => "", + }); + + await runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, + deps, + ); + + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ nativeNvidiaProviderAttachment: peerAttachment }), + ); + }); + it("detaches native NVIDIA access only after another provider is healthy", async () => { let attached = true; const detachProvider = vi.fn(async () => { diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 8944290e513..6ac9940ae5c 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -19,6 +19,7 @@ import { isNativeNvidiaProvider, NVIDIA_HOSTED_CREDENTIAL_ENV, normalizeNativeNvidiaProviderAttachment, + resolveGatewayNativeNvidiaProviderAuthority, resolveAgentInferenceApi, type NativeNvidiaProviderAttachment, type SandboxInferenceConfig, @@ -948,7 +949,7 @@ function assertNativeNvidiaMigrationReady(input: { async function prepareNativeNvidiaSelection(input: { provider: string; - previousAttachment?: NativeNvidiaProviderAttachment; + expectedAttachment?: NativeNvidiaProviderAttachment; gatewayName: string; sandboxName: string; deps: InferenceSetDeps; @@ -962,7 +963,7 @@ async function prepareNativeNvidiaSelection(input: { adapter: input.deps.providerAdapter, target, credentialValue: input.deps.resolveCredentialValue(NVIDIA_HOSTED_CREDENTIAL_ENV) || null, - ...(input.previousAttachment ? { expected: input.previousAttachment } : {}), + ...(input.expectedAttachment ? { expected: input.expectedAttachment } : {}), }); const attached = await ensureNativeNvidiaProviderAttached({ adapter: input.deps.providerAdapter, @@ -1513,6 +1514,13 @@ async function runInferenceSetWithoutHostLock( previousAttachment: previousNativeNvidiaAttachment, sandboxName, }); + const nativeNvidiaProviderAuthority = selectingNativeNvidia + ? resolveGatewayNativeNvidiaProviderAuthority({ + gatewayName: preparedRoute.gatewayName, + recordedAttachment: previousNativeNvidiaAttachment, + sandboxes: routeSandboxes, + }) + : undefined; const rollbackRoute = preMutationRoute.state === "configured" ? preMutationRoute.route : null; // Capture before registry writes: a retry already has the new route, while // the sandbox config can still carry the previous endpoint's context window. @@ -1588,7 +1596,7 @@ async function runInferenceSetWithoutHostLock( try { const nativeNvidiaSelection = await prepareNativeNvidiaSelection({ provider, - previousAttachment: previousNativeNvidiaAttachment, + expectedAttachment: nativeNvidiaProviderAuthority, gatewayName: preparedRoute.gatewayName, sandboxName, deps, diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 6d23854fe75..d4e9e370405 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -30,6 +30,7 @@ export { NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_ENDPOINT, normalizeNativeNvidiaProviderAttachment, + resolveGatewayNativeNvidiaProviderAuthority, } from "./native-nvidia"; export type { NativeNvidiaProviderAttachment } from "./native-nvidia"; diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 4fdcb71a6f6..58f53a03ada 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -15,6 +15,7 @@ import { NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, + normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, } from "./contract"; @@ -48,6 +49,35 @@ export function isNativeNvidiaProvider(provider: string | null | undefined): boo return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; } +export function resolveGatewayNativeNvidiaProviderAuthority(input: { + gatewayName: string; + recordedAttachment?: NativeNvidiaProviderAttachment | null; + sandboxes: ReadonlyArray<{ + gatewayName?: string | null; + provider?: string | null; + nativeNvidiaProviderAttachment?: unknown; + }>; +}): NativeNvidiaProviderAttachment | undefined { + if (input.recordedAttachment) return input.recordedAttachment; + + const authorities = new Map(); + for (const sandbox of input.sandboxes) { + if (sandbox.gatewayName !== input.gatewayName || !isNativeNvidiaProvider(sandbox.provider)) { + continue; + } + const attachment = normalizeNativeNvidiaProviderAttachment( + sandbox.nativeNvidiaProviderAttachment, + ); + if (attachment) authorities.set(attachment.providerId, attachment); + } + if (authorities.size > 1) { + throw new NativeNvidiaProviderError( + `Gateway '${input.gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, + ); + } + return authorities.values().next().value; +} + export function nativeInferenceProviderForSandbox( provider: string | null | undefined, ): string | null { diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 03a4efdf914..7f003498713 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -25,6 +25,7 @@ import { isNativeNvidiaProvider, NVIDIA_HOSTED_CREDENTIAL_ENV, normalizeNativeNvidiaProviderAttachment, + resolveGatewayNativeNvidiaProviderAuthority, type NativeNvidiaProviderAttachment, } from "../inference/native-nvidia"; import { @@ -631,29 +632,6 @@ function releaseSupersededOllamaModel( if (authorityRefusal) throw authorityRefusal; } -function resolveGatewayNativeNvidiaProviderAuthority( - deps: SetupInferenceDeps, - gatewayName: string, - recordedAttachment: NativeNvidiaProviderAttachment | null | undefined, -): NativeNvidiaProviderAttachment | undefined { - if (recordedAttachment) return recordedAttachment; - - const authorities = new Map(); - for (const sandbox of deps.listSandboxes?.().sandboxes ?? []) { - if (sandbox.gatewayName !== gatewayName || !isNativeNvidiaProvider(sandbox.provider)) continue; - const attachment = normalizeNativeNvidiaProviderAttachment( - sandbox.nativeNvidiaProviderAttachment, - ); - if (attachment) authorities.set(attachment.providerId, attachment); - } - if (authorities.size > 1) { - throw new Error( - `Gateway '${gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, - ); - } - return authorities.values().next().value; -} - export function createSetupInference( defaults: SetupInferenceDeps, overrides: Partial = {}, @@ -1003,11 +981,11 @@ export function createSetupInference( `Sandbox '${sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before using native NVIDIA inference; NemoClaw does not migrate existing beta sandboxes automatically.`, ); } - const providerAuthority = resolveGatewayNativeNvidiaProviderAuthority( - deps, + const providerAuthority = resolveGatewayNativeNvidiaProviderAuthority({ gatewayName, recordedAttachment, - ); + sandboxes: deps.listSandboxes?.().sandboxes ?? [], + }); nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ adapter: providerAdapter, target: { kind: "named", gatewayName }, diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index e594c19eb89..0bdd99864b2 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -48,7 +48,7 @@ describe("inference-switch catalogue boundary", () => { }, ); - it("keeps a canonical compatible Anthropic switch target", () => { + it("keeps canonical compatible Anthropic switch targets for both agents", () => { expect(catalogueTarget("openclaw-compatible-anthropic-inference-switch")).toMatchObject({ targetId: "openclaw-inference-switch", profile: "standard", @@ -64,5 +64,21 @@ describe("inference-switch catalogue boundary", () => { NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", }, }); + expect(catalogueTarget("hermes-compatible-anthropic-inference-switch")).toMatchObject({ + targetId: "hermes-inference-switch", + profile: "standard", + testFile: "test/e2e/live/hermes-inference-switch.test.ts", + runnerKey: "hermes-inference-switch", + hostPreparation: "hermes-swap", + runnerComparison: true, + shard: "anthropic", + environment: { + NEMOCLAW_AGENT: "hermes", + NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", + NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", + NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", + NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + }, + }); }); }); diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index e0935b9e928..0c6dbdea22d 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -921,6 +921,33 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ OPENSHELL_GATEWAY: "nemoclaw", }, }), + managedRuntimeTarget("hermes-compatible-anthropic-inference-switch", { + targetId: "hermes-inference-switch", + displayName: "Inference: Hermes switches to an Anthropic-compatible endpoint", + agentRuntime: "hermes", + environmentOrInferenceEndpoint: "Ubuntu; Anthropic-compatible inference fixture", + profile: "standard", + testFile: "test/e2e/live/hermes-inference-switch.test.ts", + timeoutMinutes: 55, + installMode: "authenticated", + installNonInteractive: true, + restoreCli: true, + exposeCliBin: true, + runnerKey: "hermes-inference-switch", + hostPreparation: "hermes-swap", + runnerComparison: true, + shard: "anthropic", + environment: { + ...nonInteractive, + NEMOCLAW_AGENT: "hermes", + NEMOCLAW_SANDBOX_NAME: "e2e-hm-compatible-anthropic-switch", + NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", + NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", + NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", + NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + OPENSHELL_GATEWAY: "nemoclaw", + }, + }), managedRuntimeTarget("hermes-slack", { displayName: "Messaging: isolates Hermes Slack credentials and reaches Slack APIs", From 4d7533cd7cb32248db0e32b6d9d40032fc97adc1 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 07:26:26 -0700 Subject: [PATCH 037/133] test: update restored Hermes workflow counts --- test/e2e/support/workflow-plan.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index d6a1b766a11..95c20c32263 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -99,7 +99,7 @@ describe("E2E workflow plan", () => { }), ]); expect(plan.hermesSelected).toBe(true); - expect(plan.coverageMatrix).toHaveLength(78); + expect(plan.coverageMatrix).toHaveLength(79); expect(selectedWorkflowJobs(plan)).toEqual([ "catalogue-github-read", "catalogue-nvidia-api", @@ -158,7 +158,7 @@ describe("E2E workflow plan", () => { "ubuntu-repo-cloud-openclaw", ]); expect(plan.testMatrix).toEqual([]); - expect(catalogueIds).toHaveLength(47); + expect(catalogueIds).toHaveLength(48); expect(catalogueIds).not.toEqual( expect.arrayContaining([ "bootstrap-install-smoke", From b740bde9b054c0b2ccf614a6a455bcc748cbddf6 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 09:10:42 -0700 Subject: [PATCH 038/133] fix(inference): retain native NVIDIA provider authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../inference-set-openclaw-run.test.ts | 109 +++++++++++++++++- src/lib/actions/inference-set.ts | 28 ++++- src/lib/inference/native-nvidia/index.ts | 26 ++++- ...egistry-native-provider-attachment.test.ts | 4 + src/lib/state/registry.ts | 37 +++++- src/lib/state/registry/types.ts | 2 + 6 files changed, 193 insertions(+), 13 deletions(-) diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index a210c09542f..a7167f14718 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -128,8 +128,115 @@ describe("runInferenceSet OpenClaw routing", () => { ); expect(deps.calls.updateSandbox).toHaveBeenCalledWith( "alpha", - expect.objectContaining({ nativeNvidiaProviderAttachment: undefined }), + expect.objectContaining({ + nativeNvidiaProviderAttachment: undefined, + nativeNvidiaProviderAuthority: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }), + ); + }); + + it("verifies retained NVIDIA authority across a single-sandbox round trip", async () => { + const attachment = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const entry = { + name: "alpha", + agent: "openclaw" as const, + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeNvidiaProviderAttachment: attachment, + nativeNvidiaProviderAuthority: attachment, + }; + const updateSandbox = vi.fn((name: string, updates: Record) => { + expect(name).toBe(entry.name); + Object.assign(entry, updates); + return true; + }); + const deps = createDeps({ + config: { + agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, + models: { providers: {} }, + }, + entry, + updateSandbox, + resolveCredentialValue: () => "", + }); + + await runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps); + + expect(entry).toMatchObject({ + provider: "openai-api", + nativeNvidiaProviderAuthority: attachment, + }); + expect(entry.nativeNvidiaProviderAttachment).toBeUndefined(); + + await runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, + deps, ); + + expect(entry).toMatchObject({ + provider: "nvidia-prod", + nativeNvidiaProviderAttachment: attachment, + nativeNvidiaProviderAuthority: attachment, + }); + }); + + it("rejects a replaced NVIDIA provider before restoring detached access", async () => { + const attachProvider = vi.fn(); + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true })), + getProvider: vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { + id: "replacement-provider-id", + resourceVersion: 1, + }, + }, + })), + attachProvider, + } as unknown as OpenShellProviderAdapter; + const deps = createDeps({ + config: { + agents: { defaults: { model: { primary: "inference/gpt-5.4" } } }, + models: { providers: {} }, + }, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "gpt-5.4", + nativeNvidiaProviderAuthority: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "recorded-provider-id", + }, + }, + providerAdapter, + resolveCredentialValue: () => "", + }); + + await expect( + runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps), + ).rejects.toThrow(/changed identity.*No provider was changed/u); + expect(attachProvider).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); it("does not publish a non-native route when native NVIDIA detach fails", async () => { diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 6ac9940ae5c..6c233eae2ab 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1016,10 +1016,18 @@ async function detachPreviousNativeNvidiaBeforePublish(input: { return true; } -function nativeNvidiaDepartureRegistryFields( - detached: boolean, -): Pick | Record { - return detached ? { nativeNvidiaProviderAttachment: undefined } : {}; +function nativeNvidiaDepartureRegistryFields(input: { + detached: boolean; + authority?: NativeNvidiaProviderAttachment; +}): + | Pick + | Record { + return input.detached + ? { + nativeNvidiaProviderAttachment: undefined, + nativeNvidiaProviderAuthority: input.authority, + } + : {}; } async function restorePreviousNativeNvidiaAfterFailedPublish(input: { @@ -1508,6 +1516,9 @@ async function runInferenceSetWithoutHostLock( const previousNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( entry.nativeNvidiaProviderAttachment, ); + const previousNativeNvidiaAuthority = normalizeNativeNvidiaProviderAttachment( + entry.nativeNvidiaProviderAuthority, + ); assertNativeNvidiaMigrationReady({ provider, previousProvider, @@ -1518,6 +1529,7 @@ async function runInferenceSetWithoutHostLock( ? resolveGatewayNativeNvidiaProviderAuthority({ gatewayName: preparedRoute.gatewayName, recordedAttachment: previousNativeNvidiaAttachment, + recordedAuthority: previousNativeNvidiaAuthority, sandboxes: routeSandboxes, }) : undefined; @@ -1780,7 +1792,13 @@ async function runInferenceSetWithoutHostLock( }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), - ...nativeNvidiaDepartureRegistryFields(previousNativeNvidiaDetached), + ...(nativeNvidiaProviderAttachment + ? { nativeNvidiaProviderAuthority: nativeNvidiaProviderAttachment } + : {}), + ...nativeNvidiaDepartureRegistryFields({ + detached: previousNativeNvidiaDetached, + authority: previousNativeNvidiaAttachment ?? previousNativeNvidiaAuthority, + }), }); if ( !deps.updateSandbox( diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 58f53a03ada..92151e4d5d9 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -52,23 +52,37 @@ export function isNativeNvidiaProvider(provider: string | null | undefined): boo export function resolveGatewayNativeNvidiaProviderAuthority(input: { gatewayName: string; recordedAttachment?: NativeNvidiaProviderAttachment | null; + recordedAuthority?: NativeNvidiaProviderAttachment | null; sandboxes: ReadonlyArray<{ gatewayName?: string | null; provider?: string | null; nativeNvidiaProviderAttachment?: unknown; + nativeNvidiaProviderAuthority?: unknown; }>; }): NativeNvidiaProviderAttachment | undefined { + if (input.recordedAttachment && input.recordedAuthority) { + if (input.recordedAttachment.providerId !== input.recordedAuthority.providerId) { + throw new NativeNvidiaProviderError( + `Gateway '${input.gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, + ); + } + return input.recordedAttachment; + } if (input.recordedAttachment) return input.recordedAttachment; + if (input.recordedAuthority) return input.recordedAuthority; const authorities = new Map(); for (const sandbox of input.sandboxes) { - if (sandbox.gatewayName !== input.gatewayName || !isNativeNvidiaProvider(sandbox.provider)) { - continue; - } - const attachment = normalizeNativeNvidiaProviderAttachment( - sandbox.nativeNvidiaProviderAttachment, + if (sandbox.gatewayName !== input.gatewayName) continue; + const authority = normalizeNativeNvidiaProviderAttachment( + sandbox.nativeNvidiaProviderAuthority, ); - if (attachment) authorities.set(attachment.providerId, attachment); + const attachment = isNativeNvidiaProvider(sandbox.provider) + ? normalizeNativeNvidiaProviderAttachment(sandbox.nativeNvidiaProviderAttachment) + : undefined; + for (const receipt of [authority, attachment]) { + if (receipt) authorities.set(receipt.providerId, receipt); + } } if (authorities.size > 1) { throw new NativeNvidiaProviderError( diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index 30060e64af7..fa9d99c273f 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -25,6 +25,9 @@ it("clears a stale native NVIDIA attachment when reserving a shared route", asyn gatewayName: "nemoclaw", gatewayPort: 8080, }); + expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAuthority).toMatchObject({ + providerId: "provider-id", + }); registry.reserveSandboxInferenceRoute("alpha", { provider: "anthropic-prod", @@ -36,6 +39,7 @@ it("clears a stale native NVIDIA attachment when reserving a shared route", asyn }); expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAttachment).toBeUndefined(); + expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAuthority).toBeUndefined(); } finally { await fs.rm(home, { recursive: true, force: true }); vi.unstubAllEnvs(); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 593bd1137e4..65ab54f6bbc 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -488,6 +488,12 @@ export function registerSandbox( "Cannot register a sandbox with an invalid native NVIDIA provider attachment", ); } + const nativeNvidiaProviderAuthority = normalizeNativeNvidiaProviderAttachment( + entry.nativeNvidiaProviderAuthority ?? nativeNvidiaProviderAttachment, + ); + if (entry.nativeNvidiaProviderAuthority !== undefined && !nativeNvidiaProviderAuthority) { + throw new Error("Cannot register a sandbox with invalid native NVIDIA provider authority"); + } const registered: SandboxEntry = { name: entry.name, createdAt: entry.createdAt || new Date().toISOString(), @@ -539,6 +545,7 @@ export function registerSandbox( ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeNvidiaProviderAuthority ? { nativeNvidiaProviderAuthority } : {}), lifecycleGeneration: entry.lifecycleGeneration, lifecycleLiveIdentityFingerprint: entry.lifecycleLiveIdentityFingerprint, messaging: cloneSandboxMessagingState(entry.messaging), @@ -590,6 +597,7 @@ type SandboxInferenceRouteReservation = Pick< hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeNvidiaProviderAuthority?: SandboxEntry["nativeNvidiaProviderAuthority"]; }; interface SandboxInferenceRouteReservationOptions { @@ -637,6 +645,12 @@ export function reserveSandboxInferenceRoute( if (route.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { throw new Error("Cannot reserve invalid native NVIDIA provider attachment identity"); } + const nativeNvidiaProviderAuthority = normalizeNativeNvidiaProviderAttachment( + route.nativeNvidiaProviderAuthority ?? nativeNvidiaProviderAttachment, + ); + if (route.nativeNvidiaProviderAuthority !== undefined && !nativeNvidiaProviderAuthority) { + throw new Error("Cannot reserve invalid native NVIDIA provider authority identity"); + } const provenance = cloneSandboxHostLocalInferenceProvenance(route.hostLocalInferenceProvenance); if ( route.hostLocalInferenceProvenance !== undefined && @@ -698,6 +712,10 @@ export function reserveSandboxInferenceRoute( existing.nativeNvidiaProviderAttachment, nativeNvidiaProviderAttachment ?? existing.nativeNvidiaProviderAttachment, ) && + isDeepStrictEqual( + existing.nativeNvidiaProviderAuthority, + nativeNvidiaProviderAuthority ?? existing.nativeNvidiaProviderAuthority, + ) && isDeepStrictEqual( normalizeInferenceSelection(existing), normalizeInferenceSelection(route), @@ -737,6 +755,11 @@ export function reserveSandboxInferenceRoute( nativeNvidiaProviderAttachment: isNativeNvidiaProvider(normalized.provider) ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) : undefined, + nativeNvidiaProviderAuthority: + nativeNvidiaProviderAuthority ?? + (existing?.gatewayName === route.gatewayName + ? existing.nativeNvidiaProviderAuthority + : undefined), ...(route.hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt: route.hostLocalInferenceReceipt } : {}), @@ -812,7 +835,19 @@ export function updateSandbox(name: string, updates: Partial): boo return false; } if (changesHostLocalInferenceLifecycleAuthority(current, updates)) return false; - const next = normalizeSandboxPolicyAttribution({ ...current, ...updates }); + const nativeNvidiaProviderAuthority = normalizeNativeNvidiaProviderAttachment( + updates.nativeNvidiaProviderAuthority, + ); + if (updates.nativeNvidiaProviderAuthority !== undefined && !nativeNvidiaProviderAuthority) { + throw new Error( + `Refusing to update sandbox '${name}' with invalid native NVIDIA provider authority.`, + ); + } + const normalizedUpdates = + updates.nativeNvidiaProviderAuthority === undefined + ? updates + : { ...updates, nativeNvidiaProviderAuthority }; + const next = normalizeSandboxPolicyAttribution({ ...current, ...normalizedUpdates }); if ( current.deferredN1xManagedVllmAccepted === true && Object.entries(updates).some( diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 93679f018e0..336151236c1 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -135,6 +135,8 @@ export interface SandboxEntry extends Partial { hostLocalInferenceReceipt?: string | null; /** Exact OpenShell provider identity attached for native NVIDIA hosted inference. */ nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + /** Durable ownership authority for the gateway-scoped native NVIDIA provider. */ + nativeNvidiaProviderAuthority?: NativeNvidiaProviderAttachment; /** Explicit hidden-lifecycle provenance; absence keeps llama.cpp on its legacy path. */ hostLocalInferenceProvenance?: SandboxHostLocalInferenceProvenance; /** Explicit Deferred N1x managed-vLLM choice retained after successful onboarding. */ From d47262780eb2edb2dae026829a93a9f13ab868f8 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:11:33 -0700 Subject: [PATCH 039/133] fix(inference): admit native provider authority --- ...egistry-native-provider-attachment.test.ts | 41 +++++++++++++++++++ src/lib/state/registry/route-reservation.ts | 7 ++++ 2 files changed, 48 insertions(+) diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index fa9d99c273f..2bae1d6d269 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -6,6 +6,47 @@ import os from "node:os"; import path from "node:path"; import { expect, it, vi } from "vitest"; +it("admits native NVIDIA provider authority on a pending route reservation", async () => { + const { classifySandboxInferenceRouteReservation } = await import("./registry/route-reservation"); + const selection = { + provider: "ollama-local", + model: "qwen3-vl:4b", + endpointUrl: "http://127.0.0.1:11434/v1", + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: "openai-completions", + compatibleEndpointReasoning: null, + compatibleEndpointReasoningEffort: null, + nimContainer: null, + } as const; + const authority = { + sandboxName: "alpha", + gatewayName: "nemoclaw", + sessionId: "session-owner", + selection, + }; + const disposition = classifySandboxInferenceRouteReservation(authority, { + name: authority.sandboxName, + gatewayName: authority.gatewayName, + reservationSessionId: authority.sessionId, + pendingRouteReservation: true, + provider: selection.provider, + model: selection.model, + endpointUrl: selection.endpointUrl, + endpointSource: selection.endpointSource, + credentialEnv: selection.credentialEnv, + preferredInferenceApi: selection.preferredInferenceApi, + nativeNvidiaProviderAuthority: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }, + }); + + expect(disposition.kind).toBe("owned"); +}); + it("clears a stale native NVIDIA attachment when reserving a shared route", async () => { const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-native-attachment-")); vi.stubEnv("HOME", home); diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 4ac16f5351b..541f3b6090a 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -23,6 +23,7 @@ const ROUTE_RESERVATION_KEYS = new Set([ "model", "name", "nativeNvidiaProviderAttachment", + "nativeNvidiaProviderAuthority", "openshellDriver", "pendingRouteReservation", "pendingCreateIdentity", @@ -88,6 +89,12 @@ function validCarriedRouteMetadata(entry: SandboxEntry): boolean { ) { return false; } + if ( + entry.nativeNvidiaProviderAuthority !== undefined && + !normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAuthority) + ) { + return false; + } return ( entry.webSearchProvider === undefined || entry.webSearchProvider === null || From 34a6bd674f765020d4dc075f3ae86bbbf09acb27 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:52:17 -0700 Subject: [PATCH 040/133] docs: correct native connect verification --- docs/reference/commands.mdx | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 4f3c873961c..678b056ca15 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1196,18 +1196,19 @@ Without `--probe-only`, `connect` does not pull a model itself, but it does insp -Before reading or changing the live OpenShell gateway inference route, `connect` verifies the shared provider and sandbox metadata. -When the live route differs and the metadata is compatible, `connect` warns and re-points the route to the target sandbox's recorded provider and model. +For a shared-route provider, before reading or changing the live OpenShell gateway inference route, `connect` verifies the shared provider and sandbox metadata. +When the live shared route differs and the metadata is compatible, `connect` warns and re-points the route to the target sandbox's recorded provider and model. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for provider-global identity, route drift, and hard-error recovery. Use `$$nemoclaw inference set --provider --model ` to make an intentional compatible route change outside the connect flow. -Before it opens SSH, `connect` probes the selected provider path from inside the sandbox with the selected agent's trusted CA and proxy context. -Shared-route providers use `https://inference.local/v1/models`. -NVIDIA Endpoints verifies its recorded sandbox-attached provider and probes `https://integrate.api.nvidia.com/v1/models`. -HTTP `200` through `499` confirms that the route is reachable. -For a shared-route provider, a recognized broken result lets `connect` attempt DNS or route repair and verify the route again. -For NVIDIA Endpoints, `connect` does not inspect or change the unrelated shared route. -When the initial probe cannot return a trusted result, `connect` fails closed before health-driven repair and before opening SSH. +Before it opens SSH for a shared-route provider, `connect` probes `https://inference.local/v1/models` from inside the sandbox with the selected agent's trusted CA and proxy context. +HTTP `200` through `499` confirms that the shared route is reachable. +A recognized broken shared-route result lets `connect` attempt DNS or route repair and verify the route again. +When the initial shared-route probe cannot return a trusted result, `connect` fails closed before health-driven repair and before opening SSH. It prints a bounded, redacted last-probe detail and points you to `$$nemoclaw doctor`. + +For NVIDIA Endpoints, `connect` does not inspect or change the unrelated shared route. +It verifies the recorded sandbox-attached provider and sends a native inference request for the selected model. +The request must return a structurally valid successful inference result before `connect` opens SSH. After route discovery succeeds, every configured Deep Agents Code route must also serve a valid response to a bounded request for the recorded model. A failed model request or missing provider or model metadata stops `connect` before SSH opens. From 7c4d283d9b0fda277f4b9d6f57ce02c3e1261271 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 12:35:31 -0700 Subject: [PATCH 041/133] fix(inference): satisfy integrated publication checks --- Dockerfile | 4 ++-- src/lib/state/registry-native-provider-attachment.test.ts | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 1a3230306ea..d6fadf376d8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -697,7 +697,7 @@ COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/ COPY --from=runtime-preload-builder /opt/nemoclaw-root/dist/lib/messaging/channels/ /usr/local/lib/nemoclaw/preloads-compiled-channels/ COPY scripts/codex-acp-wrapper.sh /usr/local/bin/nemoclaw-codex-acp COPY scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ -COPY src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/openrouter-headers.ts +COPY src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/ 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 nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ @@ -1547,7 +1547,7 @@ RUN mkdir -p /sandbox/.nemoclaw/blueprints/0.1.0 \ # Copy configuration inputs before the cached non-messaging plugin install. COPY scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ -COPY src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/openrouter-headers.ts +COPY src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/ RUN chmod 444 /src/lib/inference/native-hosted/openrouter-headers.ts COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index 81c625fcdb8..d08fa8a3148 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -127,6 +127,9 @@ it("retains hosted ownership across reload and clears it when moving gateways", reloaded.reserveSandboxInferenceRoute("alpha", { provider: "ollama-local", model: "local-model", + endpointUrl: "http://127.0.0.1:11434/v1", + credentialEnv: null, + preferredInferenceApi: "openai-completions", gatewayName: "nemoclaw", }); expect(reloaded.getSandbox("alpha")?.nativeHostedProviderAttachment).toBeUndefined(); @@ -134,6 +137,9 @@ it("retains hosted ownership across reload and clears it when moving gateways", reloaded.reserveSandboxInferenceRoute("beta", { provider: "ollama-local", model: "local-model", + endpointUrl: "http://127.0.0.1:11434/v1", + credentialEnv: null, + preferredInferenceApi: "openai-completions", gatewayName: "nemoclaw-9090", }); expect(reloaded.getSandbox("beta")?.nativeHostedProviderAuthorities).toBeUndefined(); From 59eeb518642dbe805b6051f30dc2ef042fbe2146 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 13:11:41 -0700 Subject: [PATCH 042/133] fix(inference): verify native selection and switch evidence --- .../status-snapshot-route-drift.test.ts | 38 ++++++ src/lib/actions/sandbox/status-snapshot.ts | 7 +- .../live/hermes-inference-switch-helpers.ts | 57 +++++--- test/e2e/live/hermes-inference-switch.test.ts | 33 +++-- .../e2e/live/public-nvidia-switch-provider.ts | 43 ++++-- ...mes-inference-switch-command-shape.test.ts | 128 ++++++++++++++++-- .../public-nvidia-switch-provider.test.ts | 75 ++++++++++ 7 files changed, 327 insertions(+), 54 deletions(-) diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index b066560954e..c3294e82390 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -623,6 +623,44 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = }, ); + it("refuses a native receipt for a different recorded provider before probing", async () => { + const sandbox: SandboxEntry = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "anthropic-prod", + model: "selected-model", + endpointUrl: "https://api.anthropic.com", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "owned-openai-id", + }, + }; + const verify = vi.fn(async () => undefined); + const invoke = vi.fn(async () => ({ ok: true }) as const); + const probeProvider = vi.fn(() => null); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + verifyNativeHostedProviderAttachmentImpl: verify, + probeProviderHealthImpl: probeProvider, + probeSandboxInferenceInvocationImpl: invoke, + }, + } as never); + expect(verify).not.toHaveBeenCalled(); + expect(invoke).not.toHaveBeenCalled(); + expect(probeProvider).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toMatchObject({ + ok: false, + probed: false, + detail: expect.stringContaining("does not match"), + }); + }); + it("reports a missing native NVIDIA attachment before probing inference", async () => { liveGatewayInference("compatible-endpoint", "other/model"); const sandbox = { diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 25acbe473f5..db66e9fe4bf 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -20,6 +20,7 @@ import { withStdoutRedirectedToStderr } from "../../cli/stdout-guard"; import { getLlamaCppRouteDetails, normalizeNativeHostedProviderAttachment, + nativeHostedProfile, NVIDIA_HOSTED_NATIVE_ENDPOINT, normalizeNativeNvidiaProviderAttachment, type GatewayInference, @@ -627,7 +628,11 @@ export async function collectSandboxStatusSnapshot( let nativeHostedAttachmentFailure: string | null = null; if (!suppressInferenceProbe && lookup.state === "present" && nativeHosted && sb) { const expected = nativeHostedAttachment; - if (!gatewayName || !expected) { + if (nativeHostedProfile(sb.provider)?.profileId !== expected?.profileId) { + nativeHostedAttachmentFailure = + `Native provider attachment does not match the recorded provider for sandbox '${sandboxName}'. ` + + "Recreate the sandbox to restore native inference."; + } else if (!gatewayName || !expected) { nativeHostedAttachmentFailure = `${nativeAttachmentLabel} provider attachment is unavailable for sandbox '${sandboxName}'. ` + `Recreate the sandbox to restore ${nativeNvidiaAttachment ? "native NVIDIA" : "native hosted"} inference.`; diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index e3694f4248f..edc16464195 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -7,8 +7,11 @@ 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 { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; +import { + resolveAgentInferenceApi, + nativeHostedProfile, +} from "../../../src/lib/inference/config.ts"; +import { OPENROUTER_DEFAULT_HEADERS } from "../../../src/lib/inference/native-hosted/openrouter-headers.ts"; import { execTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; @@ -68,7 +71,9 @@ export const SWITCH_PROVIDER = export const SWITCH_MODEL = process.env.NEMOCLAW_SWITCH_MODEL ?? PUBLIC_NVIDIA_SWITCH_MODEL; export const SWITCH_API = process.env.NEMOCLAW_SWITCH_INFERENCE_API ?? "openai-completions"; export const RUNTIME_SWITCH_API = - resolveAgentInferenceApi("hermes", SWITCH_PROVIDER, SWITCH_API) ?? SWITCH_API; + SWITCH_PROVIDER === "anthropic-prod" + ? "anthropic-messages" + : (resolveAgentInferenceApi("hermes", SWITCH_PROVIDER, SWITCH_API) ?? SWITCH_API); const SWITCH_MOCK_PORT = Number.parseInt(process.env.NEMOCLAW_SWITCH_MOCK_PORT ?? "0", 10); const INSTALL_ATTEMPTS = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true" ? 3 : 1; export const PROXY_RESOLUTION_PROVIDER = "hermes-proxy-resolution-e2e"; @@ -231,7 +236,11 @@ export async function prepareProxyResolutionRoute({ }): Promise<{ model: string; requestOffset: number }> { const endpoint = mockBaseline?.baseUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL; - const model = mockBaseline ? PROXY_RESOLUTION_MODEL : SWITCH_MODEL; + const model = mockBaseline + ? PROXY_RESOLUTION_MODEL + : nativeHostedProfile(SWITCH_PROVIDER) && SWITCH_PROVIDER !== PUBLIC_NVIDIA_SWITCH_PROVIDER + ? hostedInstallModel() + : SWITCH_MODEL; const requestOffset = mockBaseline?.requests().length ?? 0; const registered = await host.command( @@ -662,7 +671,7 @@ export async function runHermesInferenceSetWithRetry( artifacts?: InferenceSwitchRetryArtifactSink; compatibleBinding?: CompatibleAnthropicSwitchBinding | null; delay?: (milliseconds: number) => Promise; - publicNvidiaApiKey?: string | null; + nativeProviderApiKey?: string | null; } = {}, ): Promise { const args = [ @@ -676,6 +685,11 @@ export async function runHermesInferenceSetWithRetry( ...compatibleMetadataArgs, ]; const evidenceArtifacts = options.artifacts; + const nativeProfile = nativeHostedProfile(SWITCH_PROVIDER); + const nativeCredential = options.nativeProviderApiKey; + const switchRedactionValues = [ + ...new Set([...redactionValues, ...(nativeCredential ? [nativeCredential] : [])]), + ]; return runInferenceSetWithRetry({ attempts: options.attempts ?? inferenceSetAttemptCount(process.env.NEMOCLAW_SWITCH_SET_ATTEMPTS), @@ -688,11 +702,11 @@ export async function runHermesInferenceSetWithRetry( artifactName: `hermes-inference-set-${attempt}`, env: env(undefined, { ...compatibleAnthropicSwitchEnv(options.compatibleBinding ?? null), - ...(options.publicNvidiaApiKey - ? { NVIDIA_INFERENCE_API_KEY: options.publicNvidiaApiKey } + ...(nativeCredential && nativeProfile + ? { [nativeProfile.credentialEnv]: nativeCredential } : {}), }), - redactionValues, + redactionValues: switchRedactionValues, timeoutMs: 180_000, }), }); @@ -732,8 +746,9 @@ export function maybeAssertPidStable( beforePid && afterPid && assertStable(afterPid, beforePid); } -export function expectedBaseUrl(): string { - if (SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER) return NVIDIA_HOSTED_NATIVE_ENDPOINT; +export function expectedBaseUrl(provider = SWITCH_PROVIDER): string { + const profile = nativeHostedProfile(provider); + if (profile) return profile.endpoint; return RUNTIME_SWITCH_API === "anthropic-messages" ? "https://inference.local" : "https://inference.local/v1"; @@ -811,15 +826,23 @@ function quotePayload(payload: string): string { return payload.replace(/'/gu, `'\\''`); } -const NATIVE_NVIDIA_PROVIDER_PLACEHOLDER_AUTH_HEADER = +const NATIVE_PROVIDER_PLACEHOLDER_AUTH_HEADER = "Author" + "ization: Bearer nemoclaw-openshell-provider"; -export function sandboxInferenceCommand(payload: string): string { - if (SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER) { - // The upstream URL is the managed route for an attached OpenShell - // provider. OpenShell authorizes this profile-scoped request and replaces - // the placeholder without exposing the provider credential to the sandbox. - return `curl -sS --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H '${NATIVE_NVIDIA_PROVIDER_PLACEHOLDER_AUTH_HEADER}' -d '${quotePayload(payload)}'`; +export function sandboxInferenceCommand(payload: string, provider = SWITCH_PROVIDER): string { + const profile = nativeHostedProfile(provider); + if (profile) { + const anthropic = provider === "anthropic-prod"; + const endpoint = `${profile.endpoint}${anthropic ? "/v1/messages" : "/chat/completions"}`; + const authHeader = anthropic + ? "x-api-key: nemoclaw-openshell-provider" + : NATIVE_PROVIDER_PLACEHOLDER_AUTH_HEADER; + const attributionHeaders = + provider === "openrouter-api" + ? OPENROUTER_DEFAULT_HEADERS.map(([name, value]) => ` -H '${name}: ${value}'`).join("") + : ""; + const versionHeader = anthropic ? " -H 'anthropic-version: 2023-06-01'" : ""; + return `curl -sS --max-time 90 ${endpoint} -H 'Content-Type: application/json' -H '${authHeader}'${versionHeader}${attributionHeaders} -d '${quotePayload(payload)}'`; } return RUNTIME_SWITCH_API === "anthropic-messages" ? `curl -sS --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '${quotePayload(payload)}'` diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index 42244d8153e..c61f27e1a00 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { testTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText } from "../fixtures/clients/index.ts"; @@ -51,9 +52,9 @@ import { strictHashPerms, } from "./hermes-inference-switch-helpers.ts"; import { - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, + expectedNativeSwitchAttachmentEvidence, PUBLIC_NVIDIA_SWITCH_PROVIDER, - readPublicNvidiaSwitchAttachmentEvidence, + readNativeSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; @@ -145,10 +146,14 @@ test( SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) : null; + const nativeProfile = nativeHostedProfile(SWITCH_PROVIDER); + const nativeProviderApiKey = nativeProfile + ? (publicApiKey ?? secrets.required(nativeProfile.credentialEnv)) + : null; const apiKey = mockBaseline ? MOCK_BASELINE_API_KEY : (publicApiKey ?? secrets.required("NVIDIA_INFERENCE_API_KEY")); - const redactionValues = [apiKey, publicApiKey].filter( + const redactionValues = [apiKey, publicApiKey, nativeProviderApiKey].filter( (value): value is string => typeof value === "string", ); const installEnv: NodeJS.ProcessEnv = { @@ -203,7 +208,7 @@ test( { artifacts, compatibleBinding: switchBinding, - publicNvidiaApiKey: publicApiKey, + nativeProviderApiKey, }, ); expect(switched.exitCode, resultText(switched)).toBe(0); @@ -306,8 +311,8 @@ test( ); const state = registryState(); - const attachmentEvidence = await readPublicNvidiaSwitchAttachmentEvidence({ - artifactName: "hermes-native-nvidia-provider-attachment", + const attachmentEvidence = await readNativeSwitchAttachmentEvidence({ + artifactName: "hermes-native-provider-attachment", env: env(), logicalProvider: SWITCH_PROVIDER, receipt: state.registry.sandboxes?.[SANDBOX_NAME]?.nativeHostedProviderAttachment, @@ -326,9 +331,7 @@ test( ).toBe( [ "hermes", - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE - : null, + expectedNativeSwitchAttachmentEvidence(SWITCH_PROVIDER), SWITCH_MODEL, SWITCH_PROVIDER, ] @@ -336,13 +339,13 @@ test( .join("\n"), ); expect(state.session).toEqual(baselineSession); - const publicSwitch = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER; - const durableEndpointUrl = publicSwitch + const nativeSwitch = Boolean(nativeHostedProfile(SWITCH_PROVIDER)); + const durableEndpointUrl = nativeSwitch ? null : (switchEndpointUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL); - const durableCredentialEnv = publicSwitch + const durableCredentialEnv = nativeSwitch ? null : switchEndpointUrl ? "COMPATIBLE_ANTHROPIC_API_KEY" @@ -352,7 +355,11 @@ test( ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.credentialEnv).toBe(durableCredentialEnv); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.preferredInferenceApi).toBe( - publicSwitch ? null : RUNTIME_SWITCH_API, + SWITCH_PROVIDER === "anthropic-prod" + ? "anthropic-messages" + : nativeSwitch + ? null + : RUNTIME_SWITCH_API, ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.nimContainer).toBeNull(); progress.phase("exercise sandbox inference and Hermes API"); diff --git a/test/e2e/live/public-nvidia-switch-provider.ts b/test/e2e/live/public-nvidia-switch-provider.ts index c326df53df4..6a67ee769d0 100644 --- a/test/e2e/live/public-nvidia-switch-provider.ts +++ b/test/e2e/live/public-nvidia-switch-provider.ts @@ -1,12 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { - normalizeNativeNvidiaProviderAttachment, - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../../../src/lib/inference/native-nvidia/index.ts"; +import { normalizeNativeHostedProviderAttachment } from "../../../src/lib/inference/native-hosted/contract.ts"; +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { parseCliOpenShellProviderMetadata } from "../../../src/lib/adapters/openshell/provider-metadata-cli.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; @@ -22,22 +18,40 @@ export function requirePublicNvidiaSwitchKey(value: string): string { return value; } -export async function readPublicNvidiaSwitchAttachmentEvidence(options: { +type AttachmentEvidenceOptions = { readonly artifactName: string; readonly env: NodeJS.ProcessEnv; readonly logicalProvider: string; readonly receipt: unknown; readonly sandbox: SandboxClient; readonly sandboxName: string; -}): Promise { +}; + +export async function readPublicNvidiaSwitchAttachmentEvidence( + options: AttachmentEvidenceOptions, +): Promise { if (options.logicalProvider !== PUBLIC_NVIDIA_SWITCH_PROVIDER) return null; - const receipt = normalizeNativeNvidiaProviderAttachment(options.receipt); + return readNativeSwitchAttachmentEvidence(options); +} + +export function expectedNativeSwitchAttachmentEvidence(provider: string): string | null { + const profile = nativeHostedProfile(provider); + if (!profile) return null; + return `provider-inspection=0;provider-name=match;provider-profile=match;provider-id=match;attachment-inspection=0;attached=true;schema=1;profile=${profile.profileId};provider=${profile.providerName}`; +} + +export async function readNativeSwitchAttachmentEvidence( + options: AttachmentEvidenceOptions, +): Promise { + const profile = nativeHostedProfile(options.logicalProvider); + if (!profile) return null; + const receipt = normalizeNativeHostedProviderAttachment(options.receipt); const providerRedactionValues = [ options.env.NVIDIA_API_KEY, - options.env[NVIDIA_HOSTED_CREDENTIAL_ENV], + options.env[profile.credentialEnv], ].filter((value): value is string => typeof value === "string" && value.length > 0); const provider = await options.sandbox.openshell( - ["provider", "get", "-g", "nemoclaw", NVIDIA_HOSTED_NATIVE_PROVIDER], + ["provider", "get", "-g", "nemoclaw", profile.providerName], { artifactName: `${options.artifactName}-provider-metadata`, captureLimitBytes: 16 * 1024, @@ -54,6 +68,7 @@ export async function readPublicNvidiaSwitchAttachmentEvidence(options: { { artifactName: options.artifactName, env: options.env, + redactionValues: providerRedactionValues, timeoutMs: 60_000, }, ); @@ -63,15 +78,15 @@ export async function readPublicNvidiaSwitchAttachmentEvidence(options: { `provider-profile=${ metadata?.type === receipt?.profileId && metadata?.credentialKeys.length === 1 && - metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && + metadata.credentialKeys[0] === profile.credentialEnv && metadata.configKeys.length === 0 && - metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID + metadata.type === profile.profileId ? "match" : "mismatch" }`, `provider-id=${metadata?.revision?.id === receipt?.providerId ? "match" : "mismatch"}`, `attachment-inspection=${String(attachments.exitCode)}`, - `attached=${String(attachments.stdout.split(/\s+/u).includes(NVIDIA_HOSTED_NATIVE_PROVIDER))}`, + `attached=${String(attachments.stdout.split(/\s+/u).includes(profile.providerName))}`, `schema=${String(receipt?.schemaVersion ?? "missing")}`, `profile=${receipt?.profileId ?? "missing"}`, `provider=${receipt?.providerName ?? "missing"}`, 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 759d5ec7da9..99619503966 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -14,6 +14,7 @@ import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { API_KEY_SHAPE_PATTERN, apiKeyShapeCommand, + expectedBaseUrl, cleanupHermesSwitch, compatibleAnthropicMetadataArgs, expectAuthenticatedBaselineInventoryRequest, @@ -41,6 +42,59 @@ import { } from "../live/public-nvidia-switch-provider.ts"; describe("Hermes inference switch command shape", () => { + it.each([ + ["openai-api", "https://api.openai.com/v1", "authorization: bearer", "/chat/completions"], + ["anthropic-prod", "https://api.anthropic.com", "x-api-key:", "/v1/messages"], + [ + "gemini-api", + "https://generativelanguage.googleapis.com/v1beta/openai", + "authorization: bearer", + "/chat/completions", + ], + [ + "openrouter-api", + "https://openrouter.ai/api/v1", + "authorization: bearer", + "/chat/completions", + ], + [ + "hermes-provider", + "https://inference-api.nousresearch.com/v1", + "authorization: bearer", + "/chat/completions", + ], + ])( + "uses native endpoint and placeholder authentication for %s probes", + (provider, endpoint, header, route) => { + expect(expectedBaseUrl(provider)).toBe(endpoint); + const command = sandboxInferenceCommand('{"model":"selected-model"}', provider); + expect(command).toContain(`${endpoint}${route}`); + expect(command.toLowerCase()).toContain(`${header} nemoclaw-openshell-provider`); + expect(command).not.toContain("inference.local"); + }, + ); + + it("includes the Anthropic protocol version", () => { + expect(sandboxInferenceCommand("{}", "anthropic-prod")).toContain( + "anthropic-version: 2023-06-01", + ); + }); + + it("preserves OpenRouter attribution headers", () => { + const command = sandboxInferenceCommand("{}", "openrouter-api"); + expect(command).toContain("-H 'HTTP-Referer: https://www.nvidia.com/nemoclaw/'"); + expect(command).toContain("-H 'X-OpenRouter-Title: NVIDIA NemoClaw'"); + }); + + it.each(["openai-api", "anthropic-prod", "gemini-api", "hermes-provider"])( + "omits OpenRouter attribution for %s", + (provider) => { + const command = sandboxInferenceCommand("{}", provider); + expect(command).not.toContain("HTTP-Referer:"); + expect(command).not.toContain("X-OpenRouter-Title:"); + }, + ); + afterEach(() => vi.unstubAllEnvs()); function matchesApiKeyShape(line: string): boolean { @@ -663,20 +717,76 @@ describe("Hermes inference switch command shape", () => { it("passes the public NVIDIA credential only to the native provider switch", async () => { const command = vi.fn().mockResolvedValue({ exitCode: 0, stderr: "", stdout: "route synced" }); - await runHermesInferenceSetWithRetry( - { command } as unknown as HostCliClient, - ["nvapi-hosted-key"], - [], - { - attempts: 1, - publicNvidiaApiKey: "nvapi-hosted-key", - }, - ); + await runHermesInferenceSetWithRetry({ command } as unknown as HostCliClient, [], [], { + attempts: 1, + nativeProviderApiKey: "nvapi-hosted-key", + }); expect(command).toHaveBeenCalledOnce(); + expect(JSON.stringify(command.mock.calls[0]?.slice(0, 2))).not.toContain("nvapi-hosted-key"); expect(command.mock.calls[0]?.[2]).toMatchObject({ env: { NVIDIA_INFERENCE_API_KEY: "nvapi-hosted-key" }, redactionValues: ["nvapi-hosted-key"], }); }); }); + +describe("native provider switch credential isolation", () => { + it("selects native Anthropic Messages without a custom API override", async () => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "anthropic-prod"); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + expect(helpers.RUNTIME_SWITCH_API).toBe("anthropic-messages"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); + }); + + it.each([ + ["openai-api", "OPENAI_API_KEY"], + ["anthropic-prod", "ANTHROPIC_API_KEY"], + ["gemini-api", "GEMINI_API_KEY"], + ["openrouter-api", "OPENROUTER_API_KEY"], + ["hermes-provider", "OPENAI_API_KEY"], + ])("passes only the selected credential binding for %s", async (provider, credentialEnv) => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", provider); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + const command = vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + const credential = "fixture-native-provider-credential"; + await helpers.runHermesInferenceSetWithRetry({ command } as unknown as HostCliClient, [], [], { + attempts: 1, + nativeProviderApiKey: credential, + }); + const [executable, args, options] = command.mock.calls[0]!; + expect(executable).toBe("node"); + expect(args).toContain(provider); + expect(args).not.toContain(credential); + expect(options.env[credentialEnv]).toBe(credential); + expect(Object.entries(options.env).filter(([, value]) => value === credential)).toEqual([ + [credentialEnv, credential], + ]); + expect(options.redactionValues).toContain(credential); + const proxyCommand = vi + .fn() + .mockResolvedValueOnce({ exitCode: 0, stdout: "created", stderr: "" }) + .mockResolvedValueOnce({ + exitCode: 0, + stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n", + stderr: "", + }) + .mockResolvedValueOnce({ exitCode: 0, stdout: "route synced", stderr: "" }); + const proxy = await helpers.prepareProxyResolutionRoute({ + apiKey: "fixture-baseline-key", + host: { command: proxyCommand } as unknown as HostCliClient, + mockBaseline: undefined, + redactionValues: [], + }); + expect(proxy.model).toBe(DEFAULT_HOSTED_INFERENCE_MODEL); + expect(proxyCommand.mock.calls[2]?.[1]).toEqual( + expect.arrayContaining(["--model", DEFAULT_HOSTED_INFERENCE_MODEL]), + ); + }); +}); diff --git a/test/e2e/support/public-nvidia-switch-provider.test.ts b/test/e2e/support/public-nvidia-switch-provider.test.ts index 58010957ecf..60e04866d3c 100644 --- a/test/e2e/support/public-nvidia-switch-provider.test.ts +++ b/test/e2e/support/public-nvidia-switch-provider.test.ts @@ -1,10 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { describe, expect, it, vi } from "vitest"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { + expectedNativeSwitchAttachmentEvidence, + readNativeSwitchAttachmentEvidence, PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, @@ -123,3 +126,75 @@ describe("public NVIDIA inference switch provider", () => { ); }); }); + +describe("native hosted switch attachment evidence", () => { + it.each(NATIVE_HOSTED_PROFILES)( + "binds $logicalProvider metadata to its receipt and selected sandbox", + async (profile) => { + const credential = "fixture-credential-must-be-redacted"; + const receipt = { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "revision-1", + }; + const metadata = [ + `Name: ${profile.providerName}`, + "Id: revision-1", + `Type: ${profile.profileId}`, + "Resource version: 1", + `Credential keys: ${profile.credentialEnv}`, + "Config keys: ", + ].join("\n"); + const openshell = vi.fn().mockImplementation(async (args: string[]) => ({ + exitCode: 0, + stderr: "", + stdout: args[0] === "provider" ? metadata : profile.providerName, + })); + const options = { + artifactName: "native-attachment", + env: { [profile.credentialEnv]: credential }, + logicalProvider: profile.logicalProvider, + receipt, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "selected-sandbox", + }; + expect(await readNativeSwitchAttachmentEvidence(options)).toBe( + expectedNativeSwitchAttachmentEvidence(profile.logicalProvider), + ); + expect(openshell).toHaveBeenNthCalledWith( + 2, + ["sandbox", "provider", "list", "-g", "nemoclaw", "selected-sandbox"], + expect.objectContaining({ redactionValues: [credential] }), + ); + expect( + await readNativeSwitchAttachmentEvidence({ + ...options, + receipt: { ...receipt, providerId: "different-revision" }, + }), + ).toContain("provider-id=mismatch"); + expect(await readNativeSwitchAttachmentEvidence({ ...options, receipt: undefined })).not.toBe( + expectedNativeSwitchAttachmentEvidence(profile.logicalProvider), + ); + openshell + .mockResolvedValueOnce({ exitCode: 0, stdout: metadata, stderr: "" }) + .mockResolvedValueOnce({ exitCode: 0, stdout: "unrelated-provider", stderr: "" }); + expect(await readNativeSwitchAttachmentEvidence(options)).toContain("attached=false"); + }, + ); + + it("leaves custom provider coverage with its existing owner", async () => { + const openshell = vi.fn(); + expect( + await readNativeSwitchAttachmentEvidence({ + artifactName: "custom", + env: {}, + logicalProvider: "custom-provider", + receipt: undefined, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "selected-sandbox", + }), + ).toBeNull(); + expect(openshell).not.toHaveBeenCalled(); + }); +}); From 1935c1ebfad812e84102b8f4bb2dcde063063a5e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:19:37 -0700 Subject: [PATCH 043/133] fix: preserve native NVIDIA provider authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/credentials-add.ts | 53 +++++++ .../credentials-provider-adapter.test.ts | 102 +++++++++++++- src/lib/actions/credentials/reset.ts | 7 + .../inference-set-openclaw-run.test.ts | 57 ++++++++ src/lib/actions/inference-set.test-support.ts | 2 + src/lib/actions/inference-set.ts | 3 + .../sandbox/connect-inference-route-probe.ts | 2 +- src/lib/actions/sandbox/doctor-flow.test.ts | 50 +++++++ .../actions/sandbox/doctor-inference.test.ts | 130 ++++++++++++++++-- src/lib/actions/sandbox/doctor-inference.ts | 117 ++++++++++++++-- src/lib/actions/sandbox/doctor.ts | 13 +- .../sandbox/inference-route-health.test.ts | 24 ++++ .../actions/sandbox/inference-route-health.ts | 62 +++++++++ src/lib/inference/native-nvidia/index.ts | 19 ++- src/lib/onboard/providers.ts | 6 + src/lib/onboard/setup-inference.test.ts | 28 ++-- src/lib/onboard/setup-inference.ts | 4 + src/lib/state/registry-normalization.test.ts | 30 ++++ src/lib/state/registry.ts | 5 + ...ve-nvidia-provider-authority-state.test.ts | 40 ++++++ .../native-nvidia-provider-authority-state.ts | 68 +++++++++ .../native-nvidia-provider-authority.ts | 40 ++++++ src/lib/state/registry/persistence.ts | 13 ++ src/lib/state/registry/types.ts | 2 + 24 files changed, 828 insertions(+), 49 deletions(-) create mode 100644 src/lib/state/registry/native-nvidia-provider-authority-state.test.ts create mode 100644 src/lib/state/registry/native-nvidia-provider-authority-state.ts create mode 100644 src/lib/state/registry/native-nvidia-provider-authority.ts diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index a15e4b4f1b5..a880edbac01 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -14,6 +14,9 @@ import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../adapters/openshell/timeouts"; import { resolveAgentNameAlias } from "../agent/aliases"; import { CLI_NAME } from "../cli/branding"; import { + ensureNativeNvidiaProvider, + NativeNvidiaProviderError, + NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, @@ -34,6 +37,10 @@ import { SECRET_PATTERNS } from "../security/secret-patterns"; import { assertEndpointResolvesPublic } from "../security/trusted-private-endpoint"; import { withMcpCredentialOwnershipLock } from "../state/mcp-lifecycle-lock/credential-ownership"; import { ROOT } from "../state/paths"; +import { + getNativeNvidiaProviderAuthority, + setNativeNvidiaProviderAuthority, +} from "../state/registry/native-nvidia-provider-authority"; import { forgetExtraProvider, recordExtraProvider } from "./global"; export type CredentialsAddInput = { @@ -53,6 +60,8 @@ export type CredentialsAddResult = { export type CredentialsAddDeps = Readonly<{ providerAdapter?: OpenShellProviderAdapter; + getNativeNvidiaProviderAuthority?: typeof getNativeNvidiaProviderAuthority; + setNativeNvidiaProviderAuthority?: typeof setNativeNvidiaProviderAuthority; }>; const ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,255}$/; @@ -387,6 +396,50 @@ export async function runCredentialsAddAction( return fail(recoveryFailureLines); } + if ( + nativeNvidiaCredentialAlias && + !fromExisting && + (credentials.length !== 1 || credentials[0] !== NVIDIA_HOSTED_CREDENTIAL_ENV) + ) { + return fail([ + ` Native NVIDIA inference requires exactly --credential ${NVIDIA_HOSTED_CREDENTIAL_ENV}.`, + ]); + } + + if (nativeNvidiaCredentialAlias) { + return withMcpCredentialOwnershipLock(async () => { + try { + const expected = ( + deps.getNativeNvidiaProviderAuthority ?? getNativeNvidiaProviderAuthority + )(target.gatewayName); + const receipt = await ensureNativeNvidiaProvider({ + adapter: providerAdapter, + target, + credentialValue: fromExisting + ? null + : (process.env[NVIDIA_HOSTED_CREDENTIAL_ENV] ?? null), + reuseExistingCredential: fromExisting, + ...(expected ? { expected } : {}), + }); + (deps.setNativeNvidiaProviderAuthority ?? setNativeNvidiaProviderAuthority)( + target.gatewayName, + receipt, + ); + return ok([ + ` Registered provider '${provider}' with the OpenShell gateway.`, + ` Verify with '${CLI_NAME} credentials list'.`, + ` Select it with '${CLI_NAME} inference set --provider ${provider} --model '.`, + ]); + } catch (error) { + const detail = + error instanceof NativeNvidiaProviderError || error instanceof Error + ? error.message + : String(error); + return fail([` Could not register provider '${provider}'.`, ` ${detail}`]); + } + }); + } + const profile = bundledProviderProfile(effectiveType); const providerType = profile?.profileType ?? effectiveType.toLowerCase(); const providerProfileFailure = await ensureBundledProviderProfile( diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 375683a6838..99966d164e3 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -129,7 +129,36 @@ describe("credential actions use typed OpenShell provider results", () => { recordExtraProvider, forgetExtraProvider: () => true, }); - const adapter = providerAdapter(); + let providerPresent = false; + const providerId = "11111111-2222-4333-8444-555555555555"; + const adapter = providerAdapter({ + getProvider: vi.fn(async (request) => + providerPresent + ? { + ok: true as const, + value: { + name: request.providerName, + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: providerId, resourceVersion: 1 }, + }, + } + : { + ok: false as const, + error: { + kind: "command" as const, + reason: "not_found" as const, + message: "provider not found", + }, + }, + ), + createProvider: vi.fn(async () => { + providerPresent = true; + return { ok: true as const }; + }), + }); + const setNativeNvidiaProviderAuthority = vi.fn(); const result = await runCredentialsAddAction( { @@ -139,14 +168,17 @@ describe("credential actions use typed OpenShell provider results", () => { configPairs: [], fromExisting: false, }, - { providerAdapter: adapter }, + { + providerAdapter: adapter, + getNativeNvidiaProviderAuthority: () => undefined, + setNativeNvidiaProviderAuthority, + }, ); expect(result.exitCode).toBe(0); expect(adapter.importProviderProfile).toHaveBeenCalledWith({ target: { kind: "named", gatewayName: "nemoclaw" }, profilePath: expect.stringMatching(/provider-profiles\/nemoclaw-nvidia-inference-v1\.yaml$/u), - timeoutMs: 30_000, }); expect(adapter.createProvider).toHaveBeenCalledWith({ target: { kind: "named", gatewayName: "nemoclaw" }, @@ -155,12 +187,59 @@ describe("credential actions use typed OpenShell provider results", () => { credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "host-only-nvidia-value" }], config: [], fromExisting: false, - timeoutMs: 30_000, + }); + expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw", { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId, }); expect(recordExtraProvider).not.toHaveBeenCalled(); expect(JSON.stringify(result)).not.toContain("host-only-nvidia-value"); }); + it("rejects a substituted native NVIDIA provider before replacing its credential", async () => { + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "host-only-nvidia-value"); + const adapter = providerAdapter({ + getProvider: vi.fn(async (request) => ({ + ok: true as const, + value: { + name: request.providerName, + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: "replacement-provider-id", resourceVersion: 2 }, + }, + })), + }); + const setNativeNvidiaProviderAuthority = vi.fn(); + + const result = await runCredentialsAddAction( + { + provider: "nvidia-prod", + type: "nvidia", + credentials: ["NVIDIA_INFERENCE_API_KEY"], + configPairs: [], + fromExisting: false, + }, + { + providerAdapter: adapter, + getNativeNvidiaProviderAuthority: () => ({ + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }), + setNativeNvidiaProviderAuthority, + }, + ); + + expect(result.exitCode).toBe(1); + expect(result.failureLines.join("\n")).toContain("changed identity"); + expect(adapter.updateProvider).not.toHaveBeenCalled(); + expect(setNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + }); + it("lists the native NVIDIA provider only by its logical credential name", async () => { const adapter = providerAdapter({ listProviders: vi.fn(async () => ({ @@ -901,6 +980,21 @@ describe("credential actions use typed OpenShell provider results", () => { }, ); + it("clears native NVIDIA gateway authority only after provider deletion is confirmed", async () => { + const clearNativeNvidiaProviderAuthority = vi.fn(); + const adapter = providerAdapter({ + deleteProvider: vi.fn(async () => ({ ok: true as const })), + }); + + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { providerAdapter: adapter, clearNativeNvidiaProviderAuthority }, + ); + + expect(result.exitCode).toBe(0); + expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw"); + }); + it("reports recovery for sandboxes detached before final deletion fails (#9806)", async () => { const deleteProvider = vi .fn() diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 31fb86bc4fb..e8ee28977f2 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -24,6 +24,7 @@ import { recoverCredentialGatewayTargetOrExit, } from "../../credentials/command-support"; import { prompt as askPrompt, KNOWN_CREDENTIAL_ENV_KEYS } from "../../credentials/store"; +import { clearNativeNvidiaProviderAuthority } from "../../state/registry/native-nvidia-provider-authority"; import { forgetExtraProvider } from "../global"; export type CredentialsResetInput = { @@ -39,6 +40,7 @@ export type CredentialsResetResult = { export type CredentialsResetDeps = Readonly<{ providerAdapter?: OpenShellProviderAdapter; + clearNativeNvidiaProviderAuthority?: typeof clearNativeNvidiaProviderAuthority; }>; export type CredentialsProviderDeleteWithRecoveryResult = Readonly<{ @@ -153,6 +155,11 @@ export async function runCredentialsResetAction( if (!outcome.ok) return fail(outcome.lines); forgetExtraProvider(publicKey); + if (nativeNvidiaProvider) { + (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( + target.gatewayName, + ); + } return ok(outcome.lines); } diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index a7167f14718..6c57a19edde 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -68,6 +68,63 @@ describe("runInferenceSet OpenClaw routing", () => { ); }); + it("selects a native NVIDIA provider registered before any sandbox used it", async () => { + const gatewayAuthority = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + let attached = false; + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true as const })), + getProvider: vi.fn(async () => ({ + ok: true as const, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: gatewayAuthority.providerId, resourceVersion: 1 }, + }, + })), + listProviderAttachments: vi.fn(async () => ({ + ok: true as const, + value: { names: attached ? ["nemoclaw-nvidia-prod-v1"] : [] }, + })), + attachProvider: vi.fn(async () => { + attached = true; + return { ok: true as const }; + }), + } as unknown as OpenShellProviderAdapter; + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "gpt-5.4", + }, + getNativeNvidiaProviderAuthority: () => gatewayAuthority, + providerAdapter, + resolveCredentialValue: () => "", + }); + + await runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, + deps, + ); + + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + nativeNvidiaProviderAttachment: gatewayAuthority, + nativeNvidiaProviderAuthority: gatewayAuthority, + }), + ); + }); + it("detaches native NVIDIA access only after another provider is healthy", async () => { let attached = true; const detachProvider = vi.fn(async () => { diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index 58d564fe6d8..f64d3c3ae79 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -277,6 +277,7 @@ export function createDeps(options: { restartSandboxGateway?: InferenceSetDeps["restartSandboxGateway"]; settleOpenClawPairing?: InferenceSetDeps["settleOpenClawPairing"]; withGatewayRouteMutationLock?: InferenceSetDeps["withGatewayRouteMutationLock"]; + getNativeNvidiaProviderAuthority?: InferenceSetDeps["getNativeNvidiaProviderAuthority"]; }): InferenceSetDeps & { calls: { captureOpenshell: ReturnType; @@ -422,6 +423,7 @@ export function createDeps(options: { getDefaultSandbox: () => defaultSandbox, getSandbox: (name: string) => sandboxes[name] ?? null, listSandboxes: () => ({ sandboxes: entries, defaultSandbox }), + getNativeNvidiaProviderAuthority: options.getNativeNvidiaProviderAuthority, updateSandbox: calls.updateSandbox, getRequestedAgent: () => options.requestedAgent, loadSession: () => session, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 6c233eae2ab..ef40b70e543 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -178,6 +178,7 @@ export interface InferenceSetDeps extends InferenceGatewayRestartDeps { sandboxes: SandboxEntry[]; defaultSandbox: string | null; }; + getNativeNvidiaProviderAuthority?: typeof registry.getNativeNvidiaProviderAuthority; updateSandbox: (name: string, updates: Partial) => boolean; getRequestedAgent: () => string | null | undefined; loadSession: () => onboardSession.Session | null; @@ -310,6 +311,7 @@ function defaultDeps(): InferenceSetDeps { getDefaultSandbox: registry.getDefault, getSandbox: registry.getSandbox, listSandboxes: registry.listSandboxes, + getNativeNvidiaProviderAuthority: registry.getNativeNvidiaProviderAuthority, updateSandbox: registry.updateSandbox, getRequestedAgent: () => process.env.NEMOCLAW_AGENT, loadSession: onboardSession.loadSession, @@ -1528,6 +1530,7 @@ async function runInferenceSetWithoutHostLock( const nativeNvidiaProviderAuthority = selectingNativeNvidia ? resolveGatewayNativeNvidiaProviderAuthority({ gatewayName: preparedRoute.gatewayName, + gatewayAuthority: deps.getNativeNvidiaProviderAuthority?.(preparedRoute.gatewayName), recordedAttachment: previousNativeNvidiaAttachment, recordedAuthority: previousNativeNvidiaAuthority, sandboxes: routeSandboxes, diff --git a/src/lib/actions/sandbox/connect-inference-route-probe.ts b/src/lib/actions/sandbox/connect-inference-route-probe.ts index e47a9e5dca7..4844a4c0921 100644 --- a/src/lib/actions/sandbox/connect-inference-route-probe.ts +++ b/src/lib/actions/sandbox/connect-inference-route-probe.ts @@ -70,7 +70,7 @@ export function isDcodeManagedExecMissingDetail(detail: string): boolean { ); } -function formatUntrustedProbeDetail(detail: string): string { +export function formatUntrustedProbeDetail(detail: string): string { const normalized = detail.replace(/\s+/g, " ").trim(); if (isDcodeManagedExecMissingDetail(normalized)) return DCODE_MANAGED_EXEC_MISSING_DETAIL; return redactSensitiveText(normalized) ?? ""; diff --git a/src/lib/actions/sandbox/doctor-flow.test.ts b/src/lib/actions/sandbox/doctor-flow.test.ts index d2fe5532a72..00f57b89fda 100644 --- a/src/lib/actions/sandbox/doctor-flow.test.ts +++ b/src/lib/actions/sandbox/doctor-flow.test.ts @@ -54,6 +54,8 @@ function createDoctorHarness( ollamaInventoryProbeSpy: MockInstance; loadAgentSpy: MockInstance; probeSandboxInferenceGatewayHealthSpy: MockInstance; + probeSandboxNativeNvidiaModelsHealthSpy: MockInstance; + verifyNativeNvidiaStatusAttachmentSpy: MockInstance; logSpy: MockInstance; recoverNamedGatewayRuntimeSpy: MockInstance; resolveOpenShellSpy: MockInstance; @@ -213,6 +215,17 @@ function createDoctorHarness( httpStatus: 0, detail: "Inference gateway unreachable inside the sandbox.", }); + const probeSandboxNativeNvidiaModelsHealthSpy = vi + .spyOn(inferenceRouteHealth, "probeSandboxNativeNvidiaModelsHealth") + .mockResolvedValue({ + ok: true, + endpoint: "https://integrate.api.nvidia.com/v1/models", + httpStatus: 200, + detail: "native NVIDIA models route reachable", + }); + const verifyNativeNvidiaStatusAttachmentSpy = vi + .spyOn(inferenceRouteHealth, "verifyNativeNvidiaStatusAttachment") + .mockResolvedValue(undefined); const loadAgentSpy = vi.spyOn(agentDefs, "loadAgent").mockReturnValue({ name: "openclaw", configPaths: { dir: "/sandbox/.openclaw", configFile: "openclaw.json", format: "json" }, @@ -266,6 +279,8 @@ function createDoctorHarness( ollamaInventoryProbeSpy, loadAgentSpy, probeSandboxInferenceGatewayHealthSpy, + probeSandboxNativeNvidiaModelsHealthSpy, + verifyNativeNvidiaStatusAttachmentSpy, logSpy, recoverNamedGatewayRuntimeSpy, resolveOpenShellSpy, @@ -614,6 +629,41 @@ describe("runSandboxDoctor flow", () => { }, ); + it("uses the recorded native NVIDIA attachment instead of an unrelated shared route", async () => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }; + const harness = createDoctorHarness("nvidia-prod", { + registryOverrides: { nativeNvidiaProviderAttachment: receipt }, + }); + + const report = await harness.runSandboxDoctor("alpha", ["--json"], { quietJson: true }); + + expect(harness.captureOpenShellSpy).not.toHaveBeenCalledWith( + expect.arrayContaining(["inference", "get"]), + expect.anything(), + ); + expect(harness.probeSandboxInferenceGatewayHealthSpy).not.toHaveBeenCalled(); + expect(harness.verifyNativeNvidiaStatusAttachmentSpy).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", + expected: receipt, + }); + expect(harness.probeSandboxNativeNvidiaModelsHealthSpy).toHaveBeenCalledWith("alpha", { + gatewayName: "nemoclaw-19080", + agentName: "openclaw", + }); + expect(report?.checks).toContainEqual( + expect.objectContaining({ + label: "Inference route (native NVIDIA)", + status: "ok", + }), + ); + }); + it("rejects mutating --fix when JSON output was requested", async () => { const harness = createDoctorHarness(); diff --git a/src/lib/actions/sandbox/doctor-inference.test.ts b/src/lib/actions/sandbox/doctor-inference.test.ts index 9ca9b25a8fe..0544d8b9ec1 100644 --- a/src/lib/actions/sandbox/doctor-inference.test.ts +++ b/src/lib/actions/sandbox/doctor-inference.test.ts @@ -97,7 +97,7 @@ describe("doctor inference checks", () => { it("makes a broken inference.local route authoritative over a healthy upstream (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "nvidia-prod", model: "nvidia/nemotron" }, + { provider: "openai-api", model: "gpt-5.4" }, true, { probeProviderHealthImpl: () => upstream(), @@ -116,7 +116,7 @@ describe("doctor inference checks", () => { it("keeps failed upstream health diagnostic when inference.local works (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "nvidia-prod", model: "nvidia/nemotron" }, + { provider: "openai-api", model: "gpt-5.4" }, true, { probeProviderHealthImpl: () => @@ -137,7 +137,7 @@ describe("doctor inference checks", () => { it("keeps inference.local authoritative when the upstream diagnostic throws (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "nvidia-prod", model: "nvidia/nemotron" }, + { provider: "openai-api", model: "gpt-5.4" }, true, { probeProviderHealthImpl: () => { @@ -182,7 +182,7 @@ describe("doctor inference checks", () => { it("reports an HTTP 503 inference.local route as unhealthy (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "nvidia-prod", model: "model" }, + { provider: "openai-api", model: "model" }, true, { probeProviderHealthImpl: () => upstream(), @@ -204,7 +204,7 @@ describe("doctor inference checks", () => { async (failureMode) => { const checks = await collectInferenceChecks( "alpha", - { provider: "nvidia-prod", model: "model" }, + { provider: "openai-api", model: "model" }, true, { probeProviderHealthImpl: () => upstream(), @@ -230,7 +230,7 @@ describe("doctor inference checks", () => { it("keeps serving-process health explicitly unchecked until a probe contract exists (#7003)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "nvidia-prod", model: "model" }, + { provider: "openai-api", model: "model" }, true, { probeProviderHealthImpl: () => upstream(), @@ -250,7 +250,7 @@ describe("doctor inference checks", () => { it("omits serving-process health for terminal agents without a gateway process (#7003)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "nvidia-prod", model: "model" }, + { provider: "openai-api", model: "model" }, true, { probeProviderHealthImpl: () => upstream(), @@ -265,7 +265,7 @@ describe("doctor inference checks", () => { it("does not mutate direct provider health while adding route evidence", async () => { const providerHealth = upstream(); - await collectInferenceChecks("alpha", { provider: "nvidia-prod", model: "model" }, true, { + await collectInferenceChecks("alpha", { provider: "openai-api", model: "model" }, true, { probeProviderHealthImpl: () => providerHealth, probeSandboxInferenceGatewayHealthImpl: async () => gateway(true), }); @@ -274,6 +274,120 @@ describe("doctor inference checks", () => { expect(providerHealth).not.toHaveProperty("probeLabel"); }); + it("verifies and probes the attached native NVIDIA provider without consulting inference.local", async () => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const verify = vi.fn(async () => undefined); + const nativeProbe = vi.fn(async () => ({ + ok: true, + endpoint: "https://integrate.api.nvidia.com/v1/models", + httpStatus: 200, + detail: "native NVIDIA models route reachable", + })); + const sharedProbe = vi.fn(async () => gateway(true)); + + const checks = await collectInferenceChecks( + "alpha", + { + provider: "nvidia-prod", + model: "nvidia/nemotron", + agentName: "openclaw", + nativeNvidiaProviderAttachment: receipt, + }, + true, + { + gatewayName: "nemoclaw-19080", + includeServingProcessCheck: false, + verifyNativeNvidiaStatusAttachmentImpl: verify, + probeSandboxNativeNvidiaModelsHealthImpl: nativeProbe, + probeSandboxInferenceGatewayHealthImpl: sharedProbe, + }, + ); + + expect(verify).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", + expected: receipt, + }); + expect(nativeProbe).toHaveBeenCalledWith("alpha", { + gatewayName: "nemoclaw-19080", + agentName: "openclaw", + }); + expect(sharedProbe).not.toHaveBeenCalled(); + expect(checks).toContainEqual( + expect.objectContaining({ label: "Inference route (native NVIDIA)", status: "ok" }), + ); + }); + + it("fails native NVIDIA doctor when the recorded attachment is unavailable", async () => { + const nativeProbe = vi.fn(); + + const checks = await collectInferenceChecks( + "alpha", + { provider: "nvidia-prod", model: "nvidia/nemotron" }, + true, + { + gatewayName: "nemoclaw-19080", + includeServingProcessCheck: false, + probeSandboxNativeNvidiaModelsHealthImpl: nativeProbe, + }, + ); + + expect(nativeProbe).not.toHaveBeenCalled(); + expect(checks).toContainEqual( + expect.objectContaining({ + label: "Inference route (native NVIDIA)", + status: "fail", + detail: expect.stringContaining("ownership receipt"), + }), + ); + }); + + it("does not let an unrelated healthy shared route hide unavailable native NVIDIA access", async () => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const sharedProbe = vi.fn(async () => gateway(true)); + + const checks = await collectInferenceChecks( + "alpha", + { + provider: "nvidia-prod", + model: "nvidia/nemotron", + nativeNvidiaProviderAttachment: receipt, + }, + true, + { + gatewayName: "nemoclaw-19080", + includeServingProcessCheck: false, + verifyNativeNvidiaStatusAttachmentImpl: vi.fn(async () => undefined), + probeSandboxNativeNvidiaModelsHealthImpl: vi.fn(async () => ({ + ok: false, + endpoint: "https://integrate.api.nvidia.com/v1/models", + httpStatus: 401, + detail: "native NVIDIA models route returned HTTP 401", + })), + probeSandboxInferenceGatewayHealthImpl: sharedProbe, + }, + ); + + expect(sharedProbe).not.toHaveBeenCalled(); + expect(checks).toContainEqual( + expect.objectContaining({ + label: "Inference route (native NVIDIA)", + status: "fail", + detail: expect.stringContaining("401"), + }), + ); + }); + it("passes the live route model to direct provider diagnostics", async () => { const probe = vi.fn(() => upstream()); diff --git a/src/lib/actions/sandbox/doctor-inference.ts b/src/lib/actions/sandbox/doctor-inference.ts index b45a7a2801d..168670e5905 100644 --- a/src/lib/actions/sandbox/doctor-inference.ts +++ b/src/lib/actions/sandbox/doctor-inference.ts @@ -8,9 +8,21 @@ import { type EffectiveReasoningEffort, getEffectiveReasoningEffort, } from "../../inference/selection"; -import { classifyInferenceRouteFailureLabel } from "./connect-inference-route-probe"; +import { + isNativeNvidiaProvider, + normalizeNativeNvidiaProviderAttachment, + type NativeNvidiaProviderAttachment, +} from "../../inference/native-nvidia"; +import { + classifyInferenceRouteFailureLabel, + formatUntrustedProbeDetail, +} from "./connect-inference-route-probe"; import type { DoctorCheck } from "./doctor-report"; -import { probeSandboxInferenceGatewayHealth } from "./inference-route-health"; +import { + probeSandboxInferenceGatewayHealth, + probeSandboxNativeNvidiaModelsHealth, + verifyNativeNvidiaStatusAttachment, +} from "./inference-route-health"; export type DoctorInferenceRoute = { model: string; @@ -18,6 +30,8 @@ export type DoctorInferenceRoute = { effectiveReasoningEffort?: EffectiveReasoningEffort | null; /** Sandbox route endpoint recorded at onboard; selects the bearerless local vLLM host port. */ recordedEndpointUrl?: string | null; + agentName?: string | null; + nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; }; type ManagedLlamaCppDoctorDeps = { @@ -67,16 +81,96 @@ type DoctorInferenceDeps = { gatewayName?: string | null; probeProviderHealthImpl?: typeof probeProviderHealth; probeSandboxInferenceGatewayHealthImpl?: typeof probeSandboxInferenceGatewayHealth; + probeSandboxNativeNvidiaModelsHealthImpl?: typeof probeSandboxNativeNvidiaModelsHealth; + verifyNativeNvidiaStatusAttachmentImpl?: typeof verifyNativeNvidiaStatusAttachment; /** False for terminal agents that do not have a long-running gateway serving process. */ includeServingProcessCheck?: boolean; }; +async function collectNativeNvidiaRouteProbe( + sandboxName: string, + route: DoctorInferenceRoute, + sandboxReachable: boolean, + deps: DoctorInferenceDeps, +): Promise { + const endpoint = "https://integrate.api.nvidia.com/v1/models"; + if (!sandboxReachable) { + return { + ok: false, + probed: false, + providerLabel: "Native NVIDIA route", + endpoint, + detail: "skipped because the sandbox is not reachable through its named gateway", + probeLabel: "native NVIDIA", + }; + } + if (!deps.gatewayName || !route.nativeNvidiaProviderAttachment) { + return { + ok: false, + probed: false, + providerLabel: "Native NVIDIA route", + endpoint, + detail: "the native NVIDIA provider ownership receipt or gateway binding is missing", + probeLabel: "native NVIDIA", + failureLabel: "unreachable", + }; + } + try { + await (deps.verifyNativeNvidiaStatusAttachmentImpl ?? verifyNativeNvidiaStatusAttachment)({ + gatewayName: deps.gatewayName, + sandboxName, + expected: route.nativeNvidiaProviderAttachment, + }); + } catch (error) { + const detail = formatUntrustedProbeDetail( + error instanceof Error ? error.message : String(error), + ); + return { + ok: false, + probed: false, + providerLabel: "Native NVIDIA route", + endpoint, + detail: `the recorded native NVIDIA provider attachment could not be verified: ${detail}`, + probeLabel: "native NVIDIA", + failureLabel: "unreachable", + }; + } + const probe = + deps.probeSandboxNativeNvidiaModelsHealthImpl ?? probeSandboxNativeNvidiaModelsHealth; + const result = await probe(sandboxName, { + gatewayName: deps.gatewayName, + agentName: route.agentName, + }).catch(() => null); + if (!result) { + return { + ok: false, + probed: false, + providerLabel: "Native NVIDIA route", + endpoint, + detail: `Could not probe ${endpoint} through the attached provider.`, + probeLabel: "native NVIDIA", + failureLabel: "unreachable", + }; + } + return { + ok: result.ok, + probed: true, + providerLabel: "Native NVIDIA route", + endpoint: result.endpoint, + detail: result.detail, + probeLabel: "native NVIDIA", + ...(result.ok ? {} : { failureLabel: classifyInferenceRouteFailureLabel(result.httpStatus) }), + }; +} + export function resolveDoctorReasoningEffort( input: Parameters[0], ): EffectiveReasoningEffort | null { return getEffectiveReasoningEffort(input); } +export { isNativeNvidiaProvider, normalizeNativeNvidiaProviderAttachment }; + function pushInferenceHealthCheck( checks: DoctorCheck[], probe: ProviderHealthStatus, @@ -220,13 +314,18 @@ export async function collectInferenceChecks( const checks = [inferenceRouteCheck(sandboxName, route)]; const effortCheck = reasoningEffortCheck(route); if (effortCheck) checks.push(effortCheck); - const gatewayProbe = await collectInferenceRouteProbe( - sandboxName, - sandboxReachable, - deps.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth, - deps.gatewayName, - ); - pushInferenceHealthCheck(checks, gatewayProbe, { label: "Inference route (gateway)" }); + const nativeNvidia = isNativeNvidiaProvider(route.provider); + const routeProbe = nativeNvidia + ? await collectNativeNvidiaRouteProbe(sandboxName, route, sandboxReachable, deps) + : await collectInferenceRouteProbe( + sandboxName, + sandboxReachable, + deps.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth, + deps.gatewayName, + ); + pushInferenceHealthCheck(checks, routeProbe, { + label: nativeNvidia ? "Inference route (native NVIDIA)" : "Inference route (gateway)", + }); for (const diagnostic of collectProviderHealthDiagnostics( route, deps.probeProviderHealthImpl ?? probeProviderHealth, diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index 29bc524f928..9e5a6a84daf 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -39,6 +39,8 @@ import { collectInferenceChecks, collectManagedLlamaCppDoctorChecks, type DoctorInferenceRoute, + isNativeNvidiaProvider, + normalizeNativeNvidiaProviderAttachment, resolveDoctorReasoningEffort, } from "./doctor-inference"; import { @@ -386,8 +388,9 @@ async function resolveInferenceRoute( openshellConnected: boolean, gatewayName: string | null, ): Promise { + const recordedNativeNvidia = isNativeNvidiaProvider(sb?.provider); let live: { provider: string; model: string } | null = null; - if (openshellBin && openshellConnected && gatewayName) { + if (!recordedNativeNvidia && openshellBin && openshellConnected && gatewayName) { const result = await createSynchronousCliOpenShellInferenceRouteObserver( captureOpenshell, ).observeInferenceRoute({ @@ -401,6 +404,14 @@ async function resolveInferenceRoute( provider: live?.provider || sb?.provider || "unknown", effectiveReasoningEffort: resolveDoctorReasoningEffort(sb), recordedEndpointUrl: sb?.endpointUrl, + agentName: sb?.agent, + ...(recordedNativeNvidia + ? { + nativeNvidiaProviderAttachment: normalizeNativeNvidiaProviderAttachment( + sb?.nativeNvidiaProviderAttachment, + ), + } + : {}), }; } diff --git a/src/lib/actions/sandbox/inference-route-health.test.ts b/src/lib/actions/sandbox/inference-route-health.test.ts index d79ebc56d12..a662d6dc32b 100644 --- a/src/lib/actions/sandbox/inference-route-health.test.ts +++ b/src/lib/actions/sandbox/inference-route-health.test.ts @@ -11,6 +11,7 @@ import { buildSandboxInferenceRouteHealth, isTransientInferenceInvocationFailure, probeSandboxInferenceGatewayHealth, + probeSandboxNativeNvidiaModelsHealth, runSandboxInferenceInvocationProbe, type SandboxInferenceRouteHealth, } from "./inference-route-health"; @@ -116,6 +117,29 @@ describe("sandbox inference route health", () => { detail: DCODE_MANAGED_EXEC_MISSING_DETAIL, }); }); + + it("probes native NVIDIA models through the attached provider placeholder", async () => { + const commandExecutor = makeExecutor("OK 200"); + + const result = await probeSandboxNativeNvidiaModelsHealth("alpha", { + gatewayName: "nemoclaw-19080", + agentName: "openclaw", + commandExecutor, + }); + + expect(result).toMatchObject({ + ok: true, + httpStatus: 200, + endpoint: "https://integrate.api.nvidia.com/v1/models", + }); + expect(commandExecutor.runBuffered).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + target: { kind: "named", gatewayName: "nemoclaw-19080" }, + command: ["sh", "-c", expect.stringContaining("nemoclaw-openshell-provider")], + }), + ); + }); }); describe("buildSandboxInferenceRouteHealth (#10080)", () => { diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 4d797a08c7a..6f2857f8f2d 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { buildSandboxCommandEnvironment } from "../../adapters/sandbox/command-transport"; import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter-cli"; @@ -18,6 +19,7 @@ import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-h import { buildSandboxInferenceRouteProbeRequest, classifyInferenceRouteFailureLabel, + DCODE_MANAGED_EXEC_LAUNCHER, isDcodeManagedExecMissingDetail, parseSandboxInferenceRouteProbeResult, } from "./connect-inference-route-probe"; @@ -64,6 +66,66 @@ export type SandboxInferenceRouteHealth = { detail: string; }; +const NATIVE_NVIDIA_MODELS_ENDPOINT = `${NVIDIA_HOSTED_NATIVE_ENDPOINT}/models`; +const NATIVE_NVIDIA_MODELS_PROBE_SCRIPT = [ + "AUTH_HEADER=$(printf 'Authorization: %s %s' 'Bearer' 'nemoclaw-openshell-provider')", + `HTTP_CODE=$(/usr/bin/curl -q -s -o /dev/null -w '%{http_code}' -H "$AUTH_HEADER" --connect-timeout 3 --max-time 15 ${NATIVE_NVIDIA_MODELS_ENDPOINT} 2>/dev/null) || HTTP_CODE=000`, + 'case "$HTTP_CODE" in 2[0-9][0-9]) printf \'OK %s\' "$HTTP_CODE" ;; *) printf \'BROKEN %s\' "$HTTP_CODE" ;; esac', +].join("; "); + +/** Probe the exact attached native NVIDIA provider from inside one sandbox. */ +export async function probeSandboxNativeNvidiaModelsHealth( + sandboxName: string, + options: { + gatewayName: string; + agentName?: string | null; + commandExecutor?: OpenShellSandboxBufferedCommandExecutor; + }, +): Promise { + const commandExecutor = + options.commandExecutor ?? + createCliOpenShellSandboxCommandExecutor({ hostCwd: REPOSITORY_ROOT }); + const dcode = options.agentName === DCODE_AGENT_NAME; + try { + const completed = await commandExecutor.runBuffered({ + sandboxName, + target: { kind: "named", gatewayName: options.gatewayName }, + command: dcode + ? [DCODE_MANAGED_EXEC_LAUNCHER, "/bin/sh", "-c", NATIVE_NVIDIA_MODELS_PROBE_SCRIPT] + : ["sh", "-c", NATIVE_NVIDIA_MODELS_PROBE_SCRIPT], + ...(dcode + ? { + sandboxEnvironment: { BASH_ENV: "", ENV: "", HOME: "/usr/local/lib/nemoclaw" }, + tty: false, + } + : {}), + environment: buildSandboxCommandEnvironment(), + timeoutMilliseconds: OPENSHELL_INFERENCE_ROUTE_PROBE_TIMEOUT_MS, + }); + if (completed.outcome.kind !== "completed") return null; + const parsed = parseSandboxInferenceRouteProbeResult({ + status: completed.outcome.exitCode, + output: completed.stdout, + stderr: completed.stderr, + }); + if (!parsed.healthy && !parsed.broken) return null; + const httpStatus = parsed.httpStatus; + const ok = parsed.healthy; + return { + ok, + endpoint: NATIVE_NVIDIA_MODELS_ENDPOINT, + httpStatus, + detail: ok + ? `The attached native NVIDIA provider returned HTTP ${httpStatus} on ${NATIVE_NVIDIA_MODELS_ENDPOINT}.` + : httpStatus === 0 + ? `The attached native NVIDIA provider was unreachable on ${NATIVE_NVIDIA_MODELS_ENDPOINT}.` + : `The attached native NVIDIA provider returned HTTP ${httpStatus} on ${NATIVE_NVIDIA_MODELS_ENDPOINT}.`, + }; + } catch { + return null; + } +} + /** * Probe the authoritative `https://inference.local/v1/models` route from * inside the sandbox using the same agent-aware argv and parser as connect. diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 92151e4d5d9..d7ae4f9dfba 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -51,6 +51,7 @@ export function isNativeNvidiaProvider(provider: string | null | undefined): boo export function resolveGatewayNativeNvidiaProviderAuthority(input: { gatewayName: string; + gatewayAuthority?: NativeNvidiaProviderAttachment | null; recordedAttachment?: NativeNvidiaProviderAttachment | null; recordedAuthority?: NativeNvidiaProviderAttachment | null; sandboxes: ReadonlyArray<{ @@ -60,18 +61,14 @@ export function resolveGatewayNativeNvidiaProviderAuthority(input: { nativeNvidiaProviderAuthority?: unknown; }>; }): NativeNvidiaProviderAttachment | undefined { - if (input.recordedAttachment && input.recordedAuthority) { - if (input.recordedAttachment.providerId !== input.recordedAuthority.providerId) { - throw new NativeNvidiaProviderError( - `Gateway '${input.gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, - ); - } - return input.recordedAttachment; - } - if (input.recordedAttachment) return input.recordedAttachment; - if (input.recordedAuthority) return input.recordedAuthority; - const authorities = new Map(); + for (const receipt of [ + input.gatewayAuthority, + input.recordedAttachment, + input.recordedAuthority, + ]) { + if (receipt) authorities.set(receipt.providerId, receipt); + } for (const sandbox of input.sandboxes) { if (sandbox.gatewayName !== input.gatewayName) continue; const authority = normalizeNativeNvidiaProviderAttachment( diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index b2dfc1efcf5..0a5654eaf5d 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -17,6 +17,10 @@ const openrouter = require("../inference/openrouter"); const { isSafeModelId } = require("../validation"); const { compactText } = require("../core/url-utils"); const { createCliOpenShellProviderAdapter } = require("../adapters/openshell/provider-adapter-cli"); +const { + getNativeNvidiaProviderAuthority, + setNativeNvidiaProviderAuthority, +} = require("../state/registry/native-nvidia-provider-authority"); const { LLAMA_CPP_CREDENTIAL_ENV, LLAMA_CPP_HOST_OPENAI_BASE_URL, @@ -393,6 +397,8 @@ function setupInferenceProviderDeps(runOpenshell) { return { providerExistsInGateway, providerAdapter: createCliOpenShellProviderAdapter({ run: runOpenshell }), + getNativeNvidiaProviderAuthority, + setNativeNvidiaProviderAuthority, }; } diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 3cb93ed8500..ba712108fe5 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -211,6 +211,7 @@ describe("native NVIDIA onboarding", () => { } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); const updateSandbox = vi.fn(() => true); + const setNativeNvidiaProviderAuthority = vi.fn(() => true); const verifyInferenceRoute = vi.fn(); const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); const setupInference = createSetupInference({ @@ -223,6 +224,7 @@ describe("native NVIDIA onboarding", () => { getGatewayName: () => "onboarding-gateway", runOpenshell, updateSandbox, + setNativeNvidiaProviderAuthority, getSandbox: () => null, upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute, @@ -288,6 +290,12 @@ describe("native NVIDIA onboarding", () => { }, }), ); + expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("onboarding-gateway", { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }); }); it("reuses a gateway-owned provider for a fresh second sandbox", async () => { @@ -316,21 +324,11 @@ describe("native NVIDIA onboarding", () => { runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), updateSandbox, getSandbox: () => null, - listSandboxes: () => ({ - defaultSandbox: "first", - sandboxes: [ - { - name: "first", - gatewayName: "onboarding-gateway", - provider: "nvidia-prod", - nativeNvidiaProviderAttachment: { - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "provider-id", - }, - }, - ], + getNativeNvidiaProviderAuthority: () => ({ + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", }), upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 7f003498713..0cc439ce5ee 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -236,6 +236,8 @@ export type SetupInferenceDeps = ProviderBranchDeps & { // by hand, so every read below must stay optional-chained. getSandbox?: typeof import("../state/registry").getSandbox; listSandboxes?: typeof import("../state/registry").listSandboxes; + getNativeNvidiaProviderAuthority?: typeof import("../state/registry").getNativeNvidiaProviderAuthority; + setNativeNvidiaProviderAuthority?: typeof import("../state/registry").setNativeNvidiaProviderAuthority; unloadOllamaModels?: (onlyModels: readonly string[]) => OllamaUnloadResult | void; withOllamaModelOwnershipLock?: typeof withOllamaModelOwnershipLock; withOllamaModelOwnershipTransaction?: typeof withOllamaModelOwnershipTransaction; @@ -983,6 +985,7 @@ export function createSetupInference( } const providerAuthority = resolveGatewayNativeNvidiaProviderAuthority({ gatewayName, + gatewayAuthority: deps.getNativeNvidiaProviderAuthority?.(gatewayName), recordedAttachment, sandboxes: deps.listSandboxes?.().sandboxes ?? [], }); @@ -993,6 +996,7 @@ export function createSetupInference( reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, ...(providerAuthority ? { expected: providerAuthority } : {}), }); + deps.setNativeNvidiaProviderAuthority?.(gatewayName, nativeNvidiaProviderAttachment); return null; } diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index 1454305c76c..e9c46e04597 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -39,6 +39,36 @@ afterEach(() => { }); describe("sandbox registry normalization", () => { + it("persists only valid gateway-scoped native NVIDIA provider authorities", async () => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const { registry } = await loadRegistryDocument({ + defaultSandbox: null, + sandboxes: {}, + nativeNvidiaProviderAuthorities: { + broken: { ...receipt, providerId: "" }, + "nemoclaw-19080": receipt, + }, + }); + + expect(registry.getNativeNvidiaProviderAuthority("broken")).toBeUndefined(); + expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toEqual(receipt); + registry.setNativeNvidiaProviderAuthority("nemoclaw-19081", { + ...receipt, + providerId: "22222222-3333-4444-8555-666666666666", + }); + expect(registry.load().nativeNvidiaProviderAuthorities).toEqual({ + "nemoclaw-19080": receipt, + "nemoclaw-19081": { ...receipt, providerId: "22222222-3333-4444-8555-666666666666" }, + }); + registry.clearNativeNvidiaProviderAuthority("nemoclaw-19080"); + expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toBeUndefined(); + }); + it("persists incomplete OpenClaw synchronization until explicit completion", async () => { const registry = await loadRegistryWith({ alpha: { name: "alpha", agent: "openclaw", provider: "nvidia-prod", model: "old" }, diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 65ab54f6bbc..2ba630bac43 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -69,6 +69,11 @@ export { listExtraProviders, removeExtraProvider, } from "./registry/extra-providers"; +export { + clearNativeNvidiaProviderAuthority, + getNativeNvidiaProviderAuthority, + setNativeNvidiaProviderAuthority, +} from "./registry/native-nvidia-provider-authority"; import { isDcodeAutoApprovalMode } from "../onboard/dcode-auto-approval"; import { cloneSandboxHostMounts, hasUnsafeHostMountTerminalText } from "./registry/host-mount"; diff --git a/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts b/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts new file mode 100644 index 00000000000..23d620d846f --- /dev/null +++ b/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { + applyNativeNvidiaProviderAuthority, + normalizeNativeNvidiaProviderAuthorities, + readNativeNvidiaProviderAuthority, + removeNativeNvidiaProviderAuthority, +} from "./native-nvidia-provider-authority-state"; + +const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", +}; + +describe("native NVIDIA gateway provider authority", () => { + it("normalizes, reads, and removes gateway-scoped receipts", () => { + const state: { + nativeNvidiaProviderAuthorities?: Record; + } = {}; + + expect(applyNativeNvidiaProviderAuthority(state, "nemoclaw-19080", receipt)).toBe(true); + expect(readNativeNvidiaProviderAuthority(state, "nemoclaw-19080")).toEqual(receipt); + expect(removeNativeNvidiaProviderAuthority(state, "nemoclaw-19080")).toBe(true); + expect(state.nativeNvidiaProviderAuthorities).toBeUndefined(); + }); + + it("drops malformed receipts and sorts gateway keys", () => { + expect( + normalizeNativeNvidiaProviderAuthorities({ + zeta: receipt, + broken: { ...receipt, providerId: "" }, + alpha: receipt, + }), + ).toEqual({ alpha: receipt, zeta: receipt }); + }); +}); diff --git a/src/lib/state/registry/native-nvidia-provider-authority-state.ts b/src/lib/state/registry/native-nvidia-provider-authority-state.ts new file mode 100644 index 00000000000..192a739f716 --- /dev/null +++ b/src/lib/state/registry/native-nvidia-provider-authority-state.ts @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + normalizeNativeNvidiaProviderAttachment, + type NativeNvidiaProviderAttachment, +} from "../../inference/native-nvidia"; +import { isValidName } from "../../name-validation"; + +export interface NativeNvidiaProviderAuthorityState { + nativeNvidiaProviderAuthorities?: Record; +} + +export function normalizeNativeNvidiaProviderAuthorities( + value: unknown, +): Record | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const normalized: Record = Object.create(null); + for (const [gatewayName, candidate] of Object.entries(value)) { + const receipt = normalizeNativeNvidiaProviderAttachment(candidate); + if (!isValidName(gatewayName) || !receipt) continue; + normalized[gatewayName] = receipt; + } + const sorted = Object.fromEntries( + Object.entries(normalized).sort(([left], [right]) => left.localeCompare(right)), + ); + return Object.keys(sorted).length > 0 ? sorted : undefined; +} + +export function readNativeNvidiaProviderAuthority( + state: NativeNvidiaProviderAuthorityState, + gatewayName: string, +): NativeNvidiaProviderAttachment | undefined { + if (!isValidName(gatewayName)) return undefined; + return normalizeNativeNvidiaProviderAttachment( + state.nativeNvidiaProviderAuthorities?.[gatewayName], + ); +} + +export function applyNativeNvidiaProviderAuthority( + state: NativeNvidiaProviderAuthorityState, + gatewayName: string, + receipt: NativeNvidiaProviderAttachment, +): boolean { + const normalized = normalizeNativeNvidiaProviderAttachment(receipt); + if (!isValidName(gatewayName) || !normalized) return false; + const previous = readNativeNvidiaProviderAuthority(state, gatewayName); + if (previous?.providerId === normalized.providerId) return false; + state.nativeNvidiaProviderAuthorities = { + ...(state.nativeNvidiaProviderAuthorities ?? {}), + [gatewayName]: normalized, + }; + return true; +} + +export function removeNativeNvidiaProviderAuthority( + state: NativeNvidiaProviderAuthorityState, + gatewayName: string, +): boolean { + if (!isValidName(gatewayName) || !state.nativeNvidiaProviderAuthorities?.[gatewayName]) { + return false; + } + const next = { ...state.nativeNvidiaProviderAuthorities }; + delete next[gatewayName]; + if (Object.keys(next).length > 0) state.nativeNvidiaProviderAuthorities = next; + else delete state.nativeNvidiaProviderAuthorities; + return true; +} diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts new file mode 100644 index 00000000000..68599dfec2c --- /dev/null +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import { + applyNativeNvidiaProviderAuthority, + readNativeNvidiaProviderAuthority, + removeNativeNvidiaProviderAuthority as applyRemoveNativeNvidiaProviderAuthority, +} from "./native-nvidia-provider-authority-state"; +import { withLock } from "./lock"; +import { load, save } from "./persistence"; + +export function getNativeNvidiaProviderAuthority( + gatewayName: string, +): NativeNvidiaProviderAttachment | undefined { + return readNativeNvidiaProviderAuthority(load(), gatewayName); +} + +export function setNativeNvidiaProviderAuthority( + gatewayName: string, + receipt: NativeNvidiaProviderAttachment, +): void { + withLock(() => { + const data = load(); + const existing = readNativeNvidiaProviderAuthority(data, gatewayName); + if (existing?.providerId === receipt.providerId) return; + if (!applyNativeNvidiaProviderAuthority(data, gatewayName, receipt)) { + throw new Error("Cannot record invalid native NVIDIA gateway provider authority"); + } + save(data); + }); +} + +export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { + withLock(() => { + const data = load(); + if (!applyRemoveNativeNvidiaProviderAuthority(data, gatewayName)) return; + save(data); + }); +} diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index a4efa15b2da..57672142a8a 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -8,6 +8,7 @@ import { isDeferredN1xManagedVllmAcceptanceRoute } from "../../domain/sandbox/n1 import { parseServingProfileProvenance } from "../../inference/serving/profile-provenance"; import { readConfigFile, writeConfigFile } from "../config-io"; import { normalizeExtraProviders } from "../extra-providers"; +import { normalizeNativeNvidiaProviderAuthorities } from "./native-nvidia-provider-authority-state"; import { cloneSandboxMessagingState, serializeSandboxMessagingStateForDisk, @@ -124,6 +125,9 @@ export function save(data: SandboxRegistry): void { function normalizeRegistry(value: unknown): SandboxRegistry { const data = isObjectRecord(value) ? value : {}; const extraProviders = normalizeExtraProviders(data.extraProviders); + const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( + data.nativeNvidiaProviderAuthorities, + ); const sandboxes = Object.fromEntries( parseSandboxRegistryEntries(data.sandboxes).map(([name, entry]) => [ name, @@ -140,11 +144,17 @@ function normalizeRegistry(value: unknown): SandboxRegistry { sandboxes, }; if (extraProviders) base.extraProviders = extraProviders; + if (nativeNvidiaProviderAuthorities) { + base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; + } return base; } function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { const extraProviders = normalizeExtraProviders(data.extraProviders); + const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( + data.nativeNvidiaProviderAuthorities, + ); const sandboxes = Object.fromEntries( Object.entries(data.sandboxes).map(([name, entry]) => [ name, @@ -164,6 +174,9 @@ function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { sandboxes, }; if (extraProviders) base.extraProviders = extraProviders; + if (nativeNvidiaProviderAuthorities) { + base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; + } return base; } diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 336151236c1..b18e535c2b1 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -236,4 +236,6 @@ export interface SandboxRegistry { defaultSandbox: string | null; defaultSelectionRevision?: number; extraProviders?: string[]; + /** Exact NemoClaw-owned native NVIDIA provider identity for each OpenShell gateway. */ + nativeNvidiaProviderAuthorities?: Record; } From b18af4fc4b5a8b572ead526d45fba64529d8f61f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:31:03 -0700 Subject: [PATCH 044/133] test: isolate gateway doctor fixtures from native NVIDIA Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../doctor-observation-failure.test.ts | 14 +++++++---- test/cli/doctor-gateway-token.test.ts | 24 +++++++++++++------ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/src/lib/actions/sandbox/doctor-observation-failure.test.ts b/src/lib/actions/sandbox/doctor-observation-failure.test.ts index fe32bda3d03..d1347f70806 100644 --- a/src/lib/actions/sandbox/doctor-observation-failure.test.ts +++ b/src/lib/actions/sandbox/doctor-observation-failure.test.ts @@ -65,11 +65,15 @@ vi.mock("../../state/registry", () => ({ getSandbox: () => null, })); -vi.mock("./doctor-inference", () => ({ - collectInferenceChecks: () => [], - collectManagedLlamaCppDoctorChecks: () => [], - resolveDoctorReasoningEffort: () => undefined, -})); +vi.mock("./doctor-inference", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + collectInferenceChecks: () => [], + collectManagedLlamaCppDoctorChecks: () => [], + resolveDoctorReasoningEffort: () => undefined, + }; +}); vi.mock("./doctor-system-checks", async (importOriginal) => { const actual = await importOriginal(); diff --git a/test/cli/doctor-gateway-token.test.ts b/test/cli/doctor-gateway-token.test.ts index 7066b746c0e..5550b4b44f5 100644 --- a/test/cli/doctor-gateway-token.test.ts +++ b/test/cli/doctor-gateway-token.test.ts @@ -142,11 +142,14 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: build\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); // Docker-driver sandbox: no legacy `openshell-cluster-*` container exists. - writeDoctorSandboxRegistry(setup.home, "alpha", { openshellDriver: "docker" }); + writeDoctorSandboxRegistry(setup.home, "alpha", { + provider: "build", + openshellDriver: "docker", + }); // Record docker argv and make `docker inspect` fail like an absent legacy // container would. The doctor must not even attempt the inspect, so this // should never produce a failure — and we assert the call was skipped, not @@ -207,10 +210,11 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw-8090\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw-8090") printf "Gateway: nemoclaw-8090\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw-8090") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: build\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); writeDoctorSandboxRegistry(setup.home, "alpha", { + provider: "build", gatewayName: "nemoclaw-8090", gatewayPort: 8090, openshellDriver: "docker", @@ -274,10 +278,13 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: build\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); - writeDoctorSandboxRegistry(setup.home, "alpha", { openshellDriver: "kubernetes" }); + writeDoctorSandboxRegistry(setup.home, "alpha", { + provider: "build", + openshellDriver: "kubernetes", + }); const hostCalls = path.join(setup.home, "host-calls"); writeDockerInspectFailureStub(setup, hostCalls); @@ -368,11 +375,14 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: build\\nModel: test-model\\n"; exit 0 ;;', "esac", ], ); - writeDoctorSandboxRegistry(setup.home, "alpha", { openshellDriver: "kubernetes" }); + writeDoctorSandboxRegistry(setup.home, "alpha", { + provider: "build", + openshellDriver: "kubernetes", + }); const hostCalls = path.join(setup.home, "host-calls"); writeDockerInspectFailureStub(setup, hostCalls); writeLocalGatewayProbeStubs(setup, hostCalls, { From c0a0c703e3bd446db0c9d83e16feb7161633fc7f Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 14:47:18 -0700 Subject: [PATCH 045/133] fix(inference): enforce selected native provider ownership --- src/lib/actions/inference-set.ts | 6 +-- .../connect-flow-dcode-probe-preamble.test.ts | 19 +++---- src/lib/actions/sandbox/connect-flow.test.ts | 24 +++++---- .../sandbox/connect-route-containment.test.ts | 40 +++++++------- .../sandbox/connect-route-lifecycle.test.ts | 36 ++++++------- src/lib/actions/sandbox/doctor-flow.test.ts | 54 +++++++++++++++++++ .../actions/sandbox/doctor-inference.test.ts | 3 +- src/lib/actions/sandbox/doctor-inference.ts | 3 +- .../doctor-observation-failure.test.ts | 3 +- src/lib/actions/sandbox/doctor.ts | 1 + .../launch-readiness-gateway-health.test.ts | 21 ++++++++ .../actions/sandbox/launch-readiness.test.ts | 8 +-- .../sandbox/launch-readiness/health.ts | 7 ++- .../actions/sandbox/status-inference.test.ts | 29 ++++++++-- .../status-snapshot-inference-health.test.ts | 15 ++++-- .../status-snapshot-route-drift.test.ts | 36 +++++++++++++ src/lib/actions/sandbox/status-snapshot.ts | 3 +- src/lib/inference/README.md | 15 ++++-- .../inference-providers/hermes.test.ts | 2 +- .../orchestration-native-nvidia.test.ts | 27 ++++++++-- .../onboard/sandbox-create/orchestration.ts | 2 +- .../sandbox-create/provider-publication.ts | 6 ++- .../verify-deployment-inference-route.test.ts | 33 ++++++------ src/lib/verify-deployment.ts | 2 +- test/cli/doctor-gateway-token.test.ts | 16 +++--- test/cli/helpers.ts | 1 + ...rd-build-recreate-credential-reuse.test.ts | 1 + .../onboard-inference-reconciliation.test.ts | 1 + test/support/connect-flow-test-harness.ts | 2 +- test/support/setup-inference-test-harness.ts | 13 +++++ 30 files changed, 310 insertions(+), 119 deletions(-) diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 5dffc84031e..2bfae03ec78 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1063,7 +1063,7 @@ async function restorePreviousNativeHostedAfterFailedPublish(input: { const recoveryDetail = reattachError instanceof Error ? reattachError.message : String(reattachError); throw new InferenceSetError( - `${detail}\n Native NVIDIA access was detached before the failed switch, but restoring the attachment failed: ${recoveryDetail}`, + `${detail}\n Native hosted-provider access was detached before the failed switch, but restoring the attachment failed: ${recoveryDetail}`, input.error instanceof InferenceSetError ? input.error.exitCode : 1, ); } @@ -1080,7 +1080,7 @@ async function applyInferenceRouteSelection(input: { deps: InferenceSetDeps; }): Promise { if (input.nativeHosted) { - input.deps.log(` Using attached native NVIDIA provider: ${input.provider} / ${input.model}`); + input.deps.log(` Using attached native hosted provider: ${input.provider} / ${input.model}`); return false; } input.deps.log(` Setting OpenShell inference route: ${input.provider} / ${input.model}`); @@ -1787,7 +1787,7 @@ async function runInferenceSetWithoutHostLock( } } - // Removing native NVIDIA access is a security gate for publishing another + // Removing native hosted access is a security gate for publishing another // route. Do not commit the non-native registry/config while the sandbox can // still use the credential-bearing attached provider. previousNativeHostedDetached = await detachPreviousNativeHostedBeforePublish({ diff --git a/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts b/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts index 4b86a295c55..c01b1856d2d 100644 --- a/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts +++ b/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts @@ -76,10 +76,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, - inferenceGetOutput: "Provider: nvidia-prod\nModel: nvidia/nemotron-3-super-120b-a12b\n", + inferenceGetOutput: + "Provider: custom-shared-provider\nModel: nvidia/nemotron-3-super-120b-a12b\n", sessionAgent: { name: "langchain-deepagents-code" }, }); const runBuffered = harness.sandboxRunBufferedSpy.getMockImplementation()!; @@ -111,7 +112,7 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", sessionAgent: { name: "langchain-deepagents-code" }, - registryEntry: { provider: "nvidia-prod", model: "nvidia/nemotron", ...missing }, + registryEntry: { provider: "custom-shared-provider", model: "nvidia/nemotron", ...missing }, }); await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(1)"); @@ -127,11 +128,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [output], sessionAgent: { name: "langchain-deepagents-code" }, }); @@ -153,11 +154,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [ { status: 0, @@ -188,11 +189,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [`exec: ${DCODE_MANAGED_EXEC_LAUNCHER}: not found`], sessionAgent: { name: "langchain-deepagents-code" }, }); diff --git a/src/lib/actions/sandbox/connect-flow.test.ts b/src/lib/actions/sandbox/connect-flow.test.ts index 3bdc1ae7a5d..012733694e0 100644 --- a/src/lib/actions/sandbox/connect-flow.test.ts +++ b/src/lib/actions/sandbox/connect-flow.test.ts @@ -67,7 +67,7 @@ function configureAlignedInferenceGet(harness: ReturnType { registry.getSandbox.mockReturnValue({ name: "alpha", agent: "langchain-deepagents-code", - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", gpuEnabled: false, }); @@ -243,7 +243,7 @@ describe("connectSandbox flow", () => { { status: 0, output: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", }, ], ["sandbox exec", { status: 0, output: "OK 200" }], @@ -335,10 +335,11 @@ describe("connectSandbox flow", () => { const longProbeDetail = `route probe unavailable NVIDIA_API_KEY=super-secret ${"x".repeat(400)}`; const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, - inferenceGetOutput: "Provider: nvidia-prod\nModel: nvidia/nemotron-3-super-120b-a12b\n", + inferenceGetOutput: + "Provider: custom-shared-provider\nModel: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [longProbeDetail], }); @@ -363,7 +364,7 @@ describe("connectSandbox flow", () => { it("fails closed without repair when the route probe transport throws (#6192)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -389,7 +390,7 @@ describe("connectSandbox flow", () => { it("fails closed without repair when the route probe transport times out (#6192)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -426,7 +427,7 @@ describe("connectSandbox flow", () => { it("fails closed without repair when the OpenShell CA boundary is unavailable (#6192)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -826,10 +827,11 @@ describe("connectSandbox flow", () => { it("probe-only mode exits before reporting success when inference.local returns no trusted result (#8502)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, - inferenceGetOutput: "Provider: nvidia-prod\nModel: nvidia/nemotron-3-super-120b-a12b\n", + inferenceGetOutput: + "Provider: custom-shared-provider\nModel: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: ["route probe unavailable"], }); @@ -1031,7 +1033,7 @@ describe("connectSandbox flow", () => { "mismatched", { inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/other-model\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/other-model\n", }, ], ["unreachable", { inferenceProbeResponses: ["BROKEN 503"] }], diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index c1e58e4cb33..7e8d85ea6d7 100644 --- a/src/lib/actions/sandbox/connect-route-containment.test.ts +++ b/src/lib/actions/sandbox/connect-route-containment.test.ts @@ -57,7 +57,7 @@ describe("connect route containment", () => { const sandbox: SandboxEntry = { name: "demo", model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", openshellDriver: "vm", gpuEnabled: false, }; @@ -79,12 +79,12 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "anthropic-prod", + provider: "other-shared-provider", model: "claude-sonnet-4-20250514", } as const; const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: alpha, registryEntries: [ alpha, @@ -93,7 +93,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, ], @@ -109,7 +109,7 @@ describe("connect route containment", () => { "inference", "set", "--provider", - "anthropic-prod", + "other-shared-provider", "--model", "claude-sonnet-4-20250514", ]), @@ -120,7 +120,7 @@ describe("connect route containment", () => { const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); expect(errorOutput).toContain("differs from the recorded route for sandbox 'alpha'"); expect(errorOutput).toContain( - "Aligning the gateway to anthropic-prod/claude-sonnet-4-20250514", + "Aligning the gateway to other-shared-provider/claude-sonnet-4-20250514", ); expect(exitSpy).not.toHaveBeenCalled(); }); @@ -205,7 +205,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/model-a", } as const; const harness = createConnectHarness({ @@ -223,7 +223,7 @@ describe("connect route containment", () => { await lockEntered; const peer = harness.registryEntries.find((candidate) => candidate.name === "peer"); expect(peer).toBeDefined(); - Object.assign(peer!, { provider: "anthropic-prod", model: "claude-new" }); + Object.assign(peer!, { provider: "other-shared-provider", model: "claude-new" }); releaseLock(); await expect(connect).resolves.toBeUndefined(); @@ -236,7 +236,7 @@ describe("connect route containment", () => { expect.objectContaining({ ignoreError: true, timeout: 15_000 }), ); expect(harness.runOpenshellSpy).toHaveBeenCalledWith( - expect.arrayContaining(["inference", "set", "--provider", "nvidia-prod"]), + expect.arrayContaining(["inference", "set", "--provider", "custom-shared-provider"]), expect.any(Object), ); expect(exitSpy).not.toHaveBeenCalled(); @@ -303,7 +303,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/model-a", } as const; const harness = createConnectHarness({ @@ -350,7 +350,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -381,7 +381,7 @@ describe("connect route containment", () => { name: "alpha", pendingRouteReservation: true, gatewayName: "nemoclaw", - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/model-a", }, }); @@ -398,7 +398,7 @@ describe("connect route containment", () => { it("exits before repairing a lone incomplete legacy custom route (#6315)", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: { name: "alpha", agent: "openclaw", @@ -436,12 +436,12 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", } as const; const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: alpha, registryEntries: [ alpha, @@ -450,7 +450,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "anthropic-prod", + provider: "other-shared-provider", model: "claude-sonnet-4-20250514", }, ], @@ -473,12 +473,12 @@ describe("connect route containment", () => { gatewayName: "nemoclaw-9090", gatewayPort: 9090, openshellDriver: "docker", - provider: "anthropic-prod", + provider: "other-shared-provider", model: "claude-sonnet-4-20250514", } as const; const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: ["BROKEN 503", "BROKEN 503", "OK 200"], registryEntry: alpha, registryEntries: [ @@ -488,7 +488,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, ], @@ -513,7 +513,7 @@ describe("connect route containment", () => { "nemoclaw-9090", "--no-verify", "--provider", - "anthropic-prod", + "other-shared-provider", "--model", "claude-sonnet-4-20250514", ]); diff --git a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts index db1ef3bd89d..72c6a19c0cb 100644 --- a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts +++ b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts @@ -46,10 +46,10 @@ describe("connectSandbox route lifecycle", () => { it("warns and aligns a diverged route during a quiet probe-only connect (#3726)", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: { model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "other-shared-provider", }, }); @@ -58,10 +58,10 @@ describe("connectSandbox route lifecycle", () => { const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); expect(errorOutput).toContain("differs from the recorded route"); expect(errorOutput).toContain( - "Aligning the gateway to anthropic-prod/claude-sonnet-4-20250514", + "Aligning the gateway to other-shared-provider/claude-sonnet-4-20250514", ); expect(errorOutput).toContain( - "nemoclaw inference set --provider 'nvidia-prod' --model 'nvidia/nemotron-3-super-120b-a12b' --sandbox 'alpha'", + "nemoclaw inference set --provider 'custom-shared-provider' --model 'nvidia/nemotron-3-super-120b-a12b' --sandbox 'alpha'", ); expect(harness.runOpenshellSpy).toHaveBeenCalledWith( [ @@ -71,7 +71,7 @@ describe("connectSandbox route lifecycle", () => { "nemoclaw", "--no-verify", "--provider", - "anthropic-prod", + "other-shared-provider", "--model", "claude-sonnet-4-20250514", ], @@ -87,11 +87,11 @@ describe("connectSandbox route lifecycle", () => { it("stops after an ambiguous route swap before probing or attempting repair", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/old-model\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/old-model\n", inferenceSetResult: { status: null, output: "", signal: "SIGTERM" }, registryEntry: { model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "other-shared-provider", }, }); @@ -165,7 +165,7 @@ describe("connectSandbox route lifecycle", () => { registryEntry: { name: sandboxName, model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "other-shared-provider", }, }); @@ -187,12 +187,12 @@ describe("connectSandbox route lifecycle", () => { try { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: ['BROKEN 503 {"error":"inference service unavailable"}', "OK 200"], registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", openshellDriver: "vm", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); @@ -215,10 +215,10 @@ describe("connectSandbox route lifecycle", () => { it.each([ ["null", null, null], - ["provider-only", "nvidia-prod", null], + ["provider-only", "custom-shared-provider", null], ["model-only", null, "nvidia/test"], ["blank-provider", " ", "nvidia/test"], - ["blank-model", "nvidia-prod", " "], + ["blank-model", "custom-shared-provider", " "], ] as const)( "skips inference reconciliation for %s registry entries (#5937)", async (_description, provider, model) => { @@ -237,10 +237,10 @@ describe("connectSandbox route lifecycle", () => { it("does not reset an inference route that already matches the sandbox", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); @@ -257,7 +257,7 @@ describe("connectSandbox route lifecycle", () => { const harness = createConnectHarness({ registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); harness.captureOpenshellSpy @@ -285,12 +285,12 @@ describe("connectSandbox route lifecycle", () => { it("stops before opening SSH when route repair and reset both fail", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: Array(7).fill('BROKEN 503 {"error":"upstream unavailable"}'), registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", openshellDriver: "kubernetes", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); @@ -306,7 +306,7 @@ describe("connectSandbox route lifecycle", () => { "nemoclaw", "--no-verify", "--provider", - "nvidia-prod", + "custom-shared-provider", "--model", "nvidia/nemotron-3-super-120b-a12b", ], diff --git a/src/lib/actions/sandbox/doctor-flow.test.ts b/src/lib/actions/sandbox/doctor-flow.test.ts index 366e66846c2..0f28f4fe804 100644 --- a/src/lib/actions/sandbox/doctor-flow.test.ts +++ b/src/lib/actions/sandbox/doctor-flow.test.ts @@ -667,6 +667,60 @@ describe("runSandboxDoctor flow", () => { }, ); + it("keeps native OpenAI selection, gateway and Responses mode when the shared route differs", async () => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "owned-openai", + }; + const harness = createDoctorHarness("openai-api", { + registryOverrides: { + nativeHostedProviderAttachment: receipt, + preferredInferenceApi: "openai-responses", + }, + }); + const originalCapture = harness.captureOpenShellSpy.getMockImplementation()!; + harness.captureOpenShellSpy.mockImplementation((args: string[], ...rest: unknown[]) => + args[0] === "inference" && args[1] === "get" + ? { status: 0, output: "Provider: nvidia-prod\nModel: unrelated-model\n" } + : originalCapture(args, ...rest), + ); + const verify = vi + .spyOn(requireDist("./inference-route-health.js"), "verifyNativeHostedStatusAttachment") + .mockResolvedValue(undefined); + const invoke = vi + .spyOn(requireDist("./inference-invocation-probe.js"), "probeSandboxInferenceInvocation") + .mockResolvedValue({ ok: true }); + const report = await harness.runSandboxDoctor("alpha", ["--json"], { quietJson: true }); + expect(harness.captureOpenShellSpy).not.toHaveBeenCalledWith( + expect.arrayContaining(["inference", "get"]), + expect.anything(), + ); + expect(harness.probeSandboxInferenceGatewayHealthSpy).not.toHaveBeenCalled(); + expect(verify).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", + expected: receipt, + }); + expect(invoke).toHaveBeenCalledWith( + { + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", + provider: "openai-api", + model: "registry-model", + agentName: "openclaw", + preferredInferenceApi: "openai-responses", + nativeProvider: true, + }, + {}, + 95000, + ); + expect(report?.checks).toContainEqual( + expect.objectContaining({ label: "Inference route (native OpenAI)", status: "ok" }), + ); + }); + it("rejects mutating --fix when JSON output was requested", async () => { const harness = createDoctorHarness(); diff --git a/src/lib/actions/sandbox/doctor-inference.test.ts b/src/lib/actions/sandbox/doctor-inference.test.ts index 532fcc96d53..137e703bbb7 100644 --- a/src/lib/actions/sandbox/doctor-inference.test.ts +++ b/src/lib/actions/sandbox/doctor-inference.test.ts @@ -50,6 +50,7 @@ describe("doctor inference checks", () => { { provider: profile.logicalProvider, model: "selected-model", + preferredInferenceApi: "openai-responses", agentName: "hermes", nativeHostedProviderAttachment: receipt, }, @@ -74,7 +75,7 @@ describe("doctor inference checks", () => { agentName: "hermes", provider: profile.logicalProvider, model: "selected-model", - preferredInferenceApi: null, + preferredInferenceApi: "openai-responses", nativeProvider: true, }, {}, diff --git a/src/lib/actions/sandbox/doctor-inference.ts b/src/lib/actions/sandbox/doctor-inference.ts index b9a998b26e1..cdddcd09978 100644 --- a/src/lib/actions/sandbox/doctor-inference.ts +++ b/src/lib/actions/sandbox/doctor-inference.ts @@ -41,6 +41,7 @@ import { export type DoctorInferenceRoute = { model: string; provider: string; + preferredInferenceApi?: string | null; effectiveReasoningEffort?: EffectiveReasoningEffort | null; /** Sandbox route endpoint recorded at onboard; selects the bearerless local vLLM host port. */ recordedEndpointUrl?: string | null; @@ -147,7 +148,7 @@ async function collectNativeHostedRouteProbe( agentName: route.agentName, provider: route.provider, model: route.model, - preferredInferenceApi: null, + preferredInferenceApi: route.preferredInferenceApi ?? null, nativeProvider: true, }, {}, diff --git a/src/lib/actions/sandbox/doctor-observation-failure.test.ts b/src/lib/actions/sandbox/doctor-observation-failure.test.ts index fe32bda3d03..617ca13ea10 100644 --- a/src/lib/actions/sandbox/doctor-observation-failure.test.ts +++ b/src/lib/actions/sandbox/doctor-observation-failure.test.ts @@ -65,7 +65,8 @@ vi.mock("../../state/registry", () => ({ getSandbox: () => null, })); -vi.mock("./doctor-inference", () => ({ +vi.mock("./doctor-inference", async (importOriginal) => ({ + ...(await importOriginal()), collectInferenceChecks: () => [], collectManagedLlamaCppDoctorChecks: () => [], resolveDoctorReasoningEffort: () => undefined, diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index 0b4238965f7..b896cd99dd4 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -407,6 +407,7 @@ async function resolveInferenceRoute( provider: live?.provider || sb?.provider || "unknown", effectiveReasoningEffort: resolveDoctorReasoningEffort(sb), recordedEndpointUrl: sb?.endpointUrl, + preferredInferenceApi: sb?.preferredInferenceApi, agentName: sb?.agent, nativeHostedProviderAttachment: normalizeNativeHostedProviderAttachment( sb?.nativeHostedProviderAttachment ?? sb?.nativeNvidiaProviderAttachment, diff --git a/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts b/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts index f7f02f1af84..590a874b562 100644 --- a/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { execFileSync } from "node:child_process"; import { describe, expect, it, vi } from "vitest"; @@ -9,6 +10,7 @@ import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/ope import { loadAgent } from "../../agent/defs"; import type { SandboxEntry } from "../../state/registry"; import { + getNativeHostedProviderAttachment, LaunchReadinessEvidenceError, LaunchReadinessObservationError, requireLaunchSemanticHealth, @@ -20,6 +22,16 @@ import { } from "./process-recovery"; describe("launch-readiness gateway health scope", () => { + it("refuses native readiness without an ownership receipt", () => { + expect(() => + getNativeHostedProviderAttachment({ + name: "alpha", + provider: "openai-api", + model: "selected", + } as SandboxEntry), + ).toThrow(LaunchReadinessEvidenceError); + }); + it.each([ ["becomes observable", [null, null, null, null, null, true], true], ["remains unavailable", [null, null, null, null, null, null], false], @@ -208,7 +220,14 @@ const MODEL = "nvidia/nemotron-3-ultra-550b-a55b"; const dcodeAgent = loadAgent("langchain-deepagents-code"); function dcodeEntry(provider = "openrouter-api"): SandboxEntry { + const profile = nativeHostedProfile(provider)!; return { + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "owned", + }, name: SANDBOX, agent: "langchain-deepagents-code", provider, @@ -224,6 +243,7 @@ function dcodeHealthDeps( httpStatus = 404, ): LaunchReadinessHealthDeps { return { + verifyNativeHostedAttachment: vi.fn(async () => undefined), smoke: vi.fn(async () => ({ ok: true }) as const), inferenceProbe: vi.fn(async () => ({ healthy: true, @@ -278,6 +298,7 @@ describe("Deep Agents Code launch readiness", () => { provider, model: MODEL, preferredInferenceApi: null, + nativeProvider: true, }); }); diff --git a/src/lib/actions/sandbox/launch-readiness.test.ts b/src/lib/actions/sandbox/launch-readiness.test.ts index 877a0cfdef6..e5b66fe68af 100644 --- a/src/lib/actions/sandbox/launch-readiness.test.ts +++ b/src/lib/actions/sandbox/launch-readiness.test.ts @@ -970,11 +970,11 @@ describe("launch readiness validation", () => { it("uses terminal-agent smoke health for a supported non-OpenClaw runtime", async () => { sandbox = { ...entry("langchain-deepagents-code"), - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "model-a", credentialEnv: "NVIDIA_API_KEY", }; - routeOutput = "Gateway Inference:\n\n Provider: nvidia-prod\n Model: model-a\n"; + routeOutput = "Gateway Inference:\n\n Provider: custom-shared-provider\n Model: model-a\n"; const currentDeps = deps(); currentDeps.inferenceInvocationProbe = async () => ({ ok: true }); const gatewayHealth = vi.fn(async () => true); @@ -996,11 +996,11 @@ describe("launch readiness validation", () => { it("rejects a Deep Agents Code lease when model discovery succeeds but inference fails (#11520)", async () => { sandbox = { ...entry("langchain-deepagents-code"), - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "model-a", credentialEnv: "NVIDIA_API_KEY", }; - routeOutput = "Gateway Inference:\n\n Provider: nvidia-prod\n Model: model-a\n"; + routeOutput = "Gateway Inference:\n\n Provider: custom-shared-provider\n Model: model-a\n"; const currentDeps = deps(); currentDeps.inferenceInvocationProbe = vi.fn(async () => ({ ok: true }) as const); await createAcceptedLease(currentDeps); diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index d499a8d837f..46e5a59704a 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -211,8 +211,11 @@ export function resolveTrustedLaunchAgent( export function getNativeHostedProviderAttachment( entry: SandboxEntry, ): NativeHostedProviderAttachment | null { - const receipt = normalizeNativeHostedProviderAttachment(entry.nativeHostedProviderAttachment); - if (receipt && nativeHostedProfile(entry.provider)?.profileId !== receipt.profileId) { + const receipt = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment, + ); + const profile = nativeHostedProfile(entry.provider); + if ((profile && !receipt) || (receipt && profile?.profileId !== receipt.profileId)) { throw new LaunchReadinessEvidenceError(); } return receipt ?? null; diff --git a/src/lib/actions/sandbox/status-inference.test.ts b/src/lib/actions/sandbox/status-inference.test.ts index c6f72d5a9ae..7c89a9bf026 100644 --- a/src/lib/actions/sandbox/status-inference.test.ts +++ b/src/lib/actions/sandbox/status-inference.test.ts @@ -47,7 +47,7 @@ describe("sandbox status inference.local route health (#6192)", () => { } | null; routeProbeThrows?: boolean; }) { - const provider = options.provider ?? "nvidia-prod"; + const provider = options.provider ?? "custom-shared-provider"; const reportInferenceProbeError = vi.fn(); let sandbox = { name: "alpha", @@ -274,7 +274,7 @@ describe("sandbox status inference.local route health (#6192)", () => { expect(report.servingProcessHealth).toBeNull(); }); - it.each(["nvidia-router", "hermes-provider"])( + it.each(["nvidia-router", "custom-shared-provider"])( "probes inference.local for %s without a direct health probe (#6192)", async (provider) => { const deps = snapshotDeps({ @@ -297,6 +297,25 @@ describe("sandbox status inference.local route health (#6192)", () => { }, ); + it("refuses Hermes Provider without native ownership instead of probing the shared route", async () => { + const deps = snapshotDeps({ + provider: "hermes-provider", + routeHealth: { + ok: true, + endpoint: "https://inference.local/v1/models", + httpStatus: 200, + detail: "unrelated shared route reachable", + }, + }); + + const snapshot = await collectSandboxStatusSnapshot("alpha", { deps }); + + expect(snapshot.inferenceHealth).toMatchObject({ ok: false, probed: false }); + expect(deps.inferenceRouteObserver.observeInferenceRoute).not.toHaveBeenCalled(); + expect(deps.probeSandboxInferenceGatewayHealthImpl).not.toHaveBeenCalled(); + expect(deps.probeSandboxInferenceInvocationImpl).not.toHaveBeenCalled(); + }); + it("keeps an upstream failure diagnostic when inference.local is healthy (#6192)", async () => { const deps = snapshotDeps({ providerHealth: { @@ -325,7 +344,7 @@ describe("sandbox status inference.local route health (#6192)", () => { it("probes the live route while status displays the sandbox's recorded route (#6315)", async () => { const deps = snapshotDeps({ - provider: "nvidia-prod", + provider: "custom-shared-provider", liveProvider: "openai-api", liveModel: "gpt-5.2", routeHealth: { @@ -338,11 +357,11 @@ describe("sandbox status inference.local route health (#6192)", () => { const snapshot = await collectSandboxStatusSnapshot("alpha", { deps }); - expect(snapshot.currentProvider).toBe("nvidia-prod"); + expect(snapshot.currentProvider).toBe("custom-shared-provider"); expect(snapshot.currentModel).toBe("nvidia/nemotron"); expect(snapshot.routeDrift).toEqual({ live: { provider: "openai-api", model: "gpt-5.2" }, - recorded: { provider: "nvidia-prod", model: "nvidia/nemotron" }, + recorded: { provider: "custom-shared-provider", model: "nvidia/nemotron" }, canConnect: true, }); expect(deps.probeProviderHealthImpl).toHaveBeenCalledWith("openai-api", { diff --git a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts index d3d21967af5..9e47f7bce78 100644 --- a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -605,7 +605,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { expect(snapshot.inferenceHealth?.okLabel).toBeUndefined(); }); - it("reports a Deep Agents Code OpenRouter 404 route as ready once an invocation succeeds (#10080)", async () => { + it("reports native Deep Agents Code OpenRouter ready only after a verified invocation (#10080)", async () => { const gateway: SandboxInferenceRouteHealth = { ok: true, endpoint: "https://inference.local/v1/models", @@ -621,6 +621,12 @@ describe("collectSandboxStatusSnapshot inference route health", () => { { agent: "langchain-deepagents-code", gatewayName: "nemoclaw-19080", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "owned", + }, provider: "openrouter-api", model: "openai/gpt-4o-mini", }, @@ -631,6 +637,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { ...options, deps: { ...options.deps, + verifyNativeHostedProviderAttachmentImpl: async () => undefined, probeSandboxInferenceGatewayHealthImpl, probeSandboxInferenceInvocationImpl, }, @@ -644,14 +651,12 @@ describe("collectSandboxStatusSnapshot inference route health", () => { provider: "openrouter-api", model: "openai/gpt-4o-mini", preferredInferenceApi: null, + nativeProvider: true, }, {}, 95_000, ); - expect(probeSandboxInferenceGatewayHealthImpl).toHaveBeenCalledWith("alpha", { - gatewayName: "nemoclaw-19080", - }); - expect(probeSandboxInferenceGatewayHealthImpl).toHaveBeenCalledOnce(); + expect(probeSandboxInferenceGatewayHealthImpl).not.toHaveBeenCalled(); expect(snapshot.inferenceHealth).toMatchObject({ ok: true }); }); diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index c3294e82390..2de70a76f80 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -623,6 +623,42 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = }, ); + it("never falls back to a shared route when a native selection has no receipt", async () => { + const sandbox = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "selected-model", + } as SandboxEntry; + const observe = vi.fn(async () => ({ + ok: true, + value: { state: "configured", route: { provider: "nvidia-prod", model: "unrelated" } }, + })); + const shared = vi.fn(async () => ({ + ok: true, + endpoint: "https://inference.local/v1/models", + httpStatus: 200, + detail: "healthy", + })); + const invoke = vi.fn(async () => ({ ok: true })); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + inferenceRouteObserver: { observeInferenceRoute: observe }, + probeProviderHealthImpl: () => null, + probeSandboxInferenceGatewayHealthImpl: shared, + probeSandboxInferenceInvocationImpl: invoke, + }, + } as never); + expect(observe).not.toHaveBeenCalled(); + expect(shared).not.toHaveBeenCalled(); + expect(invoke).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toMatchObject({ ok: false, probed: false }); + }); + it("refuses a native receipt for a different recorded provider before probing", async () => { const sandbox: SandboxEntry = { name: "alpha", diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index db66e9fe4bf..ee8947a093f 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -573,7 +573,7 @@ export async function collectSandboxStatusSnapshot( const nativeHostedAttachment = normalizeNativeHostedProviderAttachment( sb?.nativeHostedProviderAttachment ?? sb?.nativeNvidiaProviderAttachment, ); - const nativeHosted = Boolean(nativeHostedAttachment); + const nativeHosted = Boolean(nativeHostedProfile(sb?.provider) || nativeHostedAttachment); const nativeAttachmentLabel = nativeNvidiaAttachment ? "Native NVIDIA" : "Native hosted"; if (lookup.state === "present") { try { @@ -945,6 +945,7 @@ async function buildSandboxStatusReport( sb && deps.getGatewayPresets ? await deps.getGatewayPresets(sandboxName, undefined, sb) : []; const agent = resolveSandboxStatusAgent(sb?.agent || "openclaw"); const nativeHosted = Boolean( + nativeHostedProfile(sb?.provider) || normalizeNativeHostedProviderAttachment( sb?.nativeHostedProviderAttachment ?? sb?.nativeNvidiaProviderAttachment, ), diff --git a/src/lib/inference/README.md b/src/lib/inference/README.md index d8189bb5e68..fc5ba7280b1 100644 --- a/src/lib/inference/README.md +++ b/src/lib/inference/README.md @@ -34,15 +34,22 @@ Credential values remain in OpenShell. Sandbox configuration contains only a pla `native-hosted/index.ts` owns profile import, provider identity checks, attachment, and confirmed removal. The registry records the selected attachment in `nativeHostedProviderAttachment`. +Credential registration also retains ownership by gateway and profile before any sandbox uses the +provider. Onboarding and inference selection reconcile those receipts with sandbox ownership before +reuse. Reset removes the selected provider's gateway receipt only after deletion is confirmed; +a failed deletion preserves it. Switching providers retains prior ownership without retaining access. The persistence boundary also reads Slice 1's `nativeNvidiaProviderAttachment` field without changing its provider identity. Selection does not update the shared `inference.local` route. A switch retains `pendingNativeHostedProviderDetach` until OpenShell confirms removal of the previous attachment. Retries complete that cleanup before applying another selection. -Existing beta sandboxes without an attachment receipt require recreation. +Existing beta sandboxes without an attachment receipt require recreation. Status, doctor, connect, +and launch readiness must refuse missing or mismatched ownership; they must not substitute the shared +route. Native probes preserve the selected API protocol and the recorded gateway. Custom endpoints and local providers retain their existing routing behavior. -V1alpha1 configuration export does not yet represent native profile attachments. -Native sandboxes require an exporter follow-up; exporting an older shared-route sandbox -continues to verify its original image endpoint without implicitly migrating it. +V1alpha1 configuration export supports native NVIDIA attachments. Other native hosted +profiles require an exporter follow-up and are refused before publication. Exporting an +older shared-route sandbox continues to verify its original image endpoint without +implicitly migrating it. Agent configuration preserves the provider's API protocol and native base URL. OpenRouter attribution comes from `native-hosted/openrouter-headers.ts` and is configured in each supported agent. diff --git a/src/lib/onboard/inference-providers/hermes.test.ts b/src/lib/onboard/inference-providers/hermes.test.ts index 6a05cbaa7aa..a7c557edd12 100644 --- a/src/lib/onboard/inference-providers/hermes.test.ts +++ b/src/lib/onboard/inference-providers/hermes.test.ts @@ -432,7 +432,7 @@ describe("native Hermes inference preparation", () => { }, deps as any, ), - ).resolves.toEqual({ ok: true }); + ).resolves.toEqual({ ok: true, nativeHostedProviderAttachment: expected }); expect(deps.hermesProviderAuth.ensureHermesProviderApiKeyCredentials).toHaveBeenCalledWith( "alpha", expect.objectContaining({ expected }), diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index 2118c865cbe..184e35a8f46 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -27,7 +27,10 @@ function providerAdapter(providerId: string): OpenShellProviderAdapter { } as unknown as OpenShellProviderAdapter; } -function nativeProviderBoundary(adapter: OpenShellProviderAdapter) { +function nativeProviderBoundary( + adapter: OpenShellProviderAdapter, + inferenceProvider = "nemoclaw-nvidia-prod-v1", +) { return createProviderEffectBoundary({ deferred: false, sandboxName: "alpha", @@ -40,7 +43,7 @@ function nativeProviderBoundary(adapter: OpenShellProviderAdapter) { }, preparationInput: { openshellDriver: "docker", - inferenceProvider: "nemoclaw-nvidia-prod-v1", + inferenceProvider, messagingProviders: [], messagingProviderRequests: [], extraProviders: [], @@ -80,7 +83,7 @@ describe("native NVIDIA post-create provider verification", () => { ).resolves.toBeUndefined(); expect(revalidateSandboxIdentity).toHaveBeenCalledWith( - "attaching and verifying native NVIDIA provider for sandbox 'alpha'", + "attaching and verifying native hosted provider for sandbox 'alpha'", ); expect(adapter.listProviderAttachments).toHaveBeenCalledWith( expect.objectContaining({ sandboxName: "alpha" }), @@ -113,13 +116,27 @@ describe("native NVIDIA post-create provider verification", () => { expect(adapter.listProviderAttachments).toHaveBeenCalledTimes(2); }); - it("rejects a replaced provider before inspecting its sandbox attachments", async () => { + it("rejects an ownership receipt for a different selected native provider before gateway access", async () => { + const adapter = providerAdapter(recordedProviderId); + const boundary = nativeProviderBoundary(adapter, "nemoclaw-openai-api-v1"); + + await expect(boundary.runAfterVerifiedCreate?.(verifiedCreateContext())).rejects.toThrow( + /does not match the selected profile/u, + ); + expect(adapter.getProvider).not.toHaveBeenCalled(); + expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); + }); + + it("rejects a replaced provider before changing its sandbox attachments", async () => { const adapter = providerAdapter("99999999-2222-4333-8444-555555555555"); + adapter.attachProvider = vi.fn(); + adapter.detachProvider = vi.fn(); const boundary = nativeProviderBoundary(adapter); await expect(boundary.runAfterVerifiedCreate?.(verifiedCreateContext())).rejects.toThrow( /changed identity.*Recreate the sandbox/u, ); - expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); + expect(adapter.attachProvider).not.toHaveBeenCalled(); + expect(adapter.detachProvider).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index cbeb95d7e24..9014594cd14 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1438,7 +1438,7 @@ export function createProviderEffectBoundary(input: { if (!usesNativeHostedProvider(input.preparationInput.inferenceProvider)) return; context.revalidateSandboxIdentity( - `attaching and verifying native NVIDIA provider for sandbox '${input.sandboxName}'`, + `attaching and verifying native hosted provider for sandbox '${input.sandboxName}'`, ); await verifyNativeHostedAttachmentAfterCreate({ sandboxName: input.sandboxName, diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index 8df9eeeef26..e187e34a91f 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -74,13 +74,17 @@ export async function verifyNativeHostedAttachmentAfterCreate(input: { readonly expected: SandboxEntry["nativeHostedProviderAttachment"]; readonly deps: ProviderPreparationDeps; }): Promise { - if (!usesNativeHostedProvider(input.inferenceProvider)) return; + const profile = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.providerName === input.inferenceProvider, + ); + if (!profile) return; if (!input.expected) { throw new Error( `Sandbox '${input.sandboxName}' is missing its native hosted provider identity receipt.`, ); } await ensureNativeHostedProviderAttached({ + profile, adapter: resolveProviderAdapter(input.deps), target: namedOpenShellGateway(input.gatewayName), sandboxName: input.sandboxName, diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index af10eae7017..05cebf674a3 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -62,7 +62,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { it("fails the deployment when the models route returns HTTP 404 (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, - inferenceRouteContext: { agentName: "openclaw", provider: "openrouter-api" }, + inferenceRouteContext: { agentName: "openclaw", provider: "custom-shared-provider" }, }); expect(result.verification.inferenceRouteWorking).toBe(false); @@ -72,7 +72,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { it("names the unvalidated model catalog as the reason for a 404 (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, - inferenceRouteContext: { agentName: "openclaw", provider: "openrouter-api" }, + inferenceRouteContext: { agentName: "openclaw", provider: "custom-shared-provider" }, }); const inference = result.diagnostics.find((entry) => entry.link === "inference"); @@ -95,7 +95,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { it("keeps a credential-gated HTTP 401 models route healthy (#2342)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("401"), { ...NO_RETRY, - inferenceRouteContext: { agentName: "openclaw", provider: "openrouter-api" }, + inferenceRouteContext: { agentName: "openclaw", provider: "custom-shared-provider" }, }); expect(result.verification.inferenceRouteWorking).toBe(true); @@ -131,7 +131,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.verification.inferenceRouteWorking).toBe(false); }); - it("accepts the Deep Agents Code OpenRouter 404 when an inference request succeeds (#9834)", async () => { + it("accepts native Deep Agents Code OpenRouter when an inference request succeeds", async () => { const result = await verifyDeployment( "my-sandbox", buildChain(), @@ -145,7 +145,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.verification.inferenceRouteWorking).toBe(true); }); - it("fails the Deep Agents Code OpenRouter 404 when the inference request fails (#10543)", async () => { + it("fails native Deep Agents Code OpenRouter when the inference request fails", async () => { const result = await verifyDeployment( "my-sandbox", buildChain(), @@ -161,7 +161,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.verification.inferenceRouteWorking).toBe(false); }); - it("fails the Deep Agents Code OpenRouter 404 when no invocation probe is wired (#10543)", async () => { + it("fails native Deep Agents Code OpenRouter when no invocation probe is wired", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, inferenceRouteContext: { agentName: DCODE_AGENT, provider: "openrouter-api" }, @@ -170,7 +170,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.verification.inferenceRouteWorking).toBe(false); }); - it("points a failed by-design 404 at the inference request, not the model catalog (#10543)", async () => { + it("reports the native provider credential and model when invocation fails", async () => { const result = await verifyDeployment( "my-sandbox", buildChain(), @@ -184,14 +184,15 @@ describe("verifyDeployment inference route model-catalog validation", () => { ); const inference = result.diagnostics.find((entry) => entry.link === "inference"); - expect(inference?.hint).toContain("serve no model catalog"); + expect(inference?.detail).toContain("HTTP 401"); + expect(inference?.hint).toContain("provider credential and model"); expect(inference?.hint).not.toContain("endpoint serves"); }); it("tells a plain 404 to make the model catalog available (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, - inferenceRouteContext: { agentName: "openclaw", provider: "openrouter-api" }, + inferenceRouteContext: { agentName: "openclaw", provider: "custom-shared-provider" }, }); const inference = result.diagnostics.find((entry) => entry.link === "inference"); @@ -202,7 +203,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { it("fails a 404 for the default agent that onboarding leaves unnamed (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, - inferenceRouteContext: { agentName: undefined, provider: "openrouter-api" }, + inferenceRouteContext: { agentName: undefined, provider: "custom-shared-provider" }, }); expect(result.verification.inferenceRouteWorking).toBe(false); @@ -223,7 +224,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { const result = await verifyDeployment("my-sandbox", buildChain(), deps, { retryDelaysMs: [1, 1, 1], sleep: async (_ms: number) => {}, - inferenceRouteContext: { agentName: "openclaw", provider: "openrouter-api" }, + inferenceRouteContext: { agentName: "openclaw", provider: "custom-shared-provider" }, }); expect(modelsRouteCalls).toBe(4); @@ -246,13 +247,13 @@ describe("verifyDeployment inference route model-catalog validation", () => { const result = await verifyDeployment("my-sandbox", buildChain(), deps, { retryDelaysMs: [1, 1, 1], sleep: async (_ms: number) => {}, - inferenceRouteContext: { agentName: "openclaw", provider: "openrouter-api" }, + inferenceRouteContext: { agentName: "openclaw", provider: "custom-shared-provider" }, }); expect(result.verification.inferenceRouteWorking).toBe(true); }); - it("spends no models-route retry budget on the expected Deep Agents Code 404 (#10543)", async () => { + it("never probes the shared models route for native Deep Agents Code OpenRouter", async () => { let modelsRouteCalls = 0; const deps = makeDeps({ executeSandboxCommand: async (_name: string, script: string) => { @@ -271,10 +272,10 @@ describe("verifyDeployment inference route model-catalog validation", () => { inferenceRouteContext: { agentName: DCODE_AGENT, provider: "openrouter-api" }, }); - expect(modelsRouteCalls).toBe(1); + expect(modelsRouteCalls).toBe(0); }); - it("runs the invocation probe once for the Deep Agents Code 404 exception (#10543)", async () => { + it("bounds failed native Deep Agents Code invocation retries by the startup budget", async () => { let invocationCalls = 0; const deps = makeModelsRouteDeps("404", { probeInferenceInvocation: async () => { @@ -289,7 +290,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { inferenceRouteContext: { agentName: DCODE_AGENT, provider: "openrouter-api" }, }); - expect(invocationCalls).toBe(1); + expect(invocationCalls).toBe(4); }); it("fails closed when no provider and model were recorded for the sandbox (#10543)", async () => { diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 478b4092f3b..9a930bb2f65 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -418,7 +418,7 @@ async function verifyInferenceRoute( httpCode: 0, hint: "The sandbox-attached hosted provider could not serve the selected model. Confirm the " + - "NVIDIA credential and model, then re-run: nemoclaw status.", + "provider credential and model, then re-run: nemoclaw status.", }; } const routeContext = toRouteHealthContext(context); diff --git a/test/cli/doctor-gateway-token.test.ts b/test/cli/doctor-gateway-token.test.ts index 7066b746c0e..f9c61586c3b 100644 --- a/test/cli/doctor-gateway-token.test.ts +++ b/test/cli/doctor-gateway-token.test.ts @@ -113,7 +113,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Creating\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); @@ -142,7 +142,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); // Docker-driver sandbox: no legacy `openshell-cluster-*` container exists. @@ -207,7 +207,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw-8090\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw-8090") printf "Gateway: nemoclaw-8090\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw-8090") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); writeDoctorSandboxRegistry(setup.home, "alpha", { @@ -244,7 +244,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); writeDoctorSandboxRegistry(setup.home, "alpha", { openshellDriver: "kubernetes" }); @@ -274,7 +274,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); writeDoctorSandboxRegistry(setup.home, "alpha", { openshellDriver: "kubernetes" }); @@ -368,7 +368,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ], ); @@ -439,7 +439,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ` "sandbox list -g nemoclaw") printf "NAME STATUS\\n${sandboxName} Ready\\n"; exit 0 ;;`, - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ], sandboxName, @@ -481,7 +481,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ` "sandbox list -g nemoclaw") printf "NAME STATUS\\n${sandboxName} Ready\\n"; exit 0 ;;`, - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ], sandboxName, diff --git a/test/cli/helpers.ts b/test/cli/helpers.ts index eb450f2825d..e4e82b1d6b7 100644 --- a/test/cli/helpers.ts +++ b/test/cli/helpers.ts @@ -378,6 +378,7 @@ export function writeDoctorSandboxRegistry( ): void { writeSandboxRegistry(home, sandboxName, { agent: "openclaw", + provider: "custom-shared-provider", openshellDriver: "docker", openshellVersion: "0.0.72", nemoclawVersion: "0.0.95", diff --git a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts index ea57162e2e6..75a1201c1e3 100644 --- a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts @@ -124,6 +124,7 @@ const registry = require(${registryPath}); // ownership evidence because another sandbox can use the same provider name. registry.registerSandbox({ name: "rg-test-noninter", + gatewayName: "nemoclaw", provider: "nvidia-prod", model: "nvidia/llama-3.3-nemotron-super-49b-v1", nativeNvidiaProviderAttachment: { diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 76b29fc3fe3..74354d1e3e9 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -367,6 +367,7 @@ registry.getSandbox = (name) => name === "hermes-resume" ? { name, + gatewayName: "nemoclaw", gpuEnabled: false, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 24f70b0a951..dba8e045186 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -756,7 +756,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne provider: options.agentName === "hermes" ? "ollama-local" : null, model: options.agentName === "hermes" ? "qwen3-vl:4b" : null, ...(options.agentName === "langchain-deepagents-code" - ? { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b" } + ? { provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b" } : {}), lifecycleLiveIdentityFingerprint: portableDisposition.kind === "hermes" diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 8e66e3b177c..2f95b6a84aa 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -12,6 +12,8 @@ import { type SetupInferenceDeps, } from "../../src/lib/onboard/setup-inference.js"; import { redact } from "../../src/lib/security/redact.js"; +import type { NativeHostedProviderAttachment } from "../../src/lib/inference/native-hosted/contract"; +import type { NativeNvidiaProviderAttachment } from "../../src/lib/inference/native-nvidia/contract"; const onboardProviderHelpers = require("../../src/lib/onboard/providers") as { upsertProvider: ( @@ -330,6 +332,8 @@ export function createDirectSetupInferenceHarnessFactory( createSetupInference: CreateSetupInference, ) { return function createDirectSetupInferenceHarness(options: DirectSetupHarnessOptions = {}) { + const hostedAuthorities = new Map(); + const nvidiaAuthorities = new Map(); const commands: DirectCommandEntry[] = []; const errors: string[] = []; const logs: string[] = []; @@ -491,6 +495,15 @@ export function createDirectSetupInferenceHarnessFactory( // #9110: neutralize the GPU-release seams so harness consumers backed by // the production defaults never read the developer's real registry or // curl a live Ollama daemon. + getNativeHostedProviderAuthority: (gateway, profile) => + hostedAuthorities.get(`${gateway}/${profile}`), + setNativeHostedProviderAuthority: (gateway, receipt) => { + hostedAuthorities.set(`${gateway}/${receipt.profileId}`, receipt); + }, + getNativeNvidiaProviderAuthority: (gateway) => nvidiaAuthorities.get(gateway), + setNativeNvidiaProviderAuthority: (gateway, receipt) => { + nvidiaAuthorities.set(gateway, receipt); + }, getSandbox: () => null, listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), unloadOllamaModels, From ad30ffe9b49b6370e30274ca038accfeb9fe08eb Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:15:38 -0700 Subject: [PATCH 046/133] fix: clear retired NVIDIA provider authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../credentials-provider-adapter.test.ts | 22 ++++++ src/lib/actions/credentials/reset.ts | 5 ++ .../inference-set-openclaw-run.test.ts | 76 +++++++++++++++++++ src/lib/state/registry-normalization.test.ts | 31 +++++++- .../native-nvidia-provider-authority.ts | 14 +++- .../native-nvidia-target-ownership.test.ts | 1 + tools/e2e/target-catalogue.mts | 2 + 7 files changed, 149 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 99966d164e3..42944571ab3 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -995,6 +995,28 @@ describe("credential actions use typed OpenShell provider results", () => { expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw"); }); + it("clears native NVIDIA authority when the provider is already absent", async () => { + const clearNativeNvidiaProviderAuthority = vi.fn(); + const adapter = providerAdapter({ + deleteProvider: vi.fn(async () => ({ + ok: false as const, + error: { + kind: "command" as const, + reason: "not_found" as const, + message: "provider not found", + }, + })), + }); + + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { providerAdapter: adapter, clearNativeNvidiaProviderAuthority }, + ); + + expect(result.exitCode).toBe(0); + expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw"); + }); + it("reports recovery for sandboxes detached before final deletion fails (#9806)", async () => { const deleteProvider = vi .fn() diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index e8ee28977f2..0f7b4aaa0cb 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -141,6 +141,11 @@ export async function runCredentialsResetAction( recovery.error?.kind === "command" && recovery.error.reason === "not_found" ) { + if (nativeNvidiaProvider) { + (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( + target.gatewayName, + ); + } const removedLocal = forgetExtraProvider(key); return ok([ removedLocal diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 6c57a19edde..4193d72e791 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -125,6 +125,82 @@ describe("runInferenceSet OpenClaw routing", () => { ); }); + it("creates a new native NVIDIA provider after reset removes retained authority", async () => { + const providerId = "22222222-3333-4444-8555-666666666666"; + let providerPresent = false; + let attached = false; + const createProvider = vi.fn(async () => { + providerPresent = true; + return { ok: true }; + }); + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true as const })), + getProvider: vi.fn(async () => + providerPresent + ? { + ok: true as const, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: providerId, resourceVersion: 1 }, + }, + } + : { + ok: false as const, + error: { + kind: "command" as const, + reason: "not_found" as const, + message: "provider not found", + }, + }, + ), + createProvider, + listProviderAttachments: vi.fn(async () => ({ + ok: true as const, + value: { names: attached ? ["nemoclaw-nvidia-prod-v1"] : [] }, + })), + attachProvider: vi.fn(async () => { + attached = true; + return { ok: true as const }; + }), + } as unknown as OpenShellProviderAdapter; + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "gpt-5.4", + }, + providerAdapter, + resolveCredentialValue: () => "replacement-credential", + }); + + await runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, + deps, + ); + + expect(createProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "replacement-credential" }], + config: [], + fromExisting: false, + }); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + nativeNvidiaProviderAttachment: expect.objectContaining({ providerId }), + nativeNvidiaProviderAuthority: expect.objectContaining({ providerId }), + }), + ); + }); + it("detaches native NVIDIA access only after another provider is healthy", async () => { let attached = true; const detachProvider = vi.fn(async () => { diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index e9c46e04597..746bbd0ac1e 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -48,7 +48,30 @@ describe("sandbox registry normalization", () => { }; const { registry } = await loadRegistryDocument({ defaultSandbox: null, - sandboxes: {}, + sandboxes: { + alpha: { + name: "alpha", + gatewayName: "nemoclaw-19080", + provider: "openai-api", + nativeNvidiaProviderAuthority: receipt, + }, + beta: { + name: "beta", + gatewayName: "nemoclaw-19080", + provider: "nvidia-prod", + nativeNvidiaProviderAttachment: receipt, + nativeNvidiaProviderAuthority: receipt, + }, + gamma: { + name: "gamma", + gatewayName: "nemoclaw-19081", + provider: "openai-api", + nativeNvidiaProviderAuthority: { + ...receipt, + providerId: "22222222-3333-4444-8555-666666666666", + }, + }, + }, nativeNvidiaProviderAuthorities: { broken: { ...receipt, providerId: "" }, "nemoclaw-19080": receipt, @@ -67,6 +90,12 @@ describe("sandbox registry normalization", () => { }); registry.clearNativeNvidiaProviderAuthority("nemoclaw-19080"); expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toBeUndefined(); + expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAuthority).toBeUndefined(); + expect(registry.getSandbox("beta")?.nativeNvidiaProviderAuthority).toBeUndefined(); + expect(registry.getSandbox("beta")?.nativeNvidiaProviderAttachment).toEqual(receipt); + expect(registry.getSandbox("gamma")?.nativeNvidiaProviderAuthority).toMatchObject({ + providerId: "22222222-3333-4444-8555-666666666666", + }); }); it("persists incomplete OpenClaw synchronization until explicit completion", async () => { diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index 68599dfec2c..a9461db6f08 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -34,7 +34,19 @@ export function setNativeNvidiaProviderAuthority( export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { withLock(() => { const data = load(); - if (!applyRemoveNativeNvidiaProviderAuthority(data, gatewayName)) return; + let changed = applyRemoveNativeNvidiaProviderAuthority(data, gatewayName); + for (const [sandboxName, sandbox] of Object.entries(data.sandboxes)) { + if ( + sandbox.gatewayName !== gatewayName || + sandbox.nativeNvidiaProviderAuthority === undefined + ) { + continue; + } + const { nativeNvidiaProviderAuthority: _removedAuthority, ...retained } = sandbox; + data.sandboxes[sandboxName] = retained; + changed = true; + } + if (!changed) return; save(data); }); } diff --git a/test/e2e/support/native-nvidia-target-ownership.test.ts b/test/e2e/support/native-nvidia-target-ownership.test.ts index fa6c7ee29d8..2f168adc83b 100644 --- a/test/e2e/support/native-nvidia-target-ownership.test.ts +++ b/test/e2e/support/native-nvidia-target-ownership.test.ts @@ -10,6 +10,7 @@ describe("native NVIDIA target ownership", () => { "src/lib/actions/inference-set.ts", "src/lib/inference/native-nvidia/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", + "test/e2e/live/public-nvidia-switch-provider.ts", ])("selects both provider-switch targets when %s changes", (changedFile) => { expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toEqual( expect.arrayContaining(["hermes-inference-switch", "openclaw-inference-switch"]), diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 0c6dbdea22d..1d130b8c733 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -910,6 +910,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ "src/lib/actions/inference-set.ts", "src/lib/inference/native-nvidia/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", + "test/e2e/live/public-nvidia-switch-provider.ts", ], environment: { ...nonInteractive, @@ -1205,6 +1206,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ "src/lib/onboard/openclaw/initial-inference-route.ts", "src/lib/onboard/sandbox-recreate-transaction.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", + "test/e2e/live/public-nvidia-switch-provider.ts", "scripts/patch-openclaw-device-self-approval.mts", "test/e2e/live/openclaw-admin-scope.ts", "test/e2e/fixtures/admin-approval-connect.ts", From 04fe3a32b8148ebc7116104a12b4f9c6b14a07d1 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 15:37:33 -0700 Subject: [PATCH 047/133] fix(inference): align shared-route fixtures and credential boundaries Signed-off-by: Deepak Jain --- .../openshell/provider-adapter-cli.test.ts | 14 ++++++++- .../adapters/openshell/provider-profile.ts | 6 +++- test/cli/connect-readiness.test.ts | 4 +-- test/cli/connect-terminal-agent.test.ts | 3 +- test/cli/launch-routing.test.ts | 8 +++-- test/cli/sandbox-status-json.test.ts | 12 ++++---- test/cli/sandbox-status-text.test.ts | 14 ++++----- test/cli/status-gateway-lifecycle.test.ts | 8 ++--- .../e2e-runtime/nemoclaw-cli-recovery.test.ts | 30 +++++++++++++++---- .../gateway/recover-port-forward.test.ts | 4 +-- .../sandbox/reboot-identity-drift.test.ts | 6 ++-- .../sandbox/sandbox-stuck-recovery.test.ts | 4 +-- .../auto-pair-approval.test.ts | 16 +++++----- .../route-swap-repair.test.ts | 8 +++-- 14 files changed, 90 insertions(+), 47 deletions(-) diff --git a/src/lib/adapters/openshell/provider-adapter-cli.test.ts b/src/lib/adapters/openshell/provider-adapter-cli.test.ts index 4112374535f..efc6739ccfd 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.test.ts @@ -989,7 +989,6 @@ describe("CLI OpenShell provider adapter", () => { ["provider", "profile", "-g", "nemoclaw", "export", "tavily", "--output", "json"], ]); }); - it.each([ [ "endpoint", @@ -1001,6 +1000,19 @@ describe("CLI OpenShell provider adapter", () => { ], }, ], + ...[ + { path_template: "/credential/{api_key}" }, + { token_grant: { token_endpoint: "https://other.example.com/token" } }, + ].map((boundary) => [ + Object.keys(boundary).join(), + { + ...TAVILY_PROFILE, + credentials: TAVILY_PROFILE.credentials.map((credential) => ({ + ...credential, + ...boundary, + })), + }, + ]), ["binary", { ...TAVILY_PROFILE, binaries: [...TAVILY_PROFILE.binaries, "/tmp/widened"] }], [ "credential", diff --git a/src/lib/adapters/openshell/provider-profile.ts b/src/lib/adapters/openshell/provider-profile.ts index 70b1182bcba..21d0343ae02 100644 --- a/src/lib/adapters/openshell/provider-profile.ts +++ b/src/lib/adapters/openshell/provider-profile.ts @@ -48,7 +48,9 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null typeof credential.auth_style !== "string" || typeof credential.header_name !== "string" || (credential.query_param !== undefined && typeof credential.query_param !== "string") || - (credential.refresh !== undefined && recordValue(credential.refresh) === null) + (credential.refresh !== undefined && recordValue(credential.refresh) === null) || + (credential.path_template !== undefined && typeof credential.path_template !== "string") || + (credential.token_grant !== undefined && recordValue(credential.token_grant) === null) ) { return null; } @@ -60,6 +62,8 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null header_name: credential.header_name, query_param: credential.query_param, refresh: credential.refresh ?? null, + path_template: credential.path_template ?? "", + token_grant: credential.token_grant ?? null, }; }); if (credentials.some((credential) => credential === null)) return null; diff --git a/test/cli/connect-readiness.test.ts b/test/cli/connect-readiness.test.ts index 526969f7eb7..8ba2d9ca814 100644 --- a/test/cli/connect-readiness.test.ts +++ b/test/cli/connect-readiness.test.ts @@ -31,7 +31,7 @@ describe("CLI connect readiness", () => { alpha: { name: "alpha", model: "test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, @@ -51,7 +51,7 @@ describe("CLI connect readiness", () => { 'printf \'%s\\n\' "$*" >> "$marker_file"', 'if [ "$1" = "inference" ] && [ "$2" = "get" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: test-model'", " exit 0", "fi", diff --git a/test/cli/connect-terminal-agent.test.ts b/test/cli/connect-terminal-agent.test.ts index 63896bc3f82..6bcc80eed7a 100644 --- a/test/cli/connect-terminal-agent.test.ts +++ b/test/cli/connect-terminal-agent.test.ts @@ -20,6 +20,7 @@ describe("CLI dispatch for terminal agents", () => { writeSandboxRegistry(home, { ...launchReadinessRegistryFixture(), agent: "langchain-deepagents-code", + provider: "custom-shared-provider", }); fs.writeFileSync( path.join(localBin, "openshell"), @@ -36,7 +37,7 @@ describe("CLI dispatch for terminal agents", () => { " exit 0", "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', - " printf '%s\\n' 'Gateway inference:' ' Provider: nvidia-prod' ' Model: test-model'", + " printf '%s\\n' 'Gateway inference:' ' Provider: custom-shared-provider' ' Model: test-model'", " exit 0", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', diff --git a/test/cli/launch-routing.test.ts b/test/cli/launch-routing.test.ts index d338b703611..159a6a17b3c 100644 --- a/test/cli/launch-routing.test.ts +++ b/test/cli/launch-routing.test.ts @@ -51,7 +51,11 @@ function createLaunchHarness(prefix: string, agent: string): LaunchHarness { const callArgvFile = path.join(home, "openshell-call-argv"); const execArgvFile = path.join(home, "openshell-exec-argv"); fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home, { ...launchReadinessRegistryFixture(), agent }); + writeSandboxRegistry(home, { + ...launchReadinessRegistryFixture(), + agent, + provider: "custom-shared-provider", + }); fs.writeFileSync( path.join(localBin, "openshell"), @@ -81,7 +85,7 @@ function createLaunchHarness(prefix: string, agent: string): LaunchHarness { "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: test-model'", " exit 0", "fi", diff --git a/test/cli/sandbox-status-json.test.ts b/test/cli/sandbox-status-json.test.ts index 965f8d8ee5f..16658ec088d 100644 --- a/test/cli/sandbox-status-json.test.ts +++ b/test/cli/sandbox-status-json.test.ts @@ -32,7 +32,7 @@ function createInferenceRouteStatusSetup(options: { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, sandboxName, { model: "nvidia/nemotron", - provider: "nvidia-prod", + provider: "compatible-endpoint", // These cases test only inference.local classification. Use the VM driver // so Docker post-reboot delivery recovery does not affect their assertions. openshellDriver: "vm", @@ -92,7 +92,7 @@ function createInferenceRouteStatusSetup(options: { ]), "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', - " echo 'Provider: nvidia-prod'", + " echo 'Provider: compatible-endpoint'", " echo 'Model: nvidia/nemotron'", " exit 0", "fi", @@ -262,7 +262,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) ]); }); - it("sandbox status --json reports a missing upstream credential as not probed when inference.local is reachable (#6192)", async () => { + it("sandbox status --json reports an unknown upstream endpoint as not probed when inference.local is reachable (#6192)", async () => { const { home, localBin, sandboxName } = createInferenceRouteStatusSetup({ routeOutput: "OK 200", upstreamHttpStatus: "000", @@ -400,7 +400,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) ); const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home, "alpha"); + writeSandboxRegistry(home, "alpha", { provider: "custom-shared-provider" }); fs.writeFileSync( path.join(localBin, "openshell"), [ @@ -432,7 +432,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-sandbox-status-json-rpc-")); const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home, "alpha"); + writeSandboxRegistry(home, "alpha", { provider: "custom-shared-provider" }); fs.writeFileSync( path.join(localBin, "openshell"), [ @@ -465,7 +465,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) expect(parsed.rpcIssue).toEqual({ kind: "protobuf_mismatch" }); expect(parsed.inferenceHealth).toBeNull(); expect(parsed.model).toBe("test-model"); - expect(parsed.provider).toBe("nvidia-prod"); + expect(parsed.provider).toBe("custom-shared-provider"); }); it("sandbox status --json reports found:false and exits 1 for unknown sandbox via canonical form", async () => { diff --git a/test/cli/sandbox-status-text.test.ts b/test/cli/sandbox-status-text.test.ts index 6db8acbcf5c..597247794db 100644 --- a/test/cli/sandbox-status-text.test.ts +++ b/test/cli/sandbox-status-text.test.ts @@ -84,7 +84,7 @@ describe.concurrent("CLI sandbox status text output", () => { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, "alpha", { agent: "missing-terminal-agent", - provider: "openai-api", + provider: "custom-shared-provider", model: "gpt-4o-mini", openshellDriver: "docker", }); @@ -101,7 +101,7 @@ describe.concurrent("CLI sandbox status text output", () => { "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: openai-api'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: gpt-4o-mini'", " exit 0", "fi", @@ -138,7 +138,7 @@ describe.concurrent("CLI sandbox status text output", () => { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, "dcode-station", { agent: "langchain-deepagents-code", - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", openshellDriver: "docker", openshellVersion: "0.0.44", @@ -156,7 +156,7 @@ describe.concurrent("CLI sandbox status text output", () => { "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: nvidia/nemotron-3-super-120b-a12b'", " exit 0", "fi", @@ -271,7 +271,7 @@ describe.concurrent("CLI sandbox status text output", () => { const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, "alpha", { - provider: "openai-api", + provider: "compatible-endpoint", model: "gpt-4o-mini", openshellDriver: "vm", }); @@ -285,7 +285,7 @@ describe.concurrent("CLI sandbox status text output", () => { "#!/usr/bin/env bash", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: openai-api'", + " echo ' Provider: compatible-endpoint'", " echo ' Model: gpt-4o-mini'", " exit 0", "fi", @@ -312,7 +312,7 @@ describe.concurrent("CLI sandbox status text output", () => { expect(r.code).toBe(0); expect(r.out).not.toContain("Failure layer: docker_unreachable"); expect(r.out).toContain("Sandbox: alpha"); - expect(r.out).toContain("Provider: openai-api"); + expect(r.out).toContain("Provider: compatible-endpoint"); expect(r.out).toContain("Model: gpt-4o-mini"); expect(r.out).toContain("Inference: healthy (https://inference.local/v1/models)"); expect(r.out).toContain( diff --git a/test/cli/status-gateway-lifecycle.test.ts b/test/cli/status-gateway-lifecycle.test.ts index b0e2e4c00ca..79f6b00f5c4 100644 --- a/test/cli/status-gateway-lifecycle.test.ts +++ b/test/cli/status-gateway-lifecycle.test.ts @@ -77,7 +77,7 @@ describe("CLI status gateway lifecycle process contracts", () => { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, { model: "configured-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: true, }); fs.writeFileSync( @@ -97,7 +97,7 @@ describe("CLI status gateway lifecycle process contracts", () => { 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", " echo", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: live-model'", " exit 0", "fi", @@ -140,9 +140,9 @@ describe("CLI status gateway lifecycle process contracts", () => { expect(result.code).toBe(0); expect(result.out).toContain("Sandbox: alpha"); expect(result.out).toContain("Model: configured-model"); - expect(result.out).toContain("Provider: nvidia-prod"); + expect(result.out).toContain("Provider: custom-shared-provider"); expect(result.out).toContain( - "gateway inference route (nvidia-prod/live-model) differs from the recorded route for this sandbox (nvidia-prod/configured-model)", + "gateway inference route (custom-shared-provider/live-model) differs from the recorded route for this sandbox (custom-shared-provider/configured-model)", ); expect(result.out).toContain("Inference:"); expect(result.out).toContain("healthy"); diff --git a/test/e2e-runtime/nemoclaw-cli-recovery.test.ts b/test/e2e-runtime/nemoclaw-cli-recovery.test.ts index 306641a07fd..84d26be2d3d 100644 --- a/test/e2e-runtime/nemoclaw-cli-recovery.test.ts +++ b/test/e2e-runtime/nemoclaw-cli-recovery.test.ts @@ -34,14 +34,24 @@ describe("nemoclaw CLI runtime recovery", () => { "my-assistant": { name: "my-assistant", model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, }), { mode: 0o600 }, ); - fs.writeFileSync(stateFile, JSON.stringify({ statusCalls: 0, sandboxGetCalls: 0 })); + // Recover the existing disconnected registration through the fallback CLI. + // A missing registration would require a real host gateway process. + fs.writeFileSync( + stateFile, + JSON.stringify({ + statusCalls: 0, + sandboxGetCalls: 0, + gatewaySelectCalls: 0, + gatewayStartCalls: 0, + }), + ); fs.writeFileSync( openshellPath, `#!${process.execPath} @@ -55,14 +65,21 @@ if (args[0] === "status") { state.statusCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); if (state.statusCalls === 1) { - process.stdout.write("Error: × No active gateway\\n"); + process.stdout.write("Gateway: nemoclaw\\nStatus: Disconnected\\n"); } else { process.stdout.write("Gateway: nemoclaw\\nStatus: Connected\\n"); } process.exit(0); } -if (args[0] === "gateway" && (args[1] === "start" || args[1] === "select")) { +if (args[0] === "gateway" && args[1] === "start") { + state.gatewayStartCalls += 1; + fs.writeFileSync(statePath, JSON.stringify(state)); + process.exit(1); +} + +if (args[0] === "gateway" && args[1] === "select") { + state.gatewaySelectCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); process.exit(0); } @@ -117,7 +134,10 @@ process.exit(0); ); assert.equal(result.status, 0, result.stderr); - assert.match(result.stdout, /Recovered NemoClaw gateway runtime via (start|select)/); + assert.match(result.stdout, /Recovered NemoClaw gateway runtime via select/); + const recoveredState = JSON.parse(fs.readFileSync(stateFile, "utf8")); + assert.ok(recoveredState.gatewaySelectCalls > 0); + assert.equal(recoveredState.gatewayStartCalls, 0); assert.match(result.stdout, /Phase: Ready/); }, ); diff --git a/test/runtime/gateway/recover-port-forward.test.ts b/test/runtime/gateway/recover-port-forward.test.ts index a20102341f6..b1bae917ab6 100644 --- a/test/runtime/gateway/recover-port-forward.test.ts +++ b/test/runtime/gateway/recover-port-forward.test.ts @@ -149,7 +149,7 @@ async function setupFixture(opts: { name: sandboxName, ...launchReadinessRegistryFixture(), model: "nvidia/test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, dashboardPort: Number(port), }, @@ -316,7 +316,7 @@ if (args[0] === "policy" && args[1] === "get") { if (args[0] === "inference" && args[1] === "get") { process.stdout.write( - "Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n", + "Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n", ); process.exit(0); } diff --git a/test/runtime/sandbox/reboot-identity-drift.test.ts b/test/runtime/sandbox/reboot-identity-drift.test.ts index f0b03ccee7a..d840f640a88 100644 --- a/test/runtime/sandbox/reboot-identity-drift.test.ts +++ b/test/runtime/sandbox/reboot-identity-drift.test.ts @@ -51,7 +51,7 @@ function setupFixture(sandboxName: string, mode: "healthy" | "identity_drift" | [sandboxName]: { name: sandboxName, model: "nvidia/test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, @@ -139,7 +139,7 @@ if (args[0] === "policy" && args[1] === "get") { } if (args[0] === "inference" && args[1] === "get") { - process.stdout.write("Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n"); + process.stdout.write("Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n"); process.exit(0); } @@ -233,7 +233,7 @@ if (args[0] === "policy" && args[1] === "get") { } if (args[0] === "inference" && args[1] === "get") { - process.stdout.write("Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n"); + process.stdout.write("Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n"); process.exit(0); } diff --git a/test/runtime/sandbox/sandbox-stuck-recovery.test.ts b/test/runtime/sandbox/sandbox-stuck-recovery.test.ts index 9785bca6509..9bfb4e921a6 100644 --- a/test/runtime/sandbox/sandbox-stuck-recovery.test.ts +++ b/test/runtime/sandbox/sandbox-stuck-recovery.test.ts @@ -35,7 +35,7 @@ function setupFixture(sandboxName: string, phase: string) { [sandboxName]: { name: sandboxName, model: "nvidia/test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, @@ -83,7 +83,7 @@ if (args[0] === "policy" && args[1] === "get") { } if (args[0] === "inference" && args[1] === "get") { - process.stdout.write("Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n"); + process.stdout.write("Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n"); process.exit(0); } diff --git a/test/sandbox-connect-inference/auto-pair-approval.test.ts b/test/sandbox-connect-inference/auto-pair-approval.test.ts index 16311aa0021..960de31e35c 100644 --- a/test/sandbox-connect-inference/auto-pair-approval.test.ts +++ b/test/sandbox-connect-inference/auto-pair-approval.test.ts @@ -32,10 +32,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-pass-sb", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); @@ -76,10 +76,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-pass-pol", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); @@ -143,10 +143,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-tmp-tamper", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); const maliciousPolicy = [ @@ -193,10 +193,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-tolerant", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); diff --git a/test/sandbox-connect-inference/route-swap-repair.test.ts b/test/sandbox-connect-inference/route-swap-repair.test.ts index bce30aa0aa2..c2f57adaf6f 100644 --- a/test/sandbox-connect-inference/route-swap-repair.test.ts +++ b/test/sandbox-connect-inference/route-swap-repair.test.ts @@ -16,7 +16,7 @@ describe("sandbox connect inference route swap (#1248)", () => { { name: "my-sandbox", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, "nvidia-prod", @@ -34,7 +34,7 @@ describe("sandbox connect inference route swap (#1248)", () => { "nemoclaw", "--no-verify", "--provider", - "anthropic-prod", + "custom-shared-provider", "--model", "claude-sonnet-4-20250514", ]); @@ -42,7 +42,9 @@ describe("sandbox connect inference route swap (#1248)", () => { // Override must be loud (#3726), not a silent status-style line. const combined = (result.stdout || "") + (result.stderr || ""); expect(combined).toContain("differs from the recorded route"); - expect(combined).toContain("Aligning the gateway to anthropic-prod/claude-sonnet-4-20250514"); + expect(combined).toContain( + "Aligning the gateway to custom-shared-provider/claude-sonnet-4-20250514", + ); }, ); From 1af6cd4f1dfb5a3213a2e4dcbb08fb10a0a7e12f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 16:21:58 -0700 Subject: [PATCH 048/133] fix: centralize native NVIDIA provider authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../inference-set-openclaw-run.test.ts | 70 ++++++++++--------- src/lib/actions/inference-set.test-support.ts | 5 ++ src/lib/actions/inference-set.ts | 45 ++++++------ src/lib/inference/native-nvidia/index.ts | 28 +------- src/lib/onboard/setup-inference.ts | 1 - ...egistry-native-provider-attachment.test.ts | 14 +--- src/lib/state/registry-normalization.test.ts | 8 +-- src/lib/state/registry.ts | 37 +--------- .../native-nvidia-provider-authority.ts | 14 +--- src/lib/state/registry/persistence.ts | 14 +++- src/lib/state/registry/route-reservation.ts | 7 -- src/lib/state/registry/types.ts | 2 - 12 files changed, 85 insertions(+), 160 deletions(-) diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 4193d72e791..c89439db171 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -27,7 +27,7 @@ describe("runInferenceSet OpenClaw routing", () => { expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); }); - it("reuses a same-gateway native NVIDIA provider authority from a peer sandbox", async () => { + it("does not infer native NVIDIA provider authority from a peer sandbox", async () => { const peerAttachment = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, @@ -57,15 +57,10 @@ describe("runInferenceSet OpenClaw routing", () => { resolveCredentialValue: () => "", }); - await runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, - deps, - ); - - expect(deps.calls.updateSandbox).toHaveBeenCalledWith( - "alpha", - expect.objectContaining({ nativeNvidiaProviderAttachment: peerAttachment }), - ); + await expect( + runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps), + ).rejects.toThrow(/without a matching NemoClaw ownership receipt/u); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); it("selects a native NVIDIA provider registered before any sandbox used it", async () => { @@ -120,9 +115,12 @@ describe("runInferenceSet OpenClaw routing", () => { "alpha", expect.objectContaining({ nativeNvidiaProviderAttachment: gatewayAuthority, - nativeNvidiaProviderAuthority: gatewayAuthority, }), ); + expect(deps.calls.setNativeNvidiaProviderAuthority).toHaveBeenCalledWith( + "nemoclaw", + gatewayAuthority, + ); }); it("creates a new native NVIDIA provider after reset removes retained authority", async () => { @@ -196,9 +194,12 @@ describe("runInferenceSet OpenClaw routing", () => { "alpha", expect.objectContaining({ nativeNvidiaProviderAttachment: expect.objectContaining({ providerId }), - nativeNvidiaProviderAuthority: expect.objectContaining({ providerId }), }), ); + expect(deps.calls.setNativeNvidiaProviderAuthority).toHaveBeenCalledWith( + "nemoclaw", + expect.objectContaining({ providerId }), + ); }); it("detaches native NVIDIA access only after another provider is healthy", async () => { @@ -259,21 +260,18 @@ describe("runInferenceSet OpenClaw routing", () => { expect(detachProvider.mock.invocationCallOrder[0]).toBeLessThan( deps.calls.restartSandboxGateway.mock.invocationCallOrder[0], ); - expect(deps.calls.updateSandbox).toHaveBeenCalledWith( - "alpha", - expect.objectContaining({ - nativeNvidiaProviderAttachment: undefined, - nativeNvidiaProviderAuthority: { - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "11111111-2222-4333-8444-555555555555", - }, - }), + const departureUpdate = deps.calls.updateSandbox.mock.calls.find( + ([name, updates]) => + name === "alpha" && + Object.prototype.hasOwnProperty.call(updates, "nativeNvidiaProviderAttachment"), + )?.[1]; + expect(departureUpdate).toEqual( + expect.objectContaining({ nativeNvidiaProviderAttachment: undefined }), ); + expect(departureUpdate).not.toHaveProperty("nativeNvidiaProviderAuthority"); }); - it("verifies retained NVIDIA authority across a single-sandbox round trip", async () => { + it("retains gateway authority as the sole durable receipt across a round trip", async () => { const attachment = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, @@ -287,8 +285,8 @@ describe("runInferenceSet OpenClaw routing", () => { provider: "nvidia-prod", model: "nvidia/old-model", nativeNvidiaProviderAttachment: attachment, - nativeNvidiaProviderAuthority: attachment, }; + let gatewayAuthority = attachment; const updateSandbox = vi.fn((name: string, updates: Record) => { expect(name).toBe(entry.name); Object.assign(entry, updates); @@ -301,6 +299,10 @@ describe("runInferenceSet OpenClaw routing", () => { }, entry, updateSandbox, + getNativeNvidiaProviderAuthority: () => gatewayAuthority, + setNativeNvidiaProviderAuthority: (_gatewayName, receipt) => { + gatewayAuthority = receipt; + }, resolveCredentialValue: () => "", }); @@ -308,9 +310,10 @@ describe("runInferenceSet OpenClaw routing", () => { expect(entry).toMatchObject({ provider: "openai-api", - nativeNvidiaProviderAuthority: attachment, }); expect(entry.nativeNvidiaProviderAttachment).toBeUndefined(); + expect(entry).not.toHaveProperty("nativeNvidiaProviderAuthority"); + expect(gatewayAuthority).toEqual(attachment); await runInferenceSet( { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, @@ -320,8 +323,9 @@ describe("runInferenceSet OpenClaw routing", () => { expect(entry).toMatchObject({ provider: "nvidia-prod", nativeNvidiaProviderAttachment: attachment, - nativeNvidiaProviderAuthority: attachment, }); + expect(entry).not.toHaveProperty("nativeNvidiaProviderAuthority"); + expect(gatewayAuthority).toEqual(attachment); }); it("rejects a replaced NVIDIA provider before restoring detached access", async () => { @@ -354,13 +358,13 @@ describe("runInferenceSet OpenClaw routing", () => { gatewayName: "nemoclaw", provider: "openai-api", model: "gpt-5.4", - nativeNvidiaProviderAuthority: { - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "recorded-provider-id", - }, }, + getNativeNvidiaProviderAuthority: () => ({ + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "recorded-provider-id", + }), providerAdapter, resolveCredentialValue: () => "", }); diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index f64d3c3ae79..0258720fb79 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -278,6 +278,7 @@ export function createDeps(options: { settleOpenClawPairing?: InferenceSetDeps["settleOpenClawPairing"]; withGatewayRouteMutationLock?: InferenceSetDeps["withGatewayRouteMutationLock"]; getNativeNvidiaProviderAuthority?: InferenceSetDeps["getNativeNvidiaProviderAuthority"]; + setNativeNvidiaProviderAuthority?: InferenceSetDeps["setNativeNvidiaProviderAuthority"]; }): InferenceSetDeps & { calls: { captureOpenshell: ReturnType; @@ -302,6 +303,7 @@ export function createDeps(options: { restartSandboxGateway: ReturnType; settleOpenClawPairing: ReturnType; withGatewayRouteMutationLock: ReturnType; + setNativeNvidiaProviderAuthority: ReturnType; }; getSession: () => Session | null; } { @@ -374,6 +376,7 @@ export function createDeps(options: { (async (_gatewayName: string, operation: () => Promise | unknown) => await operation()), ), + setNativeNvidiaProviderAuthority: vi.fn(), }; const providerAdapter = options.providerAdapter ?? @@ -424,6 +427,8 @@ export function createDeps(options: { getSandbox: (name: string) => sandboxes[name] ?? null, listSandboxes: () => ({ sandboxes: entries, defaultSandbox }), getNativeNvidiaProviderAuthority: options.getNativeNvidiaProviderAuthority, + setNativeNvidiaProviderAuthority: + options.setNativeNvidiaProviderAuthority ?? calls.setNativeNvidiaProviderAuthority, updateSandbox: calls.updateSandbox, getRequestedAgent: () => options.requestedAgent, loadSession: () => session, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index ef40b70e543..719c7a30ded 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -179,6 +179,7 @@ export interface InferenceSetDeps extends InferenceGatewayRestartDeps { defaultSandbox: string | null; }; getNativeNvidiaProviderAuthority?: typeof registry.getNativeNvidiaProviderAuthority; + setNativeNvidiaProviderAuthority: typeof registry.setNativeNvidiaProviderAuthority; updateSandbox: (name: string, updates: Partial) => boolean; getRequestedAgent: () => string | null | undefined; loadSession: () => onboardSession.Session | null; @@ -312,6 +313,7 @@ function defaultDeps(): InferenceSetDeps { getSandbox: registry.getSandbox, listSandboxes: registry.listSandboxes, getNativeNvidiaProviderAuthority: registry.getNativeNvidiaProviderAuthority, + setNativeNvidiaProviderAuthority: registry.setNativeNvidiaProviderAuthority, updateSandbox: registry.updateSandbox, getRequestedAgent: () => process.env.NEMOCLAW_AGENT, loadSession: onboardSession.loadSession, @@ -1018,18 +1020,19 @@ async function detachPreviousNativeNvidiaBeforePublish(input: { return true; } -function nativeNvidiaDepartureRegistryFields(input: { - detached: boolean; - authority?: NativeNvidiaProviderAttachment; -}): - | Pick - | Record { - return input.detached - ? { - nativeNvidiaProviderAttachment: undefined, - nativeNvidiaProviderAuthority: input.authority, - } - : {}; +function nativeNvidiaDepartureRegistryFields( + detached: boolean, +): Pick | Record { + return detached ? { nativeNvidiaProviderAttachment: undefined } : {}; +} + +function recordNativeNvidiaProviderAuthority(input: { + attachment?: NativeNvidiaProviderAttachment; + gatewayName: string; + deps: InferenceSetDeps; +}): void { + if (!input.attachment) return; + input.deps.setNativeNvidiaProviderAuthority(input.gatewayName, input.attachment); } async function restorePreviousNativeNvidiaAfterFailedPublish(input: { @@ -1518,9 +1521,6 @@ async function runInferenceSetWithoutHostLock( const previousNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( entry.nativeNvidiaProviderAttachment, ); - const previousNativeNvidiaAuthority = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAuthority, - ); assertNativeNvidiaMigrationReady({ provider, previousProvider, @@ -1532,8 +1532,6 @@ async function runInferenceSetWithoutHostLock( gatewayName: preparedRoute.gatewayName, gatewayAuthority: deps.getNativeNvidiaProviderAuthority?.(preparedRoute.gatewayName), recordedAttachment: previousNativeNvidiaAttachment, - recordedAuthority: previousNativeNvidiaAuthority, - sandboxes: routeSandboxes, }) : undefined; const rollbackRoute = preMutationRoute.state === "configured" ? preMutationRoute.route : null; @@ -1618,6 +1616,11 @@ async function runInferenceSetWithoutHostLock( }); nativeNvidiaProviderAttachment = nativeNvidiaSelection.attachment; nativeNvidiaAttachmentChanged = nativeNvidiaSelection.attachmentChanged; + recordNativeNvidiaProviderAuthority({ + attachment: nativeNvidiaProviderAttachment, + gatewayName: preparedRoute.gatewayName, + deps, + }); const providerBinding = httpsPinProviderBinding ?? directProviderBinding; if (providerBinding) { providerMutation = await prepareInferenceSetProviderBinding({ @@ -1795,13 +1798,7 @@ async function runInferenceSetWithoutHostLock( }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), - ...(nativeNvidiaProviderAttachment - ? { nativeNvidiaProviderAuthority: nativeNvidiaProviderAttachment } - : {}), - ...nativeNvidiaDepartureRegistryFields({ - detached: previousNativeNvidiaDetached, - authority: previousNativeNvidiaAttachment ?? previousNativeNvidiaAuthority, - }), + ...nativeNvidiaDepartureRegistryFields(previousNativeNvidiaDetached), }); if ( !deps.updateSandbox( diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index d7ae4f9dfba..e07cdc4e170 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -15,17 +15,16 @@ import { NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, - normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, } from "./contract"; export { - normalizeNativeNvidiaProviderAttachment, NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_ENDPOINT, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, + normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, } from "./contract"; @@ -53,34 +52,11 @@ export function resolveGatewayNativeNvidiaProviderAuthority(input: { gatewayName: string; gatewayAuthority?: NativeNvidiaProviderAttachment | null; recordedAttachment?: NativeNvidiaProviderAttachment | null; - recordedAuthority?: NativeNvidiaProviderAttachment | null; - sandboxes: ReadonlyArray<{ - gatewayName?: string | null; - provider?: string | null; - nativeNvidiaProviderAttachment?: unknown; - nativeNvidiaProviderAuthority?: unknown; - }>; }): NativeNvidiaProviderAttachment | undefined { const authorities = new Map(); - for (const receipt of [ - input.gatewayAuthority, - input.recordedAttachment, - input.recordedAuthority, - ]) { + for (const receipt of [input.gatewayAuthority, input.recordedAttachment]) { if (receipt) authorities.set(receipt.providerId, receipt); } - for (const sandbox of input.sandboxes) { - if (sandbox.gatewayName !== input.gatewayName) continue; - const authority = normalizeNativeNvidiaProviderAttachment( - sandbox.nativeNvidiaProviderAuthority, - ); - const attachment = isNativeNvidiaProvider(sandbox.provider) - ? normalizeNativeNvidiaProviderAttachment(sandbox.nativeNvidiaProviderAttachment) - : undefined; - for (const receipt of [authority, attachment]) { - if (receipt) authorities.set(receipt.providerId, receipt); - } - } if (authorities.size > 1) { throw new NativeNvidiaProviderError( `Gateway '${input.gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 0cc439ce5ee..fcfbf536b5b 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -987,7 +987,6 @@ export function createSetupInference( gatewayName, gatewayAuthority: deps.getNativeNvidiaProviderAuthority?.(gatewayName), recordedAttachment, - sandboxes: deps.listSandboxes?.().sandboxes ?? [], }); nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ adapter: providerAdapter, diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index 2bae1d6d269..80f9b5e9610 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -6,7 +6,7 @@ import os from "node:os"; import path from "node:path"; import { expect, it, vi } from "vitest"; -it("admits native NVIDIA provider authority on a pending route reservation", async () => { +it("admits a pending route reservation without per-sandbox provider authority", async () => { const { classifySandboxInferenceRouteReservation } = await import("./registry/route-reservation"); const selection = { provider: "ollama-local", @@ -36,12 +36,6 @@ it("admits native NVIDIA provider authority on a pending route reservation", asy endpointSource: selection.endpointSource, credentialEnv: selection.credentialEnv, preferredInferenceApi: selection.preferredInferenceApi, - nativeNvidiaProviderAuthority: { - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "provider-id", - }, }); expect(disposition.kind).toBe("owned"); @@ -66,9 +60,7 @@ it("clears a stale native NVIDIA attachment when reserving a shared route", asyn gatewayName: "nemoclaw", gatewayPort: 8080, }); - expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAuthority).toMatchObject({ - providerId: "provider-id", - }); + expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeNvidiaProviderAuthority"); registry.reserveSandboxInferenceRoute("alpha", { provider: "anthropic-prod", @@ -80,7 +72,7 @@ it("clears a stale native NVIDIA attachment when reserving a shared route", asyn }); expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAttachment).toBeUndefined(); - expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAuthority).toBeUndefined(); + expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeNvidiaProviderAuthority"); } finally { await fs.rm(home, { recursive: true, force: true }); vi.unstubAllEnvs(); diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index 746bbd0ac1e..a334b690c8c 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -90,12 +90,10 @@ describe("sandbox registry normalization", () => { }); registry.clearNativeNvidiaProviderAuthority("nemoclaw-19080"); expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toBeUndefined(); - expect(registry.getSandbox("alpha")?.nativeNvidiaProviderAuthority).toBeUndefined(); - expect(registry.getSandbox("beta")?.nativeNvidiaProviderAuthority).toBeUndefined(); + expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeNvidiaProviderAuthority"); + expect(registry.getSandbox("beta")).not.toHaveProperty("nativeNvidiaProviderAuthority"); expect(registry.getSandbox("beta")?.nativeNvidiaProviderAttachment).toEqual(receipt); - expect(registry.getSandbox("gamma")?.nativeNvidiaProviderAuthority).toMatchObject({ - providerId: "22222222-3333-4444-8555-666666666666", - }); + expect(registry.getSandbox("gamma")).not.toHaveProperty("nativeNvidiaProviderAuthority"); }); it("persists incomplete OpenClaw synchronization until explicit completion", async () => { diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 2ba630bac43..07f6b0bbf42 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -493,12 +493,6 @@ export function registerSandbox( "Cannot register a sandbox with an invalid native NVIDIA provider attachment", ); } - const nativeNvidiaProviderAuthority = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAuthority ?? nativeNvidiaProviderAttachment, - ); - if (entry.nativeNvidiaProviderAuthority !== undefined && !nativeNvidiaProviderAuthority) { - throw new Error("Cannot register a sandbox with invalid native NVIDIA provider authority"); - } const registered: SandboxEntry = { name: entry.name, createdAt: entry.createdAt || new Date().toISOString(), @@ -550,7 +544,6 @@ export function registerSandbox( ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), - ...(nativeNvidiaProviderAuthority ? { nativeNvidiaProviderAuthority } : {}), lifecycleGeneration: entry.lifecycleGeneration, lifecycleLiveIdentityFingerprint: entry.lifecycleLiveIdentityFingerprint, messaging: cloneSandboxMessagingState(entry.messaging), @@ -602,7 +595,6 @@ type SandboxInferenceRouteReservation = Pick< hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; - nativeNvidiaProviderAuthority?: SandboxEntry["nativeNvidiaProviderAuthority"]; }; interface SandboxInferenceRouteReservationOptions { @@ -650,12 +642,6 @@ export function reserveSandboxInferenceRoute( if (route.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { throw new Error("Cannot reserve invalid native NVIDIA provider attachment identity"); } - const nativeNvidiaProviderAuthority = normalizeNativeNvidiaProviderAttachment( - route.nativeNvidiaProviderAuthority ?? nativeNvidiaProviderAttachment, - ); - if (route.nativeNvidiaProviderAuthority !== undefined && !nativeNvidiaProviderAuthority) { - throw new Error("Cannot reserve invalid native NVIDIA provider authority identity"); - } const provenance = cloneSandboxHostLocalInferenceProvenance(route.hostLocalInferenceProvenance); if ( route.hostLocalInferenceProvenance !== undefined && @@ -717,10 +703,6 @@ export function reserveSandboxInferenceRoute( existing.nativeNvidiaProviderAttachment, nativeNvidiaProviderAttachment ?? existing.nativeNvidiaProviderAttachment, ) && - isDeepStrictEqual( - existing.nativeNvidiaProviderAuthority, - nativeNvidiaProviderAuthority ?? existing.nativeNvidiaProviderAuthority, - ) && isDeepStrictEqual( normalizeInferenceSelection(existing), normalizeInferenceSelection(route), @@ -760,11 +742,6 @@ export function reserveSandboxInferenceRoute( nativeNvidiaProviderAttachment: isNativeNvidiaProvider(normalized.provider) ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) : undefined, - nativeNvidiaProviderAuthority: - nativeNvidiaProviderAuthority ?? - (existing?.gatewayName === route.gatewayName - ? existing.nativeNvidiaProviderAuthority - : undefined), ...(route.hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt: route.hostLocalInferenceReceipt } : {}), @@ -840,19 +817,7 @@ export function updateSandbox(name: string, updates: Partial): boo return false; } if (changesHostLocalInferenceLifecycleAuthority(current, updates)) return false; - const nativeNvidiaProviderAuthority = normalizeNativeNvidiaProviderAttachment( - updates.nativeNvidiaProviderAuthority, - ); - if (updates.nativeNvidiaProviderAuthority !== undefined && !nativeNvidiaProviderAuthority) { - throw new Error( - `Refusing to update sandbox '${name}' with invalid native NVIDIA provider authority.`, - ); - } - const normalizedUpdates = - updates.nativeNvidiaProviderAuthority === undefined - ? updates - : { ...updates, nativeNvidiaProviderAuthority }; - const next = normalizeSandboxPolicyAttribution({ ...current, ...normalizedUpdates }); + const next = normalizeSandboxPolicyAttribution({ ...current, ...updates }); if ( current.deferredN1xManagedVllmAccepted === true && Object.entries(updates).some( diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index a9461db6f08..68599dfec2c 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -34,19 +34,7 @@ export function setNativeNvidiaProviderAuthority( export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { withLock(() => { const data = load(); - let changed = applyRemoveNativeNvidiaProviderAuthority(data, gatewayName); - for (const [sandboxName, sandbox] of Object.entries(data.sandboxes)) { - if ( - sandbox.gatewayName !== gatewayName || - sandbox.nativeNvidiaProviderAuthority === undefined - ) { - continue; - } - const { nativeNvidiaProviderAuthority: _removedAuthority, ...retained } = sandbox; - data.sandboxes[sandboxName] = retained; - changed = true; - } - if (!changed) return; + if (!applyRemoveNativeNvidiaProviderAuthority(data, gatewayName)) return; save(data); }); } diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index 57672142a8a..57358f362dc 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -206,9 +206,14 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, deferredN1xManagedVllmAccepted: _deferredN1xManagedVllmAccepted, + nativeNvidiaProviderAuthority: _legacyNativeNvidiaProviderAuthority, mcp: _legacyMcp, ...rest - } = policyEntry as SandboxEntry & { cuaRuntimeReadiness?: unknown; mcp?: unknown }; + } = policyEntry as SandboxEntry & { + cuaRuntimeReadiness?: unknown; + nativeNvidiaProviderAuthority?: unknown; + mcp?: unknown; + }; return { ...rest, ...(workload ? { workload } : {}), @@ -265,9 +270,14 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, deferredN1xManagedVllmAccepted: _deferredN1xManagedVllmAccepted, + nativeNvidiaProviderAuthority: _legacyNativeNvidiaProviderAuthority, mcp: _legacyMcp, ...rest - } = policyEntry as SandboxEntry & { cuaRuntimeReadiness?: unknown; mcp?: unknown }; + } = policyEntry as SandboxEntry & { + cuaRuntimeReadiness?: unknown; + nativeNvidiaProviderAuthority?: unknown; + mcp?: unknown; + }; return { ...rest, ...(rest.dashboardPort === 0 ? { dashboardPort: null } : {}), diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 541f3b6090a..4ac16f5351b 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -23,7 +23,6 @@ const ROUTE_RESERVATION_KEYS = new Set([ "model", "name", "nativeNvidiaProviderAttachment", - "nativeNvidiaProviderAuthority", "openshellDriver", "pendingRouteReservation", "pendingCreateIdentity", @@ -89,12 +88,6 @@ function validCarriedRouteMetadata(entry: SandboxEntry): boolean { ) { return false; } - if ( - entry.nativeNvidiaProviderAuthority !== undefined && - !normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAuthority) - ) { - return false; - } return ( entry.webSearchProvider === undefined || entry.webSearchProvider === null || diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index b18e535c2b1..6eb7f8131df 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -135,8 +135,6 @@ export interface SandboxEntry extends Partial { hostLocalInferenceReceipt?: string | null; /** Exact OpenShell provider identity attached for native NVIDIA hosted inference. */ nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; - /** Durable ownership authority for the gateway-scoped native NVIDIA provider. */ - nativeNvidiaProviderAuthority?: NativeNvidiaProviderAttachment; /** Explicit hidden-lifecycle provenance; absence keeps llama.cpp on its legacy path. */ hostLocalInferenceProvenance?: SandboxHostLocalInferenceProvenance; /** Explicit Deferred N1x managed-vLLM choice retained after successful onboarding. */ From 21d531c42b2f85db46321cb273a9d09c00a0652b Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 16:31:35 -0700 Subject: [PATCH 049/133] fix(inference): verify provider credential discovery boundaries Signed-off-by: Deepak Jain --- .../openshell/provider-profile.test.ts | 29 ++++++++++++++++++- .../adapters/openshell/provider-profile.ts | 10 +++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/provider-profile.test.ts b/src/lib/adapters/openshell/provider-profile.test.ts index b3fe4e3e048..03eb4d39614 100644 --- a/src/lib/adapters/openshell/provider-profile.test.ts +++ b/src/lib/adapters/openshell/provider-profile.test.ts @@ -1,10 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; import path from "node:path"; import { describe, expect, it } from "vitest"; -import { endpointlessProviderProfilePath } from "./provider-profile"; +import { + endpointlessProviderProfilePath, + parseCheckedInProviderProfileContract, + exportedProviderProfileMatchesContract, +} from "./provider-profile"; const PROFILE_ID = "langfuse-hermes-v1"; @@ -15,3 +20,25 @@ describe("OpenShell endpointless provider profiles", () => { ); }); }); + +describe("provider credential discovery boundary", () => { + const profile = { + id: "test", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, + }; + it.each([ + [{ credentials: [] }, true], + [{ credentials: ["foreign-source"] }, false], + [{ credentials: "invalid" }, false], + [{ credentials: [1] }, false], + ])("compares credential discovery sources [case %#]", (discovery, accepted) => { + const expected = parseCheckedInProviderProfileContract(JSON.stringify(profile)); + assert(expected, "invalid fixture"); + expect( + exportedProviderProfileMatchesContract(JSON.stringify({ ...profile, discovery }), expected), + ).toBe(accepted); + }); +}); diff --git a/src/lib/adapters/openshell/provider-profile.ts b/src/lib/adapters/openshell/provider-profile.ts index 21d0343ae02..b6753eff9b3 100644 --- a/src/lib/adapters/openshell/provider-profile.ts +++ b/src/lib/adapters/openshell/provider-profile.ts @@ -11,6 +11,7 @@ type ProviderProfileBoundary = Readonly<{ endpoints: readonly unknown[]; binaries: readonly string[]; inference_capable: boolean; + discovery: { credentials: readonly string[] }; }>; export type CheckedInProviderProfileContract = Readonly<{ @@ -37,6 +38,14 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null ) { return null; } + const discovery = profile.discovery === undefined ? {} : recordValue(profile.discovery); + if ( + !discovery || + (discovery.credentials !== undefined && + (!Array.isArray(discovery.credentials) || + discovery.credentials.some((value) => typeof value !== "string"))) + ) + return null; const credentials = profile.credentials.map((value) => { const credential = recordValue(value); if ( @@ -74,6 +83,7 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null endpoints: profile.endpoints, binaries: profile.binaries as string[], inference_capable: profile.inference_capable, + discovery: { credentials: (discovery.credentials ?? []) as string[] }, }; } From 62db861fa2e1e15c700ae09ecba79ed60eae83f5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:04:13 -0700 Subject: [PATCH 050/133] fix: recover native NVIDIA provider registration Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/security/best-practices.mdx | 2 +- src/lib/actions/credentials-add.ts | 19 +++- .../credentials-provider-adapter.test.ts | 95 +++++++++++++------ 3 files changed, 83 insertions(+), 33 deletions(-) diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index 963bf69e493..5d369ef237c 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -114,7 +114,7 @@ NemoClaw allows a credential source only in the process that is intended to hold | Execution path | Rule | |---|---| -| Host-brokered provider | Discover and use host credentials only in the host adapter. The sandbox receives a narrow `inference.local` interface, not the host credentials. | +| Host-brokered provider | Discover and use host credentials only through OpenShell-managed providers. Most providers expose `inference.local`; NVIDIA Endpoints uses a sandbox-attached least-privilege provider with placeholder credential rewriting. The sandbox receives no raw host credential. | | Sandbox-direct provider | Keep only credential sources that are deliberately provisioned and reachable inside the sandbox. | | Ambient metadata provider | Disable SDK discovery when the metadata endpoint cannot exist across the sandbox boundary. Do not make an internal or link-local endpoint reachable merely to satisfy an automatic probe. | | New agent or provider | Declare the enabled credential sources and add agent-specific tests proving that unavailable sources are not probed. | diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index a880edbac01..d8290a19ee5 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -421,10 +421,21 @@ export async function runCredentialsAddAction( reuseExistingCredential: fromExisting, ...(expected ? { expected } : {}), }); - (deps.setNativeNvidiaProviderAuthority ?? setNativeNvidiaProviderAuthority)( - target.gatewayName, - receipt, - ); + if (!expected) { + try { + (deps.setNativeNvidiaProviderAuthority ?? setNativeNvidiaProviderAuthority)( + target.gatewayName, + receipt, + ); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + return fail([ + ` OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' was created, but NemoClaw could not record its ownership.`, + ` Run '${CLI_NAME} credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER} --yes' to remove the incomplete provider, then retry.`, + ` ${detail}`, + ]); + } + } return ok([ ` Registered provider '${provider}' with the OpenShell gateway.`, ` Verify with '${CLI_NAME} credentials list'.`, diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 42944571ab3..84e1e29704d 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -78,6 +78,40 @@ function providerAdapter( }; } +function nativeNvidiaProviderAdapter(): OpenShellProviderAdapter { + let providerPresent = false; + return providerAdapter({ + getProvider: vi.fn(async (request) => + providerPresent + ? { + ok: true as const, + value: { + name: request.providerName, + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { + id: "11111111-2222-4333-8444-555555555555", + resourceVersion: 1, + }, + }, + } + : { + ok: false as const, + error: { + kind: "command" as const, + reason: "not_found" as const, + message: "provider not found", + }, + }, + ), + createProvider: vi.fn(async () => { + providerPresent = true; + return { ok: true as const }; + }), + }); +} + describe("credential actions use typed OpenShell provider results", () => { beforeEach(() => { setGlobalCliActionRuntimeHooksForTest({ @@ -129,35 +163,8 @@ describe("credential actions use typed OpenShell provider results", () => { recordExtraProvider, forgetExtraProvider: () => true, }); - let providerPresent = false; const providerId = "11111111-2222-4333-8444-555555555555"; - const adapter = providerAdapter({ - getProvider: vi.fn(async (request) => - providerPresent - ? { - ok: true as const, - value: { - name: request.providerName, - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { id: providerId, resourceVersion: 1 }, - }, - } - : { - ok: false as const, - error: { - kind: "command" as const, - reason: "not_found" as const, - message: "provider not found", - }, - }, - ), - createProvider: vi.fn(async () => { - providerPresent = true; - return { ok: true as const }; - }), - }); + const adapter = nativeNvidiaProviderAdapter(); const setNativeNvidiaProviderAuthority = vi.fn(); const result = await runCredentialsAddAction( @@ -198,6 +205,38 @@ describe("credential actions use typed OpenShell provider results", () => { expect(JSON.stringify(result)).not.toContain("host-only-nvidia-value"); }); + it("reports a reset action when native NVIDIA authority persistence fails", async () => { + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "host-only-nvidia-value"); + const adapter = nativeNvidiaProviderAdapter(); + + const result = await runCredentialsAddAction( + { + provider: "nvidia-prod", + type: "nvidia", + credentials: ["NVIDIA_INFERENCE_API_KEY"], + configPairs: [], + fromExisting: false, + }, + { + providerAdapter: adapter, + getNativeNvidiaProviderAuthority: () => undefined, + setNativeNvidiaProviderAuthority: () => { + throw new Error("state directory is read-only"); + }, + }, + ); + + expect(result.exitCode).toBe(1); + expect(result.failureLines).toContain( + " OpenShell provider 'nemoclaw-nvidia-prod-v1' was created, but NemoClaw could not record its ownership.", + ); + expect(result.failureLines).toContain( + " Run 'nemoclaw credentials reset nvidia-prod --yes' to remove the incomplete provider, then retry.", + ); + expect(result.failureLines).toContain(" state directory is read-only"); + expect(JSON.stringify(result)).not.toContain("host-only-nvidia-value"); + }); + it("rejects a substituted native NVIDIA provider before replacing its credential", async () => { vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "host-only-nvidia-value"); const adapter = providerAdapter({ From c8725eb505d1523ffb70036b52950de0c28365ee Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 17:57:48 -0700 Subject: [PATCH 051/133] fix(inference): address native hosted provider review findings Signed-off-by: Deepak Jain --- agents/langchain-deepagents-code/Dockerfile | 4 +- .../generate-config.ts | 9 +- docs/about/how-it-works.mdx | 5 +- .../inference/how-inference-routing-works.mdx | 21 +- .../understand-provider-validation.mdx | 3 +- docs/inference/use-anthropic.mdx | 1 + docs/inference/use-google-gemini.mdx | 2 +- docs/inference/use-hermes-provider.mdx | 3 +- docs/inference/use-openai.mdx | 2 +- docs/inference/use-openrouter.mdx | 23 +- docs/inference/verify-inference-route.mdx | 16 +- .../inference/view-active-inference-route.mdx | 19 +- .../actions/sandbox/inference-route-health.ts | 3 +- src/lib/inference/config.ts | 3 - src/lib/inference/native-hosted/index.test.ts | 4 +- src/lib/inference/native-nvidia.test.ts | 64 ++-- src/lib/inference/native-nvidia/index.ts | 319 +----------------- .../langchain-deepagents-code-config.test.ts | 17 + .../langchain-deepagents-code-image.test.ts | 6 + .../live/podman-portable-uninstall.test.ts | 23 +- .../native-nvidia-target-ownership.test.ts | 1 + tools/e2e/target-catalogue.mts | 2 + 22 files changed, 144 insertions(+), 406 deletions(-) diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index 67b21384834..dffc200201f 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -155,7 +155,9 @@ RUN set -eu; \ COPY agents/langchain-deepagents-code/generate-config-entrypoint.ts /opt/nemoclaw-deepagents-code/generate-config.ts COPY agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts COPY src/lib/inference/native-hosted/openrouter-headers.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/openrouter-headers.ts -RUN chmod 444 /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/openrouter-headers.ts +COPY src/lib/inference/native-hosted/profiles.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts +RUN chmod 444 /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts \ + /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/openrouter-headers.ts COPY src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts COPY src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts COPY agents/langchain-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py diff --git a/agents/langchain-deepagents-code/generate-config.ts b/agents/langchain-deepagents-code/generate-config.ts index 9377d9b2965..117b5f957c2 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -15,7 +15,7 @@ import { normalizeManagedDcodeEndpointUrl, resolveManagedDcodeIdentity, } from "../../src/lib/inference/managed-dcode/identity.ts"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../src/lib/inference/native-nvidia/contract.ts"; +import { NATIVE_HOSTED_PROFILES } from "../../src/lib/inference/native-hosted/profiles.ts"; import { OPENROUTER_DEFAULT_HEADERS } from "../../src/lib/inference/native-hosted/openrouter-headers.ts"; @@ -163,10 +163,9 @@ function providerConfigLines( baseUrl: string, reasoningEffort: ReasoningEffort | null, ): string[] { - const apiKeyEnv = - baseUrl === NVIDIA_HOSTED_NATIVE_ENDPOINT - ? ATTACHED_PROVIDER_API_KEY_ENV - : MANAGED_INFERENCE_API_KEY_ENV; + const apiKeyEnv = NATIVE_HOSTED_PROFILES.some((profile) => profile.endpoint === baseUrl) + ? ATTACHED_PROVIDER_API_KEY_ENV + : MANAGED_INFERENCE_API_KEY_ENV; return [ `[models.providers.${provider}]`, `models = ${tomlArray([model])}`, diff --git a/docs/about/how-it-works.mdx b/docs/about/how-it-works.mdx index 4bb9cfd3a3c..110a3e75fa5 100644 --- a/docs/about/how-it-works.mdx +++ b/docs/about/how-it-works.mdx @@ -210,8 +210,9 @@ Refer to [Recover and Rebuild Sandboxes](../manage-sandboxes/operate-sandboxes/r ## Inference Routing -Most managed providers send model requests through `inference.local` instead of directly to an upstream endpoint. -NVIDIA Endpoints uses a sandbox-attached OpenShell provider that permits approved requests to `integrate.api.nvidia.com`. +NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider use sandbox-attached OpenShell providers. +The agent calls the selected provider's native endpoint, and OpenShell supplies its credential only for approved requests. +Custom endpoints and local providers retain the shared `inference.local` route. During onboarding, NemoClaw validates the selected provider and model, configures the applicable OpenShell route or provider attachment, and writes the matching model reference into the managed agent configuration. In both paths, OpenShell keeps the provider credential outside the sandbox and sends only approved requests to the upstream endpoint. When you select the Model Router provider, `inference.local` routes to a host-side router that chooses from a configured model pool available through NVIDIA Endpoints for each request. diff --git a/docs/inference/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index f8bbf7c65f3..681faf3451b 100644 --- a/docs/inference/how-inference-routing-works.mdx +++ b/docs/inference/how-inference-routing-works.mdx @@ -14,23 +14,23 @@ This design keeps provider credentials outside the sandbox. ## Request Path -Most providers use the shared `inference.local` route inside the sandbox. -OpenShell intercepts each request on the host and forwards it to the provider and model selected during onboarding. +NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider use sandbox-attached OpenShell providers. +The agent addresses the selected provider's native endpoint, and OpenShell supplies the credential for approved requests. ```text -Sandbox agent -> inference.local -> shared OpenShell route -> selected provider and model +Sandbox agent -> provider API hostname -> sandbox-attached OpenShell provider -> selected provider ``` -NVIDIA Endpoints use a sandbox-attached OpenShell provider instead of the shared route. -The agent addresses the NVIDIA API hostname, but OpenShell still intercepts the request and supplies the host-managed credential. +Each sandbox receives its selected provider attachment. +A failed native request does not fall back to `inference.local`. + +Custom endpoints, local providers, and Model Router retain the shared OpenShell route. +The sandbox uses `inference.local` for those selections. ```text -Sandbox agent -> integrate.api.nvidia.com -> sandbox-attached OpenShell provider -> NVIDIA +Sandbox agent -> inference.local -> shared OpenShell route -> selected provider and model ``` -Host-side services such as Model Router and the OpenRouter runtime adapter remain behind the OpenShell route. -The sandbox uses `inference.local` for those services instead of calling their host ports directly. - ## Credential Boundary Provider credentials stay on the host and flow through the OpenShell provider system. @@ -45,7 +45,8 @@ When a rebuild reuses an automatically bridged compatible-endpoint route without ## Deep Agents Configuration -For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with a managed OpenAI-compatible provider, a scoped placeholder API key, and `use_responses_api = false`. Most providers use `https://inference.local/v1`. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox at `https://integrate.api.nvidia.com/v1`. +For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with a managed OpenAI-compatible provider, a scoped placeholder API key, and `use_responses_api = false`. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. +Custom and local selections retain `https://inference.local/v1`. The managed `dcode` runtime uses Chat Completions through OpenShell even when a compatible endpoint also supports the Responses API. diff --git a/docs/inference/understand-provider-validation.mdx b/docs/inference/understand-provider-validation.mdx index a9de17568bc..20e54d2534e 100644 --- a/docs/inference/understand-provider-validation.mdx +++ b/docs/inference/understand-provider-validation.mdx @@ -52,7 +52,8 @@ If the last retry fails or times out, validation stops without another Chat Comp -The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. +The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. +Custom and local selections retain `https://inference.local/v1`. `NEMOCLAW_PREFERRED_API` does not change that runtime selection. diff --git a/docs/inference/use-anthropic.mdx b/docs/inference/use-anthropic.mdx index 913589f97d5..a9f295e287d 100644 --- a/docs/inference/use-anthropic.mdx +++ b/docs/inference/use-anthropic.mdx @@ -11,6 +11,7 @@ content: --- The Anthropic provider routes supported agents to the native Anthropic Messages API through OpenShell. The provider uses the `anthropic-messages` protocol. +OpenShell attaches the provider to the selected sandbox and supplies credentials for approved requests to `https://api.anthropic.com`. ## Credential diff --git a/docs/inference/use-google-gemini.mdx b/docs/inference/use-google-gemini.mdx index 2ff8745839d..bec21eb9258 100644 --- a/docs/inference/use-google-gemini.mdx +++ b/docs/inference/use-google-gemini.mdx @@ -10,7 +10,7 @@ content: type: "how_to" --- The Google Gemini provider routes NemoClaw to Google's OpenAI-compatible Chat Completions endpoint. -The sandbox continues to use the managed `inference.local` route. +The sandbox calls `https://generativelanguage.googleapis.com/v1beta/openai` through its attached OpenShell provider. ## Credential diff --git a/docs/inference/use-hermes-provider.mdx b/docs/inference/use-hermes-provider.mdx index 979b292d35a..a75ad08cc55 100644 --- a/docs/inference/use-hermes-provider.mdx +++ b/docs/inference/use-hermes-provider.mdx @@ -15,7 +15,8 @@ This option is available only for Hermes Agent. ## Credential Boundary -NemoClaw uses the host OpenShell provider registered during onboarding. +NemoClaw attaches the hosted provider to the selected sandbox during onboarding. +Hermes calls `https://inference-api.nousresearch.com/v1`, and OpenShell supplies the provider credential for approved requests. The sandbox does not receive raw provider credentials. ## Model Choices diff --git a/docs/inference/use-openai.mdx b/docs/inference/use-openai.mdx index 1128ef8f655..f66e6bd1a7e 100644 --- a/docs/inference/use-openai.mdx +++ b/docs/inference/use-openai.mdx @@ -10,7 +10,7 @@ content: type: "how_to" --- The OpenAI provider routes NemoClaw inference to the OpenAI API through OpenShell. -The sandbox uses the managed `inference.local` route and does not receive the raw OpenAI API key. +The sandbox calls `https://api.openai.com/v1` through its attached OpenShell provider and does not receive the raw OpenAI API key. ## Credential diff --git a/docs/inference/use-openrouter.mdx b/docs/inference/use-openrouter.mdx index 2c5f4042e38..e72a6661176 100644 --- a/docs/inference/use-openrouter.mdx +++ b/docs/inference/use-openrouter.mdx @@ -4,13 +4,13 @@ title: "Use OpenRouter" sidebar-title: "Use OpenRouter" description: "Configure NemoClaw to route hosted inference through OpenRouter." -description-agent: "Sets up OpenRouter as the NemoClaw inference provider. Use when onboarding with an OpenRouter API key or tracing the OpenRouter host adapter." -keywords: ["NemoClaw OpenRouter", "OpenRouter API key", "OpenRouter adapter"] +description-agent: "Sets up OpenRouter as the NemoClaw inference provider. Use when onboarding with an OpenRouter API key or checking native OpenRouter routing." +keywords: ["NemoClaw OpenRouter", "OpenRouter API key", "OpenRouter native endpoint"] content: type: "how_to" --- OpenRouter provides an OpenAI-compatible Chat Completions route for OpenClaw, Hermes, and LangChain Deep Agents Code. -NemoClaw keeps the sandbox on `https://inference.local/v1` and sends upstream traffic through a host adapter. +The sandbox calls `https://openrouter.ai/api/v1` through its attached OpenShell provider. ## Credential @@ -32,19 +32,12 @@ Run the onboarding wizard and select **OpenRouter**. $$nemoclaw onboard ``` -NemoClaw registers the `openrouter-api` provider through the OpenShell `openai` profile. +NemoClaw installs its OpenRouter provider profile and attaches the provider to the selected sandbox. -## Host Adapter +## Request Headers -NemoClaw starts or reuses a local host adapter on port `11437` by default. -It registers OpenShell with `OPENAI_BASE_URL=http://host.openshell.internal:11437/v1`. - -The adapter accepts only the OpenShell bearer credential bound during setup and forwards requests to `https://openrouter.ai/api/v1`. -It adds the default `HTTP-Referer` and `X-OpenRouter-Title` attribution headers. -The adapter does not store the API key. - -The adapter exposes a host health endpoint and writes logs to `~/.nemoclaw/openrouter-runtime-adapter.log`. -Set `NEMOCLAW_OPENROUTER_RUNTIME_ADAPTER_PORT` before onboarding to use a different host port. +NemoClaw configures the agent to send the `HTTP-Referer` and `X-OpenRouter-Title` attribution headers. +OpenShell keeps the API key outside the sandbox and replaces the agent's credential placeholder for approved OpenRouter requests. ## Validation @@ -53,5 +46,5 @@ NemoClaw skips the Responses API probe and uses managed Chat Completions at runt ## Related Topics -- [About Inference Routing](../about-inference-routing) explains why the sandbox does not call the adapter directly. +- [About Inference Routing](../about-inference-routing) explains the sandbox-attached provider and credential boundary. - [Understand Provider Validation](../validate-inference/understand-provider-validation) describes provider validation behavior. diff --git a/docs/inference/verify-inference-route.mdx b/docs/inference/verify-inference-route.mdx index 3676d330161..d037b8ae2ef 100644 --- a/docs/inference/verify-inference-route.mdx +++ b/docs/inference/verify-inference-route.mdx @@ -4,7 +4,7 @@ title: "Verify the Sandbox Inference Route" sidebar-title: "Verify the Inference Route" description: "Verify that a NemoClaw sandbox can reach its configured model through its selected inference provider." -description-agent: "Verifies the in-sandbox inference path for native NVIDIA providers and shared inference routes." +description-agent: "Verifies the in-sandbox inference path for native hosted providers and shared inference routes." keywords: ["verify inference provider", "nemoclaw inference route", "sandbox inference health"] content: type: "how_to" @@ -14,14 +14,14 @@ Reading the active route confirms configuration, but it does not authenticate a ## Confirm the Configured Route -Read the live gateway route first. +Read the selected sandbox configuration first. ```bash -$$nemoclaw inference get +$$nemoclaw inference get ``` Confirm that the provider, model, and endpoint match the route you intended to configure. -NVIDIA Endpoints reports `https://integrate.api.nvidia.com/v1` instead of `inference.local`. +Fixed hosted providers report their native endpoint, such as `https://api.openai.com/v1` for OpenAI. ## Check Sandbox Inference Health @@ -31,9 +31,9 @@ Run the named sandbox status command. $$nemoclaw status ``` -For NVIDIA Endpoints, the `Inference` row verifies the recorded sandbox attachment. -It then sends a native Chat Completions request to `https://integrate.api.nvidia.com/v1`. -It does not probe `https://inference.local/v1/models` for this provider. +For fixed hosted providers, the `Inference` row verifies the recorded sandbox attachment. +It then sends an inference request to the selected native endpoint using the configured API family. +It does not probe `https://inference.local/v1/models` for these providers. For shared-route providers, the `Inference` row first checks the sandbox's `inference.local` path. When that route responds, `status` sends an inference request through the same path. @@ -73,7 +73,7 @@ For those routes, continue to the final route check, then use the status command ## Understand Final Route Checks -For NVIDIA Endpoints, onboarding verifies the sandbox-attached provider through the native endpoint. +For fixed hosted providers, onboarding verifies the sandbox-attached provider through the selected native endpoint. It does not request the shared `inference.local` models route. For shared-route providers, onboarding first requests `https://inference.local/v1/models` from inside the sandbox after policy and process recovery. diff --git a/docs/inference/view-active-inference-route.mdx b/docs/inference/view-active-inference-route.mdx index 8cff87588f9..b96c96e40ef 100644 --- a/docs/inference/view-active-inference-route.mdx +++ b/docs/inference/view-active-inference-route.mdx @@ -11,14 +11,15 @@ content: type: "how_to" --- -Use the NemoClaw CLI to read the provider and model on the live OpenShell inference route. +Use the NemoClaw CLI to read the selected sandbox's native provider configuration or the live shared OpenShell inference route. For a compatible custom provider, the command also reports its persisted endpoint URL when the registry provider and model match the live route. This command reports configuration state and does not authenticate a model request. ## Read the Live Route Run the direct route command when you need the active provider, model, and applicable custom endpoint URL. -The direct form reads the gateway that `NEMOCLAW_GATEWAY_PORT` selects. +The direct form uses the default sandbox when it has a recorded native provider attachment. +Otherwise, it reads the shared route on the gateway that `NEMOCLAW_GATEWAY_PORT` selects. ```bash $$nemoclaw inference get @@ -29,6 +30,7 @@ Expected output: ```text Provider: nvidia-prod Model: nvidia/nemotron-3-super-120b-a12b +Endpoint: https://integrate.api.nvidia.com/v1 ``` Pass `--json` for machine-readable output. @@ -42,7 +44,8 @@ Expected output: ```json { "provider": "nvidia-prod", - "model": "nvidia/nemotron-3-super-120b-a12b" + "model": "nvidia/nemotron-3-super-120b-a12b", + "endpointUrl": "https://integrate.api.nvidia.com/v1" } ``` @@ -66,7 +69,9 @@ Endpoint: https://inference.example.com/v1 } ``` -Managed providers keep the existing provider-and-model output. +Native hosted providers report the provider and model recorded for the selected sandbox, plus the profile's fixed endpoint. +This output does not verify that the attachment or credential is currently usable; run the named sandbox status command for that check. +The following endpoint-omission rules apply to shared compatible routes. Unpublished sandbox rows do not participate in endpoint selection. Equivalent stored URL forms, such as a trailing slash difference, count as the same endpoint identity. NemoClaw omits the endpoint when participating registry metadata is absent, conflicting, invalid, too long, uses another path shape, or contains userinfo, a query, a fragment, control characters, or recognized credential material in any URL component. @@ -96,10 +101,12 @@ $$nemoclaw inference get ``` `NEMOCLAW_GATEWAY_PORT` first selects the sandbox registry and fallback gateway. -When that registry contains the named sandbox, the command resolves its recorded gateway and reads that gateway-wide route. +When the named sandbox has a recorded native hosted provider attachment, the command reports its own provider, model, and endpoint. +For a shared-route selection, the command resolves the recorded gateway and reads that gateway-wide route. For a compatible custom provider, the command reports an endpoint only when every eligible published row on the resolved gateway matches the live route and records the same safe, reusable endpoint. The command does not search registries for other gateway ports. -OpenShell exposes one inference route to every sandbox registered on the same gateway. +The shared inference route applies to sandboxes that still use `inference.local`. +Native hosted selections use their own sandbox attachments. ## Include Sandbox Health diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index d6c5d84e4d4..c6f457f5d65 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -16,7 +16,6 @@ import { } from "../../inference/native-hosted"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT, - verifyNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, } from "../../inference/native-nvidia"; @@ -56,7 +55,7 @@ export async function verifyNativeNvidiaStatusAttachment(input: { await input.verify(input); return; } - await verifyNativeNvidiaProviderAttachment({ + await verifyNativeHostedProviderAttachment({ adapter: createCliOpenShellProviderAdapter(), target: { kind: "named", gatewayName: input.gatewayName }, sandboxName: input.sandboxName, diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 7f0081b44da..5551bc364d5 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -33,9 +33,6 @@ export { } from "./native-hosted"; export type { NativeHostedProviderAttachment } from "./native-hosted"; export { - detachNativeNvidiaProvider, - ensureNativeNvidiaProvider, - ensureNativeNvidiaProviderAttached, isNativeNvidiaProvider, NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_ENDPOINT, diff --git a/src/lib/inference/native-hosted/index.test.ts b/src/lib/inference/native-hosted/index.test.ts index c06cceab6e3..d204dc326c6 100644 --- a/src/lib/inference/native-hosted/index.test.ts +++ b/src/lib/inference/native-hosted/index.test.ts @@ -18,9 +18,7 @@ import { NATIVE_HOSTED_PROFILES } from "./profiles"; const target = { kind: "named", gatewayName: "nemoclaw" } as const; -describe.each( - NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"), -)("native $label OpenShell provider", (profile) => { +describe.each(NATIVE_HOSTED_PROFILES)("native $label OpenShell provider", (profile) => { function metadata(overrides: Record = {}) { return { name: profile.providerName, diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index 0b248f47b2d..bf6d6f610fc 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -7,16 +7,22 @@ import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { parseCheckedInProviderProfileContract } from "../adapters/openshell/provider-profile"; import { - ensureNativeNvidiaProvider, - ensureNativeNvidiaProviderAttached, - nativeNvidiaProviderProfilePath, - NativeNvidiaProviderError, NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, - verifyNativeNvidiaProviderAttachment, } from "./native-nvidia"; +import { + ensureNativeHostedProvider, + ensureNativeHostedProviderAttached, + nativeHostedProviderProfilePath, + NativeHostedProviderError, + verifyNativeHostedProviderAttachment, +} from "./native-hosted"; +import { nativeHostedProfile } from "./native-hosted/profiles"; + +const profile = nativeHostedProfile("nvidia-prod")!; + const target = { kind: "named", gatewayName: "nemoclaw" } as const; function metadata(overrides: Record = {}) { @@ -53,11 +59,11 @@ function adapter(overrides: Partial = {}): OpenShellPr describe("native NVIDIA OpenShell provider", () => { it("ships a profile limited to the native models and chat-completions operations (#12558)", () => { - const source = fs.readFileSync(nativeNvidiaProviderProfilePath(), "utf8"); - const profile = parseCheckedInProviderProfileContract(source); + const source = fs.readFileSync(nativeHostedProviderProfilePath(profile), "utf8"); + const contract = parseCheckedInProviderProfileContract(source); - expect(profile?.profileId).toBe(NVIDIA_HOSTED_NATIVE_PROFILE_ID); - expect(profile?.boundary.endpoints).toEqual([ + expect(contract?.profileId).toBe(NVIDIA_HOSTED_NATIVE_PROFILE_ID); + expect(contract?.boundary.endpoints).toEqual([ expect.objectContaining({ host: "integrate.api.nvidia.com", port: 443, @@ -68,7 +74,7 @@ describe("native NVIDIA OpenShell provider", () => { ], }), ]); - expect(profile?.boundary.binaries).not.toEqual( + expect(contract?.boundary.binaries).not.toEqual( expect.arrayContaining([expect.stringMatching(/[?*]/u)]), ); }); @@ -87,7 +93,8 @@ describe("native NVIDIA OpenShell provider", () => { const providerAdapter = adapter({ getProvider, createProvider }); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: providerAdapter, target, credentialValue: "opaque-test-secret", @@ -122,7 +129,8 @@ describe("native NVIDIA OpenShell provider", () => { })); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: adapter({ getProvider, createProvider }), target, credentialValue: "opaque-test-secret", @@ -144,7 +152,8 @@ describe("native NVIDIA OpenShell provider", () => { })); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: adapter({ getProvider, createProvider }), target, credentialValue: null, @@ -164,7 +173,8 @@ describe("native NVIDIA OpenShell provider", () => { const updateProvider = vi.fn(); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: adapter({ getProvider: vi.fn(async () => ({ ok: true, @@ -190,7 +200,8 @@ describe("native NVIDIA OpenShell provider", () => { const attachProvider = vi.fn(); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: adapter({ updateProvider, attachProvider }), target, credentialValue: "opaque-test-secret", @@ -211,7 +222,8 @@ describe("native NVIDIA OpenShell provider", () => { })); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: adapter({ getProvider, updateProvider }), target, credentialValue: "replacement-secret", @@ -231,7 +243,8 @@ describe("native NVIDIA OpenShell provider", () => { const createProvider = vi.fn(); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: adapter({ getProvider: vi.fn(async () => ({ ok: false, @@ -267,7 +280,8 @@ describe("native NVIDIA OpenShell provider", () => { }); await expect( - ensureNativeNvidiaProvider({ + ensureNativeHostedProvider({ + profile, adapter: providerAdapter, target, credentialValue: "opaque-test-secret", @@ -284,14 +298,16 @@ describe("native NVIDIA OpenShell provider", () => { }); await expect( - verifyNativeNvidiaProviderAttachment({ + verifyNativeHostedProviderAttachment({ + profile, adapter: providerAdapter, target, sandboxName: "alpha", }), - ).rejects.toThrow(NativeNvidiaProviderError); + ).rejects.toThrow(NativeHostedProviderError); await expect( - verifyNativeNvidiaProviderAttachment({ + verifyNativeHostedProviderAttachment({ + profile, adapter: providerAdapter, target, sandboxName: "alpha", @@ -312,7 +328,8 @@ describe("native NVIDIA OpenShell provider", () => { const providerAdapter = adapter({ listProviderAttachments, detachProvider }); await expect( - ensureNativeNvidiaProviderAttached({ + ensureNativeHostedProviderAttached({ + profile, adapter: providerAdapter, target, sandboxName: "alpha", @@ -342,7 +359,8 @@ describe("native NVIDIA OpenShell provider", () => { }); await expect( - ensureNativeNvidiaProviderAttached({ + ensureNativeHostedProviderAttached({ + profile, adapter: adapter({ listProviderAttachments }), target, sandboxName: "alpha", diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index e07cdc4e170..0c34e0421a2 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -1,22 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import path from "node:path"; - -import type { - OpenShellGatewayTarget, - OpenShellProviderAdapter, - OpenShellProviderError, - OpenShellProviderMetadata, -} from "../../adapters/openshell/sandbox-observer"; -import { REPOSITORY_ROOT } from "../../core/repository-root"; -import { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - type NativeNvidiaProviderAttachment, -} from "./contract"; +import { NVIDIA_HOSTED_LOGICAL_PROVIDER, type NativeNvidiaProviderAttachment } from "./contract"; export { NVIDIA_HOSTED_CREDENTIAL_ENV, @@ -35,15 +20,6 @@ export class NativeNvidiaProviderError extends Error { } } -export function nativeNvidiaProviderProfilePath(root = REPOSITORY_ROOT): string { - return path.join( - root, - "managed-inference", - "provider-profiles", - `${NVIDIA_HOSTED_NATIVE_PROFILE_ID}.yaml`, - ); -} - export function isNativeNvidiaProvider(provider: string | null | undefined): boolean { return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; } @@ -64,296 +40,3 @@ export function resolveGatewayNativeNvidiaProviderAuthority(input: { } return authorities.values().next().value; } - -export function nativeInferenceProviderForSandbox( - provider: string | null | undefined, -): string | null { - const normalized = provider?.trim() || null; - return isNativeNvidiaProvider(normalized) ? NVIDIA_HOSTED_NATIVE_PROVIDER : normalized; -} - -function providerErrorDetail(error: OpenShellProviderError): string { - return error.message.trim() || "OpenShell did not provide a diagnostic."; -} - -function exactNativeProvider(metadata: OpenShellProviderMetadata): boolean { - return ( - metadata.name === NVIDIA_HOSTED_NATIVE_PROVIDER && - metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID && - metadata.configKeys.length === 0 && - metadata.credentialKeys.length === 1 && - metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && - Boolean(metadata.revision?.id) - ); -} - -function attachmentFromMetadata( - metadata: OpenShellProviderMetadata, -): NativeNvidiaProviderAttachment { - if (!exactNativeProvider(metadata) || !metadata.revision) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' does not match the NemoClaw-owned NVIDIA inference boundary. No provider was changed.`, - ); - } - return { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: metadata.revision.id, - }; -} - -async function inspectNativeProvider( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, -): Promise { - const observed = await adapter.getProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (observed.ok) return observed.value; - if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; - throw new NativeNvidiaProviderError( - `Could not inspect OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(observed.error)}`, - ); -} - -function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { - return ( - error.kind === "timeout" || - (error.kind === "transport" && - (error.reason === "connection_loss" || error.reason === "unreachable")) || - (error.kind === "command" && error.reason === "uncertain") - ); -} - -/** Ensure the least-privilege NVIDIA profile and provider without retrying an ambiguous mutation. */ -export async function ensureNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - credentialValue: string | null; - reuseExistingCredential?: boolean; - expected?: NativeNvidiaProviderAttachment; - profilePath?: string; -}): Promise { - const { adapter, target } = input; - const imported = await adapter.importProviderProfile({ - target, - profilePath: input.profilePath ?? nativeNvidiaProviderProfilePath(), - }); - if (!imported.ok) { - const collision = - imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; - throw new NativeNvidiaProviderError( - collision - ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` - : `Could not prepare OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, - ); - } - - const before = await inspectNativeProvider(adapter, target); - if (before) { - const receipt = attachmentFromMetadata(before); - if (!input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' already exists without a matching NemoClaw ownership receipt. No provider was changed.`, - ); - } - if (input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - if (!input.credentialValue) return receipt; - const updated = await adapter.updateProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], - config: [], - }); - if (!updated.ok && mutationOutcomeMayBeAmbiguous(updated.error)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm whether provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' accepted its credential update. No provider receipt was recorded.`, - ); - } - if (!updated.ok) { - throw new NativeNvidiaProviderError( - `Could not update OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(updated.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after its credential update.`, - ); - } - return attachmentFromMetadata(observed); - } - - if (input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - - if (!input.credentialValue && !input.reuseExistingCredential) { - throw new NativeNvidiaProviderError( - `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, - ); - } - const created = await adapter.createProvider({ - target, - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: input.credentialValue - ? [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }] - : [], - config: [], - fromExisting: !input.credentialValue, - }); - if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { - throw new NativeNvidiaProviderError( - `Could not create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(created.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after creation.`, - ); - } - return attachmentFromMetadata(observed); -} - -/** Prove that the exact NemoClaw-owned NVIDIA provider is attached to one sandbox. */ -export async function verifyNativeNvidiaProviderAttachment(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected?: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = attachmentFromMetadata(provider); - if (input.expected && input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const attachments = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!attachments.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, - ); - } - if (!attachments.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `Sandbox '${input.sandboxName}' does not have its native NVIDIA inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, - ); - } - return receipt; -} - -/** Attach native NVIDIA access and reconcile an ambiguous command through observation. */ -export async function ensureNativeNvidiaProviderAttached(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = attachmentFromMetadata(provider); - if (receipt.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const before = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!before.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, - ); - } - if (before.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: false, - }; - } - const attached = await input.adapter.attachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { - throw new NativeNvidiaProviderError( - `Could not attach native NVIDIA provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, - ); - } - try { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: true, - }; - } catch (error) { - try { - await detachNativeNvidiaProvider(input); - } catch (detachError) { - const detail = error instanceof Error ? error.message : String(error); - const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); - throw new NativeNvidiaProviderError(`${detail}\n ${detachDetail}`); - } - throw error; - } -} - -/** Detach only the recorded native NVIDIA provider identity and prove absence. */ -export async function detachNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = attachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to detach OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const detached = await input.adapter.detachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { - throw new NativeNvidiaProviderError( - `Could not detach native NVIDIA provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, - ); - } - const after = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!after.ok || after.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm removal of native NVIDIA access from sandbox '${input.sandboxName}'.`, - ); - } -} diff --git a/test/agents/deepagents/langchain-deepagents-code-config.test.ts b/test/agents/deepagents/langchain-deepagents-code-config.test.ts index 897e531b408..890e49aafc0 100644 --- a/test/agents/deepagents/langchain-deepagents-code-config.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-config.test.ts @@ -95,6 +95,23 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).not.toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); }); + it.each([ + ["openai-api", "https://api.openai.com/v1"], + ["anthropic-prod", "https://api.anthropic.com"], + ["gemini-api", "https://generativelanguage.googleapis.com/v1beta/openai"], + ["openrouter-api", "https://openrouter.ai/api/v1"], + ["hermes-provider", "https://inference-api.nousresearch.com/v1"], + ])("uses the attached-provider placeholder for native %s (#12589)", (provider, endpoint) => { + const config = runGenerator({ + NEMOCLAW_UPSTREAM_PROVIDER: provider, + NEMOCLAW_INFERENCE_BASE_URL: endpoint, + }); + + expect(config).toContain(`base_url = "${endpoint}"`); + expect(config).toContain('api_key_env = "NEMOCLAW_ATTACHED_PROVIDER_API_KEY"'); + expect(config).not.toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); + }); + it("keeps the legacy provider key when the renamed route variables are absent", () => { const config = runGenerator({ NEMOCLAW_PROVIDER_KEY: "legacy-route", diff --git a/test/agents/deepagents/langchain-deepagents-code-image.test.ts b/test/agents/deepagents/langchain-deepagents-code-image.test.ts index 27bb0a9e173..d2ed3168a4a 100644 --- a/test/agents/deepagents/langchain-deepagents-code-image.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-image.test.ts @@ -239,6 +239,12 @@ describe("LangChain Deep Agents Code image contracts", () => { "COPY src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts", ); expect(dockerfile).toContain("node /opt/nemoclaw-deepagents-code/generate-config.ts"); + expect(dockerfile).toContain( + "COPY src/lib/inference/native-hosted/profiles.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts", + ); + expect(dockerfile).toContain( + "RUN chmod 444 /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts", + ); expect(dockerfile).not.toContain("langchain-deepagents-code-sandbox-base:latest"); expect(dockerfile).toContain( 'timeout 10 env -i /usr/local/lib/nemoclaw/dcode-wrapper.sh -n ""', diff --git a/test/e2e/live/podman-portable-uninstall.test.ts b/test/e2e/live/podman-portable-uninstall.test.ts index b747b88f986..82cae494918 100644 --- a/test/e2e/live/podman-portable-uninstall.test.ts +++ b/test/e2e/live/podman-portable-uninstall.test.ts @@ -119,7 +119,7 @@ function writePortableUninstallSummary(artifactDir: string | undefined, uid: num test( "runs full portable uninstall before a clean socket restart and reinstall start (#9189)", { meta: { e2ePhases: E2E_PHASES }, timeout: 300_000 }, - async ({ progress, shellProbe }) => { + async ({ artifacts, progress, shellProbe }) => { progress.phase("pin the current-user Podman authority"); expect(process.platform).toBe("linux"); const uid = process.getuid?.() ?? -1; @@ -177,11 +177,22 @@ test( ); progress.phase("create receipt-owned and unrelated resources"); - expect( - [...imageWasPresent.keys()].every((image) => - Object.is(engine.capture(["pull", image]).status, 0), - ), - ).toBe(true); + const pullArtifacts: Array> = []; + const imagesPulled = [...imageWasPresent.keys()].every((image, index) => { + const pull = engine.capture(["pull", image]); + pullArtifacts.push( + artifacts.writeJson(`podman-uninstall-image-pull-${index + 1}.json`, { + image, + status: pull.status, + stdout: pull.stdout, + stderr: pull.stderr, + error: pull.error?.message, + }), + ); + return pull.status === 0; + }); + await Promise.all(pullArtifacts); + expect(imagesPulled, "Pull fixture images; see image-pull artifacts").toBe(true); await runCommand(shellProbe, openshellBin, sandboxCreateArgs(), { artifactName: "podman-uninstall-create-sandbox", env: cliEnv, diff --git a/test/e2e/support/native-nvidia-target-ownership.test.ts b/test/e2e/support/native-nvidia-target-ownership.test.ts index 2f168adc83b..55f6d8a5a4c 100644 --- a/test/e2e/support/native-nvidia-target-ownership.test.ts +++ b/test/e2e/support/native-nvidia-target-ownership.test.ts @@ -9,6 +9,7 @@ describe("native NVIDIA target ownership", () => { it.each([ "src/lib/actions/inference-set.ts", "src/lib/inference/native-nvidia/index.ts", + "src/lib/inference/native-hosted/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "test/e2e/live/public-nvidia-switch-provider.ts", ])("selects both provider-switch targets when %s changes", (changedFile) => { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 1d130b8c733..da35fc5478c 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -907,6 +907,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ runnerComparison: true, shard: "native-nvidia", owningPaths: [ + "src/lib/inference/native-hosted/index.ts", "src/lib/actions/inference-set.ts", "src/lib/inference/native-nvidia/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", @@ -1192,6 +1193,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: true, exposeCliBin: true, owningPaths: [ + "src/lib/inference/native-hosted/index.ts", "src/lib/inference/native-nvidia/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "src/lib/actions/inference-set.ts", From 6c71538816258c08796c95584c656efb8f10ca90 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:21:19 -0700 Subject: [PATCH 052/133] fix: validate native NVIDIA provider boundaries Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../openshell/provider-profile.test.ts | 33 ++++- .../adapters/openshell/provider-profile.ts | 12 ++ .../langchain-deepagents-code-image.test.ts | 48 +++++++- .../07-deepagents-code-headless-inference.sh | 114 ++++++++++++------ .../langchain-deepagents-code-headless.ts | 4 + 5 files changed, 172 insertions(+), 39 deletions(-) diff --git a/src/lib/adapters/openshell/provider-profile.test.ts b/src/lib/adapters/openshell/provider-profile.test.ts index b3fe4e3e048..778ab7889d3 100644 --- a/src/lib/adapters/openshell/provider-profile.test.ts +++ b/src/lib/adapters/openshell/provider-profile.test.ts @@ -4,7 +4,11 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; -import { endpointlessProviderProfilePath } from "./provider-profile"; +import { + endpointlessProviderProfilePath, + exportedProviderProfileMatchesContract, + parseCheckedInProviderProfileContract, +} from "./provider-profile"; const PROFILE_ID = "langfuse-hermes-v1"; @@ -14,4 +18,31 @@ describe("OpenShell endpointless provider profiles", () => { path.join("/repo", "nemoclaw-blueprint", "provider-profiles", "langfuse-hermes-v1.yaml"), ); }); + + it.each([ + ["path_template", "/v1/{credential}"], + ["token_grant", { endpoint: "https://attacker.example/token" }], + ])("rejects an unowned exported credential control: %s (#12558)", (key, value) => { + const profile = { + id: "native", + credentials: [ + { + name: "api_key", + env_vars: ["API_KEY"], + required: true, + auth_style: "bearer", + header_name: "authorization", + query_param: "", + }, + ], + endpoints: [], + binaries: ["/usr/bin/curl"], + inference_capable: true, + }; + const expected = parseCheckedInProviderProfileContract(JSON.stringify(profile)); + expect(expected).not.toBeNull(); + const exported = { ...profile, credentials: [{ ...profile.credentials[0], [key]: value }] }; + + expect(exportedProviderProfileMatchesContract(JSON.stringify(exported), expected!)).toBe(false); + }); }); diff --git a/src/lib/adapters/openshell/provider-profile.ts b/src/lib/adapters/openshell/provider-profile.ts index 70b1182bcba..a0f3855b7ad 100644 --- a/src/lib/adapters/openshell/provider-profile.ts +++ b/src/lib/adapters/openshell/provider-profile.ts @@ -24,6 +24,17 @@ function recordValue(value: unknown): Record | null { : null; } +const CREDENTIAL_KEYS = new Set([ + "auth_style", + "description", + "env_vars", + "header_name", + "name", + "query_param", + "refresh", + "required", +]); + function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null { const profile = recordValue(value); if ( @@ -41,6 +52,7 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null const credential = recordValue(value); if ( !credential || + Object.keys(credential).some((key) => !CREDENTIAL_KEYS.has(key)) || typeof credential.name !== "string" || !Array.isArray(credential.env_vars) || credential.env_vars.some((envVar) => typeof envVar !== "string") || diff --git a/test/agents/deepagents/langchain-deepagents-code-image.test.ts b/test/agents/deepagents/langchain-deepagents-code-image.test.ts index 27bb0a9e173..34eeee3a93e 100644 --- a/test/agents/deepagents/langchain-deepagents-code-image.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-image.test.ts @@ -966,7 +966,7 @@ describe("LangChain Deep Agents Code image contracts", () => { "dcode_connect_fail_closed_contract", "connect rejects untrusted image-backed route evidence before session attach", "fresh direct-exec dcode session retained only the original skill", - "connect --probe-only accepted the managed inference route", + "connect --probe-only accepted the ${route_contract:-unknown} inference route", 'sandbox_login_exec "cd /sandbox', "https://inference.local/v1/models", "HTTP_CODE:%{http_code}", @@ -974,6 +974,11 @@ describe("LangChain Deep Agents Code image contracts", () => { "https://inference\\.local(/v1)?", "references_managed_placeholder_key", 'api_key_env[[:space:]]*=[[:space:]]*"DEEPAGENTS_CODE_OPENAI_API_KEY"', + "references_native_nvidia_route", + "https://integrate\\.api\\.nvidia\\.com/v1", + "references_attached_provider_placeholder_key", + 'api_key_env[[:space:]]*=[[:space:]]*"NEMOCLAW_ATTACHED_PROVIDER_API_KEY"', + "configured_inference_route_contract", "classify_headless_output", '"schema_version", "command", "data"', '"status"', @@ -1095,6 +1100,47 @@ describe("LangChain Deep Agents Code image contracts", () => { ).toBe("key"); }); + it.each([ + [ + "managed", + [ + 'base_url = "https://inference.local/v1"', + 'api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"', + ].join("\n"), + ], + [ + "native-nvidia", + [ + 'base_url = "https://integrate.api.nvidia.com/v1"', + 'api_key_env = "NEMOCLAW_ATTACHED_PROVIDER_API_KEY"', + ].join("\n"), + ], + ])("selects the %s Deep Agents Code inference route contract", (expected, config) => { + expect(runHeadlessCheckHelper("inference-route-contract", { CONFIG: config })).toBe( + `${expected}\n`, + ); + }); + + it.each([ + [ + "native endpoint with managed placeholder", + [ + 'base_url = "https://integrate.api.nvidia.com/v1"', + 'api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"', + ].join("\n"), + ], + [ + "mixed routes", + [ + 'base_url = "https://inference.local/v1"', + 'base_url = "https://integrate.api.nvidia.com/v1"', + 'api_key_env = "NEMOCLAW_ATTACHED_PROVIDER_API_KEY"', + ].join("\n"), + ], + ])("rejects an inconsistent Deep Agents Code route contract: %s", (_case, config) => { + expect(() => runHeadlessCheckHelper("inference-route-contract", { CONFIG: config })).toThrow(); + }); + it("rejects unsafe headless timeout values before sandbox execution", () => { const validate = (timeout: string) => runHeadlessCheckHelper("positive-integer", { DEEPAGENTS_HEADLESS_TIMEOUT: timeout }); diff --git a/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh b/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh index 198ec2dcb47..81009668c83 100755 --- a/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh +++ b/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh @@ -5,8 +5,10 @@ # Case: Deep Agents Code headless inference and RLIMIT enforcement (#5619, #6545). # # Headless `dcode -n ""`, run inside a built Deep Agents Code sandbox, -# must route through the managed https://inference.local/v1 endpoint using the -# placeholder OpenAI-compatible key NemoClaw writes into config.toml. The login +# must route through its configured provider contract: managed routes use +# https://inference.local/v1 and the managed placeholder, while native NVIDIA +# uses https://integrate.api.nvidia.com/v1 and the attached-provider placeholder. +# The login # shell path must reject an empty prompt with exit 2, then return a versioned # JSON success envelope containing PONG with exit 0 for a real prompt; provider, # connection, DNS, timeout, and ambiguous failures are not acceptable. No real @@ -372,6 +374,34 @@ references_managed_placeholder_key() { grep -Eq 'api_key_env[[:space:]]*=[[:space:]]*"DEEPAGENTS_CODE_OPENAI_API_KEY"' } +references_native_nvidia_route() { + grep -Eq 'base_url[[:space:]]*=[[:space:]]*"https://integrate\.api\.nvidia\.com/v1"' +} + +references_attached_provider_placeholder_key() { + grep -Eq 'api_key_env[[:space:]]*=[[:space:]]*"NEMOCLAW_ATTACHED_PROVIDER_API_KEY"' +} + +configured_inference_route_contract() { + local config + config="$(cat)" + if printf '%s\n' "$config" | references_native_nvidia_route \ + && printf '%s\n' "$config" | references_attached_provider_placeholder_key \ + && ! printf '%s\n' "$config" | references_managed_inference_route \ + && ! printf '%s\n' "$config" | references_managed_placeholder_key; then + printf '%s\n' native-nvidia + return 0 + fi + if printf '%s\n' "$config" | references_managed_inference_route \ + && printf '%s\n' "$config" | references_managed_placeholder_key \ + && ! printf '%s\n' "$config" | references_native_nvidia_route \ + && ! printf '%s\n' "$config" | references_attached_provider_placeholder_key; then + printf '%s\n' managed + return 0 + fi + return 1 +} + uses_native_openrouter_config() { local config config="$(cat)" @@ -576,19 +606,20 @@ main() { fail_test "direct-exec dcode did not reject an empty non-interactive prompt with exit 2 (exit ${empty_direct_exit})" fi - # 1. config.toml points at the managed inference route, not a real provider host. + # 1. config.toml matches exactly one supported inference route contract. config_output="$(sandbox_exec "cat /sandbox/.deepagents/config.toml 2>/dev/null" || true)" - if printf '%s' "$config_output" | references_managed_inference_route; then + route_contract="$(printf '%s' "$config_output" | configured_inference_route_contract || true)" + if [ "$route_contract" = "native-nvidia" ]; then + pass "config.toml routes through the native NVIDIA endpoint" + pass "config.toml uses the attached-provider placeholder API key" + elif [ "$route_contract" = "managed" ]; then pass "config.toml routes through the managed inference.local endpoint" - else - fail_test "config.toml does not reference the managed inference.local route (captured config redacted from log)" - fi - if printf '%s' "$config_output" | references_managed_placeholder_key; then pass "config.toml uses the managed Deep Agents Code placeholder API key" else - fail_test "config.toml does not use the managed placeholder API key env reference (captured config redacted from log)" + fail_test "config.toml does not match a supported inference route and placeholder contract (captured config redacted from log)" fi - if printf '%s\n' "$config_output" | uses_native_openrouter_config; then + if [ "$route_contract" = "managed" ] \ + && printf '%s\n' "$config_output" | uses_native_openrouter_config; then openrouter_identity_output="$(sandbox_direct_dcode identity || true)" if printf '%s\n' "$openrouter_identity_output" | grep -Fxq "Provider: openrouter" \ && printf '%s\n' "$openrouter_identity_output" | grep -Eq '^Model:[[:space:]]+openrouter:' \ @@ -601,25 +632,31 @@ main() { openrouter_identity_output="" fi - # 2. Record whether direct DNS/hosts is absent. When it is, the following + dns_hosts_output="" + direct_dns_state=not-applicable + route_output="" + + # 2. For the managed route, record whether direct DNS/hosts is absent. When it is, the following # login, direct-exec, and connect successes prove they do not depend on it; # a present route is informational and is not credited as that proof. - dns_hosts_output="$(sandbox_exec "if ! command -v getent >/dev/null 2>&1; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PROBE_MISSING_GETENT; elif ! command -v timeout >/dev/null 2>&1; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PROBE_MISSING_TIMEOUT; elif timeout 5 getent hosts inference.local >/dev/null 2>&1; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PRESENT; else status=\$?; if [ \"\$status\" -eq 124 ]; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PROBE_TIMEOUT; else printf '%s\\n' NEMOCLAW_DCODE_DNS_ABSENT; fi; fi")" - if printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_PROBE_MISSING_GETENT"; then - direct_dns_state=unknown - fail_test "required DNS diagnostic tool getent is unavailable in the sandbox" - elif printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_PROBE_MISSING_TIMEOUT"; then - direct_dns_state=unknown - fail_test "required DNS diagnostic tool timeout is unavailable in the sandbox" - elif printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_ABSENT"; then - direct_dns_state=absent - pass "direct inference.local DNS/hosts is absent; exercising the proxy-only contract" - elif printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_PRESENT"; then - direct_dns_state=present - info "direct inference.local DNS/hosts is present; proxy independence is not inferred from this observation" - else - direct_dns_state=unknown - fail_test "could not observe the direct inference.local DNS/hosts state" + if [ "$route_contract" = "managed" ]; then + dns_hosts_output="$(sandbox_exec "if ! command -v getent >/dev/null 2>&1; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PROBE_MISSING_GETENT; elif ! command -v timeout >/dev/null 2>&1; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PROBE_MISSING_TIMEOUT; elif timeout 5 getent hosts inference.local >/dev/null 2>&1; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PRESENT; else status=\$?; if [ \"\$status\" -eq 124 ]; then printf '%s\\n' NEMOCLAW_DCODE_DNS_PROBE_TIMEOUT; else printf '%s\\n' NEMOCLAW_DCODE_DNS_ABSENT; fi; fi")" + if printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_PROBE_MISSING_GETENT"; then + direct_dns_state=unknown + fail_test "required DNS diagnostic tool getent is unavailable in the sandbox" + elif printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_PROBE_MISSING_TIMEOUT"; then + direct_dns_state=unknown + fail_test "required DNS diagnostic tool timeout is unavailable in the sandbox" + elif printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_ABSENT"; then + direct_dns_state=absent + pass "direct inference.local DNS/hosts is absent; exercising the proxy-only contract" + elif printf '%s\n' "$dns_hosts_output" | grep -Fxq "NEMOCLAW_DCODE_DNS_PRESENT"; then + direct_dns_state=present + info "direct inference.local DNS/hosts is present; proxy independence is not inferred from this observation" + else + direct_dns_state=unknown + fail_test "could not observe the direct inference.local DNS/hosts state" + fi fi # 3. The login shell loaded the exact normalized proxy contract from .profile. @@ -632,12 +669,15 @@ main() { fi # 4. The managed route is reachable through the normalized login-shell proxy. - route_output="$(sandbox_login_exec "curl -sS -o /dev/null -w 'HTTP_CODE:%{http_code}' --proxy \"\${HTTPS_PROXY}\" --noproxy \"\${NO_PROXY}\" --max-time 30 https://inference.local/v1/models" || true)" - route_code="$(printf '%s' "$route_output" | sed -n 's/.*HTTP_CODE:\([0-9][0-9][0-9]\).*/\1/p' | tail -n1)" - if [ "$route_code" = "200" ]; then - pass "login-shell proxy reached https://inference.local/v1/models" - else - fail_test "login-shell proxy did not receive HTTP 200 from https://inference.local/v1/models (HTTP ${route_code:-000})" + # Native NVIDIA is proved through the attached-provider dcode PONG below. + if [ "$route_contract" = "managed" ]; then + route_output="$(sandbox_login_exec "curl -sS -o /dev/null -w 'HTTP_CODE:%{http_code}' --proxy \"\${HTTPS_PROXY}\" --noproxy \"\${NO_PROXY}\" --max-time 30 https://inference.local/v1/models" || true)" + route_code="$(printf '%s' "$route_output" | sed -n 's/.*HTTP_CODE:\([0-9][0-9][0-9]\).*/\1/p' | tail -n1)" + if [ "$route_code" = "200" ]; then + pass "login-shell proxy reached https://inference.local/v1/models" + else + fail_test "login-shell proxy did not receive HTTP 200 from https://inference.local/v1/models (HTTP ${route_code:-000})" + fi fi # Exercise the stateless public boundary, then let native DCode list/session @@ -698,7 +738,7 @@ main() { | node --no-warnings "${REPO:-.}/test/e2e/fixtures/redaction.ts" dcode_exit="$(printf '%s' "$headless_output" | sed -n 's/.*DCODE_EXIT:\([0-9]\+\).*/\1/p' | tail -n1)" if classification="$(classify_headless_output "${dcode_exit:-unknown}" "$headless_output")"; then - pass "login-shell dcode -n reached managed inference with ${classification} (exit ${dcode_exit:-unknown}; direct DNS/hosts ${direct_dns_state})" + pass "login-shell dcode -n reached ${route_contract:-unknown} inference with ${classification} (exit ${dcode_exit:-unknown}; direct DNS/hosts ${direct_dns_state})" else fail_test "login-shell dcode -n --json did not return a success envelope with PONG (${classification}, exit ${dcode_exit:-unknown})" fi @@ -714,7 +754,7 @@ DCODE_EXIT:${direct_exit}" printf '%s\n' "${PREFIX}: direct-exec stdout/stderr:" "$direct_headless_output" \ | node --no-warnings "${REPO:-.}/test/e2e/fixtures/redaction.ts" if direct_classification="$(classify_headless_output "$direct_exit" "$direct_headless_output" "$skill_marker_v1")"; then - pass "direct-exec dcode -n reached managed inference; fresh direct-exec dcode session retained only the original skill (${direct_classification}; exit ${direct_exit})" + pass "direct-exec dcode -n reached ${route_contract:-unknown} inference; fresh direct-exec dcode session retained only the original skill (${direct_classification}; exit ${direct_exit})" else fail_test "fresh direct-exec dcode session did not retain only the original skill (${direct_classification}, exit ${direct_exit})" fi @@ -750,7 +790,7 @@ DCODE_EXIT:${direct_exit}" if connect_output="$(nemoclaw_connect_probe)"; then connect_exit=0 pass "bare connect targeted the Deep Agents Code sandbox" - pass "nemoclaw connect --probe-only accepted the managed inference route (direct DNS/hosts ${direct_dns_state})" + pass "nemoclaw connect --probe-only accepted the ${route_contract:-unknown} inference route (direct DNS/hosts ${direct_dns_state})" else connect_exit=$? printf '%s\n' "$connect_output" \ @@ -759,7 +799,7 @@ DCODE_EXIT:${direct_exit}" if [ -n "$connect_target_reason" ]; then fail_test "bare connect did not target the expected sandbox (${connect_target_reason})" else - fail_test "nemoclaw connect --probe-only rejected the managed inference route (exit ${connect_exit})" + fail_test "nemoclaw connect --probe-only rejected the ${route_contract:-unknown} inference route (exit ${connect_exit})" fi fi diff --git a/test/helpers/langchain-deepagents-code-headless.ts b/test/helpers/langchain-deepagents-code-headless.ts index f107606b899..d6c763446c0 100644 --- a/test/helpers/langchain-deepagents-code-headless.ts +++ b/test/helpers/langchain-deepagents-code-headless.ts @@ -45,6 +45,7 @@ type HeadlessCheckOperation = | "classify-output" | "contains-secret" | "entrypoint-rlimits" + | "inference-route-contract" | "managed-placeholder" | "managed-route" | "positive-integer"; @@ -70,6 +71,9 @@ case "$1" in managed-placeholder) printf "%s" "$CONFIG" | references_managed_placeholder_key && printf key ;; + inference-route-contract) + printf "%s" "$CONFIG" | configured_inference_route_contract + ;; classify-output) if classification="$(classify_headless_output "$DCODE_EXIT" "$HEADLESS_OUTPUT")"; then printf "pass:%s" "$classification" From f6c786facd707b33dfa5a7417756acd7fee0cb06 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:46:25 -0700 Subject: [PATCH 053/133] fix(security): remediate Slack proxy-addr advisory Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- Dockerfile | 2 +- agents/openclaw/dependency-review.md | 14 +- .../package-lock.json | 10 +- .../package.json | 3 +- ci/source-shape-test-budget.json | 5 + scripts/lib/openclaw-npm-remediation.mts | 151 +++++++++++++++++- .../applier/build/messaging-build-applier.mts | 21 ++- .../openclaw-dependency-review.test.ts | 2 + ...aw-managed-messaging-offline-build.test.ts | 5 + .../openclaw/openclaw-npm-remediation.test.ts | 98 ++++++++++++ .../messaging-build-applier-integrity.test.ts | 80 ++++++++++ 11 files changed, 379 insertions(+), 12 deletions(-) diff --git a/Dockerfile b/Dockerfile index e9482699f4f..86152a4e6ff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -447,7 +447,7 @@ ADD --chmod=0444 --checksum=sha256:425bf8c725d23bc5ac76bcedd10d9cdbbd6354c7273dd ADD --chmod=0444 --checksum=sha256:9fe46ed2a75148c5a1a720b446f1a95ff7c67e984144a24a83e004a892258cd8 https://registry.npmjs.org/@clack/prompts/-/prompts-1.7.0.tgz /prompts-1.7.0.tgz ADD --chmod=0444 --checksum=sha256:df0241b3046b505d27396da6eef107f14dffb108f77aa89cfd9611a928eb6dfe https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz /protobufjs-7.6.6.tgz ADD --chmod=0444 --checksum=sha256:205de58fb0e9e9ce2e1d2903f634f9be1852f024883fa037eb6ab1cd0c0e6c6b https://registry.npmjs.org/protobufjs/-/protobufjs-8.7.2.tgz /protobufjs-8.7.2.tgz -ADD --chmod=0444 --checksum=sha256:a0d1b6f34f6d4e733429ba95f7adb7833c8ceab916ba574a93f8a8476bee46d9 https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz /proxy-addr-2.0.7.tgz +ADD --chmod=0444 --checksum=sha256:ffcc8055b78b0852b2889a426ad3a3003b60bc79df704faca194157efa2b2587 https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz /proxy-addr-2.0.8.tgz ADD --chmod=0444 --checksum=sha256:e9c52dbf1e382319d5da00b8d964805859b7eb1424450e049d12743d7e19fc9a https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz /proxy-from-env-2.1.0.tgz ADD --chmod=0444 --checksum=sha256:cf7d916cade644852293de603369f2f3ef13171e3f78cc3baf9a1bd6854190bd https://registry.npmjs.org/@openclaw/proxyline/-/proxyline-0.3.7.tgz /proxyline-0.3.7.tgz ADD --chmod=0444 --checksum=sha256:0c7274f0c299f39c2fddf54a2e0039b785977b0173c02d0b3f65fad68923e2b0 https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz /qrcode-1.5.4.tgz diff --git a/agents/openclaw/dependency-review.md b/agents/openclaw/dependency-review.md index ad1a32a1367..8f4477c5560 100644 --- a/agents/openclaw/dependency-review.md +++ b/agents/openclaw/dependency-review.md @@ -1,7 +1,7 @@ -# OpenClaw MCP Runtime Dependency Review +# OpenClaw Runtime Dependency Review This file records the reviewed `mcporter` baseline installed in the OpenClaw sandbox image. Update it and `agents/openclaw/mcporter-runtime/package*.json` together whenever `MCPORTER_VERSION`, its integrity value, a manifest override, or the locked graph changes in `Dockerfile.base` or `Dockerfile`. @@ -29,6 +29,16 @@ Update it and `agents/openclaw/mcporter-runtime/package*.json` together whenever Both image paths install the committed graph with `npm ci --ignore-scripts --omit=dev` because the published package declares no install-time lifecycle script and NemoClaw needs only its already-built CLI. The reviewed audit wrapper reports lower-severity production findings and blocks unaccepted high or critical advisories. The default `ci/npm-audit-exceptions.json` registry is empty. Any future exception must match one advisory, graph, package, installed version, and severity; identify an owner and NemoClaw tracking issue; state a decision, rationale, and expiry no more than 30 days away; and include compensating controls for temporary risk acceptance. Missing, malformed, expired, overlong, mismatched, or unused exceptions fail closed. The repository-wide audit also rejects exceptions for unknown graph IDs. Registry signature verification remains a separate control. +## Managed messaging proxy address remediation + +- Advisory: [GHSA-jqcg-44mw-7w3h](https://github.com/advisories/GHSA-jqcg-44mw-7w3h) affects `proxy-addr@2.0.7`; `2.0.8` contains the reviewed fix. +- Ordinary graph: `agents/openclaw/managed-image-messaging-runtime/package.json` overrides non-bundled `proxy-addr` resolutions to exact `2.0.8`. Its lock records npm integrity `sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==`, the unchanged `forwarded@0.2.0` and `ipaddr.js@1.9.1` dependencies, the MIT license, and the existing Node.js engine floor. +- Bundled Slack graph: the reviewed registry archive `@openclaw/slack@2026.9.2` bundles `@slack/bolt@5.0.0`, `express@5.2.1`, and `proxy-addr@2.0.7`. NemoClaw retains the exact official registry install and verifies OpenClaw's trusted provenance record before replacing only that nested package with the reviewed `proxy-addr@2.0.8` archive. The replacement fails closed if the Slack, Bolt, Express, vulnerable package, or replacement package contract differs from the reviewed identities. +- Audit boundary: the reviewed archive audit applies the same replacement before materializing the aggregate production graph, then pins the complete remediated archive tree digest. The registry archive remains immutable evidence; vulnerable bundled bytes do not survive in the final installed Slack extension. +- Lifecycle suppression: both the managed graph install and the replacement package retrieval keep lifecycle scripts disabled. The replacement package declares no lifecycle script. +- Removal condition: remove the Slack-specific rewrite only after the reviewed Slack archive bundles `proxy-addr@2.0.8` or newer. Keep the ordinary exact override until every supported managed-messaging path resolves outside the affected range and a regenerated lock plus reviewed audit proves the replacement is unnecessary. +- Regression evidence: `test/agents/openclaw/openclaw-npm-remediation.test.ts` guards the exact source and replacement contracts; `test/runtime/messaging/messaging-build-applier-integrity.test.ts` proves the installed official plugin is patched only after provenance verification; `test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts` guards the ordinary graph; and `test/agents/openclaw/openclaw-dependency-review.test.ts` keeps the audit and runtime remediation wiring present. + ## WeChat plugin runtime graph - Package: `@tencent-weixin/openclaw-weixin@2.4.9`. This version uses the supported channel SDK and binds inbound replies to the OpenClaw 2026.9.x model runtime. The locked production dependencies remain `qrcode-terminal@0.12.0` and `zod@4.4.3`. @@ -54,7 +64,7 @@ The lock records the exact version, registry URL, and integrity for every transi ## Source-of-Truth Boundary -- `invalidState`: the image installs a package graph, tarball, license, or advisory state that differs from the independently queried npm registry records for `mcporter@0.7.3`, resolves `@hono/node-server` to any version other than exact `2.0.11`, resolves `fast-uri` to any version other than exact `3.1.7`, resolves `hono` to any version other than exact `4.12.34`, or resolves `ip-address` to any version other than exact `10.3.1`. +- `invalidState`: the image installs a package graph, tarball, license, or advisory state that differs from the independently queried npm registry records for `mcporter@0.7.3`, resolves `@hono/node-server` to any version other than exact `2.0.11`, resolves `fast-uri` to any version other than exact `3.1.7`, resolves `hono` to any version other than exact `4.12.34`, resolves `ip-address` to any version other than exact `10.3.1`, or leaves any final managed-messaging `proxy-addr` installation at a version other than exact `2.0.8`. - `sourceBoundary`: npm owns registry metadata, tarball integrity, provenance signatures, and advisory responses; NemoClaw owns the exact lock, script-disabled install, Docker integrity assertion, empty-by-default audit exception registry, and review record. - `whyNotSourceFix`: a repository note cannot make external registry state trustworthy, so the required `reviewed-npm-audit` CI check materializes the exact locked production graph and verifies its registry signatures. - `imageBuildBoundary`: image builds verify the committed lock, registry origin, tarball integrity, installed graph, and lifecycle suppression. diff --git a/agents/openclaw/managed-image-messaging-runtime/package-lock.json b/agents/openclaw/managed-image-messaging-runtime/package-lock.json index 7a2b806c1d2..62ee51e17ca 100644 --- a/agents/openclaw/managed-image-messaging-runtime/package-lock.json +++ b/agents/openclaw/managed-image-messaging-runtime/package-lock.json @@ -8648,9 +8648,9 @@ } }, "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "license": "MIT", "dependencies": { "forwarded": "0.2.0", @@ -8658,6 +8658,10 @@ }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/proxy-from-env": { diff --git a/agents/openclaw/managed-image-messaging-runtime/package.json b/agents/openclaw/managed-image-messaging-runtime/package.json index ab79210c2f5..ca01a232183 100644 --- a/agents/openclaw/managed-image-messaging-runtime/package.json +++ b/agents/openclaw/managed-image-messaging-runtime/package.json @@ -39,6 +39,7 @@ "file-type": "22.0.2", "protobufjs": "8.7.2" } - } + }, + "proxy-addr": "2.0.8" } } diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 64146ac2c94..d9b561a536f 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -231,6 +231,11 @@ "test": "replaces the reviewed bundled Axios graph with the patched graph", "category": "security" }, + { + "file": "test/agents/openclaw/openclaw-npm-remediation.test.ts", + "test": "replaces only the reviewed Slack bundled proxy-addr package", + "category": "security" + }, { "file": "test/agents/openclaw/openclaw-npm-remediation.test.ts", "test": "replaces the reviewed Jaeger propagator with its aligned patched core", diff --git a/scripts/lib/openclaw-npm-remediation.mts b/scripts/lib/openclaw-npm-remediation.mts index 39d1411f59e..b73aa429dee 100755 --- a/scripts/lib/openclaw-npm-remediation.mts +++ b/scripts/lib/openclaw-npm-remediation.mts @@ -10,6 +10,7 @@ import { cpSync, existsSync, fstatSync, + lstatSync, mkdirSync, mkdtempSync, openSync, @@ -27,8 +28,8 @@ type JsonObject = Record; type Remediation = Readonly<{ expectedPatchedMetadataIntegrity?: string; expectedPatchedTreeIntegrity?: string; - kind: "axios" | "core" | "current-core" | "jaeger" | "legacy-core" | "undici"; - version: "2026.3.11" | "2026.6.10" | "2026.7.1"; + kind: "axios" | "core" | "current-core" | "jaeger" | "legacy-core" | "proxy-addr" | "undici"; + version: "2026.3.11" | "2026.6.10" | "2026.7.1" | "2026.9.2"; }>; type RemediationRequest = Readonly<{ @@ -44,6 +45,12 @@ type BuildRequest = RemediationRequest & expectedPatchedTreeIntegrity?: string; }>; +type InstalledSlackRemediationRequest = Readonly<{ + env?: NodeJS.ProcessEnv; + packageDirectory: string; + workingDirectory: string; +}>; + export type RemediatedArchive = Readonly< | { archivePath: string; @@ -107,6 +114,10 @@ const CURRENT_UNDICI_VERSION = "8.10.0"; const CURRENT_UNDICI_INTEGRITY = "sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ=="; const CURRENT_UNDICI_TARBALL = "https://registry.npmjs.org/undici/-/undici-8.10.0.tgz"; +const CURRENT_PROXY_ADDR_VERSION = "2.0.8"; +const CURRENT_PROXY_ADDR_INTEGRITY = + "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="; +const CURRENT_PROXY_ADDR_TARBALL = "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz"; const CURRENT_IP_ADDRESS_VERSION = "10.3.1"; const CURRENT_IP_ADDRESS_INTEGRITY = "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g=="; @@ -169,6 +180,13 @@ const REMEDIATIONS: Readonly> = Object.freeze({ kind: "axios", version: "2026.7.1", }, + // Remove after the reviewed Slack archive bundles proxy-addr@2.0.8 or newer. + "@openclaw/slack@2026.9.2": { + expectedPatchedTreeIntegrity: + "sha512-li/y4SFf6t3Z6JvP2R2H8dfauu0eybiwzd408QMCR9+zzi6oVVVffi+LGRDDYMh2TFCGgQ8Pnv2a5FiXMmPt1A==", + kind: "proxy-addr", + version: "2026.9.2", + }, "openclaw@2026.6.10": { expectedPatchedMetadataIntegrity: "sha512-XMycUUV7gCzUYbjgwrglER0AQEtfuKUz6wyo4ilm/7nSSkLocYUYVkrJuBFYPW3no8Y5FW/1+2hWCssIyjxn3g==", @@ -811,6 +829,120 @@ export function patchOpenClawDiscordPackageGraph(packageDirectory: string): void writeJson(shrinkwrapPath, shrinkwrap); } +export function patchOpenClawSlackProxyAddrPackageGraph( + packageDirectory: string, + replacementDirectory: string, +): void { + const packageJson = readJson(join(packageDirectory, "package.json")); + requirePackageIdentity(packageJson, "@openclaw/slack", "2026.9.2", "OpenClaw Slack plugin"); + if ( + packageJson.dependencies?.["@slack/bolt"] !== "5.0.0" || + !Array.isArray(packageJson.bundledDependencies) || + !packageJson.bundledDependencies.includes("@slack/bolt") + ) { + throw new Error("@openclaw/slack@2026.9.2 Bolt dependency changed after review"); + } + + const boltDirectory = join(packageDirectory, "node_modules", "@slack", "bolt"); + const boltPackageJson = readJson(join(boltDirectory, "package.json")); + requirePackageIdentity(boltPackageJson, "@slack/bolt", "5.0.0", "OpenClaw Slack bundled Bolt"); + if ( + boltPackageJson.dependencies?.express !== "^5.0.0" || + boltPackageJson.license !== "MIT" || + boltPackageJson.engines?.node !== ">=20" + ) { + throw new Error("@openclaw/slack@2026.9.2 bundled Bolt contract changed after review"); + } + + const expressPackageJson = readJson( + join(boltDirectory, "node_modules", "express", "package.json"), + ); + requirePackageIdentity(expressPackageJson, "express", "5.2.1", "OpenClaw Slack bundled Express"); + if ( + expressPackageJson.dependencies?.["proxy-addr"] !== "^2.0.7" || + expressPackageJson.license !== "MIT" || + expressPackageJson.engines?.node !== ">= 18" + ) { + throw new Error("@openclaw/slack@2026.9.2 bundled Express contract changed after review"); + } + + const proxyAddrDirectory = join(boltDirectory, "node_modules", "proxy-addr"); + const proxyAddrPackageJson = readJson(join(proxyAddrDirectory, "package.json")); + requirePackageIdentity( + proxyAddrPackageJson, + "proxy-addr", + "2.0.7", + "OpenClaw Slack bundled proxy-addr", + ); + requireDependencyShape( + proxyAddrPackageJson, + { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, + "proxy-addr@2.0.7", + ); + if (proxyAddrPackageJson.license !== "MIT" || proxyAddrPackageJson.engines?.node !== ">= 0.10") { + throw new Error("@openclaw/slack@2026.9.2 bundled proxy-addr contract changed after review"); + } + + const replacementPackageJson = readJson(join(replacementDirectory, "package.json")); + requirePackageIdentity( + replacementPackageJson, + "proxy-addr", + CURRENT_PROXY_ADDR_VERSION, + "OpenClaw Slack proxy-addr remediation package", + ); + requireDependencyShape( + replacementPackageJson, + { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, + `proxy-addr@${CURRENT_PROXY_ADDR_VERSION}`, + ); + if ( + replacementPackageJson.license !== "MIT" || + replacementPackageJson.engines?.node !== ">= 0.10" + ) { + throw new Error( + `proxy-addr@${CURRENT_PROXY_ADDR_VERSION} package contract changed; review the remediation before updating it`, + ); + } + + copyReplacementPackage(replacementDirectory, proxyAddrDirectory); +} + +export function applyOpenClawSlackProxyAddrRemediation( + request: InstalledSlackRemediationRequest, +): void { + const packageDirectory = resolve(request.packageDirectory); + const packageStat = lstatSync(packageDirectory); + if (!packageStat.isDirectory() || packageStat.isSymbolicLink()) { + throw new Error("OpenClaw Slack install is not a regular package directory"); + } + const env = { + ...process.env, + ...request.env, + NPM_CONFIG_AUDIT: "false", + NPM_CONFIG_FUND: "false", + NPM_CONFIG_IGNORE_SCRIPTS: "true", + NPM_CONFIG_UPDATE_NOTIFIER: "false", + npm_config_ignore_scripts: "true", + }; + const workingDirectory = resolve(request.workingDirectory); + mkdirSync(workingDirectory, { recursive: true, mode: 0o700 }); + const remediationRoot = mkdtempSync(join(workingDirectory, "openclaw-slack-proxy-addr-")); + const proxyAddrArchive = packReplacement( + `proxy-addr@${CURRENT_PROXY_ADDR_VERSION}`, + CURRENT_PROXY_ADDR_INTEGRITY, + CURRENT_PROXY_ADDR_TARBALL, + remediationRoot, + env, + ); + const proxyAddrPackage = extractArchive( + proxyAddrArchive.archivePath, + join(remediationRoot, "proxy-addr"), + remediationRoot, + env, + ); + patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, proxyAddrPackage); +} + export function patchLegacyOpenClawCorePackageGraph(packageDirectory: string): void { const packageJsonPath = join(packageDirectory, "package.json"); const bundledTarPackageJsonPath = join(packageDirectory, "node_modules", "tar", "package.json"); @@ -1287,6 +1419,21 @@ export function buildRemediatedOpenClawPluginArchive( ); patchOpenClawDiscordPackageGraph(sourcePackage); copyReplacementPackage(undiciPackage, join(sourcePackage, "node_modules", "undici")); + } else if (remediation.kind === "proxy-addr") { + const proxyAddrArchive = packReplacement( + `proxy-addr@${CURRENT_PROXY_ADDR_VERSION}`, + CURRENT_PROXY_ADDR_INTEGRITY, + CURRENT_PROXY_ADDR_TARBALL, + remediationRoot, + env, + ); + const proxyAddrPackage = extractArchive( + proxyAddrArchive.archivePath, + join(remediationRoot, "proxy-addr"), + remediationRoot, + env, + ); + patchOpenClawSlackProxyAddrPackageGraph(sourcePackage, proxyAddrPackage); } else if (remediation.kind === "legacy-core") { const bundledTarPath = join(sourcePackage, "node_modules", "tar"); const bundledBaileysPath = join(sourcePackage, "node_modules", "@whiskeysockets", "baileys"); diff --git a/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index f4af22c6eb7..19a003017b6 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -19,7 +19,10 @@ import { import { homedir } from "node:os"; import { dirname, isAbsolute, join, resolve, sep } from "node:path"; import { pathToFileURL } from "node:url"; -import { remediateReviewedOpenClawPluginArchive } from "../../../../../scripts/lib/openclaw-npm-remediation.mts"; +import { + applyOpenClawSlackProxyAddrRemediation, + remediateReviewedOpenClawPluginArchive, +} from "../../../../../scripts/lib/openclaw-npm-remediation.mts"; import { packReviewedNpmArchive } from "../../../../../scripts/lib/reviewed-npm-archive.mts"; import { BUILT_IN_CHANNEL_MANIFESTS } from "../../channels/built-ins.ts"; import type { ChannelAgentPackageRuntimeLockSpec, ChannelManifest } from "../../manifest/types.ts"; @@ -775,7 +778,7 @@ function installOpenClawPluginPackages(installs: readonly OpenClawPluginInstall[ const installCache = install.runtimeLock ? requireWritableRuntimeInstallCache(install.runtimeLock, env) : undefined; - const installEnv = { + const installEnv: Env = { ...env, NPM_CONFIG_IGNORE_SCRIPTS: "true", npm_config_ignore_scripts: "true", @@ -797,7 +800,7 @@ function installOpenClawPluginPackages(installs: readonly OpenClawPluginInstall[ // The verified archive warms the cache before the exact npm install. // Third-party plugins retain their reviewed local archive installation. const installTarget = officialPluginId ? install.spec : `npm-pack:${packed.archivePath}`; - const commandEnv = officialPluginId + const commandEnv: Env = officialPluginId ? { ...installEnv, NPM_CONFIG_OFFLINE: "true", npm_config_offline: "true" } : installEnv; runCommand( @@ -821,6 +824,18 @@ function installOpenClawPluginPackages(installs: readonly OpenClawPluginInstall[ ); } verifyTrustedOfficialNpmInstall(install, officialPluginId, inspection); + if (install.npmPackageSpec === "@openclaw/slack@2026.9.2") { + applyOpenClawSlackProxyAddrRemediation({ + env: installEnv as NodeJS.ProcessEnv, + packageDirectory: join( + installEnv.HOME ?? homedir(), + ".openclaw", + "extensions", + officialPluginId, + ), + workingDirectory: packed.rootDir, + }); + } } if (install.runtimeLock) { const openClawVersion = sanitizeOptionalString(env.OPENCLAW_VERSION); diff --git a/test/agents/openclaw/openclaw-dependency-review.test.ts b/test/agents/openclaw/openclaw-dependency-review.test.ts index 4ca0331cf1a..45372a51a69 100644 --- a/test/agents/openclaw/openclaw-dependency-review.test.ts +++ b/test/agents/openclaw/openclaw-dependency-review.test.ts @@ -249,6 +249,7 @@ check_not_contains "$optional_plugin_block" 'pack_reviewed_npm_tarball' "optiona grep -Fq 'hashPackageTree' "$remediation_helper" grep -Fq 'patchOpenClawCorePackageGraph' "$remediation_helper" grep -Fq 'patchOpenClawDiagnosticsPackageGraph' "$remediation_helper" + grep -Fq 'applyOpenClawSlackProxyAddrRemediation' "$messaging_build_applier" for package_spec in \ 'openclaw@2026.3.11' \ 'openclaw@2026.6.10' \ @@ -257,6 +258,7 @@ check_not_contains "$optional_plugin_block" 'pack_reviewed_npm_tarball' "optiona '@openclaw/msteams@2026.6.10' \ '@openclaw/diagnostics-otel@2026.7.1' \ '@openclaw/slack@2026.7.1' \ + '@openclaw/slack@2026.9.2' \ '@openclaw/msteams@2026.7.1'; do grep -Fq "$package_spec" "$remediation_helper" done diff --git a/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts b/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts index a7fe48a2c04..52d60d44d50 100644 --- a/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts +++ b/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts @@ -95,6 +95,7 @@ describe("OpenClaw managed messaging offline image build", () => { ), }, }, + "proxy-addr": "2.0.8", }); expect(nestedOverrideLocations).toHaveLength(3); nestedOverrideLocations.forEach((location) => { @@ -120,6 +121,10 @@ describe("OpenClaw managed messaging offline image build", () => { expect(runtimeLock.packages["node_modules/@emnapi/wasi-threads"]).toMatchObject({ version: "1.2.2", }); + expect(runtimeLock.packages["node_modules/proxy-addr"]).toMatchObject({ + version: "2.0.8", + dependencies: { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, + }); }); it("pins the complete lock graphs below the cold-build layer limit", () => { diff --git a/test/agents/openclaw/openclaw-npm-remediation.test.ts b/test/agents/openclaw/openclaw-npm-remediation.test.ts index 22d56f64859..207fdf9d5b1 100644 --- a/test/agents/openclaw/openclaw-npm-remediation.test.ts +++ b/test/agents/openclaw/openclaw-npm-remediation.test.ts @@ -24,6 +24,7 @@ import { patchOpenClawDiagnosticsOtelPackageGraph, patchOpenClawDiscordPackageGraph, patchOpenClawPluginPackageGraph, + patchOpenClawSlackProxyAddrPackageGraph, } from "../../../scripts/lib/openclaw-npm-remediation.mts"; const temporaryDirectories: string[] = []; @@ -315,6 +316,61 @@ function writeDiscordFixture(undiciVersion = "8.5.0"): string { return directory; } +function writeSlackProxyAddrFixture( + sourceVersion = "2.0.7", + replacementVersion = "2.0.8", +): { packageDirectory: string; replacementDirectory: string } { + const packageDirectory = mkdtempSync( + path.join(tmpdir(), "nemoclaw-openclaw-slack-proxy-addr-remediation-"), + ); + temporaryDirectories.push(packageDirectory); + const boltDirectory = path.join(packageDirectory, "node_modules", "@slack", "bolt"); + const expressDirectory = path.join(boltDirectory, "node_modules", "express"); + const proxyAddrDirectory = path.join(boltDirectory, "node_modules", "proxy-addr"); + mkdirSync(expressDirectory, { recursive: true }); + mkdirSync(proxyAddrDirectory, { recursive: true }); + writeJson(path.join(packageDirectory, "package.json"), { + name: "@openclaw/slack", + version: "2026.9.2", + dependencies: { "@slack/bolt": "5.0.0" }, + bundledDependencies: ["@slack/bolt"], + }); + writeJson(path.join(boltDirectory, "package.json"), { + name: "@slack/bolt", + version: "5.0.0", + dependencies: { express: "^5.0.0" }, + license: "MIT", + engines: { node: ">=20" }, + }); + writeJson(path.join(expressDirectory, "package.json"), { + name: "express", + version: "5.2.1", + dependencies: { "proxy-addr": "^2.0.7" }, + license: "MIT", + engines: { node: ">= 18" }, + }); + writeJson(path.join(proxyAddrDirectory, "package.json"), { + name: "proxy-addr", + version: sourceVersion, + dependencies: { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, + license: "MIT", + engines: { node: ">= 0.10" }, + }); + writeFileSync(path.join(proxyAddrDirectory, "index.js"), "module.exports = 'vulnerable';\n"); + + const replacementDirectory = mkdtempSync(path.join(tmpdir(), "nemoclaw-proxy-addr-replacement-")); + temporaryDirectories.push(replacementDirectory); + writeJson(path.join(replacementDirectory, "package.json"), { + name: "proxy-addr", + version: replacementVersion, + dependencies: { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, + license: "MIT", + engines: { node: ">= 0.10" }, + }); + writeFileSync(path.join(replacementDirectory, "index.js"), "module.exports = 'patched';\n"); + return { packageDirectory, replacementDirectory }; +} + function readJson(file: string): T { return JSON.parse(readFileSync(file, "utf-8")) as T; } @@ -556,6 +612,48 @@ describe("OpenClaw npm remediation", () => { ); }); + // source-shape-contract: security -- Exact Slack, Bolt, Express, and proxy-addr identities constrain the archive rewrite to the reviewed vulnerable package + it("replaces only the reviewed Slack bundled proxy-addr package", () => { + const { packageDirectory, replacementDirectory } = writeSlackProxyAddrFixture(); + + patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, replacementDirectory); + + const proxyAddrDirectory = path.join( + packageDirectory, + "node_modules", + "@slack", + "bolt", + "node_modules", + "proxy-addr", + ); + expect(readPackageField(proxyAddrDirectory, "version")).toBe("2.0.8"); + expect(readFileSync(path.join(proxyAddrDirectory, "index.js"), "utf8")).toBe( + "module.exports = 'patched';\n", + ); + expect( + readPackageField( + path.join(packageDirectory, "node_modules", "@slack", "bolt", "node_modules", "express"), + "dependencies.proxy-addr", + ), + ).toBe("^2.0.7"); + }); + + it("rejects a Slack bundled proxy-addr identity that changed after review", () => { + const { packageDirectory, replacementDirectory } = writeSlackProxyAddrFixture("2.0.6"); + + expect(() => + patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, replacementDirectory), + ).toThrow("must be proxy-addr@2.0.7"); + }); + + it("rejects a proxy-addr replacement identity that changed after review", () => { + const { packageDirectory, replacementDirectory } = writeSlackProxyAddrFixture("2.0.7", "2.0.9"); + + expect(() => + patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, replacementDirectory), + ).toThrow("must be proxy-addr@2.0.8"); + }); + // source-shape-contract: security -- Exact package and shrinkwrap identities prove the guarded Jaeger remediation installs only the reviewed aligned graph it("replaces the reviewed Jaeger propagator with its aligned patched core", () => { const directory = writeDiagnosticsFixture(); diff --git a/test/runtime/messaging/messaging-build-applier-integrity.test.ts b/test/runtime/messaging/messaging-build-applier-integrity.test.ts index 638b24ccca1..ae764b525c4 100644 --- a/test/runtime/messaging/messaging-build-applier-integrity.test.ts +++ b/test/runtime/messaging/messaging-build-applier-integrity.test.ts @@ -18,11 +18,16 @@ import { withLegacyMessagingPlanEnvDirect } from "../../messaging-plan-test-help import { officialPluginInspectionShell } from "./official-plugin-inspection-fixture"; +const { applySlackProxyAddrRemediation } = vi.hoisted(() => ({ + applySlackProxyAddrRemediation: vi.fn(), +})); + vi.mock("../../../scripts/lib/openclaw-npm-remediation.mts", async (importOriginal) => { const original = await importOriginal(); return { ...original, + applyOpenClawSlackProxyAddrRemediation: applySlackProxyAddrRemediation, remediateReviewedOpenClawPluginArchive: ({ archivePath }: { archivePath: string }) => ({ archivePath, integrity: "sha512-messaging-integrity-test-remediation", @@ -49,6 +54,8 @@ const OPENCLAW_SLACK_2026_9_1_INTEGRITY = "sha512-tU372jE40nnPcKQ6oxmDHf2/UhGtdz8ysi4JKsRZIO1QBAEkZd2YfsOw8aucmb2r0B0vjcFD3OmIV/Qzb57COg=="; const OPENCLAW_SLACK_2026_9_1_TARBALL = "https://registry.npmjs.org/@openclaw/slack/-/slack-2026.9.1.tgz"; +const OPENCLAW_SLACK_2026_9_2_INTEGRITY = + "sha512-6M1M6gL3iXahpalNsYAUuA+wvnV8lbMlNNH2ToegFvaSJcIll4S9kFa5mv3GFoquhMRHQjEjnkXPHP/pXwaWcA=="; const REPO_ROOT = path.join(import.meta.dirname, "../../.."); function channelsB64(channels: string[]): string { @@ -184,6 +191,79 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { testTimeout(15_000), ); + it("remediates proxy-addr after verifying the official Slack 2026.9.2 install", async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-slack-remediation-")); + const tracePath = path.join(tmp, "openclaw.trace"); + const inspection = JSON.stringify({ + plugin: { id: "slack", trustedOfficialInstall: true }, + install: { + source: "npm", + resolvedSpec: "@openclaw/slack@2026.9.2", + integrity: OPENCLAW_SLACK_2026_9_2_INTEGRITY, + }, + }); + fs.writeFileSync( + path.join(tmp, "npm"), + [ + "#!/bin/sh", + 'printf \'npm|%s|%s|%s\\n\' "$1" "$2" "$3" >> "$OPENCLAW_TRACE"', + 'if [ "${1:-}" = "view" ] && [ "${3:-}" = "dist.integrity" ]; then printf "%s\\n" "$OPENCLAW_SLACK_2026_9_2_INTEGRITY"; exit 0; fi', + 'if [ "${1:-}" = "view" ] && [ "${3:-}" = "dist.tarball" ]; then printf "%s\\n" "https://registry.npmjs.org/@openclaw/slack/-/slack-2026.9.2.tgz"; exit 0; fi', + 'if [ "${1:-}" = "pack" ]; then pack_dir="${4:-}"; printf "fake plugin tarball" > "$pack_dir/slack-2026.9.2.tgz"; printf \'[{"filename":"slack-2026.9.2.tgz","integrity":"%s"}]\\n\' "$OPENCLAW_SLACK_2026_9_2_INTEGRITY"; exit 0; fi', + "exit 1", + "", + ].join("\n"), + { mode: 0o755 }, + ); + fs.writeFileSync( + path.join(tmp, "openclaw"), + [ + "#!/bin/sh", + 'printf \'openclaw|%s|%s|%s|%s|%s\\n\' "$1" "$2" "$3" "$4" "$5" >> "$OPENCLAW_TRACE"', + 'if [ "${1:-}" = "plugins" ] && [ "${2:-}" = "inspect" ] && [ "${3:-}" = "slack" ]; then', + ` printf '%s\\n' '${inspection}'`, + " exit 0", + "fi", + "exit 0", + "", + ].join("\n"), + { mode: 0o755 }, + ); + + try { + const env = await withLegacyMessagingPlanEnvDirect( + { + PATH: `${tmp}:${process.env.PATH || "/usr/bin:/bin"}`, + HOME: tmp, + OPENCLAW_TRACE: tracePath, + OPENCLAW_SLACK_2026_9_2_INTEGRITY, + OPENCLAW_VERSION: "2026.9.2", + NEMOCLAW_MESSAGING_CHANNELS_B64: channelsB64(["slack"]), + }, + "openclaw", + ); + const plan = readMessagingBuildPlanFromEnv(env, "openclaw"); + + expect(applyMessagingBuildPhase(plan, "agent-install", env)).toEqual([]); + expect(applySlackProxyAddrRemediation).toHaveBeenCalledOnce(); + expect(applySlackProxyAddrRemediation).toHaveBeenCalledWith( + expect.objectContaining({ + packageDirectory: path.join(tmp, ".openclaw", "extensions", "slack"), + }), + ); + const remediationRequest = applySlackProxyAddrRemediation.mock.calls[0]?.[0] as { + env: Record; + }; + expect(remediationRequest.env.NPM_CONFIG_OFFLINE).toBeUndefined(); + const trace = fs.readFileSync(tracePath, "utf-8"); + expect(trace.indexOf("openclaw|plugins|inspect|slack")).toBeGreaterThan( + trace.indexOf("openclaw|plugins|install"), + ); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + it("pins the registry tarball URL for every trusted built-in messaging plugin", () => { expect( reviewedOpenClawPluginTarballUrlByPackageSpec({ From 3b3e75bedb88124c59e176f90d0fe44d4ad2f2aa Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 21:03:23 -0700 Subject: [PATCH 054/133] fix(inference): compare known credential profile controls Signed-off-by: Deepak Jain --- .../openshell/provider-profile.test.ts | 29 +++++++++++++++++++ .../adapters/openshell/provider-profile.ts | 2 ++ 2 files changed, 31 insertions(+) diff --git a/src/lib/adapters/openshell/provider-profile.test.ts b/src/lib/adapters/openshell/provider-profile.test.ts index b7bf63014f6..651ecf93fbd 100644 --- a/src/lib/adapters/openshell/provider-profile.test.ts +++ b/src/lib/adapters/openshell/provider-profile.test.ts @@ -23,6 +23,7 @@ describe("OpenShell endpointless provider profiles", () => { it.each([ ["path_template", "/v1/{credential}"], ["token_grant", { endpoint: "https://attacker.example/token" }], + ["unknown_control", true], ])("rejects an unowned exported credential control: %s (#12558)", (key, value) => { const profile = { id: "native", @@ -69,3 +70,31 @@ describe("provider credential discovery boundary", () => { ).toBe(accepted); }); }); + +describe("known credential controls", () => { + it.each([{ path_template: "" }, { token_grant: { endpoint: "https://issuer.example/token" } }])( + "accepts matching owned credential controls [case %#]", + (control) => { + const profile = { + id: "owned", + credentials: [ + { + name: "api_key", + env_vars: ["API_KEY"], + required: true, + auth_style: "bearer", + header_name: "authorization", + ...control, + }, + ], + endpoints: [], + binaries: ["/usr/bin/curl"], + inference_capable: true, + }; + const source = JSON.stringify(profile); + const expected = parseCheckedInProviderProfileContract(source); + assert(expected, "owned profile rejected"); + expect(exportedProviderProfileMatchesContract(source, expected)).toBe(true); + }, + ); +}); diff --git a/src/lib/adapters/openshell/provider-profile.ts b/src/lib/adapters/openshell/provider-profile.ts index ff9e0454975..9fb89719fbf 100644 --- a/src/lib/adapters/openshell/provider-profile.ts +++ b/src/lib/adapters/openshell/provider-profile.ts @@ -32,6 +32,8 @@ const CREDENTIAL_KEYS = new Set([ "header_name", "name", "query_param", + "path_template", + "token_grant", "refresh", "required", ]); From d5b0f9206a160e01ea53e9be46ba2c097f1bbb24 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 21:12:40 -0700 Subject: [PATCH 055/133] test(e2e): verify image pull diagnostic redaction Signed-off-by: Deepak Jain --- .../live/podman-cpu-lifecycle-artifacts.ts | 18 +++++++++++ .../live/podman-portable-uninstall.test.ts | 12 +++---- test/e2e/mock-parity.json | 2 ++ .../podman-cpu-lifecycle-artifacts.test.ts | 31 ++++++++++++++++++- 4 files changed, 56 insertions(+), 7 deletions(-) diff --git a/test/e2e/live/podman-cpu-lifecycle-artifacts.ts b/test/e2e/live/podman-cpu-lifecycle-artifacts.ts index 6d26c3d3d44..cf4a7a5cc1d 100644 --- a/test/e2e/live/podman-cpu-lifecycle-artifacts.ts +++ b/test/e2e/live/podman-cpu-lifecycle-artifacts.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { ContainerEngine } from "../../../src/lib/adapters/container-engine.ts"; +import type { ArtifactSink } from "../fixtures/artifacts.ts"; import path from "node:path"; import { pathToFileURL } from "node:url"; @@ -126,3 +128,19 @@ if (invokedPath && import.meta.url === pathToFileURL(path.resolve(invokedPath)). process.exitCode = 1; }); } + +/** Retain failed pull diagnostics through the canonical artifact redaction boundary. */ +export function writePodmanImagePullArtifact( + artifacts: ArtifactSink, + relativePath: string, + image: string, + result: ReturnType, +): Promise { + return artifacts.writeJson(relativePath, { + image, + status: result.status, + stdout: result.stdout, + stderr: result.stderr, + error: result.error?.message, + }); +} diff --git a/test/e2e/live/podman-portable-uninstall.test.ts b/test/e2e/live/podman-portable-uninstall.test.ts index 82cae494918..bf12b3d94a1 100644 --- a/test/e2e/live/podman-portable-uninstall.test.ts +++ b/test/e2e/live/podman-portable-uninstall.test.ts @@ -11,6 +11,7 @@ import { } from "../../../src/lib/adapters/podman"; import { portableDemoReceiptPath } from "../../../src/lib/onboard/experimental/portable-runtime-receipt-readiness"; import { expect, test } from "../fixtures/e2e-test.ts"; +import { writePodmanImagePullArtifact } from "./podman-cpu-lifecycle-artifacts.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; import { cleanupPodmanLifecycle, @@ -181,13 +182,12 @@ test( const imagesPulled = [...imageWasPresent.keys()].every((image, index) => { const pull = engine.capture(["pull", image]); pullArtifacts.push( - artifacts.writeJson(`podman-uninstall-image-pull-${index + 1}.json`, { + writePodmanImagePullArtifact( + artifacts, + `podman-uninstall-image-pull-${index + 1}.json`, image, - status: pull.status, - stdout: pull.stdout, - stderr: pull.stderr, - error: pull.error?.message, - }), + pull, + ), ); return pull.status === 0; }); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 8c6a1ae603e..5a71af04e0d 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -145,7 +145,9 @@ }, { "live": "test/e2e/live/podman-portable-uninstall.test.ts", + "liveSources": ["test/e2e/live/podman-cpu-lifecycle-artifacts.ts"], "fast": [ + "test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts", "src/lib/actions/uninstall/portable-runtime-cleanup.test.ts", "src/lib/actions/uninstall/run-plan-portable-runtime.test.ts", "src/lib/onboard/docker-driver-gateway-runtime.test.ts", diff --git a/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts b/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts index 5adc25a45e3..65faa3a56b1 100644 --- a/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts +++ b/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts @@ -18,7 +18,11 @@ import { PODMAN_SANDBOX_WORKSPACE, PODMAN_SANDBOX_WORKSPACE_LABEL, } from "../../../src/lib/onboard/runtime-provider/podman-lifecycle.ts"; -import { sanitizePodmanInspectArtifact } from "../live/podman-cpu-lifecycle-artifacts.ts"; +import { ArtifactSink } from "../fixtures/artifacts.ts"; +import { + writePodmanImagePullArtifact, + sanitizePodmanInspectArtifact, +} from "../live/podman-cpu-lifecycle-artifacts.ts"; import { captureFailureContainerDiagnostics } from "../live/podman-cpu-lifecycle-helpers.ts"; const SECRET = "nvapi-this-must-not-reach-artifacts"; @@ -133,3 +137,28 @@ describe("Podman CPU proof artifact sanitization", () => { } }); }); + +it("retains failed image pull metadata without exposing credentials", async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "podman-pull-artifact-")); + try { + const sink = new ArtifactSink(root); + const image = "docker.io/library/ubuntu@sha256:fixture"; + const file = await writePodmanImagePullArtifact(sink, "failed-pull.json", image, { + status: 1, + stdout: `NVIDIA_API_KEY=${SECRET}`, + stderr: `download failed NVIDIA_API_KEY=${SECRET}`, + error: new Error(`NVIDIA_API_KEY=${SECRET}`), + }); + const raw = fs.readFileSync(file, "utf8"); + expect(JSON.parse(raw)).toMatchObject({ + image, + status: 1, + stderr: expect.stringContaining("download failed"), + error: expect.any(String), + }); + expect(raw).not.toContain(SECRET); + expect(raw).toContain(""); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); From ed89caffadba86fa302126d2eef0b413a96c1e99 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 21:06:35 -0700 Subject: [PATCH 056/133] test(inference): align launcher assertions with native routes Signed-off-by: Deepak Jain (cherry picked from commit c0e2f8b7fa30f519d0ecf1ff64b7cf0cf657e242) --- .../langchain-deepagents-code-proxy-launcher.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts b/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts index 39e3080ccd1..ff56137b5f7 100644 --- a/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts @@ -710,8 +710,12 @@ describe.concurrent("Deep Agents Code direct-exec proxy launcher", () => { expect(headlessCheck).toContain("getent hosts inference.local >/dev/null 2>&1"); expect(headlessCheck).toContain("direct inference.local DNS/hosts is absent"); expect(headlessCheck).toContain('stat -c "%u:%a"'); - expect(headlessCheck).toContain("direct-exec dcode -n reached managed inference"); - expect(headlessCheck).toContain("connect --probe-only accepted the managed inference route"); + expect(headlessCheck).toContain( + "direct-exec dcode -n reached ${route_contract:-unknown} inference", + ); + expect(headlessCheck).toContain( + "connect --probe-only accepted the ${route_contract:-unknown} inference route", + ); }); it.each([ From cb2cf11281feb6096ab2344be310cbacb50c4d3a Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 21:39:19 -0700 Subject: [PATCH 057/133] fix(messaging): validate the installed Slack remediation path Signed-off-by: Deepak Jain --- scripts/lib/openclaw-npm-remediation.mts | 12 +- .../applier/build/messaging-build-applier.mts | 68 +++++++- .../openclaw/openclaw-npm-remediation.test.ts | 58 +++++++ .../messaging-build-applier-integrity.test.ts | 147 +++++++++++++++++- 4 files changed, 269 insertions(+), 16 deletions(-) diff --git a/scripts/lib/openclaw-npm-remediation.mts b/scripts/lib/openclaw-npm-remediation.mts index b73aa429dee..6389ee3d000 100755 --- a/scripts/lib/openclaw-npm-remediation.mts +++ b/scripts/lib/openclaw-npm-remediation.mts @@ -220,9 +220,9 @@ function run(command: string, args: readonly string[], cwd: string, env: NodeJS. maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], }); - if (result.error) throw result.error; + if (result.error) throw new Error("OpenClaw npm remediation command could not start"); if (result.status !== 0) { - throw new Error(`${command} ${args.join(" ")} failed: ${result.stderr || result.stdout}`); + throw new Error("OpenClaw npm remediation command failed"); } return result.stdout; } @@ -235,7 +235,7 @@ function validateArchiveMembers(archivePath: string, cwd: string, env: NodeJS.Pr .split("\n") .filter((entry) => entry.length > 0); if (names.length === 0 || verbose.length !== names.length) { - throw new Error(`npm archive ${archivePath} has an invalid member listing`); + throw new Error("npm archive has an invalid member listing"); } const seen = new Set(); for (let index = 0; index < names.length; index += 1) { @@ -249,12 +249,12 @@ function validateArchiveMembers(archivePath: string, cwd: string, env: NodeJS.Pr normalized.split("/").some((part) => part === "" || part === "." || part === "..") || seen.has(normalized) ) { - throw new Error(`npm archive ${archivePath} has an unsafe member: ${member}`); + throw new Error("npm archive has an unsafe member"); } seen.add(normalized); } if (!seen.has("package/package.json")) { - throw new Error(`npm archive ${archivePath} has no package/package.json`); + throw new Error("npm archive has no package/package.json"); } } @@ -269,7 +269,7 @@ function extractArchive( run("tar", ["-xzf", archivePath, "-C", destination], cwd, env); const packageDirectory = join(destination, "package"); if (!existsSync(join(packageDirectory, "package.json"))) { - throw new Error(`npm archive ${archivePath} did not extract a package directory`); + throw new Error("npm archive did not extract a package directory"); } return packageDirectory; } diff --git a/src/lib/messaging/applier/build/messaging-build-applier.mts b/src/lib/messaging/applier/build/messaging-build-applier.mts index 19a003017b6..6ef616fad63 100755 --- a/src/lib/messaging/applier/build/messaging-build-applier.mts +++ b/src/lib/messaging/applier/build/messaging-build-applier.mts @@ -17,7 +17,7 @@ import { writeFileSync, } from "node:fs"; import { homedir } from "node:os"; -import { dirname, isAbsolute, join, resolve, sep } from "node:path"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { pathToFileURL } from "node:url"; import { applyOpenClawSlackProxyAddrRemediation, @@ -823,15 +823,17 @@ function installOpenClawPluginPackages(installs: readonly OpenClawPluginInstall[ : "inspection failed", ); } - verifyTrustedOfficialNpmInstall(install, officialPluginId, inspection); + const verifiedInstall = verifyTrustedOfficialNpmInstall( + install, + officialPluginId, + inspection, + ); if (install.npmPackageSpec === "@openclaw/slack@2026.9.2") { applyOpenClawSlackProxyAddrRemediation({ env: installEnv as NodeJS.ProcessEnv, - packageDirectory: join( - installEnv.HOME ?? homedir(), - ".openclaw", - "extensions", - officialPluginId, + packageDirectory: validatedSlackInstallDirectory( + verifiedInstall.installPath, + commandEnv, ), workingDirectory: packed.rootDir, }); @@ -1459,7 +1461,7 @@ function verifyTrustedOfficialNpmInstall( install: OpenClawPluginInstall, pluginId: string, inspectOutput: string, -): void { +): Record { let inspected: unknown; try { inspected = JSON.parse(inspectOutput); @@ -1483,6 +1485,56 @@ function verifyTrustedOfficialNpmInstall( "did not retain trusted exact registry provenance", ); } + return record; +} + +/** Match the pinned OpenClaw managed npm layout, never an invented extensions path. */ +function validatedSlackInstallDirectory(installPath: unknown, env: Env): string { + try { + const homeValue = (value: string | undefined) => + value?.trim() && value.trim() !== "undefined" && value.trim() !== "null" + ? value.trim() + : undefined; + const osHome = homeValue(env.HOME) ?? homeValue(env.USERPROFILE) ?? homedir(); + const expand = (value: string, home: string) => + resolve(value.trim().replace(/^~(?=$|[\\/])/, () => home)); + const home = expand(homeValue(env.OPENCLAW_HOME) ?? osHome, osHome); + const configRoot = env.OPENCLAW_STATE_DIR?.trim() + ? expand(env.OPENCLAW_STATE_DIR, home) + : env.OPENCLAW_CONFIG_PATH?.trim() + ? dirname(expand(env.OPENCLAW_CONFIG_PATH, home)) + : join(home, ".openclaw"); + const projectsRoot = join(configRoot, "npm", "projects"); + const matchesPackageLayout = (root: string, candidate: string) => { + const parts = relative(root, candidate).split(sep); + return ( + parts.length === 4 && + parts[0] !== ".." && + parts[0] !== "" && + parts[1] === "node_modules" && + parts[2] === "@openclaw" && + parts[3] === "slack" + ); + }; + if ( + typeof installPath !== "string" || + !isAbsolute(installPath) || + installPath.split(sep).includes("..") || + !matchesPackageLayout(projectsRoot, installPath) + ) { + throw new Error(); + } + const packageStat = lstatSync(installPath); + if (!packageStat.isDirectory() || packageStat.isSymbolicLink()) throw new Error(); + const canonicalRoot = realpathSync(projectsRoot); + const canonicalPackage = realpathSync(installPath); + if (!matchesPackageLayout(canonicalRoot, canonicalPackage)) throw new Error(); + return canonicalPackage; + } catch { + throw new MessagingBuildApplierError( + "OpenClaw Slack remediation requires a valid managed npm package directory", + ); + } } function packVerifiedOpenClawPluginArchive( diff --git a/test/agents/openclaw/openclaw-npm-remediation.test.ts b/test/agents/openclaw/openclaw-npm-remediation.test.ts index 207fdf9d5b1..4e6612ab755 100644 --- a/test/agents/openclaw/openclaw-npm-remediation.test.ts +++ b/test/agents/openclaw/openclaw-npm-remediation.test.ts @@ -522,6 +522,64 @@ afterEach(() => { }); describe("OpenClaw npm remediation", () => { + it.each([ + { + failure: "malformed", + prepare: (archivePath: string) => writeFileSync(archivePath, "not a tar archive"), + env: {}, + message: "OpenClaw npm remediation command failed", + }, + { + failure: "missing", + prepare: (_archivePath: string) => undefined, + env: {}, + message: "OpenClaw npm remediation command failed", + }, + { + failure: "unavailable tar", + prepare: (archivePath: string) => writeFileSync(archivePath, "not a tar archive"), + env: { PATH: "" }, + message: "OpenClaw npm remediation command could not start", + }, + ])("withholds archive paths and child diagnostics when $failure", ({ prepare, env, message }) => { + const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-private-archive-marker-")); + temporaryDirectories.push(directory); + const archivePath = path.join(directory, "private-archive-marker.tgz"); + prepare(archivePath); + const request = { + archivePath, + packageSpec: "@openclaw/slack@2026.9.2", + workingDirectory: path.join(directory, "work"), + env, + }; + + expect(() => buildRemediatedOpenClawArchive(request)).toThrow(message); + expect(() => buildRemediatedOpenClawArchive(request)).not.toThrow("private-archive-marker"); + }); + + it("rejects unsafe archive members without echoing their names or archive path", () => { + const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-private-archive-marker-")); + temporaryDirectories.push(directory); + const memberName = "private-member-marker"; + writeFileSync(path.join(directory, memberName), "untrusted member"); + const archivePath = path.join(directory, "private-archive-marker.tgz"); + const packed = spawnSync("tar", ["-czf", archivePath, "-C", directory, memberName], { + encoding: "utf8", + }); + expect(packed.status, packed.stderr).toBe(0); + const request = { + archivePath, + packageSpec: "@openclaw/slack@2026.9.2", + workingDirectory: path.join(directory, "work"), + }; + + expect(() => buildRemediatedOpenClawArchive(request)).toThrow( + "npm archive has an unsafe member", + ); + expect(() => buildRemediatedOpenClawArchive(request)).not.toThrow("private-member-marker"); + expect(() => buildRemediatedOpenClawArchive(request)).not.toThrow("private-archive-marker"); + }); + it("hashes package entries through opened file descriptors", () => { const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-openclaw-tree-integrity-")); temporaryDirectories.push(directory); diff --git a/test/runtime/messaging/messaging-build-applier-integrity.test.ts b/test/runtime/messaging/messaging-build-applier-integrity.test.ts index ae764b525c4..2ea324d7b9b 100644 --- a/test/runtime/messaging/messaging-build-applier-integrity.test.ts +++ b/test/runtime/messaging/messaging-build-applier-integrity.test.ts @@ -191,13 +191,45 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { testTimeout(15_000), ); - it("remediates proxy-addr after verifying the official Slack 2026.9.2 install", async () => { + it.each([ + { name: "HOME", overrides: {}, root: ".openclaw" }, + { name: "state override", overrides: { OPENCLAW_STATE_DIR: "~/state" }, root: "state" }, + { + name: "config override", + overrides: { OPENCLAW_CONFIG_PATH: "~/config/openclaw.json" }, + root: "config", + }, + { + name: "home override", + overrides: { OPENCLAW_HOME: "~/alternate" }, + root: "alternate/.openclaw", + }, + { + name: "state precedence and effective home expansion", + overrides: { + OPENCLAW_HOME: "~/alternate", + OPENCLAW_STATE_DIR: "~/state", + OPENCLAW_CONFIG_PATH: "~/ignored/config.json", + }, + root: "alternate/state", + }, + ])("remediates the verified managed Slack install using $name", async ({ overrides, root }) => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-slack-remediation-")); + const packageDirectory = path.join( + tmp, + root, + "npm/projects/project/node_modules/@openclaw/slack", + ); + fs.mkdirSync(packageDirectory, { recursive: true }); + // The ordinary managed OpenClaw peer link is legal below the package root. + fs.mkdirSync(path.join(packageDirectory, "node_modules")); + fs.symlinkSync(tmp, path.join(packageDirectory, "node_modules/openclaw")); const tracePath = path.join(tmp, "openclaw.trace"); const inspection = JSON.stringify({ plugin: { id: "slack", trustedOfficialInstall: true }, install: { source: "npm", + installPath: packageDirectory, resolvedSpec: "@openclaw/slack@2026.9.2", integrity: OPENCLAW_SLACK_2026_9_2_INTEGRITY, }, @@ -235,6 +267,7 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { { PATH: `${tmp}:${process.env.PATH || "/usr/bin:/bin"}`, HOME: tmp, + ...overrides, OPENCLAW_TRACE: tracePath, OPENCLAW_SLACK_2026_9_2_INTEGRITY, OPENCLAW_VERSION: "2026.9.2", @@ -248,7 +281,7 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { expect(applySlackProxyAddrRemediation).toHaveBeenCalledOnce(); expect(applySlackProxyAddrRemediation).toHaveBeenCalledWith( expect.objectContaining({ - packageDirectory: path.join(tmp, ".openclaw", "extensions", "slack"), + packageDirectory: fs.realpathSync(packageDirectory), }), ); const remediationRequest = applySlackProxyAddrRemediation.mock.calls[0]?.[0] as { @@ -264,6 +297,116 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { } }); + it.each([ + "missing", + "empty", + "relative", + "nonexistent", + "outside", + "traversal", + "wrong package", + "package symlink", + "escaping parent symlink", + "file", + "untrusted provenance", + ])("refuses Slack remediation before mutation for %s", async (scenario) => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-slack-install-denial-")); + try { + const packageDirectory = path.join( + tmp, + ".openclaw/npm/projects/project/node_modules/@openclaw/slack", + ); + fs.mkdirSync(packageDirectory, { recursive: true }); + const sentinel = path.join(packageDirectory, "untouched"); + fs.writeFileSync(sentinel, "original"); + const installPaths: Record = { + missing: undefined, + empty: "", + relative: "project/node_modules/@openclaw/slack", + nonexistent: path.join(tmp, ".openclaw/npm/projects/absent/node_modules/@openclaw/slack"), + outside: path.join(tmp, "outside/node_modules/@openclaw/slack"), + traversal: + path.join(tmp, ".openclaw/npm/projects") + + "/../projects/project/node_modules/@openclaw/slack", + "wrong package": path.join( + tmp, + ".openclaw/npm/projects/project/node_modules/@openclaw/discord", + ), + "package symlink": path.join( + tmp, + ".openclaw/npm/projects/link/node_modules/@openclaw/slack", + ), + "escaping parent symlink": path.join( + tmp, + ".openclaw/npm/projects/escape/node_modules/@openclaw/slack", + ), + file: path.join(tmp, ".openclaw/npm/projects/file/node_modules/@openclaw/slack"), + "untrusted provenance": packageDirectory, + }; + const linkPath = installPaths["package symlink"]!; + fs.mkdirSync(path.dirname(linkPath), { recursive: true }); + fs.symlinkSync(packageDirectory, linkPath); + const outsideProject = path.join(tmp, "outside"); + fs.mkdirSync(path.join(outsideProject, "node_modules/@openclaw/slack"), { recursive: true }); + fs.symlinkSync(outsideProject, path.join(tmp, ".openclaw/npm/projects/escape")); + fs.mkdirSync(path.dirname(installPaths.file!), { recursive: true }); + fs.writeFileSync(installPaths.file!, "not a directory"); + const inspection = JSON.stringify({ + plugin: { id: "slack", trustedOfficialInstall: scenario !== "untrusted provenance" }, + install: { + source: "npm", + resolvedSpec: "@openclaw/slack@2026.9.2", + integrity: OPENCLAW_SLACK_2026_9_2_INTEGRITY, + installPath: installPaths[scenario], + }, + }); + fs.writeFileSync( + path.join(tmp, "npm"), + [ + "#!/bin/sh", + 'if [ "$1" = "view" ] && [ "$3" = "dist.integrity" ]; then printf "%s" "$TEST_INTEGRITY"; exit 0; fi', + 'if [ "$1" = "view" ]; then printf "%s" "https://registry.npmjs.org/@openclaw/slack/-/slack-2026.9.2.tgz"; exit 0; fi', + `if [ "$1" = "pack" ]; then printf "archive" > "$4/slack.tgz"; printf '[{"filename":"slack.tgz","integrity":"%s"}]' "$TEST_INTEGRITY"; exit 0; fi`, + "exit 1", + "", + ].join("\n"), + { mode: 0o755 }, + ); + fs.writeFileSync( + path.join(tmp, "openclaw"), + [ + "#!/bin/sh", + 'if [ "$2" = "inspect" ]; then printf "%s" "$TEST_INSPECTION"; fi', + "exit 0", + "", + ].join("\n"), + { mode: 0o755 }, + ); + const env = await withLegacyMessagingPlanEnvDirect( + { + PATH: `${tmp}:${process.env.PATH || "/usr/bin:/bin"}`, + HOME: tmp, + TEST_INTEGRITY: OPENCLAW_SLACK_2026_9_2_INTEGRITY, + TEST_INSPECTION: inspection, + OPENCLAW_VERSION: "2026.9.2", + NEMOCLAW_MESSAGING_CHANNELS_B64: channelsB64(["slack"]), + }, + "openclaw", + ); + const plan = readMessagingBuildPlanFromEnv(env, "openclaw"); + const failure = () => applyMessagingBuildPhase(plan, "agent-install", env); + const expectedMessage = + scenario === "untrusted provenance" + ? "OpenClaw official npm plugin slack did not retain trusted exact registry provenance" + : "OpenClaw Slack remediation requires a valid managed npm package directory"; + expect(failure).toThrow(expect.objectContaining({ message: expectedMessage })); + expect(applySlackProxyAddrRemediation).not.toHaveBeenCalled(); + expect(fs.readFileSync(sentinel, "utf8")).toBe("original"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + it("pins the registry tarball URL for every trusted built-in messaging plugin", () => { expect( reviewedOpenClawPluginTarballUrlByPackageSpec({ From 19a4a81fc90c6951833c90ba8f152ed819e0fefc Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 21:46:03 -0700 Subject: [PATCH 058/133] test(messaging): type the Slack environment cases --- .../runtime/messaging/messaging-build-applier-integrity.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/runtime/messaging/messaging-build-applier-integrity.test.ts b/test/runtime/messaging/messaging-build-applier-integrity.test.ts index 2ea324d7b9b..3802ea52f50 100644 --- a/test/runtime/messaging/messaging-build-applier-integrity.test.ts +++ b/test/runtime/messaging/messaging-build-applier-integrity.test.ts @@ -191,7 +191,7 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { testTimeout(15_000), ); - it.each([ + it.each<{ name: string; overrides: Record; root: string }>([ { name: "HOME", overrides: {}, root: ".openclaw" }, { name: "state override", overrides: { OPENCLAW_STATE_DIR: "~/state" }, root: "state" }, { From 2503c638ecd1d246d6d5a7ba268d7e008127634f Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 5 Oct 2026 22:17:00 -0700 Subject: [PATCH 059/133] fix(security): retain safe remediation failure categories Signed-off-by: Deepak Jain --- scripts/lib/openclaw-npm-remediation.mts | 8 +++++-- .../fatal-process-diagnostics.test.ts | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/scripts/lib/openclaw-npm-remediation.mts b/scripts/lib/openclaw-npm-remediation.mts index 6389ee3d000..a57d45e3339 100755 --- a/scripts/lib/openclaw-npm-remediation.mts +++ b/scripts/lib/openclaw-npm-remediation.mts @@ -1778,12 +1778,16 @@ function isMainModule(): boolean { return process.argv[1] ? import.meta.url === pathToFileURL(resolve(process.argv[1])).href : false; } -function fatalOpenClawNpmRemediationDiagnostic(error: unknown): string { +export function fatalOpenClawNpmRemediationDiagnostic(error: unknown): string { const message = error instanceof Error ? error.message : ""; if (message.startsWith("Missing --")) { return "OpenClaw npm remediation is missing required arguments."; } - if (message.includes(" failed:")) { + if ( + message === "OpenClaw npm remediation command failed" || + message === "OpenClaw npm remediation command could not start" || + message.includes(" failed:") + ) { return "OpenClaw npm remediation command failed."; } if ( diff --git a/test/security/fatal-process-diagnostics.test.ts b/test/security/fatal-process-diagnostics.test.ts index 407c9c93dca..4cb6adf426c 100644 --- a/test/security/fatal-process-diagnostics.test.ts +++ b/test/security/fatal-process-diagnostics.test.ts @@ -8,6 +8,8 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { describe, expect, it } from "vitest"; +import { fatalOpenClawNpmRemediationDiagnostic } from "../../scripts/lib/openclaw-npm-remediation.mts"; + const REPOSITORY_ROOT = path.join(import.meta.dirname, "../.."); const MESSAGING_BUILD_APPLIER = path.join( REPOSITORY_ROOT, @@ -45,6 +47,25 @@ function encodedMessagingPlan(renderTarget: string | null): string { } describe("fatal process diagnostics", () => { + it.each([ + "OpenClaw npm remediation command failed", + "OpenClaw npm remediation command could not start", + ])("classifies the fixed command diagnostic %s", (message) => { + expect(fatalOpenClawNpmRemediationDiagnostic(new Error(message))).toBe( + "OpenClaw npm remediation command failed.", + ); + }); + + it.each([ + `OpenClaw npm remediation command failed ${CREDENTIAL_CANARY}`, + `OpenClaw npm remediation command could not start ${CREDENTIAL_CANARY}`, + CREDENTIAL_CANARY, + ])("keeps unrecognized error text behind the generic diagnostic", (message) => { + const diagnostic = fatalOpenClawNpmRemediationDiagnostic(new Error(message)); + expect(diagnostic).toBe("OpenClaw npm remediation failed."); + expect(diagnostic).not.toContain(CREDENTIAL_CANARY); + }); + it("omits messaging plan credentials from a build failure (#11673)", () => { const result = spawnSync( process.execPath, From 9241f932f850399fe52b47b17d113496c916fdd2 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:39:54 -0700 Subject: [PATCH 060/133] test(inference): align native NVIDIA closeout with main Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .github/workflows/e2e.yaml | 54 +- .github/workflows/managed-images.yaml | 75 +- ci/e2e-assertion-budget.json | 2 +- install.sh | 1 + scripts/install.sh | 50 +- ...ain-deepagents-code-proxy-launcher.test.ts | 8 +- test/e2e/README.md | 17 +- test/e2e/docs/dgx-station-dispatch.md | 32 + ...press-vllm.test.ts => dgx-express.test.ts} | 38 +- test/e2e/mock-parity.json | 5 +- test/e2e/support/dgx-station-dispatch.test.ts | 208 +++++ test/e2e/support/dgx-station-express.test.ts | 861 ++++++++++++++++++ test/e2e/support/dgx-station-express.ts | 445 +++++++++ .../dgx-station-workflow-boundary.test.ts | 138 +++ .../support/e2e-semantic-phase-check.test.ts | 13 + .../support/live-vitest-invocation.test.ts | 97 ++ test/e2e/support/workflow-plan.test.ts | 6 - .../install-express-noninteractive.test.ts | 224 +++++ tools/e2e/check-semantic-phases.mts | 4 + .../contracts/v3/dgx-station-dispatch.json | 140 +++ tools/e2e/dgx-station-cleanup.mts | 323 +++++++ tools/e2e/dgx-station-dispatch-client.mts | 48 + tools/e2e/dgx-station-workflow-boundary.mts | 122 +++ tools/e2e/jetson-dispatch-client.mts | 163 ++-- tools/e2e/jetson-dispatch-contract.mts | 137 ++- tools/e2e/live-vitest-invocation.mts | 14 +- tools/e2e/operations-workflow-boundary.mts | 9 +- tools/e2e/prepare-e2e-workflow-boundary.mts | 1 + ...upload-e2e-artifacts-workflow-boundary.mts | 7 + tools/e2e/workflow-boundary.mts | 6 +- tools/e2e/workflow-plan.mts | 15 +- 31 files changed, 3139 insertions(+), 124 deletions(-) create mode 100644 test/e2e/docs/dgx-station-dispatch.md rename test/e2e/live/{spark-express-vllm.test.ts => dgx-express.test.ts} (91%) create mode 100644 test/e2e/support/dgx-station-dispatch.test.ts create mode 100644 test/e2e/support/dgx-station-express.test.ts create mode 100644 test/e2e/support/dgx-station-express.ts create mode 100644 test/e2e/support/dgx-station-workflow-boundary.test.ts create mode 100644 test/installer-integration/install-express-noninteractive.test.ts create mode 100644 tools/e2e/contracts/v3/dgx-station-dispatch.json create mode 100644 tools/e2e/dgx-station-cleanup.mts create mode 100644 tools/e2e/dgx-station-dispatch-client.mts create mode 100644 tools/e2e/dgx-station-workflow-boundary.mts diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 97f1331e5eb..20a383b058a 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -100,7 +100,7 @@ permissions: concurrency: group: e2e-${{ github.ref }}-${{ (inputs.jobs == 'staging-brev-launchable' || inputs.jobs == 'staging-brev-launchable-identity' || inputs.include_staging_brev_launchable) && format('launchable-{0}', github.run_id) || inputs.checkout_sha != '' && format('pr-{0}', inputs.pr_number) || inputs.targets || 'supported' }}-${{ inputs.checkout_sha != '' && 'manual-pr' || inputs.jobs || 'all-jobs' }} - cancel-in-progress: ${{ inputs.checkout_sha != '' && !inputs.allow_jetson_dispatch && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable-identity,') && !inputs.include_staging_brev_launchable }} + cancel-in-progress: ${{ inputs.checkout_sha != '' && !inputs.allow_jetson_dispatch && !contains(format(',{0},{1},', inputs.jobs, inputs.targets), ',dgx-station-express,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable-identity,') && !inputs.include_staging_brev_launchable }} env: NEMOCLAW_E2E_EXPECTED_SHA: ${{ inputs.checkout_sha }} @@ -5863,6 +5863,57 @@ jobs: name: e2e-jetson-nvmap-gpu path: ${{ runner.temp }}/e2e-artifacts/live/jetson-nvmap-gpu/ + dgx-station-express: + needs: [base-image-publication, generate-matrix] + if: ${{ always() && needs['base-image-publication'].result == 'success' && needs['base-image-publication'].outputs.managed_image_revision != '' && needs['generate-matrix'].result == 'success' && github.repository == 'NVIDIA/NemoClaw' && github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' && (inputs.checkout_sha == '' || inputs.checkout_sha != inputs.base_sha) && (inputs.checkout_repository == '' || inputs.checkout_repository == github.repository) && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'dgx-station-express') && ((inputs.jobs == 'dgx-station-express' && inputs.targets == '') || (inputs.targets == 'dgx-station-express' && inputs.jobs == '')) }} + concurrency: + group: dgx-station-express-dispatch + cancel-in-progress: false + runs-on: ubuntu-latest + timeout-minutes: 60 + permissions: + contents: read + id-token: write + env: + E2E_JOB: "1" + E2E_TARGET_ID: dgx-station-express + E2E_TEST_FILE: test/e2e/live/dgx-express.test.ts + E2E_DEFAULT_ENABLED: "0" + E2E_GATEWAY_RUNTIMES: agnostic + E2E_AGENT_RUNTIME: openclaw + E2E_OBSERVABLE_OUTCOME: Station Express installs managed Ultra vLLM and NemoClaw, serves sandbox inference, and removes job runtime + E2E_ENVIRONMENT_OR_INFERENCE_ENDPOINT: Dedicated DGX Station GB300 with cached Nemotron 3 Ultra 550B + steps: + - name: Check out trusted Station controller + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ github.workflow_sha }} + persist-credentials: false + + - name: Set up Node for Station controller + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24.18.1 + + - name: Install reviewed npm + uses: NVIDIA/NemoClaw/.github/actions/setup-reviewed-npm@98669f24d35f18e49b6b2769cd68709509ea24f2 + + - name: Dispatch exact commit to Station through operator backend + env: + E2E_ARTIFACT_DIR: ${{ runner.temp }}/e2e-artifacts/live/dgx-station-express + DGX_STATION_DISPATCH_CANDIDATE_SHA: ${{ inputs.checkout_sha || github.sha }} + DGX_STATION_DISPATCH_MANAGED_IMAGE_REVISION: ${{ needs.base-image-publication.outputs.managed_image_revision }} + DGX_STATION_DISPATCH_URL: ${{ vars.DGX_STATION_DISPATCH_URL }} + run: node --no-warnings tools/e2e/dgx-station-dispatch-client.mts + + - name: Upload Station Express artifacts + if: always() + uses: NVIDIA/NemoClaw/.github/actions/upload-e2e-artifacts@7768e15eb90d3ee2d33432f481dfe8747e4f6d57 + with: + name: e2e-dgx-station-express + path: ${{ runner.temp }}/e2e-artifacts/live/dgx-station-express/ + cloud-onboard: name: Cloud onboard (${{ matrix.runtime_provider }}) needs: [base-image-publication, generate-matrix] @@ -6153,6 +6204,7 @@ jobs: portable-hermes-finalization, messaging-providers, jetson-nvmap-gpu, + dgx-station-express, cloud-onboard, native-runtime-qualification-producer, native-runtime-qualification-producer-aggregate, diff --git a/.github/workflows/managed-images.yaml b/.github/workflows/managed-images.yaml index ae37bbaabee..392a839d946 100644 --- a/.github/workflows/managed-images.yaml +++ b/.github/workflows/managed-images.yaml @@ -502,18 +502,11 @@ jobs: chmod 0664 "$artifact_path" done - - name: Download same-run npm audit evidence - if: matrix.agent == 'openclaw' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: reviewed-npm-audit - path: ${{ runner.temp }}/reviewed-npm-audit - - name: Checkout trusted mcporter audit verifier if: matrix.agent == 'openclaw' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.event.pull_request.base.sha }} + ref: e0769ad0e6783e4108a1f26cc44b162f1f7ecc3f # reviewed proxy-addr 2.0.8 lock path: .trusted-mcporter-audit persist-credentials: false sparse-checkout: | @@ -521,6 +514,7 @@ jobs: ci/reviewed-npm-audit.json scripts/lib/npm-audit-receipt.mts scripts/lib/reviewed-npm-audit.mts + scripts/lib/reviewed-npm-archive.mts sparse-checkout-cone-mode: false - name: Set up Node.js @@ -536,14 +530,69 @@ jobs: id: mcporter-audit shell: bash env: - REVIEWED_AUDIT_SHA: ${{ github.event.pull_request.base.sha }} + REVIEWED_AUDIT_SHA: e0769ad0e6783e4108a1f26cc44b162f1f7ecc3f run: | set -euo pipefail - receipt="$RUNNER_TEMP/reviewed-npm-audit/mcporter-runtime.receipt.json" - raw="$RUNNER_TEMP/reviewed-npm-audit/mcporter-runtime.raw.json" - policy="$RUNNER_TEMP/reviewed-npm-audit/mcporter-runtime.policy.json" + receipt="$RUNNER_TEMP/trusted-mcporter-audit-report/mcporter-runtime.receipt.json" + raw="$RUNNER_TEMP/trusted-mcporter-audit-report/mcporter-runtime.raw.json" + policy="$RUNNER_TEMP/trusted-mcporter-audit-report/mcporter-runtime.policy.json" trusted_root="$GITHUB_WORKSPACE/.trusted-mcporter-audit" test "$(git -C "$trusted_root" rev-parse --verify HEAD)" = "$REVIEWED_AUDIT_SHA" + audit_config="$RUNNER_TEMP/pr-mcporter-audit-config.json" + # PR builds must accept an audited dependency repair before its lock + # identity reaches main. Retain all other base-owned policy fields. + node --input-type=module - \ + "$trusted_root/ci/reviewed-npm-audit.json" \ + "$GITHUB_WORKSPACE/ci/reviewed-npm-audit.json" "$audit_config" <<'NODE' + import { readFileSync, writeFileSync } from "node:fs"; + import { isDeepStrictEqual } from "node:util"; + const [trustedPath, candidatePath, outputPath] = process.argv.slice(2); + const trusted = JSON.parse(readFileSync(trustedPath, "utf8")); + const candidate = JSON.parse(readFileSync(candidatePath, "utf8")); + const baseGraph = trusted.lockedGraphs.find((graph) => graph.id === "mcporter-runtime"); + const candidateGraph = candidate.lockedGraphs.find((graph) => graph.id === "mcporter-runtime"); + if (!baseGraph || !candidateGraph || !isDeepStrictEqual( + { ...candidateGraph, lockSha256: baseGraph.lockSha256 }, baseGraph, + )) { + throw new Error("Candidate mcporter package identity differs from the trusted base"); + } + baseGraph.lockSha256 = candidateGraph.lockSha256; + writeFileSync(outputPath, JSON.stringify(trusted), { mode: 0o600 }); + NODE + node --input-type=module - "$trusted_root" \ + "$GITHUB_WORKSPACE/agents/openclaw/mcporter-runtime" "$audit_config" \ + "$RUNNER_TEMP/trusted-mcporter-audit-report" <<'AUDIT' + import { execFileSync } from "node:child_process"; + import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; + import { join } from "node:path"; + import { pathToFileURL } from "node:url"; + const [trustedRoot, sourceRoot, configPath, reportRoot] = process.argv.slice(2); + const { verifyReviewedNpmLock, verifyInstalledNpmLock } = await import(pathToFileURL(join(trustedRoot, "scripts/lib/reviewed-npm-archive.mts"))); + const { runReviewedNpmAudit } = await import(pathToFileURL(join(trustedRoot, "scripts/lib/reviewed-npm-audit.mts"))); + const { createAuditReceipt, canonicalAuditReceipt } = await import(pathToFileURL(join(trustedRoot, "scripts/lib/npm-audit-receipt.mts"))); + const config = JSON.parse(readFileSync(configPath, "utf8")); + const graph = config.lockedGraphs.find((entry) => entry.id === "mcporter-runtime"); + const directory = mkdtempSync(join(process.env.RUNNER_TEMP ?? "/tmp", "mcporter-audit-")); + const packageJson = join(sourceRoot, "package.json"), packageLock = join(sourceRoot, "package-lock.json"); + const exceptionFile = join(trustedRoot, "ci/npm-audit-exceptions.json"); + mkdirSync(reportRoot, { mode: 0o700 }); + const raw = join(reportRoot, "mcporter-runtime.raw.json"); + try { + verifyReviewedNpmLock({ expectedIntegrity: graph.integrity, expectedLockSha256: graph.lockSha256, label: graph.label, lockfilePath: packageLock, packageSpec: graph.packageSpec, registryOrigin: config.registryOrigin, tarballUrl: graph.tarballUrl }); + copyFileSync(packageJson, join(directory, "package.json")); + copyFileSync(packageLock, join(directory, "package-lock.json")); + const env = { ...process.env, NPM_CONFIG_USERCONFIG: "/dev/null", NPM_CONFIG_REGISTRY: config.registryOrigin }; + delete env.NODE_AUTH_TOKEN; delete env.NPM_TOKEN; delete env.GH_TOKEN; + execFileSync("npm", ["ci", "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund"], { cwd: directory, env, stdio: "inherit" }); + verifyInstalledNpmLock({ expectedLockSha256: graph.lockSha256, installRoot: directory, label: graph.label, lockfilePath: join(directory, "package-lock.json"), omitDev: true }); + execFileSync("npm", ["audit", "signatures", "--registry=https://registry.yarnpkg.com", "--omit=dev"], { cwd: directory, env, stdio: "inherit" }); + const result = runReviewedNpmAudit({ directory, exceptionFile, graph: graph.id, reviewedNpmIdentity: config, reportFile: raw, resultFile: join(reportRoot, "mcporter-runtime.policy.json"), threshold: "high" }); + const receipt = createAuditReceipt({ acceptedAdvisoryIds: result.acceptedAdvisories, blockingAdvisoryIds: result.unacceptedBlockingAdvisories.map((finding) => finding.advisory), exceptionPolicySha256: result.exceptionPolicySha256, graphId: graph.id, reviewedNpmIdentity: config, packageJson: readFileSync(packageJson), packageLock: readFileSync(packageLock), rawResponse: readFileSync(raw), registryOrigin: "https://registry.yarnpkg.com", severityThreshold: "high" }); + writeFileSync(join(reportRoot, "mcporter-runtime.receipt.json"), canonicalAuditReceipt(receipt), { mode: 0o600 }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + AUDIT node --experimental-strip-types --no-warnings \ "$trusted_root/scripts/lib/npm-audit-receipt.mts" \ --receipt "$receipt" \ @@ -552,7 +601,7 @@ jobs: --raw-report "$raw" \ --exceptions "$trusted_root/ci/npm-audit-exceptions.json" \ --graph mcporter-runtime \ - --audit-config "$trusted_root/ci/reviewed-npm-audit.json" \ + --audit-config "$audit_config" \ --registry https://registry.yarnpkg.com \ --threshold high \ --result "$policy" diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 4b7af678d13..b579f8bc899 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -59,6 +59,7 @@ "test/e2e/live/cron-preflight-inference-local.test.ts": [3,8,3,8,0], "test/e2e/live/dashboard-remote-bind.test.ts": [16,14,16,16,3], "test/e2e/live/deferred-onboarding.test.ts": [12,14,12,14,0], + "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], "test/e2e/live/double-onboard.test.ts": [36,43,36,43,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], @@ -115,7 +116,6 @@ "test/e2e/live/sessions-agents-cli.test.ts": [19,28,20,31,0], "test/e2e/live/skill-agent.test.ts": [7,9,8,10,0], "test/e2e/live/snapshot-commands.test.ts": [5,5,5,5,0], - "test/e2e/live/spark-express-vllm.test.ts": [35,45,46,64,3], "test/e2e/live/spark-install.test.ts": [11,13,11,15,6], "test/e2e/live/state-backup-restore.test.ts": [1,5,1,5,0], "test/e2e/live/telegram-injection.test.ts": [19,28,26,67,12], diff --git a/install.sh b/install.sh index 627c21bf357..c255f86dc3a 100755 --- a/install.sh +++ b/install.sh @@ -307,6 +307,7 @@ bootstrap_usage() { printf " curl -fsSL https://www.nvidia.com/nemoclaw.sh | bash -s -- [options]\n\n" printf " Options:\n" printf " --non-interactive Skip prompts (uses env vars / defaults)\n" + printf " --express-install Select Station Express for CI qualification (requires software acceptance)\n" printf " --station-deepseek Use DeepSeek V4 Flash for DGX Station express install\n" printf " --yes-i-accept-third-party-software Accept the third-party software notice without prompting\n" printf " --defer-onboarding Install NemoClaw without onboarding for a supported agent when NVIDIA inference credentials are absent\n" diff --git a/scripts/install.sh b/scripts/install.sh index 84b68927e9d..bd9b4959ef7 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1085,6 +1085,7 @@ usage() { printf " curl -fsSL https://www.nvidia.com/nemoclaw.sh | bash -s -- [options]\n\n" printf " ${C_DIM}Options:${C_RESET}\n" printf " --non-interactive Skip prompts (uses env vars / defaults)\n" + printf " --express-install Select Station Express for CI qualification (requires software acceptance)\n" printf " --yes-i-accept-third-party-software Accept the third-party software notice without prompting\n" printf " --defer-onboarding Install NemoClaw without onboarding for a supported agent when NVIDIA inference credentials are absent\n" printf " Use only with NEMOCLAW_AGENT=hermes or langchain-deepagents-code, no registered sandboxes, no local model profile,\n" @@ -6045,6 +6046,26 @@ fail_force_station_terminal_required() { error "--force-station-install selects the DGX Station express prompt, which needs an interactive terminal. Re-run from a terminal (for a curl|bash pipe, /dev/tty must be available), or omit --force-station-install." } +validate_noninteractive_express_install() { + [ "${EXPRESS_INSTALL:-}" = "1" ] || return 0 + [ "$1" = "DGX Station" ] \ + || error "--express-install requires a supported DGX Station (detected: ${1:-unsupported platform})." + [ "${ACCEPT_THIRD_PARTY_SOFTWARE:-${NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE:-}}" = "1" ] \ + || error "--express-install requires --yes-i-accept-third-party-software or NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE=1." + if [ "${STATION_DEEPSEEK:-}" = "1" ] || [ "${FORCE_STATION_INSTALL:-}" = "1" ]; then + error "--express-install cannot be combined with the interactive --station-deepseek or --force-station-install flags." + fi + [ "${DEFER_ONBOARDING:-}" != "1" ] \ + || error "--express-install cannot be combined with --defer-onboarding." + [ "${NEMOCLAW_NO_EXPRESS:-}" != "1" ] \ + || error "--express-install cannot be combined with NEMOCLAW_NO_EXPRESS=1 or a local model profile." + [ -z "${NEMOCLAW_PROVIDER:-}" ] \ + || error "--express-install selects its provider; remove NEMOCLAW_PROVIDER." + [ -z "${NEMOCLAW_NON_INTERACTIVE_SUDO_MODE:-}" ] \ + || error "--express-install cannot enable sudo prompts; unset NEMOCLAW_NON_INTERACTIVE_SUDO_MODE." + _STATION_INSTALL_MODE="express" +} + validate_force_station_install_override() { local platform="$1" release_state if [ "${FORCE_STATION_INSTALL:-}" != "1" ]; then @@ -6134,6 +6155,7 @@ preflight_explicit_express_flags() { _PREFLIGHT_EXPRESS_PLATFORM="$(detect_express_platform)" \ || error "Cannot classify NVIDIA platform identity. Refusing to continue installation." validate_express_platform_boundary "$_PREFLIGHT_EXPRESS_PLATFORM" + validate_noninteractive_express_install "$_PREFLIGHT_EXPRESS_PLATFORM" validate_force_station_install_override "$_PREFLIGHT_EXPRESS_PLATFORM" validate_station_deepseek_override "$_PREFLIGHT_EXPRESS_PLATFORM" } @@ -6714,7 +6736,9 @@ activate_express_install() { fi NON_INTERACTIVE=1 export NEMOCLAW_NON_INTERACTIVE=1 - export NEMOCLAW_NON_INTERACTIVE_SUDO_MODE=prompt + if [ "${EXPRESS_INSTALL:-}" != "1" ]; then + export NEMOCLAW_NON_INTERACTIVE_SUDO_MODE=prompt + fi export NEMOCLAW_YES=1 export NEMOCLAW_POLICY_MODE=suggested unset NEMOCLAW_STATION_EXPRESS @@ -6783,7 +6807,13 @@ run_station_host_preparation() { if [ "${FORCE_STATION_INSTALL:-}" = "1" ]; then helper_args+=(--force-station-install) fi - bash "$helper" "${helper_args[@]}" 2>&1 | filter_station_host_preparation_output + if [ "${EXPRESS_INSTALL:-}" = "1" ]; then + sudo -n true >/dev/null 2>&1 \ + || error "--express-install requires non-interactive sudo for Station host preparation. Ask the host operator to prepare the required access." + NEMOCLAW_STATION_PREP_SUDO_NONINTERACTIVE=1 bash "$helper" "${helper_args[@]}" 2>&1 | filter_station_host_preparation_output + else + bash "$helper" "${helper_args[@]}" 2>&1 | filter_station_host_preparation_output + fi } filter_station_host_preparation_output() { @@ -7180,10 +7210,6 @@ prepare_installer_host() { ensure_openshell_build_deps } -# Prompt the user to opt into express install on qualified platforms or the -# Deferred N1x preview. Sets non-interactive + provider/model env vars when accepted. Skipped when -# the user already passed --non-interactive, set NEMOCLAW_PROVIDER, or has -# no TTY. describe_express_install() { local platform="$1" local inference_summary="" @@ -7331,6 +7357,7 @@ maybe_offer_express_install() { platform="$(detect_express_platform)" \ || error "Cannot classify NVIDIA platform identity. Refusing to continue installation." validate_express_platform_boundary "$platform" + validate_noninteractive_express_install "$platform" validate_force_station_install_override "$platform" validate_station_deepseek_override "$platform" @@ -7402,6 +7429,11 @@ maybe_offer_express_install() { resume_loaded_station_install "$platform" return 0 fi + if [ "${EXPRESS_INSTALL:-}" = "1" ]; then + activate_express_install "$platform" + info "Using express install for ${platform}." + return 0 + fi if [ "${NON_INTERACTIVE:-}" = "1" ]; then info "Detected ${platform}. Skipping express prompt (--non-interactive set)." return 0 @@ -7541,6 +7573,7 @@ main() { FORCE_FRESH_INSTALL="" STATION_DEEPSEEK="" FORCE_STATION_INSTALL="" + EXPRESS_INSTALL="" LOCAL_MODEL_RUNTIME="" EXPERIMENTAL_PROFILE="${NEMOCLAW_EXPERIMENTAL_PROFILE:-}" local expect_experimental_profile="" @@ -7551,6 +7584,11 @@ main() { continue fi case "$arg" in + --express-install) + EXPRESS_INSTALL=1 + NON_INTERACTIVE=1 + NON_INTERACTIVE_SOURCE="the --express-install flag" + ;; --non-interactive) NON_INTERACTIVE=1 NON_INTERACTIVE_SOURCE="the --non-interactive flag" diff --git a/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts b/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts index 39e3080ccd1..ff56137b5f7 100644 --- a/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-proxy-launcher.test.ts @@ -710,8 +710,12 @@ describe.concurrent("Deep Agents Code direct-exec proxy launcher", () => { expect(headlessCheck).toContain("getent hosts inference.local >/dev/null 2>&1"); expect(headlessCheck).toContain("direct inference.local DNS/hosts is absent"); expect(headlessCheck).toContain('stat -c "%u:%a"'); - expect(headlessCheck).toContain("direct-exec dcode -n reached managed inference"); - expect(headlessCheck).toContain("connect --probe-only accepted the managed inference route"); + expect(headlessCheck).toContain( + "direct-exec dcode -n reached ${route_contract:-unknown} inference", + ); + expect(headlessCheck).toContain( + "connect --probe-only accepted the ${route_contract:-unknown} inference route", + ); }); it.each([ diff --git a/test/e2e/README.md b/test/e2e/README.md index 03dcaf23f8d..8d57f53f871 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1707,8 +1707,10 @@ its existing platform-specific qualification. ### DGX Spark Express vLLM -`spark-express-vllm.test.ts` is a physical-host qualification for the second DGX Spark Express inference option, the catalog-backed fixed vLLM profile. -It requires a qualified NVIDIA DGX Spark with Docker, NVIDIA Container Toolkit, OpenShell prerequisites, enough storage for the pinned image and model, and no unrelated `nemoclaw-vllm` container. +`dgx-express.test.ts` contains separate physical-host cases for Spark and Station Express. +The Spark case qualifies the second DGX Spark Express inference option, the catalog-backed fixed vLLM profile. +The canonical runner requires an explicit selector matching `E2E_TARGET_ID`; it rejects missing, unknown, or mismatched selections before starting Vitest. +The Spark case requires a qualified NVIDIA DGX Spark with Docker, NVIDIA Container Toolkit, OpenShell prerequisites, enough storage for the pinned image and model, and no unrelated `nemoclaw-vllm` container. The target accepts only a local Docker socket and the default Docker context, rejects remote selectors, and treats Docker inspection errors as preflight failures instead of absent resources. The target sources `scripts/install.sh` from the candidate checkout, calls the Express option-selection functions with option 2, and invokes the candidate CLI directly for onboarding. It does not run the hosted installer bootstrap, clone or ref selection, dependency installation, CLI exposure, or the real terminal prompt. @@ -1721,12 +1723,7 @@ The standard E2E artifacts retain bounded command output. Run the target from a clean candidate checkout on the Spark host: ```bash -E2E_JOB=1 \ -E2E_TARGET_ID=spark-express-vllm \ -NEMOCLAW_RUN_LIVE_E2E=1 \ -NEMOCLAW_SANDBOX_NAME=e2e-spark-vllm \ -npx tsx tools/e2e/live-vitest-invocation.mts run \ - --test-path test/e2e/live/spark-express-vllm.test.ts +E2E_JOB=1 E2E_TARGET_ID=spark-express-vllm NEMOCLAW_RUN_LIVE_E2E=1 NEMOCLAW_SANDBOX_NAME=e2e-spark-vllm npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/dgx-express.test.ts --selector '^spark-express-vllm:' ``` A passing target establishes that the source-checkout option-2 path selects the fixed vLLM preset and recipe, the managed container carries catalog provenance and the catalog-derived serve command, `inference.local` completes a chat request, and unrelated sandbox egress receives an HTTP `403` response. @@ -2078,3 +2075,7 @@ These assertions run inside the existing `full-e2e` lifecycle instead of a second standalone onboarding run. This keeps the measurement on the job's first sandbox build, avoids warming Docker layers before a duplicate performance test, and makes `full-e2e` the source of truth for the hard cold-path contract. + +## DGX Station Express + +The explicit `dgx-station-express` target runs the local Station Express installer with cached Ultra weights, checks routed sandbox inference, and uninstalls the job runtime. See [Station dispatch](docs/dgx-station-dispatch.md) for prerequisites, workflow selection, and evidence boundaries. diff --git a/test/e2e/docs/dgx-station-dispatch.md b/test/e2e/docs/dgx-station-dispatch.md new file mode 100644 index 00000000000..874d4f332df --- /dev/null +++ b/test/e2e/docs/dgx-station-dispatch.md @@ -0,0 +1,32 @@ + + + +# DGX Station Express dispatch + +Before dispatching a candidate that uses the shared entrypoint, deploy the matching Station backend update. Select a candidate that contains `test/e2e/live/dgx-express.test.ts`. + +Select `dgx-station-express` by itself in the `jobs` or `targets` input of the E2E workflow. The target is excluded from default runs. Its GitHub-hosted controller runs from the trusted main workflow and sends the candidate commit and selected managed-image publication revision to the operator's Station receiver. + +The backend selects only the Station case in `test/e2e/live/dgx-express.test.ts` with `E2E_TARGET_ID=dgx-station-express` and `--selector '^dgx-station-express:'`. The Spark case has its own selector. + +Configure the GitHub repository variable `DGX_STATION_DISPATCH_URL` with the receiver's HTTPS origin. Station uses its own queue, OIDC audience, receipt, and artifact namespace. The controller does not use `JETSON_DISPATCH_URL`. + +The receiver uses the configured runner account’s normal HOME so its systemd user manager can discover the gateway service. It requires this account’s NemoClaw installation state to be clean between runs. The receiver needs a dedicated Station with prepared host prerequisites, a cached Nemotron 3 Ultra 550B model, and the vLLM image selected by the candidate recipe. Each job uses `/tmp/ncs/` for temporary files so `tsx` IPC socket paths fit the Linux pathname limit. + +## Select Express for CI Qualification + +Use `--express-install` for the maintainer-operated Station CI smoke. Prepare non-interactive sudo access for the configured runner account before dispatch. The smoke runs the local candidate installer: + +```bash +NEMOCLAW_REPO_ROOT="$(pwd)" bash install.sh --express-install --yes-i-accept-third-party-software +``` + +`--express-install` selects the existing Station Express recipe without its selection prompt. Station qualification and explicit software acceptance remain required. It rejects conflicting provider, profile, deferred-onboarding, and interactive Station options. Ordinary non-interactive installation retains its existing selection behavior. + +The smoke checks the ready sandbox, running managed vLLM with the Ultra serving alias, the independently selected managed-image revision, and an assistant response through `inference.local`. Cleanup attempts to retire installation state left after success or failure. Cleanup uses a fresh signal through the E2E cleanup registry. + +Timing evidence records completed smoke phases. Total duration spans installer start through smoke cleanup. Readiness and assertion durations can be absent after failure. vLLM startup remains inside installation. The cache check compares paths, file sizes, and symlink targets. The smoke also checks that the vLLM image remains after uninstall. + +Qualify an untouched baseline and the local candidate before drawing performance conclusions. The new controller must be available on the trusted main workflow before a GitHub run can execute it. An unmerged candidate selection does not replace the controller source. Keep local hardware evidence separate from proof of the full GitHub dispatch path. + +If installation state remains, CI cleanup validates any available sandbox registry and invokes the product uninstaller. The shared helper then handles an orphaned OpenClaw state volume when it was absent from the pre-install inventory, has the expected ownership labels and local driver without driver options, and is not attached to a container. It rejects unexpected volume changes and checks the final inventory against the baseline. An uninstall failure stops before volume cleanup. The helper does not rewrite session or registry state to make uninstall proceed. This does not establish that the standalone product uninstaller removes every agent state volume. diff --git a/test/e2e/live/spark-express-vllm.test.ts b/test/e2e/live/dgx-express.test.ts similarity index 91% rename from test/e2e/live/spark-express-vllm.test.ts rename to test/e2e/live/dgx-express.test.ts index 137d2e0c997..2731b318c8f 100644 --- a/test/e2e/live/spark-express-vllm.test.ts +++ b/test/e2e/live/dgx-express.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -/** Exercises the catalog-backed DGX Spark Express vLLM path on physical hardware. */ +/** Exercises the DGX Spark and Station Express vLLM paths on physical hardware. */ import assert from "node:assert/strict"; @@ -21,6 +21,7 @@ import type { HostCliClient } from "../fixtures/clients/host.ts"; import { trustedSandboxShellScript, validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; +import { runStationExpressSmoke, STATION_SMOKE_PHASES } from "../support/dgx-station-express.ts"; import { assertLocalDockerEnvironment, classifyDockerContainerInspection, @@ -215,7 +216,7 @@ async function removeExactVllmContainer( } test( - "DGX Spark Express option 2 materializes the fixed vLLM profile and routes sandbox inference", + "spark-express-vllm: DGX Spark Express option 2 materializes the fixed vLLM profile and routes sandbox inference", { timeout: TEST_TIMEOUT_MS, meta: { @@ -418,3 +419,36 @@ test( expect(denied.stdout.trim()).toBe("56 403"); }, ); + +test( + "dgx-station-express: Station Express installs cached Ultra vLLM and NemoClaw, routes inference, and cleans up runtime", + { + timeout: 48 * 60_000, + meta: { e2ePhases: STATION_SMOKE_PHASES, e2eCleanupTimeoutMs: 6 * 60_000 }, + }, + async ({ host, sandbox, artifacts, progress, cleanup }) => { + await artifacts.target.declare({ + id: "dgx-station-express", + contract: [ + "local candidate Express installation", + "default Ultra model and routed inference", + "runtime cleanup with unchanged model-cache metadata and retained vLLM image", + ], + }); + await runStationExpressSmoke({ + host, + sandbox, + cleanup, + environment: process.env, + repoRoot: REPO_ROOT, + phases: { + inspect: () => progress.phase("inspect the prepared Station"), + install: () => progress.phase("install Station Express from the candidate checkout"), + assert: () => progress.phase("assert managed Ultra and routed inference"), + cleanup: () => progress.phase("clean up the job runtime"), + }, + writeEvidence: (name, value) => artifacts.writeJson(name, value), + }); + await artifacts.target.complete({ id: "dgx-station-express" }); + }, +); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 8c6a1ae603e..4161333f776 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -969,8 +969,11 @@ ] }, { - "live": "test/e2e/live/spark-express-vllm.test.ts", + "live": "test/e2e/live/dgx-express.test.ts", "fast": [ + "test/e2e/support/dgx-station-express.test.ts", + "test/e2e/support/live-vitest-invocation.test.ts", + "test/installer-integration/install-express-noninteractive.test.ts", "src/lib/inference/serving/catalog.test.ts", "src/lib/inference/serving/host-local-vllm-selection.test.ts", "src/lib/inference/vllm-models.test.ts", diff --git a/test/e2e/support/dgx-station-dispatch.test.ts b/test/e2e/support/dgx-station-dispatch.test.ts new file mode 100644 index 00000000000..cc3fc9c3ff5 --- /dev/null +++ b/test/e2e/support/dgx-station-dispatch.test.ts @@ -0,0 +1,208 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { dgxStationDispatchRequestFromEnvironment } from "../../../tools/e2e/dgx-station-dispatch-client.mts"; +import { + createGitHubOidcTokenProvider, + dispatcherBaseUrl, + pollJetsonDispatch, + dispatcherRequest, + runDispatchClient, + printableDispatchError, + submitJetsonDispatch, +} from "../../../tools/e2e/jetson-dispatch-client.mts"; +import { + DGX_STATION_DISPATCH_AUDIENCE, + dispatchJobId, + parseDgxStationDispatchRequest, + parseDispatchArtifact, + parseDispatchStatus, + parseDispatchStatusResponse, + parseJetsonDispatchArtifact, + parseJetsonDispatchRequest, + parseJetsonDispatchStatus, +} from "../../../tools/e2e/jetson-dispatch-contract.mts"; + +const vectorBytes = fs.readFileSync( + path.join(process.cwd(), "tools/e2e/contracts/v3/dgx-station-dispatch.json"), +); +const vectors = JSON.parse(vectorBytes.toString("utf8")); +const request = parseDgxStationDispatchRequest(vectors.request); +const queued = parseDispatchStatusResponse(vectors.queuedResponse, request); +const directories: string[] = []; +function artifactDirectory(): string { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "station-dispatch-")); + directories.push(directory); + return directory; +} +afterEach(() => { + vi.restoreAllMocks(); + for (const directory of directories.splice(0)) + fs.rmSync(directory, { recursive: true, force: true }); +}); + +describe("Station dispatch contract and controller", () => { + it("matches the pinned backend v3 compatibility bytes", () => { + expect(createHash("sha256").update(vectorBytes).digest("hex")).toBe( + "61c566d20543812a8d55bbc130252c30786023ce521f459ef736190883d4aa85", + ); + expect(request).toEqual(vectors.request); + expect(queued).toEqual(vectors.queuedResponse.job); + expect(parseDispatchStatus(vectors.completedStatus)).toEqual(vectors.completedStatus); + expect(parseDispatchArtifact(vectors.artifact, queued.jobId)).toEqual(vectors.artifact); + }); + + it.each(vectors.invalidRequests as { name: string; value: unknown }[])( + "rejects $name", + ({ value }) => { + expect(() => parseDgxStationDispatchRequest(value)).toThrow(); + }, + ); + + it("keeps Station evidence outside the Jetson-only parsers", () => { + expect(() => parseJetsonDispatchRequest(vectors.request)).toThrow(); + expect(() => parseJetsonDispatchStatus(vectors.completedStatus)).toThrow(); + expect(() => parseJetsonDispatchArtifact(vectors.artifact, queued.jobId)).toThrow(); + }); + + it("binds candidate and managed-image revisions independently into the job identity", () => { + expect(dispatchJobId(request)).toBe(queued.jobId); + expect(dispatchJobId({ ...request, candidateSha: "c".repeat(40) })).not.toBe(queued.jobId); + expect(dispatchJobId({ ...request, managedImageRevision: "c".repeat(40) })).not.toBe( + queued.jobId, + ); + }); + + it("constructs Station requests without reading the Jetson candidate settings", () => { + expect( + dgxStationDispatchRequestFromEnvironment({ + DGX_STATION_DISPATCH_CANDIDATE_SHA: request.candidateSha, + DGX_STATION_DISPATCH_MANAGED_IMAGE_REVISION: request.managedImageRevision, + JETSON_DISPATCH_CANDIDATE_SHA: "c".repeat(40), + JETSON_DISPATCH_MANAGED_IMAGE_REVISION: "d".repeat(40), + GITHUB_RUN_ID: request.workflowRunId, + GITHUB_RUN_ATTEMPT: String(request.workflowRunAttempt), + }), + ).toEqual(request); + expect(() => + dgxStationDispatchRequestFromEnvironment({ + JETSON_DISPATCH_CANDIDATE_SHA: request.candidateSha, + }), + ).toThrow(); + expect(() => dispatcherBaseUrl(undefined, "DGX_STATION_DISPATCH_URL")).toThrow( + "DGX_STATION_DISPATCH_URL is required", + ); + }); + + it("requests and caches tokens for the Station audience", async () => { + const fetchImpl = vi.fn(async () => Response.json({ value: "station-token" })); + const provider = createGitHubOidcTokenProvider({ + fetchImpl, + audience: DGX_STATION_DISPATCH_AUDIENCE, + }); + const environment = { + ACTIONS_ID_TOKEN_REQUEST_URL: "https://example.test/token", + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "request-token", + }; + expect(await provider(environment)).toBe("station-token"); + expect(await provider(environment)).toBe("station-token"); + expect(fetchImpl).toHaveBeenCalledTimes(1); + expect(String(fetchImpl.mock.calls[0]?.[0])).toContain( + "audience=nemoclaw-dgx-station-dispatch", + ); + }); + + it("writes the recovery receipt before submission and cancels an unknown outcome", async () => { + const receiptFile = path.join(artifactDirectory(), "station.json"); + const transport = vi + .fn() + .mockImplementationOnce(async () => { + expect(JSON.parse(fs.readFileSync(receiptFile, "utf8"))).toMatchObject({ + jobId: queued.jobId, + request, + }); + throw new Error("connection lost"); + }) + .mockResolvedValueOnce({ job: queued }); + await expect( + submitJetsonDispatch({ + baseUrl: new URL("https://example.test"), + dispatchRequest: request, + receiptFile, + request: transport, + }), + ).rejects.toThrow("submission outcome was not confirmed"); + expect(transport.mock.calls.map(([options]) => options.method)).toEqual(["POST", "DELETE"]); + }); + + it("cancels the same Station job when its controller deadline expires", async () => { + const receiptFile = path.join(artifactDirectory(), "station.json"); + const transport = vi.fn(async () => ({ job: queued })); + await expect( + pollJetsonDispatch({ + baseUrl: new URL("https://example.test"), + initialStatus: queued, + deadlineMs: 1, + now: () => 2, + receiptFile, + request: transport, + }), + ).rejects.toThrow("controller deadline"); + expect(transport).toHaveBeenCalledWith( + expect.objectContaining({ method: "DELETE", path: `v1/jobs/${queued.jobId}` }), + ); + }); + + it("requires Station device identity and rejects terminal controls in human-readable identity", () => { + expect(() => parseDispatchStatus({ ...vectors.completedStatus, device: undefined })).toThrow( + "device identity", + ); + expect(() => + parseDispatchStatus({ + ...vectors.completedStatus, + device: { ...vectors.completedStatus.device, model: "Station\u001b[2J" }, + }), + ).toThrow("Station device model is invalid"); + expect(() => + parseDispatchStatus({ + ...vectors.completedStatus, + device: { ...vectors.completedStatus.device, osRelease: "Ubuntu\u009b2J" }, + }), + ).toThrow("Station device osRelease is invalid"); + }); + + it("saves Station artifacts and removes its cancellation listeners after completion", async () => { + const directory = artifactDirectory(); + const before = [process.listenerCount("SIGINT"), process.listenerCount("SIGTERM")]; + const transport = vi.fn(async (options: Parameters[0]) => + options.path.endsWith("/artifact") ? vectors.artifact : { job: vectors.completedStatus }, + ); + await runDispatchClient({ + request, + baseUrl: new URL("https://example.test"), + artifactDirectory: directory, + receiptName: "station.json", + archiveName: "station.tar.gz", + requestImpl: transport, + }); + expect(fs.readFileSync(path.join(directory, "station.tar.gz"))).toEqual( + Buffer.from(vectors.artifact.artifactArchiveBase64, "base64"), + ); + expect(JSON.parse(fs.readFileSync(path.join(directory, "station.json"), "utf8"))).toMatchObject( + { status: { request, conclusion: "success" } }, + ); + expect([process.listenerCount("SIGINT"), process.listenerCount("SIGTERM")]).toEqual(before); + }); +}); + +it("removes terminal controls from a dispatcher error before printing it", () => { + expect(printableDispatchError(new Error("remote\u001b[2J\u009b31m\nmessage"))).toBe( + "remote [2J 31m message", + ); + expect(printableDispatchError(new Error("x".repeat(2000)))).toHaveLength(1000); +}); diff --git a/test/e2e/support/dgx-station-express.test.ts b/test/e2e/support/dgx-station-express.test.ts new file mode 100644 index 00000000000..e3f48f28649 --- /dev/null +++ b/test/e2e/support/dgx-station-express.test.ts @@ -0,0 +1,861 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { spawnSync } from "node:child_process"; +import { + cleanupStationRuntime, + createStationCleanupCommand, + STATION_STATE_VOLUME, + STATION_SANDBOX, +} from "../../../tools/e2e/dgx-station-cleanup.mts"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ArtifactSink } from "../fixtures/artifacts.ts"; +import { startTestProgress } from "../fixtures/progress.ts"; +import { CleanupRegistry } from "../fixtures/cleanup.ts"; +import { ShellProbe, trustedShellCommand } from "../fixtures/shell-probe.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import { + stationVllmCommands, + assertStationWorkload, + assertStationInference, + assertStationReady, + assertStationVllm, + runStationExpressSmoke, + stationModelCacheMetadata, + stationSmokeEnvironment, + STATION_SMOKE_MODEL, + STATION_SMOKE_SANDBOX, +} from "./dgx-station-express.ts"; + +const workspace = `/var/tmp/nemoclaw-station-e2e/${"a".repeat(64)}`; +const base = { + HOME: "/home/station-runner", + NEMOCLAW_STATION_RUNNER_HOME: "/home/station-runner", + NEMOCLAW_STATION_WORKSPACE: workspace, + E2E_MANAGED_IMAGE_REVISION: "b".repeat(40), +}; +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) + fs.rmSync(directory, { recursive: true, force: true }); +}); + +describe("Station Express smoke boundaries", () => { + it("keeps model selection in the Express installer and isolates the job environment", () => { + const env = stationSmokeEnvironment( + { + ...base, + NEMOCLAW_PROVIDER: "custom", + NEMOCLAW_VLLM_MODEL: "smaller-model", + NEMOCLAW_MODEL: "untrusted", + NEMOCLAW_DGX_STATION_PEER: "someone@elsewhere", + DOCKER_HOST: "tcp://elsewhere", + }, + "/candidate", + ); + expect(env).toMatchObject({ + NEMOCLAW_REPO_ROOT: "/candidate", + HOME: "/home/station-runner", + NEMOCLAW_PROVIDER: "", + NEMOCLAW_VLLM_MODEL: "", + NEMOCLAW_MODEL: "", + NEMOCLAW_DGX_STATION_PEER: "", + DOCKER_CONTEXT: "default", + DOCKER_HOST: "", + E2E_MANAGED_IMAGE_REVISION: base.E2E_MANAGED_IMAGE_REVISION, + npm_config_prefix: `${workspace}/npm-prefix`, + TMPDIR: `/tmp/ncs/${"a".repeat(64)}`, + }); + }); + + it.each([ + { HOME: "/home/operator" }, + { NEMOCLAW_STATION_WORKSPACE: "/var/tmp/../home/operator" }, + { E2E_MANAGED_IMAGE_REVISION: "main" }, + ])("refuses unsafe job scope %j", (override) => { + expect(() => stationSmokeEnvironment({ ...base, ...override }, "/candidate")).toThrow(); + }); + + const container = { + Image: `sha256:${"c".repeat(64)}`, + State: { Running: true }, + Config: { + Labels: { "com.nvidia.nemoclaw.managed-vllm": "true" }, + Entrypoint: ["/bin/bash"], + Cmd: ["-lc", stationVllmCommands()[0]], + }, + }; + it.each([0, 1])("pins the default Ultra serving alias in Station command %i", (index) => { + expect(stationVllmCommands()[index]).toMatch( + /(?:^|\s)--served-model-name nvidia\/nemotron-3-ultra-550b-a55b(?:\s|$)/u, + ); + }); + + it.each([ + [0, ""], + [1, ""], + [0, "--served-model-name another/model"], + [1, "--served-model-name another/model"], + ] as const)( + "rejects a missing or changed alias in Station command %i: %j", + (index, replacement) => { + const changed = stationVllmCommands()[index]!.replace( + "--served-model-name nvidia/nemotron-3-ultra-550b-a55b", + replacement, + ); + expect(() => + assertStationVllm( + JSON.stringify([ + { ...container, Config: { ...container.Config, Cmd: ["-lc", changed] } }, + ]), + ), + ).toThrow("default Ultra"); + }, + ); + + it("requires managed vLLM to run the default Ultra serving alias", () => { + expect(assertStationVllm(JSON.stringify([container]))).toBe(container.Image); + expect(() => + assertStationVllm(JSON.stringify([{ ...container, State: { Running: false } }])), + ).toThrow("must be running"); + expect(() => + assertStationVllm( + JSON.stringify([ + { ...container, Config: { ...container.Config, Cmd: ["serve", "another-model"] } }, + ]), + ), + ).toThrow("default Ultra"); + expect(() => + assertStationVllm( + JSON.stringify([{ ...container, Config: { ...container.Config, Labels: {} } }]), + ), + ).toThrow("must be running"); + }); + + const ready = { + id: "11111111-1111-4111-8111-111111111111", + name: STATION_SMOKE_SANDBOX, + labels: {}, + resource_version: 1, + created_at: "2026-09-01T00:00:00Z", + phase: "Ready", + current_policy_version: 1, + }; + it("requires an observed ready sandbox with the expected identity", () => { + expect(() => assertStationReady(JSON.stringify([ready]))).not.toThrow(); + expect(() => assertStationReady(JSON.stringify([{ ...ready, phase: "Creating" }]))).toThrow( + "ready sandbox", + ); + expect(() => assertStationReady(JSON.stringify([{ ...ready, name: "unrelated" }]))).toThrow( + "ready sandbox", + ); + expect(() => assertStationReady("[]")).toThrow("ready sandbox"); + expect(() => assertStationReady(JSON.stringify([ready, ready]))).toThrow("ready sandbox"); + }); + + it.each([ + { model: "other-model", choices: [{ message: { content: "PONG" } }] }, + { model: STATION_SMOKE_MODEL, choices: [{ message: { content: "" } }] }, + { model: STATION_SMOKE_MODEL, choices: [] }, + { error: "unavailable" }, + ])("rejects incomplete or wrongly routed inference %j", (response) => { + expect(() => assertStationInference(JSON.stringify(response))).toThrow(); + }); + + it("accepts non-empty content in an Ultra response payload", () => { + expect(() => + assertStationInference( + JSON.stringify({ model: STATION_SMOKE_MODEL, choices: [{ message: { content: "PONG" } }] }), + ), + ).not.toThrow(); + }); + + it("observes cache names, sizes, and symlink targets without writing to the cache", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "station-cache-")); + directories.push(home); + const model = path.join( + home, + ".cache/huggingface/hub/models--nvidia--NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4", + ); + fs.mkdirSync(path.join(model, "blobs"), { recursive: true }); + fs.mkdirSync(path.join(model, "snapshots")); + fs.writeFileSync(path.join(model, "blobs", "a"), "weights"); + fs.symlinkSync("../blobs/a", path.join(model, "snapshots", "weights")); + const original = stationModelCacheMetadata(home); + expect(stationModelCacheMetadata(home)).toEqual(original); + fs.appendFileSync(path.join(model, "blobs", "a"), "changed"); + expect(stationModelCacheMetadata(home).sha256).not.toBe(original.sha256); + fs.writeFileSync(path.join(model, "blobs", "a"), "weights"); + fs.unlinkSync(path.join(model, "snapshots", "weights")); + fs.symlinkSync("../blobs/b", path.join(model, "snapshots", "weights")); + expect(stationModelCacheMetadata(home).sha256).not.toBe(original.sha256); + }); + + it.each([ + { + name: "accepts zero-exit commands that finish before their deadline", + timeoutAt: "none", + expectedFailure: null, + inferenceCalls: 1, + }, + { + name: "rejects a timed-out host command even when it exits zero and still cleans up", + timeoutAt: "host", + expectedFailure: "station-express-install failed; inspect its command artifact", + inferenceCalls: 0, + }, + { + name: "rejects timed-out routed inference even when it exits zero with valid content", + timeoutAt: "inference", + expectedFailure: "Station sandbox inference request failed; inspect its artifact", + inferenceCalls: 1, + }, + ])("$name", async ({ timeoutAt, expectedFailure, inferenceCalls }) => { + const home = cleanupHome(); + const normal = await stationProbeOutcome(home, false); + expect(normal).toMatchObject({ exitCode: 0, timedOut: false }); + const observed = timeoutAt === "none" ? normal : await stationProbeOutcome(home, true); + expect(observed).toMatchObject({ exitCode: 0, timedOut: timeoutAt !== "none" }); + const state = path.join(home, ".nemoclaw"); + const effects: Record void> = { + "station-express-install": () => { + fs.mkdirSync(state); + fs.writeFileSync( + path.join(state, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + [STATION_SMOKE_SANDBOX]: { + agent: "openclaw", + workload: { + kind: "managed-image", + sourceRevision: base.E2E_MANAGED_IMAGE_REVISION, + }, + }, + }, + }), + ); + }, + "station-express-uninstall": () => fs.rmSync(state, { recursive: true }), + }; + const outputs: Record = { + "station-platform": "DGX Station\n", + "station-initial-images": `${container.Image}\n`, + "station-sandbox-ready": JSON.stringify([ready]), + "station-managed-vllm": JSON.stringify([container]), + }; + const command = vi.fn(async (_executable, _args, options) => { + const label = options?.artifactName ?? ""; + effects[label]?.(); + const result = + label === "station-express-install" && timeoutAt === "host" ? observed : normal; + return { ...result, stdout: outputs[label] ?? "" }; + }); + const exec = vi + .fn() + .mockResolvedValue(timeoutAt === "inference" ? observed : normal); + const cleanup = new CleanupRegistry(); + const writeEvidence = vi.fn(async () => {}); + const result = runStationExpressSmoke({ + host: { command }, + sandbox: { exec }, + cleanup, + environment: { ...base, HOME: home, NEMOCLAW_STATION_RUNNER_HOME: home }, + repoRoot: "/candidate", + phases: { inspect: vi.fn(), install: vi.fn(), assert: vi.fn(), cleanup: vi.fn() }, + writeEvidence, + modelCacheMetadata: () => ({ sha256: "unchanged", entries: 1 }), + }); + await expect( + result.then( + () => null, + (error: Error) => error.message, + ), + ).resolves.toBe(expectedFailure); + expect(exec).toHaveBeenCalledTimes(inferenceCalls); + expect(command).toHaveBeenCalledWith( + "bash", + ["uninstall.sh", "--yes", "--destroy-user-data"], + expect.anything(), + ); + expect(writeEvidence).toHaveBeenCalledWith("station-cleanup.json", { + passed: ["clean up Station job runtime"], + failures: [], + }); + expect(fs.existsSync(state)).toBe(false); + }); + + it("uninstalls after installer failure and records installer and cleanup durations", async () => { + const home = cleanupHome(); + let time = 0; + const controller = new AbortController(); + const cleanup = new CleanupRegistry((value) => value, undefined, { + testSignal: controller.signal, + }); + const empty = { stdout: "", stderr: "", exitCode: 0 } as Awaited< + ReturnType + >; + const command = vi + .fn() + .mockResolvedValueOnce({ ...empty, stdout: "DGX Station\n" }) + .mockResolvedValueOnce(empty) + .mockResolvedValueOnce(empty) + .mockResolvedValueOnce(empty) + .mockImplementationOnce(async () => { + time += 5000; + fs.mkdirSync(path.join(home, ".nemoclaw")); + controller.abort(); + return { ...empty, exitCode: 1 }; + }) + .mockImplementationOnce(async () => { + expect(cleanup.currentSignal().aborted).toBe(false); + time += 1000; + return empty; + }) + .mockResolvedValue(empty); + const exec = vi.fn(); + const writeEvidence = vi.fn(async () => {}); + const phases = { inspect: vi.fn(), install: vi.fn(), assert: vi.fn(), cleanup: vi.fn() }; + await expect( + runStationExpressSmoke({ + cleanup, + host: { command }, + sandbox: { exec }, + environment: { ...base, HOME: home, NEMOCLAW_STATION_RUNNER_HOME: home }, + repoRoot: "/candidate", + phases, + writeEvidence, + now: () => time, + modelCacheMetadata: () => ({ sha256: "baseline", entries: 1 }), + }), + ).rejects.toThrow("station-express-install failed"); + expect(command).toHaveBeenCalledWith( + "bash", + ["install.sh", "--express-install", "--yes-i-accept-third-party-software"], + expect.objectContaining({ + cwd: "/candidate", + env: expect.objectContaining({ NEMOCLAW_REPO_ROOT: "/candidate" }), + }), + ); + expect(command).toHaveBeenCalledWith( + "bash", + ["uninstall.sh", "--yes", "--destroy-user-data"], + expect.anything(), + ); + expect(exec).not.toHaveBeenCalled(); + expect(phases.inspect).toHaveBeenCalledOnce(); + expect(phases.install).toHaveBeenCalledOnce(); + expect(phases.assert).not.toHaveBeenCalled(); + expect(phases.cleanup).toHaveBeenCalledOnce(); + expect(phases.inspect.mock.invocationCallOrder[0]).toBeLessThan( + phases.install.mock.invocationCallOrder[0]!, + ); + expect(phases.install.mock.invocationCallOrder[0]).toBeLessThan( + phases.cleanup.mock.invocationCallOrder[0]!, + ); + expect(writeEvidence).toHaveBeenCalledWith("station-express-timings.json", { + installMs: 5000, + cleanupMs: 1000, + totalMs: 6000, + cleanup: "succeeded", + }); + }); +}); + +it("requires the managed-image revision instead of substituting the candidate code revision", () => { + const expectedRevision = "b".repeat(40); + const registry = (revision: string) => ({ + sandboxes: { + [STATION_SMOKE_SANDBOX]: { workload: { kind: "managed-image", sourceRevision: revision } }, + }, + }); + expect(() => assertStationWorkload(registry(expectedRevision), expectedRevision)).not.toThrow(); + expect(() => assertStationWorkload(registry("a".repeat(40)), expectedRevision)).toThrow( + "independently selected", + ); + expect(() => assertStationWorkload({ sandboxes: {} }, expectedRevision)).toThrow(); +}); + +function cleanupHome() { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "station-cleanup-")); + directories.push(home); + return home; +} +async function stationProbeOutcome(home: string, timeOut: boolean) { + const progress = startTestProgress( + "Station timeout result", + ["observe the child result", "record the child outcome"], + { + logLine: () => {}, + }, + ); + progress.phase("observe the child result"); + const abort = new AbortController(); + let reportReady = () => {}; + const ready = new Promise((resolve) => { + reportReady = resolve; + }); + const probe = new ShellProbe({ + artifacts: new ArtifactSink(path.join(home, "probe-artifacts")), + progress, + redact: (value) => value, + signal: AbortSignal.any([abort.signal, AbortSignal.timeout(5000)]), + }); + const output = JSON.stringify({ + model: STATION_SMOKE_MODEL, + choices: [{ message: { content: "PONG" } }], + }); + const script = timeOut + ? 'process.on("SIGTERM", () => process.exit(0)); process.stdout.write(process.argv[1]); setInterval(() => {}, 1000);' + : "process.stdout.write(process.argv[1]);"; + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const pending = probe.run( + trustedShellCommand({ + command: process.execPath, + args: ["-e", script, output], + reason: "observe a real zero-exit child", + }), + { timeoutMs: 1000, killGraceMs: 1000, onOutput: () => reportReady() }, + ); + try { + await Promise.race([ + ready, + pending.then(() => { + throw new Error("The child exited before reporting readiness"); + }), + ]); + // Wait for the signal handler before firing the supervisor's actual deadline callback. + await (timeOut ? vi.advanceTimersByTimeAsync(1000) : pending); + const result = await pending; + progress.phase("record the child outcome"); + return result; + } finally { + abort.abort(); + await vi.advanceTimersByTimeAsync(1000); + await pending.catch(() => {}); + vi.useRealTimers(); + progress.stop(); + } +} + +const leftover = { + Name: STATION_STATE_VOLUME, + Driver: "local", + Scope: "local", + Options: null, + Labels: { + "io.nvidia.nemoclaw.openclaw-state.managed": "true", + "io.nvidia.nemoclaw.openclaw-state.schema": "1", + "io.nvidia.nemoclaw.openclaw-state.sandbox": STATION_SANDBOX, + "io.nvidia.nemoclaw.openclaw-state.target": "/sandbox/.openclaw", + }, +}; +const cleanupCommand = () => + vi.fn< + (label: string, executable: string, args: string[], timeoutMs?: number) => Promise + >(); + +describe("Station CI runtime cleanup", () => { + it("uninstalls the registered sandbox before checking the volume inventory", async () => { + const home = cleanupHome(); + fs.mkdirSync(path.join(home, ".nemoclaw")); + fs.writeFileSync( + path.join(home, ".nemoclaw/sandboxes.json"), + JSON.stringify({ + sandboxes: { + [STATION_SANDBOX]: { agent: "openclaw", workload: { kind: "managed-image" } }, + }, + }), + ); + const command = cleanupCommand() + .mockResolvedValueOnce("") + .mockResolvedValueOnce("keep\n") + .mockResolvedValueOnce("keep\n"); + await expect( + cleanupStationRuntime({ home, repoRoot: "/candidate", baselineVolumes: ["keep"], command }), + ).resolves.toEqual({ uninstalled: true, fallbackVolumes: [] }); + expect(command.mock.calls.map(([label]) => label)).toEqual([ + "station-express-uninstall", + "station-cleanup-volume-inventory", + "station-cleanup-volumes-restored", + ]); + expect(command).toHaveBeenNthCalledWith( + 1, + "station-express-uninstall", + "bash", + ["uninstall.sh", "--yes", "--destroy-user-data"], + 180_000, + ); + }); + + it("uninstalls remaining installation state when no sandbox row remains", async () => { + const home = cleanupHome(); + fs.mkdirSync(path.join(home, ".nemoclaw")); + fs.writeFileSync( + path.join(home, ".nemoclaw/sandboxes.json"), + JSON.stringify({ sandboxes: {} }), + ); + const command = cleanupCommand() + .mockResolvedValueOnce("") + .mockResolvedValueOnce("") + .mockResolvedValueOnce(""); + await expect( + cleanupStationRuntime({ home, repoRoot: "/candidate", baselineVolumes: [], command }), + ).resolves.toEqual({ uninstalled: true, fallbackVolumes: [] }); + expect(command.mock.calls[0]?.[0]).toBe("station-express-uninstall"); + }); + + it("removes only the unattached owned volume added after the recorded baseline", async () => { + const command = cleanupCommand() + .mockResolvedValueOnce(`keep\n${STATION_STATE_VOLUME}\n`) + .mockResolvedValueOnce(JSON.stringify([leftover])) + .mockResolvedValueOnce("") + .mockResolvedValueOnce("") + .mockResolvedValueOnce("keep\n"); + await expect( + cleanupStationRuntime({ + home: cleanupHome(), + repoRoot: "/candidate", + baselineVolumes: ["keep"], + command, + }), + ).resolves.toEqual({ uninstalled: false, fallbackVolumes: [STATION_STATE_VOLUME] }); + expect(command).toHaveBeenCalledWith("station-leftover-volume-remove", "docker", [ + "volume", + "rm", + STATION_STATE_VOLUME, + ]); + }); + + it.each([ + { ...leftover, Name: "foreign" }, + { ...leftover, Driver: "plugin" }, + { ...leftover, Scope: "global" }, + { ...leftover, Options: { device: "/foreign" } }, + { ...leftover, Labels: {} }, + ...Object.keys(leftover.Labels).map((key) => ({ + ...leftover, + Labels: { ...leftover.Labels, [key]: "foreign" }, + })), + ])("refuses unproven leftover ownership %#", async (volume) => { + const command = cleanupCommand() + .mockResolvedValueOnce(STATION_STATE_VOLUME) + .mockResolvedValueOnce(JSON.stringify([volume])); + await expect( + cleanupStationRuntime({ + home: cleanupHome(), + repoRoot: "/candidate", + baselineVolumes: [], + command, + }), + ).rejects.toThrow("ownership is unproven"); + expect(command).toHaveBeenCalledTimes(2); + }); + + it("stops before volume cleanup when uninstall fails", async () => { + const home = cleanupHome(); + fs.mkdirSync(path.join(home, ".nemoclaw")); + const command = cleanupCommand().mockRejectedValue(new Error("uninstall failed")); + await expect( + cleanupStationRuntime({ home, repoRoot: "/candidate", baselineVolumes: [], command }), + ).rejects.toThrow("uninstall failed"); + expect(command).toHaveBeenCalledTimes(1); + expect(command.mock.calls[0]?.[0]).toBe("station-express-uninstall"); + }); + + it("does not remove a volume while a container is attached", async () => { + const command = cleanupCommand() + .mockResolvedValueOnce(STATION_STATE_VOLUME) + .mockResolvedValueOnce(JSON.stringify([leftover])) + .mockResolvedValueOnce("container-id"); + await expect( + cleanupStationRuntime({ + home: cleanupHome(), + repoRoot: "/candidate", + baselineVolumes: [], + command, + }), + ).rejects.toThrow("still attached"); + expect(command).toHaveBeenCalledTimes(3); + }); + + it.each(["foreign\n", `${STATION_STATE_VOLUME}\nforeign\n`, ""])( + "retains unexpected inventory changes: %j", + async (inventory) => { + const command = cleanupCommand().mockResolvedValueOnce(inventory); + await expect( + cleanupStationRuntime({ + home: cleanupHome(), + repoRoot: "/candidate", + baselineVolumes: ["keep"], + command, + }), + ).rejects.toThrow("unexplained change"); + expect(command).toHaveBeenCalledTimes(1); + }, + ); + + it("rejects a preexisting Station volume before invoking any cleanup command", async () => { + const command = cleanupCommand(); + await expect( + cleanupStationRuntime({ + home: cleanupHome(), + repoRoot: "/candidate", + baselineVolumes: [STATION_STATE_VOLUME], + command, + }), + ).rejects.toThrow("present before"); + expect(command).not.toHaveBeenCalled(); + }); + + it("reports a failed removal and a volume that remains after successful removal", async () => { + const failure = cleanupCommand() + .mockResolvedValueOnce(STATION_STATE_VOLUME) + .mockResolvedValueOnce(JSON.stringify([leftover])) + .mockResolvedValueOnce("") + .mockRejectedValueOnce(new Error("remove failed")); + await expect( + cleanupStationRuntime({ + home: cleanupHome(), + repoRoot: "/candidate", + baselineVolumes: [], + command: failure, + }), + ).rejects.toThrow("remove failed"); + const retained = cleanupCommand() + .mockResolvedValueOnce(STATION_STATE_VOLUME) + .mockResolvedValueOnce(JSON.stringify([leftover])) + .mockResolvedValueOnce("") + .mockResolvedValueOnce("") + .mockResolvedValueOnce(STATION_STATE_VOLUME); + await expect( + cleanupStationRuntime({ + home: cleanupHome(), + repoRoot: "/candidate", + baselineVolumes: [], + command: retained, + }), + ).rejects.toThrow("restore the volume baseline"); + }); + + it("does not uninstall another sandbox or follow a registry symlink", async () => { + const home = cleanupHome(); + fs.mkdirSync(path.join(home, ".nemoclaw")); + const registry = path.join(home, ".nemoclaw/sandboxes.json"); + fs.writeFileSync(registry, JSON.stringify({ sandboxes: { foreign: {} } })); + const command = cleanupCommand(); + await expect( + cleanupStationRuntime({ home, repoRoot: "/candidate", baselineVolumes: [], command }), + ).rejects.toThrow("another sandbox"); + fs.renameSync(registry, registry + ".retained"); + fs.symlinkSync(registry + ".retained", registry); + await expect( + cleanupStationRuntime({ home, repoRoot: "/candidate", baselineVolumes: [], command }), + ).rejects.toThrow(); + expect(command).not.toHaveBeenCalled(); + }); +}); + +it("allows consecutive tsx IPC servers within the generated temporary path length", () => { + const env = stationSmokeEnvironment(base, "/candidate"); + const worstCaseSocket = `${env.TMPDIR}/tsx-4294967295/4294967295.pipe`; + expect(Buffer.byteLength(worstCaseSocket)).toBeLessThan(108); + const root = fs.mkdtempSync("/tmp/ncs-ipc-"); + directories.push(root); + const tmp = path.join(root, "x".repeat(env.TMPDIR!.length - root.length - 1)); + fs.mkdirSync(tmp); + const program = path.join(root, "ipc.ts"); + fs.writeFileSync(program, 'process.stdout.write("ready")'); + const executable = path.join(process.cwd(), "node_modules/tsx/dist/cli.mjs"); + const first = spawnSync(process.execPath, [executable, program], { + encoding: "utf8", + env: { ...process.env, TMPDIR: tmp }, + timeout: 10000, + }); + expect(first.status, first.stderr).toBe(0); + expect(first.stdout).toBe("ready"); + const second = spawnSync(process.execPath, [executable, program], { + encoding: "utf8", + env: { ...process.env, TMPDIR: tmp }, + timeout: 10000, + }); + expect(second.status, second.stderr).toBe(0); + expect(second.stdout).toBe("ready"); +}); + +function cleanupProcessRunner(home: string) { + const artifacts = new ArtifactSink(path.join(home, "command-artifacts")); + const progress = startTestProgress( + "Station cleanup command contract", + ["run the observed cleanup command", "record the cleanup command outcome"], + { logLine: () => {} }, + ); + const command = createStationCleanupCommand({ + artifacts, + progress, + environment: process.env, + repoRoot: home, + deadline: Date.now() + 10000, + }); + return { artifacts, progress, command }; +} + +it("keeps the event loop available while an observed cleanup command waits", async () => { + const home = cleanupHome(); + const release = path.join(home, "release"); + const runner = cleanupProcessRunner(home); + let finished = false; + const script = + 'const fs = require("node:fs"); const release = process.argv[1]; function check() { if (fs.existsSync(release)) process.stdout.write("done"); else setTimeout(check, 10); } check();'; + const pending = runner + .command("waiting-cleanup", process.execPath, ["-e", script, release], 5000) + .then((value) => { + finished = true; + return value; + }); + try { + await new Promise((resolve) => setImmediate(resolve)); + expect(finished).toBe(false); + fs.writeFileSync(release, "continue"); + await expect(pending).resolves.toBe("done"); + const evidence = JSON.parse( + fs.readFileSync(runner.artifacts.pathFor("shell/waiting-cleanup.result.json"), "utf8"), + ); + expect(evidence).toMatchObject({ exitCode: 0, timedOut: false }); + runner.progress.phase("record the cleanup command outcome"); + expect(runner.progress.summary().phases[0]?.outputEvents).toBeGreaterThan(0); + } finally { + fs.writeFileSync(release, "continue"); + await pending.catch(() => {}); + runner.progress.stop(); + } +}); + +it("rejects nonzero cleanup commands and preserves redacted command evidence", async () => { + const runner = cleanupProcessRunner(cleanupHome()); + const secret = `nvapi-${"s".repeat(25)}`; + try { + await expect( + runner.command( + "failed-cleanup", + process.execPath, + ["-e", `process.stderr.write(${JSON.stringify(secret)}); process.exit(7)`], + 5000, + ), + ).rejects.toThrow("failed-cleanup failed"); + const evidence = fs.readFileSync( + runner.artifacts.pathFor("shell/failed-cleanup.result.json"), + "utf8", + ); + expect(evidence).not.toContain(secret); + expect(JSON.parse(evidence)).toMatchObject({ exitCode: 7, timedOut: false }); + } finally { + runner.progress.stop(); + } +}); + +it("rejects a timed-out cleanup command even if its signal handler exits zero", async () => { + const runner = cleanupProcessRunner(cleanupHome()); + try { + await expect( + runner.command( + "timeout-cleanup", + process.execPath, + [ + "-e", + 'process.on("SIGTERM", () => process.exit(0)); process.stdout.write("ready"); setInterval(() => {}, 1000);', + ], + 1500, + ), + ).rejects.toThrow("timeout-cleanup failed"); + const evidence = JSON.parse( + fs.readFileSync(runner.artifacts.pathFor("shell/timeout-cleanup.result.json"), "utf8"), + ); + expect(evidence).toMatchObject({ timedOut: true, stdout: "ready" }); + } finally { + runner.progress.stop(); + } +}); + +it("rejects truncated cleanup output instead of accepting its successful exit", async () => { + const runner = cleanupProcessRunner(cleanupHome()); + try { + await expect( + runner.command( + "oversized-cleanup", + process.execPath, + ["-e", 'process.stdout.write("x".repeat(1048608))'], + 5000, + ), + ).rejects.toThrow("output exceeded its bound"); + } finally { + runner.progress.stop(); + } +}); + +function standaloneCleanup(baseline: string) { + const home = cleanupHome(); + const bin = path.join(home, "bin"); + fs.mkdirSync(bin); + fs.writeFileSync( + path.join(bin, "docker"), + '#!/bin/sh\n[ "$*" = "volume ls --quiet" ] || exit 9\n', + { mode: 0o755 }, + ); + const artifacts = path.join(home, "artifacts"); + const result = spawnSync( + process.execPath, + ["--no-warnings", "--import", "tsx", "tools/e2e/dgx-station-cleanup.mts", baseline], + { + cwd: process.cwd(), + encoding: "utf8", + timeout: 10000, + env: { + PATH: `${bin}:${process.env.PATH}`, + HOME: home, + NEMOCLAW_REPO_ROOT: process.cwd(), + E2E_ARTIFACT_DIR: artifacts, + }, + }, + ); + return { artifacts, result }; +} + +it("runs standalone cleanup through the same TypeScript loader used by the backend", () => { + const { artifacts, result } = standaloneCleanup("[]"); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ uninstalled: false, fallbackVolumes: [] }); + expect(fs.existsSync(path.join(artifacts, "cleanup-error.txt"))).toBe(false); + expect(result.stderr).toContain("child lifecycle"); + expect( + fs.statSync(path.join(artifacts, "shell/station-cleanup-volumes-restored.result.json")).mode & + 0o777, + ).toBe(0o600); +}); + +it.each([ + ["{}", "Invalid Station volume baseline"], + [JSON.stringify([STATION_STATE_VOLUME]), "Station state volume was present before the job"], +])("retains a direct cleanup validation failure for baseline %s", (baseline, reason) => { + const { artifacts, result } = standaloneCleanup(baseline); + expect(result.status, result.stderr).toBe(1); + expect(result.stdout).toBe(""); + const errorFile = path.join(artifacts, "cleanup-error.txt"); + expect(fs.readFileSync(errorFile, "utf8")).toBe(reason); + expect(fs.statSync(errorFile).mode & 0o777).toBe(0o600); + expect(fs.existsSync(path.join(artifacts, "shell"))).toBe(false); +}); + +it("redacts a malformed cleanup input in its retained diagnostic", () => { + const secret = "hf_aaaaaaaaaa"; + const { artifacts, result } = standaloneCleanup(secret); + expect(result.status, result.stderr).toBe(1); + const reason = fs.readFileSync(path.join(artifacts, "cleanup-error.txt"), "utf8"); + expect(reason).toContain("JSON"); + expect(reason).toContain(""); + expect(reason).not.toContain(secret); + expect(result.stdout + result.stderr).not.toContain(secret); +}); diff --git a/test/e2e/support/dgx-station-express.ts b/test/e2e/support/dgx-station-express.ts new file mode 100644 index 00000000000..99884ccb392 --- /dev/null +++ b/test/e2e/support/dgx-station-express.ts @@ -0,0 +1,445 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { + cleanupStationRuntime, + stationVolumeBaseline, +} from "../../../tools/e2e/dgx-station-cleanup.mts"; +import { createHash } from "node:crypto"; +import path from "node:path"; +import { performance } from "node:perf_hooks"; +import { getManagedInferenceCompiledRecipe } from "../../../src/lib/inference/serving/catalog-loader.ts"; +import { isHostLocalInferenceServingRecipe } from "../../../src/lib/inference/serving/adapter-registry.ts"; +import { materializeHostLocalVllmModel } from "../../../src/lib/inference/serving/host-local-vllm-selection.ts"; +import { + buildVllmServeCommand, + resolveVllmModelAlias, +} from "../../../src/lib/inference/vllm-models.ts"; +import { detectVllmProfile, resolveVllmModelRuntime } from "../../../src/lib/inference/vllm.ts"; +import { parseStrictOpenShellSandboxListJson } from "../../../src/lib/adapters/openshell/sandbox-identity.ts"; +import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import type { CleanupRegistry } from "../fixtures/cleanup.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; + +export const STATION_SMOKE_SANDBOX = "e2e-station-express"; +export const STATION_SMOKE_MODEL = "nvidia/nemotron-3-ultra-550b-a55b"; +export const STATION_SMOKE_PHASES = [ + "inspect the prepared Station", + "install Station Express from the candidate checkout", + "assert managed Ultra and routed inference", + "clean up the job runtime", +] as const; + +function requireCondition(value: unknown, message: string): asserts value { + if (!value) throw new Error(message); +} +function record(value: unknown): Record { + requireCondition( + value && typeof value === "object" && !Array.isArray(value), + "Station smoke received an invalid record", + ); + return value as Record; +} +function parseJson(output: string): unknown { + try { + return JSON.parse(output); + } catch { + throw new Error("Station smoke received invalid JSON; inspect the command artifact"); + } +} + +export function stationSmokeEnvironment( + base: NodeJS.ProcessEnv, + repoRoot: string, +): NodeJS.ProcessEnv { + const workspace = base.NEMOCLAW_STATION_WORKSPACE ?? ""; + requireCondition( + /^\/var\/tmp\/nemoclaw-station-e2e\/[a-f0-9]{64}$/u.test(workspace), + "Station smoke requires a dispatcher-owned job workspace", + ); + const runnerHome = base.NEMOCLAW_STATION_RUNNER_HOME ?? ""; + requireCondition( + path.isAbsolute(runnerHome) && + path.normalize(runnerHome) === runnerHome && + !/[\u0000-\u001f\u007f-\u009f]/u.test(runnerHome) && + base.HOME === runnerHome, + "Station smoke requires the configured runner HOME", + ); + requireCondition( + /^[a-f0-9]{40}$/u.test(base.E2E_MANAGED_IMAGE_REVISION ?? ""), + "Station smoke requires an exact managed-image revision", + ); + return { + ...buildAvailabilityProbeEnv(base), + HOME: base.HOME, + PATH: base.PATH, + TMPDIR: `/tmp/ncs/${path.basename(workspace)}`, + XDG_BIN_HOME: `${runnerHome}/.local/bin`, + XDG_CACHE_HOME: `${runnerHome}/.cache`, + XDG_CONFIG_HOME: `${runnerHome}/.config`, + XDG_DATA_HOME: `${runnerHome}/.local/share`, + XDG_STATE_HOME: `${runnerHome}/.local/state`, + XDG_RUNTIME_DIR: base.XDG_RUNTIME_DIR, + DBUS_SESSION_BUS_ADDRESS: base.DBUS_SESSION_BUS_ADDRESS, + npm_config_prefix: `${workspace}/npm-prefix`, + GITHUB_ACTIONS: "true", + E2E_MANAGED_IMAGE_REVISION: base.E2E_MANAGED_IMAGE_REVISION, + NEMOCLAW_RUN_LIVE_E2E: "1", + NEMOCLAW_REPO_ROOT: repoRoot, + NEMOCLAW_AGENT: "openclaw", + NEMOCLAW_SANDBOX_NAME: STATION_SMOKE_SANDBOX, + NEMOCLAW_NON_INTERACTIVE: "1", + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", + NEMOCLAW_PROVIDER: "", + NEMOCLAW_MODEL: "", + NEMOCLAW_VLLM_MODEL: "", + NEMOCLAW_VLLM_EXTRA_ARGS_JSON: "", + NEMOCLAW_DGX_STATION_PEER: "", + NEMOCLAW_NON_INTERACTIVE_SUDO_MODE: "", + NEMOCLAW_NO_EXPRESS: "", + NEMOCLAW_ENABLE_LOCAL_MODEL_PROFILE: "", + NEMOCLAW_LOCAL_MODEL_RUNTIME: "", + NEMOCLAW_GATEWAY_PORT: "8080", + NEMOCLAW_DASHBOARD_PORT: "18789", + NEMOCLAW_VLLM_PORT: "8000", + DOCKER_CONTEXT: "default", + DOCKER_HOST: "", + OPENSHELL_GATEWAY: "nemoclaw", + }; +} + +export function stationModelCacheMetadata(home: string): { sha256: string; entries: number } { + const root = path.join( + home, + ".cache/huggingface/hub/models--nvidia--NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4", + ); + const rows: string[] = []; + const visit = (directory: string) => { + for (const name of fs.readdirSync(directory).sort()) { + requireCondition(rows.length < 10_000, "Station model cache metadata exceeds its bound"); + requireCondition( + !/[\u0000-\u001f\u007f-\u009f]/u.test(name), + "Station model cache contains an unsafe filename", + ); + const file = path.join(directory, name); + const stat = fs.lstatSync(file); + const relative = path.relative(root, file); + const kind = stat.isDirectory() + ? "directory" + : stat.isFile() + ? "file" + : stat.isSymbolicLink() + ? "symlink" + : "other"; + requireCondition(kind !== "other", "Station model cache contains a special file"); + rows.push( + JSON.stringify([ + relative, + kind, + stat.isFile() ? stat.size : 0, + stat.isSymbolicLink() ? fs.readlinkSync(file) : "", + ]), + ); + if (stat.isDirectory()) visit(file); + } + }; + visit(root); + requireCondition(rows.length > 0, "Station model cache is empty"); + return { + sha256: createHash("sha256").update(rows.join("\n")).digest("hex"), + entries: rows.length, + }; +} + +export function stationVllmCommands(): readonly string[] { + const recipe = getManagedInferenceCompiledRecipe( + "vllm.nemotron-3-ultra-550b-a55b-nvfp4.station-arm64-single.v1", + ); + requireCondition( + recipe && isHostLocalInferenceServingRecipe(recipe) && recipe.spec.serve.directInstall, + "Station Ultra serving recipe is unavailable", + ); + const registered = resolveVllmModelAlias("nemotron-3-ultra-550b-a55b"); + const profile = detectVllmProfile({ platform: "station" }); + requireCondition(registered && profile, "Station Ultra runtime is unavailable"); + requireCondition( + recipe.spec.model.id === "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4" && + registered.id === recipe.spec.model.id && + recipe.spec.model.servedName === STATION_SMOKE_MODEL, + "Station smoke requires the default Ultra weights and serving alias", + ); + return [ + buildVllmServeCommand( + materializeHostLocalVllmModel(recipe, recipe.spec.serve.directInstall, "station"), + {}, + ), + buildVllmServeCommand( + resolveVllmModelRuntime({ ...profile, buildDockerRunFlags: undefined }, registered, "arm64") + .model, + {}, + ), + ]; +} + +export function assertStationVllm(output: string): string { + const values = parseJson(output); + requireCondition( + Array.isArray(values) && values.length === 1, + "Station smoke requires exactly one managed vLLM container", + ); + const value = record(values[0]); + const config = record(value.Config); + const args = config.Cmd; + const labels = record(config.Labels); + requireCondition( + record(value.State).Running === true && labels["com.nvidia.nemoclaw.managed-vllm"] === "true", + "Station managed vLLM must be running", + ); + requireCondition( + JSON.stringify(config.Entrypoint) === JSON.stringify(["/bin/bash"]) && + Array.isArray(args) && + args.length === 2 && + args[0] === "-lc" && + stationVllmCommands().includes(args[1]), + "Station Express must serve the default Ultra model", + ); + requireCondition( + typeof value.Image === "string" && /^sha256:[a-f0-9]{64}$/u.test(value.Image), + "Station vLLM image identity is invalid", + ); + return value.Image; +} + +export function assertStationReady(output: string): void { + const rows = parseStrictOpenShellSandboxListJson(output); + requireCondition( + rows?.length === 1 && + rows[0].name === STATION_SMOKE_SANDBOX && + ["ready", "running"].includes(rows[0].phase.toLowerCase()), + "Station Express must produce exactly its ready sandbox", + ); +} + +export function assertStationWorkload(value: unknown, revision: string): void { + const registry = record(value); + const entry = record(record(registry.sandboxes)[STATION_SMOKE_SANDBOX]); + const workload = record(entry.workload); + requireCondition( + workload.kind === "managed-image" && workload.sourceRevision === revision, + "Station sandbox must use the independently selected managed-image revision", + ); +} + +export function assertStationInference(output: string): void { + const response = record(parseJson(output)); + const choices = response.choices; + requireCondition( + response.model === STATION_SMOKE_MODEL && Array.isArray(choices) && choices.length > 0, + "Station inference must come from the default Ultra model", + ); + const content = record(record(choices[0]).message).content; + requireCondition( + typeof content === "string" && content.trim().length > 0, + "Station routed inference returned no assistant content", + ); +} + +export async function runStationExpressSmoke(options: { + host: Pick; + cleanup: Pick; + sandbox: Pick; + environment: NodeJS.ProcessEnv; + repoRoot: string; + phases: { inspect(): void; install(): void; assert(): void; cleanup(): void }; + writeEvidence: (name: string, value: unknown) => Promise; + now?: () => number; + modelCacheMetadata?: () => ReturnType; +}): Promise { + const env = stationSmokeEnvironment(options.environment, options.repoRoot); + const now = options.now ?? (() => performance.now()); + const command = async (label: string, executable: string, args: string[], timeoutMs = 30_000) => { + const result = await options.host.command(executable, args, { + env, + cwd: options.repoRoot, + artifactName: label, + timeoutMs, + }); + requireCondition( + result.exitCode === 0 && !result.timedOut, + `${label} failed; inspect its command artifact`, + ); + return result.stdout; + }; + options.phases.inspect(); + requireCondition( + ( + await command("station-platform", "bash", [ + "--noprofile", + "--norc", + "-c", + "source scripts/install.sh >/dev/null; detect_express_platform", + ]) + ).trim() === "DGX Station", + "Station smoke requires qualified Station hardware and release metadata", + ); + const initialContainers = await command("station-initial-containers", "docker", [ + "container", + "ls", + "--all", + "--quiet", + ]); + requireCondition( + initialContainers.trim() === "", + "Station smoke requires an empty dedicated Docker host", + ); + requireCondition( + !fs.existsSync(path.join(env.HOME!, ".nemoclaw")), + "Station smoke requires fresh installer state", + ); + const initialVolumes = ( + await command("station-initial-volumes", "docker", ["volume", "ls", "--quiet"]) + ) + .split(/\r?\n/u) + .filter(Boolean) + .sort(); + stationVolumeBaseline(initialVolumes); + const initialImages = ( + await command("station-initial-images", "docker", ["image", "ls", "--quiet", "--no-trunc"]) + ) + .split(/\r?\n/u) + .filter(Boolean); + const modelCacheMetadata = + options.modelCacheMetadata ?? (() => stationModelCacheMetadata(env.HOME!)); + const cacheBefore = modelCacheMetadata(); + await options.writeEvidence("station-model-cache-baseline.json", cacheBefore); + const timings: Record = {}; + const started = now(); + let vllmImage: string | undefined; + let failure: unknown; + options.cleanup.add("clean up Station job runtime", async () => { + const cleanupStarted = now(); + try { + const runtimeCleanup = await cleanupStationRuntime({ + home: env.HOME!, + repoRoot: options.repoRoot, + baselineVolumes: initialVolumes, + command, + }); + await options.writeEvidence("station-runtime-cleanup.json", runtimeCleanup); + requireCondition( + ( + await command("station-remaining-containers", "docker", [ + "container", + "ls", + "--all", + "--quiet", + ]) + ).trim() === "", + "Station cleanup left a container behind", + ); + const volumes = ( + await command("station-remaining-volumes", "docker", ["volume", "ls", "--quiet"]) + ) + .split(/\r?\n/u) + .filter(Boolean) + .sort(); + requireCondition( + JSON.stringify(volumes) === JSON.stringify(initialVolumes), + "Station cleanup changed the preserved volume baseline", + ); + if (vllmImage) + await command("station-preserved-vllm-image", "docker", ["image", "inspect", vllmImage]); + requireCondition( + JSON.stringify(modelCacheMetadata()) === JSON.stringify(cacheBefore), + "Station cleanup changed model cache paths, sizes, or symlink targets", + ); + timings.cleanup = "succeeded"; + } catch (error) { + timings.cleanup = "failed"; + throw error; + } finally { + timings.cleanupMs = now() - cleanupStarted; + timings.totalMs = now() - started; + await options.writeEvidence("station-express-timings.json", timings); + } + }); + options.phases.install(); + try { + await command( + "station-express-install", + "bash", + ["install.sh", "--express-install", "--yes-i-accept-third-party-software"], + 40 * 60_000, + ); + timings.installMs = now() - started; + options.phases.assert(); + assertStationReady( + await command("station-sandbox-ready", "openshell", ["sandbox", "list", "-o", "json"]), + ); + timings.installToReadyMs = now() - started; + vllmImage = assertStationVllm( + await command("station-managed-vllm", "docker", [ + "inspect", + "--format", + '[{"Image":{{json .Image}},"State":{"Running":{{json .State.Running}}},"Config":{"Cmd":{{json .Config.Cmd}},"Entrypoint":{{json .Config.Entrypoint}},"Labels":{"com.nvidia.nemoclaw.managed-vllm":{{json (index .Config.Labels "com.nvidia.nemoclaw.managed-vllm")}}}}}]', + "nemoclaw-vllm", + ]), + ); + requireCondition( + initialImages.includes(vllmImage), + "The selected Station vLLM image was not pre-pulled", + ); + assertStationWorkload( + parseJson(fs.readFileSync(path.join(env.HOME!, ".nemoclaw", "sandboxes.json"), "utf8")), + env.E2E_MANAGED_IMAGE_REVISION!, + ); + const response = await options.sandbox.exec( + STATION_SMOKE_SANDBOX, + [ + "curl", + "-q", + "--fail", + "--silent", + "--show-error", + "--max-time", + "90", + "https://inference.local/v1/chat/completions", + "-H", + "Content-Type: application/json", + "--data-raw", + JSON.stringify({ + model: STATION_SMOKE_MODEL, + messages: [{ role: "user", content: "Reply with one word: PONG" }], + max_tokens: 512, + }), + ], + { env, artifactName: "station-routed-inference", timeoutMs: 120_000 }, + ); + requireCondition( + response.exitCode === 0 && !response.timedOut, + "Station sandbox inference request failed; inspect its artifact", + ); + assertStationInference(response.stdout); + timings.assertMs = now() - started - Number(timings.installMs); + } catch (error) { + timings.installMs ??= now() - started; + failure = error; + } finally { + try { + options.phases.cleanup(); + } catch (error) { + failure ??= error; + } + const cleanupResult = await options.cleanup.runAll(); + await options.writeEvidence("station-cleanup.json", cleanupResult); + if (cleanupResult.failures.length > 0) { + const cleanupError = new Error("Station runtime cleanup failed; inspect cleanup evidence"); + failure = failure + ? new AggregateError([failure, cleanupError], "Station smoke and cleanup failed") + : cleanupError; + } + } + if (failure) throw failure; +} diff --git a/test/e2e/support/dgx-station-workflow-boundary.test.ts b/test/e2e/support/dgx-station-workflow-boundary.test.ts new file mode 100644 index 00000000000..8d41b43455d --- /dev/null +++ b/test/e2e/support/dgx-station-workflow-boundary.test.ts @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { validateDgxStationDispatchBoundary } from "../../../tools/e2e/dgx-station-workflow-boundary.mts"; +import { validateE2eWorkflow } from "../../../tools/e2e/workflow-boundary.mts"; +import { buildE2eWorkflowPlan } from "../../../tools/e2e/workflow-plan.mts"; +import { readWorkflow } from "../../helpers/e2e-workflow-contract.ts"; + +describe("Station workflow authorization and ownership", () => { + it("accepts the checked-in explicit Station controller", () => { + expect(validateDgxStationDispatchBoundary(readWorkflow())).toEqual([]); + }); + + it.each([ + ["jobs", " && inputs.jobs == ''"], + ["targets", " && inputs.targets == ''"], + ])("rejects a Station guard that permits another selection in %s", (_selector, guard) => { + const workflow = readWorkflow(); + const job = (workflow.jobs as Record)["dgx-station-express"]; + job.if = job.if.replace(guard, ""); + expect(validateDgxStationDispatchBoundary(workflow)).toContain( + "Station dispatch requires an explicit same-repository selection through the trusted main workflow after image publication", + ); + }); + + it.each([ + ["if", "${{ github.event_name == 'pull_request' }}", "trusted main workflow"], + ["needs", ["generate-matrix"], "managed-image publication"], + ["runs-on", "self-hosted", "GitHub-hosted"], + ["timeout-minutes", 360, "bounded deadline"], + ["permissions", { contents: "write", "id-token": "write" }, "only source read"], + [ + "concurrency", + { group: "jetson-nvmap-gpu-dispatch", "cancel-in-progress": true }, + "own queue", + ], + [ + "env", + { E2E_JOB: "1", E2E_TARGET_ID: "dgx-station-express", E2E_DEFAULT_ENABLED: "1" }, + "explicit-only", + ], + ])("rejects an unsafe %s policy", (field, value, expected) => { + const workflow = readWorkflow(); + const job = (workflow.jobs as Record>)["dgx-station-express"]; + job[field as string] = value; + expect(validateDgxStationDispatchBoundary(workflow).join("\n")).toContain(expected); + }); + + it.each([ + [ + 0, + "with", + { + repository: "NVIDIA/NemoClaw", + ref: "${{ inputs.checkout_sha }}", + "persist-credentials": true, + }, + "trusted workflow revision", + ], + [0, "uses", `unreviewed/checkout@${"a".repeat(40)}`, "reviewed checkout action"], + [0, "uses", `actions/checkout@${"b".repeat(40)}`, "reviewed checkout action"], + [0, "if", "false", "reviewed checkout action"], + [1, "uses", "actions/setup-node@main", "reviewed Node setup"], + [1, "with", { "node-version": ">=22.19.0 <23" }, "reviewed Node setup"], + [1, "if", "false", "reviewed Node setup"], + [2, "uses", "NVIDIA/NemoClaw/.github/actions/setup-reviewed-npm@main", "npm immutably"], + [2, "if", "false", "npm immutably"], + [3, "env", { DGX_STATION_DISPATCH_URL: "${{ vars.JETSON_DISPATCH_URL }}" }, "own URL variable"], + [3, "run", "bash install.sh", "fixed controller client"], + [4, "if", "success()", "failure and cancellation"], + [4, "with", { name: "e2e-jetson-nvmap-gpu" }, "own namespace"], + ])("rejects an unsafe controller step %s %s", (index, field, value, expected) => { + const workflow = readWorkflow(); + const job = (workflow.jobs as Record[] }>)[ + "dgx-station-express" + ]; + job.steps[index as number][field as string] = value; + expect(validateDgxStationDispatchBoundary(workflow).join("\n")).toContain(expected); + expect(validateE2eWorkflow(workflow).join("\n")).toContain(expected); + }); + + it("rejects a Station controller without reviewed npm setup", () => { + const workflow = readWorkflow(); + const job = (workflow.jobs as Record[] }>)[ + "dgx-station-express" + ]; + job.steps.splice(2, 1); + expect(validateDgxStationDispatchBoundary(workflow).join("\n")).toContain("npm immutably"); + }); + + it.each([ + [1, 2], + [2, 3], + ])("rejects Station bootstrap steps reordered at %i and %i", (first, second) => { + const workflow = readWorkflow(); + const job = (workflow.jobs as Record[] }>)[ + "dgx-station-express" + ]; + [job.steps[first], job.steps[second]] = [job.steps[second], job.steps[first]]; + expect(validateDgxStationDispatchBoundary(workflow).join("\n")).toContain("in order"); + }); +}); + +it.each(["jobs", "targets"] as const)( + "selects only the external Station controller through %s", + (selector) => { + const plan = buildE2eWorkflowPlan({ [selector]: "dgx-station-express" }); + expect(plan.selectedJobs).toEqual(["dgx-station-express"]); + expect(plan.matrix).toEqual([]); + expect(plan.testMatrix).toEqual([]); + expect(plan.runtimeProvidersByJob).toEqual({ "dgx-station-express": ["none"] }); + expect(plan.explicitOnlyJobs).toEqual([ + "staging-brev-launchable-identity", + "external-gateway-health", + "mcp-bridge-dev", + "portable-hermes-finalization", + "dgx-station-express", + ]); + expect(buildE2eWorkflowPlan().selectedJobs).not.toContain("dgx-station-express"); + }, +); + +it.each([ + { jobs: "dgx-station-express,hermes-e2e" }, + { jobs: "hermes-e2e,dgx-station-express" }, + { targets: "dgx-station-express,ubuntu-repo-cloud-openclaw" }, + { targets: "ubuntu-repo-cloud-openclaw,dgx-station-express" }, + { jobs: "dgx-station-express", targets: "ubuntu-repo-cloud-openclaw" }, + { jobs: "hermes-e2e", targets: "dgx-station-express" }, + { jobs: "dgx-station-express", targets: "dgx-station-express" }, + { jobs: "dgx-station-express,dgx-station-express" }, + { targets: "dgx-station-express,dgx-station-express" }, +])("rejects Station selectors that its controller cannot execute: %j", (selectors) => { + expect(() => buildE2eWorkflowPlan(selectors)).toThrow( + "dgx-station-express must be selected by itself", + ); +}); diff --git a/test/e2e/support/e2e-semantic-phase-check.test.ts b/test/e2e/support/e2e-semantic-phase-check.test.ts index ca214508ec6..95f1728b9c7 100644 --- a/test/e2e/support/e2e-semantic-phase-check.test.ts +++ b/test/e2e/support/e2e-semantic-phase-check.test.ts @@ -695,6 +695,19 @@ getBuiltinModule("child_process").spawn("bare-child", [], { stdio: "ignore" }); ); }); + test("requires Station cleanup to retain canonical progress at its observed child boundary", () => { + const file = path.join(REPO_ROOT, "tools/e2e/dgx-station-cleanup.mts"); + const source = fs.readFileSync(file, "utf8"); + expect(scanDirectChildProcessSource(file, source).auditFailures).toEqual([]); + const forged = source.replace( + "progress: options.progress,", + "progress: { activity: () => () => undefined, onOutput: () => undefined },", + ); + expect(scanDirectChildProcessSource(file, forged).auditFailures).toEqual([ + expect.stringMatching(/progress must retain the reviewed TestProgress capability/u), + ]); + }); + test("rejects unreviewed or structurally forged observed-child progress", () => { const canonicalSource = fs.readFileSync(FAKE_OPENAI_SOURCE, "utf8"); expect(scanDirectChildProcessSource(FAKE_OPENAI_SOURCE, canonicalSource).auditFailures).toEqual( diff --git a/test/e2e/support/live-vitest-invocation.test.ts b/test/e2e/support/live-vitest-invocation.test.ts index 065284e7e6e..98c971c9899 100644 --- a/test/e2e/support/live-vitest-invocation.test.ts +++ b/test/e2e/support/live-vitest-invocation.test.ts @@ -8,6 +8,7 @@ import { describe, expect, it } from "vitest"; import { buildLiveVitestArgs, + DGX_EXPRESS_TEST_PATH, INFERENCE_ROUTING_TEST_PATH, LIVE_VITEST_PROJECT, MCP_BRIDGE_TEST_PATH, @@ -309,3 +310,99 @@ describe("runLiveVitestCommand (#6961)", () => { expect(result.stderr).toContain('expected "run"'); }); }); + +it.each([ + ["spark-express-vllm", "^spark-express-vllm:"], + ["dgx-station-express", "^dgx-station-express:"], +])("runs only the selected %s case from the shared DGX file", (target, selector) => { + let spawned: Parameters | undefined; + const spawn: LiveVitestSpawner = (...args) => { + spawned = args; + return { status: 0 }; + }; + expect( + runLiveVitestCommand( + ["run", "--test-path", DGX_EXPRESS_TEST_PATH, "--selector", selector], + spawn, + { E2E_TARGET_ID: target }, + ), + ).toBe(0); + expect(spawned?.[1]).toEqual(buildLiveVitestArgs({ testPath: DGX_EXPRESS_TEST_PATH, selector })); + expect(spawned?.[1]).toContain(selector); +}); + +it.each([ + ["dgx-station-express", []], + ["spark-express-vllm", []], + [undefined, ["--selector", "^dgx-station-express:"]], + ["unknown", ["--selector", "^dgx-station-express:"]], + ["spark-express-vllm", ["--selector", "^dgx-station-express:"]], + ["dgx-station-express", ["--selector", "^spark-express-vllm:"]], + ["dgx-station-express", ["--selector", "^dgx"]], +] as const)("rejects a DGX selector mismatch before spawning: %s / %j", (target, selectorArgs) => { + let spawned = false; + const spawn: LiveVitestSpawner = () => { + spawned = true; + return { status: 0 }; + }; + expect(() => + runLiveVitestCommand(["run", "--test-path", DGX_EXPRESS_TEST_PATH, ...selectorArgs], spawn, { + E2E_TARGET_ID: target, + }), + ).toThrow("DGX Express requires an explicit selector matching E2E_TARGET_ID"); + expect(spawned).toBe(false); +}); + +it.each([ + ["spark-express-vllm", "^spark-express-vllm:"], + ["dgx-station-express", "^dgx-station-express:"], +])( + "collects exactly the %s live case without executing hardware operations", + (target, selector) => { + const result = spawnSync( + process.execPath, + [ + path.resolve("node_modules/vitest/vitest.mjs"), + "list", + "--project", + "e2e-live", + DGX_EXPRESS_TEST_PATH, + "--json", + "-t", + selector, + ], + { + cwd: process.cwd(), + encoding: "utf8", + timeout: 30_000, + killSignal: "SIGKILL", + env: { + ...process.env, + NEMOCLAW_RUN_LIVE_E2E: "1", + NEMOCLAW_E2E_PHASE_COLLECTION: "1", + E2E_TARGET_ID: target, + }, + }, + ); + expect(result.status, result.stderr).toBe(0); + const tests = JSON.parse(result.stdout); + expect(tests).toHaveLength(1); + expect(tests[0]).toMatchObject({ name: expect.stringMatching(new RegExp(selector)) }); + }, +); + +it.each(["test/e2e/live/./dgx-express.test.ts", "test/e2e/live//dgx-express.test.ts"])( + "applies DGX selector checks to an equivalent test path: %s", + (testPath) => { + expect(validateLiveTestPath(testPath)).toBe(DGX_EXPRESS_TEST_PATH); + expect(() => + runLiveVitestCommand( + ["run", "--test-path", testPath], + () => { + throw new Error("unexpected spawn"); + }, + { E2E_TARGET_ID: "dgx-station-express" }, + ), + ).toThrow("DGX Express requires an explicit selector matching E2E_TARGET_ID"); + }, +); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 95c20c32263..6567b814735 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -118,12 +118,6 @@ describe("E2E workflow plan", () => { "shared-e2e", "staging-brev-launchable", ]); - expect(plan.explicitOnlyJobs).toEqual([ - "staging-brev-launchable-identity", - "external-gateway-health", - "mcp-bridge-dev", - "portable-hermes-finalization", - ]); expect(releaseRequiredWorkflowJobs()).toContain("live"); expect(releaseRequiredWorkflowJobs()).toContain("staging-brev-launchable"); expect(releaseRequiredWorkflowJobs()).not.toContain("staging-brev-launchable-identity"); diff --git a/test/installer-integration/install-express-noninteractive.test.ts b/test/installer-integration/install-express-noninteractive.test.ts new file mode 100644 index 00000000000..d767ac92703 --- /dev/null +++ b/test/installer-integration/install-express-noninteractive.test.ts @@ -0,0 +1,224 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { runInstallerSourced } from "../helpers/installer-express-prompt-harness"; +import { INSTALLER_PAYLOAD } from "../helpers/installer-sourced-env"; + +describe("non-interactive Station Express selection", () => { + function expectCiQualificationHelp(installer: string) { + const result = spawnSync("bash", [installer, "--help"], { encoding: "utf8" }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toMatch( + /--express-install\s+Select Station Express for CI qualification \(requires software acceptance\)/u, + ); + } + + it("describes Station Express as CI qualification in the standalone bootstrap help", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-express-help-")); + onTestFinished(() => fs.rmSync(root, { recursive: true, force: true })); + const installer = path.join(root, "install.sh"); + fs.copyFileSync(path.resolve(import.meta.dirname, "../../install.sh"), installer); + expectCiQualificationHelp(installer); + }); + + it("describes Station Express as CI qualification in the versioned payload help", () => { + expectCiQualificationHelp(INSTALLER_PAYLOAD); + }); + + function select(args: string, environment: NodeJS.ProcessEnv = {}) { + return runInstallerSourced( + ` +detect_express_platform() { printf '%s' "$EXPRESS_PLATFORM"; } +print_banner() { :; } +validate_installer_docker_target_before_host_changes() { :; } +ensure_station_express_host() { printf 'HOST_PREPARATION\\n'; } +prepare_portable_experimental_runtime_override() { :; } +installer_requires_legacy_docker_bootstrap() { return 1; } +ensure_openshell_build_deps() { :; } +install_nemoclaw_before_onboarding() { + printf 'AGENT=%s\\n' "\${NEMOCLAW_AGENT:-}" + printf 'SELECTED=%s|%s|%s|%s|%s|%s|%s|%s\\n' \\ + "\${_STATION_INSTALL_MODE:-}" "\${NEMOCLAW_STATION_EXPRESS:-}" "\${NEMOCLAW_PROVIDER:-}" \\ + "\${NEMOCLAW_VLLM_MODEL:-}" "\${NEMOCLAW_MODEL:-}" "\${NEMOCLAW_POLICY_MODE:-}" \\ + "\${NEMOCLAW_NON_INTERACTIVE_SUDO_MODE:-}" "\${NON_INTERACTIVE:-}" + exit 0 +} +main ${args} +`, + { EXPRESS_PLATFORM: "DGX Station", ...environment }, + ); + } + + it.each(["openclaw", "hermes", "langchain-deepagents-code"])( + "preserves the explicitly selected %s agent in headless Express", + (agent) => { + const { home, result, output } = select( + "--express-install --yes-i-accept-third-party-software", + { NEMOCLAW_AGENT: agent }, + ); + try { + expect(result.status, output).toBe(0); + expect(output).toContain(`AGENT=${agent}`); + expect(output).toContain("SELECTED=express|1|install-vllm|nemotron-3-ultra-550b-a55b|"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); + it.each([ + "--express-install --yes-i-accept-third-party-software", + "--yes-i-accept-third-party-software --express-install --non-interactive", + ])("selects the real Ultra Express recipe through main with %s", (args) => { + const { home, result, output } = select(args); + try { + expect(result.status, output).toBe(0); + expect(output).toContain("HOST_PREPARATION"); + expect(output).toContain( + "SELECTED=express|1|install-vllm|nemotron-3-ultra-550b-a55b|nvidia/nemotron-3-ultra-550b-a55b|suggested||1", + ); + expect(output).not.toContain("Run express install with these settings?"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("accepts the existing notice environment variable without a second acceptance mechanism", () => { + const { home, result, output } = select("--express-install", { + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", + }); + try { + expect(result.status, output).toBe(0); + expect(output).toContain("SELECTED=express|1|install-vllm|"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("keeps ordinary accepted non-interactive installation outside Express", () => { + const { home, result, output } = select("--yes-i-accept-third-party-software"); + try { + expect(result.status, output).toBe(0); + expect(output).toContain("SELECTED=|||||||1"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it.each([ + { args: "--express-install", env: {}, error: "requires --yes-i-accept-third-party-software" }, + { + args: "--express-install --station-deepseek", + env: {}, + error: "interactive --station-deepseek", + }, + { + args: "--express-install --force-station-install", + env: {}, + error: "interactive --station-deepseek", + }, + { + args: "--express-install", + env: { NEMOCLAW_NO_EXPRESS: "1" }, + error: "NEMOCLAW_NO_EXPRESS=1", + }, + { + args: "--express-install", + env: { NEMOCLAW_PROVIDER: "install-vllm" }, + error: "remove NEMOCLAW_PROVIDER", + }, + { + args: "--express-install", + env: { EXPRESS_PLATFORM: "DGX Spark" }, + error: "requires a supported DGX Station", + }, + { + args: "--express-install", + env: { EXPRESS_PLATFORM: "" }, + error: "requires a supported DGX Station", + }, + { + args: "--express-install", + env: { NEMOCLAW_NON_INTERACTIVE_SUDO_MODE: "prompt" }, + error: "cannot enable sudo prompts", + }, + { + args: "--express-install --local-model-runtime=vllm", + env: {}, + error: "NEMOCLAW_NO_EXPRESS=1", + }, + { + args: "--express-install --defer-onboarding", + env: { NEMOCLAW_AGENT: "hermes" }, + error: "cannot be combined with --defer-onboarding", + }, + ])("rejects conflicting or incomplete intent: $error ($args, $env)", ({ args, env, error }) => { + const acceptance = error.startsWith("requires --yes") + ? {} + : { NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1" }; + const { home, result, output } = select(args, { ...acceptance, ...env }); + try { + expect(result.status, output).not.toBe(0); + expect(output).toContain(error); + expect(output).not.toContain("HOST_PREPARATION"); + expect(output).not.toContain("SELECTED="); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it.each(["express", "provider"])( + "revalidates %s resume intent produced by the installer", + (mode) => { + const { home, result, output } = runInstallerSourced(` +detect_express_platform() { printf 'DGX Station'; } +station_installer_revision() { printf 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; } +_STATION_INSTALL_MODE=${mode} +configure_station_express_model +save_station_express_resume +unset NEMOCLAW_PROVIDER NEMOCLAW_VLLM_MODEL NEMOCLAW_MODEL +EXPRESS_INSTALL=1 +ACCEPT_THIRD_PARTY_SOFTWARE=1 +maybe_offer_express_install +printf 'RESUMED=%s|%s|%s\\n' "$NEMOCLAW_STATION_EXPRESS" "$NEMOCLAW_VLLM_MODEL" "\${NEMOCLAW_NON_INTERACTIVE_SUDO_MODE:-}" +`); + try { + expect(result.status, output).toBe(mode === "express" ? 0 : 1); + expect(output).toContain( + mode === "express" + ? "RESUMED=1|nemotron-3-ultra-550b-a55b|" + : "resume state was accepted in provider mode; refusing to resume it in express mode", + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); + + it.each([0, 1])( + "requires non-interactive sudo before invoking Station preparation (exit %s)", + (sudoExit) => { + const { home, result, output } = runInstallerSourced(` +EXPRESS_INSTALL=1 +sudo() { printf '%s\\n' "$*" >>"$HOME/sudo-calls"; return ${sudoExit}; } +bash() { printf 'PREPARE_SUDO_MODE=%s\\n' "$NEMOCLAW_STATION_PREP_SUDO_NONINTERACTIVE"; } +filter_station_host_preparation_output() { cat; } +run_station_host_preparation +`); + try { + expect(fs.readFileSync(path.join(home, "sudo-calls"), "utf8")).toBe("-n true\n"); + expect(result.status, output).toBe(sudoExit); + expect(output).toContain( + sudoExit === 0 ? "PREPARE_SUDO_MODE=1" : "requires non-interactive sudo", + ); + expect(output.includes("PREPARE_SUDO_MODE=")).toBe(sudoExit === 0); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); +}); diff --git a/tools/e2e/check-semantic-phases.mts b/tools/e2e/check-semantic-phases.mts index b76a896ead3..0c9e74f84ff 100644 --- a/tools/e2e/check-semantic-phases.mts +++ b/tools/e2e/check-semantic-phases.mts @@ -374,6 +374,10 @@ const OBSERVED_CHILD_PROGRESS_POLICIES = new Map Promise; + +function requireCondition(value: unknown, message: string): asserts value { + if (!value) throw new Error(message); +} +function record(value: unknown): Record { + requireCondition( + value && typeof value === "object" && !Array.isArray(value), + "Invalid Station cleanup record", + ); + return value as Record; +} +export function stationVolumeBaseline(value: unknown): string[] { + requireCondition( + Array.isArray(value) && + value.every( + (name) => typeof name === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,254}$/u.test(name), + ) && + new Set(value).size === value.length, + "Invalid Station volume baseline", + ); + requireCondition( + !value.includes(STATION_STATE_VOLUME), + "Station state volume was present before the job", + ); + return [...value].sort(); +} +function present(file: string): boolean { + try { + fs.lstatSync(file); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} +function registered(home: string): boolean { + const file = path.join(home, ".nemoclaw", "sandboxes.json"); + let fd: number; + try { + fd = fs.openSync( + file, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } + try { + const info = fs.fstatSync(fd); + requireCondition( + info.isFile() && + info.nlink === 1 && + info.uid === process.getuid?.() && + info.size <= 1024 * 1024, + "Unsafe Station sandbox registry", + ); + const rows = record(record(JSON.parse(fs.readFileSync(fd, "utf8"))).sandboxes); + requireCondition( + Object.keys(rows).every((name) => name === STATION_SANDBOX), + "Station registry contains another sandbox", + ); + if (!(STATION_SANDBOX in rows)) return false; + const entry = record(rows[STATION_SANDBOX]); + requireCondition( + entry.agent === "openclaw" && record(entry.workload).kind === "managed-image", + "Station registry does not describe the expected OpenClaw workload", + ); + return true; + } finally { + fs.closeSync(fd); + } +} +function installationPresent(home: string): boolean { + return [ + ".nemoclaw", + ".config/nemoclaw", + ".config/openshell", + ".local/state/nemoclaw", + ".config/systemd/user/nemoclaw-openshell-gateway.service", + ...[ + "nemoclaw", + "nemoclaw-acp", + "nemohermes", + "nemo-deepagents", + "openshell", + "openshell-gateway", + "openshell-sandbox", + "openshell-driver-vm", + ].map((name) => `.local/bin/${name}`), + ].some((name) => present(path.join(home, name))); +} + +export async function cleanupStationRuntime(options: { + home: string; + repoRoot: string; + baselineVolumes: unknown; + command: Command; +}): Promise<{ uninstalled: boolean; fallbackVolumes: string[] }> { + const before = stationVolumeBaseline(options.baselineVolumes); + const { command, home } = options; + const hasRegisteredSandbox = registered(home); + const uninstalled = hasRegisteredSandbox || installationPresent(home); + if (uninstalled) + await command( + "station-express-uninstall", + "bash", + ["uninstall.sh", "--yes", "--destroy-user-data"], + 180_000, + ); + const volumes = ( + await command("station-cleanup-volume-inventory", "docker", ["volume", "ls", "--quiet"]) + ) + .split(/\r?\n/u) + .filter(Boolean) + .sort(); + const added = volumes.filter((name) => !before.includes(name)); + requireCondition( + before.every((name) => volumes.includes(name)) && + added.every((name) => name === STATION_STATE_VOLUME), + "Station cleanup volume inventory contains an unexplained change", + ); + if (added.length) { + const values: unknown = JSON.parse( + await command("station-leftover-volume-identity", "docker", [ + "volume", + "inspect", + STATION_STATE_VOLUME, + ]), + ); + requireCondition( + Array.isArray(values) && values.length === 1, + "Ambiguous Station state volume", + ); + const volume = record(values[0]); + const labels = record(volume.Labels); + const expected = { + managed: "true", + schema: "1", + sandbox: STATION_SANDBOX, + target: "/sandbox/.openclaw", + }; + requireCondition( + volume.Name === STATION_STATE_VOLUME && + volume.Driver === "local" && + volume.Scope === "local" && + (volume.Options == null || Object.keys(record(volume.Options)).length === 0) && + Object.entries(expected).every( + ([key, value]) => labels[`io.nvidia.nemoclaw.openclaw-state.${key}`] === value, + ), + "Station leftover volume ownership is unproven", + ); + requireCondition( + ( + await command("station-leftover-volume-users", "docker", [ + "container", + "ls", + "--all", + "--quiet", + "--filter", + `volume=${STATION_STATE_VOLUME}`, + ]) + ).trim() === "", + "Station leftover volume is still attached", + ); + await command("station-leftover-volume-remove", "docker", [ + "volume", + "rm", + STATION_STATE_VOLUME, + ]); + } + const remaining = ( + await command("station-cleanup-volumes-restored", "docker", ["volume", "ls", "--quiet"]) + ) + .split(/\r?\n/u) + .filter(Boolean) + .sort(); + requireCondition( + JSON.stringify(remaining) === JSON.stringify(before), + "Station cleanup did not restore the volume baseline", + ); + return { uninstalled, fallbackVolumes: added }; +} + +export function createStationCleanupCommand(options: { + artifacts: ArtifactSink; + progress: ChildProcessProgress; + environment: NodeJS.ProcessEnv; + repoRoot: string; + deadline: number; +}): Command { + return async function runStationCleanupCommand(label, executable, args, timeoutMs = 30_000) { + const remaining = options.deadline - Date.now(); + requireCondition(remaining > 0, "Station cleanup deadline expired"); + const command = trustedShellCommand({ + command: executable, + args, + reason: "clean up the Station job runtime", + }); + const output = { stdout: "", stderr: "" }; + const abort = new AbortController(); + let outputExceeded = false; + const capture = (stream: "stdout" | "stderr", chunk: string): void => { + if (outputExceeded) return; + if (Buffer.byteLength(output[stream]) + Buffer.byteLength(chunk) > 1024 * 1024) { + outputExceeded = true; + output.stdout = ""; + output.stderr = ""; + abort.abort(); + } else { + output[stream] += chunk; + } + }; + const child = spawnObservedChild(command.command, command.args, { + activityLabel: label, + progress: options.progress, + spawn: { + cwd: options.repoRoot, + detached: true, + env: { ...options.environment, DOCKER_HOST: "", DOCKER_CONTEXT: "default" }, + stdio: ["ignore", "pipe", "pipe"], + }, + }); + const result = await superviseChild(child, { + timeoutMs: Math.min(timeoutMs, remaining), + killGraceMs: 1000, + signal: abort.signal, + onStdout: (chunk) => capture("stdout", chunk), + onStderr: (chunk) => capture("stderr", chunk), + }); + await options.artifacts.writeJson(`shell/${label}.result.json`, { + ...output, + exitCode: result.exitCode, + signal: result.signal, + timedOut: result.timedOut, + outputExceeded, + spawnFailed: !!result.spawnError, + cleanupFailed: !!result.cleanupError, + }); + requireCondition(!outputExceeded, "Station cleanup output exceeded its bound"); + requireCondition( + result.exitCode === 0 && + !result.timedOut && + result.signal === null && + !result.spawnError && + !result.cleanupError, + `${label} failed; inspect the private cleanup artifact`, + ); + return output.stdout; + }; +} + +async function main(): Promise { + requireCondition( + process.argv.length === 3 && + process.env.HOME && + process.env.NEMOCLAW_REPO_ROOT && + process.env.E2E_ARTIFACT_DIR, + "Station cleanup requires its runner environment and volume baseline", + ); + process.umask(0o077); + const artifacts = new ArtifactSink(process.env.E2E_ARTIFACT_DIR); + const progress = startTestProgress( + "Station runtime cleanup", + ["prepare Station cleanup", "clean up the job runtime"], + { + logLine: (line) => process.stderr.write(`${line}\n`), + }, + ); + let succeeded = false; + try { + progress.phase("clean up the job runtime"); + const result = await cleanupStationRuntime({ + home: process.env.HOME, + repoRoot: process.env.NEMOCLAW_REPO_ROOT, + baselineVolumes: JSON.parse(process.argv[2]!), + command: createStationCleanupCommand({ + artifacts, + progress, + environment: process.env, + repoRoot: process.env.NEMOCLAW_REPO_ROOT, + deadline: Date.now() + 280_000, + }), + }); + succeeded = true; + console.log(JSON.stringify(result)); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + await artifacts.writeText("cleanup-error.txt", reason); + throw error; + } finally { + progress.stop(succeeded ? "passed" : "failed"); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + main().catch(() => { + console.error("Station runtime cleanup failed; retained evidence requires recovery."); + process.exitCode = 1; + }); +} diff --git a/tools/e2e/dgx-station-dispatch-client.mts b/tools/e2e/dgx-station-dispatch-client.mts new file mode 100644 index 00000000000..88092f355c7 --- /dev/null +++ b/tools/e2e/dgx-station-dispatch-client.mts @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { pathToFileURL } from "node:url"; +import { + DGX_STATION_DISPATCH_AUDIENCE, + DGX_STATION_DISPATCH_TARGET, + parseDgxStationDispatchRequest, +} from "./jetson-dispatch-contract.mts"; +import { + createGitHubOidcTokenProvider, + dispatcherBaseUrl, + dispatcherRequest, + runDispatchClient, + printableDispatchError, +} from "./jetson-dispatch-client.mts"; + +export function dgxStationDispatchRequestFromEnvironment( + environment: NodeJS.ProcessEnv = process.env, +) { + return parseDgxStationDispatchRequest({ + schemaVersion: 3, + target: DGX_STATION_DISPATCH_TARGET, + candidateSha: environment.DGX_STATION_DISPATCH_CANDIDATE_SHA, + managedImageRevision: environment.DGX_STATION_DISPATCH_MANAGED_IMAGE_REVISION, + workflowRunId: environment.GITHUB_RUN_ID, + workflowRunAttempt: Number(environment.GITHUB_RUN_ATTEMPT), + }); +} + +async function main(): Promise { + const tokenProvider = createGitHubOidcTokenProvider({ audience: DGX_STATION_DISPATCH_AUDIENCE }); + await runDispatchClient({ + request: dgxStationDispatchRequestFromEnvironment(), + baseUrl: dispatcherBaseUrl(process.env.DGX_STATION_DISPATCH_URL, "DGX_STATION_DISPATCH_URL"), + artifactDirectory: process.env.E2E_ARTIFACT_DIR ?? "", + receiptName: "dgx-station-dispatch.json", + archiveName: "dgx-station-e2e-artifacts.tar.gz", + requestImpl: (options) => dispatcherRequest({ ...options, tokenProvider }), + }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + console.error(printableDispatchError(error)); + process.exitCode = 1; + }); +} diff --git a/tools/e2e/dgx-station-workflow-boundary.mts b/tools/e2e/dgx-station-workflow-boundary.mts new file mode 100644 index 00000000000..963d15adb8d --- /dev/null +++ b/tools/e2e/dgx-station-workflow-boundary.mts @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isDeepStrictEqual } from "node:util"; +import { E2E_ACTION_PROVENANCE } from "./workflow-boundary-policy.mts"; + +const TARGET = "dgx-station-express"; +const TRUSTED_SELECTOR = + "${{ always() && needs['base-image-publication'].result == 'success' && needs['base-image-publication'].outputs.managed_image_revision != '' && needs['generate-matrix'].result == 'success' && github.repository == 'NVIDIA/NemoClaw' && github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' && (inputs.checkout_sha == '' || inputs.checkout_sha != inputs.base_sha) && (inputs.checkout_repository == '' || inputs.checkout_repository == github.repository) && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'dgx-station-express') && ((inputs.jobs == 'dgx-station-express' && inputs.targets == '') || (inputs.targets == 'dgx-station-express' && inputs.jobs == '')) }}"; +type RecordValue = Record; +function record(value: unknown): RecordValue { + return value && typeof value === "object" && !Array.isArray(value) ? (value as RecordValue) : {}; +} + +export function validateDgxStationDispatchBoundary(workflow: unknown): string[] { + const errors: string[] = []; + const job = record(record(record(workflow).jobs)[TARGET]); + const steps = Array.isArray(job.steps) ? job.steps.map(record) : []; + const step = (name: string) => steps.find((entry) => entry.name === name) ?? {}; + const requireEqual = (observed: unknown, expected: unknown, error: string) => { + if (!isDeepStrictEqual(observed, expected)) errors.push(error); + }; + requireEqual( + job.if, + TRUSTED_SELECTOR, + "Station dispatch requires an explicit same-repository selection through the trusted main workflow after image publication", + ); + requireEqual( + job.needs, + ["base-image-publication", "generate-matrix"], + "Station dispatch must wait for its planner and managed-image publication", + ); + requireEqual( + job["runs-on"], + "ubuntu-latest", + "Station controller must run on a GitHub-hosted runner", + ); + requireEqual(job["timeout-minutes"], 60, "Station controller must retain its bounded deadline"); + requireEqual( + job.concurrency, + { group: "dgx-station-express-dispatch", "cancel-in-progress": false }, + "Station dispatch must use its own queue without cancelling active work", + ); + requireEqual( + job.permissions, + { contents: "read", "id-token": "write" }, + "Station controller must grant only source read and OIDC token permissions", + ); + const env = record(job.env); + requireEqual( + [env.E2E_JOB, env.E2E_TARGET_ID, env.E2E_DEFAULT_ENABLED, env.E2E_GATEWAY_RUNTIMES], + ["1", TARGET, "0", "agnostic"], + "Station must be an explicit-only external E2E target", + ); + const checkout = step("Check out trusted Station controller"); + requireEqual( + checkout, + { + name: "Check out trusted Station controller", + uses: "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1", + with: { + repository: "NVIDIA/NemoClaw", + ref: "${{ github.workflow_sha }}", + "persist-credentials": false, + }, + }, + "Station controller checkout must use the reviewed checkout action and trusted workflow revision without stored credentials", + ); + requireEqual( + step("Set up Node for Station controller"), + { + name: "Set up Node for Station controller", + uses: "actions/setup-node@820762786026740c76f36085b0efc47a31fe5020", + with: { "node-version": "24.18.1" }, + }, + "Station controller must use the reviewed Node setup", + ); + requireEqual( + step("Install reviewed npm"), + { name: "Install reviewed npm", uses: E2E_ACTION_PROVENANCE.reviewedNpmSetup.reference }, + "Station controller must install reviewed npm immutably", + ); + const dispatch = step("Dispatch exact commit to Station through operator backend"); + requireEqual( + dispatch.env, + { + E2E_ARTIFACT_DIR: "${{ runner.temp }}/e2e-artifacts/live/dgx-station-express", + DGX_STATION_DISPATCH_CANDIDATE_SHA: "${{ inputs.checkout_sha || github.sha }}", + DGX_STATION_DISPATCH_MANAGED_IMAGE_REVISION: + "${{ needs.base-image-publication.outputs.managed_image_revision }}", + DGX_STATION_DISPATCH_URL: "${{ vars.DGX_STATION_DISPATCH_URL }}", + }, + "Station dispatch must bind separate candidate/image revisions and its own URL variable", + ); + requireEqual( + dispatch.run, + "node --no-warnings tools/e2e/dgx-station-dispatch-client.mts", + "Station dispatch must invoke only the fixed controller client", + ); + const upload = step("Upload Station Express artifacts"); + requireEqual(upload.if, "always()", "Station must upload evidence on failure and cancellation"); + requireEqual( + upload.with, + { + name: "e2e-dgx-station-express", + path: "${{ runner.temp }}/e2e-artifacts/live/dgx-station-express/", + }, + "Station artifacts must use their own namespace", + ); + requireEqual( + steps.map((entry) => entry.name), + [ + "Check out trusted Station controller", + "Set up Node for Station controller", + "Install reviewed npm", + "Dispatch exact commit to Station through operator backend", + "Upload Station Express artifacts", + ], + "Station controller must run checkout, Node setup, npm setup, dispatch, and upload in order", + ); + return errors; +} diff --git a/tools/e2e/jetson-dispatch-client.mts b/tools/e2e/jetson-dispatch-client.mts index f24b21a8eca..7e47a6d59f6 100644 --- a/tools/e2e/jetson-dispatch-client.mts +++ b/tools/e2e/jetson-dispatch-client.mts @@ -9,14 +9,15 @@ import { decodeJetsonArtifactArchive, JETSON_DISPATCH_AUDIENCE, JETSON_DISPATCH_TARGET, - jetsonDispatchJobId, - type JetsonDispatchArtifact, - type JetsonDispatchRequest, - type JetsonDispatchStatus, + dispatchJobId, + type DispatchArtifact, + type DispatchRequest, + type DispatchStatus, MAX_JETSON_DISPATCH_ARTIFACT_RESPONSE_BYTES, - parseJetsonDispatchArtifact, + parseDispatchArtifact, parseJetsonDispatchRequest, - parseJetsonDispatchStatusResponse, + type JetsonDispatchRequest, + parseDispatchStatusResponse, } from "./jetson-dispatch-contract.mts"; import { writePrivateRegularFile } from "./private-file.mts"; @@ -43,6 +44,12 @@ type JetsonCancellationResult = | { outcome: "failed"; failure: JetsonCancellationFailure; receiptWritten: boolean } | { outcome: "succeeded"; receiptWritten: boolean }; +export function printableDispatchError(error: unknown): string { + return (error instanceof Error ? error.message : "Dispatch client failed") + .replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ") + .slice(0, 1000); +} + function record(value: unknown, name: string): Record { if (!value || typeof value !== "object" || Array.isArray(value)) { throw new Error(`${name} must be an object`); @@ -50,8 +57,11 @@ function record(value: unknown, name: string): Record { return value as Record; } -export function dispatcherBaseUrl(value: string | undefined): URL { - if (!value) throw new Error("JETSON_DISPATCH_URL is required"); +export function dispatcherBaseUrl( + value: string | undefined, + variable = "JETSON_DISPATCH_URL", +): URL { + if (!value) throw new Error(`${variable} is required`); const url = new URL(value); if ( url.protocol !== "https:" || @@ -61,14 +71,14 @@ export function dispatcherBaseUrl(value: string | undefined): URL { url.hash || (url.pathname !== "" && url.pathname !== "/") ) { - throw new Error("JETSON_DISPATCH_URL must be an HTTPS origin without credentials or a path"); + throw new Error(`${variable} must be an HTTPS origin without credentials or a path`); } url.pathname = "/"; return url; } export function createGitHubOidcTokenProvider( - options: { fetchImpl?: typeof fetch; now?: () => number } = {}, + options: { fetchImpl?: typeof fetch; now?: () => number; audience?: string } = {}, ): (env?: NodeJS.ProcessEnv) => Promise { const fetchImpl = options.fetchImpl ?? fetch; const now = options.now ?? Date.now; @@ -93,7 +103,7 @@ export function createGitHubOidcTokenProvider( if (requestUrl.protocol !== "https:") { throw new Error("GitHub OIDC request URL must use HTTPS"); } - requestUrl.searchParams.set("audience", JETSON_DISPATCH_AUDIENCE); + requestUrl.searchParams.set("audience", options.audience ?? JETSON_DISPATCH_AUDIENCE); const response = await fetchImpl(requestUrl, { headers: { Authorization: `Bearer ${requestToken}` }, signal: AbortSignal.timeout(15_000), @@ -192,7 +202,7 @@ function delay(milliseconds: number): Promise { function writeJetsonRecoveryReceipt( receiptFile: string, - dispatch: Pick, + dispatch: Pick, cancellation?: { failure?: JetsonCancellationFailure; outcome: "failed" | "pending" | "succeeded"; @@ -230,7 +240,7 @@ function classifyCancellationFailure(error: unknown): JetsonCancellationFailure async function cancelJetsonDispatch(options: { baseUrl: URL; - dispatch: Pick; + dispatch: Pick; reason: JetsonCancellationReason; receiptFile: string; request: typeof dispatcherRequest; @@ -283,7 +293,7 @@ export type CancelJetsonDispatch = ( export function createJetsonCancellation(options: { baseUrl: URL; - dispatch: Pick; + dispatch: Pick; receiptFile: string; request: typeof dispatcherRequest; }): CancelJetsonDispatch { @@ -304,12 +314,12 @@ export function createJetsonCancellation(options: { export async function submitJetsonDispatch(options: { baseUrl: URL; cancel?: CancelJetsonDispatch; - dispatchRequest: JetsonDispatchRequest; + dispatchRequest: DispatchRequest; receiptFile: string; request?: typeof dispatcherRequest; stopping?: () => boolean; -}): Promise<{ cancel: CancelJetsonDispatch; status: JetsonDispatchStatus }> { - const jobId = jetsonDispatchJobId(options.dispatchRequest); +}): Promise<{ cancel: CancelJetsonDispatch; status: DispatchStatus }> { + const jobId = dispatchJobId(options.dispatchRequest); const dispatch = { jobId, request: options.dispatchRequest }; writeJetsonRecoveryReceipt(options.receiptFile, dispatch); if (options.stopping?.()) { @@ -325,9 +335,9 @@ export async function submitJetsonDispatch(options: { request, }); - let status: JetsonDispatchStatus; + let status: DispatchStatus; try { - status = parseJetsonDispatchStatusResponse( + status = parseDispatchStatusResponse( await request({ baseUrl: options.baseUrl, method: "POST", @@ -357,13 +367,13 @@ export async function pollJetsonDispatch(options: { baseUrl: URL; cancel?: CancelJetsonDispatch; deadlineMs: number; - initialStatus: JetsonDispatchStatus; + initialStatus: DispatchStatus; now?: () => number; receiptFile: string; request?: typeof dispatcherRequest; stopping?: () => boolean; wait?: typeof delay; -}): Promise { +}): Promise { const now = options.now ?? Date.now; const request = options.request ?? dispatcherRequest; const jobId = options.initialStatus.jobId; @@ -401,7 +411,7 @@ export async function pollJetsonDispatch(options: { } await wait(POLL_INTERVAL_MS); try { - status = parseJetsonDispatchStatusResponse( + status = parseDispatchStatusResponse( await request({ baseUrl: options.baseUrl, method: "GET", @@ -442,21 +452,27 @@ export function jetsonDispatchRequestFromEnvironment( }); } -async function main(): Promise { - const request = jetsonDispatchRequestFromEnvironment(); - const baseUrl = dispatcherBaseUrl(process.env.JETSON_DISPATCH_URL); - const artifactDirectory = process.env.E2E_ARTIFACT_DIR ?? ""; +export async function runDispatchClient(options: { + request: DispatchRequest; + baseUrl: URL; + artifactDirectory: string; + receiptName: string; + archiveName: string; + requestImpl?: typeof dispatcherRequest; +}): Promise { + const { request, baseUrl, artifactDirectory } = options; + const requestImpl = options.requestImpl ?? dispatcherRequest; if (!path.isAbsolute(artifactDirectory)) throw new Error("E2E_ARTIFACT_DIR must be absolute"); fs.mkdirSync(artifactDirectory, { recursive: true, mode: 0o700 }); fs.chmodSync(artifactDirectory, 0o700); - const receiptFile = path.join(artifactDirectory, "jetson-dispatch.json"); + const receiptFile = path.join(artifactDirectory, options.receiptName); - const jobId = jetsonDispatchJobId(request); + const jobId = dispatchJobId(request); const cancelDispatch = createJetsonCancellation({ baseUrl, dispatch: { jobId, request }, receiptFile, - request: dispatcherRequest, + request: requestImpl, }); let submissionStarted = false; let stopping = false; @@ -474,48 +490,65 @@ async function main(): Promise { process.on("SIGINT", cancel); process.on("SIGTERM", cancel); - submissionStarted = true; - const submission = await submitJetsonDispatch({ - baseUrl, - cancel: cancelDispatch, - dispatchRequest: request, - receiptFile, - stopping: () => stopping, - }); - const dispatched = submission.status; - console.log(`Jetson dispatch accepted as ${jobId}`); - const deadline = Date.now() + MAX_WAIT_MS; - await pollJetsonDispatch({ - baseUrl, - cancel: cancelDispatch, - deadlineMs: deadline, - initialStatus: dispatched, - receiptFile, - stopping: () => stopping, - }); + try { + submissionStarted = true; + const submission = await submitJetsonDispatch({ + baseUrl, + cancel: cancelDispatch, + dispatchRequest: request, + request: requestImpl, + receiptFile, + stopping: () => stopping, + }); + const dispatched = submission.status; + console.log(`${request.target} dispatch accepted as ${jobId}`); + const deadline = Date.now() + MAX_WAIT_MS; + await pollJetsonDispatch({ + baseUrl, + cancel: cancelDispatch, + deadlineMs: deadline, + initialStatus: dispatched, + request: requestImpl, + receiptFile, + stopping: () => stopping, + }); - const artifactValue = await dispatcherRequest({ - baseUrl, - method: "GET", - path: `v1/jobs/${jobId}/artifact`, - maxBytes: MAX_JETSON_DISPATCH_ARTIFACT_RESPONSE_BYTES, - }); - const artifact: JetsonDispatchArtifact = parseJetsonDispatchArtifact(artifactValue, jobId); - const { artifactArchiveBase64, ...artifactReceipt } = artifact; - writePrivateRegularFile(receiptFile, `${JSON.stringify(artifactReceipt, null, 2)}\n`); - if (artifactArchiveBase64 !== undefined) { - writePrivateRegularFile( - path.join(artifactDirectory, "jetson-e2e-artifacts.tar.gz"), - decodeJetsonArtifactArchive(artifactArchiveBase64), - ); + const artifactValue = await requestImpl({ + baseUrl, + method: "GET", + path: `v1/jobs/${jobId}/artifact`, + maxBytes: MAX_JETSON_DISPATCH_ARTIFACT_RESPONSE_BYTES, + }); + const artifact: DispatchArtifact = parseDispatchArtifact(artifactValue, jobId); + const { artifactArchiveBase64, ...artifactReceipt } = artifact; + writePrivateRegularFile(receiptFile, `${JSON.stringify(artifactReceipt, null, 2)}\n`); + if (artifactArchiveBase64 !== undefined) { + writePrivateRegularFile( + path.join(artifactDirectory, options.archiveName), + decodeJetsonArtifactArchive(artifactArchiveBase64), + ); + } + console.log(`${request.target} dispatch conclusion: ${artifact.status.conclusion}`); + if (artifact.status.conclusion !== "success") process.exitCode = 1; + } finally { + process.off("SIGINT", cancel); + process.off("SIGTERM", cancel); } - console.log(`Jetson dispatch conclusion: ${artifact.status.conclusion}`); - if (artifact.status.conclusion !== "success") process.exitCode = 1; +} + +async function main(): Promise { + await runDispatchClient({ + request: jetsonDispatchRequestFromEnvironment(), + baseUrl: dispatcherBaseUrl(process.env.JETSON_DISPATCH_URL), + artifactDirectory: process.env.E2E_ARTIFACT_DIR ?? "", + receiptName: "jetson-dispatch.json", + archiveName: "jetson-e2e-artifacts.tar.gz", + }); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { main().catch((error) => { - console.error(error instanceof Error ? error.message : "Jetson dispatch client failed"); + console.error(printableDispatchError(error)); process.exitCode = 1; }); } diff --git a/tools/e2e/jetson-dispatch-contract.mts b/tools/e2e/jetson-dispatch-contract.mts index 6fb800a839c..a0c534b972b 100644 --- a/tools/e2e/jetson-dispatch-contract.mts +++ b/tools/e2e/jetson-dispatch-contract.mts @@ -53,6 +53,49 @@ export interface JetsonDispatchRequestV2 { export type JetsonDispatchRequest = JetsonDispatchRequestV1 | JetsonDispatchRequestV2; +export const DGX_STATION_DISPATCH_TARGET = "dgx-station-express"; +export const DGX_STATION_DISPATCH_AUDIENCE = "nemoclaw-dgx-station-dispatch"; +export const DGX_STATION_DISPATCH_CONTRACT_VERSION = "3.0.0"; + +export interface DgxStationDispatchRequest extends Omit< + JetsonDispatchRequestV2, + "schemaVersion" | "target" +> { + schemaVersion: 3; + target: typeof DGX_STATION_DISPATCH_TARGET; +} + +export type DispatchRequest = JetsonDispatchRequest | DgxStationDispatchRequest; + +export interface DgxStationDeviceIdentity { + model: string; + gpuUuid: string; + driverVersion: string; + osRelease: string; + kernel: string; +} + +export function parseDgxStationDispatchRequest(value: unknown): DgxStationDispatchRequest { + const request = record(value, "Station dispatch request"); + if (request.schemaVersion !== 3 || request.target !== DGX_STATION_DISPATCH_TARGET) { + throw new Error("Station dispatch requires schemaVersion 3 and target dgx-station-express"); + } + const parsed = parseJetsonDispatchRequest({ + ...request, + schemaVersion: 2, + target: JETSON_DISPATCH_TARGET, + }); + if (parsed.schemaVersion !== 2) + throw new Error("Station dispatch requires a managed-image revision"); + return { ...parsed, schemaVersion: 3, target: DGX_STATION_DISPATCH_TARGET }; +} + +export function parseDispatchRequest(value: unknown): DispatchRequest { + return record(value, "dispatch request").target === DGX_STATION_DISPATCH_TARGET + ? parseDgxStationDispatchRequest(value) + : parseJetsonDispatchRequest(value); +} + export type JetsonDispatchConclusion = | "cancelled" | "cleanup-failed" @@ -67,22 +110,35 @@ export interface JetsonDeviceIdentity { kernel: string; } -export interface JetsonDispatchStatus { - schemaVersion: 1 | 2; +export interface DispatchStatus { + schemaVersion: DispatchRequest["schemaVersion"]; jobId: string; - request: JetsonDispatchRequest; + request: DispatchRequest; state: "queued" | "running" | "completed"; conclusion?: JetsonDispatchConclusion; createdAt: string; startedAt?: string; completedAt?: string; - device?: JetsonDeviceIdentity; + device?: JetsonDeviceIdentity | DgxStationDeviceIdentity; cleanup: "pending" | "succeeded" | "failed"; error?: string; } -export interface JetsonDispatchArtifact { +export interface JetsonDispatchStatus extends Omit< + DispatchStatus, + "schemaVersion" | "request" | "device" +> { + schemaVersion: 1 | 2; + request: JetsonDispatchRequest; + device?: JetsonDeviceIdentity; +} + +export interface JetsonDispatchArtifact extends Omit { status: JetsonDispatchStatus; +} + +export interface DispatchArtifact { + status: DispatchStatus; log: string; artifactArchiveBase64?: string; } @@ -167,8 +223,12 @@ export function parseJetsonDispatchRequest(value: unknown): JetsonDispatchReques } export function jetsonDispatchJobId(request: JetsonDispatchRequest): string { + return dispatchJobId(request); +} + +export function dispatchJobId(request: DispatchRequest): string { const managedImageRevision = - request.schemaVersion === 2 ? `:${request.managedImageRevision}` : ""; + request.schemaVersion !== 1 ? `:${request.managedImageRevision}` : ""; return createHash("sha256") .update( `${request.schemaVersion}:${request.target}:${request.candidateSha}${managedImageRevision}:${request.workflowRunId}:${request.workflowRunAttempt}`, @@ -216,15 +276,45 @@ function parseDeviceIdentity(value: unknown): JetsonDeviceIdentity { }; } +function parseStationDeviceIdentity(value: unknown): DgxStationDeviceIdentity { + const device = record(value, "Station device identity"); + const fields = ["model", "gpuUuid", "driverVersion", "osRelease", "kernel"]; + requireFields( + device, + "Station device identity", + fields, + [], + DGX_STATION_DISPATCH_CONTRACT_VERSION, + ); + for (const field of fields) { + const entry = device[field]; + if ( + typeof entry !== "string" || + entry.length === 0 || + entry.length > MAX_DEVICE_IDENTITY_CHARACTERS || + /[\u0000-\u001f\u007f-\u009f]/u.test(entry) + ) { + throw new Error(`Station device ${field} is invalid`); + } + } + return device as unknown as DgxStationDeviceIdentity; +} + export function parseJetsonDispatchStatus(value: unknown): JetsonDispatchStatus { + const status = parseDispatchStatus(value); + parseJetsonDispatchRequest(status.request); + return status as JetsonDispatchStatus; +} + +export function parseDispatchStatus(value: unknown): DispatchStatus { const status = record(value, "Jetson dispatch status"); const baseFields = ["cleanup", "createdAt", "jobId", "request", "schemaVersion", "state"]; - const request = parseJetsonDispatchRequest(status.request); + const request = parseDispatchRequest(status.request); if ( status.schemaVersion !== request.schemaVersion || typeof status.jobId !== "string" || !JOB_ID_PATTERN.test(status.jobId) || - status.jobId !== jetsonDispatchJobId(request) + status.jobId !== dispatchJobId(request) ) { throw new Error("Jetson dispatch status does not match its request and job ID"); } @@ -304,7 +394,12 @@ export function parseJetsonDispatchStatus(value: unknown): JetsonDispatchStatus ) { throw new Error("completed Jetson dispatch error is invalid"); } - const device = status.device === undefined ? undefined : parseDeviceIdentity(status.device); + const device = + status.device === undefined + ? undefined + : request.target === DGX_STATION_DISPATCH_TARGET + ? parseStationDeviceIdentity(status.device) + : parseDeviceIdentity(status.device); if (status.conclusion === "success" && device === undefined) { throw new Error("successful Jetson dispatch must include device identity"); } @@ -327,10 +422,19 @@ export function parseJetsonDispatchStatusResponse( value: unknown, expectedRequest?: JetsonDispatchRequest, ): JetsonDispatchStatus { + const status = parseDispatchStatusResponse(value, expectedRequest); + parseJetsonDispatchRequest(status.request); + return status as JetsonDispatchStatus; +} + +export function parseDispatchStatusResponse( + value: unknown, + expectedRequest?: DispatchRequest, +): DispatchStatus { const response = record(value, "Jetson dispatcher response"); requireFields(response, "Jetson dispatcher response", ["job"]); - const status = parseJetsonDispatchStatus(response.job); - if (expectedRequest !== undefined && status.jobId !== jetsonDispatchJobId(expectedRequest)) { + const status = parseDispatchStatus(response.job); + if (expectedRequest !== undefined && status.jobId !== dispatchJobId(expectedRequest)) { throw new Error("Jetson dispatcher response does not match the submitted request"); } return status; @@ -356,8 +460,17 @@ export function parseJetsonDispatchArtifact( value: unknown, expectedArtifactJobId: string, ): JetsonDispatchArtifact { + const artifact = parseDispatchArtifact(value, expectedArtifactJobId); + parseJetsonDispatchRequest(artifact.status.request); + return artifact as JetsonDispatchArtifact; +} + +export function parseDispatchArtifact( + value: unknown, + expectedArtifactJobId: string, +): DispatchArtifact { const artifact = record(value, "Jetson dispatch artifact"); - const status = parseJetsonDispatchStatus(artifact.status); + const status = parseDispatchStatus(artifact.status); requireFields( artifact, "Jetson dispatch artifact", diff --git a/tools/e2e/live-vitest-invocation.mts b/tools/e2e/live-vitest-invocation.mts index 34f81fe61fb..a293b76877c 100644 --- a/tools/e2e/live-vitest-invocation.mts +++ b/tools/e2e/live-vitest-invocation.mts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import path from "node:path"; import { pathToFileURL } from "node:url"; import * as importedProcessExit from "../../src/lib/core/process-exit.ts"; @@ -22,6 +23,7 @@ export const LIVE_TEST_ROOT = "test/e2e/live/"; export const RISK_SIGNAL_REPORTER = "test/e2e/risk-signal-reporter.ts"; export const MCP_BRIDGE_TEST_PATH = "test/e2e/live/mcp-bridge.test.ts"; export const INFERENCE_ROUTING_TEST_PATH = "test/e2e/live/inference-routing.test.ts"; +export const DGX_EXPRESS_TEST_PATH = "test/e2e/live/dgx-express.test.ts"; const SHELL_METACHARACTER = /[^A-Za-z0-9_./^$=:@+-]/u; const TEST_PATH_PATTERN = /^[A-Za-z0-9_./-]+$/u; @@ -115,7 +117,7 @@ export function validateLiveTestPath(testPath: string | undefined): string { if (!value.endsWith(".test.ts")) { throw new Error("test path must name a .test.ts file"); } - return value; + return path.posix.normalize(value); } export function validateLiveSelector(selector: string | undefined): string | undefined { @@ -133,6 +135,16 @@ export function resolveLiveSelector( env: NodeJS.ProcessEnv = process.env, ): string | undefined { const validated = validateLiveSelector(selector); + if (testPath === DGX_EXPRESS_TEST_PATH) { + const target = env.E2E_TARGET_ID; + if ( + (target !== "spark-express-vllm" && target !== "dgx-station-express") || + validated !== `^${target}:` + ) { + throw new Error("DGX Express requires an explicit selector matching E2E_TARGET_ID"); + } + return validated; + } if (testPath !== MCP_BRIDGE_TEST_PATH) return validated; // PR E2E executes trusted base-branch YAML with this helper from the diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index a19017ccf57..1ca2494b1f7 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -376,10 +376,10 @@ function validateManualPrDispatch(errors: string[], workflow: OperationsWorkflow } if ( workflow.concurrency?.["cancel-in-progress"] !== - "${{ inputs.checkout_sha != '' && !inputs.allow_jetson_dispatch && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable-identity,') && !inputs.include_staging_brev_launchable }}" + "${{ inputs.checkout_sha != '' && !inputs.allow_jetson_dispatch && !contains(format(',{0},{1},', inputs.jobs, inputs.targets), ',dgx-station-express,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable-identity,') && !inputs.include_staging_brev_launchable }}" ) { errors.push( - "Manual PR E2E concurrency must not cancel an active Jetson or Launchable dispatch", + "Manual PR E2E concurrency must not cancel an active hardware or Launchable dispatch", ); } @@ -649,8 +649,9 @@ function validateManualPrDispatch(errors: string[], workflow: OperationsWorkflow step.with?.repository === "${{ github.repository }}" && step.with?.ref === "${{ inputs.workflow_sha || github.workflow_sha }}"; const trustedJetsonControllerCheckout = - jobName === "jetson-nvmap-gpu" && - step.name === "Check out trusted Jetson controller" && + ((jobName === "jetson-nvmap-gpu" && step.name === "Check out trusted Jetson controller") || + (jobName === "dgx-station-express" && + step.name === "Check out trusted Station controller")) && step.with?.repository === "NVIDIA/NemoClaw" && step.with?.ref === "${{ github.workflow_sha }}"; const trustedOpenShellDevToolingCheckout = diff --git a/tools/e2e/prepare-e2e-workflow-boundary.mts b/tools/e2e/prepare-e2e-workflow-boundary.mts index 88f2a87ff6c..dd9df379df0 100644 --- a/tools/e2e/prepare-e2e-workflow-boundary.mts +++ b/tools/e2e/prepare-e2e-workflow-boundary.mts @@ -23,6 +23,7 @@ export const PREPARE_COMPILED_ARTIFACT_ACTION = const CHECKOUT_LOCAL_PREPARE_E2E_ACTION = "./.github/actions/prepare-e2e"; export const CLI_ARTIFACT_PRODUCER_JOB = E2E_JOB_POLICY.cliArtifactProducer; const PREINSTALLED_E2E_JOBS = new Set([ + "dgx-station-express", "staging-brev-launchable", "staging-brev-launchable-identity", ]); diff --git a/tools/e2e/upload-e2e-artifacts-workflow-boundary.mts b/tools/e2e/upload-e2e-artifacts-workflow-boundary.mts index 42d09b16b46..f3db3e6bb53 100644 --- a/tools/e2e/upload-e2e-artifacts-workflow-boundary.mts +++ b/tools/e2e/upload-e2e-artifacts-workflow-boundary.mts @@ -155,6 +155,13 @@ function isExactOpenShellSdkE2ePackageUpload(jobName: string, step: WorkflowStep } const EXPLICIT_UPLOAD_CONTRACTS = new Map([ + [ + "dgx-station-express", + { + name: "e2e-dgx-station-express", + path: "${{ runner.temp }}/e2e-artifacts/live/dgx-station-express/", + }, + ], [ "external-gateway-health", { diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 3cbc287849b..3fa8673d216 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { validateDgxStationDispatchBoundary } from "./dgx-station-workflow-boundary.mts"; import { createHash } from "node:crypto"; import { readFileSync, statSync } from "node:fs"; import { dirname, join, posix } from "node:path"; @@ -199,6 +200,7 @@ const COMMON_SECRET_ENV_NAMES = [ "GITHUB_TOKEN", ]; const FREE_STANDING_SELECTOR_SPECIAL_CASES = new Set([ + "dgx-station-express", "hermes-e2e", "hermes-gpu-startup", "jetson-nvmap-gpu", @@ -212,6 +214,7 @@ const FREE_STANDING_SELECTOR_SPECIAL_CASES = new Set([ const ADAPTER_MANAGED_INFERENCE_JOBS = new Set(["hermes-e2e"]); const PUBLIC_NVIDIA_ENDPOINT_KEY_JOBS = new Set(["model-router-provider-routed-inference"]); const NO_IMAGE_E2E_JOBS = new Set([ + "dgx-station-express", "external-gateway-health", "staging-brev-launchable", "staging-brev-launchable-identity", @@ -2104,7 +2107,7 @@ function validateFullE2eConcurrency(errors: string[], workflow: WorkflowRecord): } if ( concurrency["cancel-in-progress"] !== - "${{ inputs.checkout_sha != '' && !inputs.allow_jetson_dispatch && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable-identity,') && !inputs.include_staging_brev_launchable }}" + "${{ inputs.checkout_sha != '' && !inputs.allow_jetson_dispatch && !contains(format(',{0},{1},', inputs.jobs, inputs.targets), ',dgx-station-express,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable,') && !contains(format(',{0},', inputs.jobs), ',staging-brev-launchable-identity,') && !inputs.include_staging_brev_launchable }}" ) { errors.push("workflow concurrency must not cancel an active Jetson or Launchable dispatch"); } @@ -2965,6 +2968,7 @@ export function validateE2eWorkflow(workflowValue: unknown): string[] { errors.push("workflow run-name must expose the unique manual-dispatch correlation ID"); } errors.push(...validateJetsonDispatchBoundary(workflow)); + errors.push(...validateDgxStationDispatchBoundary(workflow)); const { errors: inventoryErrors, inventory: freeStandingInventory } = deriveFreeStandingJobsInventoryFromJobs(jobs); errors.push(...inventoryErrors); diff --git a/tools/e2e/workflow-plan.mts b/tools/e2e/workflow-plan.mts index 47d70c7db98..a6b2ce9443d 100644 --- a/tools/e2e/workflow-plan.mts +++ b/tools/e2e/workflow-plan.mts @@ -23,7 +23,10 @@ import { discoverCredentialFreeTests, SHARED_E2E_JOB_ID, } from "./credential-free-tests.mts"; -import { JETSON_DISPATCH_TARGET } from "./jetson-dispatch-contract.mts"; +import { + DGX_STATION_DISPATCH_TARGET, + JETSON_DISPATCH_TARGET, +} from "./jetson-dispatch-contract.mts"; import { normalizeE2eSelectorIds } from "./selector-aliases.mts"; import { catalogueExclusionReason, @@ -628,6 +631,16 @@ export function buildE2eWorkflowPlan( const jobs = selectorIds(selectors.jobs, "jobs"); const targets = selectorIds(selectors.targets, "targets"); + if ( + (jobs.includes(DGX_STATION_DISPATCH_TARGET) || targets.includes(DGX_STATION_DISPATCH_TARGET)) && + !( + (selectors.jobs === DGX_STATION_DISPATCH_TARGET && !selectors.targets) || + (selectors.targets === DGX_STATION_DISPATCH_TARGET && !selectors.jobs) + ) + ) { + throw new Error(`${DGX_STATION_DISPATCH_TARGET} must be selected by itself`); + } + if (jobs.includes(STAGING_BREV_IDENTITY_JOB_ID) && (jobs.length !== 1 || targets.length !== 0)) { throw new Error(`${STAGING_BREV_IDENTITY_JOB_ID} must be selected by itself`); } From 2e4e7a784cf14ca17d8fd37e2b59decdc3177eb6 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:17:49 -0700 Subject: [PATCH 061/133] test(inference): refresh exact Pi candidate evidence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index 23ea6e132f1..d1fce286c14 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:114ae8041bb6f30314b43ad6a3c42743e04e6f85976599284a883088dd6805da", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:114ae8041bb6f30314b43ad6a3c42743e04e6f85976599284a883088dd6805da", + "digest": "sha256:b69df8c58d699e7dc8f2f3a8f69e932d199dbb59727cee743353524522df996b", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:b69df8c58d699e7dc8f2f3a8f69e932d199dbb59727cee743353524522df996b", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "545faaf4d3850e8cac9b84d3871e1f4330c26d03", + "revision": "84310d56c636ef79a36343de83ad7964d5c916c6", "release": "v0.1.0", - "cohort": "ghrun-37415533463-1" + "cohort": "ghrun-37466954280-2" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index deb5276418d..0d5f396a7da 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:2e93cf9ce59285aaee78a1de1b4e720aa42f61f0ce7caca8f26fdea2b3817ed4", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:2e93cf9ce59285aaee78a1de1b4e720aa42f61f0ce7caca8f26fdea2b3817ed4", + "digest": "sha256:750fa9856065c40622a7a368f32627212fc94dbe0d32f60bbebb5b7a023a6d26", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:750fa9856065c40622a7a368f32627212fc94dbe0d32f60bbebb5b7a023a6d26", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "545faaf4d3850e8cac9b84d3871e1f4330c26d03", + "revision": "84310d56c636ef79a36343de83ad7964d5c916c6", "release": "v0.1.0", - "cohort": "ghrun-37415533463-1" + "cohort": "ghrun-37466954280-2" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 7e491b3f98b..28325ebdd4c 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "337feade80ea930da432cd5ab66cd490e850de54b1f7f222bd8656ad773d0c33", - "42da369db73a6a2a64bda23cfc464f2d4fea5a98e706e85d4c089d5ba6ad00ea", + "b1ad52cecebed3a0050a740904f522084830c42009a0940db836ecfc88b6e53d", + "7d7830526f5f4c5229fb14a7cf811b108df79c88902de70b0216ad1af8ccced6", ]), }); From 9f63f8f64bf31e65357b5066236141ad75b00912 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 08:10:26 -0700 Subject: [PATCH 062/133] fix(inference): clean up unowned NVIDIA provider Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/credentials-add.ts | 24 +++-- .../credentials-provider-adapter.test.ts | 18 ++-- .../inference-set-openclaw-run.test.ts | 68 +++++++++++++ src/lib/actions/inference-set.ts | 28 +++--- src/lib/inference/config.ts | 1 + src/lib/inference/native-nvidia.test.ts | 98 +++++++++++++++++++ src/lib/inference/native-nvidia/index.ts | 86 ++++++++++++++++ src/lib/onboard/setup-inference.test.ts | 86 ++++++++++++++++ src/lib/onboard/setup-inference.ts | 15 ++- 9 files changed, 389 insertions(+), 35 deletions(-) diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index d8290a19ee5..04152905933 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -21,6 +21,7 @@ import { NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, nativeNvidiaProviderProfilePath, + persistNativeNvidiaProviderAuthority, } from "../inference/native-nvidia"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, @@ -422,19 +423,16 @@ export async function runCredentialsAddAction( ...(expected ? { expected } : {}), }); if (!expected) { - try { - (deps.setNativeNvidiaProviderAuthority ?? setNativeNvidiaProviderAuthority)( - target.gatewayName, - receipt, - ); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - return fail([ - ` OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' was created, but NemoClaw could not record its ownership.`, - ` Run '${CLI_NAME} credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER} --yes' to remove the incomplete provider, then retry.`, - ` ${detail}`, - ]); - } + await persistNativeNvidiaProviderAuthority({ + adapter: providerAdapter, + target, + gatewayName: target.gatewayName, + receipt, + readAuthority: + deps.getNativeNvidiaProviderAuthority ?? getNativeNvidiaProviderAuthority, + writeAuthority: + deps.setNativeNvidiaProviderAuthority ?? setNativeNvidiaProviderAuthority, + }); } return ok([ ` Registered provider '${provider}' with the OpenShell gateway.`, diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 84e1e29704d..6162d9e999a 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -109,6 +109,10 @@ function nativeNvidiaProviderAdapter(): OpenShellProviderAdapter { providerPresent = true; return { ok: true as const }; }), + deleteProvider: vi.fn(async () => { + providerPresent = false; + return { ok: true as const }; + }), }); } @@ -205,7 +209,7 @@ describe("credential actions use typed OpenShell provider results", () => { expect(JSON.stringify(result)).not.toContain("host-only-nvidia-value"); }); - it("reports a reset action when native NVIDIA authority persistence fails", async () => { + it("removes the native NVIDIA provider when authority persistence fails", async () => { vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "host-only-nvidia-value"); const adapter = nativeNvidiaProviderAdapter(); @@ -227,13 +231,13 @@ describe("credential actions use typed OpenShell provider results", () => { ); expect(result.exitCode).toBe(1); - expect(result.failureLines).toContain( - " OpenShell provider 'nemoclaw-nvidia-prod-v1' was created, but NemoClaw could not record its ownership.", - ); - expect(result.failureLines).toContain( - " Run 'nemoclaw credentials reset nvidia-prod --yes' to remove the incomplete provider, then retry.", + expect(result.failureLines.join("\n")).toMatch( + /newly created provider was removed.*state directory is read-only/su, ); - expect(result.failureLines).toContain(" state directory is read-only"); + expect(adapter.deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: "nemoclaw-nvidia-prod-v1", + }); expect(JSON.stringify(result)).not.toContain("host-only-nvidia-value"); }); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index c89439db171..0eeac8220da 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -202,6 +202,74 @@ describe("runInferenceSet OpenClaw routing", () => { ); }); + it("removes a new native NVIDIA provider when authority persistence fails (#12562)", async () => { + const providerId = "22222222-3333-4444-8555-666666666666"; + let providerPresent = false; + const createProvider = vi.fn(async () => { + providerPresent = true; + return { ok: true }; + }); + const deleteProvider = vi.fn(async () => { + providerPresent = false; + return { ok: true }; + }); + const attachProvider = vi.fn(); + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true as const })), + getProvider: vi.fn(async () => + providerPresent + ? { + ok: true as const, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: providerId, resourceVersion: 1 }, + }, + } + : { + ok: false as const, + error: { + kind: "command" as const, + reason: "not_found" as const, + message: "provider not found", + }, + }, + ), + createProvider, + deleteProvider, + attachProvider, + } as unknown as OpenShellProviderAdapter; + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "gpt-5.4", + }, + getNativeNvidiaProviderAuthority: () => undefined, + setNativeNvidiaProviderAuthority: () => { + throw new Error("state directory is read-only"); + }, + providerAdapter, + resolveCredentialValue: () => "replacement-credential", + }); + + await expect( + runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps), + ).rejects.toThrow(/newly created provider was removed.*state directory is read-only/su); + + expect(deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: "nemoclaw-nvidia-prod-v1", + }); + expect(attachProvider).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + it("detaches native NVIDIA access only after another provider is healthy", async () => { let attached = true; const detachProvider = vi.fn(async () => { diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 719c7a30ded..3f8abeb00b3 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -19,6 +19,7 @@ import { isNativeNvidiaProvider, NVIDIA_HOSTED_CREDENTIAL_ENV, normalizeNativeNvidiaProviderAttachment, + persistNativeNvidiaProviderAuthority, resolveGatewayNativeNvidiaProviderAuthority, resolveAgentInferenceApi, type NativeNvidiaProviderAttachment, @@ -969,6 +970,19 @@ async function prepareNativeNvidiaSelection(input: { credentialValue: input.deps.resolveCredentialValue(NVIDIA_HOSTED_CREDENTIAL_ENV) || null, ...(input.expectedAttachment ? { expected: input.expectedAttachment } : {}), }); + if (input.deps.getNativeNvidiaProviderAuthority) { + await persistNativeNvidiaProviderAuthority({ + adapter: input.deps.providerAdapter, + target, + gatewayName: input.gatewayName, + receipt: ensured, + ...(input.expectedAttachment ? { existing: input.expectedAttachment } : {}), + readAuthority: input.deps.getNativeNvidiaProviderAuthority, + writeAuthority: input.deps.setNativeNvidiaProviderAuthority, + }); + } else { + input.deps.setNativeNvidiaProviderAuthority(input.gatewayName, ensured); + } const attached = await ensureNativeNvidiaProviderAttached({ adapter: input.deps.providerAdapter, target, @@ -1026,15 +1040,6 @@ function nativeNvidiaDepartureRegistryFields( return detached ? { nativeNvidiaProviderAttachment: undefined } : {}; } -function recordNativeNvidiaProviderAuthority(input: { - attachment?: NativeNvidiaProviderAttachment; - gatewayName: string; - deps: InferenceSetDeps; -}): void { - if (!input.attachment) return; - input.deps.setNativeNvidiaProviderAuthority(input.gatewayName, input.attachment); -} - async function restorePreviousNativeNvidiaAfterFailedPublish(input: { detached: boolean; committed: boolean; @@ -1616,11 +1621,6 @@ async function runInferenceSetWithoutHostLock( }); nativeNvidiaProviderAttachment = nativeNvidiaSelection.attachment; nativeNvidiaAttachmentChanged = nativeNvidiaSelection.attachmentChanged; - recordNativeNvidiaProviderAuthority({ - attachment: nativeNvidiaProviderAttachment, - gatewayName: preparedRoute.gatewayName, - deps, - }); const providerBinding = httpsPinProviderBinding ?? directProviderBinding; if (providerBinding) { providerMutation = await prepareInferenceSetProviderBinding({ diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index d4e9e370405..5717a26480e 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -30,6 +30,7 @@ export { NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_ENDPOINT, normalizeNativeNvidiaProviderAttachment, + persistNativeNvidiaProviderAuthority, resolveGatewayNativeNvidiaProviderAuthority, } from "./native-nvidia"; export type { NativeNvidiaProviderAttachment } from "./native-nvidia"; diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index 0b248f47b2d..8a0a2865928 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -10,10 +10,12 @@ import { ensureNativeNvidiaProvider, ensureNativeNvidiaProviderAttached, nativeNvidiaProviderProfilePath, + type NativeNvidiaProviderAttachment, NativeNvidiaProviderError, NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, + persistNativeNvidiaProviderAuthority, verifyNativeNvidiaProviderAttachment, } from "./native-nvidia"; @@ -108,6 +110,102 @@ describe("native NVIDIA OpenShell provider", () => { ); }); + it("removes a new provider when authority persistence fails (#12562)", async () => { + let providerPresent = true; + const getProvider = vi.fn(async () => + providerPresent + ? { ok: true, value: metadata() } + : { + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }, + ); + const deleteProvider = vi.fn(async () => { + providerPresent = false; + return { ok: true }; + }); + const receipt = { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + } as const; + + await expect( + persistNativeNvidiaProviderAuthority({ + adapter: adapter({ getProvider, deleteProvider }), + target, + gatewayName: "nemoclaw", + receipt, + readAuthority: () => undefined, + writeAuthority: () => { + throw new Error("state directory is read-only"); + }, + }), + ).rejects.toThrow(/newly created provider was removed.*state directory is read-only/su); + expect(deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }); + }); + + it("keeps a provider when a failed write persisted its authority (#12562)", async () => { + const receipt = { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + } as const; + let authority: NativeNvidiaProviderAttachment | undefined; + const deleteProvider = vi.fn(); + + await expect( + persistNativeNvidiaProviderAuthority({ + adapter: adapter({ deleteProvider }), + target, + gatewayName: "nemoclaw", + receipt, + readAuthority: () => authority, + writeAuthority: (_gatewayName, value) => { + authority = value; + throw new Error("directory sync failed"); + }, + }), + ).resolves.toBeUndefined(); + expect(deleteProvider).not.toHaveBeenCalled(); + }); + + it("refuses cleanup when the provider identity changed after a failed write (#12562)", async () => { + const deleteProvider = vi.fn(); + + await expect( + persistNativeNvidiaProviderAuthority({ + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ + revision: { id: "replacement-id", resourceVersion: 2 }, + }), + })), + deleteProvider, + }), + target, + gatewayName: "nemoclaw", + receipt: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + }, + readAuthority: () => undefined, + writeAuthority: () => { + throw new Error("state directory is read-only"); + }, + }), + ).rejects.toThrow(/credentials reset nvidia-prod.*identity changed/su); + expect(deleteProvider).not.toHaveBeenCalled(); + }); + it("observes an ambiguous create result without issuing a second mutation (#12558)", async () => { const getProvider = vi .fn() diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index e07cdc4e170..2b062a53479 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -127,6 +127,92 @@ function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { ); } +function authorityPersistenceRecovery(gatewayName: string): string { + return `Run 'nemoclaw credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER} --yes' against gateway '${gatewayName}', then retry.`; +} + +async function removeNewNativeNvidiaProvider(input: { + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + expected: NativeNvidiaProviderAttachment; +}): Promise { + const provider = await inspectNativeProvider(input.adapter, input.target); + if (!provider) return; + const current = attachmentFromMetadata(provider); + if (current.providerId !== input.expected.providerId) { + throw new NativeNvidiaProviderError( + `Refusing to remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, + ); + } + const removed = await input.adapter.deleteProvider({ + target: input.target, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }); + if (!removed.ok && !mutationOutcomeMayBeAmbiguous(removed.error)) { + throw new NativeNvidiaProviderError( + `Could not remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(removed.error)}`, + ); + } + const after = await inspectNativeProvider(input.adapter, input.target); + if (after) { + const observed = attachmentFromMetadata(after); + const identity = + observed.providerId === input.expected.providerId ? "still exists" : "changed identity"; + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' ${identity} after cleanup.`, + ); + } +} + +/** Record provider authority or remove only the new, unreferenced provider. */ +export async function persistNativeNvidiaProviderAuthority(input: { + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + gatewayName: string; + receipt: NativeNvidiaProviderAttachment; + existing?: NativeNvidiaProviderAttachment; + readAuthority: (gatewayName: string) => NativeNvidiaProviderAttachment | undefined; + writeAuthority: (gatewayName: string, receipt: NativeNvidiaProviderAttachment) => void; +}): Promise { + try { + input.writeAuthority(input.gatewayName, input.receipt); + return; + } catch (writeError) { + const writeDetail = writeError instanceof Error ? writeError.message : String(writeError); + let observed: NativeNvidiaProviderAttachment | undefined; + try { + observed = input.readAuthority(input.gatewayName); + } catch (readError) { + const readDetail = readError instanceof Error ? readError.message : String(readError); + throw new NativeNvidiaProviderError( + `NemoClaw could not record or confirm ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Read failure: ${readDetail}`, + ); + } + if (observed?.providerId === input.receipt.providerId) return; + if (input.existing || observed) { + throw new NativeNvidiaProviderError( + `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained because this operation cannot prove that it is unreferenced. ${authorityPersistenceRecovery(input.gatewayName)}\n ${writeDetail}`, + ); + } + try { + await removeNewNativeNvidiaProvider({ + adapter: input.adapter, + target: input.target, + expected: input.receipt, + }); + } catch (cleanupError) { + const cleanupDetail = + cleanupError instanceof Error ? cleanupError.message : String(cleanupError); + throw new NativeNvidiaProviderError( + `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}', and cleanup did not complete. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Cleanup failure: ${cleanupDetail}`, + ); + } + throw new NativeNvidiaProviderError( + `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The newly created provider was removed. Retry the command.\n ${writeDetail}`, + ); + } +} + /** Ensure the least-privilege NVIDIA profile and provider without retrying an ambiguous mutation. */ export async function ensureNativeNvidiaProvider(input: { adapter: OpenShellProviderAdapter; diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index ba712108fe5..f3d8d98803d 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -298,6 +298,92 @@ describe("native NVIDIA onboarding", () => { }); }); + it("removes a new provider when gateway authority persistence fails (#12562)", async () => { + let providerPresent = false; + const getProvider = vi.fn(async () => + providerPresent + ? { + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 4 }, + }, + } + : { + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }, + ); + const deleteProvider = vi.fn(async () => { + providerPresent = false; + return { ok: true }; + }); + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true as const })), + getProvider, + createProvider: vi.fn(async () => { + providerPresent = true; + return { ok: true as const }; + }), + deleteProvider, + } as unknown as OpenShellProviderAdapter; + const updateSandbox = vi.fn(() => true); + const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); + const setupInference = createSetupInference({ + checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), + withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => + await operation(), + step: vi.fn(), + getGatewayName: () => "onboarding-gateway", + runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), + updateSandbox, + getSandbox: () => null, + getNativeNvidiaProviderAuthority: () => undefined, + setNativeNvidiaProviderAuthority: () => { + throw new Error("state directory is read-only"); + }, + upsertProvider: vi.fn(async () => ({ ok: true })), + verifyInferenceRoute: vi.fn(), + verifyOnboardInferenceSmoke, + isNonInteractive: () => true, + hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, + providerAdapter, + hydrateCredentialEnv: vi.fn(() => "host-only-nvidia-credential"), + redact: (value: string) => value, + compactText: (value: string) => value, + log: vi.fn(), + error: vi.fn(), + exitProcess: vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }), + } as unknown as SetupInferenceDeps); + + await expect( + setupInference( + "alpha", + "nvidia/nemotron-3-super-120b-a12b", + "nvidia-prod", + "https://integrate.api.nvidia.com/v1", + "NVIDIA_INFERENCE_API_KEY", + null, + [], + { revalidateSandboxIdentity: () => undefined }, + ), + ).rejects.toThrow(/newly created provider was removed.*state directory is read-only/su); + + expect(deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "onboarding-gateway" }, + providerName: "nemoclaw-nvidia-prod-v1", + }); + expect(updateSandbox).not.toHaveBeenCalled(); + expect(verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); + }); + it("reuses a gateway-owned provider for a fresh second sandbox", async () => { const importProviderProfile = vi.fn(async () => ({ ok: true as const })); const getProvider = vi.fn(async () => ({ diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index fcfbf536b5b..bc6d98c1bad 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -25,6 +25,7 @@ import { isNativeNvidiaProvider, NVIDIA_HOSTED_CREDENTIAL_ENV, normalizeNativeNvidiaProviderAttachment, + persistNativeNvidiaProviderAuthority, resolveGatewayNativeNvidiaProviderAuthority, type NativeNvidiaProviderAttachment, } from "../inference/native-nvidia"; @@ -995,7 +996,19 @@ export function createSetupInference( reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, ...(providerAuthority ? { expected: providerAuthority } : {}), }); - deps.setNativeNvidiaProviderAuthority?.(gatewayName, nativeNvidiaProviderAttachment); + if (deps.getNativeNvidiaProviderAuthority && deps.setNativeNvidiaProviderAuthority) { + await persistNativeNvidiaProviderAuthority({ + adapter: providerAdapter, + target: { kind: "named", gatewayName }, + gatewayName, + receipt: nativeNvidiaProviderAttachment, + ...(providerAuthority ? { existing: providerAuthority } : {}), + readAuthority: deps.getNativeNvidiaProviderAuthority, + writeAuthority: deps.setNativeNvidiaProviderAuthority, + }); + } else { + deps.setNativeNvidiaProviderAuthority?.(gatewayName, nativeNvidiaProviderAttachment); + } return null; } From e66692f405d884b6683e27bfe3bcfd84666aa413 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:54:36 -0700 Subject: [PATCH 063/133] test(inference): use stable cloud fixture Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/inference-set-local-provider.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/actions/inference-set-local-provider.test.ts b/src/lib/actions/inference-set-local-provider.test.ts index fd2f6acdbd9..e82d02b0272 100644 --- a/src/lib/actions/inference-set-local-provider.test.ts +++ b/src/lib/actions/inference-set-local-provider.test.ts @@ -96,7 +96,7 @@ describe("runInferenceSet local-provider verification", () => { session: baseSession(), }); - await runInferenceSet({ provider: "openrouter", model: "openai/gpt-5.4-mini" }, deps); + await runInferenceSet({ provider: "openai-api", model: "gpt-5.4-mini" }, deps); expect(deps.calls.validateLocalProvider).not.toHaveBeenCalled(); expect(deps.calls.ensureLocalProviderReachable).not.toHaveBeenCalled(); From 15d8bc09ca870193ecffafd5ba28d0e5cd821cf0 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 12:13:22 -0700 Subject: [PATCH 064/133] test(inference): refresh exact Pi candidate evidence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index d1fce286c14..cd9e6b7bcd6 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:b69df8c58d699e7dc8f2f3a8f69e932d199dbb59727cee743353524522df996b", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:b69df8c58d699e7dc8f2f3a8f69e932d199dbb59727cee743353524522df996b", + "digest": "sha256:6e4b97ebf390aaae3e350fda1bb4e8cf3b7ccb918376f2bd431884af5800a9cc", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:6e4b97ebf390aaae3e350fda1bb4e8cf3b7ccb918376f2bd431884af5800a9cc", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "84310d56c636ef79a36343de83ad7964d5c916c6", + "revision": "fd70900cedb01b9ced93626f190002581a0aa356", "release": "v0.1.0", - "cohort": "ghrun-37466954280-2" + "cohort": "ghrun-37515304733-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 0d5f396a7da..24533c750f3 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:750fa9856065c40622a7a368f32627212fc94dbe0d32f60bbebb5b7a023a6d26", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:750fa9856065c40622a7a368f32627212fc94dbe0d32f60bbebb5b7a023a6d26", + "digest": "sha256:568792426862e7264e0ea23d1708373e8c8885cf66f7c50000bbf433f1c9f277", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:568792426862e7264e0ea23d1708373e8c8885cf66f7c50000bbf433f1c9f277", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "84310d56c636ef79a36343de83ad7964d5c916c6", + "revision": "fd70900cedb01b9ced93626f190002581a0aa356", "release": "v0.1.0", - "cohort": "ghrun-37466954280-2" + "cohort": "ghrun-37515304733-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 28325ebdd4c..540e421fc89 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "b1ad52cecebed3a0050a740904f522084830c42009a0940db836ecfc88b6e53d", - "7d7830526f5f4c5229fb14a7cf811b108df79c88902de70b0216ad1af8ccced6", + "127792f62117e69dd8f5c05ba4fb2e5b8f5a087905c2c777db1ee64ac29b845c", + "9b9fdace49624f4e36d9e7b1c4ec4b775fe260d85388c038b28127f4a5aa9bf2", ]), }); From e83f98964650eeb43f08a41e70eb5ff16fbc0b95 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 12:46:59 -0700 Subject: [PATCH 065/133] test(inference): enable fixed hosted provider qualification --- ci/e2e-assertion-budget.json | 14 +- ci/e2e-assertion-growth-exceptions.json | 12 +- test/e2e/README.md | 44 +++++ .../live/hermes-inference-switch-helpers.ts | 119 +++++++++++- test/e2e/live/hermes-inference-switch.test.ts | 40 ++-- ...mes-inference-switch-command-shape.test.ts | 175 +++++++++++++++++- 6 files changed, 356 insertions(+), 48 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index b579f8bc899..3fb50f985c5 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,24 +15,24 @@ "testFileCount": 77, "liveFileCount": 184, "direct": { - "expectCalls": 1241, - "matcherAssertions": 1220, + "expectCalls": 1239, + "matcherAssertions": 1218, "nodeAssertions": 104, "namedAssertionHelpers": 426, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 166, - "assertionPoints": 1966, + "assertionPoints": 1964, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1666, - "matcherAssertions": 1640, + "expectCalls": 1664, + "matcherAssertions": 1638, "nodeAssertions": 127, "namedAssertionHelpers": 671, "failCalls": 1, - "throwGuards": 528, + "throwGuards": 530, "objectFieldAssertions": 243, "assertionPoints": 3210, "generatedProbeBlocks": 208, @@ -68,7 +68,7 @@ "test/e2e/live/hermes-discord.test.ts": [10,25,17,64,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,77,1], + "test/e2e/live/hermes-inference-switch.test.ts": [44,50,55,77,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index d472223a346..4509ab4cdc3 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nPR #12593 preserves two necessary fail-closed guards: an explicit vendor model before fixed hosted qualification and a manual Nous credential before external registration. Two incidental success/error wording assertions are removed; unique total assertion points and Hermes transitive assertion points remain unchanged, while unique throwGuards increase by two. Budget increase approved by Aaron Erickson (@ericksoa): https://nvidia.slack.com/archives/C0B1FQ51FP0/p1791301358361059. Entries bind the current local comparison and stacked PR base budget bytes to this exact candidate budget. Approval does not waive the independent trusted-base check; the exception must reach its trusted policy or that specific failure needs separate explicit maintainer disposition. Changed budget bytes invalidate the corresponding entry. Remove after #12593 merges.", "schemaVersion": 1, "exceptions": [ { @@ -11,6 +11,16 @@ "pullRequest": 12305, "baseBudgetSha256": "375c8f76724ccade48d8bbaafddc582984270350f95efde51211b0ff973a9dbe", "headBudgetSha256": "a2950bb3b5be2ba76071f3956b8a9a30fb4f3877308542c3947cea3821bfdf28" + }, + { + "pullRequest": 12593, + "baseBudgetSha256": "d0a41e5514e5cc2f7bb34d7604c82106d9e36239f1abf5859e343c7733501289", + "headBudgetSha256": "bda0267c094710272fd2a02ed05c26a2e93e5a78c81fcdb9d4d9a338e342914a" + }, + { + "pullRequest": 12593, + "baseBudgetSha256": "fdc4a78b5588629e26b00778d1bc82d69101077b9e372f2b58670510184579c2", + "headBudgetSha256": "bda0267c094710272fd2a02ed05c26a2e93e5a78c81fcdb9d4d9a338e342914a" } ] } diff --git a/test/e2e/README.md b/test/e2e/README.md index 8d57f53f871..9d9150eaf94 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1022,6 +1022,50 @@ completed onboarding session remains unchanged as historical onboarding evidence. Deterministic startup and action tests own the corresponding launch environment and session non-rewrite checks. +For explicit Slice 2 qualification, reuse this live owner with +`NEMOCLAW_SWITCH_PROVIDER` and a required `NEMOCLAW_SWITCH_MODEL` supported by that +provider. Use the canonical model ID returned by that vendor (a versioned ID +where supported): the existing raw/API checks require exact response-model +equality, so a rolling alias that returns a different model ID is unsuitable. +This manual selection does not change the scheduled catalogue's NVIDIA +or compatible-Anthropic scenarios. On an approved, disposable E2E host with a disposable gateway, supply the +selected credential through the existing environment/secret delivery boundary, +then invoke the existing runner (shown here for OpenAI; set the model separately): + +```bash +NEMOCLAW_SWITCH_PROVIDER=openai-api NEMOCLAW_RUN_LIVE_E2E=1 \ + npx tsx tools/e2e/live-vitest-invocation.mts run \ + --test-path test/e2e/live/hermes-inference-switch.test.ts +``` + +| Provider selection | Wire contract | Required environment credential | +| --- | --- | --- | +| `openai-api` | OpenAI chat completions, bearer key | `OPENAI_API_KEY` | +| `anthropic-prod` | Anthropic Messages, key and version header | `ANTHROPIC_API_KEY` | +| `gemini-api` | Existing OpenAI-compatible Gemini surface | `GEMINI_API_KEY` | +| `openrouter-api` | OpenAI-compatible with required Referer/Title headers | `OPENROUTER_API_KEY` | +| `hermes-provider` | OpenAI-compatible, manual Nous key registration | `NOUS_API_KEY` | + +These are application environment bindings, not approved GitHub repository secret +mappings. Credential provisioning and a supported account model remain external +prerequisites. Hermes Provider registers the manual Nous key once through +`credentials add`; only that command maps it into the profile's physical +`OPENAI_API_KEY` binding. The later switch consumes its owned registration. OAuth +qualification remains separate and is not established by this manual-key scenario. Do not run this owner against a personal or shared gateway: it pre-cleans and +tears down its sandbox and removes the named gateway registration. Sandbox +destroy only deletes sandbox-owned messaging/search providers; native inference +providers are shared gateway resources. Cleanup command success does not separately +prove deletion of each provider. After a failed registration/attachment, retain +and inspect the existing command artifacts and persisted ownership state before +reclaiming the disposable gateway; do not delete a provider by name alone. + +Fixed non-NVIDIA selections install against an authenticated local baseline fixture, +so an unrelated NVIDIA credential is unnecessary. The subsequent raw request, +Hermes API request, and Hermes CLI request still reach the selected real vendor; +a mock baseline is not evidence of vendor success. Select one scenario at a time +for each required protocol/credential shape; no provider-by-platform matrix or new +scheduled jobs are introduced. + ## Native plugin and package lifecycle Issue #11766 retired the dedicated `openclaw-plugin-runtime-exdev` workflow job diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index 5f39f8af1a2..5d9959cda99 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + resolveMaxTokensField, + resolveProbeReplyTokens, +} from "../../../src/lib/inference/max-tokens-field.ts"; import { nativeInferenceProbeAuthScript } from "../../../src/lib/inference/probe/native-inference-probe-auth.ts"; import fs from "node:fs"; import http from "node:http"; @@ -70,6 +74,31 @@ const USE_COMPATIBLE_HOSTED = process.env.NEMOCLAW_E2E_USE_HOSTED_INFERENCE === export const SWITCH_PROVIDER = process.env.NEMOCLAW_SWITCH_PROVIDER ?? PUBLIC_NVIDIA_SWITCH_PROVIDER; export const SWITCH_MODEL = process.env.NEMOCLAW_SWITCH_MODEL ?? PUBLIC_NVIDIA_SWITCH_MODEL; +// Explicit manual qualification reuses this owner; it does not add scheduled targets. +export function fixedHostedSwitchScenario(runtimeEnv: NodeJS.ProcessEnv = process.env) { + const provider = runtimeEnv.NEMOCLAW_SWITCH_PROVIDER; + if ( + !provider || + !["openai-api", "anthropic-prod", "gemini-api", "openrouter-api", "hermes-provider"].includes( + provider, + ) + ) + return null; + const model = runtimeEnv.NEMOCLAW_SWITCH_MODEL?.trim(); + if (!model) + throw new Error( + "Fixed hosted qualification requires NEMOCLAW_SWITCH_MODEL for the selected provider", + ); + const profile = nativeHostedProfile(provider)!; + return { + provider, + model, + credentialEnv: provider === "hermes-provider" ? "NOUS_API_KEY" : profile.credentialEnv, + protocol: provider === "anthropic-prod" ? "anthropic-messages" : "openai-completions", + manualRegistration: provider === "hermes-provider", + }; +} + export const SWITCH_API = process.env.NEMOCLAW_SWITCH_INFERENCE_API ?? "openai-completions"; export const RUNTIME_SWITCH_API = SWITCH_PROVIDER === "anthropic-prod" @@ -313,7 +342,10 @@ export function parseHermesModelBlock(text: string): Record { return model; } -export function parseInferenceRoute(text: string): { provider: string; model: string } { +export function parseInferenceRoute(text: string): { + provider: string; + model: string; +} { const plain = stripAnsi(text); const provider = plain.match(/^\s*Provider:\s*(.*?)\s*$/mu)?.[1]?.trim() ?? ""; const model = plain.match(/^\s*Model:\s*(.*?)\s*$/mu)?.[1]?.trim() ?? ""; @@ -407,7 +439,10 @@ export async function runHermesPongWithRetry( return { outcome: "failed", failureClass: "deterministic" }; } if (value.passed) return { outcome: "passed" }; - return { outcome: "failed", failureClass: hermesProbeFailureClass(value.result) }; + return { + outcome: "failed", + failureClass: hermesProbeFailureClass(value.result), + }; }, }); if (execution.value) return execution.value.result; @@ -509,7 +544,10 @@ async function startMockAnthropicProvider(): Promise { - const payload = JSON.parse(raw || "{}") as { model?: unknown; stream?: unknown }; + const payload = JSON.parse(raw || "{}") as { + model?: unknown; + stream?: unknown; + }; const model = typeof payload.model === "string" ? payload.model : "mock-anthropic-model"; if (isOpenAiChatCompletions) { if (payload.stream === true) { @@ -543,7 +581,11 @@ async function startMockAnthropicProvider(): Promise; session: Record } { +export function registryState(): { + registry: Record; + session: Record; +} { return { registry: JSON.parse( fs.readFileSync(path.join(os.homedir(), ".nemoclaw", "sandboxes.json"), "utf8"), diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index c61f27e1a00..f9582808357 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -29,11 +29,12 @@ import { hermesGatewayPid, hostedInstallModel, sandboxInferenceCommand, - inferenceLocalMaxTokens, + sandboxInferencePayload, installHermes, maybeAssertEnvHashStable, maybeAssertPidStable, mockAnthropicSwitchEnabled, + fixedHostedSwitchScenario, PROXY_FORBIDDEN_MARKERS, PROXY_RESOLUTION_PROVIDER, parseHermesModelBlock, @@ -85,6 +86,7 @@ test( }, }, async ({ artifacts, cleanup, host, progress, runtimeProvider, sandbox, secrets }) => { + const fixedScenario = fixedHostedSwitchScenario(); await artifacts.target.declare({ id: "hermes-inference-switch", boundary: @@ -123,18 +125,19 @@ test( // OpenShell reaches this fixture from its gateway network namespace, where // the runner's loopback address is not routable. - const mockBaseline = mockAnthropicSwitchEnabled() - ? await startFakeOpenAiCompatibleServer({ - apiKey: MOCK_BASELINE_API_KEY, - chatContent: "PONG", - forbiddenMarkers: PROXY_FORBIDDEN_MARKERS, - host: "0.0.0.0", - model: MOCK_BASELINE_MODEL, - publicHost: "host.openshell.internal", - progress, - requireAuth: true, - }) - : undefined; + const mockBaseline = + fixedScenario || mockAnthropicSwitchEnabled() + ? await startFakeOpenAiCompatibleServer({ + apiKey: MOCK_BASELINE_API_KEY, + chatContent: "PONG", + forbiddenMarkers: PROXY_FORBIDDEN_MARKERS, + host: "0.0.0.0", + model: MOCK_BASELINE_MODEL, + publicHost: "host.openshell.internal", + progress, + requireAuth: true, + }) + : undefined; cleanup.trackDisposable("close Hermes inference switch baseline fixture", async () => { await artifacts.writeJson( "baseline-openai-compatible-requests.json", @@ -148,7 +151,8 @@ test( : null; const nativeProfile = nativeHostedProfile(SWITCH_PROVIDER); const nativeProviderApiKey = nativeProfile - ? (publicApiKey ?? secrets.required(nativeProfile.credentialEnv)) + ? (publicApiKey ?? + secrets.required(fixedScenario?.credentialEnv ?? nativeProfile.credentialEnv)) : null; const apiKey = mockBaseline ? MOCK_BASELINE_API_KEY @@ -212,8 +216,6 @@ test( }, ); expect(switched.exitCode, resultText(switched)).toBe(0); - expect(resultText(switched)).not.toContain("writing the in-sandbox config failed"); - expect(resultText(switched)).toContain(`Inference route synced for '${SANDBOX_NAME}'`); switchBinding && (await expectOpenAiProvider( host, @@ -363,11 +365,7 @@ test( ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.nimContainer).toBeNull(); progress.phase("exercise sandbox inference and Hermes API"); - const inferenceLocalPayload = JSON.stringify({ - model: SWITCH_MODEL, - messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], - max_tokens: inferenceLocalMaxTokens(), - }); + const inferenceLocalPayload = sandboxInferencePayload(); const inferenceLocal = await runHermesPongWithRetry({ expectedModel: SWITCH_MODEL, onEvidence: async (evidence) => { 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 8aa3e4aaa91..c718a1cbb31 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -281,7 +281,11 @@ describe("Hermes inference switch command shape", () => { stderr: "", stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n", }) - .mockResolvedValueOnce({ exitCode: 0, stderr: "", stdout: "route synced" }); + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "route synced", + }); await prepareProxyResolutionRoute({ apiKey: "hosted-key", @@ -392,7 +396,10 @@ describe("Hermes inference switch command shape", () => { }), ).toBe(false); expect( - mockAnthropicSwitchEnabled({ ...mockAnthropic, NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "0" }), + mockAnthropicSwitchEnabled({ + ...mockAnthropic, + NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "0", + }), ).toBe(false); expect(mockAnthropicSwitchEnabled({})).toBe(false); }); @@ -497,7 +504,11 @@ describe("Hermes inference switch command shape", () => { path: string; }> = []; const baseline = { requests: () => requests }; - const result = { exitCode: 0, stderr: "", stdout: "PONG\n" } as ShellProbeResult; + const result = { + exitCode: 0, + stderr: "", + stdout: "PONG\n", + } as ShellProbeResult; const authenticatedRequest = (model: string) => ({ auth: "ok", authorizationSent: true, @@ -544,7 +555,11 @@ describe("Hermes inference switch command shape", () => { failureClass: "transient-external", retryScheduled: true, }), - expect.objectContaining({ attempt: 2, outcome: "passed", retryScheduled: false }), + expect.objectContaining({ + attempt: 2, + outcome: "passed", + retryScheduled: false, + }), ], }), ); @@ -567,13 +582,22 @@ describe("Hermes inference switch command shape", () => { )( "does not accept or retry a CLI PONG with %s and %s", async (_routeState, message, accepted, failureClass) => { - const result = { exitCode: 0, stderr: message, stdout: "PONG\n" } as ShellProbeResult; + const result = { + exitCode: 0, + stderr: message, + stdout: "PONG\n", + } as ShellProbeResult; const run = vi.fn().mockResolvedValue(result); const delay = vi.fn().mockResolvedValue(undefined); const onEvidence = vi.fn().mockResolvedValue(undefined); await expect( - runHermesCliPongWithRetry({ accept: () => accepted, delay, onEvidence, run }), + runHermesCliPongWithRetry({ + accept: () => accepted, + delay, + onEvidence, + run, + }), ).resolves.toBe(result); expect(run).toHaveBeenCalledOnce(); expect(delay).not.toHaveBeenCalled(); @@ -726,7 +750,11 @@ describe("Hermes inference switch command shape", () => { stderr: "failed to verify inference endpoint: timeout", stdout: "", }) - .mockResolvedValueOnce({ exitCode: 0, stderr: "", stdout: "route synced" }); + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "route synced", + }); const writeJson = vi.fn().mockResolvedValue("inference-switch-retry-evidence.json"); await expect( @@ -779,7 +807,6 @@ describe("native provider switch credential isolation", () => { ["anthropic-prod", "ANTHROPIC_API_KEY"], ["gemini-api", "GEMINI_API_KEY"], ["openrouter-api", "OPENROUTER_API_KEY"], - ["hermes-provider", "OPENAI_API_KEY"], ])("passes only the selected credential binding for %s", async (provider, credentialEnv) => { vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", provider); vi.resetModules(); @@ -799,6 +826,8 @@ describe("native provider switch credential isolation", () => { [credentialEnv, credential], ]); expect(options.redactionValues).toContain(credential); + expect(command).toHaveBeenCalledOnce(); + const proxyCommand = vi .fn() .mockResolvedValueOnce({ exitCode: 0, stdout: "created", stderr: "" }) @@ -807,7 +836,11 @@ describe("native provider switch credential isolation", () => { stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n", stderr: "", }) - .mockResolvedValueOnce({ exitCode: 0, stdout: "route synced", stderr: "" }); + .mockResolvedValueOnce({ + exitCode: 0, + stdout: "route synced", + stderr: "", + }); const proxy = await helpers.prepareProxyResolutionRoute({ apiKey: "fixture-baseline-key", host: { command: proxyCommand } as unknown as HostCliClient, @@ -820,3 +853,127 @@ describe("native provider switch credential isolation", () => { ); }); }); + +describe("fixed hosted qualification selection", () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); + }); + + it.each([ + ["openai-api", "OPENAI_API_KEY", "openai-completions"], + ["anthropic-prod", "ANTHROPIC_API_KEY", "anthropic-messages"], + ["gemini-api", "GEMINI_API_KEY", "openai-completions"], + ["openrouter-api", "OPENROUTER_API_KEY", "openai-completions"], + ["hermes-provider", "NOUS_API_KEY", "openai-completions"], + ])( + "selects %s with an explicit vendor model and its logical credential", + async (provider, credentialEnv, protocol) => { + const { fixedHostedSwitchScenario } = + await import("../live/hermes-inference-switch-helpers.ts"); + expect(() => fixedHostedSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: provider })).toThrow( + "NEMOCLAW_SWITCH_MODEL", + ); + expect( + fixedHostedSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: provider, + NEMOCLAW_SWITCH_MODEL: "vendor-model", + }), + ).toEqual({ + provider, + model: "vendor-model", + credentialEnv, + protocol, + manualRegistration: provider === "hermes-provider", + }); + expect(fixedHostedSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod" })).toBeNull(); + expect( + fixedHostedSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", + }), + ).toBeNull(); + }, + ); + + it("registers the manual Hermes credential once before switching without a new key", async () => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "hermes-provider"); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + const command = vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + const credential = "manual-nous-fixture"; + await helpers.runHermesInferenceSetWithRetry({ command } as unknown as HostCliClient, [], [], { + attempts: 1, + nativeProviderApiKey: credential, + }); + expect(command).toHaveBeenCalledTimes(2); + const [executable, args, options] = command.mock.calls[0]!; + expect(executable).toBe("node"); + expect(args).toEqual([ + helpers.CLI, + "credentials", + "add", + "hermes-provider", + "--type", + "openai", + "--credential", + "OPENAI_API_KEY", + ]); + expect(args).not.toContain(credential); + expect(Object.entries(options.env).filter(([, value]) => value === credential)).toEqual([ + ["OPENAI_API_KEY", credential], + ]); + expect(options.redactionValues).toContain(credential); + expect(command.mock.calls[1]?.[1]).toContain("set"); + expect(command.mock.calls[1]?.[2].env.OPENAI_API_KEY).toBeUndefined(); + }); + + it("does not switch or retry after failed manual Hermes registration", async () => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "hermes-provider"); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + const failure = { + exitCode: 1, + stdout: "", + stderr: "registration unavailable", + }; + const command = vi.fn().mockResolvedValue(failure); + expect( + await helpers.runHermesInferenceSetWithRetry( + { command } as unknown as HostCliClient, + [], + [], + { + attempts: 3, + nativeProviderApiKey: "manual-nous-fixture", + }, + ), + ).toBe(failure); + expect(command).toHaveBeenCalledOnce(); + expect(command.mock.calls[0]?.[2].redactionValues).toContain("manual-nous-fixture"); + expect(command.mock.calls[0]?.[1]).not.toContain("manual-nous-fixture"); + }); +}); + +it.each(["gpt-5.4", "gpt-6", "openai/o3"])( + "uses the shared raw probe token field for %s", + async (model) => { + const { sandboxInferencePayload } = await import("../live/hermes-inference-switch-helpers.ts"); + const payload = JSON.parse(sandboxInferencePayload(model, "openai-api", "openai-completions")); + expect(payload.model).toBe(model); + expect(payload.max_completion_tokens).toBe(100); + expect(payload).not.toHaveProperty("max_tokens"); + }, +); + +it("preserves Anthropic Messages and Gemini raw probe budgets", async () => { + const { sandboxInferencePayload } = await import("../live/hermes-inference-switch-helpers.ts"); + const anthropic = JSON.parse( + sandboxInferencePayload("vendor-model", "anthropic-prod", "anthropic-messages"), + ); + expect(anthropic.max_tokens).toBe(32); + expect(anthropic).not.toHaveProperty("max_completion_tokens"); + const gemini = JSON.parse( + sandboxInferencePayload("vendor-model", "gemini-api", "openai-completions"), + ); + expect(gemini.max_tokens).toBe(256); +}); From e65d5bf0a0a07761c43ec8f7f55cea99044d15c8 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 12:48:24 -0700 Subject: [PATCH 066/133] fix(images): match MCP archive to reviewed messaging lock --- Dockerfile | 2 +- .../openclaw/openclaw-managed-messaging-offline-build.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index c1431cbed40..427b4bcb6ba 100644 --- a/Dockerfile +++ b/Dockerfile @@ -479,7 +479,7 @@ ADD --chmod=0444 --checksum=sha256:e09206c60fccafb952c854af7629cbb031a98d6da2e14 ADD --chmod=0444 --checksum=sha256:5d181804516c4a693a384272a7bd0e42d17e0d4b301ccfbe408669ccafdcb3e8 https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz /safe-buffer-5.2.1.tgz ADD --chmod=0444 --checksum=sha256:78812f65ae3b98071ce1c9bacbe0666f4220d0b2753c2a11530eb27df440a3b3 https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz /safer-buffer-2.1.2.tgz ADD --chmod=0444 --checksum=sha256:22fb96ba4ca943c41560f8dd21b405f388a8e4c010ebc8b88c5e3f8f8da73c6c https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.120.0.tgz /sdk-0.120.0.tgz -ADD --chmod=0444 --checksum=sha256:2cac3f3e38fec2815ed9efafa2947faf8c6957310684f99703f3d180f3e9af1a https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz /sdk-1.30.0.tgz +ADD --chmod=0444 --checksum=sha256:d2ff62b961316c4c4d7b03367ea8f70121839401adbd7a8aa4175f8e85c87af0 https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.31.0.tgz /sdk-1.31.0.tgz ADD --chmod=0444 --checksum=sha256:57beb0f7705b09406e5bcc984d1f6a141940680b4c42755be026f77f64365a37 https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-1.4.0.tgz /sdk-1.4.0.tgz ADD --chmod=0444 --checksum=sha256:4465839df9cf25046eacb64e37a38e7a2d033546356335190234bad60bd85d42 https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.43.0.tgz /semantic-conventions-1.43.0.tgz ADD --chmod=0444 --checksum=sha256:d85045d4300d7d57c891336b95df532e73f34c22ffcd222452b6d08b9d127d5d https://registry.npmjs.org/semver/-/semver-7.8.5.tgz /semver-7.8.5.tgz diff --git a/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts b/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts index 35eea3b03e2..a99f7ae45fa 100644 --- a/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts +++ b/test/agents/openclaw/openclaw-managed-messaging-offline-build.test.ts @@ -78,6 +78,7 @@ describe("OpenClaw managed messaging offline image build", () => { }; expect(runtimeManifest.overrides).toEqual({ + "@modelcontextprotocol/sdk": "1.31.0", "proxy-addr": "2.0.8", "@openclaw/discord@2026.9.2": { "@discord/embedded-app-sdk@2.5.0": { From a38603fff64a075a08da3318a2224c82f4c099c2 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 13:27:44 -0700 Subject: [PATCH 067/133] fix(ci): refresh hosted inference image qualification Signed-off-by: Deepak Jain --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- test/e2e/README.md | 5 +++-- test/mcp/mcp-tool-discovery-image-contract.test.ts | 14 +++++++------- tools/e2e/target-catalogue.mts | 2 ++ 6 files changed, 22 insertions(+), 19 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index cd9e6b7bcd6..5b62a1a2d27 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:6e4b97ebf390aaae3e350fda1bb4e8cf3b7ccb918376f2bd431884af5800a9cc", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:6e4b97ebf390aaae3e350fda1bb4e8cf3b7ccb918376f2bd431884af5800a9cc", + "digest": "sha256:5ee57b78678be22082a1cd20a193606300c3531e7418097824efb26215955da1", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:5ee57b78678be22082a1cd20a193606300c3531e7418097824efb26215955da1", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "fd70900cedb01b9ced93626f190002581a0aa356", + "revision": "e65d5bf0a0a07761c43ec8f7f55cea99044d15c8", "release": "v0.1.0", - "cohort": "ghrun-37515304733-1" + "cohort": "ghrun-37522090169-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 24533c750f3..f2c8d4331ce 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:568792426862e7264e0ea23d1708373e8c8885cf66f7c50000bbf433f1c9f277", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:568792426862e7264e0ea23d1708373e8c8885cf66f7c50000bbf433f1c9f277", + "digest": "sha256:440810c2a95cd87cf5670b45198dede4d11c9db28198ec892361a5e16dd4ee23", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:440810c2a95cd87cf5670b45198dede4d11c9db28198ec892361a5e16dd4ee23", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "fd70900cedb01b9ced93626f190002581a0aa356", + "revision": "e65d5bf0a0a07761c43ec8f7f55cea99044d15c8", "release": "v0.1.0", - "cohort": "ghrun-37515304733-1" + "cohort": "ghrun-37522090169-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 540e421fc89..1bf7134a0a2 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "127792f62117e69dd8f5c05ba4fb2e5b8f5a087905c2c777db1ee64ac29b845c", - "9b9fdace49624f4e36d9e7b1c4ec4b775fe260d85388c038b28127f4a5aa9bf2", + "594a78eb349498fb66b0141f9a2b2b565183b935869820aa2e406c6ca4de7ad7", + "5f7cb0156e3b2ce138999323fd29908fb77098935717d54ecaa114b2edeb3e0e", ]), }); diff --git a/test/e2e/README.md b/test/e2e/README.md index 9d9150eaf94..5ec17d30f9b 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1050,8 +1050,9 @@ These are application environment bindings, not approved GitHub repository secre mappings. Credential provisioning and a supported account model remain external prerequisites. Hermes Provider registers the manual Nous key once through `credentials add`; only that command maps it into the profile's physical -`OPENAI_API_KEY` binding. The later switch consumes its owned registration. OAuth -qualification remains separate and is not established by this manual-key scenario. Do not run this owner against a personal or shared gateway: it pre-cleans and +`OPENAI_API_KEY` binding. The later switch consumes its owned registration. This scenario does not exercise OAuth acquisition. The unchanged OAuth device +flow and its native credential handoff retain their existing deterministic tests; +this migration does not introduce a separate live-login requirement. Do not run this owner against a personal or shared gateway: it pre-cleans and tears down its sandbox and removes the named gateway registration. Sandbox destroy only deletes sandbox-owned messaging/search providers; native inference providers are shared gateway resources. Cleanup command success does not separately diff --git a/test/mcp/mcp-tool-discovery-image-contract.test.ts b/test/mcp/mcp-tool-discovery-image-contract.test.ts index 4e847c80548..d7f4a10dc69 100644 --- a/test/mcp/mcp-tool-discovery-image-contract.test.ts +++ b/test/mcp/mcp-tool-discovery-image-contract.test.ts @@ -222,15 +222,15 @@ describe("MCP tool discovery image contract", () => { relativePath: "managed-startup-image-runtime.bundle", }, { - expectedHash: "724e7d681c32d786dab45d392c43311aff5083470f763bb385d428826f4393b0", + expectedHash: "6c66bda4ed6f5844dd7a3e8108b9c2747caf132ed244bb2129cc92844ad6cc9b", relativePath: "mcp-tool-discovery/BUNDLED_PACKAGES.json", }, { - expectedHash: "3aff9216ba63fa3238e0db9d907b8ef0bf68243445031247f1b3b0a58a022283", + expectedHash: "89587c2216914dd4c98933bb43d26b445086938f2dce7fe56d60ddf5d61a513a", relativePath: "mcp-tool-discovery/THIRD_PARTY_LICENSES.txt", }, { - expectedHash: "062b50521af428e3738d26aff88f3b58e64fbfd1f4af2088044b00eeb3bca607", + expectedHash: "40452d737095fd4b9d2f69d483ae9da4b2074fbef5018a3a88df4095c2dec5d4", relativePath: "mcp-tool-discovery/mcp-tool-discovery.bundle", }, ])("pins the reviewed image runtime artifacts exactly", ({ expectedHash, relativePath }) => { @@ -560,7 +560,7 @@ case "$invocation" in ;; 3) echo 'npm error code ENOTCACHED' >&2 - echo 'npm error request to https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz failed: cache mode is only-if-cached but no cached response is available.' >&2 + echo 'npm error request to https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.31.0.tgz failed: cache mode is only-if-cached but no cached response is available.' >&2 exit 1 ;; 4|5) @@ -599,9 +599,9 @@ exit 0 "ci --ignore-scripts --no-audit --no-fund --no-progress", "ls --all --json --ignore-scripts --no-audit --no-fund --no-progress", "ci --ignore-scripts --no-audit --no-fund --no-progress --offline", - "cache add https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", - "cache add https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", - "cache add https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", + "cache add https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.31.0.tgz", + "cache add https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.31.0.tgz", + "cache add https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.31.0.tgz", "ci --ignore-scripts --no-audit --no-fund --no-progress --offline", ]); } finally { diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index da35fc5478c..8122fd4acec 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -305,6 +305,8 @@ const PI_IMAGE_SOURCE_OWNING_PATHS = [ "scripts/security/patches/perl-5.44.0-net-ping-capability-tests.patch", "scripts/security/patches/python3.13-htmlparser-cve-2026-15308.patch", "scripts/upgrade-bundled-npm.mts", + "src/lib/inference/native-hosted/profiles.ts", + "src/lib/inference/native-hosted/openrouter-headers.ts", "tools/mcp-tool-discovery-runtime/reviewed-runtime-bundle/managed-startup-direct-image-runtime.bundle", ] as const; From d22278e5353844f63a7b24edd5434b2cc937b967 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 13:34:33 -0700 Subject: [PATCH 068/133] fix(hermes): validate restart fallback after supervisor handoff Signed-off-by: Deepak Jain --- agents/hermes/Dockerfile | 2 +- agents/hermes/hermes-wrapper.py | 4 ++ .../patch-external-supervisor-restart.py | 28 +++++++------- ...-external-supervisor-restart-patch.test.ts | 37 ++++++++++++++++++- .../hermes-wrapper-oneshot-routing.test.ts | 18 +++++++++ 5 files changed, 74 insertions(+), 15 deletions(-) diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index 15ce7fd2e43..6f4970a9975 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -602,7 +602,7 @@ RUN /usr/bin/python3 -I \ # restart. Map only an externally supervised unplanned SIGTERM to private status # 79 so NemoClaw can wait for its root-owned recovery transaction. Every other # restart and failure path remains upstream. -ARG NEMOCLAW_HERMES_EXTERNAL_SUPERVISOR_RESTART_PATCHER_SHA256=ae31d7a1113b1144ef0977fb736439bac35820499a6134a66e3c6b6179d08e37 +ARG NEMOCLAW_HERMES_EXTERNAL_SUPERVISOR_RESTART_PATCHER_SHA256=ab51dec1bfc2593e5ad05d09356ead4a666243607e242d421835f2161cc956b6 ARG NEMOCLAW_HERMES_EXTERNAL_SUPERVISOR_RECOVERY_PATCHER_SHA256=8428d7f0ebe5545bf87f0800dba88d05c26c458447a8558960d0738cc5a0bdad ARG NEMOCLAW_HERMES_GATEWAY_SHUTDOWN_RECOVERY_PATCHED_SHA256=fcabcd3483565c7709aca1b8d38d4c4cb4fedc0997e0c881c2e643721f57f538 # hadolint ignore=DL4006 diff --git a/agents/hermes/hermes-wrapper.py b/agents/hermes/hermes-wrapper.py index b3d4cb1cc0c..9c59a94f903 100755 --- a/agents/hermes/hermes-wrapper.py +++ b/agents/hermes/hermes-wrapper.py @@ -829,6 +829,10 @@ def main(argv: list[str]) -> int: if ( native_guard is not None and argv not in (["-h"], ["--help"], ["--version"], ["-V"], ["chat", "-h"], ["chat", "--help"]) + # The exact restart control command must reach the supervisor after + # rebuild restores the home but before startup reconciles its hashes. + # Replacement startup and direct gateway run still validate the route. + and argv != ["gateway", "restart"] and (argv[:1] == ["gateway"] or _parse_managed_invocation(argv, adapter) is not None) ): python3 = _resolve_trusted_python3() diff --git a/agents/hermes/patch-external-supervisor-restart.py b/agents/hermes/patch-external-supervisor-restart.py index 1490d06e8f1..1694d6eeada 100755 --- a/agents/hermes/patch-external-supervisor-restart.py +++ b/agents/hermes/patch-external-supervisor-restart.py @@ -48,19 +48,20 @@ def _restart_via_external_supervisor() -> bool: def _cmd_restart(args): ''' -OLD_RESTART_BRANCH = ''' if restart_all: - _restart_all(system) +OLD_RESTART_BRANCH = " if restart_all and _dispatch_all_via_service_manager_if_s6(\"restart\"):\n" +NEW_RESTART_BRANCH = ''' if not restart_all and _restart_via_external_supervisor(): return - - # The Windows restart path handles both registered installs and detached restarts. -''' -NEW_RESTART_BRANCH = ''' if restart_all: - _restart_all(system) - return - if _restart_via_external_supervisor(): - return - - # The Windows restart path handles both registered installs and detached restarts. + # A restart without a verified supervisor may launch from this CLI process. + # Preserve native route validation before any service-manager/manual fallback. + import subprocess + native_guard = subprocess.run( + [sys.executable, "-I", "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", + "native-inference-credential", "--hermes-dir", "/sandbox/.hermes", + "--hash-file", "/etc/nemoclaw/hermes.config-hash"], check=False + ) + if native_guard.returncode != 0: + sys.exit(native_guard.returncode) + if restart_all and _dispatch_all_via_service_manager_if_s6("restart"): ''' @@ -68,7 +69,8 @@ def patch_file(path: Path) -> None: source = path.read_text(encoding="utf-8") already_patched = source.count(HELPER) == 1 and source.count(NEW_RESTART_BRANCH) == 1 - if already_patched and source.count(OLD_RESTART_BRANCH) == 0: + # The replacement retains the original service-manager branch after its guard. + if already_patched and source.count(OLD_RESTART_BRANCH) == 1: return helper_count = source.count(HELPER_MARKER) diff --git a/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts b/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts index fc7106029bf..caafa1d82df 100644 --- a/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts +++ b/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts @@ -17,9 +17,14 @@ import types events = [] scenario = sys.argv[1] +import subprocess +def native_guard_run(argv, *, check): + events.append(["native-guard", argv[2:]]) + return types.SimpleNamespace(returncode={"invalid": 1, "unavailable": 2}.get(scenario, 0)) +subprocess.run = native_guard_run status = types.ModuleType("gateway.status") -status.get_running_pid = lambda: None if scenario == "missing" else 4321 +status.get_running_pid = lambda: None if scenario in ("missing", "invalid", "unavailable") else 4321 gateway = types.ModuleType("gateway") gateway.status = status sys.modules["gateway"] = gateway @@ -189,6 +194,36 @@ describe("Hermes external-supervisor restart patch", () => { } }); + it.each([ + ["invalid", 1], + ["unavailable", 2], + ] as const)( + "refuses missing-supervisor fallback when native validation is %s", + (scenario, status) => { + const { gatewayPath, temporaryRoot } = writeFixture(); + try { + expect(patch(gatewayPath).status).toBe(0); + const result = run(gatewayPath, scenario); + expect(result.status).toBe(status); + expect(lastJson(result.stdout).events).toContainEqual([ + "native-guard", + [ + "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", + "native-inference-credential", + "--hermes-dir", + "/sandbox/.hermes", + "--hash-file", + "/etc/nemoclaw/hermes.config-hash", + ], + ]); + expect(lastJson(result.stdout).events).not.toContainEqual(["manual-stop"]); + expect(lastJson(result.stdout).events).not.toContainEqual(["manual-start", 0, false]); + } finally { + fs.rmSync(temporaryRoot, { recursive: true, force: true }); + } + }, + ); + it("fails instead of falling through when the supervised gateway does not exit", () => { const { gatewayPath, temporaryRoot } = writeFixture(); try { diff --git a/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts b/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts index 06458627ae6..4575f3f0b5a 100644 --- a/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts +++ b/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts @@ -120,6 +120,10 @@ with tempfile.TemporaryDirectory() as root: "wrapper._resolve_native_inference_guard = lambda: sys.argv[4]", "wrapper._MANAGED_HERMES_HOME = sys.argv[5]", "wrapper._NATIVE_INFERENCE_HASH_FILE = sys.argv[6]", + # Other owners exercise the gateway env boundary; isolate native route validation here. + "wrapper._run_gateway_env_file_guard = lambda _path: 0", + "wrapper._run_gateway_guard = lambda _path: 0", + "wrapper.os.geteuid = lambda: 1000", "raise SystemExit(wrapper.main(sys.argv[7:]))", ]) command = [sys.executable, "-c", script, sys.argv[2], str(real), sys.argv[3], sys.argv[1], str(home), str(hashes)] @@ -137,6 +141,20 @@ with tempfile.TemporaryDirectory() as root: assert missing.returncode == 1 help_run = subprocess.run(command + ["chat", "--help"], env={"PATH": os.environ["PATH"]}, capture_output=True, text=True) assert help_run.returncode == 0, help_run.stderr + # Restoring a legitimate legacy home changes its hash before the supervised + # replacement's preparation transaction can refresh it. Restart only signals + # that supervisor; direct launch/chat must still refuse the stale snapshot. + config.write_text(json.dumps({"model": {"api_key": "sk-OPENSHELL-PROXY-REWRITE"}})) + for argv, expected in [(["gateway", "restart"], 0), (["gateway", "run"], 1), (["gateway", "restart", "--all"], 1), (["chat", "--query", "hello"], 1)]: + marker.unlink(missing_ok=True) + run = subprocess.run(command + argv, capture_output=True, text=True) + assert run.returncode == expected, run.stderr + assert marker.exists() == (expected == 0) + # The actual launch is admitted only after reconciliation seals the snapshot. + hash_text, _, _ = guard._hash_text(str(config), str(env)) + hashes.write_text(hash_text) + run = subprocess.run(command + ["gateway", "run"], capture_output=True, text=True) + assert run.returncode == 0, run.stderr config.write_text("model: {api_key: raw-secret-do-not-print}") marker.unlink(missing_ok=True) run = subprocess.run(command + ["chat", "--query", "hello"], capture_output=True, text=True) From adb0441a2278ddfa845f0d1089474912ea7a54f9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:36:14 -0700 Subject: [PATCH 069/133] fix(inference): preserve native provider identity Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/reference/commands.mdx | 6 +- .../inference-set-openclaw-run.test.ts | 64 +++++++++++++++++++ src/lib/inference/native-nvidia/index.ts | 8 ++- 3 files changed, 74 insertions(+), 4 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0e8e6f8db33..5943aae8126 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1640,7 +1640,7 @@ $$nemoclaw my-assistant start When that deadline expires, `start` keeps the existing container, exits non-zero, and prints the `NEMOCLAW_CONNECT_TIMEOUT` value to use on the next run. -After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Most providers use `https://inference.local`; NVIDIA Endpoints uses the sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. `doctor` still classifies an HTTP `401` or `403` route response as reachable, so correct the provider credential when `start` reports one of those statuses. +After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Most providers use `https://inference.local`; NVIDIA Endpoints uses the sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. For a shared gateway route, `doctor` still classifies an HTTP `401` or `403` response as reachable. The native NVIDIA doctor probe instead requires a 2xx response from the sandbox-attached provider. Correct the provider credential when `start` reports either status. ### `$$nemoclaw status` @@ -1701,7 +1701,7 @@ The command probes the selected provider path from inside the sandbox, and when | `not probed` | NemoClaw could not run the authoritative route probe from a reachable sandbox. | | `not verified` | NemoClaw could not verify the sandbox or gateway state, so it skips inference probing. | -An authentication response on the route probe alone confirms that the route is reachable, not that provider credentials are valid. `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. +An authentication response on a shared gateway route probe confirms that the route is reachable, not that provider credentials are valid. For those shared routes, `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. The native NVIDIA doctor probe is different: it verifies the sandbox-attached provider directly and requires a 2xx response. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` sends no inference request, so it always reports the `Inference (upstream)` state that it measured. @@ -1845,7 +1845,7 @@ The `Registered gateway binding` result depends on the sandbox registry: - For an unregistered sandbox name, `doctor` uses the gateway selected by `NEMOCLAW_GATEWAY_PORT` for its other gateway checks and omits the `Registered gateway binding` check. -For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Most providers probe `https://inference.local/v1/models`; NVIDIA Endpoints probes its sandbox-attached provider at `https://integrate.api.nvidia.com/v1/models`. HTTP responses from `200` through `499`, including `401` and `403`, pass this check. HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. Host-side upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox path is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. +For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Most providers probe the shared gateway route at `https://inference.local/v1/models`; responses from `200` through `499`, including `401` and `403`, pass that reachability check. NVIDIA Endpoints instead probes its sandbox-attached provider at `https://integrate.api.nvidia.com/v1/models` and requires a 2xx response. For the shared route, HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. For native NVIDIA, any non-2xx response or unavailable probe fails it. Host-side upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox path is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. Warnings do not make the command fail. Failed checks, including a failed or unavailable authoritative inference route, exit non-zero so scripts can use `doctor` as a readiness gate. Use `--json` for machine-readable output. For a `compatible-endpoint` route that uses `openai-completions`, the JSON report includes an informational `Inference` check labeled `Reasoning effort`. The check reports `low`, `medium`, `high`, or `endpoint-default` and never includes credentials. Because the check has `info` status, it does not change the command's exit status. diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 0eeac8220da..2228d13bd52 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -123,6 +123,70 @@ describe("runInferenceSet OpenClaw routing", () => { ); }); + it("does not record or attach a native NVIDIA provider replaced during credential rotation", async () => { + const gatewayAuthority = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + value: { + name: gatewayAuthority.providerName, + type: gatewayAuthority.profileId, + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: gatewayAuthority.providerId, resourceVersion: 1 }, + }, + }) + .mockResolvedValueOnce({ + ok: true, + value: { + name: gatewayAuthority.providerName, + type: gatewayAuthority.profileId, + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { + id: "22222222-3333-4444-8555-666666666666", + resourceVersion: 1, + }, + }, + }); + const attachProvider = vi.fn(); + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true as const })), + getProvider, + updateProvider: vi.fn(async () => ({ ok: true as const })), + attachProvider, + } as unknown as OpenShellProviderAdapter; + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "gpt-5.4", + }, + getNativeNvidiaProviderAuthority: () => gatewayAuthority, + providerAdapter, + resolveCredentialValue: () => "replacement-credential", + }); + + await expect( + runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps), + ).rejects.toThrow( + /changed identity during its credential update.*No provider receipt was recorded/u, + ); + + expect(deps.calls.setNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(attachProvider).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + it("creates a new native NVIDIA provider after reset removes retained authority", async () => { const providerId = "22222222-3333-4444-8555-666666666666"; let providerPresent = false; diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 2b062a53479..88b94bdaa55 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -273,7 +273,13 @@ export async function ensureNativeNvidiaProvider(input: { `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after its credential update.`, ); } - return attachmentFromMetadata(observed); + const observedReceipt = attachmentFromMetadata(observed); + if (observedReceipt.providerId !== input.expected.providerId) { + throw new NativeNvidiaProviderError( + `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity during its credential update. No provider receipt was recorded.`, + ); + } + return observedReceipt; } if (input.expected) { From f698af53370595cefc77b4b6bafcbea6adf5573c Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 13:44:02 -0700 Subject: [PATCH 070/133] fix(hermes): align wrapper integrity checksum Signed-off-by: Deepak Jain --- agents/hermes/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index 6f4970a9975..05ed1eaa954 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -757,7 +757,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=0e9e1b9ca1bb9365397c96933c09d741b848ae61904c2ebee9b21e08afddba9c +ARG NEMOCLAW_HERMES_WRAPPER_SHA256=1554ccf23f28133855bc170646a62050fe308bac69aecae3ce9df8b438195dad ARG NEMOCLAW_HERMES_CLI_ADAPTER_VALIDATOR_SHA256=5205a5446d0a509c5bc60f77fd97ec579449c2c7291dcc2878a788f25f078d6f ARG NEMOCLAW_HERMES_VALIDATOR_SHA256=8173abf39766a41afad3110622ce7dc78612a4cc96ea75e88150125e7dabc8b5 ARG NEMOCLAW_HERMES_TIRITH_FINALIZER_SHA256=a1e6b1c53ab297569abb87c29d15c294d729e46005bfd022136b4c447a791819 From 072f00e75cc84963f703cfb6f467b09dacc1a44e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 16:44:16 -0700 Subject: [PATCH 071/133] docs(inference): distinguish native provider reads Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../inference/view-active-inference-route.mdx | 26 ++++++++++++------- docs/reference/commands.mdx | 15 ++++++----- src/commands/inference/get.ts | 5 ++-- src/commands/sandbox/inference/get.ts | 4 +-- 4 files changed, 31 insertions(+), 19 deletions(-) diff --git a/docs/inference/view-active-inference-route.mdx b/docs/inference/view-active-inference-route.mdx index 8cff87588f9..f23f17c4680 100644 --- a/docs/inference/view-active-inference-route.mdx +++ b/docs/inference/view-active-inference-route.mdx @@ -3,22 +3,26 @@ # SPDX-License-Identifier: Apache-2.0 title: "View the Active Inference Route" sidebar-title: "View the Active Route" -description: "Inspect the provider and model on the live NemoClaw-managed OpenShell inference route and the persisted URL for a compatible custom endpoint." -description-agent: "Shows the live inference provider and model, plus the persisted URL for a compatible custom endpoint. Use when checking or reproducing the active route." +description: "Inspect a sandbox-attached NVIDIA provider or the live NemoClaw-managed OpenShell inference route." +description-agent: "Shows the selected sandbox's native NVIDIA provider path or the live shared route for another provider. Use when checking the active inference path." keywords: ["nemoclaw inference get", "active inference provider", "active inference model", "compatible endpoint URL"] content: type: "how_to" --- -Use the NemoClaw CLI to read the provider and model on the live OpenShell inference route. +Use the NemoClaw CLI to read the selected inference provider and model. +When the selected sandbox has a valid native NVIDIA provider attachment, the command reports the sandbox's recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. +For other providers, the command reads the live OpenShell inference route. For a compatible custom provider, the command also reports its persisted endpoint URL when the registry provider and model match the live route. This command reports configuration state and does not authenticate a model request. -## Read the Live Route +## Read the Selected Inference Path Run the direct route command when you need the active provider, model, and applicable custom endpoint URL. -The direct form reads the gateway that `NEMOCLAW_GATEWAY_PORT` selects. +The direct form first checks the default sandbox in the registry that `NEMOCLAW_GATEWAY_PORT` selects. +It reports that sandbox's native NVIDIA provider path when a valid attachment exists. +Otherwise, it reads the gateway that `NEMOCLAW_GATEWAY_PORT` selects. ```bash $$nemoclaw inference get @@ -29,6 +33,7 @@ Expected output: ```text Provider: nvidia-prod Model: nvidia/nemotron-3-super-120b-a12b +Endpoint: https://integrate.api.nvidia.com/v1 ``` Pass `--json` for machine-readable output. @@ -42,7 +47,8 @@ Expected output: ```json { "provider": "nvidia-prod", - "model": "nvidia/nemotron-3-super-120b-a12b" + "model": "nvidia/nemotron-3-super-120b-a12b", + "endpointUrl": "https://integrate.api.nvidia.com/v1" } ``` @@ -66,7 +72,8 @@ Endpoint: https://inference.example.com/v1 } ``` -Managed providers keep the existing provider-and-model output. +A valid native NVIDIA attachment adds the fixed NVIDIA endpoint to the provider-and-model output. +Other managed providers keep the provider-and-model output. Unpublished sandbox rows do not participate in endpoint selection. Equivalent stored URL forms, such as a trailing slash difference, count as the same endpoint identity. NemoClaw omits the endpoint when participating registry metadata is absent, conflicting, invalid, too long, uses another path shape, or contains userinfo, a query, a fragment, control characters, or recognized credential material in any URL component. @@ -80,7 +87,7 @@ These endpoint-omission fields never include a stored URL, registry path, or und If a sandbox-first lookup cannot resolve its gateway because the registry is corrupt or unreadable, the command exits non-zero and retains the safe recovery steps and affected path. If the requested sandbox has an invalid gateway binding, the error names that sandbox and tells you to repair or remove its registration without displaying the rejected gateway value or port. -The command exits non-zero with `OpenShell inference route is not configured for gateway ''.` when the selected gateway has no configured inference route. +A shared-route lookup exits non-zero with `OpenShell inference route is not configured for gateway ''.` when the selected gateway has no configured inference route. Run `$$nemoclaw onboard` to configure one. For lookup failures, the error names the gateway without rendering command output. It reports a timeout, a nonzero exit status, no exit status, or output NemoClaw cannot interpret after a command exits successfully. @@ -96,7 +103,8 @@ $$nemoclaw inference get ``` `NEMOCLAW_GATEWAY_PORT` first selects the sandbox registry and fallback gateway. -When that registry contains the named sandbox, the command resolves its recorded gateway and reads that gateway-wide route. +When the named sandbox has a valid native NVIDIA provider attachment, the command reports its recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. +Otherwise, when that registry contains the named sandbox, the command resolves its recorded gateway and reads that gateway-wide route. For a compatible custom provider, the command reports an endpoint only when every eligible published row on the resolved gateway matches the live route and records the same safe, reusable endpoint. The command does not search registries for other gateway ports. OpenShell exposes one inference route to every sandbox registered on the same gateway. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 5943aae8126..bfdf1602a73 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3459,9 +3459,11 @@ When at least one sandbox is registered and the named NemoClaw gateway is unreac ### `$$nemoclaw inference get` -Show the active live inference provider and model from the NemoClaw-managed OpenShell gateway that `NEMOCLAW_GATEWAY_PORT` selects. +Show the provider and model for the selected inference path. +When the selected sandbox has a valid native NVIDIA provider attachment, the command reports its recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. +For other providers, the command reports the active live route from the NemoClaw-managed OpenShell gateway that `NEMOCLAW_GATEWAY_PORT` selects. For a compatible custom provider, also show the persisted endpoint URL when the selected gateway's matching registry metadata is safe, unambiguous, and reusable. -Use this command when you want the direct runtime route without the rest of the sandbox status output. +Use this command when you want the selected inference path without the rest of the sandbox status output. It is also available in sandbox-first form as `$$nemoclaw inference get`. ```bash @@ -3469,18 +3471,19 @@ $$nemoclaw inference get $$nemoclaw inference get --json ``` -Managed providers keep the existing provider-and-model output. Compatible providers add the endpoint only when published same-gateway metadata matches the live route and is safe to display; otherwise the command keeps the live provider and model and returns credential-free recovery information. Refer to [View the Active Inference Route](../inference/manage-inference/view-active-inference-route) for the exact text and JSON fields, omission states, safety rules, and recovery procedures. +A valid native NVIDIA attachment adds the fixed NVIDIA endpoint to the recorded provider-and-model output. Other managed providers keep the provider-and-model output. Compatible providers add the endpoint only when published same-gateway metadata matches the live route and is safe to display; otherwise the command keeps the live provider and model and returns credential-free recovery information. Refer to [View the Active Inference Route](../inference/manage-inference/view-active-inference-route) for the exact text and JSON fields, omission states, safety rules, and recovery procedures. For the sandbox-first grammar, `NEMOCLAW_GATEWAY_PORT` first selects the sandbox registry and fallback gateway. -When that registry contains ``, the command resolves the sandbox's recorded gateway and reads that gateway's live route. +When `` has a valid native NVIDIA provider attachment, the command reports its recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. +Otherwise, when that registry contains ``, the command resolves the sandbox's recorded gateway and reads that gateway's live route. It does not search registries for other gateway ports. When the live provider and model match the sandbox's recorded route, text and JSON output identify a `llama-cpp-local` route as `managed` or `attached`. JSON reports this value as `llamaCpp.kind`. An attached route also reports the fixed loopback URL as `llamaCpp.endpointUrl`; NemoClaw does not report a stored arbitrary endpoint. When the ownership receipt is unreadable, `llamaCpp.kind` is `unavailable` and the output includes diagnostic and recovery text. The command omits `llamaCpp` when the recorded and live routes differ. -The global form continues to report only the live provider and model. -Lookup failures include timeouts, nonzero exits, no exit status, and output NemoClaw cannot interpret after a command exits successfully. +For a shared-route lookup, the global form reports only the live provider and model. +Shared-route lookup failures include timeouts, nonzero exits, no exit status, and output NemoClaw cannot interpret after a command exits successfully. The error names the gateway without rendering command output. It directs a direct lookup to `$$nemoclaw status` and a sandbox-first lookup to `$$nemoclaw status`. diff --git a/src/commands/inference/get.ts b/src/commands/inference/get.ts index 3fd0bf1ec4c..33b0d5c5ba5 100644 --- a/src/commands/inference/get.ts +++ b/src/commands/inference/get.ts @@ -8,8 +8,9 @@ export default class InferenceGetCommand extends NemoClawCommand { static id = "inference:get"; static strict = true; static enableJsonFlag = true; - static summary = "Show the active NemoClaw inference route"; - static description = "Read the live OpenShell inference route through the NemoClaw CLI."; + static summary = "Show the selected NemoClaw inference path"; + static description = + "Read the selected sandbox's native NVIDIA provider path or the live shared OpenShell route."; static usage = ["inference get [--json]"]; static examples = ["<%= config.bin %> inference get", "<%= config.bin %> inference get --json"]; static flags = {}; diff --git a/src/commands/sandbox/inference/get.ts b/src/commands/sandbox/inference/get.ts index ff703d69995..693fdf295a6 100644 --- a/src/commands/sandbox/inference/get.ts +++ b/src/commands/sandbox/inference/get.ts @@ -11,9 +11,9 @@ export default class SandboxInferenceGetCommand extends NemoClawCommand { static id = "sandbox:inference:get"; static strict = true; static enableJsonFlag = true; - static summary = "Show the active NemoClaw inference route"; + static summary = "Show the selected NemoClaw inference path"; static description = - "Read the live OpenShell inference route. NEMOCLAW_GATEWAY_PORT selects the sandbox registry and fallback gateway; a registered sandbox's binding selects its recorded gateway."; + "Read the sandbox's native NVIDIA provider path or its gateway's live shared route. NEMOCLAW_GATEWAY_PORT selects the sandbox registry and fallback gateway; a registered sandbox's binding selects its recorded gateway."; static usage = [" inference get [--json]"]; static examples = [ "<%= config.bin %> my-assistant inference get", From 7386dec5243b515f3177e403351a37b57001ec75 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 16:54:50 -0700 Subject: [PATCH 072/133] docs(inference): clarify selected path output Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/view-active-inference-route.mdx | 6 +++--- docs/reference/commands.mdx | 7 +++++-- src/commands/sandbox/inference/get.ts | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/inference/view-active-inference-route.mdx b/docs/inference/view-active-inference-route.mdx index f23f17c4680..f343f98318b 100644 --- a/docs/inference/view-active-inference-route.mdx +++ b/docs/inference/view-active-inference-route.mdx @@ -1,8 +1,8 @@ --- # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -title: "View the Active Inference Route" -sidebar-title: "View the Active Route" +title: "View the Selected Inference Path" +sidebar-title: "View the Inference Path" description: "Inspect a sandbox-attached NVIDIA provider or the live NemoClaw-managed OpenShell inference route." description-agent: "Shows the selected sandbox's native NVIDIA provider path or the live shared route for another provider. Use when checking the active inference path." keywords: @@ -107,7 +107,7 @@ When the named sandbox has a valid native NVIDIA provider attachment, the comman Otherwise, when that registry contains the named sandbox, the command resolves its recorded gateway and reads that gateway-wide route. For a compatible custom provider, the command reports an endpoint only when every eligible published row on the resolved gateway matches the live route and records the same safe, reusable endpoint. The command does not search registries for other gateway ports. -OpenShell exposes one inference route to every sandbox registered on the same gateway. +For other providers, OpenShell exposes one inference route to every sandbox registered on the same gateway. ## Include Sandbox Health diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index c853ce07564..9814861267e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3476,7 +3476,10 @@ $$nemoclaw inference get $$nemoclaw inference get --json ``` -A valid native NVIDIA attachment adds the fixed NVIDIA endpoint to the recorded provider-and-model output. Other managed providers keep the provider-and-model output. Compatible providers add the endpoint only when published same-gateway metadata matches the live route and is safe to display; otherwise the command keeps the live provider and model and returns credential-free recovery information. Refer to [View the Active Inference Route](../inference/manage-inference/view-active-inference-route) for the exact text and JSON fields, omission states, safety rules, and recovery procedures. +A valid native NVIDIA attachment adds the fixed NVIDIA endpoint to the recorded provider-and-model output. +Other managed providers keep the provider-and-model output. +Compatible providers add the endpoint only when published same-gateway metadata matches the live route and is safe to display; otherwise the command keeps the live provider and model and returns credential-free recovery information. +Refer to [View the Selected Inference Path](../inference/manage-inference/view-active-inference-route) for the exact text and JSON fields, omission states, safety rules, and recovery procedures. For the sandbox-first grammar, `NEMOCLAW_GATEWAY_PORT` first selects the sandbox registry and fallback gateway. When `` has a valid native NVIDIA provider attachment, the command reports its recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. @@ -3487,7 +3490,7 @@ JSON reports this value as `llamaCpp.kind`. An attached route also reports the fixed loopback URL as `llamaCpp.endpointUrl`; NemoClaw does not report a stored arbitrary endpoint. When the ownership receipt is unreadable, `llamaCpp.kind` is `unavailable` and the output includes diagnostic and recovery text. The command omits `llamaCpp` when the recorded and live routes differ. -For a shared-route lookup, the global form reports only the live provider and model. +For a shared-route lookup, the global form omits `llamaCpp` details. Shared-route lookup failures include timeouts, nonzero exits, no exit status, and output NemoClaw cannot interpret after a command exits successfully. The error names the gateway without rendering command output. It directs a direct lookup to `$$nemoclaw status` and a sandbox-first lookup to `$$nemoclaw status`. diff --git a/src/commands/sandbox/inference/get.ts b/src/commands/sandbox/inference/get.ts index 693fdf295a6..4b8f9124bab 100644 --- a/src/commands/sandbox/inference/get.ts +++ b/src/commands/sandbox/inference/get.ts @@ -6,7 +6,7 @@ import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; import { sandboxNameArg } from "../../../lib/sandbox/command-support"; // Sandbox-first mirror of the global inference:get command; both delegate to -// the shared runInferenceGet action that reads the gateway-wide route. +// the shared runInferenceGet action that selects native NVIDIA or shared-route output. export default class SandboxInferenceGetCommand extends NemoClawCommand { static id = "sandbox:inference:get"; static strict = true; From 421b8ee6eda991738a5c0732a72826b0b7c907b2 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 17:00:00 -0700 Subject: [PATCH 073/133] docs(inference): align selected path navigation Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/index.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/index.yml b/docs/index.yml index 197702b5d5f..b645c4d80dc 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -134,7 +134,7 @@ navigation: - page: "Use Shared Gateway Routes" path: _build/agent-variants/inference/use-shared-gateway-routes.openclaw.generated.mdx slug: use-shared-gateway-routes - - page: "View the Active Inference Route" + - page: "View the Selected Inference Path" path: _build/agent-variants/inference/view-active-inference-route.openclaw.generated.mdx slug: view-active-inference-route - page: "Switch Models" @@ -603,7 +603,7 @@ navigation: - page: "Use Shared Gateway Routes" path: _build/agent-variants/inference/use-shared-gateway-routes.deepagents.generated.mdx slug: use-shared-gateway-routes - - page: "View the Active Inference Route" + - page: "View the Selected Inference Path" path: _build/agent-variants/inference/view-active-inference-route.deepagents.generated.mdx slug: view-active-inference-route - page: "Switch Models" @@ -952,7 +952,7 @@ navigation: - page: "Use Shared Gateway Routes" path: _build/agent-variants/inference/use-shared-gateway-routes.hermes.generated.mdx slug: use-shared-gateway-routes - - page: "View the Active Inference Route" + - page: "View the Selected Inference Path" path: _build/agent-variants/inference/view-active-inference-route.hermes.generated.mdx slug: view-active-inference-route - page: "Switch Models" From 9aa647c603045df1250c45b9e6fbd3f17f098519 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 17:50:11 -0700 Subject: [PATCH 074/133] fix(inference): exercise native credential identity replacement Signed-off-by: Deepak Jain --- src/lib/actions/inference-set-openclaw-run.test.ts | 7 +++++-- src/lib/inference/native-hosted/index.ts | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 63e69e5276a..ae8f9d7e8d3 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -250,8 +250,9 @@ describe("runInferenceSet OpenClaw routing", () => { name: "alpha", agent: "openclaw", gatewayName: "nemoclaw", - provider: "openai-api", - model: "gpt-5.4", + provider: "nvidia-prod", + model: "nvidia/previous-model", + nativeHostedProviderAttachment: gatewayAuthority, }, getNativeNvidiaProviderAuthority: () => gatewayAuthority, providerAdapter, @@ -264,6 +265,8 @@ describe("runInferenceSet OpenClaw routing", () => { /changed identity during its credential update.*No provider receipt was recorded/u, ); + expect(providerAdapter.updateProvider).toHaveBeenCalledOnce(); + expect(getProvider).toHaveBeenCalledTimes(2); expect(deps.calls.setNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); expect(attachProvider).not.toHaveBeenCalled(); expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); diff --git a/src/lib/inference/native-hosted/index.ts b/src/lib/inference/native-hosted/index.ts index c43b5b4b39a..b4673590daf 100644 --- a/src/lib/inference/native-hosted/index.ts +++ b/src/lib/inference/native-hosted/index.ts @@ -270,7 +270,7 @@ export async function ensureNativeHostedProvider(input: { const confirmed = attachmentFromMetadata(observed, profile); if (confirmed.providerId !== receipt.providerId) { throw new NativeHostedProviderError( - `OpenShell provider '${profile.providerName}' changed identity during its credential update.`, + `OpenShell provider '${profile.providerName}' changed identity during its credential update. No provider receipt was recorded.`, ); } return confirmed; From e2875a664a94e426bd797e545cfb301a41fb7aae Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 17:55:43 -0700 Subject: [PATCH 075/133] ci(e2e): propose trusted Slice 3 assertion exception Signed-off-by: Deepak Jain --- ci/e2e-assertion-growth-exceptions.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 2457401c9e3..41d7ba82f26 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12648 adds seven live assertion points for native compatible onboarding, a fresh authenticated agent request, and native status/health after duplicate deterministic checks were removed. User-provided recorded direction from Aaron Erickson (@ericksoa): https://nvidia.slack.com/archives/C0B1FQ51FP0/p1791301358361059. This proposed entry binds the stacked PR base budget bytes to this exact candidate budget and requires maintainer review before landing. The recorded direction does not waive the independent trusted-base check; the exception must reach its trusted policy or that specific failure needs separate explicit maintainer disposition. A changed budget invalidates the corresponding entry. Remove after #12648 merges.", "schemaVersion": 1, "exceptions": [ { @@ -16,6 +16,11 @@ "pullRequest": 12591, "baseBudgetSha256": "d0a41e5514e5cc2f7bb34d7604c82106d9e36239f1abf5859e343c7733501289", "headBudgetSha256": "59c006401487a0c25d9f5cf5fd3159c9f1248a6710d559cc18879af6edef2919" + }, + { + "pullRequest": 12648, + "baseBudgetSha256": "fdc4a78b5588629e26b00778d1bc82d69101077b9e372f2b58670510184579c2", + "headBudgetSha256": "275391e461bd7f9ae5f8c59a724d4063e3bf1236d3d59586b1a1a223fcabe381" } ] } From f88487d0272abeb4a99b408fc6fd92bfcea6be77 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 18:20:20 -0700 Subject: [PATCH 076/133] docs(inference): align fixed hosted routing guidance Signed-off-by: Deepak Jain --- docs/about/ecosystem-deepagents.mdx | 4 +-- docs/about/overview.mdx | 2 +- docs/deployment/deploy-to-headless-server.mdx | 4 +-- docs/get-started/quickstart-hermes.mdx | 4 +-- .../quickstart-langchain-deepagents-code.mdx | 4 +-- docs/get-started/quickstart-pi.mdx | 2 +- docs/get-started/quickstart.mdx | 4 +-- .../recover-rebuild-sandboxes.mdx | 2 +- docs/manage-sandboxes/workspace-files.mdx | 2 +- docs/monitoring/monitor-sandbox-activity.mdx | 2 +- docs/reference/architecture.mdx | 28 +++++++++---------- docs/reference/commands.mdx | 22 +++++++-------- docs/reference/enterprise-readiness.mdx | 4 +-- docs/reference/network-policies.mdx | 5 ++-- docs/reference/pi-support.mdx | 8 +++--- docs/reference/troubleshooting.mdx | 2 +- docs/security/best-practices.mdx | 8 +++--- .../gateway-authentication-controls.mdx | 4 +-- docs/security/process-controls.mdx | 2 +- 19 files changed, 57 insertions(+), 56 deletions(-) diff --git a/docs/about/ecosystem-deepagents.mdx b/docs/about/ecosystem-deepagents.mdx index b57c09467e8..663d378c749 100644 --- a/docs/about/ecosystem-deepagents.mdx +++ b/docs/about/ecosystem-deepagents.mdx @@ -74,7 +74,7 @@ The following table compares custom OpenShell integration with `nemo-deepagents | Capability | Custom OpenShell + Deep Agents | `nemo-deepagents onboard` | |---|---|---| | Sandbox isolation | You define and apply OpenShell seccomp, Landlock, network namespace isolation, and no-new-privileges policy. | NemoClaw applies the managed Deep Agents policy through the blueprint and requires the runtime checks that the managed agent runtime depends on. | -| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding and keeps provider credentials outside the sandbox. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses a sandbox-attached provider for `https://integrate.api.nvidia.com/v1`. | +| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding and keeps provider credentials outside the sandbox. Supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local/v1`. | | Image hardening | Depends on your base image and install steps. | NemoClaw installs the pinned Deep Agents Code package in `/opt/venv`, uses managed launchers, and rejects unsupported runtime paths such as unmanaged MCP autoloading, nested sandbox providers, and alternate model routes. | | Filesystem policy | You define read-only and read-write paths in policy YAML. | NemoClaw defines a targeted layout: system paths are read-only, `/sandbox` and `/tmp` are writable, and Deep Agents state lives under `/sandbox/.deepagents`. | | Inference setup | You configure OpenShell inference routing and Deep Agents provider settings manually. | NemoClaw validates the selected provider from the host, configures the OpenShell route, and writes `/sandbox/.deepagents/config.toml` for the managed OpenAI-compatible path. | @@ -104,6 +104,6 @@ Use the following table to choose NemoClaw or custom OpenShell integration. - [About Managed MCP Servers](../manage-sandboxes/mcp-servers/about-managed-mcp-servers) explains the managed MCP security and lifecycle boundary. - [Understand Deep Agents Trace Export](../monitoring/understand-deepagents-trace-export) explains the managed trace data and receiver trust boundaries. - [Quickstart with Deep Agents](../get-started/quickstart) installs NemoClaw and launches your first Deep Agents sandbox. -- [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) explains provider choices, shared `inference.local` routes, and the native NVIDIA provider path. +- [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) explains provider choices, shared `inference.local` routes, and native hosted provider paths. - [Deep Agents Code overview](https://docs.langchain.com/oss/python/deepagents/code/overview) explains upstream `dcode` capabilities and commands. - [Community Solutions](../resources/community-contributions) explains how to contribute community-driven examples, showcases, and complete blueprint patterns. diff --git a/docs/about/overview.mdx b/docs/about/overview.mdx index 9f2b4035a61..bc7dfdc0dd8 100644 --- a/docs/about/overview.mdx +++ b/docs/about/overview.mdx @@ -37,7 +37,7 @@ NemoClaw groups its supported capabilities around running, connecting, controlli | Area | Capability | |---|---| | Run supported agents | Onboards OpenClaw, Hermes, or LangChain Deep Agents Code into an agent-specific sandbox image and configuration. | -| Route inference | Connects supported hosted and local inference providers through OpenShell-managed routes. Most use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. | +| Route inference | Connects supported hosted and local inference providers through OpenShell-managed routes. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. OpenShell keeps provider credentials outside the sandbox. | | Control sandbox access | Applies network policy, filesystem policy, process controls, and managed inference through OpenShell. | | Operate the lifecycle | Reports host readiness, creates or updates sandboxes, reports status and logs, and rebuilds or recovers sandboxes while preserving the native agent home. | | Connect Model Context Protocol (MCP) servers | Manages authenticated HTTPS Streamable HTTP MCP servers for all supported agent runtimes. OpenShell replaces credential placeholders at approved egress boundaries. | diff --git a/docs/deployment/deploy-to-headless-server.mdx b/docs/deployment/deploy-to-headless-server.mdx index e13b2d2fc3e..38c0b442572 100644 --- a/docs/deployment/deploy-to-headless-server.mdx +++ b/docs/deployment/deploy-to-headless-server.mdx @@ -206,7 +206,7 @@ $$nemoclaw headless-agent status $$nemoclaw headless-agent connect --probe-only ``` -`$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified. Its main `Inference` line probes the selected provider path from inside the sandbox. Shared providers use `https://inference.local/v1/models`, then send an inference request over the same route when that probe reports the route reachable. NVIDIA Endpoints verifies the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1` with an inference request. Status repeats inference requests up to three total attempts when they return a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after a final failure or after all transient attempts fail. +`$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified. Its main `Inference` line probes the selected provider path from inside the sandbox. Custom, local, and Model Router selections use `https://inference.local/v1/models`, then send an inference request over the same route when that probe reports the route reachable. Fixed hosted providers verify their native endpoints through sandbox-attached OpenShell providers with an inference request. Status repeats inference requests up to three total attempts when they return a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after a final failure or after all transient attempts fail. @@ -269,7 +269,7 @@ unset TOKEN -Deep Agents Code does not expose a dashboard URL or gateway token. Most model traffic uses the OpenShell-managed `inference.local` route. NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. +Deep Agents Code does not expose a dashboard URL or gateway token. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the OpenShell-managed `inference.local` route. diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index f9aac5332bb..29476a6ee58 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -352,8 +352,8 @@ Use these details when your first-run path needs more control. After you select a provider and model, review the summary and apply the configuration. NemoClaw writes Hermes configuration into `/sandbox/.hermes` and starts the Hermes gateway inside the sandbox. - NVIDIA Endpoints traffic uses the native NVIDIA endpoint through the least-privilege sandbox-attached OpenShell provider. - Other managed inference providers continue to use `inference.local`. + Fixed hosted providers use their native endpoints through least-privilege sandbox-attached OpenShell providers. + Custom, local, and Model Router selections continue to use `inference.local`. The Hermes image includes runtime dependencies for supported NemoClaw messaging integrations, the API service, and its health endpoint. The base image does not include unsupported Hermes integrations. diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index c6603548ae8..9f819ec23b9 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -165,7 +165,7 @@ The wizard asks for an inference provider, model, required credential, and sandb When you edit inference, NemoClaw clears the credential staged for the discarded selection. NemoClaw preserves the sandbox name. When you edit the sandbox name, NemoClaw preserves the inference selection. The sandbox prompt shows the prior name as its default. After you apply the configuration, routine editing ends. If inference setup fails and offers a `back` recovery action, you can return to provider and model selection and then review the updated configuration again. Provider registration, inference setup, policy selection, and sandbox creation then continue forward. The default Deep Agents sandbox name is `deepagents-code`. Use a distinct name, such as `my-deepagents`, when you run Deep Agents, Hermes, and OpenClaw sandboxes side by side. Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) for provider-specific prompts. -The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. NVIDIA Endpoints uses `https://integrate.api.nvidia.com/v1` through a least-privilege OpenShell provider attached to the sandbox. Other managed providers use `https://inference.local/v1`. Both paths put a scoped placeholder in the agent config instead of the real provider key. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. +The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. Supported fixed hosted providers use their native endpoints through least-privilege OpenShell providers attached to the sandbox. Custom, local, and Model Router selections use `https://inference.local/v1`. Both paths put a scoped placeholder in the agent config instead of the real provider key. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked.
@@ -252,7 +252,7 @@ nemo-deepagents rebuild If you upgrade from a release that persisted LangSmith environment values, rebuild each existing Deep Agents Code sandbox so its image includes the corrected `start.sh`. If an existing sandbox displays `Choose a Recommended Model`, rebuild it so its image includes the managed startup behavior. -`status` reports the selected harness as a terminal runtime and prints the interactive/headless command shape. If `status` reports `Runtime health: degraded` with an OOM kill count, rebuild the sandbox to restore the terminal runtime. Proxy launchers and startup scripts are baked into the sandbox image. After upgrading from a release that used `inference.local` for NVIDIA Endpoints, recreate each NVIDIA sandbox during onboarding. NemoClaw does not add the required native provider attachment to an existing beta sandbox. NemoClaw v0.0.78 and newer clients fail closed when a pre-v0.0.78 sandbox image lacks the trusted `/usr/local/lib/nemoclaw/dcode-managed-exec` route-probe helper, even when the installed Deep Agents Code version still matches the managed manifest. Rebuild the sandbox to install that image-owned helper before retrying `status`, `doctor`, `connect`, or onboarding recovery. There is no dashboard port or long-running gateway process for this harness. +`status` reports the selected harness as a terminal runtime and prints the interactive/headless command shape. If `status` reports `Runtime health: degraded` with an OOM kill count, rebuild the sandbox to restore the terminal runtime. Proxy launchers and startup scripts are baked into the sandbox image. After upgrading from a release that used `inference.local` for a fixed hosted provider, recreate that sandbox during onboarding. NemoClaw does not add the required native provider attachment to an existing beta sandbox. NemoClaw v0.0.78 and newer clients fail closed when a pre-v0.0.78 sandbox image lacks the trusted `/usr/local/lib/nemoclaw/dcode-managed-exec` route-probe helper, even when the installed Deep Agents Code version still matches the managed manifest. Rebuild the sandbox to install that image-owned helper before retrying `status`, `doctor`, `connect`, or onboarding recovery. There is no dashboard port or long-running gateway process for this harness. ## Next Steps diff --git a/docs/get-started/quickstart-pi.mdx b/docs/get-started/quickstart-pi.mdx index 132b09483b9..cf7bda9280d 100644 --- a/docs/get-started/quickstart-pi.mdx +++ b/docs/get-started/quickstart-pi.mdx @@ -49,7 +49,7 @@ For an existing installation, run the canonical onboarding command. nemoclaw onboard --agent pi --name my-pi ``` -Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell. Most providers give Pi the managed `https://inference.local/v1` route. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox at `https://integrate.api.nvidia.com/v1`. The credential remains in OpenShell provider state across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. +Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell. Supported fixed hosted providers give Pi their native endpoint through a least-privilege OpenShell provider attached to the sandbox. Custom, local, and Model Router selections use the managed `https://inference.local/v1` route. The credential remains in OpenShell provider state across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. Stock onboarding selects a Pi managed-image digest. It does not build the Pi Dockerfile on the host. The reviewed Dockerfile is a trusted CI image-build source, not a user onboarding mechanism. A missing, incomplete, mutable, or inconsistent image contract fails before sandbox creation. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index f9ebdeb5652..bbf04c9cffc 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -374,8 +374,8 @@ Use these details when your first-run path needs more control. After confirmation, NemoClaw registers the selected provider with OpenShell. - Most providers use the shared `inference.local` route. - NVIDIA Endpoints uses a least-privilege provider attached to the sandbox instead. + Fixed hosted providers use native endpoints through least-privilege providers attached to the sandbox. + Custom, local, and Model Router selections use the shared `inference.local` route. The wizard asks whether to enable web search and offers Brave Search or Tavily Search. Provide `BRAVE_API_KEY` for Brave Search or `TAVILY_API_KEY` for Tavily Search when prompted. NemoClaw validates the selected key before it creates the sandbox, registers a sandbox-scoped OpenShell provider, and writes only an OpenShell resolver placeholder into the OpenClaw configuration. diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 5f4cbb1ac14..a910e8a8a5f 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -190,7 +190,7 @@ During the lease, `launch` still verifies the owning OpenShell gateway, exact li Every configured route must serve a valid response to a bounded request for the recorded model before NemoClaw accepts or publishes launch readiness. Shared-route providers use `inference.local`. -NVIDIA Endpoints uses its sandbox-attached provider at `integrate.api.nvidia.com`. +Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. A failed model request rejects launch readiness. This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. diff --git a/docs/manage-sandboxes/workspace-files.mdx b/docs/manage-sandboxes/workspace-files.mdx index 9bf47acf798..3dec004cf5e 100644 --- a/docs/manage-sandboxes/workspace-files.mdx +++ b/docs/manage-sandboxes/workspace-files.mdx @@ -283,7 +283,7 @@ Deep Agents Code normally creates the `/sandbox/.deepagents/agent/` paths below | Path | Purpose | |---|---| -| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path, including shared `inference.local` routes or the native NVIDIA provider. | +| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path, including shared `inference.local` routes or a native hosted provider. | | `/sandbox/.deepagents/.state/` | Deep Agents Code runtime state, including persisted session and MCP-related state. | | `/sandbox/.deepagents/agent/AGENTS.md` | Global memory file for the default Deep Agents Code agent, loaded at session start. | | `/sandbox/.deepagents/agent/memories/` | Topic-specific markdown memories that Deep Agents Code can read and update across sessions. | diff --git a/docs/monitoring/monitor-sandbox-activity.mdx b/docs/monitoring/monitor-sandbox-activity.mdx index 63a656bae2b..2905a0dae8b 100644 --- a/docs/monitoring/monitor-sandbox-activity.mdx +++ b/docs/monitoring/monitor-sandbox-activity.mdx @@ -27,7 +27,7 @@ Run the status command to view sandbox state, gateway health, and the active inf $$nemoclaw status ``` -`$$nemoclaw status` probes the selected provider path from inside the sandbox as the authoritative inference check. Shared providers use `https://inference.local/v1/models`. NVIDIA Endpoints uses the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1` and verifies it with an inference request. +`$$nemoclaw status` probes the selected provider path from inside the sandbox as the authoritative inference check. Custom, local, and Model Router selections use `https://inference.local/v1/models`. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers and verify them with an inference request. For local Ollama and local vLLM routes, it also prints labeled host-side backend diagnostics that help identify which hop failed. Review these output fields. diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index d463d2cd802..233ed8422f0 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -29,8 +29,8 @@ graph LR USER(["👤 User"]):::user subgraph EXTERNAL["External Services"] - SHARED_INFERENCE["Shared-route inference providers
OpenAI · Anthropic · Ollama
vLLM · Model Router
"]:::external - NVIDIA_INFERENCE["NVIDIA Endpoints
integrate.api.nvidia.com"]:::external + SHARED_INFERENCE["Shared-route inference providers
Custom endpoints · Ollama
vLLM · Model Router
"]:::external + HOSTED_INFERENCE["Fixed hosted providers
Selected native endpoint"]:::external INTEGRATIONS["Integration APIs
MCP · GitHub · package indexes"]:::external INTERNET["Internet
PyPI · npm · GitHub · APIs"]:::external end @@ -65,9 +65,9 @@ graph LR BP -->|"Defines sandbox
shape + policies"| SANDBOX STATE -->|"Backup + restore"| SANDBOX - AGENT -->|"Most inference requests
inference.local · no credentials"| GW + AGENT -->|"Shared-route inference requests
inference.local · no credentials"| GW GW -->|"Shared-route request with
credential injected"| SHARED_INFERENCE - AGENT -->|"Attached NVIDIA provider
restricted request · placeholder credential"| NVIDIA_INFERENCE + AGENT -->|"Attached hosted provider
restricted request · placeholder credential"| HOSTED_INFERENCE INTEGRATIONS -->|"External APIs"| INTEG INTEG -->|"Policy-gated access"| AGENT @@ -171,14 +171,14 @@ graph TB end end - SHARED_INFER["Shared-route inference provider
OpenAI · Anthropic · Ollama
vLLM · Model Router
"]:::external - NVIDIA_INFER["NVIDIA Endpoints
integrate.api.nvidia.com"]:::external + SHARED_INFER["Shared-route inference provider
Custom endpoints · Ollama
vLLM · Model Router
"]:::external + HOSTED_INFER["Fixed hosted providers
Selected native endpoint"]:::external CLI -->|"openshell CLI
(orchestrates)"| GW GW -->|"creates/recreates
Docker-driver sandbox"| SANDBOX SANDBOX -->|"shared-route requests
inference.local · placeholder credentials"| GW GW -->|"shared-route egress
credential injected at L7 proxy"| SHARED_INFER - SANDBOX -->|"attached NVIDIA provider
restricted egress · placeholder rewritten"| NVIDIA_INFER + SANDBOX -->|"attached hosted provider
restricted egress · placeholder rewritten"| HOSTED_INFER class HOST host class DOCKER docker @@ -195,12 +195,12 @@ Layering from top to bottom: | Docker daemon | Host service | Runs the Docker-driver sandbox container and, on affected Linux hosts, the optional gateway compatibility container. | | Sandbox container | Docker container | Runs the selected supported agent runtime and NemoClaw integration under Landlock + seccomp + netns. | | OpenShell L7 proxy | Gateway process | Intercepts shared-route agent egress and rewrites `Authorization` headers (Bearer/Bot) and URL-path segments to inject the real credential at the network boundary. | -| OpenShell attached NVIDIA provider | Provider profile attached to the sandbox | Restricts NVIDIA Endpoints egress by host, method, path, and binary, then rewrites the placeholder credential at the egress boundary. | +| OpenShell attached hosted provider | Provider profile attached to the sandbox | Restricts fixed hosted provider egress by host, method, path, and binary, then rewrites the placeholder credential at the egress boundary. | NemoClaw never gives the sandbox a raw provider key. At onboard time it registers credentials with OpenShell's provider and placeholder system. Shared routes use the gateway L7 proxy to substitute the real value at egress. -NVIDIA Endpoints uses the sandbox-attached provider profile to enforce the restricted request and replace its placeholder at egress. +Fixed hosted providers use sandbox-attached provider profiles to enforce restricted requests and replace their placeholders at egress. The CLI helper `isInferenceRouteReady` (in `src/lib/onboard.ts`) is a host-side readiness check used by the resume flow to decide whether the active route already covers the chosen provider and model. It is not a runtime component. @@ -357,20 +357,20 @@ Inside the sandbox: ## Inference Routing Agent inference follows one of two OpenShell-managed paths. -Most providers use the shared `inference.local` route through the OpenShell gateway: +Custom, local, and Model Router selections use the shared `inference.local` route through the OpenShell gateway: ```text Supported agent runtime (sandbox) ──▶ inference.local ──▶ OpenShell gateway ──▶ Provider endpoint ``` -NVIDIA Endpoints uses a restricted provider attached to the sandbox: +NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider use restricted providers attached to the sandbox: ```text -Supported agent runtime (sandbox) ──▶ integrate.api.nvidia.com ──▶ NVIDIA Endpoints +Supported agent runtime (sandbox) ──▶ Selected native endpoint ──▶ Hosted provider OpenShell attached-provider policy and placeholder rewrite ``` -The NVIDIA request does not use the shared `inference.local` route. +These hosted requests do not use the shared `inference.local` route. The attached OpenShell profile allows only the configured endpoint, methods, paths, and binaries, and it replaces the placeholder credential at egress. When you select the Model Router provider, the OpenShell gateway routes to a host-side router process instead of a single upstream model. @@ -396,7 +396,7 @@ Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inf Provider credentials live in OpenShell's credential store, not on the host filesystem. NemoClaw never writes them to host disk. The OpenShell L7 proxy injects values for shared routes. -The sandbox-attached NVIDIA provider rewrites its placeholder credential at egress. +The sandbox-attached hosted provider rewrites its placeholder credential at egress. Refer to [Credential Storage](../security/credential-storage) for the inspection, rotation, and migration flow. ## Host-Side State and Config diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 2302bc129b4..7a7f3d8cc97 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1129,7 +1129,7 @@ During that lease, another `launch` still verifies these conditions: - The recorded inference selection matches its provider path, and every configured route serves a valid response to a bounded request for the recorded model. Shared-route providers use `inference.local`. - NVIDIA Endpoints verifies the recorded sandbox-attached provider and sends the request to `https://integrate.api.nvidia.com/v1`. + Fixed hosted providers verify the recorded sandbox-attached provider and send the request to the selected native endpoint. The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. A failed model request rejects readiness before the agent starts. This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. @@ -1213,7 +1213,7 @@ A recognized broken shared-route result lets `connect` attempt DNS or route repa When the initial shared-route probe cannot return a trusted result, `connect` fails closed before health-driven repair and before opening SSH. It prints a bounded, redacted last-probe detail and points you to `$$nemoclaw doctor`. -For NVIDIA Endpoints, `connect` does not inspect or change the unrelated shared route. +For fixed hosted providers, `connect` does not inspect or change the unrelated shared route. It verifies the recorded sandbox-attached provider and sends a native inference request for the selected model. The request must return a structurally valid successful inference result before `connect` opens SSH. @@ -1645,7 +1645,7 @@ $$nemoclaw my-assistant start When that deadline expires, `start` keeps the existing container, exits non-zero, and prints the `NEMOCLAW_CONNECT_TIMEOUT` value to use on the next run. -After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Most providers use `https://inference.local`; NVIDIA Endpoints uses the sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. For a shared gateway route, `doctor` still classifies an HTTP `401` or `403` response as reachable. The native NVIDIA doctor probe instead requires a 2xx response from the sandbox-attached provider. Correct the provider credential when `start` reports either status. +After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. For a shared gateway route, `doctor` still classifies an HTTP `401` or `403` response as reachable. The native NVIDIA doctor probe instead requires a 2xx response from the sandbox-attached provider. Correct the provider credential when `start` reports either status. ### `$$nemoclaw status` @@ -1661,7 +1661,7 @@ nonzero. A stopped runtime without recorded stop intent remains a For a `compatible-endpoint` route that uses `openai-completions`, the text output prints `Reasoning effort` as `low`, `medium`, `high`, or `endpoint-default`. The line is omitted for another provider or API family. -Pass `--json` to emit a structured per-sandbox report instead of the text renderer. The JSON output includes at least `schemaVersion`, `name`, `found`, `agent`, `agentDisplayName`, `agentRuntime`, `dcodeAutoApprovalMode`, `model`, `provider`, `recordedRoute`, `liveRoute`, `routeDrift`, `phase`, `gatewayState`, `inferenceHealth`, `rpcIssue`, `hostGpuDetected`, `sandboxGpuEnabled`, `sandboxGpuMode`, `sandboxGpuDevice`, `openshellDriver`, `openshellVersion`, `policies`, `policiesAvailable`, `llamaCpp`, `failureLayer`, `terminalRuntimeHealth`, `servingProcessHealth`, and `dockerPaused`. `policies` is derived from the current OpenShell policy; NemoClaw does not persist a second preset list or baseline-exclusion ledger. `policiesAvailable` is `false` when that live policy cannot be read or parsed, distinguishing an unavailable result from a verified empty `policies` array; text status prints `Policies: unavailable` for the same state. When the live gateway route matches the sandbox's recorded llama.cpp route, `llamaCpp.kind` is `attached`, `managed`, or `unavailable`. An attached route also includes its fixed loopback `llamaCpp.endpointUrl`. An unavailable result means NemoClaw could not safely verify the managed ownership receipt; it does not include an endpoint and provides a secret-free diagnostic and recovery action. During route drift, `status` omits the `llamaCpp` route attribution; inspect `routeDrift` before acting on endpoint information. Text status can still show managed-runtime details from the sandbox-owned receipt. The schema-version `1` `model` and `provider` fields keep their established live-route meaning when the gateway route is readable, except that a native NVIDIA sandbox reports its recorded sandbox-scoped route because the shared route is unrelated. Use `recordedRoute` for the sandbox's durable provider and model and `liveRoute` for the gateway-global route. When the live shared route differs for a shared-route provider, text output prints both routes and JSON output sets `routeDrift.live`, `routeDrift.recorded`, and `routeDrift.canConnect`. Native NVIDIA attachments do not report shared-route drift. When `routeDrift.canConnect` is `false`, `connect` cannot safely restore the recorded route because provider-global identity differs or required route or gateway metadata is incomplete. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for the route-sharing workflow. `openshellDriver` and `openshellVersion` are always strings (falling back to `"unknown"` when the registry has no value), so consumers can rely on `typeof` checks. `agent` is always a string and reports `openclaw` when the registry records no agent for the sandbox. `failureLayer` is `null` when no preflight failure was detected and otherwise one of `docker_unreachable`, `sandbox_container_stopped`, or `sandbox_dashboard_port_conflict`; when set, `inferenceHealth` is suppressed to `null` so automation does not see a stale remote-provider healthy status during a local outage. `inferenceHealth.ok` reports whether the selected provider path returned a structurally valid result for one request sent from inside the sandbox. The result must match Chat Completions, Responses, or Anthropic Messages for the selected route. An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. The probe captures at most 64 KiB and does not include the response body in diagnostics. The path probe treats any final HTTP status from `200` through `499` as reachable, so a route with an invalidated provider credential answers HTTP `401` while the path is up. Shared-route requests use the live gateway route's provider and model, then fall back to the recorded values when the live route is unreadable. Native NVIDIA requests always use the sandbox's recorded provider and model. When the live shared provider matches the recorded provider, the request uses the sandbox's recorded API family, even when only the model differs. This includes `openai-responses`. When the live shared provider differs, NemoClaw does not carry the recorded API family to that provider. Each attempt requests 16 reply tokens for ordinary providers or 256 for Gemini. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Hosted requests consume provider tokens on every attempt. When the inference request returns HTTP `429`, `502`, `503`, or `504`, `status` retries the provider path and inference request together up to three total attempts, with a two-second delay between failed attempts, because those statuses are transient gateway and availability answers rather than evidence that the path is broken. Before each retry, it writes the failed probe boundary, an HTTP status when one is available, the next attempt, total attempts, and delay to stderr; `--json` keeps stdout machine-readable. On an ordinary run, every other failure is final on the first attempt with no delay: HTTP `401`, `403`, `404`, and `500`, an invalid 2xx response body, a request that returned no HTTP status, and a failing provider-path probe. When the same run recovers a managed gateway, `status` retries any failed route or inference probe on that schedule instead, while the restarted delivery chain settles. Each route probe has a 10-second timeout. Three complete route probes plus their 95-second inference wrappers and two delays can take about 319 seconds. When NemoClaw sends an inference request, `inferenceHealth.subprobes` reports the provider-path result as the `route reachability` hop, so a failing verdict still shows that the path itself answered. `inferenceHealth.failureLabel` reports why the inference request failed: +Pass `--json` to emit a structured per-sandbox report instead of the text renderer. The JSON output includes at least `schemaVersion`, `name`, `found`, `agent`, `agentDisplayName`, `agentRuntime`, `dcodeAutoApprovalMode`, `model`, `provider`, `recordedRoute`, `liveRoute`, `routeDrift`, `phase`, `gatewayState`, `inferenceHealth`, `rpcIssue`, `hostGpuDetected`, `sandboxGpuEnabled`, `sandboxGpuMode`, `sandboxGpuDevice`, `openshellDriver`, `openshellVersion`, `policies`, `policiesAvailable`, `llamaCpp`, `failureLayer`, `terminalRuntimeHealth`, `servingProcessHealth`, and `dockerPaused`. `policies` is derived from the current OpenShell policy; NemoClaw does not persist a second preset list or baseline-exclusion ledger. `policiesAvailable` is `false` when that live policy cannot be read or parsed, distinguishing an unavailable result from a verified empty `policies` array; text status prints `Policies: unavailable` for the same state. When the live gateway route matches the sandbox's recorded llama.cpp route, `llamaCpp.kind` is `attached`, `managed`, or `unavailable`. An attached route also includes its fixed loopback `llamaCpp.endpointUrl`. An unavailable result means NemoClaw could not safely verify the managed ownership receipt; it does not include an endpoint and provides a secret-free diagnostic and recovery action. During route drift, `status` omits the `llamaCpp` route attribution; inspect `routeDrift` before acting on endpoint information. Text status can still show managed-runtime details from the sandbox-owned receipt. The schema-version `1` `model` and `provider` fields keep their established live-route meaning when the gateway route is readable, except that a native hosted sandbox reports its recorded sandbox-scoped route because the shared route is unrelated. Use `recordedRoute` for the sandbox's durable provider and model and `liveRoute` for the gateway-global route. When the live shared route differs for a shared-route provider, text output prints both routes and JSON output sets `routeDrift.live`, `routeDrift.recorded`, and `routeDrift.canConnect`. Native hosted attachments do not report shared-route drift. When `routeDrift.canConnect` is `false`, `connect` cannot safely restore the recorded route because provider-global identity differs or required route or gateway metadata is incomplete. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for the route-sharing workflow. `openshellDriver` and `openshellVersion` are always strings (falling back to `"unknown"` when the registry has no value), so consumers can rely on `typeof` checks. `agent` is always a string and reports `openclaw` when the registry records no agent for the sandbox. `failureLayer` is `null` when no preflight failure was detected and otherwise one of `docker_unreachable`, `sandbox_container_stopped`, or `sandbox_dashboard_port_conflict`; when set, `inferenceHealth` is suppressed to `null` so automation does not see a stale remote-provider healthy status during a local outage. `inferenceHealth.ok` reports whether the selected provider path returned a structurally valid result for one request sent from inside the sandbox. The result must match Chat Completions, Responses, or Anthropic Messages for the selected route. An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. The probe captures at most 64 KiB and does not include the response body in diagnostics. The path probe treats any final HTTP status from `200` through `499` as reachable, so a route with an invalidated provider credential answers HTTP `401` while the path is up. Shared-route requests use the live gateway route's provider and model, then fall back to the recorded values when the live route is unreadable. Native hosted requests always use the sandbox's recorded provider and model. When the live shared provider matches the recorded provider, the request uses the sandbox's recorded API family, even when only the model differs. This includes `openai-responses`. When the live shared provider differs, NemoClaw does not carry the recorded API family to that provider. Each attempt requests 16 reply tokens for ordinary providers or 256 for Gemini. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Hosted requests consume provider tokens on every attempt. When the inference request returns HTTP `429`, `502`, `503`, or `504`, `status` retries the provider path and inference request together up to three total attempts, with a two-second delay between failed attempts, because those statuses are transient gateway and availability answers rather than evidence that the path is broken. Before each retry, it writes the failed probe boundary, an HTTP status when one is available, the next attempt, total attempts, and delay to stderr; `--json` keeps stdout machine-readable. On an ordinary run, every other failure is final on the first attempt with no delay: HTTP `401`, `403`, `404`, and `500`, an invalid 2xx response body, a request that returned no HTTP status, and a failing provider-path probe. When the same run recovers a managed gateway, `status` retries any failed route or inference probe on that schedule instead, while the restarted delivery chain settles. Each route probe has a 10-second timeout. Three complete route probes plus their 95-second inference wrappers and two delays can take about 319 seconds. When NemoClaw sends an inference request, `inferenceHealth.subprobes` reports the provider-path result as the `route reachability` hop, so a failing verdict still shows that the path itself answered. `inferenceHealth.failureLabel` reports why the inference request failed: - `unauthorized` when the route rejected it with HTTP `401` or `403`. - `unhealthy` when the route returned another failing HTTP status or an invalid 2xx response body. @@ -1694,7 +1694,7 @@ $$nemoclaw my-assistant status --json $$nemoclaw sandbox status my-assistant --json ``` -The command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses the sandbox-attached provider for `https://integrate.api.nvidia.com/v1`. That inference request is the authoritative inference health check, and both checks exercise the path that agent traffic uses. The main `Inference` line reports one of these states: +The command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local/v1`. That inference request is the authoritative inference health check, and both checks exercise the path that agent traffic uses. The main `Inference` line reports one of these states: | State | Meaning | | --- | --- | @@ -1706,9 +1706,9 @@ The command probes the selected provider path from inside the sandbox, and when | `not probed` | NemoClaw could not run the authoritative route probe from a reachable sandbox. | | `not verified` | NemoClaw could not verify the sandbox or gateway state, so it skips inference probing. | -An authentication response on a shared gateway route probe confirms that the route is reachable, not that provider credentials are valid. For those shared routes, `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. The native NVIDIA doctor probe is different: it verifies the sandbox-attached provider directly and requires a 2xx response. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. +An authentication response on a shared gateway route probe confirms that the route is reachable, not that provider credentials are valid. For those shared routes, `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. Native hosted checks first verify the recorded sandbox-attached provider. NVIDIA Endpoints requires a 2xx models response; other fixed hosted providers require a structurally valid response to an inference request for the recorded model. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. -The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` sends no inference request, so it always reports the `Inference (upstream)` state that it measured. +The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` always reports the `Inference (upstream)` state that it measured; that host-side diagnostic does not override its authoritative sandbox check. Local providers add host-side backend diagnostics. For Local Ollama, the command can also print an `Inference (auth proxy)` diagnostic when a proxy token is available. Use these diagnostics to identify a failing auxiliary hop after checking the main `Inference` line. @@ -1850,7 +1850,7 @@ The `Registered gateway binding` result depends on the sandbox registry: - For an unregistered sandbox name, `doctor` uses the gateway selected by `NEMOCLAW_GATEWAY_PORT` for its other gateway checks and omits the `Registered gateway binding` check. -For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Most providers probe the shared gateway route at `https://inference.local/v1/models`; responses from `200` through `499`, including `401` and `403`, pass that reachability check. NVIDIA Endpoints instead probes its sandbox-attached provider at `https://integrate.api.nvidia.com/v1/models` and requires a 2xx response. For the shared route, HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. For native NVIDIA, any non-2xx response or unavailable probe fails it. Host-side upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox path is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. +For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Custom, local, and Model Router selections probe the shared gateway route at `https://inference.local/v1/models`; responses from `200` through `499`, including `401` and `403`, pass that reachability check. NVIDIA Endpoints instead probes its sandbox-attached provider at `https://integrate.api.nvidia.com/v1/models` and requires a 2xx response. For the shared route, HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. For native NVIDIA, any non-2xx response or unavailable probe fails it. Other fixed hosted providers verify their recorded sandbox attachment and send an inference request to the selected native endpoint; a missing attachment, failed request, or invalid response fails the check. Host-side upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox path is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. Warnings do not make the command fail. Failed checks, including a failed or unavailable authoritative inference route, exit non-zero so scripts can use `doctor` as a readiness gate. Use `--json` for machine-readable output. For a `compatible-endpoint` route that uses `openai-completions`, the JSON report includes an informational `Inference` check labeled `Reasoning effort`. The check reports `low`, `medium`, `high`, or `endpoint-default` and never includes credentials. Because the check has `info` status, it does not change the command's exit status. @@ -2046,7 +2046,7 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet` -`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. Most model traffic uses the OpenShell-managed `inference.local` route. NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. +`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the OpenShell-managed `inference.local` route. @@ -3216,7 +3216,7 @@ After the rebuild succeeds, retrieve the replacement token with `nemohermes my-a
-After restore, the command starts Deep Agents with the complete source native home, including `config.toml`, hooks, skills, memories, histories, packages, and unrelated native entries. Before changing the sandbox, rebuild verifies that the recorded provider path is still reachable and that the target provider, model, reasoning settings, web search selection, base image, current agent MCP source, and current live OpenShell policy can be captured. Most providers use `inference.local`; NVIDIA Endpoints uses its sandbox-attached provider at `integrate.api.nvidia.com`. If those checks fail after backup, NemoClaw keeps the existing sandbox intact. Use rebuild after a failed Deep Agents version check, after enabling Tavily Search, or as the apply step for legacy MCP migration. +After restore, the command starts Deep Agents with the complete source native home, including `config.toml`, hooks, skills, memories, histories, packages, and unrelated native entries. Before changing the sandbox, rebuild verifies that the recorded provider path is still reachable and that the target provider, model, reasoning settings, web search selection, base image, current agent MCP source, and current live OpenShell policy can be captured. Custom, local, and Model Router selections use `inference.local`; fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. If those checks fail after backup, NemoClaw keeps the existing sandbox intact. Use rebuild after a failed Deep Agents version check, after enabling Tavily Search, or as the apply step for legacy MCP migration. @@ -3516,7 +3516,7 @@ Switch the active inference provider or model for a NemoClaw-managed Hermes sand By default, the command syncs the default registered sandbox. -For providers other than NVIDIA Endpoints, each OpenShell gateway exposes one shared inference route to every sandbox registered on that gateway. NVIDIA Endpoints instead uses a sandbox-attached provider and does not change the shared route. +For custom, local, and Model Router selections, each OpenShell gateway exposes one shared inference route to every sandbox registered on that gateway. Fixed hosted providers use sandbox-attached providers and do not change the shared route. Before changing the route, NemoClaw compares it with every same-gateway registry entry, including stopped sandboxes. When only the provider or model differs, the command names the affected sandboxes and warns immediately before it re-points the shared route. Those sandboxes use the new live route until `connect`, onboarding, or another `inference set` command re-points it. diff --git a/docs/reference/enterprise-readiness.mdx b/docs/reference/enterprise-readiness.mdx index 48541df5164..12c44defe9b 100644 --- a/docs/reference/enterprise-readiness.mdx +++ b/docs/reference/enterprise-readiness.mdx @@ -82,7 +82,7 @@ Each row links to deeper documentation and, when a concrete fix is in progress, | Audit and session records | Supported with caveats | OpenClaw stores per-session JSONL event logs, and Hermes stores its own runtime state. Deep Agents Code has no equivalent session-log export, but it can emit bounded-content traces when you explicitly enable observability. Export is manual per sandbox. | | Resource quotas | Supported with caveats | The entrypoint applies best-effort process and file-descriptor limits (`ulimit -u 512`, `ulimit -n 65536`). Set hard limits through the container runtime for fail-closed enforcement. Refer to [Process Controls](../security/security-controls/process-controls). | | Cost and spend controls | Platform or partner-owned | Deny-by-default egress and routed inference reduce exfiltration and stray endpoints, but NemoClaw does not enforce per-token spend budgets. Set spend limits with your inference provider and monitor unattended agents. | -| Credential isolation | Supported | Inference credentials stay in OpenShell provider state and never enter the sandbox. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. CLI output redaction adds defense in depth, and OpenClaw sandboxes also run a memory secret scanner. Refer to [Credential Storage](../security/credential-storage) and [Security Best Practices](../security/best-practices). | +| Credential isolation | Supported | Inference credentials stay in OpenShell provider state and never enter the sandbox. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. CLI output redaction adds defense in depth, and OpenClaw sandboxes also run a memory secret scanner. Refer to [Credential Storage](../security/credential-storage) and [Security Best Practices](../security/best-practices). | | Upgrades and lifecycle | Supported with caveats | Upgrade NemoClaw, then run `$$nemoclaw rebuild` to recreate the sandbox with the current image while backing up and restoring its complete native home. Do not update the agent runtime in place inside the sandbox because the agent is image-pinned. Version attachment flexibility remains tracked in [#2217](https://github.com/NVIDIA/NemoClaw/issues/2217). | | State persistence | Supported | OpenShell preserves the native home/workspace across routine lifecycle operations. NemoClaw transfers the complete native tree during rebuild and recreation. Refer to [Persist Sandbox State](../manage-sandboxes/state-and-backups/create-and-restore-snapshots). | | Remote and cloud deployment | Supported with caveats | Provision a tested Linux host, connect over SSH, run the installer, and run `$$nemoclaw onboard`. For OpenClaw or Hermes, keep the agent dashboard bound to loopback and access it through SSH port forwarding. Automatic recovery after a host reboot is not guaranteed; follow the manual recovery flow in [Deploy to a Headless Server](../deployment/deploy-to-headless-server). | @@ -132,7 +132,7 @@ Use the following phrasing to describe NemoClaw accurately in customer and field - Describe NemoClaw as an open-source reference stack for running agents more safely inside OpenShell, in active development, rather than a finished enterprise control plane. - State that egress is deny-by-default and that an operator approves new endpoints, so the agent cannot reach arbitrary hosts. -- Explain that inference credentials remain in OpenShell provider state, so the sandbox never holds provider keys. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. +- Explain that inference credentials remain in OpenShell provider state, so the sandbox never holds provider keys. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. - Frame centralized fleet management, operator RBAC, enterprise SSO, and multi-tenant isolation as roadmap-only or out of scope today, and avoid presenting them as current capabilities. - Position cost controls and spend limits as provider-owned, and recommend setting provider-side limits for unattended agents. - When a customer hits a known limitation, point to the workaround in this guide and the tracked issue rather than promising a fix date. diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index 6c8f228a32e..1254884ecee 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -86,7 +86,8 @@ The separate `raw.githubusercontent.com` route lets Deep Agents Code follow GitH -When you select NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1` provider to the sandbox instead of using `inference.local` or the broader baseline compatibility rule. +Fixed hosted providers use restricted sandbox-attached OpenShell profiles for their selected endpoint, protocol paths, and agent binaries. +For NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1` provider to the sandbox instead of using `inference.local` or the broader baseline compatibility rule. This attached provider is the effective NVIDIA Endpoints route. Its profile permits only `GET /v1/models` and `POST /v1/chat/completions` at `integrate.api.nvidia.com:443` from the listed agent-runtime and readiness-verification binaries. The NVIDIA API key remains in OpenShell provider state and does not enter the sandbox. @@ -217,7 +218,7 @@ Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced ### Inference -Most providers use the OpenShell-managed `inference.local` route. NVIDIA Endpoints instead uses its least-privilege, sandbox-attached OpenShell provider at `integrate.api.nvidia.com`. In both cases, OpenShell mediates inference traffic and keeps provider credentials outside the sandbox. +Fixed hosted providers use their native endpoints through least-privilege, sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the OpenShell-managed `inference.local` route. In both cases, OpenShell mediates inference traffic and keeps provider credentials outside the sandbox. diff --git a/docs/reference/pi-support.mdx b/docs/reference/pi-support.mdx index f77581163fd..6e2a68cd2d2 100644 --- a/docs/reference/pi-support.mdx +++ b/docs/reference/pi-support.mdx @@ -33,7 +33,7 @@ Pi is a NemoClaw agent runtime. Docker is the initial compute runtime. Pi-specif | Host platform | Linux AMD64 or Linux ARM64 | | Compute runtime | Docker | | Managed API | OpenAI Chat Completions | -| Sandbox route | Shared: `https://inference.local/v1`; NVIDIA: `https://integrate.api.nvidia.com/v1` | +| Sandbox route | Fixed hosted: selected native endpoint; custom, local, and Model Router: `https://inference.local/v1` | | Qualification model | `nvidia/nemotron-3-super-120b-a12b` | | Interactive command | `pi` | | Headless command | `pi --no-approve --print` | @@ -60,11 +60,11 @@ Each receipt must match the protected inputs and an image digest in the candidat Pi reads a generated `/sandbox/.pi/agent/models.json` file. The file contains the model, managed route, API family, and a non-secret route placeholder. It does not contain the upstream provider credential. -The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. Most providers give Pi the managed `inference.local` route. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox for `integrate.api.nvidia.com`. Direct unmanaged provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. +The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. Supported fixed hosted providers give Pi their native endpoint through a least-privilege OpenShell provider attached to the sandbox. Custom, local, and Model Router selections use the managed `https://inference.local/v1` route. Direct unmanaged provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. -When Pi uses the recorded `openrouter-api` provider, `https://inference.local/v1/models` returns `HTTP 404` by design because NemoClaw's OpenRouter adapter serves Chat Completions without a model catalog. +When Pi uses the recorded `openrouter-api` provider, requests use the attached native OpenRouter endpoint and preserve its required attribution headers. NemoClaw reports the route ready only after a bounded inference request successfully serves the selected model. -If that request fails, the expected catalog response does not make the route ready. +If that request fails, a successful endpoint reachability check does not make the route ready. The initial qualification requires streaming, a structured `read` tool call, a successful tool result, and an independently checked final response with `nvidia/nemotron-3-super-120b-a12b`. diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 8199edd074a..72ff3de3426 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1995,7 +1995,7 @@ Verify that the inference provider endpoint is reachable from the host. Check th $$nemoclaw status ``` -The main `Inference` line probes the selected provider path from inside the sandbox and then sends an inference request over the same path, so it reflects the route the agent uses. Most providers use `https://inference.local`. NVIDIA Endpoints uses the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1/chat/completions`. When that request returns a transient gateway status, `status` repeats both probes up to three total attempts before it reports a failure. It prints the HTTP status, next attempt, and two-second delay to stderr before each retry; the configured timeout envelope for three complete probe pairs and two delays is about 124 seconds. If that line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. +The main `Inference` line probes the selected provider path from inside the sandbox and then sends an inference request over the same path, so it reflects the route the agent uses. Custom, local, and Model Router selections use `https://inference.local`. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. When that request returns a transient gateway status, `status` repeats both probes up to three total attempts before it reports a failure. It prints the HTTP status, next attempt, and two-second delay to stderr before each retry; refer to the [CLI commands reference](commands) for the current probe timeout envelope and token cost. If that line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. For local Ollama and local vLLM, `Inference (ollama backend)` or the corresponding local-backend line reports the host-side service separately. If a local-backend diagnostic fails, start the backend. For Local Ollama, current releases can also print `Inference (auth proxy)` when a proxy token is available. Docker Desktop on Windows Subsystem for Linux (WSL) reaches host loopback directly, so its auth-proxy diagnostic is non-authoritative. Native Docker Engine inside WSL is unqualified; enable Docker Desktop WSL integration, then rerun onboarding. diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index 5d369ef237c..4b155f7d98a 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -114,7 +114,7 @@ NemoClaw allows a credential source only in the process that is intended to hold | Execution path | Rule | |---|---| -| Host-brokered provider | Discover and use host credentials only through OpenShell-managed providers. Most providers expose `inference.local`; NVIDIA Endpoints uses a sandbox-attached least-privilege provider with placeholder credential rewriting. The sandbox receives no raw host credential. | +| Host-brokered provider | Discover and use host credentials only through OpenShell-managed providers. Custom, local, and Model Router selections expose `inference.local`; fixed hosted providers use sandbox-attached least-privilege providers with placeholder credential rewriting. The sandbox receives no raw host credential. | | Sandbox-direct provider | Keep only credential sources that are deliberately provisioned and reachable inside the sandbox. | | Ambient metadata provider | Disable SDK discovery when the metadata endpoint cannot exist across the sandbox boundary. Do not make an internal or link-local endpoint reachable merely to satisfy an automatic probe. | | New agent or provider | Declare the enabled credential sources and add agent-specific tests proving that unavailable sources are not probed. | @@ -144,7 +144,7 @@ NemoClaw's host-local Amazon Bedrock adapter runs outside this sandbox credentia #### Hermes Managed Inference Credential Discovery -NemoClaw configures Hermes with a custom provider. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. The shipped Hermes image does not install the optional native Bedrock dependency. +NemoClaw configures Hermes with a custom provider. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. The shipped Hermes image does not install the optional native Bedrock dependency. AWS credential discovery for supported Bedrock inference therefore remains in NemoClaw's host-local adapter, outside the sandbox. If direct Hermes Bedrock support is added later, it must apply the same unavailable-metadata rule and include Hermes-specific credential-probe acceptance tests before it is enabled. @@ -153,7 +153,7 @@ If direct Hermes Bedrock support is added later, it must apply the same unavaila #### Deep Agents Managed Inference Credential Discovery -NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. +NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. The sandbox receives a placeholder route key, not the upstream provider credential. The managed launchers reject credential-shaped environment values and upstream auth files before Deep Agents Code starts, so provider discovery stays on the host-side OpenShell boundary. If you need a new sandbox-direct credential source, design it as an explicit provider or MCP integration instead of placing secrets in `/sandbox/.deepagents`. @@ -305,7 +305,7 @@ The agent never receives the provider API key. | Aspect | Detail | |---|---| -| Default | Most providers use the shared `inference.local` route. NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell owns the credential and upstream endpoint in both cases. | +| Default | Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the shared `inference.local` route. OpenShell owns the credential and upstream endpoint in both cases. | | What you can change | You select a supported provider. NemoClaw selects and enforces that provider's managed path. | | Risk if bypassed | Adding an unowned provider endpoint to network policy bypasses NemoClaw's managed provider boundary and could let an agent use a stolen or hardcoded key. The NVIDIA Endpoints path is not a bypass: its checked-in OpenShell provider profile restricts the endpoint, methods, paths, and binaries, then rewrites a placeholder credential at the egress boundary. | | Recommendation | Do not add inference provider hosts to network policy for NemoClaw model traffic. Use the provider path created by onboarding. The `claude-code` preset is a separate opt-in exception for running the Claude Code CLI with its own credentials, not a way to configure NemoClaw inference. | diff --git a/docs/security/gateway-authentication-controls.mdx b/docs/security/gateway-authentication-controls.mdx index f1b341cb410..41be0218ed3 100644 --- a/docs/security/gateway-authentication-controls.mdx +++ b/docs/security/gateway-authentication-controls.mdx @@ -153,8 +153,8 @@ Hermes exposes an OpenAI-compatible API on the forwarded Hermes port and can opt Do not publish those endpoints on shared or public networks unless you put them behind your own access controls. NemoClaw keeps provider credentials in OpenShell. -NVIDIA Endpoints traffic uses the native NVIDIA endpoint through the sandbox-attached OpenShell provider. -Other managed inference providers continue to use `inference.local`. +Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. +Custom, local, and Model Router selections continue to use `inference.local`. Generated Hermes runtime files use OpenShell resolver placeholders for managed-tool and messaging credentials. Hermes startup rejects raw secret-shaped values in sandbox-visible environment or config fields, while allowing empty values, migration sentinels, OpenShell resolver placeholders, and expected Slack placeholder forms. diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index 9ec841cdd9f..cceae374c91 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -292,7 +292,7 @@ A registry-side tag change cannot silently select another managed sandbox image. For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. It removes only the exact legacy NemoClaw-generated profile for the selected managed provider and preserves other profiles. -The native NVIDIA route uses `integrate.api.nvidia.com` with an OpenShell-managed placeholder credential. It does not retain a supplied NVIDIA credential in the sandbox. +Fixed hosted providers use their selected native endpoints with OpenShell-managed placeholder credentials. They do not retain supplied provider credentials in the sandbox. Other unmanaged direct routes retain supplied credentials. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain. From ff6ae4bec4082b8d2eb8750f2254d18d1ae077e7 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 18:21:39 -0700 Subject: [PATCH 077/133] docs(inference): qualify native hosted platform evidence Signed-off-by: Deepak Jain --- ci/platform-matrix.json | 4 ++-- docs/reference/platform-support.mdx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index c9a7862c5bc..e5ae2a40c59 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -207,8 +207,8 @@ }, { "name": "Managed inference", - "status": "tested", - "notes": "Provider-routed model calls through OpenShell, transparent to the agent. Most providers use `inference.local` inside the sandbox; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table." + "status": "caveated", + "notes": "Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use `inference.local` inside the sandbox. OpenShell keeps provider credentials outside the sandbox. Existing tested paths retain their evidence; live qualification of the newly migrated OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider paths remains pending." }, { "name": "Declarative network policy", diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index 930500bbdee..4c9f119c874 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -135,7 +135,7 @@ Each row below is a launch-facing capability claim that NemoClaw makes in docs, |------------|--------|-------| | Guided onboarding | Tested | Single-command interactive wizard (`$$nemoclaw onboard`) that walks the user through inference provider selection, credential setup, and sandbox creation or update. It opens the agent dashboard when the selected runtime provides one. Non-interactive mode is supported with `--non-interactive` and `NEMOCLAW_*` environment variables for CI and scripted installs. | | Sandboxed execution | Tested with limitations | Landlock, seccomp, network namespace isolation, no-new-privileges, privilege dropping, and process limits (nproc 512 at `scripts/lib/sandbox-rlimits.sh:8`) are tested and on by default. OpenShell owns capability enforcement for managed entrypoints, exec processes, and connect shells; those paths do not call NemoClaw capability handling. Direct container runtimes that explicitly override the image user to root retain the existing compatibility drop and required `setpriv` transition. Direct container launches must configure capabilities at the container runtime. | -| Managed inference | Tested | Provider-routed model calls through OpenShell, transparent to the agent. Most providers use `inference.local` inside the sandbox; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table. | +| Managed inference | Tested with limitations | Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use `inference.local` inside the sandbox. OpenShell keeps provider credentials outside the sandbox. Existing tested paths retain their evidence; live qualification of the newly migrated OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider paths remains pending. | | Declarative network policy | Tested | YAML-defined egress with policy presets. Presets include `slack`, `discord`, `telegram`, `weather`, `openclaw-pricing`, `huggingface`, `npm`, `pypi`, `brew`, and others. Hot-reloadable at runtime with `$$nemoclaw policy add`. | | State persistence and rebuild transfer | Tested | OpenShell preserves the native agent home during routine lifecycle operations. Before destructive replacement, NemoClaw archives and integrity-checks the complete native home/workspace, then restores it into the replacement sandbox. | | Agent skills | Tested | Packaged agent skills are discoverable by Cursor, Claude Code, and other coding assistants under `.agents/skills/`. Skills also install into the sandbox with `$$nemoclaw skill install`. | From 2964a9ead4f0671157ad620e44ee94554cf1854b Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 19:01:32 -0700 Subject: [PATCH 078/133] fix(inference): complete hosted provider runtime contracts --- .../patch-managed-deepagents-code.py | 14 ++- ci/platform-matrix.json | 4 +- docs/inference/choose-inference-provider.mdx | 2 +- docs/inference/switch-providers.mdx | 2 +- docs/inference/verify-inference-route.mdx | 5 +- docs/reference/commands.mdx | 4 +- docs/reference/platform-support.mdx | 2 +- docs/reference/troubleshooting.mdx | 10 +- src/lib/inference/managed-dcode/identity.ts | 16 ++-- .../orchestration-native-nvidia.test.ts | 63 +++++++++++++ .../onboard/sandbox-create/orchestration.ts | 15 ++- .../sandbox-create/provider-publication.ts | 10 ++ src/lib/state/registry-normalization.test.ts | 65 ++++++++++++- ...ve-nvidia-provider-authority-state.test.ts | 60 +++++++----- .../native-nvidia-provider-authority-state.ts | 94 +++++-------------- .../native-nvidia-provider-authority.ts | 32 ++----- src/lib/state/registry/persistence.ts | 15 +-- src/lib/state/registry/types.ts | 1 - .../langchain-deepagents-code-config.test.ts | 17 ++++ ...eepagents-code-direct-module-patch.test.ts | 25 ++++- 20 files changed, 289 insertions(+), 167 deletions(-) diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index 0bc0b061def..a8cd099cb7a 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -471,10 +471,12 @@ def _get_provider_kwargs(provider: str, *, model_name: str | None = None) -> dic managed_reasoning_effort, ) - if provider not in {"openai", "openrouter"}: + if provider not in {"openai", "openrouter", "anthropic"}: raise ModelConfigError( "Only NemoClaw-managed inference providers are enabled" ) + if provider == "anthropic" and managed_inference_base_url() != "https://api.anthropic.com": + raise ModelConfigError("Anthropic requires the selected native Anthropic route") # Load once so malformed TOML still fails through the upstream config error # path, but do not consume mutable provider classes, credentials, params, or # endpoints from it. @@ -1565,13 +1567,21 @@ def _nemoclaw_codex_mount(self) -> None: def _nemoclaw_select_with_auth_check(self, model_spec: str, provider: str) -> None: if provider: - if provider not in {"openai", "openrouter"}: + if provider not in {"openai", "openrouter", "anthropic"}: self.app.notify( "Only NemoClaw-managed inference providers are enabled.", severity="warning", markup=False, ) return + from deepagents_code._nemoclaw_managed import managed_inference_base_url + if provider == "anthropic" and managed_inference_base_url() != "https://api.anthropic.com": + self.app.notify( + "Anthropic requires the selected native Anthropic route.", + severity="warning", + markup=False, + ) + return from deepagents_code.config_manifest import ( is_provider_package_installed, provider_install_extra, diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index e5ae2a40c59..2635b2d6c5a 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -95,9 +95,9 @@ }, { "name": "OpenRouter", - "status": "tested", + "status": "caveated", "endpoint_type": "OpenAI-compatible", - "notes": "First-class onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw registers the `openrouter-api` provider through OpenShell's `openai` profile with a host runtime adapter URL; host-side validation and runtime traffic send the default OpenRouter attribution headers." + "notes": "Onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw attaches the native OpenRouter provider for `https://openrouter.ai/api/v1`; host-side validation and agent requests preserve the required attribution headers. Live qualification of this migrated path remains pending." }, { "name": "OpenAI", diff --git a/docs/inference/choose-inference-provider.mdx b/docs/inference/choose-inference-provider.mdx index 6a6f993f28a..7b2fb6d574c 100644 --- a/docs/inference/choose-inference-provider.mdx +++ b/docs/inference/choose-inference-provider.mdx @@ -32,7 +32,7 @@ Use this status table to distinguish validated provider integrations from adapte | Provider | Status | Endpoint type | Notes | |----------|--------|---------------|-------| | NVIDIA Endpoints | Tested | OpenAI-compatible | Hosted models on integrate.api.nvidia.com | -| OpenRouter | Tested | OpenAI-compatible | First-class onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw registers the `openrouter-api` provider through OpenShell's `openai` profile with a host runtime adapter URL; host-side validation and runtime traffic send the default OpenRouter attribution headers. | +| OpenRouter | Tested with limitations | OpenAI-compatible | Onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw attaches the native OpenRouter provider for `https://openrouter.ai/api/v1`; host-side validation and agent requests preserve the required attribution headers. Live qualification of this migrated path remains pending. | | OpenAI | Tested | Native OpenAI-compatible | Uses OpenAI model IDs | | Other OpenAI-compatible endpoint | Tested with limitations | Custom OpenAI-compatible | Custom base-URL adapter for servers that implement OpenAI-compatible `/v1/chat/completions` or `/v1/responses`. Behavior on OpenAI-compatible proxies, gateways, and self-hosted implementations may vary; this row claims the adapter, not the universe of compatible endpoints. | | Anthropic | Tested | Native Anthropic | Uses anthropic-messages | diff --git a/docs/inference/switch-providers.mdx b/docs/inference/switch-providers.mdx index 871b2a689b4..f50e82a70b1 100644 --- a/docs/inference/switch-providers.mdx +++ b/docs/inference/switch-providers.mdx @@ -49,7 +49,7 @@ $$nemoclaw inference set --provider --model --sandbox ``` For `openrouter-api`, NemoClaw verifies the selected model through the sandbox before it commits agent configuration. -It skips the host-side provider probe because the OpenRouter adapter uses the sandbox-only `host.openshell.internal` route. +It verifies the native endpoint through the recorded sandbox-attached provider, preserving the required OpenRouter attribution headers. If sandbox verification fails, NemoClaw tries to restore the previous inference selection and does not commit the agent configuration. diff --git a/docs/inference/verify-inference-route.mdx b/docs/inference/verify-inference-route.mdx index d44a560e59e..65fc1f1fd93 100644 --- a/docs/inference/verify-inference-route.mdx +++ b/docs/inference/verify-inference-route.mdx @@ -43,8 +43,8 @@ The row reports `healthy` only when the route returns a structurally valid resul An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. Status diagnostics do not include the response body. An ordinary HTTP `404` from `/v1/models` reports an unhealthy route because the model catalog is absent. -The recorded `openrouter-api` provider uses NemoClaw's Chat Completions-only OpenRouter adapter. -Its models route returns `404` by design, so `status` requires a successful inference request before it reports the route as healthy. +OpenRouter uses its native `https://openrouter.ai/api/v1` endpoint through the recorded sandbox-attached provider. +Its status check requires a successful inference request for the selected model, with the required OpenRouter attribution headers. When the models route responds and `status` sends an inference request, a failing row names the endpoint that request used. When the models route itself does not respond, the row names the models route. An HTTP `401` or `403` response reports `unauthorized`. @@ -85,7 +85,6 @@ Each attempt allows 2 seconds for the route to return an HTTP response. For OpenClaw, this leaves time for client overhead before its 2.5-second provider preflight stops. A transport failure, an unsupported models-route HTTP 404, or HTTP 5xx leaves the onboarding session retryable at final verification. -For a supported OpenRouter agent, onboarding accepts the adapter's catalog 404 only after a bounded inference request validates the selected model. Onboarding retries any other 404 within its startup budget, then reports the missing model catalog and exits nonzero if the failure persists. Confirm the provider and model configuration and restore the endpoint's `/v1/models` route. Run `$$nemoclaw onboard --resume` to verify the retained session again without rebuilding a healthy sandbox. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 7a7f3d8cc97..d8cc679119c 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -4373,9 +4373,9 @@ Do not set `NEMOCLAW_PROVIDER=ollama` when onboarding a `nemocua` sandbox; that Choose a non-host-local inference provider instead. -When NemoCUA uses the recorded `openrouter-api` provider, `https://inference.local/v1/models` returns `HTTP 404` by design because NemoClaw's OpenRouter adapter serves Chat Completions without a model catalog. +When NemoCUA uses the recorded `openrouter-api` provider, it uses the native OpenRouter endpoint through a sandbox-attached provider. NemoClaw reports the route ready only after a bounded inference request successfully serves the selected model. -If that request fails, the expected catalog response does not make the route ready. +If that request fails, endpoint reachability alone does not make the route ready. | Variable | Format | Effect | | --- | --- | --- | diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index 4c9f119c874..09e63900e30 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -95,7 +95,7 @@ NemoClaw routes inference through the OpenShell gateway. Each row below is a pro | Provider | Status | Endpoint type | Notes | |----------|--------|---------------|-------| | NVIDIA Endpoints | Tested | OpenAI-compatible | Hosted models on integrate.api.nvidia.com | -| OpenRouter | Tested | OpenAI-compatible | First-class onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw registers the `openrouter-api` provider through OpenShell's `openai` profile with a host runtime adapter URL; host-side validation and runtime traffic send the default OpenRouter attribution headers. | +| OpenRouter | Tested with limitations | OpenAI-compatible | Onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw attaches the native OpenRouter provider for `https://openrouter.ai/api/v1`; host-side validation and agent requests preserve the required attribution headers. Live qualification of this migrated path remains pending. | | OpenAI | Tested | Native OpenAI-compatible | Uses OpenAI model IDs | | Other OpenAI-compatible endpoint | Tested with limitations | Custom OpenAI-compatible | Custom base-URL adapter for servers that implement OpenAI-compatible `/v1/chat/completions` or `/v1/responses`. Behavior on OpenAI-compatible proxies, gateways, and self-hosted implementations may vary; this row claims the adapter, not the universe of compatible endpoints. | | Anthropic | Tested | Native Anthropic | Uses anthropic-messages | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 72ff3de3426..4b77eb551ff 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1284,10 +1284,10 @@ curl -fsSL https://www.nvidia.com/nemoclaw.sh | bash ### Onboarding reports a model-catalog HTTP 404 -NemoClaw's OpenRouter adapter serves Chat Completions but does not serve a model catalog. -An `HTTP 404` response from `https://inference.local/v1/models` is expected when the recorded provider is `openrouter-api`. -NemoClaw accepts that response only after a bounded inference request serves the selected model. -Onboarding and `status` report the route ready when that request succeeds. +OpenRouter uses a sandbox-attached provider at `https://openrouter.ai/api/v1`. +Onboarding and `status` verify the selected model with an inference request through that provider. +They do not use the shared `inference.local` model catalog for OpenRouter. +For a custom or local shared route, a missing model catalog remains a failure to investigate. Re-check the route and the recorded provider and model: @@ -1295,7 +1295,7 @@ Re-check the route and the recorded provider and model: $$nemoclaw status ``` -If the inference request fails, `status` reports that failure instead of accepting the catalog response. +If the inference request fails, `status` reports that failure and leaves model health unverified. Confirm the OpenRouter credential and selected model, then continue the recorded session: ```bash diff --git a/src/lib/inference/managed-dcode/identity.ts b/src/lib/inference/managed-dcode/identity.ts index 211cb7472e8..4545bc88c16 100644 --- a/src/lib/inference/managed-dcode/identity.ts +++ b/src/lib/inference/managed-dcode/identity.ts @@ -4,7 +4,7 @@ export const OPENROUTER_ENDPOINT_URL = "https://openrouter.ai/api/v1"; export const OPENROUTER_PROVIDER_NAME = "openrouter-api"; -export type ManagedDcodeProvider = "openai" | "openrouter"; +export type ManagedDcodeProvider = "openai" | "openrouter" | "anthropic"; export type ManagedDcodeIdentity = { provider: ManagedDcodeProvider; @@ -41,7 +41,7 @@ export function normalizeManagedDcodeEndpointUrl( export function normalizeManagedDcodeModelName(model: string): string { const trimmed = model.trim(); - for (const prefix of ["openai:", "openrouter:"]) { + for (const prefix of ["openai:", "openrouter:", "anthropic:"]) { if (trimmed.startsWith(prefix)) return trimmed.slice(prefix.length); } return trimmed; @@ -69,11 +69,13 @@ export function resolveManagedDcodeIdentity( ): ManagedDcodeIdentity { const providerName = upstreamProvider?.trim(); const provider = - providerName === "openrouter" || - providerName === OPENROUTER_PROVIDER_NAME || - (providerName === "compatible-endpoint" && isOpenRouterEndpointUrl(upstreamEndpointUrl)) - ? "openrouter" - : "openai"; + providerName === "anthropic-prod" + ? "anthropic" + : providerName === "openrouter" || + providerName === OPENROUTER_PROVIDER_NAME || + (providerName === "compatible-endpoint" && isOpenRouterEndpointUrl(upstreamEndpointUrl)) + ? "openrouter" + : "openai"; const normalizedModel = normalizeManagedDcodeModelName(model); return { provider, diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index 184e35a8f46..40334afd510 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -127,6 +127,69 @@ describe("native NVIDIA post-create provider verification", () => { expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); }); + it("publishes and verifies the physical provider for a logical OpenAI selection", async () => { + const adapter = providerAdapter(recordedProviderId); + vi.mocked(adapter.getProvider).mockResolvedValue({ + ok: true, + value: { + name: "nemoclaw-openai-api-v1", + type: "nemoclaw-openai-inference-v1", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { id: recordedProviderId, resourceVersion: 1 }, + }, + }); + adapter.updateProvider = vi.fn(async () => ({ ok: true as const })); + vi.mocked(adapter.listProviderAttachments).mockResolvedValue({ + ok: true, + value: { names: ["nemoclaw-openai-api-v1"] }, + }); + const revalidateSandboxIdentity = vi.fn(); + const preparationInput = { + openshellDriver: "docker" as const, + inferenceProvider: "openai-api", + messagingProviders: [], + messagingProviderRequests: [], + extraProviders: [], + gatewayName: "nemoclaw", + }; + const boundary = createProviderEffectBoundary({ + deferred: false, + sandboxName: "alpha", + gatewayName: "nemoclaw", + expectedNativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: recordedProviderId, + }, + preparationInput, + preparationDeps: { + runOpenshell: vi.fn() as never, + providerAdapter: adapter, + cleanupCreateSources: vi.fn(), + }, + runVerifiedSandboxCreateEffects: null, + activateDeferredProviderEffects: null, + revalidateSandboxIdentityBeforeCreate: revalidateSandboxIdentity, + }); + + await boundary.publishBeforeCreate(); + expect(revalidateSandboxIdentity).toHaveBeenCalledOnce(); + expect(adapter.updateProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: "nemoclaw-openai-api-v1", + credentials: [], + config: [], + }); + expect(boundary.runAfterVerifiedCreate).toBeTypeOf("function"); + await boundary.runAfterVerifiedCreate!(verifiedCreateContext(revalidateSandboxIdentity)); + expect(adapter.listProviderAttachments).toHaveBeenCalledWith( + expect.objectContaining({ sandboxName: "alpha" }), + ); + expect(preparationInput.inferenceProvider).toBe("openai-api"); + }); + it("rejects a replaced provider before changing its sandbox attachments", async () => { const adapter = providerAdapter("99999999-2222-4333-8444-555555555555"); adapter.attachProvider = vi.fn(); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 9014594cd14..36c74187066 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -86,6 +86,7 @@ import { } from "./identity-boundary"; import { publishAttachedProvidersBeforeDockerSandboxCreation, + resolveProviderPreparationInput, usesNativeHostedProvider, validateAttachedMessagingProvidersBeforeSandboxCreation, verifyNativeHostedAttachmentAfterCreate, @@ -1424,18 +1425,16 @@ export function createProviderEffectBoundary(input: { | null; readonly revalidateSandboxIdentityBeforeCreate: () => void; }): ProviderEffectBoundary { + const preparationInput = resolveProviderPreparationInput(input.preparationInput); const validate = async () => validateAttachedMessagingProvidersBeforeSandboxCreation( - input.preparationInput, + preparationInput, input.preparationDeps, ); const publish = async () => - publishAttachedProvidersBeforeDockerSandboxCreation( - input.preparationInput, - input.preparationDeps, - ); + publishAttachedProvidersBeforeDockerSandboxCreation(preparationInput, input.preparationDeps); const verifyNativeHostedAttachment = async (context: VerifiedSandboxCreateEffectsContext) => { - if (!usesNativeHostedProvider(input.preparationInput.inferenceProvider)) return; + if (!usesNativeHostedProvider(preparationInput.inferenceProvider)) return; context.revalidateSandboxIdentity( `attaching and verifying native hosted provider for sandbox '${input.sandboxName}'`, @@ -1443,7 +1442,7 @@ export function createProviderEffectBoundary(input: { await verifyNativeHostedAttachmentAfterCreate({ sandboxName: input.sandboxName, gatewayName: input.gatewayName, - inferenceProvider: input.preparationInput.inferenceProvider, + inferenceProvider: preparationInput.inferenceProvider, expected: input.expectedNativeHostedProviderAttachment, deps: input.preparationDeps, }); @@ -1455,7 +1454,7 @@ export function createProviderEffectBoundary(input: { input.revalidateSandboxIdentityBeforeCreate(); await publish(); }, - runAfterVerifiedCreate: usesNativeHostedProvider(input.preparationInput.inferenceProvider) + runAfterVerifiedCreate: usesNativeHostedProvider(preparationInput.inferenceProvider) ? verifyNativeHostedAttachment : undefined, }; diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index e187e34a91f..1a75b1042fb 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -63,6 +63,16 @@ function resolveProviderAdapter(deps: ProviderPreparationDeps): OpenShellProvide ); } +/** Keep logical selection metadata outside the OpenShell publication boundary. */ +export function resolveProviderPreparationInput( + input: ProviderPreparationInput, +): ProviderPreparationInput { + const profile = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.logicalProvider === input.inferenceProvider, + ); + return { ...input, inferenceProvider: profile?.providerName ?? input.inferenceProvider }; +} + export function usesNativeHostedProvider(inferenceProvider: string | null): boolean { return NATIVE_HOSTED_PROFILES.some((profile) => profile.providerName === inferenceProvider); } diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index 9720044a5a1..e3d745f83cb 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -39,6 +39,64 @@ afterEach(() => { }); describe("sandbox registry normalization", () => { + it("migrates NVIDIA ownership to one durable authority and shares compatibility API cleanup", async () => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "nvidia-owned", + } as const; + const { home, registry } = await loadRegistryDocument({ + sandboxes: {}, + nativeNvidiaProviderAuthorities: { first: receipt }, + }); + const migrated = registry.load(); + expect(migrated).not.toHaveProperty("nativeNvidiaProviderAuthorities"); + expect(registry.getNativeHostedProviderAuthority("first", receipt.profileId)).toEqual(receipt); + registry.save(migrated); + const disk = JSON.parse( + fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8"), + ); + expect(disk).not.toHaveProperty("nativeNvidiaProviderAuthorities"); + expect(disk.gatewayNativeHostedProviderAuthorities).toEqual({ first: [receipt] }); + expect(() => + registry.setNativeNvidiaProviderAuthority("first", { ...receipt, providerId: "foreign" }), + ).toThrow("Conflicting native provider ownership receipts"); + expect(() => + registry.setNativeHostedProviderAuthority("first", { ...receipt, providerId: "foreign" }), + ).toThrow("Conflicting native provider ownership receipts"); + expect(registry.getNativeNvidiaProviderAuthority("first")).toEqual(receipt); + registry.clearNativeHostedProviderAuthority("first", receipt.profileId); + expect(registry.getNativeNvidiaProviderAuthority("first")).toBeUndefined(); + registry.setNativeNvidiaProviderAuthority("first", receipt); + expect(registry.getNativeHostedProviderAuthority("first", receipt.profileId)).toEqual(receipt); + registry.clearNativeNvidiaProviderAuthority("first"); + expect(registry.load().gatewayNativeHostedProviderAuthorities).toBeUndefined(); + }); + + it("refuses conflicting disk authority without rewriting its recovery evidence", async () => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "original", + }; + const document = { + sandboxes: {}, + nativeNvidiaProviderAuthorities: { first: receipt }, + gatewayNativeHostedProviderAuthorities: { + first: [{ ...receipt, providerId: "replacement" }], + }, + }; + const { home, registry } = await loadRegistryDocument(document); + expect(() => registry.getNativeNvidiaProviderAuthority("first")).toThrow( + "Conflicting native provider ownership receipts", + ); + expect( + JSON.parse(fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8")), + ).toEqual(document); + }); + it("retains hosted registration ownership per gateway and profile and refuses replacement", async () => { const { registry } = await loadRegistryDocument({ sandboxes: {} }); const openai = { @@ -182,7 +240,6 @@ describe("sandbox registry normalization", () => { }, }, nativeNvidiaProviderAuthorities: { - broken: { ...receipt, providerId: "" }, "nemoclaw-19080": receipt, }, }); @@ -193,9 +250,9 @@ describe("sandbox registry normalization", () => { ...receipt, providerId: "22222222-3333-4444-8555-666666666666", }); - expect(registry.load().nativeNvidiaProviderAuthorities).toEqual({ - "nemoclaw-19080": receipt, - "nemoclaw-19081": { ...receipt, providerId: "22222222-3333-4444-8555-666666666666" }, + expect(registry.load().gatewayNativeHostedProviderAuthorities).toEqual({ + "nemoclaw-19080": [receipt], + "nemoclaw-19081": [{ ...receipt, providerId: "22222222-3333-4444-8555-666666666666" }], }); registry.clearNativeNvidiaProviderAuthority("nemoclaw-19080"); expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toBeUndefined(); diff --git a/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts b/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts index 23d620d846f..86d57042ada 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts @@ -2,39 +2,49 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; -import { - applyNativeNvidiaProviderAuthority, - normalizeNativeNvidiaProviderAuthorities, - readNativeNvidiaProviderAuthority, - removeNativeNvidiaProviderAuthority, -} from "./native-nvidia-provider-authority-state"; +import { normalizeGatewayNativeHostedAuthorities } from "./native-nvidia-provider-authority-state"; const receipt = { schemaVersion: 1 as const, - profileId: "nemoclaw-nvidia-inference-v1" as const, - providerName: "nemoclaw-nvidia-prod-v1" as const, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", providerId: "11111111-2222-4333-8444-555555555555", }; -describe("native NVIDIA gateway provider authority", () => { - it("normalizes, reads, and removes gateway-scoped receipts", () => { - const state: { - nativeNvidiaProviderAuthorities?: Record; - } = {}; +describe("gateway native provider authority migration", () => { + it("merges legacy NVIDIA ownership into sorted gateway records without duplicating identities", () => { + expect( + normalizeGatewayNativeHostedAuthorities( + { zeta: [receipt] }, + { zeta: receipt, alpha: receipt }, + ), + ).toEqual({ alpha: [receipt], zeta: [receipt] }); + }); - expect(applyNativeNvidiaProviderAuthority(state, "nemoclaw-19080", receipt)).toBe(true); - expect(readNativeNvidiaProviderAuthority(state, "nemoclaw-19080")).toEqual(receipt); - expect(removeNativeNvidiaProviderAuthority(state, "nemoclaw-19080")).toBe(true); - expect(state.nativeNvidiaProviderAuthorities).toBeUndefined(); + it("migrates a valid gateway name that matches an inherited object property", () => { + expect(normalizeGatewayNativeHostedAuthorities(undefined, { constructor: receipt })).toEqual({ + constructor: [receipt], + }); }); - it("drops malformed receipts and sorts gateway keys", () => { - expect( - normalizeNativeNvidiaProviderAuthorities({ - zeta: receipt, - broken: { ...receipt, providerId: "" }, - alpha: receipt, - }), - ).toEqual({ alpha: receipt, zeta: receipt }); + it("refuses conflicting legacy and hosted identities", () => { + expect(() => + normalizeGatewayNativeHostedAuthorities( + { alpha: [{ ...receipt, providerId: "replacement" }] }, + { alpha: receipt }, + ), + ).toThrow("Conflicting native provider ownership receipts"); + }); + + it.each([ + null, + [], + "invalid", + { alpha: { ...receipt, providerId: "" } }, + { "../gateway": receipt }, + ])("refuses malformed legacy authority instead of dropping ownership: %j", (legacy) => { + expect(() => normalizeGatewayNativeHostedAuthorities(undefined, legacy)).toThrow( + "Invalid legacy native NVIDIA", + ); }); }); diff --git a/src/lib/state/registry/native-nvidia-provider-authority-state.ts b/src/lib/state/registry/native-nvidia-provider-authority-state.ts index c3189ece6f3..97facd2d1a9 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority-state.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority-state.ts @@ -1,85 +1,43 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import { - normalizeNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; -import { normalizeNativeHostedProviderAuthorities } from "../../inference/native-hosted/authority"; + normalizeNativeHostedProviderAuthorities, + retainNativeHostedProviderAuthority, +} from "../../inference/native-hosted/authority"; import type { NativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; import { isValidName } from "../../name-validation"; -export interface NativeNvidiaProviderAuthorityState { - nativeNvidiaProviderAuthorities?: Record; -} - -export function normalizeNativeNvidiaProviderAuthorities( - value: unknown, -): Record | undefined { - if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; - const normalized: Record = Object.create(null); - for (const [gatewayName, candidate] of Object.entries(value)) { - const receipt = normalizeNativeNvidiaProviderAttachment(candidate); - if (!isValidName(gatewayName) || !receipt) continue; - normalized[gatewayName] = receipt; - } - const sorted = Object.fromEntries( - Object.entries(normalized).sort(([left], [right]) => left.localeCompare(right)), - ); - return Object.keys(sorted).length > 0 ? sorted : undefined; -} - -export function readNativeNvidiaProviderAuthority( - state: NativeNvidiaProviderAuthorityState, - gatewayName: string, -): NativeNvidiaProviderAttachment | undefined { - if (!isValidName(gatewayName)) return undefined; - return normalizeNativeNvidiaProviderAttachment( - state.nativeNvidiaProviderAuthorities?.[gatewayName], - ); -} - -export function applyNativeNvidiaProviderAuthority( - state: NativeNvidiaProviderAuthorityState, - gatewayName: string, - receipt: NativeNvidiaProviderAttachment, -): boolean { - const normalized = normalizeNativeNvidiaProviderAttachment(receipt); - if (!isValidName(gatewayName) || !normalized) return false; - const previous = readNativeNvidiaProviderAuthority(state, gatewayName); - if (previous?.providerId === normalized.providerId) return false; - state.nativeNvidiaProviderAuthorities = { - ...(state.nativeNvidiaProviderAuthorities ?? {}), - [gatewayName]: normalized, - }; - return true; -} - -export function removeNativeNvidiaProviderAuthority( - state: NativeNvidiaProviderAuthorityState, - gatewayName: string, -): boolean { - if (!isValidName(gatewayName) || !state.nativeNvidiaProviderAuthorities?.[gatewayName]) { - return false; - } - const next = { ...state.nativeNvidiaProviderAuthorities }; - delete next[gatewayName]; - if (Object.keys(next).length > 0) state.nativeNvidiaProviderAuthorities = next; - else delete state.nativeNvidiaProviderAuthorities; - return true; -} - +// Slice 1 receipts remain readable, but only the hosted map is runtime authority. export function normalizeGatewayNativeHostedAuthorities( value: unknown, + legacy: unknown = undefined, ): Record | undefined { - if (value === undefined) return undefined; - if (!value || typeof value !== "object" || Array.isArray(value)) + if (value === undefined && legacy === undefined) return undefined; + if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value))) throw new Error("Invalid gateway native provider authorities"); - const entries = Object.entries(value).map(([gatewayName, receipts]) => { + const entries = Object.entries(value ?? {}).map(([gatewayName, receipts]) => { if (!isValidName(gatewayName)) throw new Error("Invalid native provider authority gateway"); return [gatewayName, normalizeNativeHostedProviderAuthorities(receipts) ?? []] as const; }); - return Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right))); + const merged: Record = Object.assign( + Object.create(null), + Object.fromEntries(entries), + ); + if (legacy !== undefined) { + if (!legacy || typeof legacy !== "object" || Array.isArray(legacy)) + throw new Error("Invalid legacy native NVIDIA provider authorities"); + for (const [gatewayName, candidate] of Object.entries(legacy)) { + const receipt = normalizeNativeNvidiaProviderAttachment(candidate); + if (!isValidName(gatewayName) || !receipt) + throw new Error("Invalid legacy native NVIDIA provider authority"); + merged[gatewayName] = retainNativeHostedProviderAuthority(merged[gatewayName], receipt); + } + } + return Object.fromEntries( + Object.entries(merged).sort(([left], [right]) => left.localeCompare(right)), + ); } export { isValidName as isValidNativeProviderGateway }; diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index 5c0ac8fc683..7a6c285b453 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -11,12 +11,10 @@ import { } from "../../inference/native-hosted/authority"; import { isValidNativeProviderGateway as isValidName } from "./native-nvidia-provider-authority-state"; -import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import { - applyNativeNvidiaProviderAuthority, - readNativeNvidiaProviderAuthority, - removeNativeNvidiaProviderAuthority as applyRemoveNativeNvidiaProviderAuthority, -} from "./native-nvidia-provider-authority-state"; + normalizeNativeNvidiaProviderAttachment, + type NativeNvidiaProviderAttachment, +} from "../../inference/native-nvidia"; import type { SandboxRegistry } from "./types"; import { withLock } from "./lock"; import { load, save } from "./persistence"; @@ -24,32 +22,22 @@ import { load, save } from "./persistence"; export function getNativeNvidiaProviderAuthority( gatewayName: string, ): NativeNvidiaProviderAttachment | undefined { - return readNativeNvidiaProviderAuthority(load(), gatewayName); + return normalizeNativeNvidiaProviderAttachment( + getNativeHostedProviderAuthority(gatewayName, "nemoclaw-nvidia-inference-v1"), + ); } export function setNativeNvidiaProviderAuthority( gatewayName: string, receipt: NativeNvidiaProviderAttachment, ): void { - withLock(() => { - const data = load(); - const existing = readNativeNvidiaProviderAuthority(data, gatewayName); - if (existing?.providerId === receipt.providerId) return; - if (!applyNativeNvidiaProviderAuthority(data, gatewayName, receipt)) { - throw new Error("Cannot record invalid native NVIDIA gateway provider authority"); - } - save(data); - }); + if (receipt.profileId !== "nemoclaw-nvidia-inference-v1") + throw new Error("Invalid native NVIDIA gateway provider authority"); + setNativeHostedProviderAuthority(gatewayName, receipt); } export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { - withLock(() => { - const data = load(); - const removedNvidia = applyRemoveNativeNvidiaProviderAuthority(data, gatewayName); - const removedHosted = removeHostedAuthority(data, gatewayName, "nemoclaw-nvidia-inference-v1"); - if (!removedNvidia && !removedHosted) return; - save(data); - }); + clearNativeHostedProviderAuthority(gatewayName, "nemoclaw-nvidia-inference-v1"); } export function getNativeHostedProviderAuthority( diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index 5c6fb5ed54e..b3bb2abe749 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -11,7 +11,6 @@ import { isDeferredN1xManagedVllmAcceptanceRoute } from "../../domain/sandbox/n1 import { parseServingProfileProvenance } from "../../inference/serving/profile-provenance"; import { readConfigFile, writeConfigFile } from "../config-io"; import { normalizeExtraProviders } from "../extra-providers"; -import { normalizeNativeNvidiaProviderAuthorities } from "./native-nvidia-provider-authority-state"; import { cloneSandboxMessagingState, serializeSandboxMessagingStateForDisk, @@ -128,9 +127,6 @@ export function save(data: SandboxRegistry): void { function normalizeRegistry(value: unknown): SandboxRegistry { const data = isObjectRecord(value) ? value : {}; const extraProviders = normalizeExtraProviders(data.extraProviders); - const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( - data.nativeNvidiaProviderAuthorities, - ); const sandboxes = Object.fromEntries( parseSandboxRegistryEntries(data.sandboxes).map(([name, entry]) => [ name, @@ -148,20 +144,15 @@ function normalizeRegistry(value: unknown): SandboxRegistry { }; const hostedAuthorities = normalizeGatewayNativeHostedAuthorities( data.gatewayNativeHostedProviderAuthorities, + Reflect.get(data, "nativeNvidiaProviderAuthorities"), ); if (hostedAuthorities) base.gatewayNativeHostedProviderAuthorities = hostedAuthorities; if (extraProviders) base.extraProviders = extraProviders; - if (nativeNvidiaProviderAuthorities) { - base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; - } return base; } function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { const extraProviders = normalizeExtraProviders(data.extraProviders); - const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( - data.nativeNvidiaProviderAuthorities, - ); const sandboxes = Object.fromEntries( Object.entries(data.sandboxes).map(([name, entry]) => [ name, @@ -182,12 +173,10 @@ function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { }; const hostedAuthorities = normalizeGatewayNativeHostedAuthorities( data.gatewayNativeHostedProviderAuthorities, + Reflect.get(data, "nativeNvidiaProviderAuthorities"), ); if (hostedAuthorities) base.gatewayNativeHostedProviderAuthorities = hostedAuthorities; if (extraProviders) base.extraProviders = extraProviders; - if (nativeNvidiaProviderAuthorities) { - base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; - } return base; } diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 9bf44ece2b6..6c410d85c13 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -242,6 +242,5 @@ export interface SandboxRegistry { defaultSelectionRevision?: number; extraProviders?: string[]; /** Exact NemoClaw-owned native NVIDIA provider identity for each OpenShell gateway. */ - nativeNvidiaProviderAuthorities?: Record; gatewayNativeHostedProviderAuthorities?: Record; } diff --git a/test/agents/deepagents/langchain-deepagents-code-config.test.ts b/test/agents/deepagents/langchain-deepagents-code-config.test.ts index cac220691bb..72b969c6080 100644 --- a/test/agents/deepagents/langchain-deepagents-code-config.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-config.test.ts @@ -114,6 +114,23 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).not.toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); }); + it("selects the Anthropic Messages client for native Anthropic inference (#12589)", () => { + const config = runGenerator({ + NEMOCLAW_MODEL: "anthropic:claude-sonnet-4-5-20250929", + NEMOCLAW_UPSTREAM_PROVIDER: "anthropic-prod", + NEMOCLAW_INFERENCE_BASE_URL: "https://api.anthropic.com", + NEMOCLAW_INFERENCE_API: "anthropic-messages", + }); + + expect(config).toContain('default = "anthropic:claude-sonnet-4-5-20250929"'); + expect(config).toContain("[models.providers.anthropic]"); + expect(config).toContain('models = ["claude-sonnet-4-5-20250929"]'); + expect(config).toContain('api_key_env = "ANTHROPIC_API_KEY"'); + expect(config).toContain('base_url = "https://api.anthropic.com"'); + expect(config).not.toContain("[models.providers.openai"); + expect(config).not.toContain("use_responses_api"); + }); + it("keeps the legacy provider key when the renamed route variables are absent", () => { const config = runGenerator({ NEMOCLAW_PROVIDER_KEY: "legacy-route", diff --git a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts index f266327ac15..756ce785232 100644 --- a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts @@ -1136,9 +1136,30 @@ async def validate(): try: config._get_provider_kwargs("anthropic") except model_config.ModelConfigError as exc: - assert "managed inference providers" in str(exc) + assert "selected native Anthropic route" in str(exc) else: - raise AssertionError("non-managed model provider was allowed") + raise AssertionError("Anthropic was allowed on an unrelated managed route") + from deepagents_code import _nemoclaw_managed as managed_runtime + original_base_url = managed_runtime.managed_inference_base_url + original_api_key = managed_runtime.managed_inference_api_key + managed_runtime.managed_inference_base_url = lambda: "https://api.anthropic.com" + managed_runtime.managed_inference_api_key = lambda: "openshell:resolve:env:v1_ANTHROPIC_API_KEY" + try: + assert config._get_provider_kwargs("anthropic") == { + "api_key": "openshell:resolve:env:v1_ANTHROPIC_API_KEY", + "base_url": "https://api.anthropic.com", + } + selector._select_with_auth_check("anthropic:model", "anthropic") + assert selector.original_selection == ("anthropic:model", "anthropic") + try: + config._get_provider_kwargs("google_genai") + except model_config.ModelConfigError: + pass + else: + raise AssertionError("non-managed model provider was allowed") + finally: + managed_runtime.managed_inference_base_url = original_base_url + managed_runtime.managed_inference_api_key = original_api_key os.environ["LANGGRAPH_CLI_NO_ANALYTICS"] = "0" child_env = server._build_server_env() assert child_env["LANGGRAPH_NO_VERSION_CHECK"] == "true" From 352fbcd9981061e38c1585ea5a2fe70fd75466fc Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:12:39 -0700 Subject: [PATCH 079/133] docs(inference): clarify selected route output Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/verify-inference-route.mdx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/inference/verify-inference-route.mdx b/docs/inference/verify-inference-route.mdx index d75d7013b5b..f5ce92e2dab 100644 --- a/docs/inference/verify-inference-route.mdx +++ b/docs/inference/verify-inference-route.mdx @@ -14,14 +14,15 @@ Reading the active route confirms configuration, but it does not authenticate a ## Confirm the Configured Route -Read the live gateway route first. +Read the selected inference path first. ```bash $$nemoclaw inference get ``` -Confirm that the provider, model, and endpoint match the route you intended to configure. -NVIDIA Endpoints reports `https://integrate.api.nvidia.com/v1` instead of `inference.local`. +For a selected sandbox with a valid native NVIDIA attachment, the command returns that sandbox's recorded provider, model, and `https://integrate.api.nvidia.com/v1` endpoint. +For other providers, the command reads the live shared gateway route. +Confirm that the provider, model, and endpoint match the path you intended to configure. ## Check Sandbox Inference Health From 5a926f234e8735160798821164fd6712df692245 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 19:33:39 -0700 Subject: [PATCH 080/133] test(inference): align onboarding fixtures with native providers --- ci/test-file-size-budget.json | 2 +- test/e2e/mock-parity.json | 2 + test/helpers/onboard-script-mocks.cjs | 80 ++++++++++- .../onboard-custom-dockerfile.test.ts | 8 +- ...oard-extra-provider-reconciliation.test.ts | 7 +- .../onboard-fresh-create-identity.test.ts | 3 +- ...rmes-portable-provider-publication.test.ts | 34 ++++- .../onboard-installer-restore-intent.test.ts | 1 + .../onboard-messaging-reuse.test.ts | 124 ++++++++++++++++++ test/onboarding/onboard-messaging.test.ts | 111 ++-------------- .../onboard-prepared-build-context.test.ts | 1 + .../onboard-reservation-recreate.test.ts | 2 + test/onboarding/onboard-sandbox-build.test.ts | 5 + .../onboard-sandbox-recreation.test.ts | 6 + .../onboard-terminal-dashboard.test.ts | 1 + test/security/shellquote-sandbox.test.ts | 3 +- 16 files changed, 273 insertions(+), 117 deletions(-) create mode 100644 test/onboarding/onboard-messaging-reuse.test.ts diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 636d18c3681..616fc7dc3a5 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -7,7 +7,7 @@ "test/generation/generate-openclaw-config.test.ts": 1844, "test/installer-integration/install-preflight.test.ts": 2995, "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 3308, - "test/onboarding/onboard-messaging.test.ts": 1960, + "test/onboarding/onboard-messaging.test.ts": 1869, "test/onboarding/onboard-selection.test.ts": 4125 } } diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 946e82aa3d2..ed10ff83a45 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -777,6 +777,7 @@ "test/e2e/support/messaging-providers-installed-runtime-paths.test.ts", "test/e2e/support/messaging-providers-runtime-proofs.test.ts", "test/onboarding/onboard-messaging.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/runtime/messaging/messaging-build-applier.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", @@ -861,6 +862,7 @@ "test/e2e/support/openclaw-discord-pairing-helpers.test.ts", "test/e2e/support/messaging-providers-runtime-proofs.test.ts", "test/onboarding/onboard-messaging.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts" ] diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index f4912f118f3..d5622f8037a 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -225,6 +225,13 @@ function mockNvidiaProviderGetRun(command, gatewayName) { const request = parseNamedProviderGet(command, gatewayName); if (request === null) return null; if (request.error) return request.error; + if (request.providerName === "nemoclaw-nvidia-prod-v1") { + return { + status: 0, + stdout: + "Name: nemoclaw-nvidia-prod-v1\nType: nemoclaw-nvidia-inference-v1\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: \nId: provider-revision-1\nResource version: 1\n", + }; + } if (request.providerName !== "nvidia-prod") return null; return { status: 0, @@ -301,6 +308,7 @@ function createStatefulMessagingProviderRunner({ commands, initialProviders = [], createdSandbox = null, + nativeNvidiaProvider = false, }) { const providers = new Map( initialProviders.map(([name, type, credential]) => [name, { type, credential }]), @@ -322,6 +330,10 @@ function createStatefulMessagingProviderRunner({ const sandboxResult = createdSandbox?.run(command) ?? null; if (sandboxResult !== null) return sandboxResult; + if (nativeNvidiaProvider && args.at(-1) === "nemoclaw-nvidia-prod-v1") { + const nativeProvider = mockNvidiaProviderGetRun(command, "nemoclaw"); + if (nativeProvider !== null) return nativeProvider; + } const providerAction = providerIndex >= 0 ? args[providerIndex + 1] : null; if (providerAction === "profile") { const profileActionIndex = providerIndex + 2; @@ -379,6 +391,12 @@ function createStatefulMessagingProviderRunner({ : { status: 1, stderr: `provider '${name}' not found` }; } if (providerAction === "update") { + const nativeUpdateArgs = exactOpenShellArgs(command); + if ( + nativeNvidiaProvider && + nativeUpdateArgs?.join(" ") === "provider update -g nemoclaw nemoclaw-nvidia-prod-v1" + ) + return { status: 0 }; const name = providerNameAfterAction(args, providerIndex); const credentialIndex = args.indexOf("--credential"); const credential = credentialIndex >= 0 ? args[credentialIndex + 1] : null; @@ -526,7 +544,7 @@ function mockOnboardRunCapture(command, options = {}) { function exactOpenShellArgs(command) { const args = Array.isArray(command) ? command.map(String) : []; - const verbs = new Set(["gateway", "policy", "sandbox"]); + const verbs = new Set(["gateway", "policy", "sandbox", "provider"]); if (verbs.has(args[0])) return args; if (args.length > 1 && verbs.has(args[1])) return args.slice(1); if ( @@ -632,6 +650,7 @@ function createCreatedSandboxFixture(options = {}) { return nonces[0]; }; + let attachedProviders = []; const isCreated = () => state.lifecycleState === "created"; const observe = (command, allowPublishedUnscopedGet) => { const details = commandDetails(command); @@ -653,6 +672,16 @@ function createCreatedSandboxFixture(options = {}) { ? `Name: ${state.sandboxName}\nId: ${state.sandboxId}\nPhase: ${state.phase}\n` : ""; } + if ( + action === "provider" && + args[args.indexOf("sandbox") + 2] === "list" && + gatewayName === state.gatewayName && + args.at(-1) === state.sandboxName + ) { + return isCreated() + ? `NAME TYPE CREDENTIAL_KEYS CONFIG_KEYS\n${attachedProviders.map((name) => `${name} ${name === "nemoclaw-nvidia-prod-v1" ? "nemoclaw-nvidia-inference-v1" : "fixture-provider"} 1 0`).join("\n")}\n` + : ""; + } if (action !== "list") return null; const selectorIndex = args.indexOf("--selector"); @@ -724,6 +753,9 @@ function createCreatedSandboxFixture(options = {}) { if (state.lifecycleState !== "absent") { throw new Error("Created sandbox fixture cannot create a deleted sandbox."); } + attachedProviders = details.args.flatMap((arg, index) => + arg === "--provider" ? [details.args[index + 1]] : [], + ); state.createAttemptNonce = createAttemptNonce; state.ownerScopedIdentityObserved = false; assertState(); @@ -744,6 +776,9 @@ function createCreatedSandboxFixture(options = {}) { throw new Error("Created sandbox fixture can recreate only a deleted sandbox."); } const createAttemptNonce = nonceFromCreateCommand(command); + attachedProviders = commandDetails(command).args.flatMap((arg, index, args) => + arg === "--provider" ? [args[index + 1]] : [], + ); state.generation += 1; const replacementFingerprint = sandboxIdentity.fingerprintOpenShellSandboxId(initialSandboxId); state.sandboxId = `sbx-recreated-${state.generation}-${replacementFingerprint}`; @@ -798,11 +833,54 @@ function createCreatedSandboxFixture(options = {}) { }); } +// Direct-create tests bypass the onboarding machine, which normally supplies this +// receipt to the real create-plan resolver from the inference reservation. +function installNativeHostedCreateIntentFixture(sandboxName, profile) { + const owner = require( + path.resolve(__dirname, "../../src/lib/onboard/sandbox-create-intent-resolution.ts"), + ); + const createResolver = owner.createSandboxCreateIntentResolver; + owner.createSandboxCreateIntentResolver = (...args) => { + const resolver = createResolver(...args); + const resolvePortableLifecycle = resolver.resolvePortableLifecycle; + resolver.resolvePortableLifecycle = (input, options) => + resolvePortableLifecycle( + input.sandboxName === sandboxName && + input.inferenceProvider === profile.logicalProvider && + input.nativeHostedProviderAttachment === undefined && + !options.resolvedIntent + ? { + ...input, + inferenceProvider: profile.providerName, + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-revision-1", + }, + } + : input, + options, + ); + return resolver; + }; +} + function installVerifiedSandboxCreateFixture(registry, options) { const sandboxName = options.sandboxName; const gatewayName = options.gatewayName || "nemoclaw"; const gatewayPort = options.gatewayPort || 8080; mockStructuredOpenShellCaptureFromRunner({ gatewayName, gatewayPort, sandboxName }); + if ( + (options.nativeNvidiaCreateIntent === true && options.provider === "nvidia-prod") || + options.nativeHostedCreateIntent === true + ) { + const { nativeHostedProfile } = require( + path.resolve(__dirname, "../../src/lib/inference/native-hosted/profiles.ts"), + ); + const profile = nativeHostedProfile(options.provider); + if (profile) installNativeHostedCreateIntentFixture(sandboxName, profile); + } const sessionId = options.sessionId || "integration-fixture-session"; const selection = { provider: options.provider, diff --git a/test/onboarding/onboard-custom-dockerfile.test.ts b/test/onboarding/onboard-custom-dockerfile.test.ts index ed0b1251006..cb9d3682b26 100644 --- a/test/onboarding/onboard-custom-dockerfile.test.ts +++ b/test/onboarding/onboard-custom-dockerfile.test.ts @@ -238,11 +238,10 @@ runner.run = (command, opts = {}) => { commands.push({ command: normalized, env: opts.env || null }); const profileResult = fixtureMocks.mockManagedEndpointlessProviderProfileRun(command); if (profileResult !== null) return profileResult; - if (normalized.endsWith("provider get -g nemoclaw openai-api")) { + if (normalized.endsWith("provider get -g nemoclaw nemoclaw-openai-api-v1")) { return { - status: 1, - stdout: "", - stderr: "provider 'openai-api' not found", + status: 0, + stdout: "Name: nemoclaw-openai-api-v1\nType: nemoclaw-openai-inference-v1\nCredential keys: OPENAI_API_KEY\nConfig keys: \nId: provider-revision-1\nResource version: 1\n", }; } const sandboxResult = createdSandbox.run(command); @@ -263,6 +262,7 @@ runner.runCapture = (command) => { }; fixtureMocks.mockDockerSandboxLifecycleReleaseFromRunner(); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeHostedCreateIntent: true, sandboxName: "my-assistant", provider: "openai-api", model: "gpt-5.4", diff --git a/test/onboarding/onboard-extra-provider-reconciliation.test.ts b/test/onboarding/onboard-extra-provider-reconciliation.test.ts index 4f349ab19df..aa8be43687d 100644 --- a/test/onboarding/onboard-extra-provider-reconciliation.test.ts +++ b/test/onboarding/onboard-extra-provider-reconciliation.test.ts @@ -56,6 +56,7 @@ registry.addExtraProvider("brave-search"); registry.addExtraProvider("custom-provider"); registry.addExtraProvider("my-slack-bridge"); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -232,8 +233,10 @@ const createReservedSandbox = () => { "provider get -g nemoclaw custom-provider", "provider get -g nemoclaw my-slack-bridge", "provider get -g nemoclaw my-slack-bridge", - "provider get -g nemoclaw nvidia-prod", - "provider get -g nemoclaw nvidia-prod", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", "provider get -g nemoclaw tavily-search", ].sort(), ); diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index ec2f1eeabe2..b95d5f1683d 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -513,6 +513,7 @@ managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle = (input, deps = } const durableGetSandbox = registry.getSandbox.bind(registry); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", gatewayName: ${JSON.stringify(gatewayName)}, gatewayPort: ${String(gatewayPort)}, @@ -988,7 +989,7 @@ if (${JSON.stringify( assert.equal("policyAuthority" in payload.registeredSandbox, false); assert.equal("policyCreationReceipt" in payload.registeredSandbox, false); assert.match(payload.createCommand, /--policy \S+/u); - assert.match(payload.createCommand, /--provider nvidia-prod/u); + assert.match(payload.createCommand, /--provider nemoclaw-nvidia-prod-v1/u); }; const assertProviderlessApfCreation = () => { assertProviderlessInference(); diff --git a/test/onboarding/onboard-hermes-portable-provider-publication.test.ts b/test/onboarding/onboard-hermes-portable-provider-publication.test.ts index 858a20d1f74..727d92af4ff 100644 --- a/test/onboarding/onboard-hermes-portable-provider-publication.test.ts +++ b/test/onboarding/onboard-hermes-portable-provider-publication.test.ts @@ -37,9 +37,15 @@ type ProviderBoundaryResult = { result: string; }; +const expectedAttachmentCalls = [ + ["provider", "list", "-g", "nemoclaw", "my-assistant"], + ["provider", "get", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ["provider", "list", "-g", "nemoclaw", "my-assistant"], +]; const expectedProviderCalls = [ - ["provider", "get", "-g", "nemoclaw", "nvidia-prod"], - ["provider", "update", "-g", "nemoclaw", "nvidia-prod"], + ["provider", "get", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ["provider", "update", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ...expectedAttachmentCalls, ]; function shellQuote(value: string): string { @@ -152,11 +158,15 @@ runner.run = (command) => { if (providerArgs) providerCalls.push(providerArgs); const providerGet = fixtureMocks.mockNvidiaProviderGetRun(command, gatewayName); if (providerGet !== null) return providerGet; - if (text === "provider update -g nemoclaw nvidia-prod") { + const providerList = text === "provider list -g nemoclaw my-assistant" + ? { status: 0, stdout: "NAME TYPE CREDENTIAL_KEYS CONFIG_KEYS\n" + + "nemoclaw-nvidia-prod-v1 nemoclaw-nvidia-inference-v1 1 0\n" } + : null; + if (text === "provider update -g nemoclaw nemoclaw-nvidia-prod-v1") { events.push("provider:update"); return { status: 0, stdout: "" }; } - return createdSandbox.run(command) ?? { status: 0, stdout: "" }; + return providerList ?? createdSandbox.run(command) ?? { status: 0, stdout: "" }; }; runner.runCapture = (command) => { const captured = createdSandbox.capture(command); @@ -178,6 +188,7 @@ const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, gatewayName, agentName: portableMode ? "hermes" : "langchain-deepagents-code", provider: inferenceProvider, + nativeNvidiaCreateIntent: !portableMode, model: "gpt-5.4", }); if (!portableMode) { @@ -355,6 +366,12 @@ const { resolveSandboxGpuConfig } = require(${modulePath("onboard/sandbox-gpu-mo basePolicyPath: ${JSON.stringify(path.join(repoRoot, "agents/hermes/policy-additions.yaml"))}, sandboxName, inferenceProvider, + nativeHostedProviderAttachment: inferenceProvider === "nvidia-prod" ? { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-revision-1", + } : undefined, channels: [], enabledChannels: [], disabledChannelNames: new Set(), @@ -424,7 +441,9 @@ describe("sandbox-create provider publication branches", () => { "carries the real Portable caller request through the receipt-owned lifecycle adapter (#12119)", { timeout: 60_000 }, async () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-real-boundary-")); + const tmpDir = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-real-boundary-")), + ); const executablePath = path.join(tmpDir, "openshell"); const statePath = path.join(tmpDir, "sandbox-created"); const invocationPath = path.join(tmpDir, "openshell-invocations.log"); @@ -839,7 +858,10 @@ describe("sandbox-create provider publication branches", () => { const payload = runProviderBoundary("ordinary-resume"); assert.equal(payload.result, "my-assistant"); - assert.deepEqual(payload.providerCalls, expectedProviderCalls); + assert.deepEqual(payload.providerCalls, [ + ...expectedProviderCalls, + ...expectedAttachmentCalls, + ]); assert.equal(payload.portableTransactions, 0); assert.match(payload.firstError ?? "", /registry publication/u); assert.equal(payload.gpuCreateCalls, 2); diff --git a/test/onboarding/onboard-installer-restore-intent.test.ts b/test/onboarding/onboard-installer-restore-intent.test.ts index b67993f3b5d..f3a8fe73701 100644 --- a/test/onboarding/onboard-installer-restore-intent.test.ts +++ b/test/onboarding/onboard-installer-restore-intent.test.ts @@ -122,6 +122,7 @@ const sourceEntry = fixtureMocks.sandboxLifecycleFixture({ toolDisclosure: "progressive", }); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-messaging-reuse.test.ts b/test/onboarding/onboard-messaging-reuse.test.ts new file mode 100644 index 00000000000..a2e780a4fa0 --- /dev/null +++ b/test/onboarding/onboard-messaging-reuse.test.ts @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { beforeEach, describe, it, vi } from "vitest"; +import { parseMessagingFixturePayload as parseStdoutJson } from "../helpers/messaging-plan-fixtures"; +import { runBoundedOnboardScriptAsync } from "../helpers/onboard-child-process-harness"; +import { writeOkOpenshell } from "../helpers/onboard-openshell-fixture"; + +type CommandEntry = { command: string }; +const repoRoot = path.join(import.meta.dirname, "../.."); +const onboardScriptMocksPath = JSON.stringify( + path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), +); +beforeEach(() => { + vi.stubEnv("NEMOCLAW_TEST_MANAGED_IMAGE_CATALOG", "1"); + vi.stubEnv("NEMOCLAW_TEST_FORWARD_SERVICE_FIXTURE", "1"); + vi.stubEnv("NEMOCLAW_SANDBOX_PREBUILD", "1"); +}); +describe("onboard messaging reuse", () => { + it.sequential( + "reuses sandbox without refreshing unselected ambient messaging providers (#10277)", + { + timeout: 60_000, + }, + async (context) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-reuse-providers-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "reuse-with-providers.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "registry.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const fixtureMocks = require(${onboardScriptMocksPath}); + +// This test owns a simulated standalone gateway, not the host service installation. +fixtureMocks.mockStandaloneGatewayTeardownAuthority(); +const commands = []; +const existingSandbox = fixtureMocks.createCreatedSandboxFixture({ lifecycleState: "created" }); existingSandbox.installRuntimeObservation(); +const messagingProviderRunner = require(${onboardScriptMocksPath}).createStatefulMessagingProviderRunner({ + commands, + createdSandbox: existingSandbox, + initialProviders: [ + ["my-assistant-discord-bridge", "nemoclaw-mcp-v1", "DISCORD_BOT_TOKEN"], + ["my-assistant-slack-bridge", "nemoclaw-mcp-v1", "SLACK_BOT_TOKEN"], + ["my-assistant-slack-app", "nemoclaw-mcp-v1", "SLACK_APP_TOKEN"], + ], +}); +runner.run = messagingProviderRunner; +runner.runCapture = (command) => { + const sandboxCapture = existingSandbox.capture(command); + if (sandboxCapture !== null) return sandboxCapture; + // All messaging providers already exist in gateway + if (_n(command).includes("provider get")) return "Provider: exists"; + if (_n(command).includes("forward list")) return "SANDBOX BIND PORT PID STATUS"; + return ""; +}; +registry.getSandbox = () => fixtureMocks.sandboxLifecycleFixture( + { name: "my-assistant", toolDisclosure: "progressive" }, + { sandboxId: existingSandbox.state.sandboxId }, +); +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.DISCORD_BOT_TOKEN = "test-discord-token"; + process.env.SLACK_BOT_TOKEN = "xoxb-test-slack-token"; + process.env.SLACK_APP_TOKEN = "xapp-test-slack-token"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, commands })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = await runBoundedOnboardScriptAsync(scriptPath, { + context, + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payload = parseStdoutJson(result.stdout); + + assert.equal(payload.sandboxName, "my-assistant", "should reuse existing sandbox"); + assert.ok( + payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox create")), + "should NOT recreate sandbox when providers already exist in gateway", + ); + assert.ok( + payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox delete")), + "should NOT delete sandbox when providers already exist in gateway", + ); + + // Existing gateway providers do not select messaging for this onboarding request. + const providerUpserts = payload.commands.filter((entry: CommandEntry) => + entry.command.includes("provider update"), + ); + assert.equal( + providerUpserts.length, + 0, + "should not refresh ambient messaging providers without a selected channel plan", + ); + }, + ); +}); diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index fe8e9849d09..7c83d8da8ae 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -81,7 +81,7 @@ const { EventEmitter } = require("node:events"); const fs = require("node:fs"); const commands = []; const createdSandbox = fixtureMocks.createCreatedSandboxFixture({ sandboxName: "my-assistant" }); createdSandbox.installRuntimeObservation(); -runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox }); +runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox, nativeNvidiaProvider: true }); runner.runCapture = (command) => { const sandboxCapture = createdSandbox.capture(command); if (sandboxCapture !== null) return sandboxCapture; @@ -100,6 +100,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -355,7 +356,7 @@ const nonSlackMessagingEnvKeys = [ const commands = []; let registeredSandbox = null; const createdSandbox = fixtureMocks.createCreatedSandboxFixture({ sandboxName: "my-assistant" }); createdSandbox.installRuntimeObservation(); -runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox }); +runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox, nativeNvidiaProvider: true }); runner.runCapture = (command) => { const sandboxCapture = createdSandbox.capture(command); if (sandboxCapture !== null) return sandboxCapture; @@ -376,6 +377,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -728,6 +730,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -887,6 +890,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1056,6 +1060,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1235,105 +1240,6 @@ const { createSandbox } = require(${onboardPath}); }, ); - it.sequential( - "reuses sandbox without refreshing unselected ambient messaging providers (#10277)", - { - timeout: 60_000, - }, - async (context) => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-reuse-providers-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "reuse-with-providers.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "registry.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const fixtureMocks = require(${onboardScriptMocksPath}); - -const commands = []; -const existingSandbox = fixtureMocks.createCreatedSandboxFixture({ lifecycleState: "created" }); existingSandbox.installRuntimeObservation(); -const messagingProviderRunner = require(${onboardScriptMocksPath}).createStatefulMessagingProviderRunner({ - commands, - createdSandbox: existingSandbox, - initialProviders: [ - ["my-assistant-discord-bridge", "nemoclaw-mcp-v1", "DISCORD_BOT_TOKEN"], - ["my-assistant-slack-bridge", "nemoclaw-mcp-v1", "SLACK_BOT_TOKEN"], - ["my-assistant-slack-app", "nemoclaw-mcp-v1", "SLACK_APP_TOKEN"], - ], -}); -runner.run = messagingProviderRunner; -runner.runCapture = (command) => { - const sandboxCapture = existingSandbox.capture(command); - if (sandboxCapture !== null) return sandboxCapture; - // All messaging providers already exist in gateway - if (_n(command).includes("provider get")) return "Provider: exists"; - if (_n(command).includes("forward list")) return "SANDBOX BIND PORT PID STATUS"; - return ""; -}; -registry.getSandbox = () => fixtureMocks.sandboxLifecycleFixture( - { name: "my-assistant", toolDisclosure: "progressive" }, - { sandboxId: existingSandbox.state.sandboxId }, -); -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.DISCORD_BOT_TOKEN = "test-discord-token"; - process.env.SLACK_BOT_TOKEN = "xoxb-test-slack-token"; - process.env.SLACK_APP_TOKEN = "xapp-test-slack-token"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, commands })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = await runBoundedOnboardScriptAsync(scriptPath, { - context, - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payload = parseStdoutJson(result.stdout); - - assert.equal(payload.sandboxName, "my-assistant", "should reuse existing sandbox"); - assert.ok( - payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox create")), - "should NOT recreate sandbox when providers already exist in gateway", - ); - assert.ok( - payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox delete")), - "should NOT delete sandbox when providers already exist in gateway", - ); - - // Existing gateway providers do not select messaging for this onboarding request. - const providerUpserts = payload.commands.filter((entry: CommandEntry) => - entry.command.includes("provider update"), - ); - assert.equal( - providerUpserts.length, - 0, - "should not refresh ambient messaging providers without a selected channel plan", - ); - }, - ); - it( "filters messaging providers to only enabledChannels when provided", { @@ -1375,6 +1281,7 @@ const createdSandbox = fixtureMocks.createCreatedSandboxFixture(); createdSandbo runner.run = require(${onboardScriptMocksPath}).createStatefulMessagingProviderRunner({ commands, createdSandbox, + nativeNvidiaProvider: true, }); runner.runCapture = (command) => { const createdIdentity = createdSandbox.capture(command); @@ -1391,6 +1298,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1531,6 +1439,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-prepared-build-context.test.ts b/test/onboarding/onboard-prepared-build-context.test.ts index 65f8354510c..26c6bae1e97 100644 --- a/test/onboarding/onboard-prepared-build-context.test.ts +++ b/test/onboarding/onboard-prepared-build-context.test.ts @@ -91,6 +91,7 @@ createdSandbox.installRuntimeObservation(); const commands = []; const registerCalls = []; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName, provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", diff --git a/test/onboarding/onboard-reservation-recreate.test.ts b/test/onboarding/onboard-reservation-recreate.test.ts index d6e597d8aff..d732abfe261 100644 --- a/test/onboarding/onboard-reservation-recreate.test.ts +++ b/test/onboarding/onboard-reservation-recreate.test.ts @@ -228,6 +228,7 @@ const removeSandbox = (name) => { }; registry.removeSandbox = removeSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -480,6 +481,7 @@ if (mode === "seed") { } const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: null, model: null, diff --git a/test/onboarding/onboard-sandbox-build.test.ts b/test/onboarding/onboard-sandbox-build.test.ts index 33a7788adcc..8b9734785a6 100644 --- a/test/onboarding/onboard-sandbox-build.test.ts +++ b/test/onboarding/onboard-sandbox-build.test.ts @@ -129,6 +129,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -386,6 +387,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "hermes-sandbox", provider: "nvidia-prod", model: "gpt-5.4", @@ -607,6 +609,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -724,6 +727,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -844,6 +848,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-sandbox-recreation.test.ts b/test/onboarding/onboard-sandbox-recreation.test.ts index f402cd84175..b2e994d87e9 100644 --- a/test/onboarding/onboard-sandbox-recreation.test.ts +++ b/test/onboarding/onboard-sandbox-recreation.test.ts @@ -193,6 +193,7 @@ runner.run = (command, opts = {}) => { const getSandbox = () => registeredSandbox || sourceSandbox; registry.getSandbox = getSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -366,6 +367,7 @@ runner.run = (command) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -550,6 +552,7 @@ runner.run = (command) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -711,6 +714,7 @@ runner.run = (command) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1069,6 +1073,7 @@ runner.runFile = (file, args = [], opts = {}) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1230,6 +1235,7 @@ runner.run = (command, opts = {}) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-terminal-dashboard.test.ts b/test/onboarding/onboard-terminal-dashboard.test.ts index 9e9c9d5d7d1..175b2403c7f 100644 --- a/test/onboarding/onboard-terminal-dashboard.test.ts +++ b/test/onboarding/onboard-terminal-dashboard.test.ts @@ -212,6 +212,7 @@ registry.removeSandbox = () => true; const createFixture = scenario === "create" ? fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName, provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/security/shellquote-sandbox.test.ts b/test/security/shellquote-sandbox.test.ts index fc3f00be56f..8e4e4f67213 100644 --- a/test/security/shellquote-sandbox.test.ts +++ b/test/security/shellquote-sandbox.test.ts @@ -118,7 +118,7 @@ runner.run = (command, opts = {}) => { stderr: Buffer.alloc(0), }; } - return createdSandbox.run(command) ?? { status: 0 }; + return fixtureMocks.mockNvidiaProviderGetRun(command, "nemoclaw") ?? createdSandbox.run(command) ?? { status: 0 }; }; runner.runFile = (file, args = [], opts = {}) => { commands.push({ type: "runFile", file, args, command: asText([file, ...args]), env: opts.env || null }); @@ -157,6 +157,7 @@ registry.registerSandbox = () => true; registry.removeSandbox = () => true; registry.updateSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", From 5755d24ee1caf0b3891b36c4573cb08e81de56e7 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 6 Oct 2026 19:35:51 -0700 Subject: [PATCH 081/133] test(inference): preserve messaging reuse watch coverage --- test/helpers/vitest-watch-triggers.ts | 1 + test/repository/vitest-watch-triggers.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index 8fc56c4d6c1..8dbc50efceb 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -85,6 +85,7 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ "test/onboarding/onboard-extra-provider-reconciliation.test.ts", "test/onboarding/onboard-fresh-create-identity.test.ts", "test/onboarding/onboard-installer-restore-intent.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/onboarding/onboard-messaging.test.ts", "test/onboarding/onboard-prepared-build-context.test.ts", "test/onboarding/onboard-reservation-recreate.test.ts", diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts index a98fde899aa..6d7766c5c09 100644 --- a/test/repository/vitest-watch-triggers.test.ts +++ b/test/repository/vitest-watch-triggers.test.ts @@ -122,6 +122,7 @@ describe("Vitest opaque-input watch triggers", () => { "test/onboarding/onboard-extra-provider-reconciliation.test.ts", "test/onboarding/onboard-fresh-create-identity.test.ts", "test/onboarding/onboard-installer-restore-intent.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/onboarding/onboard-messaging.test.ts", "test/onboarding/onboard-prepared-build-context.test.ts", "test/onboarding/onboard-reservation-recreate.test.ts", From 39f19964f37a733c96a1fa2054431cfe2d1f6a32 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 20:01:33 -0700 Subject: [PATCH 082/133] docs(inference): clarify native provider switching Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/reference/commands.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 9814861267e..160af728295 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3503,12 +3503,12 @@ $$nemoclaw my-assistant inference get -Switch the active inference provider or model for a NemoClaw-managed OpenClaw sandbox. The command updates the OpenShell gateway route, patches the selected running agent config so it matches the route, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For OpenClaw, the patch updates the OpenClaw config provider namespace and selected model. After any changed config sync, NemoClaw uses the managed supervisor to restart only the OpenClaw gateway and verify its health and forwards. The sandbox remains running, but agent requests are briefly interrupted. If the restart fails, the route and config remain committed; run `$$nemoclaw gateway restart` to finish applying the switch. After every changed synchronized route, NemoClaw also verifies that the local CLI device has the managed gateway's required pairing scopes before it reports success. If pairing does not converge, the route and config remain committed. Run `$$nemoclaw doctor --fix`, then retry the agent turn. +Switch the active inference provider or model for a NemoClaw-managed OpenClaw sandbox. For NVIDIA Endpoints, the command attaches or updates the sandbox's native NVIDIA provider. For other providers, it updates the shared OpenShell gateway route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For OpenClaw, the patch updates the OpenClaw config provider namespace and selected model. After any changed config sync, NemoClaw uses the managed supervisor to restart only the OpenClaw gateway and verify its health and forwards. The sandbox remains running, but agent requests are briefly interrupted. If the restart fails, the selected inference path and config remain committed; run `$$nemoclaw gateway restart` to finish applying the switch. After every changed synchronized inference selection, NemoClaw also verifies that the local CLI device has the managed gateway's required pairing scopes before it reports success. If pairing does not converge, the selected inference path and config remain committed. Run `$$nemoclaw doctor --fix`, then retry the agent turn. -Switch the active inference provider or model for a NemoClaw-managed Hermes sandbox. The command updates the OpenShell gateway route, patches the selected running agent config so it matches the route, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For Hermes, the patch updates the shared native `/sandbox/.hermes/config.yaml` (`model.default`, `model.base_url`, `model.provider: custom`, API-family mode when needed, and the OpenShell proxy API-key placeholder) and does not rebuild or restart the gateway. The gateway, CLI, TUI, and Web Dashboard read that same configuration. Keeping the placeholder preserves dashboard and API authentication after provider switches. Under the `nemohermes` alias, the command uses the registered Hermes sandbox when exactly one exists; otherwise pass `--sandbox ` to target one explicitly. +Switch the active inference provider or model for a NemoClaw-managed Hermes sandbox. For NVIDIA Endpoints, the command attaches or updates the sandbox's native NVIDIA provider. For other providers, it updates the shared OpenShell gateway route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For Hermes, the patch updates the shared native `/sandbox/.hermes/config.yaml` (`model.default`, `model.base_url`, `model.provider: custom`, API-family mode when needed, and the OpenShell proxy API-key placeholder) and does not rebuild or restart the gateway. The gateway, CLI, TUI, and Web Dashboard read that same configuration. Keeping the placeholder preserves dashboard and API authentication after provider switches. Under the `nemohermes` alias, the command uses the registered Hermes sandbox when exactly one exists; otherwise pass `--sandbox ` to target one explicitly. @@ -3539,13 +3539,13 @@ You can also name the sandbox in sandbox-first position instead of passing `--sa $$nemoclaw my-assistant inference set --provider nvidia-prod --model nvidia/nemotron-3-super-120b-a12b ``` -Pass both `--provider` and `--model` when you want NemoClaw to update the OpenShell inference route and sync the selected sandbox's agent config. NemoClaw resolves the OpenShell gateway from the target sandbox's recorded gateway binding, including non-default `NEMOCLAW_GATEWAY_PORT` deployments. Do not run `openshell inference set` directly on a shared NemoClaw gateway because that bypasses registry compatibility checks and can break other sandboxes. When either flag is missing, `$$nemoclaw inference set` reports both required flags without suggesting a raw OpenShell command. The command updates the host registry immediately after the gateway route changes. +Pass both `--provider` and `--model` to select the provider and model for the target sandbox. For providers other than NVIDIA Endpoints, NemoClaw updates the shared OpenShell inference route and syncs the selected sandbox's agent config. For NVIDIA Endpoints, NemoClaw attaches or updates the selected sandbox's native NVIDIA provider and syncs its agent config without changing the shared route. NemoClaw resolves the OpenShell gateway from the target sandbox's recorded gateway binding, including non-default `NEMOCLAW_GATEWAY_PORT` deployments. Do not run `openshell inference set` directly on a shared NemoClaw gateway because that bypasses registry compatibility checks and can break other sandboxes. When either flag is missing, `$$nemoclaw inference set` reports both required flags without suggesting a raw OpenShell command. The command updates the host registry after the selected inference path changes. -If NemoClaw cannot confirm the native OpenClaw config batch, the OpenShell route and registry remain committed, but `inference set` exits with status `1`. +If NemoClaw cannot confirm the native OpenClaw config batch, the selected inference path and registry remain committed, but `inference set` exits with status `1`. Rerun the same `inference set` command to converge the config. When the changed route lacks context-window evidence, the retry removes the previous route's context-window value so OpenClaw uses its default. A same-route retry preserves an existing context-window value. @@ -3555,7 +3555,7 @@ A rebuild restores the previous native `openclaw.json`, so it does not repair th -If the in-sandbox config write or integrity hash update fails, the OpenShell route and NemoClaw registry remain committed, but the command exits with status `1` and points you to `$$nemoclaw rebuild`. +If the in-sandbox config write or integrity hash update fails, the selected inference path and NemoClaw registry remain committed, but the command exits with status `1` and points you to `$$nemoclaw rebuild`. From 28e7731cb919059f863ea1afc0eadef72d53c644 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 6 Oct 2026 20:45:55 -0700 Subject: [PATCH 083/133] docs(inference): correct status probe guidance Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/reference/troubleshooting.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 8199edd074a..9984701756d 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1995,7 +1995,7 @@ Verify that the inference provider endpoint is reachable from the host. Check th $$nemoclaw status ``` -The main `Inference` line probes the selected provider path from inside the sandbox and then sends an inference request over the same path, so it reflects the route the agent uses. Most providers use `https://inference.local`. NVIDIA Endpoints uses the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1/chat/completions`. When that request returns a transient gateway status, `status` repeats both probes up to three total attempts before it reports a failure. It prints the HTTP status, next attempt, and two-second delay to stderr before each retry; the configured timeout envelope for three complete probe pairs and two delays is about 124 seconds. If that line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. +The main `Inference` line checks the provider path from inside the sandbox and sends an inference request over the path the agent uses. For shared-route providers, `status` probes `https://inference.local/v1/models` before it sends the request through `https://inference.local`. For NVIDIA Endpoints, it verifies the recorded sandbox attachment and sends the request directly to `https://integrate.api.nvidia.com/v1/chat/completions`; it does not probe `inference.local`. When an inference request returns a transient gateway status, `status` makes up to three request attempts before it reports a failure. Shared-route retries repeat the route probe and request, while NVIDIA Endpoints retries only the native request. It prints the next attempt and two-second delay to stderr before each retry. Each inference request attempt has a 90-second request timeout. If the main line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. For local Ollama and local vLLM, `Inference (ollama backend)` or the corresponding local-backend line reports the host-side service separately. If a local-backend diagnostic fails, start the backend. For Local Ollama, current releases can also print `Inference (auth proxy)` when a proxy token is available. Docker Desktop on Windows Subsystem for Linux (WSL) reaches host loopback directly, so its auth-proxy diagnostic is non-authoritative. Native Docker Engine inside WSL is unqualified; enable Docker Desktop WSL integration, then rerun onboarding. From 73762d8d71b6c28196f0a2a70702c24e14dfded3 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 06:15:47 -0700 Subject: [PATCH 084/133] ci(e2e): include Slice 2 qualification guard exception Signed-off-by: Deepak Jain --- ci/e2e-assertion-growth-exceptions.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 41d7ba82f26..942b3687fcc 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12648 adds seven live assertion points for native compatible onboarding, a fresh authenticated agent request, and native status/health after duplicate deterministic checks were removed. User-provided recorded direction from Aaron Erickson (@ericksoa): https://nvidia.slack.com/archives/C0B1FQ51FP0/p1791301358361059. This proposed entry binds the stacked PR base budget bytes to this exact candidate budget and requires maintainer review before landing. The recorded direction does not waive the independent trusted-base check; the exception must reach its trusted policy or that specific failure needs separate explicit maintainer disposition. A changed budget invalidates the corresponding entry. Remove after #12648 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12648 adds seven live assertion points for native compatible onboarding, a fresh authenticated agent request, and native status/health after duplicate deterministic checks were removed. User-provided recorded direction from Aaron Erickson (@ericksoa): https://nvidia.slack.com/archives/C0B1FQ51FP0/p1791301358361059. This proposed entry binds the stacked PR base budget bytes to this exact candidate budget and requires maintainer review before landing. The recorded direction does not waive the independent trusted-base check; the exception must reach its trusted policy or that specific failure needs separate explicit maintainer disposition. A changed budget invalidates the corresponding entry. Remove after #12648 merges.\n\nPR #12593 adds two necessary OpenClaw qualification input guards for an explicit model and the selected protocol. Existing live expectations remain unchanged. Deterministic support tests cover both refusals. This entry also includes the previously recorded Slice 2 guard transition and binds only the stacked base and candidate budget hashes. Aaron Erickson approved necessary budget increases in the recorded decision linked above. Independent enforcement requires this entry in its trusted base policy; no gate is waived. Remove after #12593 merges.", "schemaVersion": 1, "exceptions": [ { @@ -21,6 +21,11 @@ "pullRequest": 12648, "baseBudgetSha256": "fdc4a78b5588629e26b00778d1bc82d69101077b9e372f2b58670510184579c2", "headBudgetSha256": "275391e461bd7f9ae5f8c59a724d4063e3bf1236d3d59586b1a1a223fcabe381" + }, + { + "pullRequest": 12593, + "baseBudgetSha256": "fdc4a78b5588629e26b00778d1bc82d69101077b9e372f2b58670510184579c2", + "headBudgetSha256": "4c23631362f14df242b533a09b8b26f9f65b448611848c084d3263feb40c423c" } ] } From 7556d899c6a8712cb26df5124491f0e733e01e46 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 06:18:38 -0700 Subject: [PATCH 085/133] test(inference): qualify native fixed hosted provider paths Signed-off-by: Deepak Jain --- .github/workflows/e2e-standard-profile.yaml | 32 +++ .github/workflows/e2e.yaml | 58 ++++++ ci/e2e-assertion-budget.json | 8 +- ci/e2e-assertion-growth-exceptions.json | 11 +- docs/inference/model-capability-audit.mdx | 8 +- test/e2e/README.md | 23 +++ .../live/openclaw-inference-switch-helpers.ts | 38 ++++ .../live/openclaw-inference-switch.test.ts | 88 ++++---- .../fixed-hosted-qualification.test.ts | 189 ++++++++++++++++++ .../openclaw-inference-switch-helpers.test.ts | 62 ++++++ ...standard-profile-workflow-boundary.test.ts | 2 +- .../support/workflow-plan-test-assertions.ts | 1 + test/e2e/support/workflow-plan.test.ts | 14 +- tools/e2e/fixed-hosted-qualification.mts | 91 +++++++++ tools/e2e/operations-workflow-boundary.mts | 2 + tools/e2e/pre-candidate-workflow-contract.mts | 1 + .../standard-profile-workflow-boundary.mts | 49 ++++- tools/e2e/target-catalogue.mts | 44 +++- tools/e2e/workflow-boundary.mts | 3 +- tools/e2e/workflow-plan.mts | 36 +++- 20 files changed, 693 insertions(+), 67 deletions(-) create mode 100644 test/e2e/support/fixed-hosted-qualification.test.ts create mode 100644 tools/e2e/fixed-hosted-qualification.mts diff --git a/.github/workflows/e2e-standard-profile.yaml b/.github/workflows/e2e-standard-profile.yaml index a5623fc4d19..1dba8e42030 100644 --- a/.github/workflows/e2e-standard-profile.yaml +++ b/.github/workflows/e2e-standard-profile.yaml @@ -105,11 +105,17 @@ on: trusted_main: required: true type: boolean + hosted_model: + required: false + type: string + default: "" secrets: DOCKERHUB_USERNAME: required: false DOCKERHUB_TOKEN: required: false + HOSTED_PROVIDER_API_KEY: + required: false NVIDIA_API_KEY: required: false NVIDIA_INFERENCE_API_KEY: @@ -150,6 +156,7 @@ jobs: ENV: /dev/null EXECUTION_ID: ${{ inputs.execution_id }} GITHUB_WORKSPACE_VALUE: ${{ github.workspace }} + HOSTED_MODEL: ${{ inputs.hosted_model }} HOST_PACKAGES: ${{ inputs.host_packages }} HOST_PREPARATION: ${{ inputs.host_preparation }} INSTALL_MODE: ${{ inputs.install_mode }} @@ -181,6 +188,21 @@ jobs: if [[ "$ARTIFACT_LAYOUT" == "flat-shard" && "$SHARD" == "default" ]]; then fail "flat shard layout requires a named shard" fi + hosted_credential="" + case "$CATALOGUE_ID" in + hermes-fixed-bearer-inference-switch) [[ "$TARGET_ID" == "hermes-inference-switch" && "$TEST_FILE" == "test/e2e/live/hermes-inference-switch.test.ts" && "$SHARD" == "hermes-provider" ]] || fail "fixed hosted identity"; hosted_credential=NOUS_API_KEY ;; + hermes-fixed-anthropic-inference-switch) [[ "$TARGET_ID" == "hermes-inference-switch" && "$TEST_FILE" == "test/e2e/live/hermes-inference-switch.test.ts" && "$SHARD" == "anthropic-prod" ]] || fail "fixed hosted identity"; hosted_credential=ANTHROPIC_API_KEY ;; + hermes-fixed-openrouter-inference-switch) [[ "$TARGET_ID" == "hermes-inference-switch" && "$TEST_FILE" == "test/e2e/live/hermes-inference-switch.test.ts" && "$SHARD" == "openrouter-api" ]] || fail "fixed hosted identity"; hosted_credential=OPENROUTER_API_KEY ;; + openclaw-fixed-openai-inference-switch) [[ "$TARGET_ID" == "openclaw-inference-switch" && "$TEST_FILE" == "test/e2e/live/openclaw-inference-switch.test.ts" && "$SHARD" == "openai-api" ]] || fail "fixed hosted identity"; hosted_credential=OPENAI_API_KEY ;; + openclaw-fixed-anthropic-inference-switch) [[ "$TARGET_ID" == "openclaw-inference-switch" && "$TEST_FILE" == "test/e2e/live/openclaw-inference-switch.test.ts" && "$SHARD" == "anthropic-prod" ]] || fail "fixed hosted identity"; hosted_credential=ANTHROPIC_API_KEY ;; + *) [[ -z "${HOSTED_MODEL:-}" ]] || fail "unexpected hosted model" ;; + esac + if [[ -n "$hosted_credential" ]]; then + [[ "$RUNTIME_PROVIDER" == "docker" ]] || fail "fixed hosted runtime" + [[ "$HOSTED_MODEL" =~ ^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$ ]] || fail "hosted model" + fi + printf 'hosted_credential=%s + ' "$hosted_credential" >>"$GITHUB_OUTPUT" artifact_directory="e2e-artifacts/live/${TARGET_ID}" upload_name="e2e-${EXECUTION_ID}" if [[ "$SHARD" != "default" ]]; then @@ -532,6 +554,9 @@ jobs: INSTALL_MODE: ${{ inputs.install_mode }} CATALOGUE_ID: ${{ inputs.catalogue_id }} TEST_FILE: ${{ inputs.test_file }} + HOSTED_PROVIDER_API_KEY: ${{ inputs.trusted_main && secrets.HOSTED_PROVIDER_API_KEY || '' }} + HOSTED_CREDENTIAL_NAME: ${{ steps.execution_plan.outputs.hosted_credential }} + HOSTED_MODEL: ${{ inputs.hosted_model }} NVIDIA_API_KEY: ${{ inputs.trusted_main && secrets.NVIDIA_API_KEY || '' }} NVIDIA_INFERENCE_API_KEY: ${{ inputs.trusted_main && secrets.NVIDIA_INFERENCE_API_KEY || '' }} COMPATIBLE_API_KEY: ${{ inputs.compatible_api_key && inputs.trusted_main && secrets.NVIDIA_INFERENCE_API_KEY || '' }} @@ -551,6 +576,13 @@ jobs: export OPENSHELL_BIN "$OPENSHELL_BIN" --version fi + if [[ -n "$HOSTED_CREDENTIAL_NAME" ]]; then + [[ -n "$HOSTED_PROVIDER_API_KEY" ]] || { echo "::error::Selected hosted provider credential is unavailable" >&2; exit 1; } + printf -v "$HOSTED_CREDENTIAL_NAME" '%s' "$HOSTED_PROVIDER_API_KEY" + export "$HOSTED_CREDENTIAL_NAME" + export NEMOCLAW_SWITCH_MODEL="$HOSTED_MODEL" + fi + unset HOSTED_PROVIDER_API_KEY npx tsx tools/e2e/target-catalogue.mts run "$CATALOGUE_ID" "$TEST_FILE" - name: Finalize runner comparison telemetry diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index dd611ee0919..e5eff488fc7 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -25,6 +25,11 @@ on: required: false default: false type: boolean + hosted_model: + description: "Explicit model ID for one manually selected fixed hosted inference target. No default model is chosen." + required: false + default: "" + type: string inference_mode: description: "Inference adapter mode for compatible Vitest E2E jobs: mock, internal-nvidia, or public-nvidia." required: false @@ -375,6 +380,7 @@ jobs: selected_jobs: ${{ steps.matrix.outputs.selected_jobs }} selected_workflow_jobs: ${{ steps.matrix.outputs.selected_workflow_jobs }} catalogue_standard_matrix: ${{ steps.matrix.outputs.catalogue_standard_matrix }} + catalogue_fixed_hosted_matrix: ${{ steps.matrix.outputs.catalogue_fixed_hosted_matrix }} catalogue_nvidia_api_matrix: ${{ steps.matrix.outputs.catalogue_nvidia_api_matrix }} catalogue_nvidia_inference_matrix: ${{ steps.matrix.outputs.catalogue_nvidia_inference_matrix }} catalogue_github_read_matrix: ${{ steps.matrix.outputs.catalogue_github_read_matrix }} @@ -659,6 +665,7 @@ jobs: - id: matrix name: Generate E2E target matrix env: + HOSTED_MODEL: ${{ inputs.hosted_model }} INFERENCE_MODE: ${{ inputs.inference_mode || 'mock' }} NEMOCLAW_GATEWAY_RUNTIMES: ${{ inputs.jobs == 'portable-hermes-finalization' && 'podman' || inputs.gateway_runtimes || inputs.gateway_runtime || 'docker' }} JOBS: ${{ inputs.jobs }} @@ -673,6 +680,7 @@ jobs: { echo 'matrix=[]' echo 'test_matrix=[]' + echo 'catalogue_fixed_hosted_matrix=[]' echo 'catalogue_standard_matrix=[]' echo 'catalogue_nvidia_api_matrix=[]' echo 'catalogue_nvidia_inference_matrix=[]' @@ -3290,6 +3298,55 @@ jobs: DOCKERHUB_USERNAME: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_USERNAME || '' }} DOCKERHUB_TOKEN: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_TOKEN || '' }} + catalogue-fixed-hosted: + name: ${{ matrix.display_name }} (${{ matrix.runtime_provider }}) + needs: [base-image-publication, generate-matrix, package-openshell-sdk] + if: ${{ needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix != '[]' }} + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix) }} + uses: ./.github/workflows/e2e-standard-profile.yaml + with: + candidate_repository: ${{ inputs.checkout_repository || github.repository }} + candidate_sha: ${{ inputs.checkout_sha || github.sha }} + runtime_provider: ${{ matrix.runtime_provider }} + execution_id: ${{ matrix.execution_id }} + coverage_variant: ${{ matrix.coverage_variant }} + risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} + risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} + cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} + openshell_sdk_artifact_name: ${{ needs.package-openshell-sdk.outputs.artifact_name }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + managed_image_catalog: ${{ needs.base-image-publication.outputs.managed_image_catalog }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} + credential_boundary: Selected fixed hosted provider + hosted_model: ${{ inputs.hosted_model }} + target_id: ${{ matrix.target_id }} + catalogue_id: ${{ matrix.id }} + runner: ${{ matrix.runner_key != '' && fromJSON(needs.generate-matrix.outputs.runner_routing)[matrix.runner_key] || matrix.runner }} + checkout_sha: ${{ inputs.checkout_sha }} + workflow_sha: ${{ inputs.workflow_sha }} + test_file: ${{ matrix.test_file }} + timeout_minutes: ${{ matrix.timeout_minutes }} + install_mode: ${{ matrix.install_mode }} + install_non_interactive: ${{ matrix.install_non_interactive }} + restore_cli: ${{ matrix.restore_cli }} + cloudflared: ${{ matrix.cloudflared }} + host_packages: ${{ matrix.host_packages }} + host_preparation: ${{ matrix.host_preparation }} + runner_comparison: ${{ matrix.runner_comparison }} + compatible_api_key: ${{ matrix.compatible_api_key }} + github_token: false + shard: ${{ matrix.shard }} + artifact_layout: ${{ matrix.artifact_layout }} + trusted_main: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/main') && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }} + secrets: + DOCKERHUB_USERNAME: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_USERNAME || '' }} + DOCKERHUB_TOKEN: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_TOKEN || '' }} + HOSTED_PROVIDER_API_KEY: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }} + catalogue-nvidia-api: name: ${{ matrix.display_name }} (${{ matrix.runtime_provider }}) needs: [base-image-publication, generate-matrix, package-openshell-sdk] @@ -6193,6 +6250,7 @@ jobs: live, shared-e2e, catalogue-standard, + catalogue-fixed-hosted, catalogue-nvidia-api, catalogue-nvidia-inference, catalogue-github-read, diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 3fb50f985c5..9633313f35f 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -32,9 +32,9 @@ "nodeAssertions": 127, "namedAssertionHelpers": 671, "failCalls": 1, - "throwGuards": 530, + "throwGuards": 532, "objectFieldAssertions": 243, - "assertionPoints": 3210, + "assertionPoints": 3212, "generatedProbeBlocks": 208, "generatedProbeConditions": 720 }, @@ -62,7 +62,7 @@ "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], "test/e2e/live/double-onboard.test.ts": [36,43,36,43,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], - "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], + "test/e2e/live/full-e2e.test.ts": [27,30,28,62,7], "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [10,25,17,64,14], @@ -95,7 +95,7 @@ "test/e2e/live/onboard-repair.test.ts": [21,25,21,25,0], "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], - "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,52,1], + "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,54,1], "test/e2e/live/openclaw-skill-cli.test.ts": [10,14,10,14,1], "test/e2e/live/openclaw-slack-pairing.test.ts": [11,18,26,84,10], "test/e2e/live/openshell-credential-generation-window.test.ts": [42,92,43,112,18], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index cf656631056..9741cc2df9f 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nPR #12593 preserves two necessary fail-closed guards: an explicit vendor model before fixed hosted qualification and a manual Nous credential before external registration. Two incidental success/error wording assertions are removed; unique total assertion points and Hermes transitive assertion points remain unchanged, while unique throwGuards increase by two. Budget increase approved by Aaron Erickson (@ericksoa): https://nvidia.slack.com/archives/C0B1FQ51FP0/p1791301358361059. Entries bind the current local comparison and stacked PR base budget bytes to this exact candidate budget. Approval does not waive the independent trusted-base check; the exception must reach its trusted policy or that specific failure needs separate explicit maintainer disposition. Changed budget bytes invalidate the corresponding entry. Remove after #12593 merges.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nPR #12593 preserves two necessary fail-closed guards: an explicit vendor model before fixed hosted qualification and a manual Nous credential before external registration. Two incidental success/error wording assertions are removed; unique total assertion points and Hermes transitive assertion points remain unchanged, while unique throwGuards increase by two. Budget increase approved by Aaron Erickson (@ericksoa): https://nvidia.slack.com/archives/C0B1FQ51FP0/p1791301358361059. Entries bind the current local comparison and stacked PR base budget bytes to this exact candidate budget. Approval does not waive the independent trusted-base check; the exception must reach its trusted policy or that specific failure needs separate explicit maintainer disposition. Changed budget bytes invalidate the corresponding entry. Remove after #12593 merges.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12593 current OpenClaw qualification adds two preflight guards: require an explicit canonical model and reject a protocol inconsistent with the selected fixed provider before allocating a runtime. Deterministic support tests own both input contracts. Existing live expectation counts do not increase; unique throwGuards and assertionPoints increase by two, and the shared helper contributes the same two to OpenClaw/full-e2e transitive counts. Aaron Erickson approved necessary budget increases at the linked Slack decision above. Updated exact candidate hashes do not waive independent trusted-base policy.", "schemaVersion": 1, "exceptions": [ { @@ -15,17 +15,22 @@ { "pullRequest": 12593, "baseBudgetSha256": "d0a41e5514e5cc2f7bb34d7604c82106d9e36239f1abf5859e343c7733501289", - "headBudgetSha256": "bda0267c094710272fd2a02ed05c26a2e93e5a78c81fcdb9d4d9a338e342914a" + "headBudgetSha256": "4c23631362f14df242b533a09b8b26f9f65b448611848c084d3263feb40c423c" }, { "pullRequest": 12593, "baseBudgetSha256": "fdc4a78b5588629e26b00778d1bc82d69101077b9e372f2b58670510184579c2", - "headBudgetSha256": "bda0267c094710272fd2a02ed05c26a2e93e5a78c81fcdb9d4d9a338e342914a" + "headBudgetSha256": "4c23631362f14df242b533a09b8b26f9f65b448611848c084d3263feb40c423c" }, { "pullRequest": 12591, "baseBudgetSha256": "d0a41e5514e5cc2f7bb34d7604c82106d9e36239f1abf5859e343c7733501289", "headBudgetSha256": "59c006401487a0c25d9f5cf5fd3159c9f1248a6710d559cc18879af6edef2919" + }, + { + "pullRequest": 12593, + "baseBudgetSha256": "bda0267c094710272fd2a02ed05c26a2e93e5a78c81fcdb9d4d9a338e342914a", + "headBudgetSha256": "4c23631362f14df242b533a09b8b26f9f65b448611848c084d3263feb40c423c" } ] } diff --git a/docs/inference/model-capability-audit.mdx b/docs/inference/model-capability-audit.mdx index a9b21934b7b..fda58e1e85c 100644 --- a/docs/inference/model-capability-audit.mdx +++ b/docs/inference/model-capability-audit.mdx @@ -121,14 +121,14 @@ When importing a completed row from an issue comment, preserve the commit SHA, w | OpenClaw primary agent | NVIDIA Endpoints (retired route) | `deepseek-ai/deepseek-v4-pro` | Managed `inference.local` OpenAI-compatible completions | `unsupported` | The featured-model feed still listed this model after the NVIDIA Endpoints model catalog removed it. NemoClaw excludes it from featured selections. | The retirement exclusion applies to NVIDIA Endpoints featured selections. It does not determine whether another compatible endpoint serves the same model ID. | Select a supported NVIDIA Endpoints model. | `src/lib/inference/nvidia-featured-models.ts`, `src/lib/inference/nvidia-featured-models.test.ts`. | | OpenClaw primary agent | NVIDIA Endpoints (retired route) | `z-ai/glm-5.2` | Managed `inference.local` OpenAI-compatible completions | `unsupported` | [Issue #10222](https://github.com/NVIDIA/NemoClaw/issues/10222) records authenticated NVIDIA Endpoints `/v1/models` results from WSL and DGX Spark with no GLM model IDs. NemoClaw excludes this model from featured selections. | The retirement exclusion applies to NVIDIA Endpoints featured selections. It does not determine whether another compatible endpoint serves the same model ID. | Select a supported NVIDIA Endpoints model. | `src/lib/inference/nvidia-featured-models.ts`, `src/lib/inference/nvidia-featured-models.test.ts`. | | OpenClaw primary agent | NVIDIA Endpoints | Any model from `CLOUD_MODEL_OPTIONS` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions. | `not-yet-run` | Add one evidence row per model before changing state. | Record `none`, model-specific setup, or provider-class transport behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/config.ts`. | -| OpenClaw primary agent | OpenAI | Any model from `REMOTE_MODEL_OPTIONS.openai` | `openai` provider through `https://inference.local/v1`. | `not-yet-run` | Add one evidence row per model before changing state. | Record Responses or Chat Completions behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | -| OpenClaw primary agent | Anthropic | Any model from `REMOTE_MODEL_OPTIONS.anthropic` | `anthropic` provider through `https://inference.local` with `anthropic-messages`. | `not-yet-run` | Add one evidence row per model before changing state. | Record native Anthropic Messages behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | -| OpenClaw primary agent | Gemini | Any model from `REMOTE_MODEL_OPTIONS.gemini` | Managed `inference.local` OpenAI-compatible route. | `not-yet-run` | Add one evidence row per model before changing state. | Record provider state and tool-result continuation behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | +| OpenClaw primary agent | OpenAI | Any model from `REMOTE_MODEL_OPTIONS.openai` | Attached OpenShell provider `nemoclaw-openai-api-v1` at `https://api.openai.com/v1` using OpenAI Responses or Chat Completions. | `not-yet-run` | Add one evidence row per model before changing state. | Record Responses or Chat Completions behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`, `src/lib/inference/native-hosted/profiles.ts`. | +| OpenClaw primary agent | Anthropic | Any model from `REMOTE_MODEL_OPTIONS.anthropic` | Attached OpenShell provider `nemoclaw-anthropic-prod-v1` at `https://api.anthropic.com` using Anthropic Messages. | `not-yet-run` | Add one evidence row per model before changing state. | Record native Anthropic Messages behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`, `src/lib/inference/native-hosted/profiles.ts`. | +| OpenClaw primary agent | Gemini | Any model from `REMOTE_MODEL_OPTIONS.gemini` | Attached OpenShell provider `nemoclaw-gemini-api-v1` at `https://generativelanguage.googleapis.com/v1beta/openai` using OpenAI-compatible Chat Completions. | `not-yet-run` | Add one evidence row per model before changing state. | Record provider state and tool-result continuation behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`, `src/lib/inference/native-hosted/profiles.ts`. | | OpenClaw primary agent | Local Ollama | Default `nemotron-3-nano:30b` or any installed model selected by onboarding. | Managed `inference.local` route to the host Ollama proxy. | `not-yet-run` | Add local daemon, model tag, and trajectory evidence before changing state. | Record tool capability, streaming usage, and local proxy behavior. | Add one row per audited local model tag. | `src/lib/inference/local.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Local vLLM | Any model from `VLLM_MODELS`. | Managed `inference.local` route to the host vLLM server. | `not-yet-run` | Add vLLM serve flags, model id, and trajectory evidence before changing state. | Record parser flags, reasoning parser, and tool-call parser behavior. | Add one row per audited vLLM model id. | `src/lib/inference/vllm-models.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Other OpenAI-compatible endpoint | User-selected `custom-model` or another configured model id. | Managed `inference.local` route to the compatible endpoint. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record endpoint API path forcing and store/streaming assumptions. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | | OpenClaw primary agent | Other Anthropic-compatible endpoint | User-selected `custom-anthropic-model` or another configured model id. | `anthropic` route when supported, otherwise managed compatible route. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record native Anthropic Messages or compatible-route transport behavior. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | -| Hermes sandbox API | Hermes Provider | Default `moonshotai/kimi-k2.6` or any model from `HERMES_PROVIDER_MODEL_OPTIONS`. | Hermes Provider route through NemoClaw managed inference. | `not-yet-run` | Add Hermes session, request dump, logs, and local API evidence before changing state. | Generated config uses native `tools.tool_search.enabled: on` with snake-case 5/20 limits; core tools stay direct while deferred MCP and non-core plugin tools use structured search, describe, and call. | Verify a deferred-tool trajectory and keep it separate from OpenClaw `mode: tools` evidence. | `agents/hermes/config/managed-policy.ts`, `test/generation/generate-hermes-config.test.ts`. | +| Hermes sandbox API | Hermes Provider | Default `moonshotai/kimi-k2.6` or any model from `HERMES_PROVIDER_MODEL_OPTIONS`. | Attached OpenShell provider `nemoclaw-hermes-provider-v1` at `https://inference-api.nousresearch.com/v1` using OpenAI-compatible Chat Completions. | `not-yet-run` | Add Hermes session, request dump, logs, and local API evidence before changing state. | Generated config uses native `tools.tool_search.enabled: on` with snake-case 5/20 limits; core tools stay direct while deferred MCP and non-core plugin tools use structured search, describe, and call. | Verify a deferred-tool trajectory and keep it separate from OpenClaw `mode: tools` evidence. | `agents/hermes/config/managed-policy.ts`, `src/lib/inference/native-hosted/profiles.ts`, `test/generation/generate-hermes-config.test.ts`. | | Deep Agents interactive `dcode` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add separate default-disabled and thread-opt-in terminal transcripts, host status output, reset evidence, and route evidence before changing state. | The managed Ultra profile preserves required nonempty tool-call content and rejects the observed literal `[content]` execute placeholder before shell dispatch; optional `thread-opt-in` remains a per-thread approval affordance. | Verify a terminal task with approval prompts intact, then separately verify explicit thread activation, reset behavior, policy enforcement, placeholder rejection, and no provider credential in sandbox-visible files. | `agents/langchain-deepagents-code/generate-config.ts`, `agents/langchain-deepagents-code/profile-plugin`, `docs/get-started/quickstart-langchain-deepagents-code`. | | Deep Agents headless `dcode -n` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add headless command transcript and status output before changing state. | Headless mode uses the managed Ultra profile, preserves required nonempty tool-call content, rejects the observed literal `[content]` execute placeholder, has no approval UI, and auto-approves non-shell tools while managed shell execution remains disabled. | Verify a bounded non-shell task, placeholder rejection, and the approval boundary separately from interactive evidence. | `agents/langchain-deepagents-code/dcode-wrapper.sh`, `agents/langchain-deepagents-code/profile-plugin`, `docs/security/best-practices`. | diff --git a/test/e2e/README.md b/test/e2e/README.md index 5ec17d30f9b..21db761006c 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1067,6 +1067,29 @@ a mock baseline is not evidence of vendor success. Select one scenario at a time for each required protocol/credential shape; no provider-by-platform matrix or new scheduled jobs are introduced. +Trusted workflow qualification uses an explicitly selected target and a nonempty +`hosted_model` input. Select one of `hermes-fixed-bearer-inference-switch`, +`hermes-fixed-anthropic-inference-switch`, `hermes-fixed-openrouter-inference-switch`, +`openclaw-fixed-openai-inference-switch`, or +`openclaw-fixed-anthropic-inference-switch` through the existing E2E workflow's +`targets` input. Each selection runs on Docker and receives only its declared +provider credential. These targets are excluded from the default suite. The +trusted workflow revision must contain this selection and credential transport +before it can dispatch a candidate PR; candidate code cannot authorize its own +credential access. Approved credential provisioning and a canonical supported +model remain prerequisites. The existing manifest binds the candidate revision, +selected target, and switch artifacts to the workflow result. + +The existing `openclaw-inference-switch` owner also accepts `openai-api` and +`anthropic-prod` with an explicit `NEMOCLAW_SWITCH_MODEL`. These two selections +cover the native OpenAI-compatible and Anthropic Messages consumer paths. They +start from an authenticated local baseline, then supply only the selected +`OPENAI_API_KEY` or `ANTHROPIC_API_KEY` to the switch command. The existing +attachment, configuration, sandbox response, and gateway model-run checks prove +the native route. A native provider failure fails the target rather than skipping +qualification. Models must match the provider's response model ID. Local fixture +and support-test passes do not prove that either real provider succeeded. + ## Native plugin and package lifecycle Issue #11766 retired the dedicated `openclaw-plugin-runtime-exdev` workflow job diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index 44d898c18ac..9f3b0780e00 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -7,6 +7,9 @@ // accepted while echoed or embedded tokens are rejected, without gating on // NEMOCLAW_RUN_LIVE_E2E=1. +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; +import { nativeInferenceProbeAuthScript } from "../../../src/lib/inference/probe/native-inference-probe-auth.ts"; + import type { RetryFailureClass } from "../../../tools/e2e/retry-evidence.mts"; export interface OpenClawPostSwitchInferenceAttempt { @@ -173,3 +176,38 @@ export function mockBaselineInference(endpointUrl: string): BaselineInferenceCon }, }; } + +/** Fixed-provider proofs reuse the live switch owner with an explicit model. */ +export function fixedOpenClawSwitchScenario(env: NodeJS.ProcessEnv) { + const provider = env.NEMOCLAW_SWITCH_PROVIDER; + if (provider !== "openai-api" && provider !== "anthropic-prod") return null; + const model = env.NEMOCLAW_SWITCH_MODEL?.trim(); + if (!model) throw new Error("Fixed hosted qualification requires NEMOCLAW_SWITCH_MODEL"); + const profile = nativeHostedProfile(provider)!; + const inferenceApi = provider === "anthropic-prod" ? "anthropic-messages" : "openai-completions"; + if (env.NEMOCLAW_SWITCH_INFERENCE_API && env.NEMOCLAW_SWITCH_INFERENCE_API !== inferenceApi) + throw new Error("Fixed hosted qualification protocol does not match the selected provider"); + return { provider, model, inferenceApi, credentialEnv: profile.credentialEnv }; +} + +export function openClawSwitchRoute(provider: string | null, inferenceApi: string) { + const profile = nativeHostedProfile(provider); + return { + baseUrl: + profile?.endpoint ?? + (inferenceApi === "anthropic-messages" + ? "https://inference.local" + : "https://inference.local/v1"), + apiKey: profile ? `\${${profile.credentialEnv}}` : "unused", + }; +} + +export function openClawSwitchCurlCommand(provider: string, inferenceApi: string): string { + const profile = nativeHostedProfile(provider); + const endpoint = openClawSwitchRoute(provider, inferenceApi).baseUrl; + const anthropic = inferenceApi === "anthropic-messages"; + const auth = profile + ? nativeInferenceProbeAuthScript(profile.credentialEnv, anthropic).join("; ") + : ""; + return `${auth ? `${auth}; ` : ""}curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 ${endpoint}${anthropic ? "/v1/messages" : "/chat/completions"} -H 'Content-Type: application/json'${profile ? ' -H "$AUTH_HEADER"' : ""}${anthropic ? " -H 'anthropic-version: 2023-06-01'" : ""} --data-binary @/tmp/nemoclaw-switch-payload.json`; +} diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index f03b3afe60e..9573eb646f3 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -16,7 +16,8 @@ import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; +import { resolveMaxTokensField } from "../../../src/lib/inference/max-tokens-field.ts"; +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; @@ -53,6 +54,9 @@ import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; import { runBoundedRetry } from "../../../tools/e2e/retry-evidence.mts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { + fixedOpenClawSwitchScenario, + openClawSwitchRoute, + openClawSwitchCurlCommand, agentReplyContainsToken, anthropicToolCount, classifyExhaustedPostSwitchEvidence, @@ -64,17 +68,22 @@ import { parseOpenClawGatewayModelRun, } from "./openclaw-inference-switch-helpers.ts"; import { - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, - readPublicNvidiaSwitchAttachmentEvidence, + readNativeSwitchAttachmentEvidence, + expectedNativeSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-oc-inf-switch"; const SWITCH_PROVIDER = process.env.NEMOCLAW_SWITCH_PROVIDER ?? PUBLIC_NVIDIA_SWITCH_PROVIDER; -const SWITCH_MODEL = process.env.NEMOCLAW_SWITCH_MODEL ?? PUBLIC_NVIDIA_SWITCH_MODEL; -const SWITCH_INFERENCE_API = process.env.NEMOCLAW_SWITCH_INFERENCE_API ?? "openai-completions"; +const FIXED_HOSTED_SWITCH = fixedOpenClawSwitchScenario(process.env); +const SWITCH_MODEL = + FIXED_HOSTED_SWITCH?.model ?? process.env.NEMOCLAW_SWITCH_MODEL ?? PUBLIC_NVIDIA_SWITCH_MODEL; +const SWITCH_INFERENCE_API = + process.env.NEMOCLAW_SWITCH_INFERENCE_API ?? + (SWITCH_PROVIDER === "anthropic-prod" ? "anthropic-messages" : "openai-completions"); +const SWITCH_PROFILE = nativeHostedProfile(SWITCH_PROVIDER); const SWITCH_MOCK_ANTHROPIC = process.env.NEMOCLAW_SWITCH_MOCK_ANTHROPIC ?? "0"; const SWITCH_MOCK_PORT = parsePortEnv("NEMOCLAW_SWITCH_MOCK_PORT", 0); const TEST_TIMEOUT_MS = testTimeout(75 * 60_000); @@ -82,7 +91,6 @@ const INSTALL_TIMEOUT_MS = execTimeout(30 * 60_000); const COMMAND_TIMEOUT_MS = 120_000; const INFERENCE_TIMEOUT_MS = 150_000; const AGENT_TIMEOUT_MS = 150_000; -const NATIVE_NVIDIA_AUTH_HEADER = "Author" + "ization: Bearer nemoclaw-openshell-provider"; validateSandboxName(SANDBOX_NAME); @@ -569,7 +577,9 @@ async function assertRegistryAndSession( default: expect(sandbox?.endpointUrl).toBeNull(); expect(sandbox?.credentialEnv).toBe(sandbox?.provider === SWITCH_PROVIDER ? null : undefined); - expect(sandbox?.preferredInferenceApi).toBeNull(); + expect(sandbox?.preferredInferenceApi).toBe( + SWITCH_PROVIDER === "anthropic-prod" ? "anthropic-messages" : null, + ); } const sessionPath = path.join(home, ".nemoclaw", "onboard-session.json"); @@ -586,14 +596,16 @@ async function assertRegistryAndSession( case "compatible-anthropic-endpoint": expect(session.preferredInferenceApi).toBe("anthropic-messages"); break; + case "openai-api": + case "anthropic-prod": case PUBLIC_NVIDIA_SWITCH_PROVIDER: expect( [ session.endpointUrl, session.credentialEnv, session.preferredInferenceApi, - await readPublicNvidiaSwitchAttachmentEvidence({ - artifactName: "native-nvidia-provider-attachment-after-switch", + await readNativeSwitchAttachmentEvidence({ + artifactName: "native-provider-attachment-after-switch", env: commandEnv(home), logicalProvider: SWITCH_PROVIDER, receipt: sandbox?.nativeHostedProviderAttachment, @@ -603,10 +615,10 @@ async function assertRegistryAndSession( ].join("\n"), ).toBe( [ - NVIDIA_HOSTED_NATIVE_ENDPOINT, - "NVIDIA_INFERENCE_API_KEY", - "openai-completions", - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, + SWITCH_PROFILE?.endpoint, + SWITCH_PROFILE?.credentialEnv, + SWITCH_INFERENCE_API, + expectedNativeSwitchAttachmentEvidence(SWITCH_PROVIDER), ].join("\n"), ); break; @@ -620,6 +632,7 @@ async function readAndAssertOpenClawConfig( model: string; inferenceApi: string; artifactName: string; + baseline?: boolean; }, ): Promise { const configResult = await sandbox.exec( @@ -640,14 +653,12 @@ 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", + const route = openClawSwitchRoute( + expected.baseline && FIXED_HOSTED_SWITCH ? null : SWITCH_PROVIDER, + expected.inferenceApi, ); - expect(provider?.apiKey).toBe("unused"); + expect(provider?.baseUrl).toBe(route.baseUrl); + expect(provider?.apiKey).toBe(route.apiKey); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; @@ -675,7 +686,10 @@ async function assertInitialOpenClawConfig( artifactName: string; }, ): Promise { - const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); + const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, { + ...expected, + baseline: true, + }); expect(selectedModel?.contextWindow).toBeUndefined(); expect(selectedModel?.maxTokens).toBeUndefined(); } @@ -737,15 +751,10 @@ async function checkSandboxInference( : { model: SWITCH_MODEL, messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], - max_tokens: 100, + [resolveMaxTokensField(SWITCH_MODEL)]: 100, }; const payloadB64 = Buffer.from(JSON.stringify(payload), "utf8").toString("base64"); - const curlCommand = - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H '${NATIVE_NVIDIA_AUTH_HEADER}' --data-binary @/tmp/nemoclaw-switch-payload.json` - : SWITCH_INFERENCE_API === "anthropic-messages" - ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' --data-binary @/tmp/nemoclaw-switch-payload.json` - : `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data-binary @/tmp/nemoclaw-switch-payload.json`; + const curlCommand = openClawSwitchCurlCommand(SWITCH_PROVIDER, SWITCH_INFERENCE_API); const script = [ "set -u", "tmp=$(mktemp)", @@ -827,7 +836,7 @@ async function checkSandboxInference( const lastFailure = execution.value?.lastFailure ?? "probe failed without a result"; if (execution.evidence.outcome === "exhausted") { const exhausted = classifyExhaustedPostSwitchEvidence({ - required: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, + required: Boolean(SWITCH_PROFILE), lastFailure, }); return exhausted.outcome === "failed" @@ -1040,7 +1049,7 @@ async function runOpenClawInferenceSetWithRetry( home: string, redactionValues: string[], switchBinding: CompatibleAnthropicSwitchBinding | null, - publicNvidiaApiKey: string | null, + nativeApiKey: string | null, artifacts: { writeJson(path: string, value: unknown): Promise }, ): Promise { const attempts = inferenceSetAttemptCount(process.env.NEMOCLAW_SWITCH_SET_ATTEMPTS); @@ -1084,7 +1093,9 @@ async function runOpenClawInferenceSetWithRetry( artifactName: `nemoclaw-inference-set-${attempt}`, env: { ...compatibleAnthropicSwitchEnv(switchBinding), - ...(publicNvidiaApiKey ? { NVIDIA_INFERENCE_API_KEY: publicNvidiaApiKey } : {}), + ...(nativeApiKey && SWITCH_PROFILE + ? { [SWITCH_PROFILE.credentialEnv]: nativeApiKey } + : {}), }, redactionValues, timeoutMs: COMMAND_TIMEOUT_MS, @@ -1149,12 +1160,14 @@ test( }); const useMockBaseline = - SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"; + FIXED_HOSTED_SWITCH || + (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 startFakeOpenAiCompatibleServer({ apiKey: MOCK_BASELINE_API_KEY, + chatContent: "PONG", host: "0.0.0.0", model: MOCK_BASELINE_MODEL, publicHost: "host.openshell.internal", @@ -1166,13 +1179,16 @@ test( SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) : null; + const nativeApiKey = SWITCH_PROFILE + ? (publicApiKey ?? secrets.required(SWITCH_PROFILE.credentialEnv)) + : null; const baseline = baselineProvider ? mockBaselineInference(baselineProvider.baseUrl) : requireHostedInferenceConfig({ required: (name) => publicApiKey ?? secrets.required(name), }); const apiKey = baseline.apiKey; - const redactionValues = [apiKey, publicApiKey].filter( + const redactionValues = [apiKey, publicApiKey, nativeApiKey].filter( (value): value is string => typeof value === "string", ); @@ -1229,7 +1245,7 @@ test( const providerValidationUnavailable = onboard.exitCode !== 0 && isExternalProviderValidationFailure(onboardText); const unavailable = classifyUnavailableInitialProviderEvidence({ - required: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, + required: Boolean(SWITCH_PROFILE), detail: onboardText, }); if (providerValidationUnavailable && unavailable.outcome === "skipped") { @@ -1288,7 +1304,7 @@ test( redactionValues, false, ); - const apiFamilyChanges = SWITCH_MOCK_ANTHROPIC === "1"; + const apiFamilyChanges = SWITCH_MOCK_ANTHROPIC === "1" || SWITCH_PROVIDER === "anthropic-prod"; expect(SWITCH_INFERENCE_API).toBe( apiFamilyChanges ? "anthropic-messages" : "openai-completions", ); @@ -1298,7 +1314,7 @@ test( home, redactionValues, switchBinding, - publicApiKey, + nativeApiKey, artifacts, ); expect(switchResult.exitCode, resultText(switchResult)).toBe(0); diff --git a/test/e2e/support/fixed-hosted-qualification.test.ts b/test/e2e/support/fixed-hosted-qualification.test.ts new file mode 100644 index 00000000000..aadf31f48dd --- /dev/null +++ b/test/e2e/support/fixed-hosted-qualification.test.ts @@ -0,0 +1,189 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { readWorkflow } from "../../helpers/e2e-workflow-contract"; +import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; +import { + FIXED_HOSTED_PLAN_SCRIPT, + FIXED_HOSTED_RUN_SCRIPT, + FIXED_HOSTED_QUALIFICATIONS, + validateFixedHostedSelection, +} from "../../../tools/e2e/fixed-hosted-qualification.mts"; +import { + buildE2eWorkflowPlan, + releaseRequiredWorkflowJobs, +} from "../../../tools/e2e/workflow-plan.mts"; +import { catalogueTargetsForChangedFiles } from "../../../tools/e2e/target-catalogue.mts"; + +const explicit = { hostedModel: "approved/model", eventName: "workflow_dispatch" }; + +describe("fixed hosted qualification planning", () => { + it.each(FIXED_HOSTED_QUALIFICATIONS)( + "selects only the requested protocol representative [$id]", + ({ id, agent }) => { + const plan = buildE2eWorkflowPlan({ targets: id }, explicit); + expect(plan.catalogueMatrices["fixed-hosted"]).toMatchObject([ + { id, agent_runtime: agent, runtime_provider: "docker" }, + ]); + expect(plan.catalogueMatrices["fixed-hosted"]).toHaveLength(1); + }, + ); + + it("keeps explicit qualification out of default, shared-change and release inventory", () => { + expect(buildE2eWorkflowPlan().catalogueMatrices["fixed-hosted"]).toEqual([]); + expect( + catalogueTargetsForChangedFiles(["tools/e2e/target-catalogue.mts"]).some( + (row) => row.profile === "fixed-hosted", + ), + ).toBe(false); + expect(releaseRequiredWorkflowJobs()).not.toContain("catalogue-fixed-hosted"); + expect( + buildE2eWorkflowPlan({ targets: "hermes-inference-switch" }).catalogueMatrices[ + "fixed-hosted" + ], + ).toEqual([]); + }); + + it("rejects missing models, automatic selection and mixed selections before planning work", () => { + const id = FIXED_HOSTED_QUALIFICATIONS[0].id; + expect(() => buildE2eWorkflowPlan({ targets: id })).toThrow(/manual/); + expect(() => buildE2eWorkflowPlan({ targets: id }, { eventName: "workflow_dispatch" })).toThrow( + /model/, + ); + expect(() => buildE2eWorkflowPlan({ targets: id }, { ...explicit, eventName: "push" })).toThrow( + /manual/, + ); + expect(() => + buildE2eWorkflowPlan({ targets: `${id},hermes-inference-switch` }, explicit), + ).toThrow(/one explicitly/); + expect(() => + buildE2eWorkflowPlan({ targets: id }, { ...explicit, gatewayRuntimes: ["podman"] }), + ).toThrow(/does not support/); + expect(() => validateFixedHostedSelection(["unknown"], "model", "workflow_dispatch")).toThrow( + /requires one/, + ); + expect(() => + buildE2eWorkflowPlan({ targets: id }, { ...explicit, hostedModel: "$(leak)" }), + ).toThrow(/model/); + }); + + it("rejects credential crossover in the trusted caller", () => { + const workflow = readWorkflow(); + (workflow.jobs as Record }>)[ + "catalogue-fixed-hosted" + ]!.secrets.HOSTED_PROVIDER_API_KEY = "${{ secrets.NVIDIA_API_KEY }}"; + expect(validateStandardProfileWorkflowBoundary(workflow)).toContain( + "catalogue-fixed-hosted must receive only its profile secrets", + ); + }); + + it("exports only the selected credential and removes the transport alias without logging values", () => { + const credential = "fake-selected-provider-key"; + const result = spawnSync( + "bash", + [ + "-c", + `set -euo pipefail +${FIXED_HOSTED_RUN_SCRIPT} +[[ "$OPENAI_API_KEY" == "fake-selected-provider-key" ]] +[[ -z "\${HOSTED_PROVIDER_API_KEY+x}" ]] +[[ -z "\${ANTHROPIC_API_KEY+x}" && -z "\${NOUS_API_KEY+x}" && -z "\${NVIDIA_API_KEY+x}" && -z "\${OPENROUTER_API_KEY+x}" ]] +[[ "$NEMOCLAW_SWITCH_MODEL" == "approved/model" ]] +`, + ], + { + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOSTED_CREDENTIAL_NAME: "OPENAI_API_KEY", + HOSTED_PROVIDER_API_KEY: credential, + HOSTED_MODEL: "approved/model", + }, + }, + ); + expect(result.status).toBe(0); + expect(result.stdout + result.stderr).not.toContain(credential); + const missing = spawnSync("bash", ["-c", `set -euo pipefail\n${FIXED_HOSTED_RUN_SCRIPT}`], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOSTED_CREDENTIAL_NAME: "OPENAI_API_KEY", + HOSTED_PROVIDER_API_KEY: "", + HOSTED_MODEL: "approved/model", + }, + }); + expect(missing.status).toBe(1); + expect(missing.stderr).toContain("Selected hosted provider credential is unavailable"); + }); + + it.each(FIXED_HOSTED_QUALIFICATIONS)( + "derives credentials before checkout without accepting candidate metadata [$id]", + (selection) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "fixed-hosted-plan-")); + try { + const output = path.join(directory, "outputs"); + const result = spawnSync( + "bash", + ["-c", `set -euo pipefail\nfail() { exit 17; }\n${FIXED_HOSTED_PLAN_SCRIPT}`], + { + encoding: "utf8", + env: { + PATH: process.env.PATH, + CATALOGUE_ID: selection.id, + TARGET_ID: `${selection.agent}-inference-switch`, + TEST_FILE: `test/e2e/live/${selection.agent}-inference-switch.test.ts`, + SHARD: selection.provider, + HOSTED_MODEL: "approved/model", + RUNTIME_PROVIDER: "docker", + GITHUB_OUTPUT: output, + HOSTED_CREDENTIAL_NAME: "ATTACKER_SECRET", + NEMOCLAW_SWITCH_PROVIDER: "attacker", + }, + }, + ); + expect(result.status).toBe(0); + expect(fs.readFileSync(output, "utf8")).toBe(`hosted_credential=${selection.credential}\n`); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it.each([ + { scenario: "target mismatch", override: { TARGET_ID: "hermes-e2e" } }, + { scenario: "test file mismatch", override: { TEST_FILE: "test/e2e/live/hermes-e2e.test.ts" } }, + { scenario: "shard mismatch", override: { SHARD: "nvidia-prod" } }, + { scenario: "missing model", override: { HOSTED_MODEL: "" } }, + { scenario: "unsafe model", override: { HOSTED_MODEL: "model\nATTACKER=value" } }, + { scenario: "unknown target", override: { CATALOGUE_ID: "unknown" } }, + ])("refuses invalid qualification metadata [$scenario]", ({ override }) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "fixed-hosted-denial-")); + try { + const result = spawnSync( + "bash", + ["-c", `set -euo pipefail\nfail() { exit 17; }\n${FIXED_HOSTED_PLAN_SCRIPT}`], + { + env: { + PATH: process.env.PATH, + CATALOGUE_ID: FIXED_HOSTED_QUALIFICATIONS[0].id, + TARGET_ID: "hermes-inference-switch", + TEST_FILE: "test/e2e/live/hermes-inference-switch.test.ts", + SHARD: "hermes-provider", + HOSTED_MODEL: "approved/model", + RUNTIME_PROVIDER: "docker", + GITHUB_OUTPUT: path.join(directory, "outputs"), + ...override, + }, + }, + ); + expect(result.status).toBe(17); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); +}); diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index 24330acba82..40195c13862 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -4,6 +4,9 @@ import { describe, expect, it } from "vitest"; import { + fixedOpenClawSwitchScenario, + openClawSwitchRoute, + openClawSwitchCurlCommand, agentReplyContainsToken, anthropicToolCount, classifyExhaustedPostSwitchEvidence, @@ -239,3 +242,62 @@ describe("openclaw-inference-switch mock-Anthropic baseline", () => { expect(baseline.env.NEMOCLAW_ENDPOINT_URL).toBe("http://10.0.0.5:9000/v1"); }); }); + +describe("native OpenClaw switch qualification", () => { + it.each([ + [ + "openai-api", + "openai-completions", + "OPENAI_API_KEY", + "https://api.openai.com/v1", + "/chat/completions", + "Authorization: Bearer ", + ], + [ + "anthropic-prod", + "anthropic-messages", + "ANTHROPIC_API_KEY", + "https://api.anthropic.com", + "/v1/messages", + "x-api-key: ", + ], + ])( + "selects the native protocol and issued credential for %s", + (provider, inferenceApi, credentialEnv, baseUrl, suffix, auth) => { + expect( + fixedOpenClawSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: provider, + NEMOCLAW_SWITCH_MODEL: " selected-model ", + }), + ).toEqual({ provider, model: "selected-model", inferenceApi, credentialEnv }); + expect(openClawSwitchRoute(provider, inferenceApi)).toEqual({ + baseUrl, + apiKey: `\${${credentialEnv}}`, + }); + const command = openClawSwitchCurlCommand(provider, inferenceApi); + expect(command).toContain(baseUrl + suffix); + expect(command).toContain(auth); + expect(command).toContain(`_${credentialEnv}$`); + expect(command).not.toContain("inference.local"); + expect(() => fixedOpenClawSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: provider })).toThrow( + "NEMOCLAW_SWITCH_MODEL", + ); + expect(() => + fixedOpenClawSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: provider, + NEMOCLAW_SWITCH_MODEL: "selected-model", + NEMOCLAW_SWITCH_INFERENCE_API: "wrong-api", + }), + ).toThrow("protocol"); + }, + ); + it("keeps the authenticated mock baseline on its own shared route", () => { + expect(openClawSwitchRoute(null, "openai-completions")).toEqual({ + baseUrl: "https://inference.local/v1", + apiKey: "unused", + }); + expect( + fixedOpenClawSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint" }), + ).toBeNull(); + }); +}); diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index f01f1d47642..cf5ec468bb9 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -288,7 +288,7 @@ describe("standard E2E execution profile", () => { }); expect(valid.status, valid.stderr).toBe(0); expect(fs.readFileSync(githubOutput, "utf8")).toBe( - "artifact_directory=e2e-artifacts/live/hermes-inference-switch/anthropic\n" + + "hosted_credential=\nartifact_directory=e2e-artifacts/live/hermes-inference-switch/anthropic\n" + "upload_name=e2e-hermes-inference-switch-anthropic-podman\n", ); expect(fs.readFileSync(githubEnvironment, "utf8")).toBe( diff --git a/test/e2e/support/workflow-plan-test-assertions.ts b/test/e2e/support/workflow-plan-test-assertions.ts index 4e29c6bbf20..637278e84da 100644 --- a/test/e2e/support/workflow-plan-test-assertions.ts +++ b/test/e2e/support/workflow-plan-test-assertions.ts @@ -14,6 +14,7 @@ export function expectedWorkflowPlanCiOutput( `matrix=${JSON.stringify(plan.matrix)}`, `test_matrix=${JSON.stringify(plan.testMatrix)}`, `catalogue_standard_matrix=${JSON.stringify(plan.catalogueMatrices.standard)}`, + `catalogue_fixed_hosted_matrix=${JSON.stringify(plan.catalogueMatrices["fixed-hosted"])}`, `catalogue_nvidia_api_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-api"])}`, `catalogue_nvidia_inference_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-inference"])}`, `catalogue_github_read_matrix=${JSON.stringify(plan.catalogueMatrices["github-read"])}`, diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 6567b814735..1dd74ad9888 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -79,14 +79,16 @@ describe("E2E workflow plan", () => { expect(plan.testMatrix).toEqual( credentialFreeTestMatrix(discoverCredentialFreeTests(), ["docker"]), ); - expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength(E2E_TARGET_CATALOGUE.length); + expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength( + E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired).length, + ); expect( plan.coverageMatrix.reduce>((counts, row) => { counts[row.source] = (counts[row.source] ?? 0) + 1; return counts; }, {}), ).toEqual({ - catalogue: E2E_TARGET_CATALOGUE.length, + catalogue: E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired).length, "typed-registry": 3, "shared-e2e": 1, "retained-workflow": 14, @@ -699,6 +701,7 @@ describe("E2E workflow plan", () => { "nvidia-api": false, "nvidia-inference": false, "github-read": false, + "fixed-hosted": false, }); }); @@ -969,7 +972,9 @@ describe("E2E workflow plan", () => { { changedFiles: [".github/workflows/e2e-standard-profile.yaml"] }, ); - expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength(E2E_TARGET_CATALOGUE.length); + expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength( + E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired).length, + ); expect(plan.selectedJobs).toEqual(["jetson-nvmap-gpu"]); expect(plan.matrix).toEqual([]); expect(plan.testMatrix).toEqual([]); @@ -977,7 +982,7 @@ describe("E2E workflow plan", () => { it("selects every catalogue target when its shared installer changes", () => { expect(catalogueTargetsForChangedFiles(["scripts/install-openshell.sh"])).toEqual( - E2E_TARGET_CATALOGUE, + E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired), ); }); @@ -1149,6 +1154,7 @@ describe("E2E workflow plan", () => { "nvidia-api": [], "nvidia-inference": [], "github-read": [], + "fixed-hosted": [], }, coverageMatrix: [], selectedJobs: ["jetson-nvmap-gpu"], diff --git a/tools/e2e/fixed-hosted-qualification.mts b/tools/e2e/fixed-hosted-qualification.mts new file mode 100644 index 00000000000..7d14594ac92 --- /dev/null +++ b/tools/e2e/fixed-hosted-qualification.mts @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Explicit protocol/credential representatives, not a vendor/platform matrix. +export const FIXED_HOSTED_QUALIFICATIONS = [ + { + id: "hermes-fixed-bearer-inference-switch", + agent: "hermes", + provider: "hermes-provider", + credential: "NOUS_API_KEY", + protocol: "openai-completions", + }, + { + id: "hermes-fixed-anthropic-inference-switch", + agent: "hermes", + provider: "anthropic-prod", + credential: "ANTHROPIC_API_KEY", + protocol: "anthropic-messages", + }, + { + id: "hermes-fixed-openrouter-inference-switch", + agent: "hermes", + provider: "openrouter-api", + credential: "OPENROUTER_API_KEY", + protocol: "openai-completions", + }, + { + id: "openclaw-fixed-openai-inference-switch", + agent: "openclaw", + provider: "openai-api", + credential: "OPENAI_API_KEY", + protocol: "openai-completions", + }, + { + id: "openclaw-fixed-anthropic-inference-switch", + agent: "openclaw", + provider: "anthropic-prod", + credential: "ANTHROPIC_API_KEY", + protocol: "anthropic-messages", + }, +] as const; + +export function fixedHostedQualification(id: string) { + return FIXED_HOSTED_QUALIFICATIONS.find((row) => row.id === id); +} + +export function validateFixedHostedModel(model: string): void { + if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$/u.test(model)) { + throw new Error( + "Fixed hosted qualification requires an explicit model ID without whitespace or shell syntax", + ); + } +} + +export function validateFixedHostedSelection( + ids: readonly string[], + model: string, + event: string, +): void { + const selected = ids.filter((id) => fixedHostedQualification(id)); + if (selected.length === 0) { + if (model !== "") + throw new Error("hosted_model requires one fixed hosted qualification target"); + return; + } + if (event !== "workflow_dispatch" || ids.length !== 1) { + throw new Error("Fixed hosted qualification requires one explicitly selected manual target"); + } + validateFixedHostedModel(model); +} + +// Executed by the trusted reusable workflow before candidate checkout. No candidate +// metadata chooses the credential name, provider, protocol, or model validation. +export const FIXED_HOSTED_PLAN_SCRIPT = `hosted_credential="" +case "$CATALOGUE_ID" in +${FIXED_HOSTED_QUALIFICATIONS.map((row) => ` ${row.id}) [[ "$TARGET_ID" == "${row.agent}-inference-switch" && "$TEST_FILE" == "test/e2e/live/${row.agent}-inference-switch.test.ts" && "$SHARD" == "${row.provider}" ]] || fail "fixed hosted identity"; hosted_credential=${row.credential} ;;`).join("\n")} + *) [[ -z "\${HOSTED_MODEL:-}" ]] || fail "unexpected hosted model" ;; +esac +if [[ -n "$hosted_credential" ]]; then + [[ "$RUNTIME_PROVIDER" == "docker" ]] || fail "fixed hosted runtime" + [[ "$HOSTED_MODEL" =~ ^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$ ]] || fail "hosted model" +fi +printf 'hosted_credential=%s\n' "$hosted_credential" >>"$GITHUB_OUTPUT"`; + +export const FIXED_HOSTED_RUN_SCRIPT = `if [[ -n "$HOSTED_CREDENTIAL_NAME" ]]; then + [[ -n "$HOSTED_PROVIDER_API_KEY" ]] || { echo "::error::Selected hosted provider credential is unavailable" >&2; exit 1; } + printf -v "$HOSTED_CREDENTIAL_NAME" '%s' "$HOSTED_PROVIDER_API_KEY" + export "$HOSTED_CREDENTIAL_NAME" + export NEMOCLAW_SWITCH_MODEL="$HOSTED_MODEL" +fi +unset HOSTED_PROVIDER_API_KEY`; diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 1ca2494b1f7..11f9fac8635 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -1009,6 +1009,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): } for (const jobName of [ "catalogue-standard", + "catalogue-fixed-hosted", "catalogue-nvidia-api", "catalogue-nvidia-inference", "catalogue-github-read", @@ -1112,6 +1113,7 @@ const STOCK_ONBOARDING_JOBS = [ const STOCK_ONBOARDING_CATALOGUE_JOBS = [ "catalogue-standard", + "catalogue-fixed-hosted", "catalogue-nvidia-api", "catalogue-nvidia-inference", "catalogue-github-read", diff --git a/tools/e2e/pre-candidate-workflow-contract.mts b/tools/e2e/pre-candidate-workflow-contract.mts index 3d40ec7bb33..81b7c1060b0 100644 --- a/tools/e2e/pre-candidate-workflow-contract.mts +++ b/tools/e2e/pre-candidate-workflow-contract.mts @@ -61,6 +61,7 @@ export const PRE_CANDIDATE_STEP_ENV: Readonly `\${{ ${TRUSTED_CALLER_CREDENTIAL_PREDICATE} && secrets.${name} || '' }}`; +const FIXED_HOSTED_CALLER_SECRET = + "${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }}"; const SKILL_AGENT_UPLOAD_PATH = `${[ "e2e-artifacts/live/skill-agent/evidence-manifest.json", "e2e-artifacts/live/skill-agent/*/artifact-summary.json", @@ -47,6 +53,14 @@ const SKILL_AGENT_UPLOAD_PATH = `${[ "e2e-artifacts/live/skill-agent/*/shell/*.stderr.txt", ].join("\n")}\n`; const PROFILE_JOBS = { + "fixed-hosted": { + job: "catalogue-fixed-hosted", + matrix: "catalogue_fixed_hosted_matrix", + credentialBoundary: "Selected fixed hosted provider", + secrets: ["DOCKERHUB_TOKEN", "DOCKERHUB_USERNAME", "HOSTED_PROVIDER_API_KEY"], + githubToken: false, + maxParallel: undefined, + }, standard: { job: "catalogue-standard", matrix: "catalogue_standard_matrix", @@ -208,10 +222,18 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi errors.push(`${contract.job} must pass ${name} from the catalogue matrix`); } } + if (profile === "fixed-hosted" && withInputs.hosted_model !== "${{ inputs.hosted_model }}") + errors.push("fixed hosted profile must pass the explicit model input"); const callerSecrets = record(job.secrets); if ( Object.keys(callerSecrets).sort().join(",") !== [...contract.secrets].sort().join(",") || - contract.secrets.some((name) => callerSecrets[name] !== guardedCallerSecret(name)) + contract.secrets.some( + (name) => + callerSecrets[name] !== + (name === "HOSTED_PROVIDER_API_KEY" + ? FIXED_HOSTED_CALLER_SECRET + : guardedCallerSecret(name)), + ) ) { errors.push(`${contract.job} must receive only its profile secrets`); } @@ -222,6 +244,16 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi const triggers = record(profile.on ?? profile[true as unknown as string]); const call = record(triggers.workflow_call); const inputs = record(call.inputs); + const hostedModelInput = record(inputs.hosted_model); + if ( + hostedModelInput.required !== false || + hostedModelInput.type !== "string" || + hostedModelInput.default !== "" + ) + errors.push("fixed hosted model must be an optional explicit string input"); + const requiredCallInputs = Object.fromEntries( + Object.entries(inputs).filter(([name]) => name !== "hosted_model"), + ); const requiredInputs = { candidate_repository: "string", candidate_sha: "string", @@ -258,7 +290,8 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi trusted_main: "boolean", }; if ( - Object.keys(inputs).sort().join(",") !== Object.keys(requiredInputs).sort().join(",") || + Object.keys(requiredCallInputs).sort().join(",") !== + Object.keys(requiredInputs).sort().join(",") || Object.entries(requiredInputs).some( ([name, type]) => record(inputs[name]).required !== true || record(inputs[name]).type !== type, @@ -267,6 +300,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi errors.push("standard E2E profile must require its exact execution-plan inputs"); } const acceptedSecrets = [ + "HOSTED_PROVIDER_API_KEY", "DOCKERHUB_TOKEN", "DOCKERHUB_USERNAME", "NVIDIA_API_KEY", @@ -277,7 +311,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi Object.keys(declaredSecrets).sort().join(",") !== acceptedSecrets.sort().join(",") || acceptedSecrets.some((name) => record(declaredSecrets[name]).required !== false) ) { - errors.push("standard E2E profile must accept only its four optional profile secrets"); + errors.push("standard E2E profile must accept only its reviewed optional profile secrets"); } if (record(profile.permissions).contents !== "read") { errors.push("standard E2E profile permissions must be contents: read"); @@ -390,6 +424,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi ENV: "/dev/null", EXECUTION_ID: "${{ inputs.execution_id }}", GITHUB_WORKSPACE_VALUE: "${{ github.workspace }}", + HOSTED_MODEL: "${{ inputs.hosted_model }}", HOST_PACKAGES: "${{ inputs.host_packages }}", HOST_PREPARATION: "${{ inputs.host_preparation }}", INSTALL_MODE: "${{ inputs.install_mode }}", @@ -399,7 +434,8 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi TARGET_ID: "${{ inputs.target_id }}", TEST_FILE: "${{ inputs.test_file }}", }) || - executionPlanFragments.some((fragment) => !executionPlanRun.includes(fragment)) + executionPlanFragments.some((fragment) => !executionPlanRun.includes(fragment)) || + !executionPlanRun.includes(FIXED_HOSTED_PLAN_SCRIPT) ) { errors.push( "standard E2E profile must derive validated execution paths before candidate checkout", @@ -661,6 +697,11 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi !String(execute?.run).includes( 'npx tsx tools/e2e/target-catalogue.mts run "$CATALOGUE_ID" "$TEST_FILE"', ) || + !String(execute?.run).includes(FIXED_HOSTED_RUN_SCRIPT) || + executeEnv.HOSTED_PROVIDER_API_KEY !== + "${{ inputs.trusted_main && secrets.HOSTED_PROVIDER_API_KEY || '' }}" || + executeEnv.HOSTED_CREDENTIAL_NAME !== "${{ steps.execution_plan.outputs.hosted_credential }}" || + executeEnv.HOSTED_MODEL !== "${{ inputs.hosted_model }}" || executeEnv.INSTALL_MODE !== "${{ inputs.install_mode }}" || executeEnv.CATALOGUE_ID !== "${{ inputs.catalogue_id }}" || executeEnv.TEST_FILE !== "${{ inputs.test_file }}" || diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 8122fd4acec..0aebc3b184c 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -31,7 +31,10 @@ import { import { SANDBOX_SURVIVAL_TARGET_TIMEOUT_MINUTES } from "./sandbox-survival-timeout-contract.mts"; import { normalizeE2eSelectorId } from "./selector-aliases.mts"; +import { FIXED_HOSTED_QUALIFICATIONS } from "./fixed-hosted-qualification.mts"; + export const E2E_EXECUTION_PROFILES = [ + "fixed-hosted", "standard", "nvidia-api", "nvidia-inference", @@ -1620,6 +1623,33 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: false, exposeCliBin: false, }), + ...FIXED_HOSTED_QUALIFICATIONS.map((selection) => ({ + ...target(selection.id, { + displayName: `Inference: ${selection.agent} switches to ${selection.provider}`, + agentRuntime: selection.agent, + environmentOrInferenceEndpoint: `Ubuntu; native ${selection.provider} inference`, + profile: "fixed-hosted", + targetId: `${selection.agent}-inference-switch`, + testFile: `test/e2e/live/${selection.agent}-inference-switch.test.ts`, + timeoutMinutes: selection.agent === "openclaw" ? 90 : 55, + installMode: selection.agent === "openclaw" ? "none" : "authenticated", + installNonInteractive: true, + restoreCli: true, + exposeCliBin: true, + hostPreparation: selection.agent === "hermes" ? "hermes-swap" : "none", + shard: selection.provider, + gatewayRuntimes: ["docker"], + environment: { + ...nonInteractive, + NEMOCLAW_AGENT: selection.agent, + NEMOCLAW_SWITCH_PROVIDER: selection.provider, + NEMOCLAW_SWITCH_INFERENCE_API: selection.protocol, + NEMOCLAW_SANDBOX_NAME: `e2e-${selection.agent}-${selection.provider}`, + OPENSHELL_GATEWAY: "nemoclaw", + }, + }), + releaseRequired: false, + })), ] as const; export const E2E_CATALOGUE_SHARED_PATHS = [ @@ -1821,13 +1851,15 @@ export function catalogueTargetsForChangedFiles( ): E2eCatalogueTarget[] { const files = [...new Set(changedFiles)]; if (files.some((file) => E2E_CATALOGUE_SHARED_PATHS.some((owner) => pathMatches(file, owner)))) { - return [...E2E_TARGET_CATALOGUE]; + return E2E_TARGET_CATALOGUE.filter((entry) => entry.profile !== "fixed-hosted"); } - return E2E_TARGET_CATALOGUE.filter((entry) => - files.some( - (file) => - file === entry.testFile || entry.owningPaths.some((owner) => pathMatches(file, owner)), - ), + return E2E_TARGET_CATALOGUE.filter( + (entry) => + entry.profile !== "fixed-hosted" && + files.some( + (file) => + file === entry.testFile || entry.owningPaths.some((owner) => pathMatches(file, owner)), + ), ); } diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 3fa8673d216..01a7d561dfb 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -262,6 +262,7 @@ const MATRIX_ROUTED_JOB_RUNNER_EXPRESSIONS = { } as const; const CATALOGUE_ROUTED_JOB_NAMES = [ "catalogue-standard", + "catalogue-fixed-hosted", "catalogue-nvidia-api", "catalogue-nvidia-inference", "catalogue-github-read", @@ -2651,7 +2652,7 @@ const PRE_CANDIDATE_RUN_SHA256: Readonly> = { "ee0b2e6c6aa4552b228bd1cc3ba4e1f9cd72701c30b81f7d5fbf9bc011fb51c7", "Authorize Launchable E2E maintainer dispatch": "bbf442a006b47016eda56133eb400a48c6931c55364c1220b84327b5ffd6f171", - "Generate E2E target matrix": "7b250c79a05973c6bc2f904195c174ddd6ffee80c62a2ff3362d7362e075b0ef", + "Generate E2E target matrix": "a34c4e9f4e7d28d28e1f8096612f3db91ecbcb8a5638ae161ac0a0c1e3ae7ee8", }; function requirePreCandidateEnvironment( diff --git a/tools/e2e/workflow-plan.mts b/tools/e2e/workflow-plan.mts index a6b2ce9443d..899ce99e5ab 100644 --- a/tools/e2e/workflow-plan.mts +++ b/tools/e2e/workflow-plan.mts @@ -1,3 +1,4 @@ +import { validateFixedHostedSelection } from "./fixed-hosted-qualification.mts"; // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 @@ -80,6 +81,8 @@ export type E2eWorkflowPlan = { }; type WorkflowPlanOptions = { + hostedModel?: string; + eventName?: string; changedFiles?: readonly string[]; gatewayRuntimes?: readonly E2eGatewayRuntime[]; }; @@ -97,6 +100,7 @@ const INFERENCE_MODES = new Set(["mock", "internal-nvidia", "public-nvidia"]); const CATALOGUE_JOB_BY_PROFILE: Record = { standard: "catalogue-standard", "nvidia-api": "catalogue-nvidia-api", + "fixed-hosted": "catalogue-fixed-hosted", "nvidia-inference": "catalogue-nvidia-inference", "github-read": "catalogue-github-read", }; @@ -443,6 +447,7 @@ function emptyCatalogueMatrices(): Record 0 || targets.length > 0) { const selectedIds = new Set([...jobs, ...targets]); const selectedCatalogueTargets = E2E_TARGET_CATALOGUE.filter( - (target) => selectedIds.has(target.id) || selectedIds.has(target.targetId), + (target) => + selectedIds.has(target.id) || + (target.profile !== "fixed-hosted" && selectedIds.has(target.targetId)), ); const unsupportedCatalogueTarget = selectedCatalogueTargets.find( (target) => e2eRuntimeProviders(target.gatewayRuntimes, gatewayRuntimes).length === 0, @@ -824,7 +836,9 @@ export function buildE2eWorkflowPlan( ...riskJobIds, ]); const selectedCatalogueTargets = E2E_TARGET_CATALOGUE.filter( - (target) => selectedCatalogueIds.has(target.id) || selectedCatalogueIds.has(target.targetId), + (target) => + target.profile !== "fixed-hosted" && + (selectedCatalogueIds.has(target.id) || selectedCatalogueIds.has(target.targetId)), ); const unresolvedRiskJobIds = riskJobIds.filter((id) => { const workflowJob = inventory.targetToJob.get(id) ?? id; @@ -876,7 +890,10 @@ export function buildE2eWorkflowPlan( gatewayRuntimes, matrix: buildLiveTargetMatrix([], gatewayRuntimes), testMatrix, - catalogueMatrices: catalogueMatrices(E2E_TARGET_CATALOGUE, gatewayRuntimes), + catalogueMatrices: catalogueMatrices( + E2E_TARGET_CATALOGUE.filter((target) => target.profile !== "fixed-hosted"), + gatewayRuntimes, + ), selectedJobs, runtimeProvidersByJob: runtimeProvidersByJob( inventory, @@ -1139,6 +1156,11 @@ export function writeE2eWorkflowPlanCiOutput( selectors: WorkflowPlanSelectors, environment: NodeJS.ProcessEnv = process.env, ): void { + validateFixedHostedSelection( + [...selectorIds(selectors.jobs, "jobs"), ...selectorIds(selectors.targets, "targets")], + environment.HOSTED_MODEL ?? "", + environment.EVENT_NAME ?? "", + ); const inferenceMode = environment.INFERENCE_MODE ?? ""; if (!INFERENCE_MODES.has(inferenceMode)) { throw new Error(`Invalid inference_mode: ${inferenceMode}`); @@ -1154,7 +1176,12 @@ export function writeE2eWorkflowPlanCiOutput( ); const hasPlannerSelectors = Boolean(selectors.jobs || selectors.targets); const changedFiles = hasPlannerSelectors ? undefined : changedFilesFromEnvironment(environment); - const planned = buildE2eWorkflowPlan(selectors, { changedFiles, gatewayRuntimes }); + const planned = buildE2eWorkflowPlan(selectors, { + changedFiles, + gatewayRuntimes, + hostedModel: environment.HOSTED_MODEL, + eventName: environment.EVENT_NAME, + }); const plan = validateE2eWorkflowPlan(planned); const expectedHermes = expectedHermesSelection(selectors); if (!changedFiles && plan.hermesSelected !== expectedHermes) { @@ -1169,6 +1196,7 @@ export function writeE2eWorkflowPlanCiOutput( `matrix=${JSON.stringify(plan.matrix)}`, `test_matrix=${JSON.stringify(plan.testMatrix)}`, `catalogue_standard_matrix=${JSON.stringify(plan.catalogueMatrices.standard)}`, + `catalogue_fixed_hosted_matrix=${JSON.stringify(plan.catalogueMatrices["fixed-hosted"])}`, `catalogue_nvidia_api_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-api"])}`, `catalogue_nvidia_inference_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-inference"])}`, `catalogue_github_read_matrix=${JSON.stringify(plan.catalogueMatrices["github-read"])}`, From 578edc9faca0bfb0d2475e4a6c3dc2555cf42329 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 06:39:51 -0700 Subject: [PATCH 086/133] test(e2e): include fixed qualification inventory dependency Signed-off-by: Deepak Jain --- test/automation/e2e/e2e-recommendations.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/automation/e2e/e2e-recommendations.test.ts b/test/automation/e2e/e2e-recommendations.test.ts index 37ea6320eae..ad37cdf06e2 100644 --- a/test/automation/e2e/e2e-recommendations.test.ts +++ b/test/automation/e2e/e2e-recommendations.test.ts @@ -136,6 +136,7 @@ describe("E2E recommendation normalizer", () => { "tools/advisors/risk-plan.mts", "tools/e2e/credential-free-tests.mts", "tools/e2e/execution-coverage.mts", + "tools/e2e/fixed-hosted-qualification.mts", "tools/e2e/full-e2e-timeout-contract.mts", "tools/e2e/gateway-runtime.mts", "tools/e2e/hermes-acp-owning-paths.mts", From b725b87f278415baa9be563eeb04fc6f3f98f7ac Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 07:41:46 -0700 Subject: [PATCH 087/133] fix(inference): address native hosted review findings Signed-off-by: Deepak Jain --- .github/workflows/e2e.yaml | 10 +- docs/about/ecosystem-hermes.mdx | 8 +- src/lib/actions/credentials-add.ts | 10 +- src/lib/actions/credentials/reset.ts | 2 +- .../actions/inference-set-hermes-run.test.ts | 89 ++++ src/lib/actions/inference-set.ts | 4 +- src/lib/actions/sandbox/doctor-inference.ts | 2 +- .../actions/sandbox/inference-route-health.ts | 2 +- src/lib/credentials/provider-list.ts | 2 +- src/lib/inference/config.test.ts | 2 +- src/lib/inference/config.ts | 7 +- .../inference/native-hosted/authority.test.ts | 28 ++ src/lib/inference/native-hosted/authority.ts | 20 +- src/lib/inference/native-hosted/index.test.ts | 102 ++++ src/lib/inference/native-hosted/profiles.ts | 3 + src/lib/inference/native-nvidia.test.ts | 452 +----------------- src/lib/inference/native-nvidia/contract.ts | 4 + src/lib/inference/native-nvidia/index.ts | 42 -- .../native-nvidia-provider-authority-state.ts | 2 +- .../native-nvidia-provider-authority.ts | 2 +- test/e2e/README.md | 11 +- .../fixed-hosted-qualification.test.ts | 67 ++- .../native-nvidia-target-ownership.test.ts | 2 +- .../standard-profile-workflow-boundary.mts | 15 +- tools/e2e/target-catalogue.mts | 4 +- 25 files changed, 355 insertions(+), 537 deletions(-) delete mode 100644 src/lib/inference/native-nvidia/index.ts diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index e5eff488fc7..32ba756d083 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -3301,7 +3301,7 @@ jobs: catalogue-fixed-hosted: name: ${{ matrix.display_name }} (${{ matrix.runtime_provider }}) needs: [base-image-publication, generate-matrix, package-openshell-sdk] - if: ${{ needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix != '[]' }} + if: ${{ needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix != '[]' && github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }} strategy: fail-fast: false matrix: @@ -3341,11 +3341,11 @@ jobs: github_token: false shard: ${{ matrix.shard }} artifact_layout: ${{ matrix.artifact_layout }} - trusted_main: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/main') && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }} + trusted_main: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }} secrets: - DOCKERHUB_USERNAME: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_USERNAME || '' }} - DOCKERHUB_TOKEN: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_TOKEN || '' }} - HOSTED_PROVIDER_API_KEY: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }} + DOCKERHUB_USERNAME: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_USERNAME || '' }} + DOCKERHUB_TOKEN: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_TOKEN || '' }} + HOSTED_PROVIDER_API_KEY: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }} catalogue-nvidia-api: name: ${{ matrix.display_name }} (${{ matrix.runtime_provider }}) diff --git a/docs/about/ecosystem-hermes.mdx b/docs/about/ecosystem-hermes.mdx index 60968612b9b..b63cc40c3d3 100644 --- a/docs/about/ecosystem-hermes.mdx +++ b/docs/about/ecosystem-hermes.mdx @@ -43,8 +43,8 @@ flowchart TB NemoClaw sits above OpenShell in the operator workflow. It calls OpenShell APIs and CLI commands to create and configure the sandbox that runs Hermes. -Models and endpoints sit behind OpenShell's inference routing. -NemoClaw onboarding connects your provider choice to that route, including the Hermes Provider route when you onboard through `nemohermes`. +Fixed hosted providers, including Hermes Provider, use native endpoints through OpenShell providers attached to the selected sandbox. +Custom, local, and Model Router selections use the shared `inference.local` route. The following table shows the scope of each component in the stack. @@ -75,10 +75,10 @@ The following table compares custom OpenShell integration with `nemohermes onboa | Capability | Custom OpenShell + Hermes | `nemohermes onboard` | |---|---|---| | Sandbox isolation | Yes, when you apply OpenShell seccomp, Landlock, network namespace isolation, and no-new-privileges enforcement through your policy. | Yes. NemoClaw applies these through the blueprint and layers a Hermes-specific restrictive policy on top. | -| Credential handling | You create OpenShell providers manually with `openshell provider create` and configure placeholder resolution at egress. | NemoClaw creates OpenShell providers during onboarding and filters sensitive host environment variables from the sandbox creation command to reduce accidental leakage through build args. | +| Credential handling | You create OpenShell providers manually with `openshell provider create` and configure placeholder resolution at egress. | OpenShell retains provider credentials outside the sandbox; Hermes uses a placeholder that OpenShell resolves at egress. NemoClaw filters sensitive host environment variables from sandbox creation to reduce accidental leakage through build args. | | Image hardening | Depends on your base image and install steps. | NemoClaw removes build toolchains (`gcc`, `g++`, `make`) and network probes (`netcat`) from the runtime image to reduce attack surface. | | Filesystem policy | You define read-only and read-write paths in policy YAML. | NemoClaw defines a targeted layout: system paths (`/usr`, `/lib`, `/etc`) are read-only; `/sandbox` and `/sandbox/.hermes` are writable for agent state and configuration. | -| Inference setup | You configure OpenShell inference routing and Hermes `config.yaml` manually. | NemoClaw validates the selected provider and model from the host, configures the OpenShell route, and writes the managed model settings into `/sandbox/.hermes/config.yaml`. Hermes Provider onboarding is available through `nemohermes`. | +| Inference setup | You configure OpenShell inference routing and Hermes `config.yaml` manually. | NemoClaw validates the selected provider and model from the host and writes managed model settings into `/sandbox/.hermes/config.yaml`. Fixed hosted providers use sandbox-attached OpenShell providers and native endpoints. Custom, local, and Model Router selections use the shared `inference.local` route. | | Managed MCP | You register providers, network policy, and Hermes MCP configuration yourself. | NemoClaw manages authenticated HTTPS Streamable HTTP MCP server lifecycle, ownership records, policy, and credential placeholders through host-side commands. | | Channel messaging | OpenShell delivers channel credentials through its provider system and L7 proxy. You configure Hermes platform adapters manually. | NemoClaw configures supported channels during onboarding or through lifecycle commands and writes the managed Hermes channel settings. | | Blueprint versioning | No NemoClaw blueprint; your image tag is whatever you built locally. | NemoClaw downloads the blueprint artifact, checks version compatibility, and verifies its digest before applying. Repeated onboarding uses the selected blueprint and recorded configuration; host and platform differences can still affect the result. | diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index 8fe6aabdb04..a3c2f1a7083 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -23,10 +23,7 @@ import { persistNativeHostedProviderAuthority, nativeHostedProviderProfilePath, } from "../inference/native-hosted"; -import { - normalizeNativeNvidiaProviderAttachment, - NativeNvidiaProviderError, -} from "../inference/native-nvidia"; +import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia/contract"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, TAVILY_PROVIDER_PROFILE_AGENTS, @@ -481,10 +478,7 @@ export async function runCredentialsAddAction( ` Select it with '${CLI_NAME} inference set --provider ${provider} --model '.`, ]); } catch (error) { - const detail = - error instanceof NativeNvidiaProviderError || error instanceof Error - ? error.message - : String(error); + const detail = error instanceof Error ? error.message : String(error); return fail([` Could not register provider '${provider}'.`, ` ${detail}`]); } }); diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 995045c9d00..43c214c5925 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -18,7 +18,7 @@ import { CLI_NAME } from "../../cli/branding"; import { NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_LOGICAL_PROVIDER, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import { isBridgeProviderName, recoverCredentialGatewayTargetOrExit, diff --git a/src/lib/actions/inference-set-hermes-run.test.ts b/src/lib/actions/inference-set-hermes-run.test.ts index 2b2ede4c3ca..027512e0792 100644 --- a/src/lib/actions/inference-set-hermes-run.test.ts +++ b/src/lib/actions/inference-set-hermes-run.test.ts @@ -21,6 +21,95 @@ describe("runInferenceSet Hermes routing", () => { portableMocks.assertUnavailable.mockReset(); }); + it("creates the first native Hermes provider from its Nous API key", async () => { + const deps = createDeps({ + config: { + model: { default: "baseline", provider: "custom", base_url: "https://inference.local/v1" }, + }, + entry: { + name: "hermes", + agent: "hermes", + gatewayName: "nemoclaw", + provider: "compatible-endpoint", + model: "baseline", + }, + defaultSandbox: "hermes", + target: HERMES_TARGET, + resolveCredentialValue: (name) => (name === "NOUS_API_KEY" ? "nous-test-credential" : ""), + }); + const create = vi.spyOn(deps.providerAdapter, "createProvider"); + const attach = vi.spyOn(deps.providerAdapter, "attachProvider"); + await runInferenceSet( + { + provider: "hermes-provider", + model: "selected-model", + sandboxName: "hermes", + noVerify: true, + }, + deps, + ); + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + name: "nemoclaw-hermes-provider-v1", + credentials: [{ name: "OPENAI_API_KEY", value: "nous-test-credential" }], + }), + ); + expect(attach).toHaveBeenCalledWith( + expect.objectContaining({ + providerName: "nemoclaw-hermes-provider-v1", + sandboxName: "hermes", + }), + ); + expect(deps.calls.resolveCredentialValue).toHaveBeenCalledWith("NOUS_API_KEY"); + expect(JSON.stringify(deps.calls.writeSandboxConfig.mock.calls)).not.toContain( + "nous-test-credential", + ); + expect(JSON.stringify(deps.calls.updateSandbox.mock.calls)).not.toContain( + "nous-test-credential", + ); + }); + + it("reuses an owned Hermes provider without a manual Nous API key", async () => { + const deps = createDeps({ + config: { + model: { + default: "baseline", + provider: "custom", + base_url: "https://inference-api.nousresearch.com/v1", + }, + }, + entry: { + name: "hermes", + agent: "hermes", + gatewayName: "nemoclaw", + provider: "hermes-provider", + model: "baseline", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "owned-oauth-provider", + }, + }, + defaultSandbox: "hermes", + target: HERMES_TARGET, + resolveCredentialValue: () => "", + }); + const create = vi.spyOn(deps.providerAdapter, "createProvider"); + const update = vi.spyOn(deps.providerAdapter, "updateProvider"); + await runInferenceSet( + { + provider: "hermes-provider", + model: "selected-model", + sandboxName: "hermes", + noVerify: true, + }, + deps, + ); + expect(create).not.toHaveBeenCalled(); + expect(update).not.toHaveBeenCalled(); + }); + it("rejects schema-5 before OpenShell or registry mutation (#9203)", async () => { portableMocks.assertUnavailable.mockImplementation(() => { throw new Error("schema-5 rejected"); diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index b1da38d37b2..3ade37ff512 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1002,9 +1002,7 @@ async function prepareNativeHostedSelection(input: { target, profile, credentialValue: - input.provider === "hermes-provider" - ? null - : input.deps.resolveCredentialValue(profile.credentialEnv) || null, + input.deps.resolveCredentialValue(profile.hostCredentialEnv ?? profile.credentialEnv) || null, ...(input.expectedAttachment?.profileId === profile.profileId ? { expected: input.expectedAttachment } : {}), diff --git a/src/lib/actions/sandbox/doctor-inference.ts b/src/lib/actions/sandbox/doctor-inference.ts index 1922bd24269..1d4feaf5ea9 100644 --- a/src/lib/actions/sandbox/doctor-inference.ts +++ b/src/lib/actions/sandbox/doctor-inference.ts @@ -26,7 +26,7 @@ import { isNativeNvidiaProvider, normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import { classifyInferenceRouteFailureLabel, formatUntrustedProbeDetail, diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 6b014677fbb..5198313c55f 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -18,7 +18,7 @@ import { import { NVIDIA_HOSTED_NATIVE_ENDPOINT, type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import { isOpenRouterRuntimeAdapterModelsRoute404 } from "../../inference/openrouter"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; import { diff --git a/src/lib/credentials/provider-list.ts b/src/lib/credentials/provider-list.ts index 7c393993085..411e3208005 100644 --- a/src/lib/credentials/provider-list.ts +++ b/src/lib/credentials/provider-list.ts @@ -5,7 +5,7 @@ import { listMessagingProviderSuffixes } from "../messaging/channels"; import { NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../inference/native-nvidia"; +} from "../inference/native-nvidia/contract"; const BRIDGE_PROVIDER_SUFFIXES: readonly string[] = [...listMessagingProviderSuffixes()]; diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index e280d3215a5..1adc3dd3bbd 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -29,7 +29,7 @@ import { sanitizeRouteValueForDisplay, VLLM_LOCAL_CREDENTIAL_ENV, } from "./config"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia/contract"; describe("resolveAgentDefaultCloudModel", () => { it("uses the Deep Agents manifest default", () => { diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 8a4ae2cf75b..f456ba05d44 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -14,7 +14,7 @@ import { LLAMA_CPP_PROVIDER_NAME, } from "./llama-cpp/contract"; import { nativeHostedProfile, NATIVE_HOSTED_PROFILES } from "./native-hosted/profiles"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia/contract"; import type { ManagedLlamaCppOwnership } from "./llama-cpp/managed-state"; import { DEFAULT_OLLAMA_MODEL_TAG as DEFAULT_OLLAMA_MODEL } from "./ollama-model-registry"; import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "./ollama/contract"; @@ -38,9 +38,8 @@ export { NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_ENDPOINT, normalizeNativeNvidiaProviderAttachment, - resolveGatewayNativeNvidiaProviderAuthority, -} from "./native-nvidia"; -export type { NativeNvidiaProviderAttachment } from "./native-nvidia"; +} from "./native-nvidia/contract"; +export type { NativeNvidiaProviderAttachment } from "./native-nvidia/contract"; export const INFERENCE_ROUTE_URL = "https://inference.local/v1"; export const NOUS_RECOMMENDED_MODELS_URL = diff --git a/src/lib/inference/native-hosted/authority.test.ts b/src/lib/inference/native-hosted/authority.test.ts index 9fe8c3109d2..5382dc2c4c3 100644 --- a/src/lib/inference/native-hosted/authority.test.ts +++ b/src/lib/inference/native-hosted/authority.test.ts @@ -65,6 +65,34 @@ describe("native hosted provider ownership", () => { ).toBeUndefined(); }, ); + it("uses gateway ownership despite a stale peer attachment", () => { + const current = { ...openaiReceipt, providerId: "new-registration" }; + expect( + resolveGatewayNativeHostedProviderAuthority({ + profile: openai, + gatewayName: "alpha", + gatewayAuthority: current, + sandboxes: [ + { + gatewayName: "alpha", + nativeHostedProviderAttachment: openaiReceipt, + nativeHostedProviderAuthorities: [openaiReceipt], + }, + ], + }), + ).toEqual(current); + }); + it("does not promote retained peer receipts to gateway ownership", () => { + expect( + resolveGatewayNativeHostedProviderAuthority({ + profile: openai, + gatewayName: "alpha", + recordedGatewayName: "alpha", + recordedAuthorities: [openaiReceipt], + sandboxes: [{ gatewayName: "alpha", nativeHostedProviderAttachment: openaiReceipt }], + }), + ).toBeUndefined(); + }); it("rejects legacy peer Slice 1 proof without gateway authority", () => { expect( resolveGatewayNativeHostedProviderAuthority({ diff --git a/src/lib/inference/native-hosted/authority.ts b/src/lib/inference/native-hosted/authority.ts index 75e853d69f9..c2fc53c8c03 100644 --- a/src/lib/inference/native-hosted/authority.ts +++ b/src/lib/inference/native-hosted/authority.ts @@ -64,22 +64,8 @@ export function resolveGatewayNativeHostedProviderAuthority(input: { if (input.recordedGatewayName === input.gatewayName) { collect(input.recordedAttachment); } - if (input.profile.logicalProvider === "nvidia-prod") { - return normalizeNativeHostedProviderAuthorities(receipts)?.[0]; - } - if (input.recordedGatewayName === input.gatewayName) { - for (const receipt of normalizeNativeHostedProviderAuthorities(input.recordedAuthorities) ?? []) - collect(receipt); - } - for (const sandbox of input.sandboxes) { - if (sandbox.gatewayName !== input.gatewayName) continue; - collect(sandbox.nativeHostedProviderAttachment); - collect(sandbox.nativeNvidiaProviderAttachment); - collect(sandbox.nativeNvidiaProviderAuthority); - for (const receipt of normalizeNativeHostedProviderAuthorities( - sandbox.nativeHostedProviderAuthorities, - ) ?? []) - collect(receipt); - } + // Only the selected sandbox's active attachment may corroborate the gateway + // identity. Peer and retained receipts describe earlier selections, so they + // cannot establish ownership or veto a newly registered gateway provider. return normalizeNativeHostedProviderAuthorities(receipts)?.[0]; } diff --git a/src/lib/inference/native-hosted/index.test.ts b/src/lib/inference/native-hosted/index.test.ts index d204dc326c6..ef44c118e41 100644 --- a/src/lib/inference/native-hosted/index.test.ts +++ b/src/lib/inference/native-hosted/index.test.ts @@ -8,6 +8,7 @@ import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider import { parseCheckedInProviderProfileContract } from "../../adapters/openshell/provider-profile"; import { ensureNativeHostedProvider, + persistNativeHostedProviderAuthority, ensureNativeHostedProviderAttached, nativeHostedProviderProfilePath, NativeHostedProviderError, @@ -67,6 +68,107 @@ describe.each(NATIVE_HOSTED_PROFILES)("native $label OpenShell provider", (profi ); }); + it("removes a new provider when authority persistence fails (#12562)", async () => { + let providerPresent = true; + const getProvider = vi.fn(async () => + providerPresent + ? { ok: true, value: metadata() } + : { + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }, + ); + const deleteProvider = vi.fn(async () => { + providerPresent = false; + return { ok: true }; + }); + const receipt = { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + } as const; + + await expect( + persistNativeHostedProviderAuthority({ + profile, + adapter: adapter({ getProvider, deleteProvider }), + target, + gatewayName: "nemoclaw", + receipt, + readAuthority: () => undefined, + writeAuthority: () => { + throw new Error("state directory is read-only"); + }, + }), + ).rejects.toThrow(/newly created provider was removed.*state directory is read-only/su); + expect(deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target, + providerName: profile.providerName, + }); + }); + + it("keeps a provider when a failed write persisted its authority (#12562)", async () => { + const receipt = { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + } as const; + let authority: + | Parameters[0]["receipt"] + | undefined; + const deleteProvider = vi.fn(); + + await expect( + persistNativeHostedProviderAuthority({ + profile, + adapter: adapter({ deleteProvider }), + target, + gatewayName: "nemoclaw", + receipt, + readAuthority: () => authority, + writeAuthority: (_gatewayName, value) => { + authority = value; + throw new Error("directory sync failed"); + }, + }), + ).resolves.toBeUndefined(); + expect(deleteProvider).not.toHaveBeenCalled(); + }); + + it("refuses cleanup when the provider identity changed after a failed write (#12562)", async () => { + const deleteProvider = vi.fn(); + + await expect( + persistNativeHostedProviderAuthority({ + profile, + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ + revision: { id: "replacement-id", resourceVersion: 2 }, + }), + })), + deleteProvider, + }), + target, + gatewayName: "nemoclaw", + receipt: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + readAuthority: () => undefined, + writeAuthority: () => { + throw new Error("state directory is read-only"); + }, + }), + ).rejects.toThrow(/credentials reset .*.*identity changed/su); + expect(deleteProvider).not.toHaveBeenCalled(); + }); + it("refuses a receipt for another profile before mutation (#12589)", async () => { const other = NATIVE_HOSTED_PROFILES.find( (candidate) => candidate.profileId !== profile.profileId, diff --git a/src/lib/inference/native-hosted/profiles.ts b/src/lib/inference/native-hosted/profiles.ts index 330673f9597..c7aa430d477 100644 --- a/src/lib/inference/native-hosted/profiles.ts +++ b/src/lib/inference/native-hosted/profiles.ts @@ -7,6 +7,8 @@ export interface NativeHostedProfile { readonly profileId: string; readonly providerName: string; readonly endpoint: string; + // Host credentials can use a different name from the OpenShell profile binding. + readonly hostCredentialEnv?: "NOUS_API_KEY"; readonly credentialEnv: | "NVIDIA_INFERENCE_API_KEY" | "OPENAI_API_KEY" @@ -59,6 +61,7 @@ export const NATIVE_HOSTED_PROFILES: readonly NativeHostedProfile[] = [ { label: "Hermes Provider", logicalProvider: "hermes-provider", + hostCredentialEnv: "NOUS_API_KEY", profileId: "nemoclaw-hermes-inference-v1", providerName: "nemoclaw-hermes-provider-v1", endpoint: "https://inference-api.nousresearch.com/v1", diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index 4385d037119..36a0c13fed4 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -2,63 +2,22 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; -import { describe, expect, it, vi } from "vitest"; - -import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { describe, expect, it } from "vitest"; import { parseCheckedInProviderProfileContract } from "../adapters/openshell/provider-profile"; import { - NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "./native-nvidia"; - + normalizeNativeNvidiaProviderAttachment, +} from "./native-nvidia/contract"; import { - ensureNativeHostedProvider, - persistNativeHostedProviderAuthority, - ensureNativeHostedProviderAttached, nativeHostedProviderProfilePath, - NativeHostedProviderError, - verifyNativeHostedProviderAttachment, + normalizeNativeHostedProviderAttachment, } from "./native-hosted"; import { nativeHostedProfile } from "./native-hosted/profiles"; const profile = nativeHostedProfile("nvidia-prod")!; -const target = { kind: "named", gatewayName: "nemoclaw" } as const; - -function metadata(overrides: Record = {}) { - return { - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentialKeys: [NVIDIA_HOSTED_CREDENTIAL_ENV], - configKeys: [], - revision: { id: "provider-id", resourceVersion: 1 }, - ...overrides, - }; -} - -function adapter(overrides: Partial = {}): OpenShellProviderAdapter { - return { - importProviderProfile: vi.fn(() => ({ ok: true })), - getProvider: vi.fn(async () => ({ ok: true, value: metadata() })), - createProvider: vi.fn(async () => ({ ok: true })), - updateProvider: vi.fn(async () => ({ ok: true })), - listProviderAttachments: vi.fn(async () => ({ - ok: true, - value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, - })), - listProviders: vi.fn(), - inspectProviderProfile: vi.fn(), - deleteProvider: vi.fn(), - detachProvider: vi.fn(async () => ({ ok: true })), - attachProvider: vi.fn(async () => ({ ok: true })), - configureProviderRefresh: vi.fn(), - getProviderRefreshStatus: vi.fn(), - ...overrides, - } as OpenShellProviderAdapter; -} - -describe("native NVIDIA OpenShell provider", () => { +describe("native NVIDIA receipt compatibility", () => { it("ships a profile limited to the native models and chat-completions operations (#12558)", () => { const source = fs.readFileSync(nativeHostedProviderProfilePath(profile), "utf8"); const contract = parseCheckedInProviderProfileContract(source); @@ -80,401 +39,26 @@ describe("native NVIDIA OpenShell provider", () => { ); }); - it("creates the internal provider once and records its immutable identity (#12558)", async () => { - const getProvider = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }) - .mockResolvedValueOnce({ ok: true, value: metadata() }); - const createProvider = vi.fn(async () => ({ - ok: true, - })); - const providerAdapter = adapter({ getProvider, createProvider }); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: providerAdapter, - target, - credentialValue: "opaque-test-secret", - }), - ).resolves.toEqual({ - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }); - expect(createProvider).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: "opaque-test-secret" }], - config: [], - }), - ); - }); - - it("removes a new provider when authority persistence fails (#12562)", async () => { - let providerPresent = true; - const getProvider = vi.fn(async () => - providerPresent - ? { ok: true, value: metadata() } - : { - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }, - ); - const deleteProvider = vi.fn(async () => { - providerPresent = false; - return { ok: true }; - }); + it("preserves a Slice 1 receipt in both receipt readers", () => { const receipt = { schemaVersion: 1, profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - } as const; - - await expect( - persistNativeHostedProviderAuthority({ - profile, - adapter: adapter({ getProvider, deleteProvider }), - target, - gatewayName: "nemoclaw", - receipt, - readAuthority: () => undefined, - writeAuthority: () => { - throw new Error("state directory is read-only"); - }, - }), - ).rejects.toThrow(/newly created provider was removed.*state directory is read-only/su); - expect(deleteProvider).toHaveBeenCalledExactlyOnceWith({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); + providerId: "legacy-provider-id", + }; + expect(normalizeNativeNvidiaProviderAttachment(receipt)).toEqual(receipt); + expect(normalizeNativeHostedProviderAttachment(receipt)).toEqual(receipt); }); - it("keeps a provider when a failed write persisted its authority (#12562)", async () => { + it("rejects a hosted vendor receipt in the legacy NVIDIA reader", () => { + const openai = nativeHostedProfile("openai-api")!; const receipt = { schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - } as const; - let authority: - | Parameters[0]["receipt"] - | undefined; - const deleteProvider = vi.fn(); - - await expect( - persistNativeHostedProviderAuthority({ - profile, - adapter: adapter({ deleteProvider }), - target, - gatewayName: "nemoclaw", - receipt, - readAuthority: () => authority, - writeAuthority: (_gatewayName, value) => { - authority = value; - throw new Error("directory sync failed"); - }, - }), - ).resolves.toBeUndefined(); - expect(deleteProvider).not.toHaveBeenCalled(); - }); - - it("refuses cleanup when the provider identity changed after a failed write (#12562)", async () => { - const deleteProvider = vi.fn(); - - await expect( - persistNativeHostedProviderAuthority({ - profile, - adapter: adapter({ - getProvider: vi.fn(async () => ({ - ok: true, - value: metadata({ - revision: { id: "replacement-id", resourceVersion: 2 }, - }), - })), - deleteProvider, - }), - target, - gatewayName: "nemoclaw", - receipt: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - readAuthority: () => undefined, - writeAuthority: () => { - throw new Error("state directory is read-only"); - }, - }), - ).rejects.toThrow(/credentials reset nvidia-prod.*identity changed/su); - expect(deleteProvider).not.toHaveBeenCalled(); - }); - - it("observes an ambiguous create result without issuing a second mutation (#12558)", async () => { - const getProvider = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }) - .mockResolvedValueOnce({ ok: true, value: metadata() }); - const createProvider = vi.fn(async () => ({ - ok: false, - error: { kind: "timeout", message: "timed out" }, - })); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: adapter({ getProvider, createProvider }), - target, - credentialValue: "opaque-test-secret", - }), - ).resolves.toMatchObject({ providerId: "provider-id" }); - expect(createProvider).toHaveBeenCalledOnce(); - }); - - it("creates from an existing gateway credential when recreation has no local key (#12558)", async () => { - const getProvider = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }) - .mockResolvedValueOnce({ ok: true, value: metadata() }); - const createProvider = vi.fn(async () => ({ - ok: true, - })); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: adapter({ getProvider, createProvider }), - target, - credentialValue: null, - reuseExistingCredential: true, - }), - ).resolves.toMatchObject({ providerId: "provider-id" }); - expect(createProvider).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - credentials: [], - fromExisting: true, - }), - ); - }); - - it("refuses a replaced provider before rotating its credential (#12558)", async () => { - const updateProvider = vi.fn(); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: adapter({ - getProvider: vi.fn(async () => ({ - ok: true, - value: metadata({ revision: { id: "replacement-id", resourceVersion: 1 } }), - })), - updateProvider, - }), - target, - credentialValue: "opaque-test-secret", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "recorded-id", - }, - }), - ).rejects.toThrow(/changed identity.*No provider was changed/u); - expect(updateProvider).not.toHaveBeenCalled(); - }); - - it("refuses an existing provider without an ownership receipt before mutation (#12558)", async () => { - const updateProvider = vi.fn(); - const attachProvider = vi.fn(); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: adapter({ updateProvider, attachProvider }), - target, - credentialValue: "opaque-test-secret", - }), - ).rejects.toThrow(/already exists without a matching NemoClaw ownership receipt/u); - expect(updateProvider).not.toHaveBeenCalled(); - expect(attachProvider).not.toHaveBeenCalled(); - }); - - it("does not record a receipt after an ambiguous credential update (#12558)", async () => { - const getProvider = vi.fn(async () => ({ - ok: true, - value: metadata(), - })); - const updateProvider = vi.fn(async () => ({ - ok: false, - error: { kind: "timeout", message: "timed out" }, - })); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: adapter({ getProvider, updateProvider }), - target, - credentialValue: "replacement-secret", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow(/did not confirm.*credential update.*No provider receipt was recorded/u); - expect(updateProvider).toHaveBeenCalledOnce(); - expect(getProvider).toHaveBeenCalledOnce(); - }); - - it("refuses to replace a recorded provider that is missing (#12558)", async () => { - const createProvider = vi.fn(); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: adapter({ - getProvider: vi.fn(async () => ({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - })), - createProvider, - }), - target, - credentialValue: "opaque-test-secret", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "recorded-id", - }, - }), - ).rejects.toThrow(/is missing.*No provider was changed/u); - expect(createProvider).not.toHaveBeenCalled(); - }); - - it("fails before provider mutation when the profile collides (#12558)", async () => { - const createProvider = vi.fn(); - const providerAdapter = adapter({ - importProviderProfile: vi.fn(() => ({ - ok: false, - error: { - kind: "command", - reason: "profile_incompatible", - message: "different profile", - }, - })), - createProvider, - }); - - await expect( - ensureNativeHostedProvider({ - profile, - adapter: providerAdapter, - target, - credentialValue: "opaque-test-secret", - }), - ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); - expect(createProvider).not.toHaveBeenCalled(); - }); - - it("requires the exact provider attachment before native inference is published (#12558)", async () => { - const providerAdapter = adapter({ - listProviderAttachments: vi.fn( - async () => ({ ok: true, value: { names: [] } }), - ), - }); - - await expect( - verifyNativeHostedProviderAttachment({ - profile, - adapter: providerAdapter, - target, - sandboxName: "alpha", - }), - ).rejects.toThrow(NativeHostedProviderError); - await expect( - verifyNativeHostedProviderAttachment({ - profile, - adapter: providerAdapter, - target, - sandboxName: "alpha", - }), - ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); - }); - - it("removes a newly attached provider when attachment verification fails (#12558)", async () => { - const listProviderAttachments = vi - .fn() - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ ok: true, value: { names: [] } }); - const detachProvider = vi.fn(async () => ({ - ok: true, - value: { changed: true }, - })); - const providerAdapter = adapter({ listProviderAttachments, detachProvider }); - - await expect( - ensureNativeHostedProviderAttached({ - profile, - adapter: providerAdapter, - target, - sandboxName: "alpha", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); - expect(detachProvider).toHaveBeenCalledExactlyOnceWith({ - target, - sandboxName: "alpha", - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - }); - - it("preserves verification and cleanup failures after a new attachment (#12558)", async () => { - const listProviderAttachments = vi - .fn() - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ - ok: true, - value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, - }); - - await expect( - ensureNativeHostedProviderAttached({ - profile, - adapter: adapter({ listProviderAttachments }), - target, - sandboxName: "alpha", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow( - /does not have its native NVIDIA inference provider attached[\s\S]*did not confirm removal/u, - ); + profileId: openai.profileId, + providerName: openai.providerName, + providerId: "openai-id", + }; + expect(normalizeNativeNvidiaProviderAttachment(receipt)).toBeUndefined(); + expect(normalizeNativeHostedProviderAttachment(receipt)).toEqual(receipt); }); }); diff --git a/src/lib/inference/native-nvidia/contract.ts b/src/lib/inference/native-nvidia/contract.ts index 62822577f66..4059292656f 100644 --- a/src/lib/inference/native-nvidia/contract.ts +++ b/src/lib/inference/native-nvidia/contract.ts @@ -35,3 +35,7 @@ export function normalizeNativeNvidiaProviderAttachment( providerId: receipt.providerId, }; } + +export function isNativeNvidiaProvider(provider: string | null | undefined): boolean { + return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; +} diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts deleted file mode 100644 index 0c34e0421a2..00000000000 --- a/src/lib/inference/native-nvidia/index.ts +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { NVIDIA_HOSTED_LOGICAL_PROVIDER, type NativeNvidiaProviderAttachment } from "./contract"; - -export { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - normalizeNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "./contract"; - -export class NativeNvidiaProviderError extends Error { - constructor(message: string) { - super(message); - this.name = "NativeNvidiaProviderError"; - } -} - -export function isNativeNvidiaProvider(provider: string | null | undefined): boolean { - return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; -} - -export function resolveGatewayNativeNvidiaProviderAuthority(input: { - gatewayName: string; - gatewayAuthority?: NativeNvidiaProviderAttachment | null; - recordedAttachment?: NativeNvidiaProviderAttachment | null; -}): NativeNvidiaProviderAttachment | undefined { - const authorities = new Map(); - for (const receipt of [input.gatewayAuthority, input.recordedAttachment]) { - if (receipt) authorities.set(receipt.providerId, receipt); - } - if (authorities.size > 1) { - throw new NativeNvidiaProviderError( - `Gateway '${input.gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, - ); - } - return authorities.values().next().value; -} diff --git a/src/lib/state/registry/native-nvidia-provider-authority-state.ts b/src/lib/state/registry/native-nvidia-provider-authority-state.ts index 97facd2d1a9..b910bb7fc53 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority-state.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority-state.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia/contract"; import { normalizeNativeHostedProviderAuthorities, retainNativeHostedProviderAuthority, diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index 7a6c285b453..36c3be33977 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -14,7 +14,7 @@ import { isValidNativeProviderGateway as isValidName } from "./native-nvidia-pro import { normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import type { SandboxRegistry } from "./types"; import { withLock } from "./lock"; import { load, save } from "./persistence"; diff --git a/test/e2e/README.md b/test/e2e/README.md index 21db761006c..7a5f55e9258 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1075,8 +1075,15 @@ Trusted workflow qualification uses an explicitly selected target and a nonempty `targets` input. Each selection runs on Docker and receives only its declared provider credential. These targets are excluded from the default suite. The trusted workflow revision must contain this selection and credential transport -before it can dispatch a candidate PR; candidate code cannot authorize its own -credential access. Approved credential provisioning and a canonical supported +before it can dispatch a candidate PR. Dispatch from `main`; arbitrary branch +dispatches are rejected, including an empty candidate checkout. PR selections +use the existing current-head/exact-base identity authorization. Before dispatch, +review the complete selected candidate diff: candidate test and CLI code can +read and use the selected provider key. This follows the existing manual PR E2E +trust contract, not a credential-isolated execution boundary. Record the candidate +and workflow SHAs and selected credential source; after failure inspect artifacts, +clean up retained resources, and rotate or revoke exposed credentials when necessary. +The workflow does not revoke provider keys. Approved credential provisioning and a canonical supported model remain prerequisites. The existing manifest binds the candidate revision, selected target, and switch artifacts to the workflow result. diff --git a/test/e2e/support/fixed-hosted-qualification.test.ts b/test/e2e/support/fixed-hosted-qualification.test.ts index aadf31f48dd..f191b804e1f 100644 --- a/test/e2e/support/fixed-hosted-qualification.test.ts +++ b/test/e2e/support/fixed-hosted-qualification.test.ts @@ -1,13 +1,17 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { runInNewContext } from "node:vm"; import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; -import { validateStandardProfileWorkflowBoundary } from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; +import { + FIXED_HOSTED_CREDENTIAL_PREDICATE, + validateStandardProfileWorkflowBoundary, +} from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; import { FIXED_HOSTED_PLAN_SCRIPT, FIXED_HOSTED_RUN_SCRIPT, @@ -20,7 +24,10 @@ import { } from "../../../tools/e2e/workflow-plan.mts"; import { catalogueTargetsForChangedFiles } from "../../../tools/e2e/target-catalogue.mts"; -const explicit = { hostedModel: "approved/model", eventName: "workflow_dispatch" }; +const explicit = { + hostedModel: "approved/model", + eventName: "workflow_dispatch", +}; describe("fixed hosted qualification planning", () => { it.each(FIXED_HOSTED_QUALIFICATIONS)( @@ -72,6 +79,52 @@ describe("fixed hosted qualification planning", () => { ).toThrow(/model/); }); + it.each([ + ["direct main", "refs/heads/main", "", "false", "workflow_dispatch", true], + ["validated PR", "refs/heads/main", "candidate", "true", "workflow_dispatch", true], + ["arbitrary branch", "refs/heads/feature", "", "false", "workflow_dispatch", false], + [ + "branch with authorized PR", + "refs/heads/feature", + "candidate", + "true", + "workflow_dispatch", + false, + ], + ["unvalidated PR", "refs/heads/main", "candidate", "false", "workflow_dispatch", false], + ["automatic event", "refs/heads/main", "", "false", "push", false], + ])( + "guards fixed hosted credential delivery: %s", + (_label, ref, checkout, allowed, event, expected) => { + expect( + runInNewContext( + FIXED_HOSTED_CREDENTIAL_PREDICATE.replaceAll( + "needs.generate-matrix", + 'needs["generate-matrix"]', + ), + { + github: { repository: "NVIDIA/NemoClaw", ref, event_name: event }, + inputs: { checkout_sha: checkout }, + needs: { + "generate-matrix": { + outputs: { e2e_credentials_allowed: allowed }, + }, + }, + }, + ), + ).toBe(expected); + }, + ); + + it("rejects removing the fixed hosted trusted-main job gate", () => { + const workflow = readWorkflow(); + (workflow.jobs as Record)["catalogue-fixed-hosted"]!.if = + "${{ needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix != '[]' }}"; + expect(validateStandardProfileWorkflowBoundary(workflow)).toContain( + "catalogue-fixed-hosted must use its generated catalogue matrix", + ); + }); + it("rejects credential crossover in the trusted caller", () => { const workflow = readWorkflow(); (workflow.jobs as Record }>)[ @@ -156,10 +209,16 @@ ${FIXED_HOSTED_RUN_SCRIPT} it.each([ { scenario: "target mismatch", override: { TARGET_ID: "hermes-e2e" } }, - { scenario: "test file mismatch", override: { TEST_FILE: "test/e2e/live/hermes-e2e.test.ts" } }, + { + scenario: "test file mismatch", + override: { TEST_FILE: "test/e2e/live/hermes-e2e.test.ts" }, + }, { scenario: "shard mismatch", override: { SHARD: "nvidia-prod" } }, { scenario: "missing model", override: { HOSTED_MODEL: "" } }, - { scenario: "unsafe model", override: { HOSTED_MODEL: "model\nATTACKER=value" } }, + { + scenario: "unsafe model", + override: { HOSTED_MODEL: "model\nATTACKER=value" }, + }, { scenario: "unknown target", override: { CATALOGUE_ID: "unknown" } }, ])("refuses invalid qualification metadata [$scenario]", ({ override }) => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "fixed-hosted-denial-")); diff --git a/test/e2e/support/native-nvidia-target-ownership.test.ts b/test/e2e/support/native-nvidia-target-ownership.test.ts index 55f6d8a5a4c..a778d7fd8ca 100644 --- a/test/e2e/support/native-nvidia-target-ownership.test.ts +++ b/test/e2e/support/native-nvidia-target-ownership.test.ts @@ -8,7 +8,7 @@ import { catalogueTargetsForChangedFiles } from "../../../tools/e2e/target-catal describe("native NVIDIA target ownership", () => { it.each([ "src/lib/actions/inference-set.ts", - "src/lib/inference/native-nvidia/index.ts", + "src/lib/inference/native-nvidia/contract.ts", "src/lib/inference/native-hosted/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "test/e2e/live/public-nvidia-switch-provider.ts", diff --git a/tools/e2e/standard-profile-workflow-boundary.mts b/tools/e2e/standard-profile-workflow-boundary.mts index 78ddcac3d48..dccaba38086 100644 --- a/tools/e2e/standard-profile-workflow-boundary.mts +++ b/tools/e2e/standard-profile-workflow-boundary.mts @@ -38,8 +38,10 @@ const TRUSTED_CALLER_CREDENTIAL_PREDICATE = "github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true')"; const guardedCallerSecret = (name: string): string => `\${{ ${TRUSTED_CALLER_CREDENTIAL_PREDICATE} && secrets.${name} || '' }}`; +export const FIXED_HOSTED_CREDENTIAL_PREDICATE = + "github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true')"; const FIXED_HOSTED_CALLER_SECRET = - "${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }}"; + "${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }}"; const SKILL_AGENT_UPLOAD_PATH = `${[ "e2e-artifacts/live/skill-agent/evidence-manifest.json", "e2e-artifacts/live/skill-agent/*/artifact-summary.json", @@ -166,7 +168,8 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi } const matrixOutput = `needs.generate-matrix.outputs.${contract.matrix}`; if ( - job.if !== `\${{ ${matrixOutput} != '[]' }}` || + job.if !== + `\${{ ${matrixOutput} != '[]'${profile === "fixed-hosted" ? ` && ${FIXED_HOSTED_CREDENTIAL_PREDICATE}` : ""} }}` || record(record(job.strategy).matrix).include !== `\${{ fromJSON(${matrixOutput}) }}` ) { errors.push(`${contract.job} must use its generated catalogue matrix`); @@ -216,7 +219,9 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi shard: "${{ matrix.shard }}", artifact_layout: "${{ matrix.artifact_layout }}", trusted_main: - "${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/main') && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }}", + profile === "fixed-hosted" + ? `\${{ ${FIXED_HOSTED_CREDENTIAL_PREDICATE} }}` + : "${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/main') && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }}", })) { if (withInputs[name] !== expected) { errors.push(`${contract.job} must pass ${name} from the catalogue matrix`); @@ -232,7 +237,9 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi callerSecrets[name] !== (name === "HOSTED_PROVIDER_API_KEY" ? FIXED_HOSTED_CALLER_SECRET - : guardedCallerSecret(name)), + : profile === "fixed-hosted" + ? `\${{ ${FIXED_HOSTED_CREDENTIAL_PREDICATE} && secrets.${name} || '' }}` + : guardedCallerSecret(name)), ) ) { errors.push(`${contract.job} must receive only its profile secrets`); diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index 0aebc3b184c..df9c960e9af 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -914,7 +914,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ owningPaths: [ "src/lib/inference/native-hosted/index.ts", "src/lib/actions/inference-set.ts", - "src/lib/inference/native-nvidia/index.ts", + "src/lib/inference/native-nvidia/contract.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "test/e2e/live/public-nvidia-switch-provider.ts", ], @@ -1199,7 +1199,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ exposeCliBin: true, owningPaths: [ "src/lib/inference/native-hosted/index.ts", - "src/lib/inference/native-nvidia/index.ts", + "src/lib/inference/native-nvidia/contract.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "src/lib/actions/inference-set.ts", "src/lib/onboard.ts", From d8304bdd2875d95e81fe681d07e3d8abbb2d6ff3 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 08:12:17 -0700 Subject: [PATCH 088/133] fix(pi): refresh native hosted qualification receipts Signed-off-by: Deepak Jain --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index 5b62a1a2d27..9cbb7f8f79c 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:5ee57b78678be22082a1cd20a193606300c3531e7418097824efb26215955da1", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:5ee57b78678be22082a1cd20a193606300c3531e7418097824efb26215955da1", + "digest": "sha256:87d9b55b0da963463ebcaab1e21e8cc8283d651170ab6153c4a208257d7eb7dd", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:87d9b55b0da963463ebcaab1e21e8cc8283d651170ab6153c4a208257d7eb7dd", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "e65d5bf0a0a07761c43ec8f7f55cea99044d15c8", + "revision": "e29a2c32f2c7b9d1bcbd7718fe349db040d70dbb", "release": "v0.1.0", - "cohort": "ghrun-37522090169-1" + "cohort": "ghrun-37640333995-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index f2c8d4331ce..436f26b28a7 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:440810c2a95cd87cf5670b45198dede4d11c9db28198ec892361a5e16dd4ee23", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:440810c2a95cd87cf5670b45198dede4d11c9db28198ec892361a5e16dd4ee23", + "digest": "sha256:2fd15236de9bd3817a77fdfe61d6546def6f4ca113c9a01680a9751c827f7937", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:2fd15236de9bd3817a77fdfe61d6546def6f4ca113c9a01680a9751c827f7937", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "e65d5bf0a0a07761c43ec8f7f55cea99044d15c8", + "revision": "e29a2c32f2c7b9d1bcbd7718fe349db040d70dbb", "release": "v0.1.0", - "cohort": "ghrun-37522090169-1" + "cohort": "ghrun-37640333995-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 1bf7134a0a2..86f8398d63f 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "594a78eb349498fb66b0141f9a2b2b565183b935869820aa2e406c6ca4de7ad7", - "5f7cb0156e3b2ce138999323fd29908fb77098935717d54ecaa114b2edeb3e0e", + "d7993a7c1b9d192bef0c2857c2ace529b2ee0ee2be7687c8184fbb1c68bcf377", + "c9994060adc0e34583c9eb273aace6ffb2d04b9904614fb1568dfcab85fb033d", ]), }); From 110347102d915ca3334be30e4da6018c3ed2d2f9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:18:56 -0700 Subject: [PATCH 089/133] fix(inference): preserve native provider ownership Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../recover-rebuild-sandboxes.mdx | 6 +- .../actions/credentials-native-reset.test.ts | 102 ++++++++++++++++ .../credentials-provider-adapter.test.ts | 20 ++- src/lib/actions/credentials/reset.ts | 115 +++++++++++++----- src/lib/inference/native-nvidia.test.ts | 71 +++++++++++ src/lib/inference/native-nvidia/index.ts | 34 ++++-- ...egistry-native-provider-attachment.test.ts | 27 ++++ .../native-nvidia-provider-authority.ts | 7 ++ 8 files changed, 335 insertions(+), 47 deletions(-) create mode 100644 src/lib/actions/credentials-native-reset.test.ts diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 5f4cbb1ac14..35281f963ce 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -190,9 +190,9 @@ During the lease, `launch` still verifies the owning OpenShell gateway, exact li Every configured route must serve a valid response to a bounded request for the recorded model before NemoClaw accepts or publishes launch readiness. Shared-route providers use `inference.local`. -NVIDIA Endpoints uses its sandbox-attached provider at `integrate.api.nvidia.com`. -The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. -A failed model request rejects launch readiness. +Their models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. +NVIDIA Endpoints verifies its sandbox-attached provider at `integrate.api.nvidia.com` and runs the bounded model request without the shared-route models probe. +A failed required probe or model request rejects launch readiness. This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts new file mode 100644 index 00000000000..c2d360c84c2 --- /dev/null +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { setGlobalCliActionRuntimeHooksForTest } from "./global"; +import { runCredentialsResetAction } from "./credentials/reset"; + +vi.mock("../onboard/gateway-teardown-authority", () => ({ + resolveGatewayCredentialMutationAuthority: vi.fn(() => ({})), +})); + +function adapter( + deleteProvider: OpenShellProviderAdapter["deleteProvider"], +): OpenShellProviderAdapter { + return { deleteProvider: vi.fn(deleteProvider) } as unknown as OpenShellProviderAdapter; +} + +describe("native NVIDIA credential reset ownership", () => { + beforeEach(() => { + setGlobalCliActionRuntimeHooksForTest({ + recoverNamedGatewayRuntime: async () => ({ recovered: true }), + forgetExtraProvider: () => true, + }); + }); + + afterEach(() => setGlobalCliActionRuntimeHooksForTest({})); + + it.each([ + ["present", { ok: true as const }], + [ + "absent", + { + ok: false as const, + error: { + kind: "command" as const, + reason: "not_found" as const, + message: "provider not found", + }, + }, + ], + ])( + "blocks reset when a recorded sandbox remains and the provider is %s (#12562)", + async (_providerState, deleteResult) => { + const operations: string[] = []; + const deleteProvider = vi.fn(async () => { + operations.push("delete"); + return deleteResult; + }); + const clearNativeNvidiaProviderAuthority = vi.fn(() => operations.push("clear-authority")); + + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames: () => ["alpha"], + withGatewayRouteMutationLock: async (_gatewayName, operation) => { + operations.push("lock"); + return operation(); + }, + }, + ); + + expect(result.exitCode).toBe(1); + expect(operations).toEqual(["lock"]); + expect(deleteProvider).not.toHaveBeenCalled(); + expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(result.failureLines).toContain(" 'nvidia-prod' is recorded by sandbox(es): alpha."); + expect(result.failureLines).toContain(" No provider or ownership authority was changed."); + expect(result.failureLines).toContain(" nemoclaw alpha destroy"); + }, + ); + + it("fails closed before reset when registry ownership cannot be read", async () => { + const deleteProvider = vi.fn(); + const clearNativeNvidiaProviderAuthority = vi.fn(); + + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames: () => { + throw new Error("opaque registry failure"); + }, + withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), + }, + ); + + expect(result.exitCode).toBe(1); + expect(deleteProvider).not.toHaveBeenCalled(); + expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(result.failureLines).toEqual([ + " Could not safely inspect native NVIDIA inference ownership on gateway 'nemoclaw'.", + " No provider or ownership authority was changed.", + " Repair the existing NemoClaw state and retry.", + ]); + expect(JSON.stringify(result)).not.toContain("opaque registry failure"); + }); +}); diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 6162d9e999a..5492b5b01f8 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -1002,7 +1002,11 @@ describe("credential actions use typed OpenShell provider results", () => { const result = await runCredentialsResetAction( { provider, confirmed: true }, - { providerAdapter: adapter }, + { + providerAdapter: adapter, + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), + }, ); expect(result.exitCode).toBe(1); @@ -1031,7 +1035,12 @@ describe("credential actions use typed OpenShell provider results", () => { const result = await runCredentialsResetAction( { provider: "nvidia-prod", confirmed: true }, - { providerAdapter: adapter, clearNativeNvidiaProviderAuthority }, + { + providerAdapter: adapter, + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), + }, ); expect(result.exitCode).toBe(0); @@ -1053,7 +1062,12 @@ describe("credential actions use typed OpenShell provider results", () => { const result = await runCredentialsResetAction( { provider: "nvidia-prod", confirmed: true }, - { providerAdapter: adapter, clearNativeNvidiaProviderAuthority }, + { + providerAdapter: adapter, + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), + }, ); expect(result.exitCode).toBe(0); diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 0f7b4aaa0cb..e42565b6f06 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -24,7 +24,11 @@ import { recoverCredentialGatewayTargetOrExit, } from "../../credentials/command-support"; import { prompt as askPrompt, KNOWN_CREDENTIAL_ENV_KEYS } from "../../credentials/store"; -import { clearNativeNvidiaProviderAuthority } from "../../state/registry/native-nvidia-provider-authority"; +import { withGatewayRouteMutationLock } from "../../inference/gateway-route-mutation-lock"; +import { + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames, +} from "../../state/registry/native-nvidia-provider-authority"; import { forgetExtraProvider } from "../global"; export type CredentialsResetInput = { @@ -41,6 +45,8 @@ export type CredentialsResetResult = { export type CredentialsResetDeps = Readonly<{ providerAdapter?: OpenShellProviderAdapter; clearNativeNvidiaProviderAuthority?: typeof clearNativeNvidiaProviderAuthority; + listNativeNvidiaProviderAttachmentSandboxNames?: typeof listNativeNvidiaProviderAttachmentSandboxNames; + withGatewayRouteMutationLock?: typeof withGatewayRouteMutationLock; }>; export type CredentialsProviderDeleteWithRecoveryResult = Readonly<{ @@ -92,6 +98,35 @@ function detachedSandboxGuidance(key: string, sandboxes: readonly string[]): str ]; } +function nativeNvidiaResetBlockers( + deps: CredentialsResetDeps, +): { ok: true; sandboxes: readonly string[] } | { ok: false } { + try { + return { + ok: true, + sandboxes: ( + deps.listNativeNvidiaProviderAttachmentSandboxNames ?? + listNativeNvidiaProviderAttachmentSandboxNames + )(), + }; + } catch { + return { ok: false }; + } +} + +function nativeNvidiaResetBlockedResult(sandboxes: readonly string[]): CredentialsResetResult { + return fail([ + ` Could not remove provider '${NVIDIA_HOSTED_LOGICAL_PROVIDER}'.`, + "", + ` '${NVIDIA_HOSTED_LOGICAL_PROVIDER}' is recorded by sandbox(es): ${sandboxes.join(", ")}.`, + " No provider or ownership authority was changed.", + ` To rotate the credential in place, set ${NVIDIA_HOSTED_CREDENTIAL_ENV} and rerun '${CLI_NAME} onboard --name '.`, + " To remove the provider completely, preserve any required sandbox state, destroy every recorded sandbox,", + ` then rerun '${CLI_NAME} credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER}'.`, + ...sandboxes.map((sandbox) => ` ${CLI_NAME} ${sandbox} destroy`), + ]); +} + export async function runCredentialsResetAction( input: CredentialsResetInput, deps: CredentialsResetDeps = {}, @@ -131,41 +166,63 @@ export async function runCredentialsResetAction( if (!target) return fail(recoveryFailureLines); const providerAdapter = deps.providerAdapter ?? createCliOpenShellProviderAdapter(); - const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter, { - detachAttached: !nativeNvidiaProvider, - }); + const resetProvider = async (): Promise => { + if (nativeNvidiaProvider) { + const blockers = nativeNvidiaResetBlockers(deps); + if (!blockers.ok) { + return fail([ + ` Could not safely inspect native NVIDIA inference ownership on gateway '${target.gatewayName}'.`, + " No provider or ownership authority was changed.", + " Repair the existing NemoClaw state and retry.", + ]); + } + if (blockers.sandboxes.length > 0) { + return nativeNvidiaResetBlockedResult(blockers.sandboxes); + } + } - if ( - !recovery.ok && - !KNOWN_CREDENTIAL_ENV_KEY_SET.has(key) && - recovery.error?.kind === "command" && - recovery.error.reason === "not_found" - ) { + const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter, { + detachAttached: !nativeNvidiaProvider, + }); + + if ( + !recovery.ok && + !KNOWN_CREDENTIAL_ENV_KEY_SET.has(key) && + recovery.error?.kind === "command" && + recovery.error.reason === "not_found" + ) { + if (nativeNvidiaProvider) { + (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( + target.gatewayName, + ); + } + const removedLocal = forgetExtraProvider(key); + return ok([ + removedLocal + ? ` Provider '${key}' is already absent from the OpenShell gateway. Local state was cleaned up.` + : ` Provider '${key}' is already absent from the OpenShell gateway.`, + ` Rerun '${CLI_NAME} onboard' to enter a new value.`, + ...detachedSandboxGuidance(key, recovery.detachedSandboxes), + ]); + } + + const outcome = formatResetOutcome(publicKey, recovery, target.gatewayName); + if (!outcome.ok) return fail(outcome.lines); + + forgetExtraProvider(publicKey); if (nativeNvidiaProvider) { (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( target.gatewayName, ); } - const removedLocal = forgetExtraProvider(key); - return ok([ - removedLocal - ? ` Provider '${key}' is already absent from the OpenShell gateway. Local state was cleaned up.` - : ` Provider '${key}' is already absent from the OpenShell gateway.`, - ` Rerun '${CLI_NAME} onboard' to enter a new value.`, - ...detachedSandboxGuidance(key, recovery.detachedSandboxes), - ]); - } + return ok(outcome.lines); + }; - const outcome = formatResetOutcome(publicKey, recovery, target.gatewayName); - if (!outcome.ok) return fail(outcome.lines); - - forgetExtraProvider(publicKey); - if (nativeNvidiaProvider) { - (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( - target.gatewayName, - ); - } - return ok(outcome.lines); + if (!nativeNvidiaProvider) return resetProvider(); + return (deps.withGatewayRouteMutationLock ?? withGatewayRouteMutationLock)( + target.gatewayName, + resetProvider, + ); } /** Build the user-facing result after a provider delete attempt. */ diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index 8a0a2865928..d6d868c3dea 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -397,6 +397,77 @@ describe("native NVIDIA OpenShell provider", () => { ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); }); + it("rejects a matching attachment when the live provider profile exceeds the checked-in boundary (#12562)", async () => { + const getProvider = vi.fn(async () => ({ + ok: true, + value: metadata(), + })); + const listProviderAttachments = vi.fn( + async () => ({ + ok: true, + value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, + }), + ); + const providerAdapter = adapter({ + importProviderProfile: vi.fn(() => ({ + ok: false, + error: { + kind: "command", + reason: "profile_incompatible", + message: "live endpoint rules are wider than the checked-in profile", + }, + })), + getProvider, + listProviderAttachments, + }); + + await expect( + verifyNativeNvidiaProviderAttachment({ + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); + expect(getProvider).not.toHaveBeenCalled(); + expect(listProviderAttachments).not.toHaveBeenCalled(); + }); + + it("refuses to attach through a live provider profile that exceeds the checked-in boundary (#12562)", async () => { + const attachProvider = vi.fn(); + const providerAdapter = adapter({ + importProviderProfile: vi.fn(() => ({ + ok: false, + error: { + kind: "command", + reason: "profile_incompatible", + message: "live endpoint rules are wider than the checked-in profile", + }, + })), + attachProvider, + }); + + await expect( + ensureNativeNvidiaProviderAttached({ + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); + expect(attachProvider).not.toHaveBeenCalled(); + }); + it("removes a newly attached provider when attachment verification fails (#12558)", async () => { const listProviderAttachments = vi .fn() diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index 88b94bdaa55..a27ad5322f0 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -76,6 +76,22 @@ function providerErrorDetail(error: OpenShellProviderError): string { return error.message.trim() || "OpenShell did not provide a diagnostic."; } +async function requireNativeNvidiaProviderProfileBoundary( + adapter: OpenShellProviderAdapter, + target: OpenShellGatewayTarget, + profilePath = nativeNvidiaProviderProfilePath(), +): Promise { + const imported = await adapter.importProviderProfile({ target, profilePath }); + if (imported.ok) return; + const collision = + imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; + throw new NativeNvidiaProviderError( + collision + ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` + : `Could not verify OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, + ); +} + function exactNativeProvider(metadata: OpenShellProviderMetadata): boolean { return ( metadata.name === NVIDIA_HOSTED_NATIVE_PROVIDER && @@ -223,19 +239,11 @@ export async function ensureNativeNvidiaProvider(input: { profilePath?: string; }): Promise { const { adapter, target } = input; - const imported = await adapter.importProviderProfile({ + await requireNativeNvidiaProviderProfileBoundary( + adapter, target, - profilePath: input.profilePath ?? nativeNvidiaProviderProfilePath(), - }); - if (!imported.ok) { - const collision = - imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; - throw new NativeNvidiaProviderError( - collision - ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` - : `Could not prepare OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, - ); - } + input.profilePath ?? nativeNvidiaProviderProfilePath(), + ); const before = await inspectNativeProvider(adapter, target); if (before) { @@ -324,6 +332,7 @@ export async function verifyNativeNvidiaProviderAttachment(input: { sandboxName: string; expected?: NativeNvidiaProviderAttachment; }): Promise { + await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); const provider = await inspectNativeProvider(input.adapter, input.target); if (!provider) { throw new NativeNvidiaProviderError( @@ -360,6 +369,7 @@ export async function ensureNativeNvidiaProviderAttached(input: { sandboxName: string; expected: NativeNvidiaProviderAttachment; }): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { + await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); const provider = await inspectNativeProvider(input.adapter, input.target); if (!provider) { throw new NativeNvidiaProviderError( diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index 80f9b5e9610..b3a607979ea 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -78,3 +78,30 @@ it("clears a stale native NVIDIA attachment when reserving a shared route", asyn vi.unstubAllEnvs(); } }); + +it("lists registered sandboxes that retain native NVIDIA provider ownership", async () => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-native-attachment-list-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + const authority = await import("./registry/native-nvidia-provider-authority"); + registry.registerSandbox({ + name: "alpha", + provider: "nvidia-prod", + model: "model-a", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }, + }); + registry.registerSandbox({ name: "beta", provider: "openai", model: "model-b" }); + + expect(authority.listNativeNvidiaProviderAttachmentSandboxNames()).toEqual(["alpha"]); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } +}); diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index 68599dfec2c..300bf56eb58 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -38,3 +38,10 @@ export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { save(data); }); } + +export function listNativeNvidiaProviderAttachmentSandboxNames(): readonly string[] { + return Object.values(load().sandboxes) + .filter((sandbox) => sandbox.nativeNvidiaProviderAttachment !== undefined) + .map((sandbox) => sandbox.name) + .sort(); +} From 26a65185e32e332c97208f5f548064c4f262f2ad Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:39:16 -0700 Subject: [PATCH 090/133] test(inference): refresh exact Pi candidate evidence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- .../sandbox-create/orchestration-native-nvidia.test.ts | 1 + 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index cd9e6b7bcd6..becc99ae4fc 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:6e4b97ebf390aaae3e350fda1bb4e8cf3b7ccb918376f2bd431884af5800a9cc", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:6e4b97ebf390aaae3e350fda1bb4e8cf3b7ccb918376f2bd431884af5800a9cc", + "digest": "sha256:319d45feee24bd7727b05c5c837ff5c9a651192d4be299ad362feeb7e780ed22", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:319d45feee24bd7727b05c5c837ff5c9a651192d4be299ad362feeb7e780ed22", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "fd70900cedb01b9ced93626f190002581a0aa356", + "revision": "11ae5b4b21f68300ed1decd7985e3ee860731e87", "release": "v0.1.0", - "cohort": "ghrun-37515304733-1" + "cohort": "ghrun-37643621249-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 24533c750f3..a7f3835b567 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:568792426862e7264e0ea23d1708373e8c8885cf66f7c50000bbf433f1c9f277", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:568792426862e7264e0ea23d1708373e8c8885cf66f7c50000bbf433f1c9f277", + "digest": "sha256:428104608270ad73845f5d6f8baa2c70a2349cf0dc367da9c45b4baf6834e96a", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:428104608270ad73845f5d6f8baa2c70a2349cf0dc367da9c45b4baf6834e96a", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "fd70900cedb01b9ced93626f190002581a0aa356", + "revision": "11ae5b4b21f68300ed1decd7985e3ee860731e87", "release": "v0.1.0", - "cohort": "ghrun-37515304733-1" + "cohort": "ghrun-37643621249-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 540e421fc89..4db9851eeba 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "127792f62117e69dd8f5c05ba4fb2e5b8f5a087905c2c777db1ee64ac29b845c", - "9b9fdace49624f4e36d9e7b1c4ec4b775fe260d85388c038b28127f4a5aa9bf2", + "4b2299a7aa863527e30b383446090deeb11994d89b7026497b19a9967836e439", + "a0db5ddb457d426c2677f47d0873a8f34cd5f9a08a8b3751443511a1c77aa16c", ]), }); diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index 5081c0bbf6d..d33208f7c6a 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -10,6 +10,7 @@ const recordedProviderId = "11111111-2222-4333-8444-555555555555"; function providerAdapter(providerId: string): OpenShellProviderAdapter { return { + importProviderProfile: vi.fn(() => ({ ok: true })), getProvider: vi.fn(async () => ({ ok: true, value: { From 4555909b23cf57db374b8e10801473ea0b375b9c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:12:32 -0700 Subject: [PATCH 091/133] fix(credentials): scope native reset blockers to gateway Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../actions/credentials-native-reset.test.ts | 35 ++++++++++++++++++- src/lib/actions/credentials/reset.ts | 5 +-- ...egistry-native-provider-attachment.test.ts | 19 ++++++++-- .../native-nvidia-provider-authority.ts | 9 +++-- 4 files changed, 61 insertions(+), 7 deletions(-) diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index c2d360c84c2..37c9a814ba3 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -49,13 +49,16 @@ describe("native NVIDIA credential reset ownership", () => { return deleteResult; }); const clearNativeNvidiaProviderAuthority = vi.fn(() => operations.push("clear-authority")); + const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName: string) => + gatewayName === "nemoclaw" ? ["alpha"] : [], + ); const result = await runCredentialsResetAction( { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), clearNativeNvidiaProviderAuthority, - listNativeNvidiaProviderAttachmentSandboxNames: () => ["alpha"], + listNativeNvidiaProviderAttachmentSandboxNames, withGatewayRouteMutationLock: async (_gatewayName, operation) => { operations.push("lock"); return operation(); @@ -65,6 +68,9 @@ describe("native NVIDIA credential reset ownership", () => { expect(result.exitCode).toBe(1); expect(operations).toEqual(["lock"]); + expect(listNativeNvidiaProviderAttachmentSandboxNames).toHaveBeenCalledExactlyOnceWith( + "nemoclaw", + ); expect(deleteProvider).not.toHaveBeenCalled(); expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines).toContain(" 'nvidia-prod' is recorded by sandbox(es): alpha."); @@ -73,6 +79,33 @@ describe("native NVIDIA credential reset ownership", () => { }, ); + it("does not let another gateway's attachment block the selected gateway reset", async () => { + const deleteProvider = vi.fn(async () => ({ + ok: true, + })); + const clearNativeNvidiaProviderAuthority = vi.fn(); + const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName: string) => + gatewayName === "other-gateway" ? ["beta"] : [], + ); + + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames, + withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), + }, + ); + + expect(result.exitCode).toBe(0); + expect(listNativeNvidiaProviderAttachmentSandboxNames).toHaveBeenCalledExactlyOnceWith( + "nemoclaw", + ); + expect(deleteProvider).toHaveBeenCalledOnce(); + expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledExactlyOnceWith("nemoclaw"); + }); + it("fails closed before reset when registry ownership cannot be read", async () => { const deleteProvider = vi.fn(); const clearNativeNvidiaProviderAuthority = vi.fn(); diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index e42565b6f06..44b88d161b1 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -100,6 +100,7 @@ function detachedSandboxGuidance(key: string, sandboxes: readonly string[]): str function nativeNvidiaResetBlockers( deps: CredentialsResetDeps, + gatewayName: string, ): { ok: true; sandboxes: readonly string[] } | { ok: false } { try { return { @@ -107,7 +108,7 @@ function nativeNvidiaResetBlockers( sandboxes: ( deps.listNativeNvidiaProviderAttachmentSandboxNames ?? listNativeNvidiaProviderAttachmentSandboxNames - )(), + )(gatewayName), }; } catch { return { ok: false }; @@ -168,7 +169,7 @@ export async function runCredentialsResetAction( const providerAdapter = deps.providerAdapter ?? createCliOpenShellProviderAdapter(); const resetProvider = async (): Promise => { if (nativeNvidiaProvider) { - const blockers = nativeNvidiaResetBlockers(deps); + const blockers = nativeNvidiaResetBlockers(deps, target.gatewayName); if (!blockers.ok) { return fail([ ` Could not safely inspect native NVIDIA inference ownership on gateway '${target.gatewayName}'.`, diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index b3a607979ea..a6f6f43b45f 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -96,10 +96,25 @@ it("lists registered sandboxes that retain native NVIDIA provider ownership", as providerName: "nemoclaw-nvidia-prod-v1", providerId: "provider-id", }, + gatewayName: "nemoclaw", + }); + registry.registerSandbox({ + name: "beta", + provider: "nvidia-prod", + model: "model-b", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-id", + }, + gatewayName: "other-gateway", }); - registry.registerSandbox({ name: "beta", provider: "openai", model: "model-b" }); - expect(authority.listNativeNvidiaProviderAttachmentSandboxNames()).toEqual(["alpha"]); + expect(authority.listNativeNvidiaProviderAttachmentSandboxNames("nemoclaw")).toEqual(["alpha"]); + expect(authority.listNativeNvidiaProviderAttachmentSandboxNames("other-gateway")).toEqual([ + "beta", + ]); } finally { await fs.rm(home, { recursive: true, force: true }); vi.unstubAllEnvs(); diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index 300bf56eb58..d22c746020d 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -39,9 +39,14 @@ export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { }); } -export function listNativeNvidiaProviderAttachmentSandboxNames(): readonly string[] { +export function listNativeNvidiaProviderAttachmentSandboxNames( + gatewayName: string, +): readonly string[] { return Object.values(load().sandboxes) - .filter((sandbox) => sandbox.nativeNvidiaProviderAttachment !== undefined) + .filter( + (sandbox) => + sandbox.gatewayName === gatewayName && sandbox.nativeNvidiaProviderAttachment !== undefined, + ) .map((sandbox) => sandbox.name) .sort(); } From 250cf40d5e3e830e4d0b89418711e842c123e8fe Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 11:12:15 -0700 Subject: [PATCH 092/133] test: match native reset mock gateway signature Signed-off-by: Deepak Jain --- src/lib/actions/credentials-native-reset.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index 5d8f6d3a9ef..d894bfb18f9 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -49,7 +49,7 @@ describe("native NVIDIA credential reset ownership", () => { return deleteResult; }); const clearNativeNvidiaProviderAuthority = vi.fn(() => operations.push("clear-authority")); - const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName: string) => + const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName?: string) => gatewayName === "nemoclaw" ? ["alpha"] : [], ); @@ -112,7 +112,7 @@ describe("native NVIDIA credential reset ownership", () => { ok: true, })); const clearNativeNvidiaProviderAuthority = vi.fn(); - const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName: string) => + const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName?: string) => gatewayName === "other-gateway" ? ["beta"] : [], ); From ca837d8dd61f058f0088e00aee94fa2728617426 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 14:02:38 -0700 Subject: [PATCH 093/133] fix(inference): address native hosted review findings Signed-off-by: Deepak Jain --- .github/workflows/e2e.yaml | 4 + .../recover-rebuild-sandboxes.mdx | 4 +- docs/reference/commands.mdx | 6 +- docs/security/best-practices.mdx | 4 +- scripts/lib/openclaw-npm-remediation.mts | 100 +----------------- .../actions/inference-set-openrouter.test.ts | 6 +- src/lib/actions/inference-set.ts | 19 +++- src/lib/actions/sandbox/connect.ts | 16 ++- src/lib/actions/sandbox/launch-readiness.ts | 2 +- .../sandbox/launch-readiness/health.ts | 8 +- .../hermes-wrapper-oneshot-routing.test.ts | 2 + .../openclaw-dependency-review.test.ts | 2 +- .../openclaw/openclaw-npm-remediation.test.ts | 52 +++++---- .../fixed-hosted-qualification.test.ts | 33 +++++- .../route-swap-repair.test.ts | 17 +++ 15 files changed, 140 insertions(+), 135 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 32ba756d083..26668a55d90 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -677,6 +677,10 @@ jobs: run: | set -euo pipefail if [[ "${JOBS:-}" == "native-runtime-qualification-producer" && -z "${TARGETS:-}" ]]; then + if [[ -n "${HOSTED_MODEL:-}" ]]; then + echo "::error::hosted_model requires an explicit fixed hosted qualification target" >&2 + exit 1 + fi { echo 'matrix=[]' echo 'test_matrix=[]' diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 6166738f33c..77077a1f286 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -190,14 +190,14 @@ During the lease, `launch` still verifies the owning OpenShell gateway, exact li Every configured route must serve a valid response to a bounded request for the recorded model before NemoClaw accepts or publishes launch readiness. Shared-route providers use `inference.local`. -Their models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. +Their models probe must return HTTP 2xx. Fixed hosted providers verify their sandbox-attached OpenShell provider and run the bounded model request at their native endpoint without the shared-route models probe. A failed required probe or model request rejects launch readiness. This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. Every configured route must serve a valid response to a bounded request for the recorded model before NemoClaw accepts or publishes launch readiness. -The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models`. +Shared-route providers require HTTP 2xx from the models probe. Fixed hosted providers verify their sandbox-attached provider and send the model request to its native endpoint. A failed request rejects launch readiness and identifies the inference request as the failed check. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 7ac81513e89..6503434d507 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1133,7 +1133,7 @@ During that lease, another `launch` still verifies these conditions: - The recorded inference selection matches its provider path, and every configured route serves a valid response to a bounded request for the recorded model. Shared-route providers use `inference.local`. Fixed hosted providers verify the recorded sandbox-attached provider and send the request to the selected native endpoint. - The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. + The shared-route models probe must return HTTP 2xx. A failed model request rejects readiness before the agent starts. This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. @@ -1141,7 +1141,7 @@ During that lease, another `launch` still verifies these conditions: - The recorded inference selection matches the live route, and every configured route serves a valid response to a bounded request for the recorded model. - The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models`. + Shared-route providers require HTTP 2xx from the models probe. Fixed hosted providers verify their sandbox-attached provider and send the model request to its native endpoint. A failed model request rejects readiness before the agent starts. @@ -1642,7 +1642,7 @@ $$nemoclaw my-assistant start When that deadline expires, `start` keeps the existing container, exits non-zero, and prints the `NEMOCLAW_CONNECT_TIMEOUT` value to use on the next run. -After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. For a shared gateway route, `doctor` still classifies an HTTP `401` or `403` response as reachable. The native NVIDIA doctor probe instead requires a 2xx response from the sandbox-attached provider. Correct the provider credential when `start` reports either status. +After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. For a shared gateway route, `doctor` still classifies an HTTP `401` or `403` response as reachable. Native hosted doctor checks require a 2xx models response for NVIDIA Endpoints, or a valid inference response for other fixed hosted providers. Correct the provider credential when `start` reports either status. ### `$$nemoclaw status` diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index dd2539aaa2c..31d51d6cc12 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -180,7 +180,7 @@ Endpoint rules restrict allowed HTTP methods and URL paths. | Aspect | Detail | |---|---| -| Default | Some endpoints allow GET and POST on `/**` (for example, `clawhub.ai`). Others restrict methods and paths to specific API routes. The sandbox-attached NVIDIA inference provider allows POST only to `/v1/chat/completions` and GET only to `/v1/models`; it does not permit embedding requests. Read-only endpoints such as `docs.openclaw.ai`, the OpenClaw `npm_registry` baseline entry, and the `pypi` preset allow GET only (PyPI also allows HEAD). The broader `npm` preset is an intentional exception: npm/Yarn registry traffic uses L4 pass-through for Node 22 undici CONNECT compatibility. While that preset is active, NemoClaw temporarily aligns the overlapping baseline npm endpoint with the same reviewed L4 metadata because OpenShell 0.0.116 requires a single connection mode. | +| Default | Some endpoints allow GET and POST on `/**` (for example, `clawhub.ai`). Others restrict methods and paths to specific API routes. Each sandbox-attached hosted provider restricts its own methods and paths. For example, the NVIDIA profile allows POST only to `/v1/chat/completions` and GET only to `/v1/models`, excluding embedding requests. Read-only endpoints such as `docs.openclaw.ai`, the OpenClaw `npm_registry` baseline entry, and the `pypi` preset allow GET only (PyPI also allows HEAD). The broader `npm` preset is an intentional exception: npm/Yarn registry traffic uses L4 pass-through for Node 22 undici CONNECT compatibility. While that preset is active, NemoClaw temporarily aligns the overlapping baseline npm endpoint with the same reviewed L4 metadata because OpenShell 0.0.116 requires a single connection mode. | | What you can change | Add methods (PUT, DELETE, PATCH) or restrict paths to specific prefixes. | | Risk if relaxed | Allowing all methods on an API endpoint gives the agent write and delete access. For example, allowing DELETE on `api.github.com` lets the agent delete repositories. | | Recommendation | Use GET-only rules for endpoints that the agent only reads. Add write methods only for endpoints where the agent must create or modify resources. Restrict paths to specific API routes when possible. | @@ -307,7 +307,7 @@ The agent never receives the provider API key. |---|---| | Default | Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the shared `inference.local` route. OpenShell owns the credential and upstream endpoint in both cases. | | What you can change | You select a supported provider. NemoClaw selects and enforces that provider's managed path. | -| Risk if bypassed | Adding an unowned provider endpoint to network policy bypasses NemoClaw's managed provider boundary and could let an agent use a stolen or hardcoded key. The NVIDIA Endpoints path is not a bypass: its checked-in OpenShell provider profile restricts the endpoint, methods, paths, and binaries, then rewrites a placeholder credential at the egress boundary. | +| Risk if bypassed | Adding an unowned provider endpoint to network policy bypasses NemoClaw's managed provider boundary and could let an agent use a stolen or hardcoded key. Each fixed hosted provider uses a checked-in OpenShell profile that restricts the endpoint, methods, paths, and binaries, then rewrites a placeholder credential at egress. | | Recommendation | Do not add inference provider hosts to network policy for NemoClaw model traffic. Use the provider path created by onboarding. The `claude-code` preset is a separate opt-in exception for running the Claude Code CLI with its own credentials, not a way to configure NemoClaw inference. | ### Provider Trust Tiers diff --git a/scripts/lib/openclaw-npm-remediation.mts b/scripts/lib/openclaw-npm-remediation.mts index 23b31fed49f..74bcf8f082f 100755 --- a/scripts/lib/openclaw-npm-remediation.mts +++ b/scripts/lib/openclaw-npm-remediation.mts @@ -35,7 +35,6 @@ type Remediation = Readonly<{ | "current-core" | "jaeger" | "legacy-core" - | "proxy-addr" | "slack-proxy-addr" | "undici"; version: "2026.3.11" | "2026.6.10" | "2026.7.1" | "2026.9.2"; @@ -54,12 +53,6 @@ type BuildRequest = RemediationRequest & expectedPatchedTreeIntegrity?: string; }>; -type InstalledSlackRemediationRequest = Readonly<{ - env?: NodeJS.ProcessEnv; - packageDirectory: string; - workingDirectory: string; -}>; - export type RemediatedArchive = Readonly< | { archivePath: string; @@ -123,10 +116,6 @@ const CURRENT_UNDICI_VERSION = "8.10.0"; const CURRENT_UNDICI_INTEGRITY = "sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ=="; const CURRENT_UNDICI_TARBALL = "https://registry.npmjs.org/undici/-/undici-8.10.0.tgz"; -const CURRENT_PROXY_ADDR_VERSION = "2.0.8"; -const CURRENT_PROXY_ADDR_INTEGRITY = - "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="; -const CURRENT_PROXY_ADDR_TARBALL = "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz"; const CURRENT_IP_ADDRESS_VERSION = "10.3.1"; const CURRENT_IP_ADDRESS_INTEGRITY = "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g=="; @@ -900,62 +889,26 @@ export function patchOpenClawSlackProxyAddrPackageGraph( requirePackageIdentity( replacementPackageJson, "proxy-addr", - CURRENT_PROXY_ADDR_VERSION, + PROXY_ADDR_VERSION, "OpenClaw Slack proxy-addr remediation package", ); requireDependencyShape( replacementPackageJson, { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, - `proxy-addr@${CURRENT_PROXY_ADDR_VERSION}`, + `proxy-addr@${PROXY_ADDR_VERSION}`, ); if ( replacementPackageJson.license !== "MIT" || replacementPackageJson.engines?.node !== ">= 0.10" ) { throw new Error( - `proxy-addr@${CURRENT_PROXY_ADDR_VERSION} package contract changed; review the remediation before updating it`, + `proxy-addr@${PROXY_ADDR_VERSION} package contract changed; review the remediation before updating it`, ); } copyReplacementPackage(replacementDirectory, proxyAddrDirectory); } -export function applyOpenClawSlackProxyAddrRemediation( - request: InstalledSlackRemediationRequest, -): void { - const packageDirectory = resolve(request.packageDirectory); - const packageStat = lstatSync(packageDirectory); - if (!packageStat.isDirectory() || packageStat.isSymbolicLink()) { - throw new Error("OpenClaw Slack install is not a regular package directory"); - } - const env = { - ...process.env, - ...request.env, - NPM_CONFIG_AUDIT: "false", - NPM_CONFIG_FUND: "false", - NPM_CONFIG_IGNORE_SCRIPTS: "true", - NPM_CONFIG_UPDATE_NOTIFIER: "false", - npm_config_ignore_scripts: "true", - }; - const workingDirectory = resolve(request.workingDirectory); - mkdirSync(workingDirectory, { recursive: true, mode: 0o700 }); - const remediationRoot = mkdtempSync(join(workingDirectory, "openclaw-slack-proxy-addr-")); - const proxyAddrArchive = packReplacement( - `proxy-addr@${CURRENT_PROXY_ADDR_VERSION}`, - CURRENT_PROXY_ADDR_INTEGRITY, - CURRENT_PROXY_ADDR_TARBALL, - remediationRoot, - env, - ); - const proxyAddrPackage = extractArchive( - proxyAddrArchive.archivePath, - join(remediationRoot, "proxy-addr"), - remediationRoot, - env, - ); - patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, proxyAddrPackage); -} - export function patchLegacyOpenClawCorePackageGraph(packageDirectory: string): void { const packageJsonPath = join(packageDirectory, "package.json"); const bundledTarPackageJsonPath = join(packageDirectory, "node_modules", "tar", "package.json"); @@ -1269,34 +1222,6 @@ function packReplacement( }); } -export function patchOpenClawSlackProxyPackageGraph( - packageDirectory: string, - replacementDirectory: string, -): void { - requirePackageIdentity( - readJson(join(packageDirectory, "package.json")), - "@openclaw/slack", - "2026.9.2", - "OpenClaw Slack plugin", - ); - const target = join( - packageDirectory, - "node_modules", - "@slack", - "bolt", - "node_modules", - "proxy-addr", - ); - const original = readJson(join(target, "package.json")); - const replacement = readJson(join(replacementDirectory, "package.json")); - requirePackageIdentity(original, "proxy-addr", "2.0.7", "Bundled Slack proxy-addr"); - requirePackageIdentity(replacement, "proxy-addr", PROXY_ADDR_VERSION, "proxy-addr replacement"); - const dependencies = { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }; - requireDependencyShape(original, dependencies, "Bundled Slack proxy-addr"); - requireDependencyShape(replacement, dependencies, "proxy-addr replacement"); - copyReplacementPackage(replacementDirectory, target); -} - export function buildRemediatedOpenClawPluginArchive( request: BuildRequest, ): Extract { @@ -1336,7 +1261,7 @@ export function buildRemediatedOpenClawPluginArchive( remediationRoot, env, ); - patchOpenClawSlackProxyPackageGraph(sourcePackage, replacement); + patchOpenClawSlackProxyAddrPackageGraph(sourcePackage, replacement); } else if (remediation.kind === "core") { const fsSafeArchive = packReplacement( `@openclaw/fs-safe@${FS_SAFE_VERSION}`, @@ -1475,21 +1400,6 @@ export function buildRemediatedOpenClawPluginArchive( ); patchOpenClawDiscordPackageGraph(sourcePackage); copyReplacementPackage(undiciPackage, join(sourcePackage, "node_modules", "undici")); - } else if (remediation.kind === "proxy-addr") { - const proxyAddrArchive = packReplacement( - `proxy-addr@${CURRENT_PROXY_ADDR_VERSION}`, - CURRENT_PROXY_ADDR_INTEGRITY, - CURRENT_PROXY_ADDR_TARBALL, - remediationRoot, - env, - ); - const proxyAddrPackage = extractArchive( - proxyAddrArchive.archivePath, - join(remediationRoot, "proxy-addr"), - remediationRoot, - env, - ); - patchOpenClawSlackProxyAddrPackageGraph(sourcePackage, proxyAddrPackage); } else if (remediation.kind === "legacy-core") { const bundledTarPath = join(sourcePackage, "node_modules", "tar"); const bundledBaileysPath = join(sourcePackage, "node_modules", "@whiskeysockets", "baileys"); @@ -1908,7 +1818,7 @@ function remediateVerifiedInstalledOfficialOpenClawPlugin( directory, env, ); - patchOpenClawSlackProxyPackageGraph(packageDirectory, replacement); + patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, replacement); } finally { rmSync(directory, { force: true, recursive: true }); } diff --git a/src/lib/actions/inference-set-openrouter.test.ts b/src/lib/actions/inference-set-openrouter.test.ts index ef9c14d067f..853f3b05b51 100644 --- a/src/lib/actions/inference-set-openrouter.test.ts +++ b/src/lib/actions/inference-set-openrouter.test.ts @@ -194,7 +194,7 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), ).rejects.toThrow( - /Sandbox-side verification rejected.*previous OpenShell inference selection was restored/s, + /Sandbox-side verification rejected.*shared OpenShell inference selection was not changed/s, ); expect(routeSelections(deps)).toEqual([]); @@ -214,7 +214,7 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), - ).rejects.toThrow(/previous OpenShell inference selection was restored/); + ).rejects.toThrow(/shared OpenShell inference selection was not changed/); expect(deps.calls.probeSandboxRoute).toHaveBeenCalledTimes(3); expect(routeSelections(deps)).toEqual([]); @@ -228,7 +228,7 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), - ).rejects.toThrow(/sandbox dial failed.*previous OpenShell inference selection was restored/s); + ).rejects.toThrow(/sandbox dial failed.*shared OpenShell inference selection was not changed/s); expect(routeSelections(deps)).toEqual([]); expect(deps.getSandbox("alpha")?.model).toBe(ULTRA); diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 3ade37ff512..570fd3c02e9 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1327,6 +1327,18 @@ function recordNativeProviderAuthority( else deps.setNativeHostedProviderAuthority(gatewayName, attachment); } +function inferenceSelectionRecoveryDetail( + selectingNativeHosted: boolean, + previousNativeAttachment: NativeHostedProviderAttachment | null | undefined, + previousProvider: string, + previousModel: string, +): string { + if (selectingNativeHosted || previousNativeAttachment) { + return "The shared OpenShell inference selection was not changed."; + } + return `The previous OpenShell inference selection was restored to '${previousProvider}' / '${previousModel}'.`; +} + async function runInferenceSetWithoutHostLock( options: InferenceSetOptions, deps: InferenceSetDeps, @@ -1832,7 +1844,12 @@ async function runInferenceSetWithoutHostLock( } throw new InferenceSetError( `Sandbox-side verification rejected provider '${provider}' / '${model}': ${probe.detail}. ` + - `The previous OpenShell inference selection was restored to '${rollbackRoute?.provider ?? previousProvider}' / '${rollbackRoute?.model ?? previousModel}'.`, + inferenceSelectionRecoveryDetail( + selectingNativeHosted, + previousNativeHostedAttachment, + rollbackRoute?.provider ?? previousProvider, + rollbackRoute?.model ?? previousModel, + ), ); } } diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 4f046828275..9a29766b97e 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -122,6 +122,7 @@ import { publicationFromDecision, publishLaunchReadiness, getNativeHostedProviderAttachment, + LaunchReadinessEvidenceError, requireNativeHostedInferenceHealth, settlePortableOpenClawPairing, withLaunchReadinessMutationGate, @@ -1878,7 +1879,20 @@ async function ensureSandboxInferenceRoute( if (!snapshot) return { sandbox: null, routeHealthy: null }; if (registry.getSandboxEntryInference(snapshot).kind !== "configured") return { sandbox: snapshot, routeHealthy: null }; - if (getNativeHostedProviderAttachment(snapshot)) { + let nativeAttachment: ReturnType; + try { + nativeAttachment = getNativeHostedProviderAttachment(snapshot); + } catch (error) { + if (!(error instanceof LaunchReadinessEvidenceError)) throw error; + if (!quiet) { + console.error( + ` Error: sandbox '${sandboxName}' has no valid native hosted provider attachment receipt. Recreate the sandbox to restore native inference.`, + ); + console.error(` Run: ${CLI_NAME} ${sandboxName} doctor`); + } + return { sandbox: snapshot, routeHealthy: false }; + } + if (nativeAttachment) { return ensureSandboxInferenceRouteUnlocked(sandboxName, agent, { quiet }); } const gatewayName = getPersistedSandboxTargetGatewayName(snapshot); diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 1870c7f69d7..1a95219837c 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -86,7 +86,7 @@ import { } from "./launch-readiness/openclaw-pairing-qualification"; export { createProbeTimingRecorder, type ProbeTimingRecorder } from "./probe/timing"; -export { createBoundLaunchReadinessDeps }; +export { createBoundLaunchReadinessDeps, LaunchReadinessEvidenceError }; export { getNativeHostedProviderAttachment, requireNativeHostedInferenceHealth, diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index 5ec18d0aab1..14cae0539b5 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -136,8 +136,8 @@ export class LaunchReadinessObservationError extends Error { /** The required observation could not produce authoritative evidence. */ export class LaunchReadinessEvidenceError extends Error { - constructor() { - super("launch readiness evidence unavailable"); + constructor(message = "launch readiness evidence unavailable") { + super(message); } } @@ -214,7 +214,9 @@ export function getNativeHostedProviderAttachment( ); const profile = nativeHostedProfile(entry.provider); if ((profile && !receipt) || (receipt && profile?.profileId !== receipt.profileId)) { - throw new LaunchReadinessEvidenceError(); + throw new LaunchReadinessEvidenceError( + "No valid native hosted provider attachment receipt. Recreate the sandbox to restore native inference.", + ); } return receipt ?? null; } diff --git a/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts b/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts index 4575f3f0b5a..0b4ede29c0c 100644 --- a/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts +++ b/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts @@ -156,6 +156,8 @@ with tempfile.TemporaryDirectory() as root: run = subprocess.run(command + ["gateway", "run"], capture_output=True, text=True) assert run.returncode == 0, run.stderr config.write_text("model: {api_key: raw-secret-do-not-print}") + hash_text, _, _ = guard._hash_text(str(config), str(env)) + hashes.write_text(hash_text) marker.unlink(missing_ok=True) run = subprocess.run(command + ["chat", "--query", "hello"], capture_output=True, text=True) assert run.returncode == 1 diff --git a/test/agents/openclaw/openclaw-dependency-review.test.ts b/test/agents/openclaw/openclaw-dependency-review.test.ts index 112f1946320..ad4565f8356 100644 --- a/test/agents/openclaw/openclaw-dependency-review.test.ts +++ b/test/agents/openclaw/openclaw-dependency-review.test.ts @@ -250,7 +250,7 @@ check_not_contains "$optional_plugin_block" 'pack_reviewed_npm_tarball' "optiona grep -Fq 'patchOpenClawCorePackageGraph' "$remediation_helper" grep -Fq 'patchOpenClawDiagnosticsPackageGraph' "$remediation_helper" grep -Fq 'remediateInstalledOfficialOpenClawPlugin' "$messaging_build_applier" - grep -Fq 'patchOpenClawSlackProxyPackageGraph(packageDirectory, replacement)' "$remediation_helper" + grep -Fq 'patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, replacement)' "$remediation_helper" for package_spec in \ 'openclaw@2026.3.11' \ 'openclaw@2026.6.10' \ diff --git a/test/agents/openclaw/openclaw-npm-remediation.test.ts b/test/agents/openclaw/openclaw-npm-remediation.test.ts index 57dcb8c2e10..dbbe9877fc1 100644 --- a/test/agents/openclaw/openclaw-npm-remediation.test.ts +++ b/test/agents/openclaw/openclaw-npm-remediation.test.ts @@ -25,7 +25,6 @@ import { patchOpenClawDiscordPackageGraph, patchOpenClawPluginPackageGraph, patchOpenClawSlackProxyAddrPackageGraph, - patchOpenClawSlackProxyPackageGraph, } from "../../../scripts/lib/openclaw-npm-remediation.mts"; const temporaryDirectories: string[] = []; @@ -581,29 +580,34 @@ describe("OpenClaw npm remediation", () => { expect(() => buildRemediatedOpenClawArchive(request)).not.toThrow("private-archive-marker"); }); + it.each(["@slack/bolt", "@slack/bolt/node_modules/express"])( + "rejects changed Slack %s contracts before replacing proxy bytes", + (dependency) => { + const { packageDirectory, replacementDirectory } = writeSlackProxyAddrFixture(); + const metadataPath = path.join(packageDirectory, "node_modules", dependency, "package.json"); + const metadata = readJson>(metadataPath); + writeJson(metadataPath, { ...metadata, license: "unexpected" }); + expect(() => + patchOpenClawSlackProxyAddrPackageGraph(packageDirectory, replacementDirectory), + ).toThrow("contract changed after review"); + expect( + readFileSync( + path.join(packageDirectory, "node_modules/@slack/bolt/node_modules/proxy-addr/index.js"), + "utf8", + ), + ).toContain("vulnerable"); + }, + ); it("replaces bundled Slack proxy-addr bytes and rejects an unexpected source version", () => { - const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-slack-proxy-")); - temporaryDirectories.push(directory); + const { packageDirectory: directory, replacementDirectory: replacement } = + writeSlackProxyAddrFixture(); const target = path.join(directory, "node_modules/@slack/bolt/node_modules/proxy-addr"); - const replacement = path.join(directory, "replacement"); - mkdirSync(target, { recursive: true }); - mkdirSync(replacement); - writeJson(path.join(directory, "package.json"), { - name: "@openclaw/slack", - version: "2026.9.2", - }); - const metadata = { - name: "proxy-addr", - dependencies: { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, - }; - writeJson(path.join(target, "package.json"), { ...metadata, version: "2.0.7" }); - writeJson(path.join(replacement, "package.json"), { ...metadata, version: "2.0.8" }); - writeFileSync(path.join(target, "index.js"), "vulnerable"); - writeFileSync(path.join(replacement, "index.js"), "patched"); - patchOpenClawSlackProxyPackageGraph(directory, replacement); - expect(readFileSync(path.join(target, "index.js"), "utf8")).toBe("patched"); + patchOpenClawSlackProxyAddrPackageGraph(directory, replacement); + expect(readFileSync(path.join(target, "index.js"), "utf8")).toBe( + readFileSync(path.join(replacement, "index.js"), "utf8"), + ); expect(readJson(path.join(target, "package.json"))).toMatchObject({ version: "2.0.8" }); - expect(() => patchOpenClawSlackProxyPackageGraph(directory, replacement)).toThrow( + expect(() => patchOpenClawSlackProxyAddrPackageGraph(directory, replacement)).toThrow( "must be proxy-addr@2.0.7", ); }); @@ -1046,7 +1050,11 @@ describe("OpenClaw npm remediation", () => { ), ).toMatchObject({ name: "tar", version: "7.5.21" }); expect( - readJson<{ dependencies?: Record; name?: string; version?: string }>( + readJson<{ + dependencies?: Record; + name?: string; + version?: string; + }>( path.join( extracted, "package", diff --git a/test/e2e/support/fixed-hosted-qualification.test.ts b/test/e2e/support/fixed-hosted-qualification.test.ts index f191b804e1f..2a9b82a72b2 100644 --- a/test/e2e/support/fixed-hosted-qualification.test.ts +++ b/test/e2e/support/fixed-hosted-qualification.test.ts @@ -7,7 +7,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; -import { readWorkflow } from "../../helpers/e2e-workflow-contract"; +import { readWorkflow, readYaml, type Workflow } from "../../helpers/e2e-workflow-contract"; import { FIXED_HOSTED_CREDENTIAL_PREDICATE, validateStandardProfileWorkflowBoundary, @@ -30,6 +30,37 @@ const explicit = { }; describe("fixed hosted qualification planning", () => { + it.each([ + ["", 0, true], + ["approved/model", 1, false], + ] as const)( + "rejects unrelated hosted model selections before native runtime planning [%s]", + (hostedModel, status, outputExists) => { + const workflow = readYaml(".github/workflows/e2e.yaml") as Workflow; + const script = workflow.jobs["generate-matrix"].steps?.find( + (step) => step.name === "Generate E2E target matrix", + )?.run; + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "native-runtime-plan-")); + try { + const output = path.join(directory, "output"); + const result = spawnSync("bash", ["-c", script!], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + JOBS: "native-runtime-qualification-producer", + TARGETS: "", + HOSTED_MODEL: hostedModel, + GITHUB_OUTPUT: output, + }, + }); + expect(result.status).toBe(status); + expect(fs.existsSync(output)).toBe(outputExists); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + it.each(FIXED_HOSTED_QUALIFICATIONS)( "selects only the requested protocol representative [$id]", ({ id, agent }) => { diff --git a/test/sandbox-connect-inference/route-swap-repair.test.ts b/test/sandbox-connect-inference/route-swap-repair.test.ts index c2f57adaf6f..537c4715e82 100644 --- a/test/sandbox-connect-inference/route-swap-repair.test.ts +++ b/test/sandbox-connect-inference/route-swap-repair.test.ts @@ -8,6 +8,23 @@ import { testTimeoutOptions } from "../helpers/timeouts"; import { isHostWsl, runConnect, setupFixture } from "./helpers"; describe("sandbox connect inference route swap (#1248)", () => { + it( + "refuses a legacy hosted selection without an attachment receipt", + testTimeoutOptions(20_000), + () => { + const { tmpDir, stateFile, sandboxName } = setupFixture( + { name: "my-sandbox", model: "gpt-4o", provider: "openai-api", gpuEnabled: false }, + "openai-api", + "gpt-4o", + ); + const result = runConnect(tmpDir, sandboxName); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("Recreate the sandbox to restore native inference"); + const state = JSON.parse(fs.readFileSync(stateFile, "utf-8")); + expect(state.inferenceSetCalls).toEqual([]); + }, + ); + it( "swaps inference route when live route does not match sandbox provider", testTimeoutOptions(20_000), From 22d5d63a9c2ffb7d770bfa42935ca6d2a18428ef Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 14:23:22 -0700 Subject: [PATCH 094/133] test: align hosted inference validation fixtures Signed-off-by: Deepak Jain --- ...messaging-build-applier-googlechat.test.ts | 32 ++++++++++++++++++- .../messaging-build-applier-integrity.test.ts | 32 ++++++++++++++++++- tools/e2e/workflow-boundary.mts | 2 +- 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/test/runtime/messaging/messaging-build-applier-googlechat.test.ts b/test/runtime/messaging/messaging-build-applier-googlechat.test.ts index f66254ae9a2..253c01f8dd5 100644 --- a/test/runtime/messaging/messaging-build-applier-googlechat.test.ts +++ b/test/runtime/messaging/messaging-build-applier-googlechat.test.ts @@ -220,11 +220,41 @@ it("patches the installed official Slack bundle only after registry provenance i fs.mkdirSync(target, { recursive: true }); fs.writeFileSync( path.join(installed, "package.json"), - JSON.stringify({ name: "@openclaw/slack", version: "2026.9.2" }), + JSON.stringify({ + name: "@openclaw/slack", + version: "2026.9.2", + dependencies: { "@slack/bolt": "5.0.0" }, + bundledDependencies: ["@slack/bolt"], + }), + ); + const boltDirectory = path.join(installed, "node_modules/@slack/bolt"); + const expressDirectory = path.join(boltDirectory, "node_modules/express"); + fs.mkdirSync(expressDirectory, { recursive: true }); + fs.writeFileSync( + path.join(boltDirectory, "package.json"), + JSON.stringify({ + name: "@slack/bolt", + version: "5.0.0", + dependencies: { express: "^5.0.0" }, + license: "MIT", + engines: { node: ">=20" }, + }), + ); + fs.writeFileSync( + path.join(expressDirectory, "package.json"), + JSON.stringify({ + name: "express", + version: "5.2.1", + dependencies: { "proxy-addr": "^2.0.7" }, + license: "MIT", + engines: { node: ">= 18" }, + }), ); const metadata = { name: "proxy-addr", dependencies: { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, + license: "MIT", + engines: { node: ">= 0.10" }, }; fs.writeFileSync( path.join(target, "package.json"), diff --git a/test/runtime/messaging/messaging-build-applier-integrity.test.ts b/test/runtime/messaging/messaging-build-applier-integrity.test.ts index 0505b636602..d9d0353d6ec 100644 --- a/test/runtime/messaging/messaging-build-applier-integrity.test.ts +++ b/test/runtime/messaging/messaging-build-applier-integrity.test.ts @@ -241,7 +241,35 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { fs.mkdirSync(dependencyDirectory, { recursive: true }); fs.writeFileSync( path.join(packageDirectory, "package.json"), - JSON.stringify({ name: "@openclaw/slack", version: "2026.9.2" }), + JSON.stringify({ + name: "@openclaw/slack", + version: "2026.9.2", + dependencies: { "@slack/bolt": "5.0.0" }, + bundledDependencies: ["@slack/bolt"], + }), + ); + const boltDirectory = path.join(packageDirectory, "node_modules/@slack/bolt"); + const expressDirectory = path.join(boltDirectory, "node_modules/express"); + fs.mkdirSync(expressDirectory, { recursive: true }); + fs.writeFileSync( + path.join(boltDirectory, "package.json"), + JSON.stringify({ + name: "@slack/bolt", + version: "5.0.0", + dependencies: { express: "^5.0.0" }, + license: "MIT", + engines: { node: ">=20" }, + }), + ); + fs.writeFileSync( + path.join(expressDirectory, "package.json"), + JSON.stringify({ + name: "express", + version: "5.2.1", + dependencies: { "proxy-addr": "^2.0.7" }, + license: "MIT", + engines: { node: ">= 18" }, + }), ); fs.writeFileSync( path.join(dependencyDirectory, "package.json"), @@ -249,6 +277,8 @@ describe("messaging-build-applier.mts: plugin archive integrity", () => { name: "proxy-addr", version: "2.0.7", dependencies: { forwarded: "0.2.0", "ipaddr.js": "1.9.1" }, + license: "MIT", + engines: { node: ">= 0.10" }, }), ); fs.writeFileSync(path.join(dependencyDirectory, "index.js"), "vulnerable-canary"); diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 01a7d561dfb..5f51c3593eb 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -2652,7 +2652,7 @@ const PRE_CANDIDATE_RUN_SHA256: Readonly> = { "ee0b2e6c6aa4552b228bd1cc3ba4e1f9cd72701c30b81f7d5fbf9bc011fb51c7", "Authorize Launchable E2E maintainer dispatch": "bbf442a006b47016eda56133eb400a48c6931c55364c1220b84327b5ffd6f171", - "Generate E2E target matrix": "a34c4e9f4e7d28d28e1f8096612f3db91ecbcb8a5638ae161ac0a0c1e3ae7ee8", + "Generate E2E target matrix": "ad7b0daa0cbe086c843f27ed29df84791262a564187085eedd5d1d9c574e2c87", }; function requirePreCandidateEnvironment( From 616bfea61e89d9b46c9737e178310e7a54692f49 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 15:18:30 -0700 Subject: [PATCH 095/133] refactor(inference): remove unused authority resolver inputs Signed-off-by: Deepak Jain --- src/lib/actions/inference-set.ts | 2 - .../inference/native-hosted/authority.test.ts | 45 ++----------------- src/lib/inference/native-hosted/authority.ts | 8 ---- src/lib/onboard/setup-inference.ts | 2 - 4 files changed, 3 insertions(+), 54 deletions(-) diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 570fd3c02e9..b16fca7028c 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1614,8 +1614,6 @@ async function runInferenceSetWithoutHostLock( gatewayAuthority: readRegisteredNativeAuthority(deps, preparedRoute.gatewayName, provider), recordedGatewayName: entry.gatewayName, recordedAttachment: previousNativeHostedAttachment, - recordedAuthorities: entry.nativeHostedProviderAuthorities, - sandboxes: deps.listSandboxes().sandboxes, }) : undefined; const rollbackRoute = preMutationRoute.state === "configured" ? preMutationRoute.route : null; diff --git a/src/lib/inference/native-hosted/authority.test.ts b/src/lib/inference/native-hosted/authority.test.ts index 5382dc2c4c3..af5c1ab2be1 100644 --- a/src/lib/inference/native-hosted/authority.test.ts +++ b/src/lib/inference/native-hosted/authority.test.ts @@ -35,21 +35,11 @@ describe("native hosted provider ownership", () => { profile: nvidia, gatewayName: "alpha", recordedGatewayName: "alpha", - recordedAuthorities: receipts, gatewayAuthority: nvidiaReceipt, - sandboxes: [], }), ).toEqual(nvidiaReceipt); }); - it("does not borrow proof from another gateway", () => { - expect( - resolveGatewayNativeHostedProviderAuthority({ - profile: nvidia, - gatewayName: "alpha", - sandboxes: [{ gatewayName: "beta", nativeHostedProviderAuthorities: [nvidiaReceipt] }], - }), - ).toBeUndefined(); - }); + it.each(["beta", undefined])( "does not use explicit proof from gateway %s", (recordedGatewayName) => { @@ -59,49 +49,21 @@ describe("native hosted provider ownership", () => { gatewayName: "alpha", recordedGatewayName, recordedAttachment: nvidiaReceipt, - recordedAuthorities: [nvidiaReceipt], - sandboxes: [], }), ).toBeUndefined(); }, ); - it("uses gateway ownership despite a stale peer attachment", () => { + it("uses the registered gateway ownership", () => { const current = { ...openaiReceipt, providerId: "new-registration" }; expect( resolveGatewayNativeHostedProviderAuthority({ profile: openai, gatewayName: "alpha", gatewayAuthority: current, - sandboxes: [ - { - gatewayName: "alpha", - nativeHostedProviderAttachment: openaiReceipt, - nativeHostedProviderAuthorities: [openaiReceipt], - }, - ], }), ).toEqual(current); }); - it("does not promote retained peer receipts to gateway ownership", () => { - expect( - resolveGatewayNativeHostedProviderAuthority({ - profile: openai, - gatewayName: "alpha", - recordedGatewayName: "alpha", - recordedAuthorities: [openaiReceipt], - sandboxes: [{ gatewayName: "alpha", nativeHostedProviderAttachment: openaiReceipt }], - }), - ).toBeUndefined(); - }); - it("rejects legacy peer Slice 1 proof without gateway authority", () => { - expect( - resolveGatewayNativeHostedProviderAuthority({ - profile: nvidia, - gatewayName: "alpha", - sandboxes: [{ gatewayName: "alpha", nativeNvidiaProviderAuthority: nvidiaReceipt }], - }), - ).toBeUndefined(); - }); + it("refuses conflicting identities even when the current sandbox has a receipt", () => { expect(() => resolveGatewayNativeHostedProviderAuthority({ @@ -110,7 +72,6 @@ describe("native hosted provider ownership", () => { recordedGatewayName: "alpha", recordedAttachment: nvidiaReceipt, gatewayAuthority: { ...nvidiaReceipt, providerId: "replacement" }, - sandboxes: [], }), ).toThrow("Conflicting"); }); diff --git a/src/lib/inference/native-hosted/authority.ts b/src/lib/inference/native-hosted/authority.ts index c2fc53c8c03..befc095eb4c 100644 --- a/src/lib/inference/native-hosted/authority.ts +++ b/src/lib/inference/native-hosted/authority.ts @@ -46,14 +46,6 @@ export function resolveGatewayNativeHostedProviderAuthority(input: { gatewayAuthority?: unknown; recordedGatewayName?: string | null; recordedAttachment?: NativeHostedProviderAttachment; - recordedAuthorities?: unknown; - sandboxes: ReadonlyArray<{ - gatewayName?: string | null; - nativeHostedProviderAttachment?: unknown; - nativeHostedProviderAuthorities?: unknown; - nativeNvidiaProviderAttachment?: unknown; - nativeNvidiaProviderAuthority?: unknown; - }>; }): NativeHostedProviderAttachment | undefined { const receipts: NativeHostedProviderAttachment[] = []; const collect = (raw: unknown) => { diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 2492cb5835b..2a733cc8235 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -967,8 +967,6 @@ export function createSetupInference( gatewayName, recordedGatewayName: recordedSandbox?.gatewayName, recordedAttachment, - recordedAuthorities: recordedSandbox?.nativeHostedProviderAuthorities, - sandboxes: deps.listSandboxes?.().sandboxes ?? [], }) : undefined; if (provider === deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { From 031508bfbdcaa404a90f201532fc102da3a2d896 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 16:12:51 -0700 Subject: [PATCH 096/133] fix(config): preserve native hosted provider export Signed-off-by: Deepak Jain --- docs/security/credential-rotation.mdx | 5 +- .../config/live-export-source-test-fixture.ts | 99 +++++++++++++++++++ .../config/live-export-source.test.ts | 90 +++++++++++++++++ src/lib/adapters/config/live-export-source.ts | 69 ++++++------- .../native-nvidia-profile-response.ts | 52 +++++++--- src/lib/adapters/openshell/providers.ts | 26 ++--- src/lib/domain/config/export-evidence.ts | 29 ++++-- src/lib/domain/config/verify-export-source.ts | 76 +++++++------- src/lib/inference/native-hosted/profiles.ts | 2 +- 9 files changed, 340 insertions(+), 108 deletions(-) diff --git a/docs/security/credential-rotation.mdx b/docs/security/credential-rotation.mdx index a31f7d9b7df..aea0188b6bf 100644 --- a/docs/security/credential-rotation.mdx +++ b/docs/security/credential-rotation.mdx @@ -181,9 +181,10 @@ unset TAVILY_API_KEY Use `credentials reset` only when you need to remove an inference or web search provider before its replacement is available. Run `$$nemoclaw credentials list` first, then pass the provider name from that output. -The native NVIDIA provider cannot be reset while it is attached to a sandbox. +A native hosted provider cannot be reset while any recorded sandbox uses it. Use [Rotate an Inference API key](#rotate-an-inference-api-key) to replace its credential in place. -To remove it completely, preserve required sandbox state, destroy every attached sandbox, and then run: +To remove it completely, preserve required sandbox state, destroy every recorded sandbox that uses it, and then run `credentials reset` with its provider name. +For example, to remove the NVIDIA provider: ```bash $$nemoclaw credentials reset nvidia-prod --yes diff --git a/src/lib/adapters/config/live-export-source-test-fixture.ts b/src/lib/adapters/config/live-export-source-test-fixture.ts index e9913ad9be6..07ee66863ef 100644 --- a/src/lib/adapters/config/live-export-source-test-fixture.ts +++ b/src/lib/adapters/config/live-export-source-test-fixture.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { NativeHostedProfile } from "../../inference/native-hosted/profiles"; import { createHash } from "node:crypto"; import { vi } from "vitest"; @@ -393,3 +394,101 @@ export function braveProvider() { }, }; } + +export function nativeHostedExportFixture(profile: NativeHostedProfile) { + const api = + profile.logicalProvider === "anthropic-prod" ? "anthropic-messages" : "openai-completions"; + const route = resolveManagedStartupInferenceRoute( + "openclaw", + profile.logicalProvider, + "model-a", + api, + ); + const built = buildManagedStartupProfile({ + ...startupInput, + inference: { + ...startupInput.inference, + routeProvider: route.providerKey, + upstreamProvider: profile.logicalProvider, + routedBaseUrl: route.inferenceBaseUrl, + primaryModelRef: route.primaryModelRef, + compatibility: route.inferenceCompat ?? {}, + api, + }, + }); + const sourceEntry: SandboxEntry = { + ...entry, + provider: profile.logicalProvider, + preferredInferenceApi: api, + endpointUrl: profile.endpoint, + credentialEnv: profile.hostCredentialEnv ?? profile.credentialEnv, + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "native-provider-id", + }, + workload: { + ...entry.workload, + encodedProfile: built.encodedProfile, + startupProfileSha256: built.startupProfileSha256, + }, + }; + const readCredential = vi.fn(() => { + throw new Error(readFailureCanary); + }); + const providerValue = { + ...nativeNvidiaProvider(), + metadata: { + ...nativeNvidiaProvider().metadata, + id: "native-provider-id", + name: profile.providerName, + }, + type: profile.profileId, + credentials: Object.defineProperty({}, profile.credentialEnv, { + enumerable: true, + get: readCredential, + }), + }; + const profileValue = nativeHostedProfileFixture(profile, api); + return { sourceEntry, providerValue, profileValue, readCredential }; +} + +function nativeHostedProfileFixture(profile: NativeHostedProfile, api: string) { + const url = new URL(profile.endpoint); + const prefix = url.pathname === "/" ? "/v1" : url.pathname; + return { + ...nativeNvidiaProfile(), + id: profile.profileId, + credentials: [ + { + name: "api_key", + envVars: [profile.credentialEnv] as string[], + required: true, + authStyle: api === "anthropic-messages" ? "header" : "bearer", + headerName: api === "anthropic-messages" ? "x-api-key" : "authorization", + queryParam: "", + pathTemplate: "", + }, + ], + endpoints: [ + { + ...nativeNvidiaEndpoint(), + host: url.hostname, + rules: [ + { allow: { ...emptyNativeAllow, method: "GET", path: `${prefix}/models` } }, + { + allow: { + ...emptyNativeAllow, + method: "POST", + path: `${prefix}/${api === "anthropic-messages" ? "messages" : "chat/completions"}`, + }, + }, + ...(["openai-api", "hermes-provider"].includes(profile.logicalProvider) + ? [{ allow: { ...emptyNativeAllow, method: "POST", path: `${prefix}/responses` } }] + : []), + ], + }, + ], + }; +} diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index 3e82fde71e8..3791684ad59 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -7,6 +7,11 @@ import { exportLiveSource, expectExportRefusal, } from "../../../../test/support/config-export-harness"; +import { + NATIVE_HOSTED_PROFILES, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; +import { getSandboxEntryInference } from "../../state/registry-entry-view"; import { createHash } from "node:crypto"; import { describe, expect, it, vi } from "vitest"; import YAML from "yaml"; @@ -40,6 +45,7 @@ import { legacySharedNvidiaProvider, provider, configuration, + nativeHostedExportFixture, nativeNvidiaEntry, nativeNvidiaProvider, nativeNvidiaProfile, @@ -146,6 +152,25 @@ function mockNativeNvidiaSource(profileWorkspace = "default") { }); } +function mockNativeHostedSource(profile: NativeHostedProfile) { + const fixture = nativeHostedExportFixture(profile); + mockSupportedLiveSource(3, 3, fixture.sourceEntry); + vi.mocked(getSandboxEntryInference).mockReturnValue({ + kind: "configured", + provider: profile.logicalProvider, + model: "model-a", + }); + raw.getProvider.mockResolvedValue({ provider: fixture.providerValue }); + raw.getProviderProfile.mockResolvedValue({ profile: fixture.profileValue }); + raw.getSandbox.mockResolvedValue({ + sandbox: { + ...inventory().sandbox, + spec: { ...inventory().sandbox.spec, providers: [profile.providerName] }, + }, + }); + return fixture; +} + describe("live export snapshot reader", () => { it.each(["openclaw", "hermes"] as const)( "exports %s Tavily from verified SDK reads without reading credential values (#12138)", @@ -696,6 +721,71 @@ describe("live export snapshot reader", () => { expect(raw.getProviderProfile).toHaveBeenCalled(); }); + it.each(NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"))( + "exports native $label without shared-route or credential reads", + async (profile) => { + const fixture = mockNativeHostedSource(profile); + const { result, writeStdout, publish } = await exportLiveSource(); + expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); + const yaml = writeStdout.mock.calls[0]![0]; + const document = asExportedConfig(YAML.parse(yaml)); + expect(document.spec.inferenceProviders[0]).toMatchObject({ + endpoint: profile.endpoint, + credential: { env: profile.hostCredentialEnv ?? profile.credentialEnv }, + }); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + expect(fixture.readCredential).not.toHaveBeenCalled(); + expect(yaml).not.toContain(readFailureCanary); + expect(publish).not.toHaveBeenCalled(); + }, + ); + + it.each<{ + label: string; + change: (fixture: ReturnType) => void; + }>([ + { + label: "provider identity", + change: (fixture) => { + fixture.providerValue.metadata.id = "replacement"; + }, + }, + { + label: "profile host", + change: (fixture) => { + fixture.profileValue.endpoints[0]!.host = "other.example"; + }, + }, + { + label: "profile rules", + change: (fixture) => { + fixture.profileValue.endpoints[0]!.rules[1]!.allow.path = "/v1/*"; + }, + }, + { + label: "credential binding", + change: (fixture) => { + fixture.profileValue.credentials[0]!.envVars = ["OTHER_KEY"]; + }, + }, + { + label: "sandbox attachment", + change: () => { + raw.getSandbox.mockResolvedValue(inventory()); + }, + }, + ])("refuses native hosted $label drift without exporting credentials", async ({ change }) => { + const fixture = mockNativeHostedSource( + NATIVE_HOSTED_PROFILES.find((profile) => profile.logicalProvider === "openai-api")!, + ); + change(fixture); + const { result, writeStdout, publish } = await exportLiveSource(); + expect(result.ok).toBe(false); + expect(writeStdout).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); + expect(fixture.readCredential).not.toHaveBeenCalled(); + }); + it("retains the legacy shared-route NVIDIA export without a native receipt", async () => { mockSupportedLiveSource(); raw.getProvider.mockResolvedValue({ provider: legacySharedNvidiaProvider() }); diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index 1ba68446c61..2712b908221 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -14,7 +14,8 @@ import { fingerprintOpenShellSandboxId } from "../openshell/sandbox-identity"; import { namedOpenShellGateway } from "../openshell/sandbox-observer"; import { EXPORT_REGISTRY_EVIDENCE_KEYS, - exportNativeNvidiaReceipt, + exportNativeHostedReceipt, + exportNativeHostedProfile, exportWebSearchBinding, } from "../../domain/config/export-evidence"; import type { @@ -179,31 +180,34 @@ function inferenceTopology( : "hosted"; } -type NativeNvidiaReceipt = NonNullable; +type NativeHostedReceipt = NonNullable>; function matchesNativeProviderMetadata( provider: Provider, - normalized: ReturnType, routeProvider: string, - receipt: NativeNvidiaReceipt, + receipt: NativeHostedReceipt, ): boolean { - return isDeepStrictEqual( - [ - provider.name, - provider.id, - provider.type, - provider.credentialKeys, - provider.configKeys, - provider.managedProfile?.id, - ], - [ - routeProvider, - receipt.providerId, - receipt.profileId, - expectedCredentialKeys(normalized.credentialEnv, routeProvider), - [], - receipt.profileId, - ], + const profile = exportNativeHostedProfile(receipt); + return ( + profile !== undefined && + isDeepStrictEqual( + [ + provider.name, + provider.id, + provider.type, + provider.credentialKeys, + provider.configKeys, + provider.managedProfile?.id, + ], + [ + routeProvider, + receipt.providerId, + receipt.profileId, + [profile.credentialEnv], + [], + receipt.profileId, + ], + ) ); } @@ -212,10 +216,10 @@ function matchesProviderMetadata( normalized: ReturnType, routeProvider: string, managed: boolean, - nativeReceipt?: NativeNvidiaReceipt, + nativeReceipt?: NativeHostedReceipt, ): boolean { if (nativeReceipt !== undefined) { - return matchesNativeProviderMetadata(provider, normalized, routeProvider, nativeReceipt); + return matchesNativeProviderMetadata(provider, routeProvider, nativeReceipt); } const { type, configKey } = providerContract(normalized.preferredInferenceApi); const builtin = provider.builtinInferenceEndpoint !== undefined; @@ -243,16 +247,13 @@ function matchesProviderMetadata( ); } -function profileContractFor( - routeProvider: string, - nativeReceipt: NativeNvidiaReceipt | undefined, -): "native-nvidia" | "openai" | undefined { - if (nativeReceipt) return "native-nvidia"; +function profileContractFor(routeProvider: string, nativeReceipt: NativeHostedReceipt | undefined) { + if (nativeReceipt) return exportNativeHostedProfile(nativeReceipt); return routeProvider === "ollama-local" ? "openai" : undefined; } function endpointSourceFor( - nativeReceipt: NativeNvidiaReceipt | undefined, + nativeReceipt: NativeHostedReceipt | undefined, builtin: boolean, configKey: "ANTHROPIC_BASE_URL" | "OPENAI_BASE_URL", ): ObservedExportEndpointEvidence["source"] { @@ -267,7 +268,7 @@ async function readProviderEvidence( gatewayName: string, signal: AbortSignal, managedServing?: ObservedManagedVllmRuntime, - nativeReceipt?: NativeNvidiaReceipt, + nativeReceipt?: NativeHostedReceipt, ): Promise { const { configKey } = providerContract(normalized.preferredInferenceApi); const profileContract = profileContractFor(routeProvider, nativeReceipt); @@ -300,7 +301,7 @@ async function readProviderEvidence( async function resolveLiveInference( entry: Readonly, gatewayName: string, - nativeReceipt: NativeNvidiaReceipt | undefined, + nativeReceipt: NativeHostedReceipt | undefined, ): Promise> { if (!nativeReceipt) { const live = await readInferenceRoute(entry, gatewayName); @@ -308,7 +309,7 @@ async function resolveLiveInference( } const selected = getSandboxEntryInference(entry); if (selected.kind !== "configured") { - throw new Error("The native NVIDIA inference selection is incomplete."); + throw new Error("The native hosted inference selection is incomplete."); } return { provider: nativeReceipt.providerName, @@ -326,9 +327,9 @@ async function inferenceFor( ): Promise { const normalized = normalizeInferenceSelection(entry); const gateway = resolveGatewayBinding(entry); - const nativeReceipt = exportNativeNvidiaReceipt(entry); + const nativeReceipt = exportNativeHostedReceipt(entry); if (nativeReceipt && !sandbox.providerNames.includes(nativeReceipt.providerName)) { - throw new Error("The native NVIDIA provider is not attached to the sandbox."); + throw new Error("The native hosted provider is not attached to the sandbox."); } const live = await resolveLiveInference(entry, gateway.name, nativeReceipt); beforeRead("provider-metadata"); diff --git a/src/lib/adapters/openshell/native-nvidia-profile-response.ts b/src/lib/adapters/openshell/native-nvidia-profile-response.ts index 0b4b6d7d7da..957f1622e04 100644 --- a/src/lib/adapters/openshell/native-nvidia-profile-response.ts +++ b/src/lib/adapters/openshell/native-nvidia-profile-response.ts @@ -1,9 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -type NativeNvidiaProfileResponse = Readonly<{ +import { + NATIVE_HOSTED_PROFILES, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; + +type NativeHostedProfileResponse = Readonly<{ profile: Readonly<{ - id: "nemoclaw-nvidia-inference-v1"; + id: NativeHostedProfile["profileId"]; source: "user"; scope: "platform" | "workspace"; resourceVersion: bigint | string; @@ -33,15 +38,17 @@ function stringArrayEquals(value: unknown, expected: readonly string[]): boolean ); } -function nativeCredential(value: unknown): boolean { +function nativeCredential(value: unknown, expected: NativeHostedProfile): boolean { const credential = record(value); return ( credential !== null && credential.name === "api_key" && - stringArrayEquals(credential.envVars, ["NVIDIA_INFERENCE_API_KEY"]) && + stringArrayEquals(credential.envVars, [expected.credentialEnv]) && credential.required === true && - credential.authStyle === "bearer" && - credential.headerName === "authorization" && + credential.authStyle === + (expected.logicalProvider === "anthropic-prod" ? "header" : "bearer") && + credential.headerName === + (expected.logicalProvider === "anthropic-prod" ? "x-api-key" : "authorization") && credential.queryParam === "" && credential.pathTemplate === "" && credential.refresh === undefined && @@ -66,12 +73,24 @@ function nativeRule(value: unknown, method: "GET" | "POST", path: string): boole ); } -function nativeEndpoint(value: unknown): boolean { +function nativeEndpoint(value: unknown, expected: NativeHostedProfile): boolean { + const url = new URL(expected.endpoint); + const prefix = url.pathname === "/" ? "/v1" : url.pathname; + const expectedRules: ReadonlyArray = [ + ["GET", `${prefix}/models`], + [ + "POST", + `${prefix}/${expected.logicalProvider === "anthropic-prod" ? "messages" : "chat/completions"}`, + ], + ...(["openai-api", "hermes-provider"].includes(expected.logicalProvider) + ? [["POST", `${prefix}/responses`] as const] + : []), + ]; const endpoint = record(value); const rules = endpoint?.rules; return ( endpoint !== null && - endpoint.host === "integrate.api.nvidia.com" && + endpoint.host === url.hostname && endpoint.port === 443 && emptyArray(endpoint.ports) && endpoint.protocol === "rest" && @@ -79,9 +98,8 @@ function nativeEndpoint(value: unknown): boolean { endpoint.enforcement === "enforce" && endpoint.access === "" && Array.isArray(rules) && - rules.length === 2 && - nativeRule(rules[0], "GET", "/v1/models") && - nativeRule(rules[1], "POST", "/v1/chat/completions") && + rules.length === expectedRules.length && + expectedRules.every(([method, path], index) => nativeRule(rules[index], method, path)) && emptyArray(endpoint.allowedIps) && emptyArray(endpoint.denyRules) && endpoint.allowEncodedSlash === false && @@ -116,17 +134,19 @@ function nativeBinaries(value: unknown): boolean { } /** Verify the live custom profile at the credential, egress, and binary security boundary. */ -export function isManagedNativeNvidiaProfileResponse( +export function isManagedNativeHostedProfileResponse( value: unknown, -): value is NativeNvidiaProfileResponse { + expected: NativeHostedProfile, +): value is NativeHostedProfileResponse { const response = record(value); const profile = record(response?.profile); const revision = profile?.resourceVersion; const credentials = profile?.credentials; const endpoints = profile?.endpoints; return ( + NATIVE_HOSTED_PROFILES.includes(expected) && profile !== null && - profile.id === "nemoclaw-nvidia-inference-v1" && + profile.id === expected.profileId && profile.source === "user" && (profile.scope === "platform" || profile.scope === "workspace") && (typeof revision === "bigint" || typeof revision === "string") && @@ -135,10 +155,10 @@ export function isManagedNativeNvidiaProfileResponse( profile.discovery === undefined && Array.isArray(credentials) && credentials.length === 1 && - nativeCredential(credentials[0]) && + nativeCredential(credentials[0], expected) && Array.isArray(endpoints) && endpoints.length === 1 && - nativeEndpoint(endpoints[0]) && + nativeEndpoint(endpoints[0], expected) && nativeBinaries(profile.binaries) ); } diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index ec4e0c43d91..628ac4e2a34 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -24,13 +24,13 @@ import { BuiltinNvidiaProfileResponseSchema, ProviderResponseSchema, } from "./sdk-read-schema"; -import { isManagedNativeNvidiaProfileResponse } from "./native-nvidia-profile-response"; +import { isManagedNativeHostedProfileResponse } from "./native-nvidia-profile-response"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; import { - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, -} from "../../inference/native-nvidia/contract"; + NATIVE_HOSTED_PROFILES, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; import type { OpenShellProviderMetadata } from "./provider-adapter"; @@ -41,7 +41,7 @@ const managedProfileSchemas = { "tavily-hermes-v1": ManagedHermesTavilyProfileResponseSchema, }; type ManagedProfileContract = keyof typeof managedProfileSchemas; -type ProfileContract = ManagedProfileContract | "native-nvidia"; +type ProfileContract = ManagedProfileContract | NativeHostedProfile; export type Provider = Readonly< Pick & { @@ -54,7 +54,7 @@ export type Provider = Readonly< profileWorkspace?: string; // null records a successful not-found read at the OpenAI provider's profile binding. managedProfile?: Readonly<{ - id: ManagedProfileContract | typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; + id: ManagedProfileContract | NativeHostedProfile["profileId"]; source: "builtin" | "user"; scope: "" | "platform" | "workspace"; resourceVersion: string; @@ -96,7 +96,7 @@ async function readManagedProfile( profileWorkspace: string | undefined, ): Promise | null> { const profileId = - profileContract === "native-nvidia" ? NVIDIA_HOSTED_NATIVE_PROFILE_ID : profileContract; + typeof profileContract === "object" ? profileContract.profileId : profileContract; if ( providerType !== profileId || (profileWorkspace !== "" && profileWorkspace !== request.workspace) @@ -121,8 +121,9 @@ async function readManagedProfile( function validateNativeManagedProfileResponse( response: unknown, profileWorkspace: string, + expected: NativeHostedProfile, ): NonNullable { - if (!isManagedNativeNvidiaProfileResponse(response)) { + if (!isManagedNativeHostedProfileResponse(response, expected)) { throw new OpenShellReadError("schema"); } const profile = response.profile; @@ -141,8 +142,8 @@ function validateManagedProfileResponse( profileContract: ProfileContract, profileWorkspace: string, ): NonNullable { - if (profileContract === "native-nvidia") { - return validateNativeManagedProfileResponse(response, profileWorkspace); + if (typeof profileContract === "object") { + return validateNativeManagedProfileResponse(response, profileWorkspace, profileContract); } const { profile } = readValue(managedProfileSchemas[profileContract], response); const builtin = profile.source === "builtin"; @@ -166,9 +167,8 @@ function validateManagedProfileResponse( function managedInferenceEndpointFor( managedProfile: Provider["managedProfile"], ): string | undefined { - return managedProfile?.id === NVIDIA_HOSTED_NATIVE_PROFILE_ID - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : undefined; + return NATIVE_HOSTED_PROFILES.find((profile) => profile.profileId === managedProfile?.id) + ?.endpoint; } async function readProfileEvidence( diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index 275cb4cbb83..39acf4247c7 100644 --- a/src/lib/domain/config/export-evidence.ts +++ b/src/lib/domain/config/export-evidence.ts @@ -1,16 +1,31 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia/contract"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; +import { + NATIVE_HOSTED_PROFILES, + nativeHostedProfile, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; -export function exportNativeNvidiaReceipt(entry: { +export function exportNativeHostedReceipt(entry: { provider?: string | null; nativeNvidiaProviderAttachment?: unknown; nativeHostedProviderAttachment?: unknown; }) { - if (entry.provider?.trim() !== "nvidia-prod") return undefined; - return normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAttachment ?? entry.nativeHostedProviderAttachment, + const profile = nativeHostedProfile(entry.provider); + const receipt = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment, + ); + return receipt?.profileId === profile?.profileId ? receipt : undefined; +} + +export function exportNativeHostedProfile( + receipt: NonNullable>, +) { + return NATIVE_HOSTED_PROFILES.find( + (profile) => + profile.profileId === receipt.profileId && profile.providerName === receipt.providerName, ); } @@ -154,7 +169,7 @@ export interface ObservedExportEndpointEvidence { | "openai" | "tavily" | "tavily-hermes-v1" - | "nemoclaw-nvidia-inference-v1"; + | NativeHostedProfile["profileId"]; readonly source: "builtin" | "user"; readonly scope: "" | "platform" | "workspace"; readonly resourceVersion: string; @@ -169,7 +184,7 @@ export interface ObservedExportEndpointEvidence { | { readonly kind: "builtin-profile"; readonly profileId: "nvidia" } | { readonly kind: "managed-profile"; - readonly profileId: "nemoclaw-nvidia-inference-v1"; + readonly profileId: NativeHostedProfile["profileId"]; }; } diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 88b28f33542..df3ba038d5c 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -8,12 +8,6 @@ import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/rou import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { normalizeInferenceSelection } from "../../inference/selection"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; -import { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, -} from "../../inference/native-nvidia/contract"; import type { ManagedStartupProfile } from "../../onboard/managed-startup/profile"; import { buildManagedStartupProfile, @@ -46,7 +40,7 @@ import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "../../inference/ollama/contract"; import { ExportSourceValuesSchema, exportWebSearchBinding, - exportNativeNvidiaReceipt, + exportNativeHostedReceipt, } from "./export-evidence"; import { inspectAgentInterfaces } from "./verify-agent-interfaces"; import { V1ALPHA1_RUNTIME_DEFAULTS } from "./v1alpha1-runtime-defaults"; @@ -832,37 +826,49 @@ function classifyManagedStartupProfile( return [...findings, ...classifyProfileEquality(profile, supported)]; } +function nativeEndpointEvidenceMatches(snapshot: QualifiedExportSnapshot): boolean { + const { inference } = snapshot; + const evidence = inference.endpointEvidence; + if (evidence?.source.kind !== "managed-profile") return false; + const receipt = exportNativeHostedReceipt(snapshot.registry); + const profile = nativeHostedProfile(snapshot.registry.provider); + return ( + receipt !== undefined && + profile !== undefined && + (profile.logicalProvider === "anthropic-prod" + ? inference.api === "anthropic-messages" + : inference.api === "openai-completions" || + (["openai-api", "hermes-provider"].includes(profile.logicalProvider) && + inference.api === "openai-responses")) && + isDeepStrictEqual( + [ + evidence.source.profileId, + evidence.provider.name, + evidence.provider.id, + inference.provider, + inference.endpoint, + evidence.endpoint, + inference.credentialEnv, + ], + [ + profile.profileId, + receipt.providerName, + receipt.providerId, + profile.logicalProvider, + profile.endpoint, + profile.endpoint, + profile.hostCredentialEnv ?? profile.credentialEnv, + ], + ) + ); +} + function endpointEvidenceMatchesRoute(snapshot: QualifiedExportSnapshot): boolean { const { inference } = snapshot; const evidence = inference.endpointEvidence; if (!evidence) return false; if (evidence.source.kind === "managed-profile") { - const receipt = exportNativeNvidiaReceipt(snapshot.registry); - return ( - receipt !== undefined && - isDeepStrictEqual( - [ - evidence.source.profileId, - evidence.provider.name, - evidence.provider.id, - inference.provider, - inference.api, - inference.endpoint, - evidence.endpoint, - inference.credentialEnv, - ], - [ - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - receipt.providerName, - receipt.providerId, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - "openai-completions", - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_CREDENTIAL_ENV, - ], - ) - ); + return nativeEndpointEvidenceMatches(snapshot); } if (evidence.source.kind === "builtin-profile") { return ( @@ -937,7 +943,7 @@ function validateSandboxIdentity( function sandboxProviderAttachmentsMatch(snapshot: QualifiedExportSnapshot): boolean { const { registry: entry, sandbox, inference } = snapshot; - const nativeReceipt = exportNativeNvidiaReceipt(entry); + const nativeReceipt = exportNativeHostedReceipt(entry); const inferenceAttachment = nativeReceipt?.providerName ?? inference.provider; const additionalProviders = sandbox.providerNames.filter((name) => name !== inferenceAttachment); const webSearch = exportWebSearchBinding(entry); @@ -1248,7 +1254,7 @@ function validateInferenceRepresentation(snapshot: QualifiedExportSnapshot): Exp } function expectedEndpointProviderName(snapshot: QualifiedExportSnapshot): string { - return exportNativeNvidiaReceipt(snapshot.registry)?.providerName ?? snapshot.inference.provider; + return exportNativeHostedReceipt(snapshot.registry)?.providerName ?? snapshot.inference.provider; } function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFinding[] { diff --git a/src/lib/inference/native-hosted/profiles.ts b/src/lib/inference/native-hosted/profiles.ts index c7aa430d477..1e62ceb0297 100644 --- a/src/lib/inference/native-hosted/profiles.ts +++ b/src/lib/inference/native-hosted/profiles.ts @@ -4,7 +4,7 @@ export interface NativeHostedProfile { readonly label: string; readonly logicalProvider: string; - readonly profileId: string; + readonly profileId: `nemoclaw-${"nvidia" | "openai" | "anthropic" | "gemini" | "openrouter" | "hermes"}-inference-v1`; readonly providerName: string; readonly endpoint: string; // Host credentials can use a different name from the OpenShell profile binding. From 2404ed060f477ea409a56babdc4250d6bc04c663 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 16:19:18 -0700 Subject: [PATCH 097/133] fix(config): bind export evidence to validated profile Signed-off-by: Deepak Jain --- src/lib/adapters/config/live-export-source.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index 2712b908221..a336be94e14 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -257,7 +257,12 @@ function endpointSourceFor( builtin: boolean, configKey: "ANTHROPIC_BASE_URL" | "OPENAI_BASE_URL", ): ObservedExportEndpointEvidence["source"] { - if (nativeReceipt) return { kind: "managed-profile", profileId: nativeReceipt.profileId }; + if (nativeReceipt) { + const profile = exportNativeHostedProfile(nativeReceipt); + if (!profile) + throw new Error("The native hosted export receipt does not match a managed profile."); + return { kind: "managed-profile", profileId: profile.profileId }; + } if (builtin) return { kind: "builtin-profile", profileId: "nvidia" }; return { kind: "provider-config", key: configKey }; } From ffded84e0f5846c19241df692452ca89cb43f862 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 16:32:48 -0700 Subject: [PATCH 098/133] fix(config): preserve unchanged Pi profile inputs Signed-off-by: Deepak Jain --- src/lib/adapters/openshell/providers.ts | 2 +- src/lib/domain/config/export-evidence.ts | 7 +------ src/lib/inference/native-hosted/profiles.ts | 2 +- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index 628ac4e2a34..2df25fb8119 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -54,7 +54,7 @@ export type Provider = Readonly< profileWorkspace?: string; // null records a successful not-found read at the OpenAI provider's profile binding. managedProfile?: Readonly<{ - id: ManagedProfileContract | NativeHostedProfile["profileId"]; + id: NativeHostedProfile["profileId"]; source: "builtin" | "user"; scope: "" | "platform" | "workspace"; resourceVersion: string; diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index 39acf4247c7..d7ec7da7e2e 100644 --- a/src/lib/domain/config/export-evidence.ts +++ b/src/lib/domain/config/export-evidence.ts @@ -164,12 +164,7 @@ export interface ObservedExportEndpointEvidence { readonly profileWorkspace?: string; /** null means the OpenAI profile was read at its binding and confirmed absent. */ readonly managedProfile?: { - readonly id: - | "brave" - | "openai" - | "tavily" - | "tavily-hermes-v1" - | NativeHostedProfile["profileId"]; + readonly id: NativeHostedProfile["profileId"]; readonly source: "builtin" | "user"; readonly scope: "" | "platform" | "workspace"; readonly resourceVersion: string; diff --git a/src/lib/inference/native-hosted/profiles.ts b/src/lib/inference/native-hosted/profiles.ts index 1e62ceb0297..c7aa430d477 100644 --- a/src/lib/inference/native-hosted/profiles.ts +++ b/src/lib/inference/native-hosted/profiles.ts @@ -4,7 +4,7 @@ export interface NativeHostedProfile { readonly label: string; readonly logicalProvider: string; - readonly profileId: `nemoclaw-${"nvidia" | "openai" | "anthropic" | "gemini" | "openrouter" | "hermes"}-inference-v1`; + readonly profileId: string; readonly providerName: string; readonly endpoint: string; // Host credentials can use a different name from the OpenShell profile binding. From 711b8efec3d61af920d49f4b053848b10b7199e3 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 16:43:07 -0700 Subject: [PATCH 099/133] test(deepagents): consolidate native constructor coverage Signed-off-by: Deepak Jain --- ...epagents-code-managed-model-params.test.ts | 61 ++++++++++++++++- ...-deepagents-code-native-credential.test.ts | 65 ------------------- 2 files changed, 59 insertions(+), 67 deletions(-) delete mode 100644 test/agents/deepagents/langchain-deepagents-code-native-credential.test.ts diff --git a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts index 978d0f6c402..1075e3e258a 100644 --- a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts @@ -1,17 +1,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterAll, afterEach, describe, expect, it } from "vitest"; import { + cleanupCachedPatchedFixture, cleanupPackageFixtures, + createPatchedPackageFixture, createPackageFixture, patchFixture, } from "../../helpers/langchain-deepagents-code-patch-fixture"; afterEach(cleanupPackageFixtures); +afterAll(cleanupCachedPatchedFixture); const e2eProfileCheckPath = path.join( process.cwd(), @@ -115,3 +118,57 @@ print("managed-ultra-template-argument-ok") expect(reportedResult).toBeGreaterThan(resolverContract); }); }); + +describe("native inference issued credentials", () => { + it.each([ + ["nvidia-prod", "https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"], + ["openai-api", "https://api.openai.com/v1", "OPENAI_API_KEY"], + ["anthropic-prod", "https://api.anthropic.com", "ANTHROPIC_API_KEY"], + ["gemini-api", "https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"], + ["openrouter-api", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"], + ["hermes-provider", "https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY"], + ])("binds %s constructor credentials to the issued scoped handle", (provider, endpoint, key) => { + const tempDir = createPatchedPackageFixture(); + const result = spawnSync( + "python3", + [ + "-c", + ` +import os +from pathlib import Path +from deepagents_code import config, _nemoclaw_managed as managed +for name, value in [("managed-upstream-provider", ${JSON.stringify(provider)}), ("managed-inference-base-url", ${JSON.stringify(endpoint)})]: + target = Path(${JSON.stringify(tempDir)}) / name + target.chmod(0o644) + target.write_text(value + "\\n") + target.chmod(0o444) +key = ${JSON.stringify(key)} +for value in ["openshell:resolve:env:v42_" + key, "openshell:resolve:env:s" + "a" * 64 + "_" + key]: + os.environ[key] = value + assert config._get_provider_kwargs("openai")["api_key"] == value +for value in ["", "raw-secret-do-not-print", "openshell:resolve:env:" + key, "openshell:resolve:env:v42_OTHER_KEY"]: + os.environ[key] = value + try: + config._get_provider_kwargs("openai") + except RuntimeError as error: + assert str(error) == "Native inference requires an issued OpenShell credential handle" + else: + raise AssertionError("unsafe credential accepted") +del os.environ[key] +try: + config._get_provider_kwargs("openai") +except RuntimeError: + pass +else: + raise AssertionError("missing credential accepted") +`, + ], + { + env: { PATH: process.env.PATH, PYTHONPATH: tempDir }, + encoding: "utf8", + }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout + result.stderr).not.toContain("raw-secret-do-not-print"); + }); +}); diff --git a/test/agents/deepagents/langchain-deepagents-code-native-credential.test.ts b/test/agents/deepagents/langchain-deepagents-code-native-credential.test.ts deleted file mode 100644 index 919a71433fa..00000000000 --- a/test/agents/deepagents/langchain-deepagents-code-native-credential.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; -import { afterAll, afterEach, describe, expect, it } from "vitest"; -import { - cleanupCachedPatchedFixture, - cleanupPackageFixtures, - createPatchedPackageFixture, -} from "../../helpers/langchain-deepagents-code-patch-fixture"; -afterEach(cleanupPackageFixtures); -afterAll(cleanupCachedPatchedFixture); - -describe("native inference issued credentials", () => { - it.each([ - ["nvidia-prod", "https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"], - ["openai-api", "https://api.openai.com/v1", "OPENAI_API_KEY"], - ["anthropic-prod", "https://api.anthropic.com", "ANTHROPIC_API_KEY"], - ["gemini-api", "https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"], - ["openrouter-api", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"], - ["hermes-provider", "https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY"], - ])("binds %s constructor credentials to the issued scoped handle", (provider, endpoint, key) => { - const tempDir = createPatchedPackageFixture(); - const result = spawnSync( - "python3", - [ - "-c", - ` -import os -from pathlib import Path -from deepagents_code import config, _nemoclaw_managed as managed -for name, value in [("managed-upstream-provider", ${JSON.stringify(provider)}), ("managed-inference-base-url", ${JSON.stringify(endpoint)})]: - target = Path(${JSON.stringify(tempDir)}) / name - target.chmod(0o644) - target.write_text(value + "\\n") - target.chmod(0o444) -key = ${JSON.stringify(key)} -for value in ["openshell:resolve:env:v42_" + key, "openshell:resolve:env:s" + "a" * 64 + "_" + key]: - os.environ[key] = value - assert config._get_provider_kwargs("openai")["api_key"] == value -for value in ["", "raw-secret-do-not-print", "openshell:resolve:env:" + key, "openshell:resolve:env:v42_OTHER_KEY"]: - os.environ[key] = value - try: - config._get_provider_kwargs("openai") - except RuntimeError as error: - assert str(error) == "Native inference requires an issued OpenShell credential handle" - else: - raise AssertionError("unsafe credential accepted") -del os.environ[key] -try: - config._get_provider_kwargs("openai") -except RuntimeError: - pass -else: - raise AssertionError("missing credential accepted") -`, - ], - { - env: { PATH: process.env.PATH, PYTHONPATH: tempDir }, - encoding: "utf8", - }, - ); - expect(result.status, result.stderr).toBe(0); - expect(result.stdout + result.stderr).not.toContain("raw-secret-do-not-print"); - }); -}); From 33ef375b3faf606ec39c6a7d03d396c964638ad7 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 16:45:52 -0700 Subject: [PATCH 100/133] docs(config): clarify native export fallback refusal Signed-off-by: Deepak Jain --- src/lib/adapters/config/live-export-source.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index a336be94e14..0e4cb4c1d34 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -103,8 +103,8 @@ function sandboxIdentity(row: Sandbox): ObservedExportSandboxIdentity { } async function readInferenceRoute(entry: Readonly, gatewayName: string) { - // The v1 exporter cannot represent workspace profile attachments yet. - // Never substitute the unrelated gateway route for a native selection. + // Recognized native receipts use the native export path. Refuse an unmatched + // attachment here rather than substituting the unrelated shared gateway route. if (entry.nativeHostedProviderAttachment) { throw new Error("Native provider attachment export is not supported."); } From 96b7ca0e237a3467ab291508c386a545475d1e34 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 16:58:46 -0700 Subject: [PATCH 101/133] fix(inference): close native NVIDIA lifecycle review gaps Signed-off-by: Deepak Jain --- .../actions/credentials-native-reset.test.ts | 51 ++++++++++++++++++- src/lib/actions/credentials/reset.ts | 31 +++++++++++ src/lib/actions/inference-get.test.ts | 27 ++++++++++ src/lib/actions/inference-get.ts | 13 +++-- src/lib/actions/inference-route-api.test.ts | 15 ++++++ src/lib/actions/inference-route-api.ts | 7 ++- .../inference-set-openclaw-run.test.ts | 43 ++++++++++++++-- .../inference-set-route-containment.ts | 14 +++++ src/lib/actions/inference-set.ts | 2 +- .../orchestration-native-nvidia.test.ts | 23 ++++++--- .../onboard/sandbox-create/orchestration.ts | 12 ++++- 11 files changed, 220 insertions(+), 18 deletions(-) diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index 37c9a814ba3..f717d309843 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -102,10 +102,59 @@ describe("native NVIDIA credential reset ownership", () => { expect(listNativeNvidiaProviderAttachmentSandboxNames).toHaveBeenCalledExactlyOnceWith( "nemoclaw", ); - expect(deleteProvider).toHaveBeenCalledOnce(); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + "nemoclaw-nvidia-prod-v1", + "nvidia-prod", + ]); expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledExactlyOnceWith("nemoclaw"); }); + it("keeps explicit native identity reset separate from legacy removal", async () => { + const deleteProvider = vi.fn(async () => ({ + ok: true, + })); + await runCredentialsResetAction( + { provider: "nemoclaw-nvidia-prod-v1", confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeNvidiaProviderAuthority: vi.fn(), + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gateway, operation) => operation(), + }, + ); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + "nemoclaw-nvidia-prod-v1", + ]); + }); + + it.each(["nemoclaw-nvidia-prod-v1", "nvidia-prod"])( + "preserves authority when deleting %s fails", + async (failedName) => { + const deleteProvider = vi.fn(async (input) => + input.providerName === failedName + ? { ok: false, error: { kind: "command", reason: "failed", message: "delete failed" } } + : { ok: true }, + ); + const clearNativeNvidiaProviderAuthority = vi.fn(); + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gateway, operation) => operation(), + }, + ); + expect(result.exitCode).toBe(1); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + "nemoclaw-nvidia-prod-v1", + "nvidia-prod", + ]); + expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(result.failureLines.join("\n")).toContain(failedName); + }, + ); + it("fails closed before reset when registry ownership cannot be read", async () => { const deleteProvider = vi.fn(); const clearNativeNvidiaProviderAuthority = vi.fn(); diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 44b88d161b1..c92e53988bf 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -182,6 +182,37 @@ export async function runCredentialsResetAction( } } + if (key === NVIDIA_HOSTED_LOGICAL_PROVIDER) { + const lines: string[] = []; + let complete = true; + for (const name of [NVIDIA_HOSTED_NATIVE_PROVIDER, NVIDIA_HOSTED_LOGICAL_PROVIDER]) { + const result = await deleteProviderWithRecovery(name, target, providerAdapter, { + detachAttached: false, + }); + if (!result.ok && result.error?.kind === "command" && result.error.reason === "not_found") { + lines.push(` Provider '${name}' is already absent from the OpenShell gateway.`); + } else { + const outcome = formatResetOutcome( + !result.ok && result.error?.kind === "command" && result.error.reason === "attached" + ? publicKey + : name, + result, + target.gatewayName, + ); + lines.push(...outcome.lines); + complete = outcome.ok && complete; + if (!result.ok && result.error?.kind === "command" && result.error.reason === "attached") + return fail(lines); + } + } + if (!complete) return fail(lines); + forgetExtraProvider(publicKey); + (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( + target.gatewayName, + ); + return ok(lines); + } + const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter, { detachAttached: !nativeNvidiaProvider, }); diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index e60ba29acf7..dc60abcbe48 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -924,6 +924,33 @@ describe("runInferenceGet", () => { }, ); + it.each( + ["default", "named"].flatMap((lookup) => + [false, true].map((permission) => ({ lookup, permission })), + ), + )( + "maps $lookup registry lookup errors with permission=$permission to recovery guidance", + async ({ lookup, permission }) => { + const deps = createDeps({ ok: true, value: { state: "unconfigured" } }); + const fail = () => { + throw permission + ? new ConfigPermissionError("/safe/state/sandboxes.json", "read") + : new ConfigCorruptError("/safe/state/sandboxes.json"); + }; + deps.getDefaultSandbox = lookup === "default" ? fail : () => "alpha"; + deps.getSandbox = fail; + await expect(runInferenceGet({}, deps)).rejects.toMatchObject({ + name: "InferenceGetError", + message: expect.stringContaining( + permission + ? "Cannot read config file: /safe/state/sandboxes.json" + : "Configuration file is present but is not valid JSON: /safe/state/sandboxes.json", + ), + }); + expect(deps.observeInferenceRoute).not.toHaveBeenCalled(); + }, + ); + it("sanitizes route values only for human-readable output", async () => { const deps = createDeps(configuredRoute("openai\u001b[2J", "gpt\u0007-5.4")); diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index fa0e0ffc070..ed87d68911b 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -309,10 +309,15 @@ export async function runInferenceGet( options: InferenceGetOptions = {}, deps: InferenceGetDeps = defaultDeps(), ): Promise { - const selectedSandboxName = options.sandboxName ?? deps.getDefaultSandbox?.() ?? null; - const selectedSandbox = selectedSandboxName - ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) - : null; + let selectedSandbox: ReturnType | null; + try { + const selectedSandboxName = options.sandboxName ?? deps.getDefaultSandbox?.() ?? null; + selectedSandbox = selectedSandboxName + ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) + : null; + } catch (error) { + throw new InferenceGetError(formatGatewayResolutionFailure(error, options.sandboxName)); + } if ( selectedSandbox && isNativeNvidiaProvider(selectedSandbox.provider) && diff --git a/src/lib/actions/inference-route-api.test.ts b/src/lib/actions/inference-route-api.test.ts index a0413a92882..af0e0ea4cf9 100644 --- a/src/lib/actions/inference-route-api.test.ts +++ b/src/lib/actions/inference-route-api.test.ts @@ -94,6 +94,21 @@ describe("readOpenClawPrimaryRouteApi", () => { }); describe("resolveRuntimeInferenceApi", () => { + it("uses native NVIDIA Completions despite stale route history", () => { + expect( + resolve( + {}, + { + provider: "nvidia-prod", + currentProvider: "nvidia-prod", + session: session({ + provider: "nvidia-prod", + preferredInferenceApi: "anthropic-messages", + }), + }, + ), + ).toBe("openai-completions"); + }); it("uses the current config route API before matching onboard history", () => { expect( resolve( diff --git a/src/lib/actions/inference-route-api.ts b/src/lib/actions/inference-route-api.ts index bee719cbdbf..59fe9c521ab 100644 --- a/src/lib/actions/inference-route-api.ts +++ b/src/lib/actions/inference-route-api.ts @@ -1,7 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { getSandboxInferenceConfig, resolveAgentInferenceApi } from "../inference/config"; +import { + getSandboxInferenceConfig, + resolveAgentInferenceApi, + isNativeNvidiaProvider, +} from "../inference/config"; import type { ConfigObject } from "../security/credential-filter"; import { isConfigObject } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; @@ -106,6 +110,7 @@ export function resolveRuntimeInferenceApi(options: { session: Session | null; }): InferenceApi | null { const { agentName, config, currentProvider, provider, sandboxName, session } = options; + if (isNativeNvidiaProvider(provider)) return "openai-completions"; if (provider === "anthropic-prod") return "anthropic-messages"; const agentApi = resolveAgentInferenceApi(agentName, provider, null); if (agentApi) return normalizeInferenceApi(agentApi); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 2228d13bd52..5ef8914882f 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -334,6 +334,43 @@ describe("runInferenceSet OpenClaw routing", () => { expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); + it("restores the peer shared route after a failed departure from native NVIDIA", async () => { + const setInferenceRoute = vi.fn< + import("../adapters/openshell/inference-route").OpenShellInferenceRouteMutator["setInferenceRoute"] + >(async () => ({ ok: true as const })); + const deps = createDeps({ + config: { models: { providers: {} } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + inferenceRouteMutator: { setInferenceRoute }, + inferenceRouteObserver: { + observeInferenceRoute: async () => ({ + ok: true, + value: { state: "configured", route: { provider: "anthropic", model: "peer-model" } }, + }), + }, + probeSandboxRoute: async () => ({ ok: false, detail: "probe refused", httpStatus: 401 }), + }); + await expect( + runInferenceSet({ provider: "openrouter-api", model: "openai/gpt-5.4" }, deps), + ).rejects.toThrow("probe refused"); + expect(setInferenceRoute.mock.calls.map(([input]) => input.route)).toEqual([ + { provider: "openrouter-api", model: "openai/gpt-5.4" }, + { provider: "anthropic", model: "peer-model" }, + ]); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + it("detaches native NVIDIA access only after another provider is healthy", async () => { let attached = true; const detachProvider = vi.fn(async () => { @@ -767,10 +804,10 @@ describe("runInferenceSet OpenClaw routing", () => { expect.objectContaining({ provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - endpointUrl: null, - credentialEnv: null, + endpointUrl: "https://integrate.api.nvidia.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", nimContainer: null, - preferredInferenceApi: null, + preferredInferenceApi: "openai-completions", nativeNvidiaProviderAttachment: expect.objectContaining({ providerName: "nemoclaw-nvidia-prod-v1", }), diff --git a/src/lib/actions/inference-set-route-containment.ts b/src/lib/actions/inference-set-route-containment.ts index 3319c39c9ed..14da9fd9e93 100644 --- a/src/lib/actions/inference-set-route-containment.ts +++ b/src/lib/actions/inference-set-route-containment.ts @@ -25,6 +25,11 @@ import { ConfigUrlValidationError } from "../sandbox/config"; import type { ConfigValue } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; import type { SandboxEntry } from "../state/registry"; +import { + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_CREDENTIAL_ENV, + isNativeNvidiaProvider, +} from "../inference/native-nvidia"; import { InferenceSetError } from "./inference-set-error"; /** @@ -381,6 +386,15 @@ function registryMetadataForProviderSwitch(options: { }): RegistryInferenceMetadata { const { entry, provider, model, sandboxName, session, explicitMetadata } = options; if (explicitMetadata) return explicitMetadata; + if (isNativeNvidiaProvider(provider)) { + return { + endpointUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + endpointSource: null, + credentialEnv: NVIDIA_HOSTED_CREDENTIAL_ENV, + preferredInferenceApi: "openai-completions", + nimContainer: null, + }; + } if (entry.provider === provider) { return { endpointUrl: entry.endpointUrl ?? null, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 9d50e1fb6bc..a0d4b14e500 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1585,7 +1585,7 @@ async function runInferenceSetWithoutHostLock( let previousNativeNvidiaDetached = false; let previousNativeNvidiaDetachCommitted = false; const restorePreviousInferenceSelection = async (): Promise => { - if (selectingNativeNvidia || previousNativeNvidiaAttachment) { + if (selectingNativeNvidia) { appliedInferenceSelection = false; return null; } diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index d33208f7c6a..2d11c1ed280 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -28,17 +28,19 @@ function providerAdapter(providerId: string): OpenShellProviderAdapter { } as unknown as OpenShellProviderAdapter; } -function nativeProviderBoundary(adapter: OpenShellProviderAdapter) { +function nativeProviderBoundary(adapter: OpenShellProviderAdapter, missingReceipt = false) { return createProviderEffectBoundary({ deferred: false, sandboxName: "alpha", gatewayName: "nemoclaw", - expectedNativeNvidiaProviderAttachment: { - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: recordedProviderId, - }, + expectedNativeNvidiaProviderAttachment: missingReceipt + ? undefined + : { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: recordedProviderId, + }, preparationInput: { openshellDriver: "docker", inferenceProvider: "nemoclaw-nvidia-prod-v1", @@ -71,6 +73,13 @@ function verifiedCreateContext(revalidateSandboxIdentity = vi.fn()) { } describe("native NVIDIA post-create provider verification", () => { + it("rejects a missing native receipt before creation", async () => { + const boundary = nativeProviderBoundary(providerAdapter(recordedProviderId), true); + await expect(boundary.validateBeforeCreate()).rejects.toThrow( + "native NVIDIA provider identity receipt", + ); + }); + it("confirms the recorded provider is attached after sandbox identity is verified", async () => { const adapter = providerAdapter(recordedProviderId); const revalidateSandboxIdentity = vi.fn(); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index f1093b70c09..e1c8a1e629f 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1451,7 +1451,17 @@ export function createProviderEffectBoundary(input: { }; if (!input.deferred) { return { - validateBeforeCreate: validate, + validateBeforeCreate: async () => { + if ( + usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) && + !input.expectedNativeNvidiaProviderAttachment + ) { + throw new Error( + `Sandbox '${input.sandboxName}' is missing its native NVIDIA provider identity receipt.`, + ); + } + await validate(); + }, publishBeforeCreate: async () => { input.revalidateSandboxIdentityBeforeCreate(); await publish(); From d92ffc97125d0f9fb7566209988966ff73e9c835 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 17:20:45 -0700 Subject: [PATCH 102/133] fix(inference): restore routes on registry publication failure Signed-off-by: Deepak Jain --- .../inference-set-openclaw-run.test.ts | 69 +++++++++++++++++++ src/lib/actions/inference-set.ts | 49 +++++++++---- .../cli/credentials-cli-command.test.ts | 12 ++-- 3 files changed, 112 insertions(+), 18 deletions(-) diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 5ef8914882f..14c88af5a76 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -371,6 +371,75 @@ describe("runInferenceSet OpenClaw routing", () => { expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); + it.each([ + { failure: "registry", configure: (_deps: ReturnType) => {} }, + { + failure: "rollback", + configure: (deps: ReturnType) => { + vi.mocked(deps.inferenceRouteMutator.setInferenceRoute) + .mockResolvedValueOnce({ ok: true }) + .mockRejectedValueOnce(new Error("route restore denied")); + vi.mocked(deps.providerAdapter.attachProvider).mockRejectedValueOnce( + new Error("attachment restore denied"), + ); + }, + }, + { + failure: "config", + configure: (deps: ReturnType) => { + deps.calls.setOpenClawConfigValues.mockImplementation(() => { + throw new Error("config sync denied"); + }); + }, + }, + ])( + "preserves the correct rollback boundary for $failure failure", + async ({ failure, configure }) => { + const setInferenceRoute = vi.fn< + import("../adapters/openshell/inference-route").OpenShellInferenceRouteMutator["setInferenceRoute"] + >(async () => ({ ok: true as const })); + const deps = createDeps({ + config: { models: { providers: {} } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + inferenceRouteMutator: { setInferenceRoute }, + inferenceRouteObserver: { + observeInferenceRoute: async () => ({ + ok: true, + value: { state: "configured", route: { provider: "anthropic", model: "peer-model" } }, + }), + }, + updateSandbox: () => failure === "config", + }); + const attachProvider = vi.spyOn(deps.providerAdapter, "attachProvider"); + configure(deps); + await expect( + runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps), + ).rejects.toThrow( + failure === "rollback" + ? /Failed to update NemoClaw registry.*route restore denied.*attachment restore denied/su + : failure === "config" + ? /config sync denied/su + : /Failed to update NemoClaw registry/u, + ); + expect(setInferenceRoute.mock.calls.map(([input]) => input.route)).toEqual([ + { provider: "openai-api", model: "gpt-5.4" }, + ...(failure === "config" ? [] : [{ provider: "anthropic", model: "peer-model" }]), + ]); + expect(attachProvider).toHaveBeenCalledTimes(failure === "config" ? 0 : 1); + }, + ); + it("detaches native NVIDIA access only after another provider is healthy", async () => { let attached = true; const detachProvider = vi.fn(async () => { diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index a0d4b14e500..11e87018c4c 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1043,26 +1043,48 @@ function nativeNvidiaDepartureRegistryFields( async function restorePreviousNativeNvidiaAfterFailedPublish(input: { detached: boolean; committed: boolean; + routeApplied: boolean; + routeAmbiguous: boolean; + restoreRoute: () => Promise; previousAttachment?: NativeNvidiaProviderAttachment; gatewayName: string; sandboxName: string; error: unknown; deps: InferenceSetDeps; }): Promise { - if (!input.detached || input.committed || !input.previousAttachment) return; - try { - await ensureNativeNvidiaProviderAttached({ - adapter: input.deps.providerAdapter, - target: { kind: "named", gatewayName: input.gatewayName }, - sandboxName: input.sandboxName, - expected: input.previousAttachment, - }); - } catch (reattachError) { + if (input.committed || !input.previousAttachment) return; + const recoveryErrors: string[] = []; + if (input.routeApplied && !input.routeAmbiguous) { + try { + const failure = await input.restoreRoute(); + if (failure) + recoveryErrors.push( + `Failed to restore the previous OpenShell inference selection: ${failure}`, + ); + } catch (error) { + recoveryErrors.push( + `Failed to restore the previous OpenShell inference selection: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + if (input.detached) { + try { + await ensureNativeNvidiaProviderAttached({ + adapter: input.deps.providerAdapter, + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: input.previousAttachment, + }); + } catch (error) { + recoveryErrors.push( + `Native NVIDIA access was detached before the failed switch, but restoring the attachment failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + if (recoveryErrors.length > 0) { const detail = input.error instanceof Error ? input.error.message : String(input.error); - const recoveryDetail = - reattachError instanceof Error ? reattachError.message : String(reattachError); throw new InferenceSetError( - `${detail}\n Native NVIDIA access was detached before the failed switch, but restoring the attachment failed: ${recoveryDetail}`, + `${detail}\n ${recoveryErrors.join("\n ")}`, input.error instanceof InferenceSetError ? input.error.exitCode : 1, ); } @@ -2004,6 +2026,9 @@ async function runInferenceSetWithoutHostLock( await restorePreviousNativeNvidiaAfterFailedPublish({ detached: previousNativeNvidiaDetached, committed: previousNativeNvidiaDetachCommitted, + routeApplied: appliedInferenceSelection, + routeAmbiguous: ambiguousInferenceSelection, + restoreRoute: restorePreviousInferenceSelection, previousAttachment: previousNativeNvidiaAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index 702a58f0802..744f071115b 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -336,7 +336,7 @@ describe("credentials oclif commands", () => { expect(runOpenshell).not.toHaveBeenCalled(); }); - it("deletes a provider credential with --yes", async () => { + it("deletes native and legacy NVIDIA provider credentials with --yes", async () => { const calls = installRuntimeBridge({ runOpenshell: (args, opts) => { calls.push({ args, opts }); @@ -347,9 +347,9 @@ describe("credentials oclif commands", () => { const output = await captureOutput(() => CredentialsResetCommand.run(["nvidia-prod", "--yes"])); - expect(calls).toEqual([ - { - args: ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + expect(calls).toEqual( + ["nemoclaw-nvidia-prod-v1", "nvidia-prod"].map((providerName) => ({ + args: ["provider", "delete", "-g", "nemoclaw", providerName], opts: { env: expect.any(Object), ignoreError: true, @@ -358,8 +358,8 @@ describe("credentials oclif commands", () => { suppressOutput: true, timeout: 30_000, }, - }, - ]); + })), + ); expect(output.stdout).toContain("Removed provider 'nvidia-prod'"); expect(output.stdout).toContain("Rerun 'nemoclaw onboard'"); }); From 6e71fbbc3dd1ebcfb2dfbeb67f7cea2aa80aa3a1 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 17:47:09 -0700 Subject: [PATCH 103/133] fix(inference): keep detached authority at gateway scope Signed-off-by: Deepak Jain --- .../inference-set-openclaw-run.test.ts | 6 ---- src/lib/actions/inference-set.ts | 8 ----- ...egistry-native-provider-attachment.test.ts | 34 +++++++++++++++---- src/lib/state/registry-normalization.test.ts | 28 +++++++++++---- src/lib/state/registry.ts | 13 ------- .../native-nvidia-provider-authority.ts | 15 +------- src/lib/state/registry/persistence.ts | 18 ++++------ src/lib/state/registry/route-reservation.ts | 1 - src/lib/state/registry/types.ts | 2 -- 9 files changed, 58 insertions(+), 67 deletions(-) diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index efc0158916e..784851fd45f 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -56,7 +56,6 @@ describe("runInferenceSet OpenClaw routing", () => { "alpha", expect.objectContaining({ provider: "gemini-api", - nativeHostedProviderAuthorities: expect.arrayContaining([old]), }), ); }); @@ -200,7 +199,6 @@ describe("runInferenceSet OpenClaw routing", () => { "alpha", expect.objectContaining({ nativeHostedProviderAttachment: gatewayAuthority, - nativeHostedProviderAuthorities: expect.arrayContaining([gatewayAuthority]), }), ); }); @@ -311,7 +309,6 @@ describe("runInferenceSet OpenClaw routing", () => { "alpha", expect.objectContaining({ nativeHostedProviderAttachment: receipt, - nativeHostedProviderAuthorities: expect.arrayContaining([receipt]), }), ); }); @@ -938,7 +935,6 @@ describe("runInferenceSet OpenClaw routing", () => { model: "nvidia/old-model", nativeNvidiaProviderAttachment: attachment, nativeHostedProviderAttachment: attachment, - nativeHostedProviderAuthorities: [attachment], }; const updateSandbox = vi.fn((name: string, updates: Record) => { expect(name).toBe(entry.name); @@ -960,7 +956,6 @@ describe("runInferenceSet OpenClaw routing", () => { expect(entry).toMatchObject({ provider: "openai-api", - nativeHostedProviderAuthorities: expect.arrayContaining([attachment]), }); expect(entry.nativeNvidiaProviderAttachment).toBeUndefined(); expect(entry.nativeHostedProviderAttachment).toMatchObject({ @@ -975,7 +970,6 @@ describe("runInferenceSet OpenClaw routing", () => { expect(entry).toMatchObject({ provider: "nvidia-prod", nativeHostedProviderAttachment: attachment, - nativeHostedProviderAuthorities: expect.arrayContaining([attachment]), }); }); diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 622786207a2..09e02f1b102 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -24,7 +24,6 @@ import { normalizeNativeHostedProviderAttachment, normalizeNativeNvidiaProviderAttachment, resolveGatewayNativeHostedProviderAuthority, - retainNativeHostedProviderAuthority, resolveAgentInferenceApi, type NativeHostedProviderAttachment, type SandboxInferenceConfig, @@ -1904,13 +1903,6 @@ async function runInferenceSetWithoutHostLock( ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), nativeHostedProviderAttachment, nativeNvidiaProviderAttachment: undefined, - nativeHostedProviderAuthorities: retainNativeHostedProviderAuthority( - retainNativeHostedProviderAuthority( - entry.nativeHostedProviderAuthorities, - previousNativeHostedAttachment, - ), - nativeHostedProviderAttachment, - ), }); if ( !deps.updateSandbox( diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index 78333508089..e86b5d1adac 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -79,7 +79,7 @@ it("clears a stale native NVIDIA attachment when reserving a shared route", asyn } }); -it("retains hosted ownership across reload and clears it when moving gateways", async () => { +it("keeps gateway ownership without treating detached history as an active attachment", async () => { const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-hosted-authority-")); vi.stubEnv("HOME", home); vi.resetModules(); @@ -104,8 +104,13 @@ it("retains hosted ownership across reload and clears it when moving gateways", provider: "openai-api", model: "selected-model", nativeHostedProviderAttachment: openai, - nativeHostedProviderAuthorities: [nvidia, openai], }); + registry.setNativeHostedProviderAuthority("nemoclaw", nvidia); + registry.setNativeHostedProviderAuthority("nemoclaw", openai); + const registryPath = path.join(home, ".nemoclaw", "sandboxes.json"); + const legacy = JSON.parse(await fs.readFile(registryPath, "utf8")); + legacy.sandboxes.alpha.nativeHostedProviderAuthorities = [nvidia, openai]; + await fs.writeFile(registryPath, JSON.stringify(legacy)); vi.resetModules(); const reloaded = await import("./registry"); const authority = await import("./registry/native-nvidia-provider-authority"); @@ -114,13 +119,12 @@ it("retains hosted ownership across reload and clears it when moving gateways", ).toEqual(["alpha"]); expect( authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "nemoclaw"), - ).toEqual(["alpha"]); + ).toEqual([]); expect( authority.listNativeHostedProviderAttachmentSandboxNames(openai.profileId, "other-gateway"), ).toEqual([]); expect(reloaded.getSandbox("alpha")).toMatchObject({ nativeHostedProviderAttachment: openai, - nativeHostedProviderAuthorities: [nvidia, openai], }); reloaded.registerSandbox({ ...reloaded.getSandbox("alpha")!, @@ -135,7 +139,22 @@ it("retains hosted ownership across reload and clears it when moving gateways", gatewayName: "nemoclaw", }); expect(reloaded.getSandbox("alpha")?.nativeHostedProviderAttachment).toBeUndefined(); - expect(reloaded.getSandbox("alpha")?.nativeHostedProviderAuthorities).toEqual([nvidia, openai]); + expect(reloaded.getSandbox("alpha")).not.toHaveProperty("nativeHostedProviderAuthorities"); + expect(reloaded.getNativeHostedProviderAuthority("nemoclaw", nvidia.profileId)).toEqual(nvidia); + reloaded.updateSandbox("alpha", { pendingNativeHostedProviderDetach: nvidia }); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "nemoclaw"), + ).toEqual(["alpha"]); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "other-gateway"), + ).toEqual([]); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(openai.profileId, "nemoclaw"), + ).toEqual(["beta"]); + reloaded.updateSandbox("alpha", { pendingNativeHostedProviderDetach: undefined }); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "nemoclaw"), + ).toEqual([]); reloaded.reserveSandboxInferenceRoute("beta", { provider: "ollama-local", model: "local-model", @@ -144,7 +163,10 @@ it("retains hosted ownership across reload and clears it when moving gateways", preferredInferenceApi: "openai-completions", gatewayName: "nemoclaw-9090", }); - expect(reloaded.getSandbox("beta")?.nativeHostedProviderAuthorities).toBeUndefined(); + expect(reloaded.getSandbox("beta")).not.toHaveProperty("nativeHostedProviderAuthorities"); + const saved = JSON.parse(await fs.readFile(registryPath, "utf8")); + expect(saved.sandboxes.alpha).not.toHaveProperty("nativeHostedProviderAuthorities"); + expect(reloaded.getNativeHostedProviderAuthority("nemoclaw", nvidia.profileId)).toEqual(nvidia); } finally { await fs.rm(home, { recursive: true, force: true }); vi.unstubAllEnvs(); diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index e3d745f83cb..e64cfd6972f 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -39,6 +39,24 @@ afterEach(() => { }); describe("sandbox registry normalization", () => { + it("rejects malformed legacy hosted history without rewriting or promoting it", async () => { + const document = { + sandboxes: { + alpha: { + name: "alpha", + gatewayName: "nemoclaw", + provider: "ollama-local", + nativeHostedProviderAuthorities: [{ profileId: "nemoclaw-openai-inference-v1" }], + }, + }, + }; + const { home, registry } = await loadRegistryDocument(document); + expect(() => registry.getSandbox("alpha")).toThrow("Invalid native provider ownership receipt"); + expect( + JSON.parse(fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8")), + ).toEqual(document); + }); + it("migrates NVIDIA ownership to one durable authority and shares compatibility API cleanup", async () => { const receipt = { schemaVersion: 1 as const, @@ -126,17 +144,15 @@ describe("sandbox registry normalization", () => { name: "retired", gatewayName: "first", provider: "ollama-local", - nativeHostedProviderAuthorities: [openai, anthropic], }); registry.registerSandbox({ name: "other", gatewayName: "second", provider: "ollama-local", - nativeHostedProviderAuthorities: [openai], }); registry.clearNativeHostedProviderAuthority("first", openai.profileId); - expect(registry.getSandbox("retired")?.nativeHostedProviderAuthorities).toEqual([anthropic]); - expect(registry.getSandbox("other")?.nativeHostedProviderAuthorities).toEqual([openai]); + expect(registry.getSandbox("retired")).not.toHaveProperty("nativeHostedProviderAuthorities"); + expect(registry.getSandbox("other")).not.toHaveProperty("nativeHostedProviderAuthorities"); expect(registry.getNativeHostedProviderAuthority("first", openai.profileId)).toBeUndefined(); expect(registry.getNativeHostedProviderAuthority("first", anthropic.profileId)).toEqual( anthropic, @@ -256,10 +272,10 @@ describe("sandbox registry normalization", () => { }); registry.clearNativeNvidiaProviderAuthority("nemoclaw-19080"); expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toBeUndefined(); - expect(registry.getSandbox("alpha")?.nativeHostedProviderAuthorities).toBeUndefined(); + expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeHostedProviderAuthorities"); expect(registry.getSandbox("beta")).not.toHaveProperty("nativeNvidiaProviderAuthority"); expect(registry.getSandbox("beta")?.nativeHostedProviderAttachment).toEqual(receipt); - expect(registry.getSandbox("gamma")?.nativeHostedProviderAuthorities).toBeUndefined(); + expect(registry.getSandbox("gamma")).not.toHaveProperty("nativeHostedProviderAuthorities"); expect(registry.getSandbox("gamma")).not.toHaveProperty("nativeNvidiaProviderAuthority"); }); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 63a84094a74..8d16b12be53 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -11,7 +11,6 @@ import { import { normalizeNativeNvidiaProviderAttachment, normalizeNativeHostedProviderAttachment, - retainNativeHostedProviderAuthority, } from "../inference/native-hosted"; import { parseServingProfileProvenance } from "../inference/serving/profile-provenance"; @@ -549,10 +548,6 @@ export function registerSandbox( ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), - nativeHostedProviderAuthorities: retainNativeHostedProviderAuthority( - entry.nativeHostedProviderAuthorities, - nativeHostedProviderAttachment, - ), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), lifecycleGeneration: entry.lifecycleGeneration, lifecycleLiveIdentityFingerprint: entry.lifecycleLiveIdentityFingerprint, @@ -605,7 +600,6 @@ type SandboxInferenceRouteReservation = Pick< hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; - nativeHostedProviderAuthorities?: SandboxEntry["nativeHostedProviderAuthorities"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; }; @@ -767,13 +761,6 @@ export function reserveSandboxInferenceRoute( (existing?.gatewayName === route.gatewayName && existing?.provider === normalized.provider ? existing.nativeHostedProviderAttachment : undefined), - nativeHostedProviderAuthorities: retainNativeHostedProviderAuthority( - route.nativeHostedProviderAuthorities ?? - (existing?.gatewayName === route.gatewayName - ? existing.nativeHostedProviderAuthorities - : undefined), - nativeHostedProviderAttachment, - ), gatewayName: route.gatewayName, gatewayPort: diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index 20c81a2dbe2..a138eab1a4a 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -94,19 +94,6 @@ function removeHostedAuthority( else delete data.gatewayNativeHostedProviderAuthorities; changed = true; } - for (const sandbox of Object.values(data.sandboxes)) { - if ( - sandbox.gatewayName !== gatewayName || - !sandbox.nativeHostedProviderAuthorities?.some((receipt) => receipt.profileId === profileId) - ) - continue; - const retained = sandbox.nativeHostedProviderAuthorities.filter( - (receipt) => receipt.profileId !== profileId, - ); - if (retained.length) sandbox.nativeHostedProviderAuthorities = retained; - else delete sandbox.nativeHostedProviderAuthorities; - changed = true; - } return changed; } @@ -120,7 +107,7 @@ export function listNativeHostedProviderAttachmentSandboxNames( (sandbox) => sandbox.nativeHostedProviderAttachment?.profileId === profileId || sandbox.nativeNvidiaProviderAttachment?.profileId === profileId || - sandbox.nativeHostedProviderAuthorities?.some((receipt) => receipt.profileId === profileId), + sandbox.pendingNativeHostedProviderDetach?.profileId === profileId, ) .map((sandbox) => sandbox.name) .sort(); diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index b3bb2abe749..32d4937ef43 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -3,7 +3,7 @@ import { normalizeNativeHostedProviderAttachment } from "../../inference/native- // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { retainNativeHostedProviderAuthority } from "../../inference/native-hosted/authority"; +import { normalizeNativeHostedProviderAuthorities } from "../../inference/native-hosted/authority"; import path from "node:path"; import { isObjectRecord } from "../../core/json-types"; import { GATEWAY_PORT } from "../../core/ports"; @@ -186,10 +186,8 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); if (rawAttachment !== undefined && !nativeHostedProviderAttachment) throw new Error("Invalid native inference provider receipt"); - const nativeHostedProviderAuthorities = retainNativeHostedProviderAuthority( - entry.nativeHostedProviderAuthorities, - nativeHostedProviderAttachment, - ); + // Validate legacy history before discarding it; gateway receipts own durable authority. + normalizeNativeHostedProviderAuthorities(Reflect.get(entry, "nativeHostedProviderAuthorities")); const pendingNativeHostedProviderDetach = normalizeNativeHostedProviderAttachment( entry.pendingNativeHostedProviderDetach, ); @@ -228,6 +226,7 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { mcp: _legacyMcp, ...rest } = policyEntry as SandboxEntry & { + nativeHostedProviderAuthorities?: unknown; cuaRuntimeReadiness?: unknown; nativeNvidiaProviderAuthority?: unknown; mcp?: unknown; @@ -235,7 +234,6 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { return { ...rest, ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), - ...(nativeHostedProviderAuthorities.length ? { nativeHostedProviderAuthorities } : {}), ...(pendingNativeHostedProviderDetach ? { pendingNativeHostedProviderDetach } : {}), ...(workload ? { workload } : {}), ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), @@ -271,10 +269,8 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); if (rawAttachment !== undefined && !nativeHostedProviderAttachment) throw new Error("Invalid native inference provider receipt"); - const nativeHostedProviderAuthorities = retainNativeHostedProviderAuthority( - durable.nativeHostedProviderAuthorities, - nativeHostedProviderAttachment, - ); + // Validate legacy history before discarding it; gateway receipts own durable authority. + normalizeNativeHostedProviderAuthorities(Reflect.get(durable, "nativeHostedProviderAuthorities")); const pendingNativeHostedProviderDetach = normalizeNativeHostedProviderAttachment( durable.pendingNativeHostedProviderDetach, ); @@ -313,6 +309,7 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { mcp: _legacyMcp, ...rest } = policyEntry as SandboxEntry & { + nativeHostedProviderAuthorities?: unknown; cuaRuntimeReadiness?: unknown; nativeNvidiaProviderAuthority?: unknown; mcp?: unknown; @@ -320,7 +317,6 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { return { ...rest, ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), - ...(nativeHostedProviderAuthorities.length ? { nativeHostedProviderAuthorities } : {}), ...(pendingNativeHostedProviderDetach ? { pendingNativeHostedProviderDetach } : {}), ...(rest.dashboardPort === 0 ? { dashboardPort: null } : {}), ...(workload ? { workload } : {}), diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 0baca6fe1be..3ce9cfa4809 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -23,7 +23,6 @@ const ROUTE_RESERVATION_KEYS = new Set([ "model", "name", "nativeHostedProviderAttachment", - "nativeHostedProviderAuthorities", "nativeNvidiaProviderAttachment", "openshellDriver", "pendingRouteReservation", diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 6c410d85c13..8ffe1ca88b9 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -136,8 +136,6 @@ export interface SandboxEntry extends Partial { hostLocalInferenceReceipt?: string | null; /** Exact OpenShell provider identity attached for native NVIDIA hosted inference. */ nativeHostedProviderAttachment?: NativeHostedProviderAttachment; - /** Gateway-scoped ownership retained across provider switches. */ - nativeHostedProviderAuthorities?: NativeHostedProviderAttachment[]; /** Previous native access retained until provider-switch cleanup is confirmed. */ pendingNativeHostedProviderDetach?: NativeHostedProviderAttachment; /** Legacy Slice 1 receipt; normalized when loaded. */ From 430a9caf4d17fd32c8685fd3bed9c7b43ee222ae Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 18:11:22 -0700 Subject: [PATCH 104/133] test(credentials): cover both reset identities in retry fixture Signed-off-by: Deepak Jain --- src/lib/actions/credentials-provider-adapter.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 055915c99ca..1d3becaca29 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -984,6 +984,8 @@ describe("credential actions use typed OpenShell provider results", () => { ok: false, error: { kind: "command", reason: "failed", message: "failed" }, }) + .mockResolvedValueOnce({ ok: true }) + .mockResolvedValueOnce({ ok: true }) .mockResolvedValueOnce({ ok: true }); const adapter = providerAdapter({ deleteProvider: deletion }); const failed = await runCredentialsResetAction( @@ -997,6 +999,12 @@ describe("credential actions use typed OpenShell provider results", () => { { providerAdapter: adapter, clearNativeHostedProviderAuthority: clear }, ); expect(succeeded.exitCode).toBe(0); + expect(deletion.mock.calls.map(([request]) => request.providerName)).toEqual([ + profile.providerName, + profile.logicalProvider, + profile.providerName, + profile.logicalProvider, + ]); expect(clear).toHaveBeenCalledExactlyOnceWith("nemoclaw", profile.profileId); }, ); From 25fa8fe814f7e49c7438ee4ddf2eabba7576d3dc Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 18:20:32 -0700 Subject: [PATCH 105/133] fix(inference): preserve reset authority and validate deferred receipts Signed-off-by: Deepak Jain --- .../actions/credentials-native-reset.test.ts | 9 +++---- .../credentials-provider-adapter.test.ts | 4 +-- src/lib/actions/credentials/reset.ts | 8 ++---- .../orchestration-native-nvidia.test.ts | 26 +++++++++++++------ .../onboard/sandbox-create/orchestration.ts | 21 ++++++++------- .../cli/credentials-cli-command.test.ts | 2 +- 6 files changed, 39 insertions(+), 31 deletions(-) diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index f717d309843..18d23959575 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -103,8 +103,8 @@ describe("native NVIDIA credential reset ownership", () => { "nemoclaw", ); expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ - "nemoclaw-nvidia-prod-v1", "nvidia-prod", + "nemoclaw-nvidia-prod-v1", ]); expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledExactlyOnceWith("nemoclaw"); }); @@ -146,10 +146,9 @@ describe("native NVIDIA credential reset ownership", () => { }, ); expect(result.exitCode).toBe(1); - expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ - "nemoclaw-nvidia-prod-v1", - "nvidia-prod", - ]); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual( + failedName === "nvidia-prod" ? ["nvidia-prod"] : ["nvidia-prod", "nemoclaw-nvidia-prod-v1"], + ); expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines.join("\n")).toContain(failedName); }, diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 5492b5b01f8..79525183250 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -986,7 +986,7 @@ describe("credential actions use typed OpenShell provider results", () => { }); it.each(["nvidia-prod", "nemoclaw-nvidia-prod-v1"])( - "preserves attached native NVIDIA providers during credential reset via %s", + "preserves attached NVIDIA providers during credential reset via %s", async (provider) => { const deleteProvider = vi.fn(async () => ({ ok: false, @@ -1013,7 +1013,7 @@ describe("credential actions use typed OpenShell provider results", () => { expect(deleteProvider).toHaveBeenCalledOnce(); expect(deleteProvider).toHaveBeenCalledWith({ target: { kind: "named", gatewayName: "nemoclaw" }, - providerName: "nemoclaw-nvidia-prod-v1", + providerName: provider, timeoutMs: 30_000, }); expect(detachProvider).not.toHaveBeenCalled(); diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index c92e53988bf..0cc47305ce5 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -184,8 +184,7 @@ export async function runCredentialsResetAction( if (key === NVIDIA_HOSTED_LOGICAL_PROVIDER) { const lines: string[] = []; - let complete = true; - for (const name of [NVIDIA_HOSTED_NATIVE_PROVIDER, NVIDIA_HOSTED_LOGICAL_PROVIDER]) { + for (const name of [NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROVIDER]) { const result = await deleteProviderWithRecovery(name, target, providerAdapter, { detachAttached: false, }); @@ -200,12 +199,9 @@ export async function runCredentialsResetAction( target.gatewayName, ); lines.push(...outcome.lines); - complete = outcome.ok && complete; - if (!result.ok && result.error?.kind === "command" && result.error.reason === "attached") - return fail(lines); + if (!outcome.ok) return fail(lines); } } - if (!complete) return fail(lines); forgetExtraProvider(publicKey); (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( target.gatewayName, diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index 2d11c1ed280..c9a9feff3fe 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -28,9 +28,13 @@ function providerAdapter(providerId: string): OpenShellProviderAdapter { } as unknown as OpenShellProviderAdapter; } -function nativeProviderBoundary(adapter: OpenShellProviderAdapter, missingReceipt = false) { +function nativeProviderBoundary( + adapter: OpenShellProviderAdapter, + missingReceipt = false, + deferred = false, +) { return createProviderEffectBoundary({ - deferred: false, + deferred, sandboxName: "alpha", gatewayName: "nemoclaw", expectedNativeNvidiaProviderAttachment: missingReceipt @@ -73,12 +77,18 @@ function verifiedCreateContext(revalidateSandboxIdentity = vi.fn()) { } describe("native NVIDIA post-create provider verification", () => { - it("rejects a missing native receipt before creation", async () => { - const boundary = nativeProviderBoundary(providerAdapter(recordedProviderId), true); - await expect(boundary.validateBeforeCreate()).rejects.toThrow( - "native NVIDIA provider identity receipt", - ); - }); + it.each([false, true])( + "rejects a missing native receipt before creation with deferred=%s", + async (deferred) => { + const adapter = providerAdapter(recordedProviderId); + const boundary = nativeProviderBoundary(adapter, true, deferred); + await expect(boundary.validateBeforeCreate()).rejects.toThrow( + "native NVIDIA provider identity receipt", + ); + expect(adapter.getProvider).not.toHaveBeenCalled(); + expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); + }, + ); it("confirms the recorded provider is attached after sandbox identity is verified", async () => { const adapter = providerAdapter(recordedProviderId); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index e1c8a1e629f..8e53b08ee69 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1449,17 +1449,20 @@ export function createProviderEffectBoundary(input: { deps: input.preparationDeps, }); }; + const validateNativeNvidiaReceipt = async () => { + if ( + usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) && + !input.expectedNativeNvidiaProviderAttachment + ) { + throw new Error( + `Sandbox '${input.sandboxName}' is missing its native NVIDIA provider identity receipt.`, + ); + } + }; if (!input.deferred) { return { validateBeforeCreate: async () => { - if ( - usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) && - !input.expectedNativeNvidiaProviderAttachment - ) { - throw new Error( - `Sandbox '${input.sandboxName}' is missing its native NVIDIA provider identity receipt.`, - ); - } + await validateNativeNvidiaReceipt(); await validate(); }, publishBeforeCreate: async () => { @@ -1472,7 +1475,7 @@ export function createProviderEffectBoundary(input: { }; } return { - validateBeforeCreate: async () => undefined, + validateBeforeCreate: validateNativeNvidiaReceipt, publishBeforeCreate: async () => undefined, runAfterVerifiedCreate: async (context) => { context.revalidateSandboxIdentity( diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index 744f071115b..d4ef00dd322 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -348,7 +348,7 @@ describe("credentials oclif commands", () => { const output = await captureOutput(() => CredentialsResetCommand.run(["nvidia-prod", "--yes"])); expect(calls).toEqual( - ["nemoclaw-nvidia-prod-v1", "nvidia-prod"].map((providerName) => ({ + ["nvidia-prod", "nemoclaw-nvidia-prod-v1"].map((providerName) => ({ args: ["provider", "delete", "-g", "nemoclaw", providerName], opts: { env: expect.any(Object), From 68a5241f28a52afe9a8ad986327078b9fa5acd9f Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 19:04:26 -0700 Subject: [PATCH 106/133] fix(pi): reject every native provider credential in image environment Signed-off-by: Deepak Jain --- agents/pi/Dockerfile | 2 +- .../pi-candidate-runtime-artifacts.test.ts | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/agents/pi/Dockerfile b/agents/pi/Dockerfile index 091fdfe7b72..172ea3f535d 100644 --- a/agents/pi/Dockerfile +++ b/agents/pi/Dockerfile @@ -269,7 +269,7 @@ RUN set -eu; \ # upstream provider credential pattern. # hadolint ignore=DL4006 RUN set -eu; \ - if env | grep -Eq '^(NVIDIA_API_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|OPENROUTER_API_KEY)='; then \ + if env | grep -Eq '^(NVIDIA_API_KEY|NVIDIA_INFERENCE_API_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|GEMINI_API_KEY|OPENROUTER_API_KEY)='; then \ echo "ERROR: an upstream provider credential is present in the Pi image environment" >&2; \ exit 1; \ fi; \ diff --git a/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts b/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts index b5e09d671d6..1561dcf6412 100644 --- a/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts +++ b/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts @@ -10,6 +10,7 @@ import { CANDIDATE_MANAGED_IMAGE_AGENTS, SHIPPED_MANAGED_IMAGE_AGENTS, } from "../../../../src/lib/onboard/managed-image/contract.ts"; +import { NATIVE_HOSTED_PROFILES } from "../../../../src/lib/inference/native-hosted/profiles.ts"; import { validateCandidateContract } from "../../../../tools/managed-images/validate-candidate-contract.mts"; import { readWorkflow, @@ -97,6 +98,28 @@ describe("Pi candidate contract validation", () => { }); }); +describe("Pi final-image credential boundary", () => { + const dockerfile = fs.readFileSync(path.join(root, "agents/pi/Dockerfile"), "utf8"); + const environmentGate = required( + dockerfile.match(/if env \| grep -Eq '[^']+'; then [\s\S]*?fi;/u)?.[0], + "Pi Dockerfile is missing its final-image credential environment gate", + ); + it.each([ + ...new Set([ + "NVIDIA_API_KEY", + ...NATIVE_HOSTED_PROFILES.map((profile) => profile.credentialEnv), + ]), + ])("rejects inherited %s before admitting the final image", (credential) => { + const result = spawnSync("bash", ["-c", environmentGate], { + encoding: "utf8", + env: { PATH: process.env.PATH, [credential]: "fake-inherited-secret" }, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("upstream provider credential is present"); + expect(result.stdout + result.stderr).not.toContain("fake-inherited-secret"); + }); +}); + describe("Pi managed model catalog generation", () => { function generate(env: Record): { home: string; From ced3adfaa977d91995feb8c57ba606e80b535308 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 19:20:39 -0700 Subject: [PATCH 107/133] chore(pi): refresh exact native credential image receipts Signed-off-by: Deepak Jain --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index e199731e75b..d91165ab98b 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:d4b30d997db5bee7231beb21eab1f4cea27fb52aec3c3202f505d05698351f3f", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:d4b30d997db5bee7231beb21eab1f4cea27fb52aec3c3202f505d05698351f3f", + "digest": "sha256:4f85b691897bab274b426fc99ff84f0b123331d63c116ae0a20af71df9e786b8", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:4f85b691897bab274b426fc99ff84f0b123331d63c116ae0a20af71df9e786b8", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "f0e556fd6713b0f6f38f38a392434a65f7bad308", + "revision": "68a5241f28a52afe9a8ad986327078b9fa5acd9f", "release": "v0.1.0", - "cohort": "ghrun-37649607224-1" + "cohort": "ghrun-37716478093-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 653336e8eaa..83a81dd5c7c 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:a9633f98b6efeed9f064912a5ac00b83272e1cd3f64fa13f90f9c103b3a5598f", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:a9633f98b6efeed9f064912a5ac00b83272e1cd3f64fa13f90f9c103b3a5598f", + "digest": "sha256:3227ec2aecdfdfa464396ae4c503d7c04d44acc2cb9bd449f2052929fd5f4dbc", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:3227ec2aecdfdfa464396ae4c503d7c04d44acc2cb9bd449f2052929fd5f4dbc", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "f0e556fd6713b0f6f38f38a392434a65f7bad308", + "revision": "68a5241f28a52afe9a8ad986327078b9fa5acd9f", "release": "v0.1.0", - "cohort": "ghrun-37649607224-1" + "cohort": "ghrun-37716478093-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 7313366c8fa..6a3fd06a43f 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "6fb52eda32e2329537bbf32a0be0cf9b3c267db4c525562e61ad3e7c54928539", - "fe9dd37e94cb3252b1bd917f0cc4a15380b348c4320e3cd35b3b2c92b9d55924", + "6c7bc0d9b5adcc6f96f7440cda879de387dedb34d2474b1e5ebb65b88bd255e4", + "c30a15606295463f3d4d06b699d69a2b7093e6a16d498c93d15223c50c75fe50", ]), }); From 7fa70a8de5fab3da048ce62eed4d155a4e1f3aba Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 20:20:44 -0700 Subject: [PATCH 108/133] docs(inference): clarify native hosted export support Signed-off-by: Deepak Jain --- docs/reference/commands.mdx | 3 ++- src/lib/actions/sandbox/inference-invocation-probe.test.ts | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 6503434d507..f2fd333f90c 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -314,7 +314,8 @@ If either identity cannot be verified, do not remove files by name alone. Do not remove the requested output file to clean up a temporary link. Version 1 exports Docker-managed OpenClaw sandboxes and canonical managed Hermes or LangChain Deep Agents Code sandboxes in the default workspace. -Supported sandboxes use hosted external inference or the native NVIDIA hosted provider with its default endpoint, an immutable managed image, a NemoClaw-owned gateway, and an explicit representable policy. +Supported sandboxes use hosted external inference or a fixed native hosted provider with its default endpoint, an immutable managed image, a NemoClaw-owned gateway, and an explicit representable policy. +Native hosted export requires a matching provider profile, attachment receipt, endpoint, API family, and credential reference. OpenClaw exports for attached Ollama with a managed proxy and the fixed managed vLLM profile include a named service with `image: null`. Replace only that value with an official, immutable, compatible v1 runtime image before v1 parsing or planning. Other local inference and Podman exports remain deferred. diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 892f2890dcd..da61aed0714 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -117,6 +117,12 @@ describe("native hosted inference protocol requests", () => { "https://openrouter.ai/api/v1/chat/completions", ["HTTP-Referer: https://www.nvidia.com/nemoclaw/", "X-OpenRouter-Title: NVIDIA NemoClaw"], ], + [ + "openrouter-api", + "openai-responses", + "https://openrouter.ai/api/v1/chat/completions", + ["HTTP-Referer: https://www.nvidia.com/nemoclaw/", "X-OpenRouter-Title: NVIDIA NemoClaw"], + ], [ "hermes-provider", "openai-responses", From c6a7f7c0b285a2f6c935b4260592e2fa6611b356 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 21:19:26 -0700 Subject: [PATCH 109/133] fix(credentials): preserve unowned legacy NVIDIA provider Signed-off-by: Deepak Jain --- .../actions/credentials-native-reset.test.ts | 65 ++++++++++++++++--- .../credentials-provider-adapter.test.ts | 19 +++++- src/lib/actions/credentials/reset.ts | 38 +++++------ .../cli/credentials-cli-command.test.ts | 8 ++- 4 files changed, 94 insertions(+), 36 deletions(-) diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index 18d23959575..5af507332ae 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -14,7 +14,13 @@ vi.mock("../onboard/gateway-teardown-authority", () => ({ function adapter( deleteProvider: OpenShellProviderAdapter["deleteProvider"], ): OpenShellProviderAdapter { - return { deleteProvider: vi.fn(deleteProvider) } as unknown as OpenShellProviderAdapter; + return { + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), + deleteProvider: vi.fn(deleteProvider), + } as unknown as OpenShellProviderAdapter; } describe("native NVIDIA credential reset ownership", () => { @@ -79,6 +85,48 @@ describe("native NVIDIA credential reset ownership", () => { }, ); + it.each(["present", "timeout", "authentication", "schema"] as const)( + "preserves providers and native authority when legacy observation is %s", + async (state) => { + const deleteProvider = vi.fn(async () => ({ + ok: true, + })); + const clearNativeNvidiaProviderAuthority = vi.fn(); + const providerAdapter = adapter(deleteProvider); + providerAdapter.getProvider = vi.fn(async () => + state === "present" + ? { + ok: true, + value: { + name: "nvidia-prod", + type: "nvidia", + credentialKeys: ["NVIDIA_API_KEY"], + configKeys: [], + }, + } + : { ok: false, error: { kind: state, message: "observation failed" } }, + ); + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { + providerAdapter, + clearNativeNvidiaProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gateway, operation) => operation(), + }, + ); + expect(result.exitCode).toBe(1); + expect(providerAdapter.getProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: "nvidia-prod", + timeoutMs: 30_000, + }); + expect(deleteProvider).not.toHaveBeenCalled(); + expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(result.failureLines.join("\n")).toContain("ownership conflict"); + }, + ); + it("does not let another gateway's attachment block the selected gateway reset", async () => { const deleteProvider = vi.fn(async () => ({ ok: true, @@ -103,7 +151,6 @@ describe("native NVIDIA credential reset ownership", () => { "nemoclaw", ); expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ - "nvidia-prod", "nemoclaw-nvidia-prod-v1", ]); expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledExactlyOnceWith("nemoclaw"); @@ -113,21 +160,23 @@ describe("native NVIDIA credential reset ownership", () => { const deleteProvider = vi.fn(async () => ({ ok: true, })); + const providerAdapter = adapter(deleteProvider); await runCredentialsResetAction( { provider: "nemoclaw-nvidia-prod-v1", confirmed: true }, { - providerAdapter: adapter(deleteProvider), + providerAdapter, clearNativeNvidiaProviderAuthority: vi.fn(), listNativeNvidiaProviderAttachmentSandboxNames: () => [], withGatewayRouteMutationLock: async (_gateway, operation) => operation(), }, ); + expect(providerAdapter.getProvider).not.toHaveBeenCalled(); expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ "nemoclaw-nvidia-prod-v1", ]); }); - it.each(["nemoclaw-nvidia-prod-v1", "nvidia-prod"])( + it.each(["nemoclaw-nvidia-prod-v1"])( "preserves authority when deleting %s fails", async (failedName) => { const deleteProvider = vi.fn(async (input) => @@ -146,11 +195,11 @@ describe("native NVIDIA credential reset ownership", () => { }, ); expect(result.exitCode).toBe(1); - expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual( - failedName === "nvidia-prod" ? ["nvidia-prod"] : ["nvidia-prod", "nemoclaw-nvidia-prod-v1"], - ); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + "nemoclaw-nvidia-prod-v1", + ]); expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); - expect(result.failureLines.join("\n")).toContain(failedName); + expect(result.failureLines.join("\n")).toContain("delete failed"); }, ); diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 79525183250..b5812a124cc 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -998,7 +998,14 @@ describe("credential actions use typed OpenShell provider results", () => { }, })); const detachProvider = vi.fn(); - const adapter = providerAdapter({ deleteProvider, detachProvider }); + const adapter = providerAdapter({ + deleteProvider, + detachProvider, + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), + }); const result = await runCredentialsResetAction( { provider, confirmed: true }, @@ -1013,7 +1020,7 @@ describe("credential actions use typed OpenShell provider results", () => { expect(deleteProvider).toHaveBeenCalledOnce(); expect(deleteProvider).toHaveBeenCalledWith({ target: { kind: "named", gatewayName: "nemoclaw" }, - providerName: provider, + providerName: "nemoclaw-nvidia-prod-v1", timeoutMs: 30_000, }); expect(detachProvider).not.toHaveBeenCalled(); @@ -1030,6 +1037,10 @@ describe("credential actions use typed OpenShell provider results", () => { it("clears native NVIDIA gateway authority only after provider deletion is confirmed", async () => { const clearNativeNvidiaProviderAuthority = vi.fn(); const adapter = providerAdapter({ + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), deleteProvider: vi.fn(async () => ({ ok: true as const })), }); @@ -1050,6 +1061,10 @@ describe("credential actions use typed OpenShell provider results", () => { it("clears native NVIDIA authority when the provider is already absent", async () => { const clearNativeNvidiaProviderAuthority = vi.fn(); const adapter = providerAdapter({ + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), deleteProvider: vi.fn(async () => ({ ok: false as const, error: { diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 0cc47305ce5..0b707835b47 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -183,30 +183,22 @@ export async function runCredentialsResetAction( } if (key === NVIDIA_HOSTED_LOGICAL_PROVIDER) { - const lines: string[] = []; - for (const name of [NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROVIDER]) { - const result = await deleteProviderWithRecovery(name, target, providerAdapter, { - detachAttached: false, - }); - if (!result.ok && result.error?.kind === "command" && result.error.reason === "not_found") { - lines.push(` Provider '${name}' is already absent from the OpenShell gateway.`); - } else { - const outcome = formatResetOutcome( - !result.ok && result.error?.kind === "command" && result.error.reason === "attached" - ? publicKey - : name, - result, - target.gatewayName, - ); - lines.push(...outcome.lines); - if (!outcome.ok) return fail(lines); - } + const legacy = await providerAdapter.getProvider({ + target, + providerName: NVIDIA_HOSTED_LOGICAL_PROVIDER, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + // Native authority binds only the native identity. No durable legacy receipt exists. + if (legacy.ok || legacy.error.kind !== "command" || legacy.error.reason !== "not_found") { + return fail([ + ` Provider ownership conflict for '${NVIDIA_HOSTED_LOGICAL_PROVIDER}'.`, + legacy.ok + ? " NemoClaw has no durable ownership proof for this legacy provider." + : " NemoClaw could not confirm that the legacy provider is absent.", + " No provider or ownership authority was changed.", + " Inspect the legacy provider with its owner before retrying the logical reset.", + ]); } - forgetExtraProvider(publicKey); - (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( - target.gatewayName, - ); - return ok(lines); } const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter, { diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index d4ef00dd322..acba4833856 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -336,7 +336,7 @@ describe("credentials oclif commands", () => { expect(runOpenshell).not.toHaveBeenCalled(); }); - it("deletes native and legacy NVIDIA provider credentials with --yes", async () => { + it("deletes only the explicit native NVIDIA provider credential with --yes", async () => { const calls = installRuntimeBridge({ runOpenshell: (args, opts) => { calls.push({ args, opts }); @@ -345,10 +345,12 @@ describe("credentials oclif commands", () => { }); const { CredentialsResetCommand } = loadCommands(); - const output = await captureOutput(() => CredentialsResetCommand.run(["nvidia-prod", "--yes"])); + const output = await captureOutput(() => + CredentialsResetCommand.run(["nemoclaw-nvidia-prod-v1", "--yes"]), + ); expect(calls).toEqual( - ["nvidia-prod", "nemoclaw-nvidia-prod-v1"].map((providerName) => ({ + ["nemoclaw-nvidia-prod-v1"].map((providerName) => ({ args: ["provider", "delete", "-g", "nemoclaw", providerName], opts: { env: expect.any(Object), From f36287d9eda7376fe34518bfd8c41a73645a05f9 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 21:23:33 -0700 Subject: [PATCH 110/133] test(credentials): cover logical reset ownership boundary Signed-off-by: Deepak Jain --- .../cli/credentials-cli-command.test.ts | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index acba4833856..9b7d18487b8 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -366,6 +366,45 @@ describe("credentials oclif commands", () => { expect(output.stdout).toContain("Rerun 'nemoclaw onboard'"); }); + it.each(["present", "absent"])( + "checks the legacy identity before logical reset when %s", + async (state) => { + const responses = [ + state === "absent" + ? { status: 1, stderr: "Error: provider 'nvidia-prod' not found" } + : { + status: 0, + stdout: + "Name: nvidia-prod\nId: 11111111-2222-4333-8444-555555555555\nType: nvidia\nResource version: 7\nCredential keys: NVIDIA_API_KEY\nConfig keys: ", + }, + { status: 0 }, + ]; + const calls = installRuntimeBridge({ + runOpenshell: (args, opts) => { + calls.push({ args, opts }); + return responses.shift()!; + }, + }); + const { CredentialsResetCommand } = loadCommands(); + const output = await captureOutput(() => + state === "present" + ? expectExitCode(() => CredentialsResetCommand.run(["nvidia-prod", "--yes"]), 1) + : CredentialsResetCommand.run(["nvidia-prod", "--yes"]), + ); + expect(calls.map((call) => call.args)).toEqual( + state === "present" + ? [["provider", "get", "-g", "nemoclaw", "nvidia-prod"]] + : [ + ["provider", "get", "-g", "nemoclaw", "nvidia-prod"], + ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ], + ); + expect(state === "present" ? output.stderr : output.stdout).toContain( + state === "present" ? "ownership conflict" : "Removed provider 'nvidia-prod'", + ); + }, + ); + it("rejects per-sandbox messaging bridge names for credential reset", async () => { installRuntimeBridge(); const { CredentialsResetCommand } = loadCommands(); From 8d824f8723fe1fb655823c19fc961615c458e135 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 21:29:08 -0700 Subject: [PATCH 111/133] test(credentials): type provider observation fixture Signed-off-by: Deepak Jain --- src/lib/actions/credentials-native-reset.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index 5af507332ae..5a54c34edee 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -93,7 +93,7 @@ describe("native NVIDIA credential reset ownership", () => { })); const clearNativeNvidiaProviderAuthority = vi.fn(); const providerAdapter = adapter(deleteProvider); - providerAdapter.getProvider = vi.fn(async () => + providerAdapter.getProvider = vi.fn(async () => state === "present" ? { ok: true, From 0c7fdac324ab66c8446ceca3457bd63d5cc63a6e Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 21:31:22 -0700 Subject: [PATCH 112/133] test(credentials): type legacy absence fixtures Signed-off-by: Deepak Jain --- src/lib/actions/credentials-provider-adapter.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index b5812a124cc..b0ee2207056 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -1001,7 +1001,7 @@ describe("credential actions use typed OpenShell provider results", () => { const adapter = providerAdapter({ deleteProvider, detachProvider, - getProvider: vi.fn(async () => ({ + getProvider: vi.fn(async () => ({ ok: false, error: { kind: "command", reason: "not_found", message: "absent" }, })), @@ -1037,7 +1037,7 @@ describe("credential actions use typed OpenShell provider results", () => { it("clears native NVIDIA gateway authority only after provider deletion is confirmed", async () => { const clearNativeNvidiaProviderAuthority = vi.fn(); const adapter = providerAdapter({ - getProvider: vi.fn(async () => ({ + getProvider: vi.fn(async () => ({ ok: false, error: { kind: "command", reason: "not_found", message: "absent" }, })), @@ -1061,7 +1061,7 @@ describe("credential actions use typed OpenShell provider results", () => { it("clears native NVIDIA authority when the provider is already absent", async () => { const clearNativeNvidiaProviderAuthority = vi.fn(); const adapter = providerAdapter({ - getProvider: vi.fn(async () => ({ + getProvider: vi.fn(async () => ({ ok: false, error: { kind: "command", reason: "not_found", message: "absent" }, })), From ea2103156f26aaa425f7794d73872a2c31fff719 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 21:55:50 -0700 Subject: [PATCH 113/133] test(credentials): observe legacy absence before logical reset Signed-off-by: Deepak Jain --- src/commands/credentials.test.ts | 34 +++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/src/commands/credentials.test.ts b/src/commands/credentials.test.ts index d102a91bc3a..4f65f6702df 100644 --- a/src/commands/credentials.test.ts +++ b/src/commands/credentials.test.ts @@ -339,18 +339,34 @@ describe("credentials oclif adapter source coverage", () => { it("deletes provider credentials with --yes", async () => { const log = vi.spyOn(console, "log").mockImplementation(() => {}); + mocks.runOpenshellProviderCommand.mockReturnValueOnce({ + status: 1, + stderr: "Error: provider 'nvidia-prod' not found", + }); await CredentialsResetCommand.run(["nvidia-prod", "--yes"], rootDir); expect(mocks.prompt).not.toHaveBeenCalled(); - expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledWith( - ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], - { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, - timeout: 30_000, - }, - ); + expect(mocks.runOpenshellProviderCommand.mock.calls).toEqual([ + [ + ["provider", "get", "-g", "nemoclaw", "nvidia-prod"], + { + ignoreError: true, + maxBuffer: 64 * 1024, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + ], + [ + ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + suppressOutput: true, + timeout: 30_000, + }, + ], + ]); const output = log.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); log.mockRestore(); expect(output).toContain("Removed provider 'nvidia-prod'"); From 35a814f7487655e11bbbef32463487f220f75d2b Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 7 Oct 2026 22:26:38 -0700 Subject: [PATCH 114/133] chore(pi): refresh receipts after main audit integration Signed-off-by: Deepak Jain --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 ++++---- ci/pi-agent-qualification-v1-linux-arm64.json | 8 ++++---- src/lib/agent/candidate-authority.ts | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index dc71bc77af4..045d10b9821 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:3bf1dcebb4fdefe4ad588b15f287e2546a570c4464897835c37599de2ec1b66b", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:3bf1dcebb4fdefe4ad588b15f287e2546a570c4464897835c37599de2ec1b66b", + "digest": "sha256:1d042f71e146de375c909df9b07691e4c8a9782e9032f3a196362e020b750614", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:1d042f71e146de375c909df9b07691e4c8a9782e9032f3a196362e020b750614", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "9abef33ddf73105c8f3f952ced9ce4eb53252126", + "revision": "9640e8c6c43d0ecf563b711233daaa1ef5da7b02", "release": "v0.1.0", - "cohort": "ghrun-37676667241-1" + "cohort": "ghrun-37731249553-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 8154ec8d0fd..2eb80a2ff82 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:f3d7ed13c07c7c3840414752aa72e77178fa957137951c25ad4afa84206b11ac", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:f3d7ed13c07c7c3840414752aa72e77178fa957137951c25ad4afa84206b11ac", + "digest": "sha256:7760fe9a1a59eb370d9469c913d674c0c5f3c6ba64b6440cb7819184754cc528", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:7760fe9a1a59eb370d9469c913d674c0c5f3c6ba64b6440cb7819184754cc528", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "9abef33ddf73105c8f3f952ced9ce4eb53252126", + "revision": "9640e8c6c43d0ecf563b711233daaa1ef5da7b02", "release": "v0.1.0", - "cohort": "ghrun-37676667241-1" + "cohort": "ghrun-37731249553-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 0ab2fb71aed..1329c063a69 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "ba5f7fc419ada9de012546d8bbaa7f251eb1a9075d1df82af573aaf57809cbe9", - "8bf8a0d80ec7e70687f0f696d8ff1fded3214e5858b6881a5380b4cf25faa455", + "c259c8157abddf52c2cdd4d976b1dca6f98a65a83d7a1b9e0ceba02dbec84f6a", + "c886825c5ec1a4cd4c2461b681b8439bccc18dbfc958348daadd73a4928d3c7d", ]), }); From 5e0b84c44f1670f2805ade198f9892e1f35f45fa Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 08:53:40 -0700 Subject: [PATCH 115/133] fix(inference): preserve remediation diagnostics after base sync Signed-off-by: Deepak Jain --- ci/e2e-assertion-budget.json | 20 ++++++++--------- ci/e2e-assertion-growth-exceptions.json | 14 ++---------- scripts/lib/openclaw-npm-remediation.mts | 8 ++++++- .../openclaw/openclaw-npm-remediation.test.ts | 22 ++++++++++++++----- .../messaging-build-applier-integrity.test.ts | 1 - 5 files changed, 36 insertions(+), 29 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 0d257132d41..ceaa8fa8426 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 184, "direct": { - "expectCalls": 1234, - "matcherAssertions": 1213, + "expectCalls": 1232, + "matcherAssertions": 1211, "nodeAssertions": 104, "namedAssertionHelpers": 426, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 166, - "assertionPoints": 1959, + "assertionPoints": 1957, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1659, - "matcherAssertions": 1633, + "expectCalls": 1657, + "matcherAssertions": 1631, "nodeAssertions": 127, "namedAssertionHelpers": 671, "failCalls": 1, - "throwGuards": 528, + "throwGuards": 532, "objectFieldAssertions": 243, - "assertionPoints": 3203, + "assertionPoints": 3205, "generatedProbeBlocks": 208, "generatedProbeConditions": 720 }, @@ -62,13 +62,13 @@ "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], "test/e2e/live/double-onboard.test.ts": [36,43,36,43,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], - "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], + "test/e2e/live/full-e2e.test.ts": [27,30,28,62,7], "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [10,25,17,64,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,77,1], + "test/e2e/live/hermes-inference-switch.test.ts": [44,50,55,77,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], @@ -95,7 +95,7 @@ "test/e2e/live/onboard-repair.test.ts": [21,25,21,25,0], "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], - "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,52,1], + "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,54,1], "test/e2e/live/openclaw-skill-cli.test.ts": [10,14,10,14,1], "test/e2e/live/openclaw-slack-pairing.test.ts": [11,18,26,84,10], "test/e2e/live/openshell-credential-generation-window.test.ts": [42,92,43,112,18], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 6db6c3c90ab..a99d54ea36c 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -29,18 +29,8 @@ }, { "pullRequest": 12593, - "baseBudgetSha256": "fdc4a78b5588629e26b00778d1bc82d69101077b9e372f2b58670510184579c2", - "headBudgetSha256": "4c23631362f14df242b533a09b8b26f9f65b448611848c084d3263feb40c423c" - }, - { - "pullRequest": 12593, - "baseBudgetSha256": "d0a41e5514e5cc2f7bb34d7604c82106d9e36239f1abf5859e343c7733501289", - "headBudgetSha256": "4c23631362f14df242b533a09b8b26f9f65b448611848c084d3263feb40c423c" - }, - { - "pullRequest": 12593, - "baseBudgetSha256": "bda0267c094710272fd2a02ed05c26a2e93e5a78c81fcdb9d4d9a338e342914a", - "headBudgetSha256": "4c23631362f14df242b533a09b8b26f9f65b448611848c084d3263feb40c423c" + "baseBudgetSha256": "53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441", + "headBudgetSha256": "e8fb0b98decdc20f8253ed0f378f39e6a5b6b0ce44c9f1f2ad6e612a8c086c15" } ] } diff --git a/scripts/lib/openclaw-npm-remediation.mts b/scripts/lib/openclaw-npm-remediation.mts index b53ab37bbc2..c89a4953880 100755 --- a/scripts/lib/openclaw-npm-remediation.mts +++ b/scripts/lib/openclaw-npm-remediation.mts @@ -1999,7 +1999,13 @@ export function remediateInstalledOfficialOpenClawPlugin( ): void { try { remediateVerifiedInstalledOfficialOpenClawPlugin(request); - } catch { + } catch (error) { + if ( + error instanceof OpenClawNpmRemediationCommandError || + error instanceof OpenClawNpmPackageRecoveryError + ) { + throw error; + } throw new Error( "OpenClaw Slack remediation requires a valid managed npm package directory and reviewed dependency graph", ); diff --git a/test/agents/openclaw/openclaw-npm-remediation.test.ts b/test/agents/openclaw/openclaw-npm-remediation.test.ts index 755fd2d29c8..2ab006a1572 100644 --- a/test/agents/openclaw/openclaw-npm-remediation.test.ts +++ b/test/agents/openclaw/openclaw-npm-remediation.test.ts @@ -574,7 +574,8 @@ describe("OpenClaw npm remediation", () => { failure: "unavailable tar", prepare: (archivePath: string) => writeFileSync(archivePath, "not a tar archive"), env: { PATH: "" }, - message: "OpenClaw npm remediation operation 'list archive' could not start a required command.", + message: + "OpenClaw npm remediation operation 'list archive' could not start a required command.", }, ])("withholds archive paths and child diagnostics when $failure", ({ prepare, env, message }) => { const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-private-archive-marker-")); @@ -588,8 +589,15 @@ describe("OpenClaw npm remediation", () => { env, }; - expect(() => buildRemediatedOpenClawPluginArchive(request)).toThrow(message); - expect(() => buildRemediatedOpenClawPluginArchive(request)).not.toThrow("private-archive-marker"); + let failure: unknown; + try { + buildRemediatedOpenClawPluginArchive(request); + } catch (error) { + failure = error; + } + expect(failure).toBeInstanceOf(OpenClawNpmRemediationCommandError); + expect(fatalOpenClawNpmRemediationDiagnostic(failure)).toBe(message); + expect(String(failure)).not.toContain("private-archive-marker"); }); it("rejects unsafe archive members without echoing their names or archive path", () => { @@ -611,8 +619,12 @@ describe("OpenClaw npm remediation", () => { expect(() => buildRemediatedOpenClawPluginArchive(request)).toThrow( "npm archive has an unsafe member", ); - expect(() => buildRemediatedOpenClawPluginArchive(request)).not.toThrow("private-member-marker"); - expect(() => buildRemediatedOpenClawPluginArchive(request)).not.toThrow("private-archive-marker"); + expect(() => buildRemediatedOpenClawPluginArchive(request)).not.toThrow( + "private-member-marker", + ); + expect(() => buildRemediatedOpenClawPluginArchive(request)).not.toThrow( + "private-archive-marker", + ); }); it.each(["@slack/bolt", "@slack/bolt/node_modules/express"])( diff --git a/test/runtime/messaging/messaging-build-applier-integrity.test.ts b/test/runtime/messaging/messaging-build-applier-integrity.test.ts index 44ffa792616..0e70292107a 100644 --- a/test/runtime/messaging/messaging-build-applier-integrity.test.ts +++ b/test/runtime/messaging/messaging-build-applier-integrity.test.ts @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { createHash } from "node:crypto"; import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import fs from "node:fs"; From 06eb9cdc4d70dd21e7022b42762e6f1ab25f8654 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 09:38:13 -0700 Subject: [PATCH 116/133] fix(inference): reattach native providers when resuming Signed-off-by: Deepak Jain --- ...ovider-inference-openrouter-resume.test.ts | 91 ++++++++++--------- ...er-inference-resume-requested-name.test.ts | 8 +- .../handlers/provider-inference.test.ts | 53 ++++++----- .../machine/handlers/provider-inference.ts | 4 +- 4 files changed, 87 insertions(+), 69 deletions(-) diff --git a/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts b/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts index 48804c8000c..6b23e6b3cbe 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts @@ -7,50 +7,57 @@ import { createSession } from "../../../state/onboard-session"; import { handleProviderInferenceState } from "./provider-inference"; import { baseOptions, createDeps } from "./provider-inference.test-support"; -describe("OpenRouter provider inference resume", () => { - it("reconciles the adapter when resumed route metadata already matches", async () => { - const session = createSession({ - agent: "langchain-deepagents-code", - sandboxName: "deep-code", +describe("Native hosted provider inference resume", () => { + it.each([ + { provider: "openrouter-api", model: "moonshotai/kimi-k2.6", - credentialEnv: "OPENROUTER_API_KEY", - preferredInferenceApi: "openai-completions", - }); - session.steps.provider_selection.status = "complete"; - const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); - calls.complete.mockResolvedValue(session); + credential: "OPENROUTER_API_KEY", + resumeOptions: { skipHostInferenceSmoke: true, reuseGatewayCredentialWithoutLocalKey: true }, + }, + { provider: "openai-api", model: "gpt-4.1", credential: "OPENAI_API_KEY", resumeOptions: {} }, + ])( + "reconciles $provider when shared route metadata already matches", + async ({ provider, model, credential, resumeOptions }) => { + const session = createSession({ + agent: "langchain-deepagents-code", + sandboxName: "deep-code", + provider, + model, + credentialEnv: credential, + preferredInferenceApi: "openai-completions", + }); + session.steps.provider_selection.status = "complete"; + const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); + calls.complete.mockResolvedValue(session); - await handleProviderInferenceState({ - ...baseOptions(deps, session), - resume: true, - sandboxName: "deep-code", - agent: { name: "langchain-deepagents-code" }, - }); + await handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "deep-code", + agent: { name: "langchain-deepagents-code" }, + }); - expect(calls.setupNim).not.toHaveBeenCalled(); - expect(calls.skipped).not.toHaveBeenCalledWith( - "inference", - "openrouter-api / moonshotai/kimi-k2.6", - ); - expect(calls.setupInference).toHaveBeenCalledWith( - "deep-code", - "moonshotai/kimi-k2.6", - "openrouter-api", - null, - "OPENROUTER_API_KEY", - null, - [], - { - gatewayName: "nemoclaw", - allowToolsIncompatible: false, - skipHostInferenceSmoke: true, - reuseGatewayCredentialWithoutLocalKey: true, - preferredInferenceApi: "openai-completions", - endpointSource: null, - reservationSessionId: session.sessionId, - }, - ); - expect(calls.deleteEnv).toHaveBeenCalledWith("OPENROUTER_API_KEY"); - }); + expect(calls.setupNim).not.toHaveBeenCalled(); + expect(calls.skipped).not.toHaveBeenCalledWith("inference", `${provider} / ${model}`); + expect(calls.setupInference).toHaveBeenCalledWith( + "deep-code", + model, + provider, + null, + credential, + null, + [], + { + gatewayName: "nemoclaw", + allowToolsIncompatible: false, + ...resumeOptions, + preferredInferenceApi: "openai-completions", + endpointSource: null, + reservationSessionId: session.sessionId, + }, + ); + expect(calls.deleteEnv).toHaveBeenCalledWith(credential); + }, + ); }); diff --git a/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts b/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts index 3e6ebc09431..8e424552cab 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts @@ -16,10 +16,10 @@ import { baseOptions, createDeps } from "./provider-inference.test-support"; function interruptedResumeSession() { const session = createSession({ - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; diff --git a/src/lib/onboard/machine/handlers/provider-inference.test.ts b/src/lib/onboard/machine/handlers/provider-inference.test.ts index 49a7518110e..2b5446c9396 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test.ts @@ -333,7 +333,11 @@ describe("handleProviderInferenceState", () => { }); it("stops an authoritative rebuild before inference state when route persistence throws", async () => { - const session = createSession({ provider: "openai-api", model: "gpt-test" }); + const session = createSession({ + provider: "compatible-endpoint", + model: "gpt-test", + endpointUrl: "http://127.0.0.1:8000/v1", + }); const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); calls.reserveRoute.mockImplementation(() => { throw new Error("registry save failed"); @@ -600,10 +604,10 @@ describe("handleProviderInferenceState", () => { it("reserves the prompted sandbox route when resume skips already-ready inference (#6562)", async () => { const session = createSession({ - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; @@ -622,11 +626,11 @@ describe("handleProviderInferenceState", () => { expect(calls.setupNim).not.toHaveBeenCalled(); expect(calls.setupInference).not.toHaveBeenCalled(); expect(calls.reserveRoute).toHaveBeenCalledWith("tm", { - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", endpointSource: "inference-set", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", gatewayName: "nemoclaw", reservationSessionId: session.sessionId, @@ -642,10 +646,10 @@ describe("handleProviderInferenceState", () => { async (_label, identity) => { const session = createSession({ sandboxName: "stale-sandbox", - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; @@ -674,10 +678,10 @@ describe("handleProviderInferenceState", () => { it("does not reserve a route when resume skips inference after sandbox completion (#6562)", async () => { const session = createSession({ sandboxName: "completed-sandbox", - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; @@ -702,6 +706,13 @@ describe("handleProviderInferenceState", () => { const completedSelection = createSession({ sessionId: "resume-selection-session" }); const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); calls.complete.mockResolvedValueOnce(completedSelection); + calls.setupNim.mockResolvedValueOnce({ + ...baseSelection, + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", + }); calls.promptName.mockResolvedValue("tm"); const result = await handleProviderInferenceState({ @@ -714,11 +725,11 @@ describe("handleProviderInferenceState", () => { expect(calls.setupInference).not.toHaveBeenCalled(); expect(calls.promptName).toHaveBeenCalledWith(null); expect(calls.reserveRoute).toHaveBeenCalledWith("tm", { - provider: "nvidia-prod", - model: "nvidia/test", - endpointUrl: "https://integrate.api.nvidia.com/v1", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", endpointSource: null, - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", gatewayName: "nemoclaw", reservationSessionId: "resume-selection-session", diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 7368b0e5435..9c5eeb76b4d 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { clearAutoDetectedCompatibleContextWindow } from "../../../inference/compatible-endpoint-context"; -import { resolveAgentProviderInferenceApi } from "../../../inference/config"; +import { nativeHostedProfile, resolveAgentProviderInferenceApi } from "../../../inference/config"; import type { TrustedPrivateEndpointCapability } from "../../../inference/endpoint-ssrf-preflight"; import { type CurrentGatewayRouteCompatibilityCheck, @@ -532,7 +532,7 @@ function canResumeInferenceRoute(input: { }): boolean { return ( !input.needsBedrockRuntimeAdapter && - input.provider !== OPENROUTER_PROVIDER_NAME && + !nativeHostedProfile(input.provider) && !input.hasHostLocalInference && !input.forceProviderSelection && !input.forceInferenceSetup && From fbd1e1a173eedb2236e61d01cfaedd1fe9a4fdb6 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 10:09:32 -0700 Subject: [PATCH 117/133] test(inference): preserve legacy reservation resume coverage Signed-off-by: Deepak Jain --- .../abandoned-route-reservation.test.ts | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/lib/onboard/abandoned-route-reservation.test.ts b/src/lib/onboard/abandoned-route-reservation.test.ts index f0c9c68f4e4..74ca8a2ec68 100644 --- a/src/lib/onboard/abandoned-route-reservation.test.ts +++ b/src/lib/onboard/abandoned-route-reservation.test.ts @@ -95,16 +95,24 @@ describe("abandoned inference route reservation (#11051)", () => { const { baseOptions, baseSelection, createDeps } = await import("./machine/handlers/provider-inference.test-support"); const session = sessionStore.loadSession()!; - Object.assign(session, baseSelection, { sandboxName: SANDBOX }); + const legacySelection = { + ...baseSelection, + provider: "compatible-endpoint", + model: "local/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: null, + preferredInferenceApi: "openai-completions", + }; + Object.assign(session, legacySelection, { sandboxName: SANDBOX }); session.steps.provider_selection.status = "complete"; session.steps.inference.status = "complete"; sessionStore.saveSession(session); const route = { - provider: baseSelection.provider, - model: baseSelection.model, - endpointUrl: baseSelection.endpointUrl, - credentialEnv: baseSelection.credentialEnv, - preferredInferenceApi: baseSelection.preferredInferenceApi, + provider: legacySelection.provider, + model: legacySelection.model, + endpointUrl: legacySelection.endpointUrl, + credentialEnv: legacySelection.credentialEnv, + preferredInferenceApi: legacySelection.preferredInferenceApi, endpointSource: null, gatewayName: GATEWAY, }; From 0b1661dad1052e81f1a71d9b28fc29bbae9252dd Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 10:13:28 -0700 Subject: [PATCH 118/133] test(inference): accept native resume configuration review Signed-off-by: Deepak Jain --- .../onboard-inference-reconciliation.test.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 74354d1e3e9..e644332dcef 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -244,6 +244,7 @@ describe("onboard helpers", () => { ); fs.mkdirSync(fakeBin, { recursive: true }); + fs.writeFileSync(inferenceCommandLogPath, ""); writeOkOpenshell(fakeBin, { inferenceRoute: { gatewayName: "nemoclaw", @@ -385,6 +386,7 @@ registry.removeSandbox = () => true; credentials.prompt = async (question) => { prompts.push(String(question)); if (String(question).includes("Sandbox name")) return "hermes-resume"; + if (String(question).includes("Choose [1]")) return "1"; return "yes"; }; @@ -511,11 +513,12 @@ const { onboard } = require(${onboardPath}); }); assert.equal(result.status, 0, result.stderr); - const inferenceCommands = fs.readFileSync(inferenceCommandLogPath, "utf8").trim().split("\n"); - assert.ok( - inferenceCommands.includes("inference get -g nemoclaw"), - `expected a scoped inference read, received ${JSON.stringify(inferenceCommands)}`, - ); + const inferenceCommands = fs + .readFileSync(inferenceCommandLogPath, "utf8") + .trim() + .split("\n") + .filter(Boolean); + assert.deepEqual(inferenceCommands, [], "native resume must not consult the shared route"); assert.ok( !inferenceCommands.some((command) => command.startsWith("inference set")), `native Hermes must not mutate the shared route: ${JSON.stringify(inferenceCommands)}`, From 1e0c036be626409a62e5a05d0cda18fabcd278a2 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 10:49:44 -0700 Subject: [PATCH 119/133] test(inference): retain typed shared-route assertions Signed-off-by: Deepak Jain --- test/onboarding/onboard-inference-reconciliation.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index e644332dcef..20ee4c14a30 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -518,11 +518,11 @@ const { onboard } = require(${onboardPath}); .trim() .split("\n") .filter(Boolean); - assert.deepEqual(inferenceCommands, [], "native resume must not consult the shared route"); assert.ok( !inferenceCommands.some((command) => command.startsWith("inference set")), `native Hermes must not mutate the shared route: ${JSON.stringify(inferenceCommands)}`, ); + assert.deepEqual(inferenceCommands, [], "native resume must not consult the shared route"); assert.doesNotMatch( `${result.stderr}\n${result.stdout}`, /Hermes Provider requires a sandbox name/, From cc3d30aac46f13d65a53fd30d7446471f5c8983c Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 12:28:04 -0700 Subject: [PATCH 120/133] fix(inference): require receipts for logical native selections Signed-off-by: Deepak Jain --- .../sandbox-create/orchestration-native-nvidia.test.ts | 4 ++++ src/lib/onboard/sandbox-create/orchestration.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index 871d373dc79..22545b3f24b 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -83,6 +83,10 @@ describe("native NVIDIA post-create provider verification", () => { [true, "nemoclaw-nvidia-prod-v1"], [false, "nemoclaw-openai-api-v1"], [true, "nemoclaw-openai-api-v1"], + [false, "openai-api"], + [true, "openai-api"], + [false, "nvidia-prod"], + [true, "nvidia-prod"], ] as const)( "rejects a missing native receipt before creation with deferred=%s for %s", async (deferred, inferenceProvider) => { diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 5e24fca4d98..ae109c98404 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1449,7 +1449,7 @@ export function createProviderEffectBoundary(input: { }; const validateNativeHostedReceipt = async () => { if ( - usesNativeHostedProvider(input.preparationInput.inferenceProvider) && + usesNativeHostedProvider(preparationInput.inferenceProvider) && !input.expectedNativeHostedProviderAttachment ) { throw new Error( From d7146eb37271603408b56379351683d0ea83cd6c Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 13:02:04 -0700 Subject: [PATCH 121/133] refactor(inference): use one hosted provider authority interface Signed-off-by: Deepak Jain --- src/lib/actions/credentials-add.ts | 47 +++------------ .../actions/credentials-native-reset.test.ts | 35 ++++++------ .../credentials-provider-adapter.test.ts | 38 +++++++------ src/lib/actions/credentials/reset.ts | 16 +----- .../inference-set-openclaw-run.test.ts | 22 +++---- src/lib/actions/inference-set.test-support.ts | 7 --- src/lib/actions/inference-set.ts | 19 ++----- src/lib/inference/README.md | 8 +-- src/lib/onboard/providers.ts | 4 -- src/lib/onboard/setup-inference.test.ts | 44 +++----------- src/lib/onboard/setup-inference.ts | 33 +++-------- src/lib/state/registry-normalization.test.ts | 57 +++++++++++++------ src/lib/state/registry.ts | 5 -- .../native-nvidia-provider-authority.ts | 25 -------- test/support/setup-inference-test-harness.ts | 6 -- 15 files changed, 125 insertions(+), 241 deletions(-) diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index a3c2f1a7083..0991fee6a59 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -23,7 +23,6 @@ import { persistNativeHostedProviderAuthority, nativeHostedProviderProfilePath, } from "../inference/native-hosted"; -import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia/contract"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, TAVILY_PROVIDER_PROFILE_AGENTS, @@ -39,10 +38,6 @@ import { SECRET_PATTERNS } from "../security/secret-patterns"; import { assertEndpointResolvesPublic } from "../security/trusted-private-endpoint"; import { withMcpCredentialOwnershipLock } from "../state/mcp-lifecycle-lock/credential-ownership"; import { ROOT } from "../state/paths"; -import { - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, -} from "../state/registry/native-nvidia-provider-authority"; import { forgetExtraProvider, recordExtraProvider } from "./global"; export type CredentialsAddInput = { @@ -64,8 +59,6 @@ export type CredentialsAddDeps = Readonly<{ providerAdapter?: OpenShellProviderAdapter; getNativeHostedProviderAuthority?: typeof getNativeHostedProviderAuthority; setNativeHostedProviderAuthority?: typeof setNativeHostedProviderAuthority; - getNativeNvidiaProviderAuthority?: typeof getNativeNvidiaProviderAuthority; - setNativeNvidiaProviderAuthority?: typeof setNativeNvidiaProviderAuthority; }>; const ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,255}$/; @@ -283,7 +276,6 @@ export async function runCredentialsAddAction( const nativeHostedCredentialAlias = hostedProfile && (normalizedType === expectedType || normalizedType === hostedProfile.profileId); - const nativeNvidiaCredentialAlias = nativeHostedCredentialAlias && provider === "nvidia-prod"; const isTavily = normalizedType === TAVILY_PROVIDER_PROFILE_ID || normalizedType === HERMES_TAVILY_PROVIDER_PROFILE_ID; @@ -422,14 +414,9 @@ export async function runCredentialsAddAction( if (nativeHostedCredentialAlias) { return withMcpCredentialOwnershipLock(async () => { try { - const expected = nativeNvidiaCredentialAlias - ? (deps.getNativeNvidiaProviderAuthority ?? getNativeNvidiaProviderAuthority)( - target.gatewayName, - ) - : (deps.getNativeHostedProviderAuthority ?? getNativeHostedProviderAuthority)( - target.gatewayName, - hostedProfile!.profileId, - ); + const expected = ( + deps.getNativeHostedProviderAuthority ?? getNativeHostedProviderAuthority + )(target.gatewayName, hostedProfile!.profileId); const receipt = await ensureNativeHostedProvider({ profile: hostedProfile!, adapter: providerAdapter, @@ -448,28 +435,12 @@ export async function runCredentialsAddAction( gatewayName: target.gatewayName, receipt, readAuthority: (gatewayName) => - nativeNvidiaCredentialAlias - ? (deps.getNativeNvidiaProviderAuthority ?? getNativeNvidiaProviderAuthority)( - gatewayName, - ) - : (deps.getNativeHostedProviderAuthority ?? getNativeHostedProviderAuthority)( - gatewayName, - hostedProfile!.profileId, - ), - writeAuthority: (gatewayName, authority) => { - const nvidiaReceipt = normalizeNativeNvidiaProviderAttachment(authority); - if (nvidiaReceipt) { - (deps.setNativeNvidiaProviderAuthority ?? setNativeNvidiaProviderAuthority)( - gatewayName, - nvidiaReceipt, - ); - } else { - (deps.setNativeHostedProviderAuthority ?? setNativeHostedProviderAuthority)( - gatewayName, - authority, - ); - } - }, + (deps.getNativeHostedProviderAuthority ?? getNativeHostedProviderAuthority)( + gatewayName, + hostedProfile!.profileId, + ), + writeAuthority: + deps.setNativeHostedProviderAuthority ?? setNativeHostedProviderAuthority, }); } return ok([ diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index 72acbcabe6c..2452601b186 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -55,7 +55,7 @@ describe("native NVIDIA credential reset ownership", () => { operations.push("delete"); return deleteResult; }); - const clearNativeNvidiaProviderAuthority = vi.fn(() => operations.push("clear-authority")); + const clearNativeHostedProviderAuthority = vi.fn(() => operations.push("clear-authority")); const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName?: string) => gatewayName === "nemoclaw" ? ["alpha"] : [], ); @@ -64,7 +64,7 @@ describe("native NVIDIA credential reset ownership", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames, withGatewayRouteMutationLock: async (_gatewayName, operation) => { operations.push("lock"); @@ -79,7 +79,7 @@ describe("native NVIDIA credential reset ownership", () => { "nemoclaw", ); expect(deleteProvider).not.toHaveBeenCalled(); - expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines).toContain(" 'nvidia-prod' is recorded by sandbox(es): alpha."); expect(result.failureLines).toContain(" No provider or ownership authority was changed."); expect(result.failureLines).toContain(" nemoclaw alpha destroy"); @@ -99,7 +99,7 @@ describe("native NVIDIA credential reset ownership", () => { const deleteProvider = vi.fn(async () => ({ ok: true, })); - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const providerAdapter = adapter(deleteProvider); providerAdapter.getProvider = vi.fn(async () => state === "present" @@ -121,8 +121,7 @@ describe("native NVIDIA credential reset ownership", () => { { provider: profile.logicalProvider, confirmed: true }, { providerAdapter, - clearNativeNvidiaProviderAuthority, - clearNativeHostedProviderAuthority: clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeHostedProviderAttachmentSandboxNames: () => [], listNativeNvidiaProviderAttachmentSandboxNames: () => [], withGatewayRouteMutationLock: async (_gateway, operation) => operation(), @@ -135,7 +134,7 @@ describe("native NVIDIA credential reset ownership", () => { timeoutMs: 30_000, }); expect(deleteProvider).not.toHaveBeenCalled(); - expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines.join("\n")).toContain("ownership conflict"); }, ); @@ -199,7 +198,7 @@ describe("native NVIDIA credential reset ownership", () => { const deleteProvider = vi.fn(async () => ({ ok: true, })); - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName?: string) => gatewayName === "other-gateway" ? ["beta"] : [], ); @@ -208,7 +207,7 @@ describe("native NVIDIA credential reset ownership", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames, withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), }, @@ -221,7 +220,10 @@ describe("native NVIDIA credential reset ownership", () => { expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ "nemoclaw-nvidia-prod-v1", ]); - expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledExactlyOnceWith("nemoclaw"); + expect(clearNativeHostedProviderAuthority).toHaveBeenCalledExactlyOnceWith( + "nemoclaw", + "nemoclaw-nvidia-inference-v1", + ); }); it.each(NATIVE_HOSTED_PROFILES)( @@ -235,7 +237,6 @@ describe("native NVIDIA credential reset ownership", () => { { provider: profile.providerName, confirmed: true }, { providerAdapter, - clearNativeNvidiaProviderAuthority: vi.fn(), clearNativeHostedProviderAuthority: vi.fn(), listNativeHostedProviderAttachmentSandboxNames: () => [], listNativeNvidiaProviderAttachmentSandboxNames: () => [], @@ -264,12 +265,12 @@ describe("native NVIDIA credential reset ownership", () => { } : { ok: true }, ); - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const result = await runCredentialsResetAction( { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames: () => [], withGatewayRouteMutationLock: async (_gateway, operation) => operation(), }, @@ -278,20 +279,20 @@ describe("native NVIDIA credential reset ownership", () => { expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ "nemoclaw-nvidia-prod-v1", ]); - expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines.join("\n")).toContain("delete failed"); }, ); it("fails closed before reset when registry ownership cannot be read", async () => { const deleteProvider = vi.fn(); - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const result = await runCredentialsResetAction( { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames: () => { throw new Error("opaque registry failure"); }, @@ -301,7 +302,7 @@ describe("native NVIDIA credential reset ownership", () => { expect(result.exitCode).toBe(1); expect(deleteProvider).not.toHaveBeenCalled(); - expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines).toEqual([ " Could not safely inspect native NVIDIA inference ownership on gateway 'nemoclaw'.", " No provider or ownership authority was changed.", diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 3cb23e9fd88..203668d728c 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -116,7 +116,7 @@ describe("credential actions use typed OpenShell provider results", () => { }); const providerId = "11111111-2222-4333-8444-555555555555"; const adapter = nativeNvidiaProviderAdapter(); - const setNativeNvidiaProviderAuthority = vi.fn(); + const setNativeHostedProviderAuthority = vi.fn(); const result = await runCredentialsAddAction( { @@ -128,8 +128,8 @@ describe("credential actions use typed OpenShell provider results", () => { }, { providerAdapter: adapter, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority, + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority, }, ); @@ -146,7 +146,7 @@ describe("credential actions use typed OpenShell provider results", () => { config: [], fromExisting: false, }); - expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw", { + expect(setNativeHostedProviderAuthority).toHaveBeenCalledWith("nemoclaw", { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -170,8 +170,8 @@ describe("credential actions use typed OpenShell provider results", () => { }, { providerAdapter: adapter, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority: () => { + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority: () => { throw new Error("state directory is read-only"); }, }, @@ -202,7 +202,7 @@ describe("credential actions use typed OpenShell provider results", () => { }, })), }); - const setNativeNvidiaProviderAuthority = vi.fn(); + const setNativeHostedProviderAuthority = vi.fn(); const result = await runCredentialsAddAction( { @@ -214,20 +214,20 @@ describe("credential actions use typed OpenShell provider results", () => { }, { providerAdapter: adapter, - getNativeNvidiaProviderAuthority: () => ({ + getNativeHostedProviderAuthority: () => ({ schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", providerId: "11111111-2222-4333-8444-555555555555", }), - setNativeNvidiaProviderAuthority, + setNativeHostedProviderAuthority, }, ); expect(result.exitCode).toBe(1); expect(result.failureLines.join("\n")).toContain("changed identity"); expect(adapter.updateProvider).not.toHaveBeenCalled(); - expect(setNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(setNativeHostedProviderAuthority).not.toHaveBeenCalled(); }); it("lists the native NVIDIA provider only by its logical credential name", async () => { @@ -1042,7 +1042,7 @@ describe("credential actions use typed OpenShell provider results", () => { ); it("clears native NVIDIA gateway authority only after provider deletion is confirmed", async () => { - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const adapter = providerAdapter({ getProvider: vi.fn(async () => ({ ok: false, @@ -1055,18 +1055,21 @@ describe("credential actions use typed OpenShell provider results", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter, - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames: () => [], withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), }, ); expect(result.exitCode).toBe(0); - expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw"); + expect(clearNativeHostedProviderAuthority).toHaveBeenCalledWith( + "nemoclaw", + "nemoclaw-nvidia-inference-v1", + ); }); it("clears native NVIDIA authority when the provider is already absent", async () => { - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const adapter = providerAdapter({ getProvider: vi.fn(async () => ({ ok: false, @@ -1086,14 +1089,17 @@ describe("credential actions use typed OpenShell provider results", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter, - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames: () => [], withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), }, ); expect(result.exitCode).toBe(0); - expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw"); + expect(clearNativeHostedProviderAuthority).toHaveBeenCalledWith( + "nemoclaw", + "nemoclaw-nvidia-inference-v1", + ); }); it("reports recovery for sandboxes detached before final deletion fails (#9806)", async () => { diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 0c30b8546b3..86288121f55 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -28,7 +28,6 @@ import { } from "../../credentials/command-support"; import { prompt as askPrompt, KNOWN_CREDENTIAL_ENV_KEYS } from "../../credentials/store"; import { clearNativeHostedProviderAuthority } from "../../state/registry/native-nvidia-provider-authority"; -import { clearNativeNvidiaProviderAuthority } from "../../state/registry/native-nvidia-provider-authority"; import { withGatewayRouteMutationLock } from "../../inference/gateway-route-mutation-lock"; import { listNativeNvidiaProviderAttachmentSandboxNames, @@ -53,7 +52,6 @@ export type CredentialsResetDeps = Readonly<{ listNativeHostedProviderAttachmentSandboxNames?: typeof listNativeHostedProviderAttachmentSandboxNames; withGatewayRouteMutationLock?: typeof withGatewayRouteMutationLock; clearNativeHostedProviderAuthority?: typeof clearNativeHostedProviderAuthority; - clearNativeNvidiaProviderAuthority?: typeof clearNativeNvidiaProviderAuthority; }>; export type CredentialsProviderDeleteWithRecoveryResult = Readonly<{ @@ -228,12 +226,7 @@ export async function runCredentialsResetAction( recovery.error?.kind === "command" && recovery.error.reason === "not_found" ) { - if (nativeProfile?.logicalProvider === "nvidia-prod") { - (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( - target.gatewayName, - ); - } - if (nativeProfile && nativeProfile.logicalProvider !== "nvidia-prod") { + if (nativeProfile) { (deps.clearNativeHostedProviderAuthority ?? clearNativeHostedProviderAuthority)( target.gatewayName, nativeProfile.profileId, @@ -253,17 +246,12 @@ export async function runCredentialsResetAction( if (!outcome.ok) return fail(outcome.lines); forgetExtraProvider(publicKey); - if (nativeProfile && nativeProfile.logicalProvider !== "nvidia-prod") { + if (nativeProfile) { (deps.clearNativeHostedProviderAuthority ?? clearNativeHostedProviderAuthority)( target.gatewayName, nativeProfile.profileId, ); } - if (nativeProfile?.logicalProvider === "nvidia-prod") { - (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( - target.gatewayName, - ); - } return ok(outcome.lines); }; if (!nativeProfile) return resetProvider(); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 784851fd45f..47952a02912 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -176,11 +176,6 @@ describe("runInferenceSet OpenClaw routing", () => { model: "", }, getNativeHostedProviderAuthority: () => gatewayAuthority, - getNativeNvidiaProviderAuthority: () => ({ - ...gatewayAuthority, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - }), providerAdapter, resolveCredentialValue: () => "", }); @@ -190,10 +185,7 @@ describe("runInferenceSet OpenClaw routing", () => { deps, ); - const recordAuthority = - profile.logicalProvider === "nvidia-prod" - ? deps.calls.setNativeNvidiaProviderAuthority - : deps.calls.setNativeHostedProviderAuthority; + const recordAuthority = deps.calls.setNativeHostedProviderAuthority; expect(recordAuthority).toHaveBeenCalledWith("nemoclaw", gatewayAuthority); expect(deps.calls.updateSandbox).toHaveBeenCalledWith( "alpha", @@ -252,7 +244,7 @@ describe("runInferenceSet OpenClaw routing", () => { model: "nvidia/previous-model", nativeHostedProviderAttachment: gatewayAuthority, }, - getNativeNvidiaProviderAuthority: () => gatewayAuthority, + getNativeHostedProviderAuthority: () => gatewayAuthority, providerAdapter, resolveCredentialValue: () => "replacement-credential", }); @@ -265,7 +257,7 @@ describe("runInferenceSet OpenClaw routing", () => { expect(providerAdapter.updateProvider).toHaveBeenCalledOnce(); expect(getProvider).toHaveBeenCalledTimes(2); - expect(deps.calls.setNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(deps.calls.setNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(attachProvider).not.toHaveBeenCalled(); expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); @@ -367,8 +359,8 @@ describe("runInferenceSet OpenClaw routing", () => { providerId: "previous-openai-id", }, }, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority: () => { + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority: () => { throw new Error("state directory is read-only"); }, providerAdapter, @@ -948,7 +940,7 @@ describe("runInferenceSet OpenClaw routing", () => { }, entry, updateSandbox, - getNativeNvidiaProviderAuthority: () => attachment, + getNativeHostedProviderAuthority: () => attachment, resolveCredentialValue: (key) => (key === "OPENAI_API_KEY" ? "synthetic-openai-key" : ""), }); @@ -1004,7 +996,7 @@ describe("runInferenceSet OpenClaw routing", () => { provider: "ollama-local", model: "gpt-5.4", }, - getNativeNvidiaProviderAuthority: () => ({ + getNativeHostedProviderAuthority: () => ({ schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index 2ed3fa7a3b9..8a900cd4821 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -283,8 +283,6 @@ export function createDeps(options: { settleOpenClawPairing?: InferenceSetDeps["settleOpenClawPairing"]; withGatewayRouteMutationLock?: InferenceSetDeps["withGatewayRouteMutationLock"]; getNativeHostedProviderAuthority?: InferenceSetDeps["getNativeHostedProviderAuthority"]; - getNativeNvidiaProviderAuthority?: InferenceSetDeps["getNativeNvidiaProviderAuthority"]; - setNativeNvidiaProviderAuthority?: InferenceSetDeps["setNativeNvidiaProviderAuthority"]; setNativeHostedProviderAuthority?: InferenceSetDeps["setNativeHostedProviderAuthority"]; }): InferenceSetDeps & { calls: { @@ -310,7 +308,6 @@ export function createDeps(options: { restartSandboxGateway: ReturnType; settleOpenClawPairing: ReturnType; withGatewayRouteMutationLock: ReturnType; - setNativeNvidiaProviderAuthority: ReturnType; setNativeHostedProviderAuthority: ReturnType; }; getSession: () => Session | null; @@ -394,7 +391,6 @@ export function createDeps(options: { (async (_gatewayName: string, operation: () => Promise | unknown) => await operation()), ), - setNativeNvidiaProviderAuthority: vi.fn(), setNativeHostedProviderAuthority: vi.fn(), }; const providerAdapter = @@ -448,9 +444,6 @@ export function createDeps(options: { getNativeHostedProviderAuthority: options.getNativeHostedProviderAuthority, setNativeHostedProviderAuthority: options.setNativeHostedProviderAuthority ?? calls.setNativeHostedProviderAuthority, - getNativeNvidiaProviderAuthority: options.getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority: - options.setNativeNvidiaProviderAuthority ?? calls.setNativeNvidiaProviderAuthority, updateSandbox: calls.updateSandbox, getRequestedAgent: () => options.requestedAgent, loadSession: () => session, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 09e02f1b102..9733f27b7b2 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -22,7 +22,6 @@ import { ensureNativeHostedProviderAttached, isNativeHostedProvider, normalizeNativeHostedProviderAttachment, - normalizeNativeNvidiaProviderAttachment, resolveGatewayNativeHostedProviderAuthority, resolveAgentInferenceApi, type NativeHostedProviderAttachment, @@ -183,8 +182,6 @@ export interface InferenceSetDeps extends InferenceGatewayRestartDeps { defaultSandbox: string | null; }; getNativeHostedProviderAuthority?: typeof registry.getNativeHostedProviderAuthority; - getNativeNvidiaProviderAuthority?: typeof registry.getNativeNvidiaProviderAuthority; - setNativeNvidiaProviderAuthority: typeof registry.setNativeNvidiaProviderAuthority; setNativeHostedProviderAuthority: typeof registry.setNativeHostedProviderAuthority; updateSandbox: (name: string, updates: Partial) => boolean; getRequestedAgent: () => string | null | undefined; @@ -319,8 +316,6 @@ function defaultDeps(): InferenceSetDeps { getSandbox: registry.getSandbox, listSandboxes: registry.listSandboxes, getNativeHostedProviderAuthority: registry.getNativeHostedProviderAuthority, - getNativeNvidiaProviderAuthority: registry.getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority: registry.setNativeNvidiaProviderAuthority, setNativeHostedProviderAuthority: registry.setNativeHostedProviderAuthority, updateSandbox: registry.updateSandbox, getRequestedAgent: () => process.env.NEMOCLAW_AGENT, @@ -1329,12 +1324,10 @@ function readRegisteredNativeAuthority( gatewayName: string, provider: string, ) { - return provider === "nvidia-prod" - ? deps.getNativeNvidiaProviderAuthority?.(gatewayName) - : deps.getNativeHostedProviderAuthority?.( - gatewayName, - nativeHostedProfile(provider)!.profileId, - ); + return deps.getNativeHostedProviderAuthority?.( + gatewayName, + nativeHostedProfile(provider)!.profileId, + ); } function recordNativeProviderAuthority( @@ -1343,9 +1336,7 @@ function recordNativeProviderAuthority( attachment?: NativeHostedProviderAttachment, ): void { if (!attachment) return; - const nvidiaAuthority = normalizeNativeNvidiaProviderAttachment(attachment); - if (nvidiaAuthority) deps.setNativeNvidiaProviderAuthority(gatewayName, nvidiaAuthority); - else deps.setNativeHostedProviderAuthority(gatewayName, attachment); + deps.setNativeHostedProviderAuthority(gatewayName, attachment); } function inferenceSelectionRecoveryDetail( diff --git a/src/lib/inference/README.md b/src/lib/inference/README.md index fc5ba7280b1..fc8e67d08fa 100644 --- a/src/lib/inference/README.md +++ b/src/lib/inference/README.md @@ -46,10 +46,10 @@ Existing beta sandboxes without an attachment receipt require recreation. Status and launch readiness must refuse missing or mismatched ownership; they must not substitute the shared route. Native probes preserve the selected API protocol and the recorded gateway. Custom endpoints and local providers retain their existing routing behavior. -V1alpha1 configuration export supports native NVIDIA attachments. Other native hosted -profiles require an exporter follow-up and are refused before publication. Exporting an -older shared-route sandbox continues to verify its original image endpoint without -implicitly migrating it. +V1alpha1 configuration export supports native NVIDIA, OpenAI, Anthropic, OpenRouter, +and Hermes Provider attachments. Gemini export is refused before publication because +V1 cannot consume that provider. Exporting an older shared-route sandbox continues to +verify its original image endpoint without implicitly migrating it. Agent configuration preserves the provider's API protocol and native base URL. OpenRouter attribution comes from `native-hosted/openrouter-headers.ts` and is configured in each supported agent. diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index defef5a249f..e07016ea690 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -20,8 +20,6 @@ const { createCliOpenShellProviderAdapter } = require("../adapters/openshell/pro const { getNativeHostedProviderAuthority, setNativeHostedProviderAuthority, - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, } = require("../state/registry/native-nvidia-provider-authority"); const { LLAMA_CPP_CREDENTIAL_ENV, @@ -401,8 +399,6 @@ function setupInferenceProviderDeps(runOpenshell) { providerAdapter: createCliOpenShellProviderAdapter({ run: runOpenshell }), getNativeHostedProviderAuthority, setNativeHostedProviderAuthority, - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, }; } diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 538212fda71..f12f13f6755 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -214,7 +214,6 @@ describe("native NVIDIA onboarding", () => { } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); const updateSandbox = vi.fn(() => true); - const setNativeNvidiaProviderAuthority = vi.fn(() => true); const setNativeHostedProviderAuthority = vi.fn(); const verifyInferenceRoute = vi.fn(); const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); @@ -228,7 +227,6 @@ describe("native NVIDIA onboarding", () => { getGatewayName: () => "onboarding-gateway", runOpenshell, updateSandbox, - setNativeNvidiaProviderAuthority, setNativeHostedProviderAuthority, getSandbox: () => null, upsertProvider: vi.fn(async () => ({ ok: true })), @@ -296,36 +294,12 @@ describe("native NVIDIA onboarding", () => { }, }), ); - expect(setNativeHostedProviderAuthority.mock.calls).toEqual( - profile.logicalProvider === "nvidia-prod" - ? [] - : [ - [ - "onboarding-gateway", - { - schemaVersion: 1, - profileId: profile.profileId, - providerName: profile.providerName, - providerId: "provider-id", - }, - ], - ], - ); - expect(setNativeNvidiaProviderAuthority.mock.calls).toEqual( - profile.logicalProvider === "nvidia-prod" - ? [ - [ - "onboarding-gateway", - { - schemaVersion: 1, - profileId: profile.profileId, - providerName: profile.providerName, - providerId: "provider-id", - }, - ], - ] - : [], - ); + expect(setNativeHostedProviderAuthority).toHaveBeenCalledExactlyOnceWith("onboarding-gateway", { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }); }); it("removes a new provider when gateway authority persistence fails (#12562)", async () => { @@ -373,8 +347,8 @@ describe("native NVIDIA onboarding", () => { runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), updateSandbox, getSandbox: () => null, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority: () => { + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority: () => { throw new Error("state directory is read-only"); }, upsertProvider: vi.fn(async () => ({ ok: true })), @@ -440,7 +414,7 @@ describe("native NVIDIA onboarding", () => { runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), updateSandbox, getSandbox: () => null, - getNativeNvidiaProviderAuthority: () => ({ + getNativeHostedProviderAuthority: () => ({ schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 2a733cc8235..5d55da1ca7d 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -21,7 +21,6 @@ import { } from "../inference/gateway-route-mutation-lock"; import { getManagedVllmProviderBinding, shouldFrontOllamaWithProxy } from "../inference/local"; import { - normalizeNativeNvidiaProviderAttachment, nativeHostedProfile, ensureNativeHostedProvider, persistNativeHostedProviderAuthority, @@ -241,8 +240,6 @@ export type SetupInferenceDeps = ProviderBranchDeps & { listSandboxes?: typeof import("../state/registry").listSandboxes; getNativeHostedProviderAuthority?: typeof import("../state/registry").getNativeHostedProviderAuthority; setNativeHostedProviderAuthority?: typeof import("../state/registry").setNativeHostedProviderAuthority; - getNativeNvidiaProviderAuthority?: typeof import("../state/registry").getNativeNvidiaProviderAuthority; - setNativeNvidiaProviderAuthority?: typeof import("../state/registry").setNativeNvidiaProviderAuthority; unloadOllamaModels?: (onlyModels: readonly string[]) => OllamaUnloadResult | void; withOllamaModelOwnershipLock?: typeof withOllamaModelOwnershipLock; withOllamaModelOwnershipTransaction?: typeof withOllamaModelOwnershipTransaction; @@ -957,13 +954,10 @@ export function createSetupInference( let providerAuthority = selectedNativeProfile ? resolveGatewayNativeHostedProviderAuthority({ profile: selectedNativeProfile, - gatewayAuthority: - provider === "nvidia-prod" - ? deps.getNativeNvidiaProviderAuthority?.(gatewayName) - : deps.getNativeHostedProviderAuthority?.( - gatewayName, - selectedNativeProfile.profileId, - ), + gatewayAuthority: deps.getNativeHostedProviderAuthority?.( + gatewayName, + selectedNativeProfile.profileId, + ), gatewayName, recordedGatewayName: recordedSandbox?.gatewayName, recordedAttachment, @@ -1023,21 +1017,10 @@ export function createSetupInference( reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, ...(providerAuthority ? { expected: providerAuthority } : {}), }); - const nvidiaAuthority = normalizeNativeNvidiaProviderAttachment( - nativeHostedProviderAttachment, - ); - const readAuthority = nvidiaAuthority - ? deps.getNativeNvidiaProviderAuthority - : deps.getNativeHostedProviderAuthority && - ((name: string) => deps.getNativeHostedProviderAuthority!(name, profile.profileId)); - const writeAuthority = nvidiaAuthority - ? deps.setNativeNvidiaProviderAuthority && - ((name: string, receipt: NativeHostedProviderAttachment) => - deps.setNativeNvidiaProviderAuthority!( - name, - normalizeNativeNvidiaProviderAttachment(receipt)!, - )) - : deps.setNativeHostedProviderAuthority; + const readAuthority = + deps.getNativeHostedProviderAuthority && + ((name: string) => deps.getNativeHostedProviderAuthority!(name, profile.profileId)); + const writeAuthority = deps.setNativeHostedProviderAuthority; if (readAuthority && writeAuthority) { await persistNativeHostedProviderAuthority({ adapter: providerAdapter, diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index e64cfd6972f..35abd78bcfd 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -57,7 +57,7 @@ describe("sandbox registry normalization", () => { ).toEqual(document); }); - it("migrates NVIDIA ownership to one durable authority and shares compatibility API cleanup", async () => { + it("migrates legacy NVIDIA ownership alongside another hosted authority through the generic API", async () => { const receipt = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1", @@ -77,18 +77,37 @@ describe("sandbox registry normalization", () => { ); expect(disk).not.toHaveProperty("nativeNvidiaProviderAuthorities"); expect(disk.gatewayNativeHostedProviderAuthorities).toEqual({ first: [receipt] }); - expect(() => - registry.setNativeNvidiaProviderAuthority("first", { ...receipt, providerId: "foreign" }), - ).toThrow("Conflicting native provider ownership receipts"); + const hostedReceipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "openai-owned", + }; + registry.setNativeHostedProviderAuthority("first", hostedReceipt); + expect(registry.getNativeHostedProviderAuthority("first", hostedReceipt.profileId)).toEqual( + hostedReceipt, + ); + expect(registry.load().gatewayNativeHostedProviderAuthorities?.first).toEqual([ + receipt, + hostedReceipt, + ]); expect(() => registry.setNativeHostedProviderAuthority("first", { ...receipt, providerId: "foreign" }), ).toThrow("Conflicting native provider ownership receipts"); - expect(registry.getNativeNvidiaProviderAuthority("first")).toEqual(receipt); + expect( + registry.getNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"), + ).toEqual(receipt); registry.clearNativeHostedProviderAuthority("first", receipt.profileId); - expect(registry.getNativeNvidiaProviderAuthority("first")).toBeUndefined(); - registry.setNativeNvidiaProviderAuthority("first", receipt); + expect( + registry.getNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"), + ).toBeUndefined(); + registry.setNativeHostedProviderAuthority("first", receipt); expect(registry.getNativeHostedProviderAuthority("first", receipt.profileId)).toEqual(receipt); - registry.clearNativeNvidiaProviderAuthority("first"); + registry.clearNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"); + expect(registry.getNativeHostedProviderAuthority("first", hostedReceipt.profileId)).toEqual( + hostedReceipt, + ); + registry.clearNativeHostedProviderAuthority("first", hostedReceipt.profileId); expect(registry.load().gatewayNativeHostedProviderAuthorities).toBeUndefined(); }); @@ -107,9 +126,9 @@ describe("sandbox registry normalization", () => { }, }; const { home, registry } = await loadRegistryDocument(document); - expect(() => registry.getNativeNvidiaProviderAuthority("first")).toThrow( - "Conflicting native provider ownership receipts", - ); + expect(() => + registry.getNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"), + ).toThrow("Conflicting native provider ownership receipts"); expect( JSON.parse(fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8")), ).toEqual(document); @@ -260,9 +279,13 @@ describe("sandbox registry normalization", () => { }, }); - expect(registry.getNativeNvidiaProviderAuthority("broken")).toBeUndefined(); - expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toEqual(receipt); - registry.setNativeNvidiaProviderAuthority("nemoclaw-19081", { + expect( + registry.getNativeHostedProviderAuthority("broken", "nemoclaw-nvidia-inference-v1"), + ).toBeUndefined(); + expect( + registry.getNativeHostedProviderAuthority("nemoclaw-19080", "nemoclaw-nvidia-inference-v1"), + ).toEqual(receipt); + registry.setNativeHostedProviderAuthority("nemoclaw-19081", { ...receipt, providerId: "22222222-3333-4444-8555-666666666666", }); @@ -270,8 +293,10 @@ describe("sandbox registry normalization", () => { "nemoclaw-19080": [receipt], "nemoclaw-19081": [{ ...receipt, providerId: "22222222-3333-4444-8555-666666666666" }], }); - registry.clearNativeNvidiaProviderAuthority("nemoclaw-19080"); - expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toBeUndefined(); + registry.clearNativeHostedProviderAuthority("nemoclaw-19080", "nemoclaw-nvidia-inference-v1"); + expect( + registry.getNativeHostedProviderAuthority("nemoclaw-19080", "nemoclaw-nvidia-inference-v1"), + ).toBeUndefined(); expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeHostedProviderAuthorities"); expect(registry.getSandbox("beta")).not.toHaveProperty("nativeNvidiaProviderAuthority"); expect(registry.getSandbox("beta")?.nativeHostedProviderAttachment).toEqual(receipt); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 8d16b12be53..9fa4c5a6872 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -70,11 +70,6 @@ export { listExtraProviders, removeExtraProvider, } from "./registry/extra-providers"; -export { - clearNativeNvidiaProviderAuthority, - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, -} from "./registry/native-nvidia-provider-authority"; import { isDcodeAutoApprovalMode } from "../onboard/dcode-auto-approval"; import { cloneSandboxHostMounts, hasUnsafeHostMountTerminalText } from "./registry/host-mount"; diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index a138eab1a4a..928e23204b4 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -11,35 +11,10 @@ import { } from "../../inference/native-hosted/authority"; import { isValidNativeProviderGateway as isValidName } from "./native-nvidia-provider-authority-state"; -import { - normalizeNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia/contract"; import type { SandboxRegistry } from "./types"; import { withLock } from "./lock"; import { load, save } from "./persistence"; -export function getNativeNvidiaProviderAuthority( - gatewayName: string, -): NativeNvidiaProviderAttachment | undefined { - return normalizeNativeNvidiaProviderAttachment( - getNativeHostedProviderAuthority(gatewayName, "nemoclaw-nvidia-inference-v1"), - ); -} - -export function setNativeNvidiaProviderAuthority( - gatewayName: string, - receipt: NativeNvidiaProviderAttachment, -): void { - if (receipt.profileId !== "nemoclaw-nvidia-inference-v1") - throw new Error("Invalid native NVIDIA gateway provider authority"); - setNativeHostedProviderAuthority(gatewayName, receipt); -} - -export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { - clearNativeHostedProviderAuthority(gatewayName, "nemoclaw-nvidia-inference-v1"); -} - export function getNativeHostedProviderAuthority( gatewayName: string, profileId: string, diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 2f95b6a84aa..1abfba115ae 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -13,7 +13,6 @@ import { } from "../../src/lib/onboard/setup-inference.js"; import { redact } from "../../src/lib/security/redact.js"; import type { NativeHostedProviderAttachment } from "../../src/lib/inference/native-hosted/contract"; -import type { NativeNvidiaProviderAttachment } from "../../src/lib/inference/native-nvidia/contract"; const onboardProviderHelpers = require("../../src/lib/onboard/providers") as { upsertProvider: ( @@ -333,7 +332,6 @@ export function createDirectSetupInferenceHarnessFactory( ) { return function createDirectSetupInferenceHarness(options: DirectSetupHarnessOptions = {}) { const hostedAuthorities = new Map(); - const nvidiaAuthorities = new Map(); const commands: DirectCommandEntry[] = []; const errors: string[] = []; const logs: string[] = []; @@ -500,10 +498,6 @@ export function createDirectSetupInferenceHarnessFactory( setNativeHostedProviderAuthority: (gateway, receipt) => { hostedAuthorities.set(`${gateway}/${receipt.profileId}`, receipt); }, - getNativeNvidiaProviderAuthority: (gateway) => nvidiaAuthorities.get(gateway), - setNativeNvidiaProviderAuthority: (gateway, receipt) => { - nvidiaAuthorities.set(gateway, receipt); - }, getSandbox: () => null, listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), unloadOllamaModels, From 3c6149c23fad7d72e42c9242fc0fc54b98ea23b2 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 13:13:45 -0700 Subject: [PATCH 122/133] fix(config): identify legacy exports from retained routing Signed-off-by: Deepak Jain --- .../config/verify-export-source.test.ts | 23 +++++++++++++++++++ src/lib/domain/config/verify-export-source.ts | 18 +++++++++++---- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/lib/domain/config/verify-export-source.test.ts b/src/lib/domain/config/verify-export-source.test.ts index 82ed776d8af..688cb4b89e4 100644 --- a/src/lib/domain/config/verify-export-source.test.ts +++ b/src/lib/domain/config/verify-export-source.test.ts @@ -615,6 +615,29 @@ describe("config export source verification (#10938)", () => { }, ); + it.each([ + ["https://inference.local/v1", true], + ["https://api.openai.com/v1", false], + ] as const)( + "requires retained legacy routing or a native receipt for %s", + async (routedBaseUrl, legacy) => { + const observed = changeRetainedProfile( + hermesSnapshot({ endpointUrl: "https://api.openai.com/v1" }), + (profile) => { + profile.inference!.routedBaseUrl = routedBaseUrl; + }, + ); + const result = await exportSnapshots([observed]); + expect(result.outcome.ok).toBe(legacy); + expect(result.publish).not.toHaveBeenCalled(); + expect( + result.writeStdout.mock.calls.map( + ([yaml]) => asExportedConfig(YAML.parse(yaml)).spec.inferenceProviders[0]!.endpoint, + ), + ).toEqual(legacy ? ["https://api.openai.com/v1"] : []); + }, + ); + it("rejects a credential-bearing HTTP inference route that v1 cannot consume (#11977)", () => { const endpoint = "http://host.openshell.internal:35271/v1"; const observed = hermesSnapshot({ toolDisclosure: "progressive", endpointUrl: endpoint }); diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 436d9a616d2..6da1f6bf81f 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -527,6 +527,7 @@ function deepAgentsObservability( function preserveLegacyExportEndpoint( entry: ObservedExportRegistry, inference: ReturnType, + retainedProfile: ManagedStartupProfile, ): void { // Export verifies the retained image contract; older hosted sandboxes were // built for the shared route and do not acquire native access by inspection. @@ -535,14 +536,21 @@ function preserveLegacyExportEndpoint( entry.provider !== "nvidia-prod" && nativeHostedProfile(entry.provider) ) { - inference.inferenceBaseUrl = + const legacyEndpoint = inference.inferenceApi === "anthropic-messages" ? "https://inference.local" : "https://inference.local/v1"; + if (retainedProfile.inference?.routedBaseUrl !== legacyEndpoint) { + throw new Error("Native hosted export requires its provider ownership receipt."); + } + inference.inferenceBaseUrl = legacyEndpoint; } } -function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedStartupProfile { +function expectedManagedStartupProfile( + entry: ObservedExportRegistry, + retainedProfile: ManagedStartupProfile, +): ManagedStartupProfile { if (!isSupportedExportAgent(entry.agent)) { throw new Error("The agent is unsupported."); } @@ -562,7 +570,7 @@ function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedSt selected.model, selected.preferredInferenceApi, ); - preserveLegacyExportEndpoint(entry, inference); + preserveLegacyExportEndpoint(entry, inference, retainedProfile); const projection = EXPORT_AGENT_PROFILE_PROJECTIONS[agent](inference); const search = exportWebSearchBinding(entry); return buildManagedStartupProfile({ @@ -767,7 +775,7 @@ function expectedProfileWithObservedHostSettings( profile: ManagedStartupProfile, ): ManagedStartupProfile | null { try { - let expected = supportedHostProfile(profile, expectedManagedStartupProfile(entry)); + let expected = supportedHostProfile(profile, expectedManagedStartupProfile(entry, profile)); const servingPreset = profile.inference?.servingPreset; if ( expected.inference && @@ -1530,7 +1538,7 @@ function projectHostSettings( const proxy = authority.profile.proxy; return { ...(interfaces ? { interfaces } : {}), - ...(!hasEqualJsonStructure(proxy, expectedManagedStartupProfile(entry).proxy) + ...(!hasEqualJsonStructure(proxy, expectedManagedStartupProfile(entry, authority.profile).proxy) ? { proxy: { host: proxy.managedHost, port: proxy.managedPort } } : {}), }; From 79daec818a7e5431ea39875e8c48111e7037a8ae Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 14:23:46 -0700 Subject: [PATCH 123/133] fix(inference): preserve Hermes host credential identity Signed-off-by: Deepak Jain --- agents/hermes/Dockerfile | 2 +- src/lib/actions/credentials-add.ts | 9 ++++----- src/lib/actions/credentials-native-hosted.test.ts | 11 +++++++++-- test/e2e-runtime/nemoclaw-cli-recovery.test.ts | 6 +++++- test/onboarding/onboard-messaging-reuse.test.ts | 4 +++- 5 files changed, 22 insertions(+), 10 deletions(-) diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index 05ed1eaa954..605b6cfd1bc 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -378,7 +378,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/inference/native-hosted/profiles.ts /src/lib/hermes-managed-route.ts /src/lib/tool-disclosure.ts /src/lib/providerless-inference.ts \ + && chmod 444 /src/lib/inference/native-hosted/profiles.ts /src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/hermes-managed-route.ts /src/lib/tool-disclosure.ts /src/lib/providerless-inference.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/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index 0991fee6a59..86525b38474 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -401,13 +401,14 @@ export async function runCredentialsAddAction( return fail(recoveryFailureLines); } + const hostedHostCredentialEnv = hostedProfile?.hostCredentialEnv ?? hostedProfile?.credentialEnv; if ( nativeHostedCredentialAlias && !fromExisting && - (credentials.length !== 1 || credentials[0] !== hostedProfile!.credentialEnv) + (credentials.length !== 1 || credentials[0] !== hostedHostCredentialEnv) ) { return fail([ - ` Native ${hostedProfile!.label} inference requires exactly --credential ${hostedProfile!.credentialEnv}.`, + ` Native ${hostedProfile!.label} inference requires exactly --credential ${hostedHostCredentialEnv}.`, ]); } @@ -421,9 +422,7 @@ export async function runCredentialsAddAction( profile: hostedProfile!, adapter: providerAdapter, target, - credentialValue: fromExisting - ? null - : (process.env[hostedProfile!.credentialEnv] ?? null), + credentialValue: fromExisting ? null : (process.env[hostedHostCredentialEnv!] ?? null), reuseExistingCredential: fromExisting, ...(expected ? { expected } : {}), }); diff --git a/src/lib/actions/credentials-native-hosted.test.ts b/src/lib/actions/credentials-native-hosted.test.ts index b24115233c9..9bf89f63748 100644 --- a/src/lib/actions/credentials-native-hosted.test.ts +++ b/src/lib/actions/credentials-native-hosted.test.ts @@ -33,7 +33,9 @@ describe("native hosted credential registration", () => { const recordExtraProvider = vi .spyOn(await import("./global"), "recordExtraProvider") .mockReturnValue(true); - vi.stubEnv(profile.credentialEnv, "host-only-test-value"); + const hostCredential = profile.hostCredentialEnv ?? profile.credentialEnv; + vi.stubEnv("OPENAI_API_KEY", "unrelated-openai-key"); + vi.stubEnv(hostCredential, "host-only-test-value"); let present = false; const adapter = providerAdapter({ getProvider: vi.fn(async () => @@ -67,7 +69,7 @@ describe("native hosted credential registration", () => { { provider: profile.logicalProvider, type: profile.profileId, - credentials: [profile.credentialEnv], + credentials: [hostCredential], configPairs: [], fromExisting: false, }, @@ -78,6 +80,11 @@ describe("native hosted credential registration", () => { }, ); expect(result.exitCode).toBe(0); + expect(adapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + credentials: [{ name: profile.credentialEnv, value: "host-only-test-value" }], + }), + ); expect(save).toHaveBeenCalledWith("nemoclaw", { schemaVersion: 1, profileId: profile.profileId, diff --git a/test/e2e-runtime/nemoclaw-cli-recovery.test.ts b/test/e2e-runtime/nemoclaw-cli-recovery.test.ts index 84d26be2d3d..9fd33374714 100644 --- a/test/e2e-runtime/nemoclaw-cli-recovery.test.ts +++ b/test/e2e-runtime/nemoclaw-cli-recovery.test.ts @@ -47,6 +47,7 @@ describe("nemoclaw CLI runtime recovery", () => { stateFile, JSON.stringify({ statusCalls: 0, + connected: false, sandboxGetCalls: 0, gatewaySelectCalls: 0, gatewayStartCalls: 0, @@ -64,7 +65,7 @@ const state = JSON.parse(fs.readFileSync(statePath, "utf8")); if (args[0] === "status") { state.statusCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); - if (state.statusCalls === 1) { + if (!state.connected) { process.stdout.write("Gateway: nemoclaw\\nStatus: Disconnected\\n"); } else { process.stdout.write("Gateway: nemoclaw\\nStatus: Connected\\n"); @@ -80,6 +81,7 @@ if (args[0] === "gateway" && args[1] === "start") { if (args[0] === "gateway" && args[1] === "select") { state.gatewaySelectCalls += 1; + state.connected = true; fs.writeFileSync(statePath, JSON.stringify(state)); process.exit(0); } @@ -93,6 +95,8 @@ if (args[0] === "sandbox" && args[1] === "get" && (args[2] === "my-assistant" || state.sandboxGetCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); if (state.sandboxGetCalls === 1) { + state.connected = false; + fs.writeFileSync(statePath, JSON.stringify(state)); process.stdout.write("Error: × transport error\\n ╰─▶ Connection reset by peer (os error 104)\\n"); process.exit(1); } diff --git a/test/onboarding/onboard-messaging-reuse.test.ts b/test/onboarding/onboard-messaging-reuse.test.ts index a2e780a4fa0..eef952e3d94 100644 --- a/test/onboarding/onboard-messaging-reuse.test.ts +++ b/test/onboarding/onboard-messaging-reuse.test.ts @@ -112,7 +112,9 @@ const { createSandbox } = require(${onboardPath}); // Existing gateway providers do not select messaging for this onboarding request. const providerUpserts = payload.commands.filter((entry: CommandEntry) => - entry.command.includes("provider update"), + /provider (?:create|update|delete)\b.*my-assistant-(?:discord-bridge|slack-bridge|slack-app)\b/u.test( + entry.command, + ), ); assert.equal( providerUpserts.length, From 11f3cedda5f52b3bd0c85c354de5207feb7883a9 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 15:16:51 -0700 Subject: [PATCH 124/133] fix(inference): preserve native ownership across rebuild integration Signed-off-by: Deepak Jain --- .../generate-config.ts | 1 + .../sandbox/rebuild-credential-preflight.ts | 19 ++- .../rebuild-flow-credential-preflight.test.ts | 67 +++++++-- .../rebuild-flow-target-credentials.test.ts | 60 +++++++- src/lib/actions/sandbox/rebuild-pipeline.ts | 16 +- .../sandbox/rebuild-preflight-phase.ts | 3 +- .../rebuild-provider-preflight.test.ts | 142 ++++++++++++++++++ .../sandbox/rebuild-provider-preflight.ts | 82 +++++++--- .../actions/sandbox/rebuild-resume-config.ts | 4 +- src/lib/inference/native-hosted/index.test.ts | 43 ++++++ src/lib/inference/native-hosted/index.ts | 10 ++ .../onboard/build-credential-reuse.test.ts | 45 ++++-- src/lib/onboard/build-credential-reuse.ts | 12 +- ...epagents-code-managed-model-params.test.ts | 2 +- test/helpers/credentials-provider-adapter.ts | 3 + test/helpers/onboard-split-context.ts | 3 + .../onboard-inference-reconciliation.test.ts | 4 +- .../native-provider-command-runtime.ts | 7 + 18 files changed, 456 insertions(+), 67 deletions(-) diff --git a/agents/langchain-deepagents-code/generate-config.ts b/agents/langchain-deepagents-code/generate-config.ts index 3e45b377f1b..b8b1410181a 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -15,6 +15,7 @@ import { normalizeManagedDcodeEndpointUrl, resolveManagedDcodeIdentity, } from "../../src/lib/inference/managed-dcode/identity.ts"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../src/lib/inference/native-nvidia/contract.ts"; import { NATIVE_HOSTED_PROFILES } from "../../src/lib/inference/native-hosted/profiles.ts"; import { OPENROUTER_DEFAULT_HEADERS } from "../../src/lib/inference/native-hosted/openrouter-headers.ts"; diff --git a/src/lib/actions/sandbox/rebuild-credential-preflight.ts b/src/lib/actions/sandbox/rebuild-credential-preflight.ts index 575918952b9..09dc2ddde28 100644 --- a/src/lib/actions/sandbox/rebuild-credential-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-credential-preflight.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { runOpenshell } from "../../adapters/openshell/runtime"; -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia/contract"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; import { CLI_NAME } from "../../cli/branding"; import { R, RD } from "../../cli/terminal-style"; import type { RebuildSandboxEntry } from "./rebuild-flow-helpers"; @@ -66,7 +66,10 @@ async function preflightHermesProviderCredentials( if (binding.exists) { const matches = - binding.credentialKeys?.length === 1 && binding.credentialKeys[0] === expectedCredentialEnv; + binding.credentialKeys?.length === 1 && + (binding.credentialKeys[0] === expectedCredentialEnv || + (authMethod === "api_key" && + binding.credentialKeys[0] === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV)); if (matches) { log("Hermes Provider rebuild preflight: credential binding matches"); return true; @@ -116,9 +119,15 @@ export async function preflightRebuildCredentials( sb.endpointUrl, ); const rebuildProvider = sb.provider; - const nativeAttachment = normalizeNativeNvidiaProviderAttachment( - sb.nativeNvidiaProviderAttachment, - ); + const rawAttachment = + sb.nativeHostedProviderAttachment !== undefined + ? sb.nativeHostedProviderAttachment + : sb.nativeNvidiaProviderAttachment; + const nativeAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); + if (rawAttachment !== undefined && !nativeAttachment) { + bail("Malformed native provider attachment; sandbox is untouched."); + return false; + } if (nativeAttachment) { return checkRebuildGatewayProviderOrBail(rebuildProvider, rebuildCredentialEnv, log, bail, { nativeAttachment, diff --git a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts index 5587a7a6521..514558e6076 100644 --- a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts @@ -13,7 +13,10 @@ import { nativeHostedProfile, NATIVE_HOSTED_PROFILES, } from "../../inference/native-hosted/profiles"; -import { makePreparedRecoveryManifest } from "./rebuild-flow-test-fixtures"; +import { + makePreparedRecoveryManifest, + nativeProviderRebuildScenario, +} from "./rebuild-flow-test-fixtures"; function createRebuildFlowHarness( options: NonNullable[0]>, @@ -37,9 +40,12 @@ function createRebuildFlowHarness( : {}), ...(profile?.logicalProvider === "hermes-provider" && !options.runOpenshell ? { - runOpenshell: providerRuntime(["hermes-provider"], { - "hermes-provider": "OPENAI_API_KEY", - }), + runOpenshell: providerRuntime( + options.hermesProviderExists === false ? [] : ["hermes-provider"], + { + "hermes-provider": "OPENAI_API_KEY", + }, + ), } : {}), }); @@ -275,10 +281,27 @@ describe("rebuildSandbox flow: credential preflight", () => { provider: "nvidia-prod", model: MODEL, credentialEnv: "NVIDIA_INFERENCE_API_KEY", + nativeHostedProviderAttachment: undefined, }, hydrateCredentialEnv: (credentialEnv) => credentialEnv === "NVIDIA_INFERENCE_API_KEY" ? "saved-provider-key" : null, - runOpenshell: providerRuntime(["nvidia-prod"]), + runOpenshell: (args) => { + const stdout = + args[1] === "get" + ? "Name: nvidia-prod\nType: nvidia\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: NVIDIA_BASE_URL" + : JSON.stringify([ + { + name: "nvidia-prod", + credential_keys: ["NVIDIA_INFERENCE_API_KEY"], + credential_expires_at_ms: {}, + }, + ]); + return args.includes("nemoclaw-nvidia-prod-v1") + ? { status: 1, output: "provider not found", stdout: "", stderr: "provider not found" } + : args[0] === "provider" && ["get", "list"].includes(args[1]) + ? { status: 0, output: stdout, stdout, stderr: "" } + : undefined; + }, }); configureSession(harness, "nvidia-prod", "NVIDIA_INFERENCE_API_KEY"); @@ -888,16 +911,24 @@ describe("rebuildSandbox flow: credential preflight", () => { hermesAuthMethod: "api_key", }); - await expect( - harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow("Missing Hermes Provider credentials"); + const failure = await harness + .rebuildSandbox("alpha", ["--yes"], { throwOnError: true }) + .catch((error: Error) => error); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain( + "Native inference provider identity changed or is missing", + ); expect(harness.registerHermesInferenceProviderSpy).not.toHaveBeenCalled(); - const output = [...harness.logSpy.mock.calls, ...harness.errorSpy.mock.calls] + const output = [ + [(failure as Error).message], + ...harness.logSpy.mock.calls, + ...harness.errorSpy.mock.calls, + ] .flat() .map(String) .join("\n"); - expect(output).toContain("Hermes Provider is not registered in OpenShell"); + expect(output).toContain("sandbox is untouched"); expect(output).not.toContain("nous-key-from-env"); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); @@ -923,13 +954,17 @@ describe("rebuildSandbox flow: credential preflight", () => { hermesAuthMethod: "oauth", }); - await expect( - harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow("Missing Hermes Provider credentials"); + const failure = await harness + .rebuildSandbox("alpha", ["--yes"], { throwOnError: true }) + .catch((error: Error) => error); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain( + "Native inference provider identity changed or is missing", + ); - const output = diagnostics(harness); - expect(output).toContain("Hermes Provider is not registered in OpenShell"); - expect(output).toContain("credentials must be stored in OpenShell"); + const output = `${(failure as Error).message}\n${diagnostics(harness)}`; + expect(output).toContain("sandbox is untouched"); + expectNoSandboxDelete(harness.runOpenshellSpy); expect(output).not.toContain("Missing credential: OPENAI_API_KEY"); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts index 3f8c17f0f8d..fbf0ee79c21 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts @@ -144,12 +144,70 @@ describe("rebuildSandbox flow: target credentials", () => { expect(harness.session.credentialEnv).toBe("OPENAI_API_KEY"); }); + it.each([false, true])( + "rechecks legacy Hermes migration target before deletion (changed: %s)", + async (changed) => { + const restoreEnv = snapshotEnv(["NOUS_API_KEY"]); + process.env.NOUS_API_KEY = "fixture-legacy-nous-key"; + let backupStarted = false; + const harness = createRebuildFlowHarness({ + sandboxEntry: { + provider: "hermes-provider", + model: "hermes-model", + hermesAuthMethod: "api_key", + credentialEnv: "NOUS_API_KEY", + }, + beforeBackup: () => { + backupStarted = true; + }, + hermesCredentialKeys: ["NOUS_API_KEY"], + hydrateCredentialEnv: (key) => (key === "NOUS_API_KEY" ? "fixture-legacy-nous-key" : null), + runOpenshell: (args) => { + const result = + args[0] === "provider" && + args[1] === "get" && + args.includes("nemoclaw-hermes-provider-v1") + ? changed && backupStarted + ? { + status: 0, + stdout: + "Name: nemoclaw-hermes-provider-v1\nType: nemoclaw-hermes-inference-v1\nId: unowned-id\nResource version: 1\nCredential keys: OPENAI_API_KEY\nConfig keys: ", + stderr: "", + } + : { status: 1, stdout: "", stderr: "provider not found" } + : undefined; + return result && { ...result, output: result.stdout || result.stderr }; + }, + }); + try { + const outcome = await harness + .rebuildSandbox("alpha", ["--yes"], { throwOnError: true }) + .then( + () => "rebuilt", + (error: Error) => error.message, + ); + expect(outcome).toEqual( + changed ? expect.stringContaining("Replacement validation failed") : "rebuilt", + ); + expect(harness.onboardSpy).toHaveBeenCalledTimes(changed ? 0 : 1); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + expect( + harness.runOpenshellSpy.mock.calls.some( + ([args]) => Array.isArray(args) && args[0] === "sandbox" && args[1] === "delete", + ), + ).toBe(!changed); + } finally { + restoreEnv(); + } + }, + ); + it("rejects a shared Hermes Provider whose credential binding changed", async () => { const harness = createRebuildFlowHarness({ sandboxEntry: { provider: "hermes-provider", model: "hermes-model", - hermesAuthMethod: "api_key", + hermesAuthMethod: "oauth", }, hermesCredentialKeys: ["NOUS_API_KEY"], }); diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index c0f110a3668..8fc42fa0dfd 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -74,6 +74,7 @@ import { revalidatePreparedRecoveryBeforeDelete, } from "./rebuild-prepared-recovery"; import { + checkRebuildGatewayCredentialReuseOrBail, inspectRebuildGatewayProviderRegistration, shouldVerifyRebuildGatewayProvider, } from "./rebuild-provider-preflight"; @@ -830,6 +831,18 @@ async function rebuildSandboxUnlocked( }, validateAtDeleteEdge: async (runtimeSelection) => { stoppedSource?.assertCurrent(); + if ( + !resumeConfig.nativeHostedProviderAttachment && + !resumeConfig.nativeNvidiaProviderAttachment + ) { + await checkRebuildGatewayCredentialReuseOrBail( + sandboxName, + resumeConfig, + Boolean(credentialEnv && hydrateCredentialEnv(credentialEnv)), + log, + bail, + ); + } if ( !recreateOptions.rebuildProviderReconfigure && shouldVerifyRebuildGatewayProvider(resumeConfig.provider) @@ -841,7 +854,8 @@ async function rebuildSandboxUnlocked( runtimeSelection, undefined, resumeConfig.credentialEnv, - resumeConfig.nativeNvidiaProviderAttachment, + resumeConfig.nativeHostedProviderAttachment ?? + resumeConfig.nativeNvidiaProviderAttachment, ); if (registration !== "registered") { return { diff --git a/src/lib/actions/sandbox/rebuild-preflight-phase.ts b/src/lib/actions/sandbox/rebuild-preflight-phase.ts index b5e9e6c62ad..795c8e695ae 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-phase.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-phase.ts @@ -336,7 +336,8 @@ export async function runRebuildPreflightPhase( // but before backup or any destructive rebuild work begins. const { resumeConfig } = preparedTarget.targetConfig; const hostCredentialAvailable = Boolean( - resumeConfig.credentialEnv && hydrateCredentialEnv(resumeConfig.credentialEnv), + preparedTarget.targetConfig.credentialEnv && + hydrateCredentialEnv(preparedTarget.targetConfig.credentialEnv), ); if ( !(await checkRebuildGatewayCredentialReuseOrBail( diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts index 7a00ee978f1..7ffaf49fa53 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts @@ -102,6 +102,71 @@ describe("canRecreateMissingRebuildGatewayProvider", () => { }); describe("inspectRebuildGatewayProviderRegistration", () => { + it.each([ + ["recorded", {}, "registered"], + ["replaced", { revision: { id: "foreign", resourceVersion: 2 } }, "indeterminate"], + ["expired", { credentialExpiresAtMs: { OPENAI_API_KEY: 1 } }, "expired"], + ] as const)("checks generic hosted receipt %s", async (_label, changes, expected) => { + const adapter = createCliOpenShellProviderAdapter(); + const get = vi.spyOn(adapter, "getProvider").mockResolvedValue({ + ok: true, + value: { + name: "nemoclaw-openai-api-v1", + type: "nemoclaw-openai-inference-v1", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + credentialExpiresAtMs: {}, + revision: { id: "recorded-id", resourceVersion: 1 }, + ...changes, + }, + }); + await expect( + inspectRebuildGatewayProviderRegistration( + "openai-api", + vi.fn(), + "Preflight", + undefined, + adapter, + "OPENAI_API_KEY", + { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }, + ), + ).resolves.toBe(expected); + expect(get).toHaveBeenCalledWith( + expect.objectContaining({ + providerName: "nemoclaw-openai-api-v1", + includeCredentialExpirations: true, + }), + ); + }); + it("inspects the logical legacy registration without a native receipt", async () => { + const adapter = createCliOpenShellProviderAdapter(); + const get = vi.spyOn(adapter, "getProvider").mockResolvedValue({ + ok: true, + value: { + name: "openai-api", + type: "openai", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: ["OPENAI_BASE_URL"], + credentialExpiresAtMs: {}, + }, + }); + await expect( + inspectRebuildGatewayProviderRegistration( + "openai-api", + vi.fn(), + "Preflight", + undefined, + adapter, + "OPENAI_API_KEY", + ), + ).resolves.toBe("registered"); + expect(get).toHaveBeenCalledWith(expect.objectContaining({ providerName: "openai-api" })); + }); it.each([ ["exact native binding", {}, "registered"], ["replaced provider", { revision: { id: "foreign", resourceVersion: 2 } }, "indeterminate"], @@ -197,6 +262,83 @@ describe("inspectRebuildGatewayProviderRegistration", () => { }); describe("checkRebuildGatewayCredentialReuseOrBail", () => { + it.each(["missing", "owned", "unowned", "replaced", "indeterminate", "keyless"] as const)( + "checks receiptless migration target %s on recorded gateway", + async (state) => { + const native = { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + } as const; + const providerAdapter = createCliOpenShellProviderAdapter(); + const get = vi.spyOn(providerAdapter, "getProvider").mockResolvedValue( + state === "missing" || state === "indeterminate" + ? { + ok: false, + error: { + kind: "command", + reason: state === "missing" ? "not_found" : "failed", + message: "unavailable", + }, + } + : { + ok: true, + value: { + name: native.providerName, + type: native.profileId, + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { + id: state === "replaced" ? "foreign" : native.providerId, + resourceVersion: 1, + }, + }, + }, + ); + const readNativeAuthority = vi + .fn() + .mockReturnValue(state === "owned" || state === "replaced" ? native : undefined); + const outcome = checkRebuildGatewayCredentialReuseOrBail( + "alpha", + config({ + gatewayName: "nemoclaw", + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + }), + state !== "keyless", + vi.fn(), + throwingBail, + { + providerAdapter, + readNativeAuthority, + readGatewayProviderMetadata: vi.fn(), + readRecordedProviderEndpoints: vi.fn(), + }, + ); + await expect( + outcome.then( + (result) => ({ result }), + (error) => ({ error: error.message }), + ), + ).resolves.toEqual( + state === "missing" || state === "owned" + ? { result: true } + : { error: expect.stringContaining("sandbox is untouched") }, + ); + expect( + get.mock.calls.every( + ([request]) => + request.target.kind === "named" && request.target.gatewayName === "nemoclaw", + ), + ).toBe(true); + expect( + readNativeAuthority.mock.calls.every( + ([gateway, profile]) => gateway === "nemoclaw" && profile === native.profileId, + ), + ).toBe(true); + }, + ); it("accepts an exact complete registry route and gateway provider identity", async () => { await expect( checkRebuildGatewayCredentialReuseOrBail("alpha", config(), false, vi.fn(), throwingBail, { diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.ts index 39d04e49106..aadb750f154 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.ts @@ -9,18 +9,16 @@ import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider import type { RunProviderCommand } from "../../adapters/openshell/provider-adapter-cli"; import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-command"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; -import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; +import { + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../inference/native-hosted/contract"; import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { RD as _RD, R } from "../../cli/terminal-style"; import { hasBedrockRuntimeAwsAuthEnv, isBedrockRuntimeEndpoint, } from "../../inference/bedrock-runtime"; -import { - isNativeNvidiaProvider, - nativeNvidiaProviderAttachmentFromMetadata, - type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; import type { GatewayProviderMetadata } from "../../onboard/gateway-provider-metadata"; import { assessRecoveredProviderCredentialReuse, @@ -73,10 +71,16 @@ export async function inspectRebuildGatewayProviderRegistration( runtimeSelection?: OpenShellRuntimeSelection, providerAdapter = rebuildProviderAdapter(runtimeSelection), credentialKey?: string | null, - nativeAttachment?: NativeNvidiaProviderAttachment, + nativeAttachment?: NativeHostedProviderAttachment, ): Promise { - const nativeProfile = nativeHostedProfile(provider); - if (nativeAttachment && !isNativeNvidiaProvider(provider)) return "indeterminate"; + const nativeProfile = nativeAttachment ? nativeHostedProfile(provider) : undefined; + if ( + nativeAttachment && + (!nativeProfile || + nativeAttachment.profileId !== nativeProfile.profileId || + nativeAttachment.providerName !== nativeProfile.providerName) + ) + return "indeterminate"; const effectiveCredentialKey = nativeProfile ? credentialKey ? nativeProfile.credentialEnv @@ -87,17 +91,8 @@ export async function inspectRebuildGatewayProviderRegistration( target: managedProviderGatewayTarget, ...(effectiveCredentialKey ? { includeCredentialExpirations: true } : {}), }); - if (result.ok && nativeAttachment) { - try { - if ( - nativeNvidiaProviderAttachmentFromMetadata(result.value).providerId !== - nativeAttachment.providerId - ) - return "indeterminate"; - } catch { - return "indeterminate"; - } - } + if (result.ok && nativeAttachment && result.value.revision?.id !== nativeAttachment.providerId) + return "indeterminate"; const expiresAtMs = result.ok && effectiveCredentialKey ? result.value.credentialExpiresAtMs : undefined; const credentialExpiresAtMs = effectiveCredentialKey @@ -146,6 +141,8 @@ export async function inspectRebuildGatewayProviderRegistration( } type GatewayCredentialReusePreflightDeps = { + providerAdapter?: OpenShellProviderAdapter; + readNativeAuthority?: typeof registry.getNativeHostedProviderAuthority; hasBedrockRuntimeAwsAuth?(): boolean; readGatewayProviderMetadata( provider: string, @@ -264,7 +261,7 @@ export async function checkRebuildGatewayProviderOrBail( log: (msg: string) => void, bail: (msg: string, code?: number) => never, options: { - nativeAttachment?: NativeNvidiaProviderAttachment; + nativeAttachment?: NativeHostedProviderAttachment; allowProviderReconfigure?: boolean; hostCredentialAvailable?: boolean; onProviderReconfigureRequired?: (provider: string, credentialEnv: string) => void; @@ -323,7 +320,7 @@ function defaultGatewayCredentialReusePreflightDeps(): GatewayCredentialReusePre return { readGatewayProviderMetadata: async (provider) => { const result = await providerAdapter.getProvider({ - providerName: nativeHostedProfile(provider)?.providerName ?? provider, + providerName: provider, target: managedProviderGatewayTarget, }); return result.ok ? result.value : null; @@ -354,6 +351,47 @@ export async function checkRebuildGatewayCredentialReuseOrBail( ): Promise { const native = nativeHostedProfile(config.provider); if (native) { + if ( + config.nativeHostedProviderAttachment === undefined && + config.nativeNvidiaProviderAttachment === undefined + ) { + if (hostCredentialAvailable && config.gatewayName) { + const authority = (deps.readNativeAuthority ?? registry.getNativeHostedProviderAuthority)( + config.gatewayName, + native.profileId, + ); + const result = await (deps.providerAdapter ?? rebuildProviderAdapter()).getProvider({ + providerName: native.providerName, + target: { kind: "named", gatewayName: config.gatewayName }, + }); + if ( + !result.ok && + result.error.kind === "command" && + result.error.reason === "not_found" && + !authority + ) + return true; + if ( + result.ok && + authority && + authority.profileId === native.profileId && + authority.providerName === native.providerName && + authority.providerId === result.value.revision?.id && + result.value.name === native.providerName && + result.value.type === native.profileId && + result.value.configKeys.length === 0 && + result.value.credentialKeys.length === 1 && + result.value.credentialKeys[0] === native.credentialEnv + ) + return true; + bail( + "Native rebuild migration target ownership could not be verified; sandbox is untouched.", + ); + return false; + } + bail("Native rebuild migration requires a host credential; sandbox is untouched."); + return false; + } if (config.nativeNvidiaProviderAttachment) { return checkRebuildGatewayProviderOrBail(config.provider, config.credentialEnv, log, bail, { nativeAttachment: config.nativeNvidiaProviderAttachment, diff --git a/src/lib/actions/sandbox/rebuild-resume-config.ts b/src/lib/actions/sandbox/rebuild-resume-config.ts index 802f7a818bb..c8ef4e6dcc2 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.ts @@ -20,7 +20,7 @@ import type { ReasoningEffort } from "../../onboard/reasoning-mode"; import type { RegistryInferenceRoute } from "../../onboard/rebuild-route-handoff"; import * as onboardSession from "../../state/onboard-session"; import type { AmbientRecreateEnvAssessment } from "./rebuild-env-isolation"; -import type { RebuildSandboxEntry } from "./rebuild-flow-helpers"; +import { resolveSandboxGatewayName, type RebuildSandboxEntry } from "./rebuild-flow-helpers"; import { assessRebuildAmbientEnv, assessRebuildInferencePreflight, @@ -46,6 +46,7 @@ const hermesProviderAuth = require("../../hermes-provider-auth") as { * from ambient selection env. */ export interface RebuildResumeConfig { + readonly gatewayName?: string; readonly nativeHostedProviderAttachment?: import("../../inference/native-hosted").NativeHostedProviderAttachment; readonly nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; readonly agent: string | null; @@ -251,6 +252,7 @@ export function prepareRebuildResumeConfig( return null; } return { + gatewayName: resolveSandboxGatewayName(sb), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), agent: rebuildAgent, provider: trustedSelection.provider, diff --git a/src/lib/inference/native-hosted/index.test.ts b/src/lib/inference/native-hosted/index.test.ts index 73d5b27924e..1ede9e2ce48 100644 --- a/src/lib/inference/native-hosted/index.test.ts +++ b/src/lib/inference/native-hosted/index.test.ts @@ -33,6 +33,9 @@ describe.each(NATIVE_HOSTED_PROFILES)("native $label OpenShell provider", (profi function adapter(overrides: Partial = {}): OpenShellProviderAdapter { return { + ensureProviderPolicyComposition: vi.fn< + OpenShellProviderAdapter["ensureProviderPolicyComposition"] + >(async () => ({ ok: true, value: undefined })), importProviderProfile: vi.fn(() => ({ ok: true })), getProvider: vi.fn(async () => ({ ok: true, value: metadata() })), createProvider: vi.fn(async () => ({ ok: true })), @@ -52,6 +55,46 @@ describe.each(NATIVE_HOSTED_PROFILES)("native $label OpenShell provider", (profi } as OpenShellProviderAdapter; } + it.each(["create", "update", "reuse"])( + "refuses %s when provider policy activation fails", + async (operation) => { + const providerAdapter = adapter({ + ensureProviderPolicyComposition: vi.fn(async () => ({ + ok: false as const, + error: { + kind: "command" as const, + reason: "failed" as const, + message: "policy unavailable", + }, + })), + }); + vi.mocked(providerAdapter.getProvider).mockResolvedValue( + operation === "create" + ? { ok: false, error: { kind: "command", reason: "not_found", message: "missing" } } + : { ok: true, value: metadata() }, + ); + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: operation === "reuse" ? null : "test-host-credential", + expected: + operation === "create" + ? undefined + : { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/policy/); + expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); + expect(providerAdapter.createProvider).not.toHaveBeenCalled(); + }, + ); + it.each([verifyNativeHostedProviderAttachment, ensureNativeHostedProviderAttached])( "refuses a widened profile before observing or attaching a provider (%s)", async (operation) => { diff --git a/src/lib/inference/native-hosted/index.ts b/src/lib/inference/native-hosted/index.ts index 8dca7a4421b..f43bb50f846 100644 --- a/src/lib/inference/native-hosted/index.ts +++ b/src/lib/inference/native-hosted/index.ts @@ -218,6 +218,14 @@ export async function ensureNativeHostedProvider(input: { const { adapter, target, profile } = input; assertExpectedProfile(profile, input.expected); await requireNativeHostedProviderProfileBoundary(adapter, target, profile, input.profilePath); + const activatePolicy = async () => { + const policy = await adapter.ensureProviderPolicyComposition({ target }); + if (!policy.ok) { + throw new NativeHostedProviderError( + `Could not activate native ${profile.label} provider policy: ${providerErrorDetail(policy.error)}`, + ); + } + }; const before = await inspectNativeProvider(adapter, target, profile); if (before) { @@ -232,6 +240,7 @@ export async function ensureNativeHostedProvider(input: { `OpenShell provider '${profile.providerName}' changed identity. Recreate the sandbox before using native ${profile.label} inference. No provider was changed.`, ); } + await activatePolicy(); if (!input.credentialValue) return receipt; const updated = await adapter.updateProvider({ target, @@ -275,6 +284,7 @@ export async function ensureNativeHostedProvider(input: { `A host credential is required to create OpenShell provider '${profile.providerName}'.`, ); } + await activatePolicy(); const created = await adapter.createProvider({ target, name: profile.providerName, diff --git a/src/lib/onboard/build-credential-reuse.test.ts b/src/lib/onboard/build-credential-reuse.test.ts index 5c363d85bee..9bc300d1442 100644 --- a/src/lib/onboard/build-credential-reuse.test.ts +++ b/src/lib/onboard/build-credential-reuse.test.ts @@ -38,20 +38,39 @@ it.each([ }, ); -it("rejects malformed persisted native authority before looking up a provider", async () => { +it.each(["nativeNvidiaProviderAttachment", "nativeHostedProviderAttachment"])( + "rejects malformed persisted %s before looking up a provider", + async (field) => { + vi.spyOn(credentials, "resolveProviderCredential").mockReturnValue(null); + const getSandbox = vi.fn().mockReturnValue({ + name: "alpha", + [field]: { ...attachment, providerId: "" }, + }); + const providerExistsInGateway = vi.fn().mockResolvedValue(true); + await expect( + resolveNonInteractiveBuildCredential({ + helpUrl: null, + recovery: { recoveredFromSandbox: true, sandboxName: "alpha" }, + getSandbox, + providerExistsInGateway, + }), + ).rejects.toThrow("Malformed native NVIDIA provider attachment"); + expect(providerExistsInGateway).not.toHaveBeenCalled(); + }, +); + +it("reuses the generic persisted NVIDIA receipt during keyless recreation", async () => { vi.spyOn(credentials, "resolveProviderCredential").mockReturnValue(null); - const getSandbox = vi.fn().mockReturnValue({ - name: "alpha", - nativeNvidiaProviderAttachment: { ...attachment, providerId: "" }, - }); const providerExistsInGateway = vi.fn().mockResolvedValue(true); - await expect( - resolveNonInteractiveBuildCredential({ - helpUrl: null, - recovery: { recoveredFromSandbox: true, sandboxName: "alpha" }, - getSandbox, - providerExistsInGateway, + const result = await resolveNonInteractiveBuildCredential({ + helpUrl: null, + recovery: { recoveredFromSandbox: true, sandboxName: "alpha" }, + getSandbox: () => ({ + nativeNvidiaProviderAttachment: undefined, + nativeHostedProviderAttachment: attachment, }), - ).rejects.toThrow("Malformed native NVIDIA provider attachment"); - expect(providerExistsInGateway).not.toHaveBeenCalled(); + providerExistsInGateway, + }); + expect(result).toBe(true); + expect(providerExistsInGateway).toHaveBeenCalledExactlyOnceWith("nemoclaw-nvidia-prod-v1"); }); diff --git a/src/lib/onboard/build-credential-reuse.ts b/src/lib/onboard/build-credential-reuse.ts index 2fac36af000..82bbe2ad431 100644 --- a/src/lib/onboard/build-credential-reuse.ts +++ b/src/lib/onboard/build-credential-reuse.ts @@ -30,15 +30,19 @@ import { logMissingNvidiaApiKeyHelp } from "./missing-credential-hints"; export async function resolveNonInteractiveBuildCredential(opts: { helpUrl: string | null | undefined; recovery: { recoveredFromSandbox: boolean; sandboxName?: string | null }; - getSandbox: (name: string) => { nativeNvidiaProviderAttachment?: unknown } | null; + getSandbox: (name: string) => { + nativeNvidiaProviderAttachment?: unknown; + nativeHostedProviderAttachment?: unknown; + } | null; providerExistsInGateway: (name: string) => boolean | Promise; }): Promise { const { helpUrl, recovery, providerExistsInGateway } = opts; const { recoveredFromSandbox, sandboxName } = recovery; + const recovered = recoveredFromSandbox && sandboxName ? opts.getSandbox(sandboxName) : null; const recordedAttachment = - recoveredFromSandbox && sandboxName - ? opts.getSandbox(sandboxName)?.nativeNvidiaProviderAttachment - : undefined; + recovered?.nativeHostedProviderAttachment !== undefined + ? recovered.nativeHostedProviderAttachment + : recovered?.nativeNvidiaProviderAttachment; const nativeAttachment = normalizeNativeNvidiaProviderAttachment(recordedAttachment); if (recordedAttachment !== undefined && !nativeAttachment) { throw new Error("Malformed native NVIDIA provider attachment"); diff --git a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts index 116b9b4d61a..d1e46d794cc 100644 --- a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts @@ -107,7 +107,6 @@ from deepagents_code import config name = "NVIDIA_INFERENCE_API_KEY" for value in ( - "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", "openshell:resolve:env:v12_NVIDIA_INFERENCE_API_KEY", "openshell:resolve:env:s" + "a" * 64 + "_NVIDIA_INFERENCE_API_KEY", ): @@ -120,6 +119,7 @@ for value in ( assert resolved["base_url"] == "https://integrate.api.nvidia.com/v1" for value in ( + "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", "", "nvapi-" + "x" * 32, "nemoclaw-managed-inference", diff --git a/test/helpers/credentials-provider-adapter.ts b/test/helpers/credentials-provider-adapter.ts index 330be6dae66..eac4891dc86 100644 --- a/test/helpers/credentials-provider-adapter.ts +++ b/test/helpers/credentials-provider-adapter.ts @@ -43,6 +43,9 @@ export function providerAdapter( const getProviderRefreshStatus: OpenShellProviderAdapter["getProviderRefreshStatus"] = async () => ({ ok: true, value: { status: "refreshed" } }); return { + ensureProviderPolicyComposition: vi.fn< + OpenShellProviderAdapter["ensureProviderPolicyComposition"] + >(async () => ({ ok: true, value: undefined })), listProviders: vi.fn(listProviders), createProvider: vi.fn(createProvider), getProvider: vi.fn(getProvider), diff --git a/test/helpers/onboard-split-context.ts b/test/helpers/onboard-split-context.ts index ec2032d8dcb..b1530e2a509 100644 --- a/test/helpers/onboard-split-context.ts +++ b/test/helpers/onboard-split-context.ts @@ -116,6 +116,9 @@ export function createNativeSetupProviderAdapter( throw new Error("Unexpected provider operation"); }; const adapter = { + ensureProviderPolicyComposition: vi.fn< + OpenShellProviderAdapter["ensureProviderPolicyComposition"] + >(async () => ({ ok: true, value: undefined })), importProviderProfile: vi.fn(() => ({ ok: true, })), diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 20ee4c14a30..0cd7ebcf308 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -319,7 +319,6 @@ const prompts = []; const registryUpdates = []; const done = new Error("INFERENCE_STEP_DONE"); let inferenceSessionSnapshot = null; -const hermesApiKeyProviderMetadata = ${JSON.stringify(HERMES_API_KEY_PROVIDER_METADATA)}; delete process.env.NEMOCLAW_NON_INTERACTIVE; delete process.env.NEMOCLAW_SANDBOX_NAME; @@ -343,9 +342,10 @@ try { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + if (normalized.includes("settings get")) return { status: 0, stdout: JSON.stringify({ scope: "global", settings: { providers_v2_enabled: "true" } }), stderr: "" }; if (normalized.includes("provider profile") && normalized.includes("export")) return { status: 0, stdout: ${JSON.stringify(HERMES_NATIVE_PROFILE_JSON)}, stderr: "" }; if (normalized.includes("provider get") && normalized.includes("nemoclaw-hermes-provider-v1")) { - return { status: 0, stdout: hermesApiKeyProviderMetadata, stderr: "" }; + return { status: 0, stdout: ${JSON.stringify(HERMES_API_KEY_PROVIDER_METADATA)}, stderr: "" }; } return { status: 0, stdout: "", stderr: "" }; }; diff --git a/test/support/native-provider-command-runtime.ts b/test/support/native-provider-command-runtime.ts index cd4ef2a528b..9c630a2d67f 100644 --- a/test/support/native-provider-command-runtime.ts +++ b/test/support/native-provider-command-runtime.ts @@ -35,6 +35,13 @@ export function createNativeProviderCommandRuntime( ].join("\n"); let exists = initiallyExists; const run = (args: string[]) => { + if (args[0] === "settings" && args[1] === "get") { + const output = JSON.stringify({ + scope: "global", + settings: { providers_v2_enabled: "true" }, + }); + return { status: 0, output, stdout: output, stderr: "" }; + } if (args[0] !== "provider") return undefined; if (args[1] === "profile") return { status: 0, output: profileJson, stdout: profileJson, stderr: "" }; From 75dee6f0633983bbabc19b4b3de0ad55d00f5594 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 15:23:34 -0700 Subject: [PATCH 125/133] test(credentials): format merged adapter fixture Signed-off-by: Deepak Jain --- src/lib/actions/credentials-provider-adapter.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index f7393307b40..203668d728c 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -25,7 +25,6 @@ vi.mock("../gateway-start-guidance", () => ({ gatewayStartGuidance: () => "Start the gateway again with `nemoclaw onboard`.", })); - function nativeNvidiaProviderAdapter(): OpenShellProviderAdapter { let providerPresent = false; return providerAdapter({ From 8209bce867fca7120206446b8a5a729cd2f7a34a Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 15:36:29 -0700 Subject: [PATCH 126/133] fix(rebuild): verify native policy before legacy migration Signed-off-by: Deepak Jain --- .../rebuild-flow-credential-preflight.test.ts | 23 +-- .../rebuild-flow-target-credentials.test.ts | 53 ++++-- .../rebuild-provider-preflight.test.ts | 167 ++++++++++-------- .../sandbox/rebuild-provider-preflight.ts | 25 ++- 4 files changed, 160 insertions(+), 108 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts index 514558e6076..4ac7c47b83f 100644 --- a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts @@ -287,18 +287,21 @@ describe("rebuildSandbox flow: credential preflight", () => { credentialEnv === "NVIDIA_INFERENCE_API_KEY" ? "saved-provider-key" : null, runOpenshell: (args) => { const stdout = - args[1] === "get" - ? "Name: nvidia-prod\nType: nvidia\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: NVIDIA_BASE_URL" - : JSON.stringify([ - { - name: "nvidia-prod", - credential_keys: ["NVIDIA_INFERENCE_API_KEY"], - credential_expires_at_ms: {}, - }, - ]); + args[0] === "settings" + ? JSON.stringify({ scope: "global", settings: { providers_v2_enabled: "true" } }) + : args[1] === "get" + ? "Name: nvidia-prod\nType: nvidia\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: NVIDIA_BASE_URL" + : JSON.stringify([ + { + name: "nvidia-prod", + credential_keys: ["NVIDIA_INFERENCE_API_KEY"], + credential_expires_at_ms: {}, + }, + ]); return args.includes("nemoclaw-nvidia-prod-v1") ? { status: 1, output: "provider not found", stdout: "", stderr: "provider not found" } - : args[0] === "provider" && ["get", "list"].includes(args[1]) + : (args[0] === "settings" && args[1] === "get") || + (args[0] === "provider" && ["get", "list"].includes(args[1])) ? { status: 0, output: stdout, stdout, stderr: "" } : undefined; }, diff --git a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts index fbf0ee79c21..107b2b952a5 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts @@ -144,9 +144,11 @@ describe("rebuildSandbox flow: target credentials", () => { expect(harness.session.credentialEnv).toBe("OPENAI_API_KEY"); }); - it.each([false, true])( - "rechecks legacy Hermes migration target before deletion (changed: %s)", - async (changed) => { + it.each(["unchanged", "collision", "disabled"] as const)( + "rechecks legacy Hermes migration target before deletion (%s)", + async (state) => { + const changed = state === "collision"; + const disabled = state === "disabled"; const restoreEnv = snapshotEnv(["NOUS_API_KEY"]); process.env.NOUS_API_KEY = "fixture-legacy-nous-key"; let backupStarted = false; @@ -164,18 +166,27 @@ describe("rebuildSandbox flow: target credentials", () => { hydrateCredentialEnv: (key) => (key === "NOUS_API_KEY" ? "fixture-legacy-nous-key" : null), runOpenshell: (args) => { const result = - args[0] === "provider" && - args[1] === "get" && - args.includes("nemoclaw-hermes-provider-v1") - ? changed && backupStarted - ? { - status: 0, - stdout: - "Name: nemoclaw-hermes-provider-v1\nType: nemoclaw-hermes-inference-v1\nId: unowned-id\nResource version: 1\nCredential keys: OPENAI_API_KEY\nConfig keys: ", - stderr: "", - } - : { status: 1, stdout: "", stderr: "provider not found" } - : undefined; + args[0] === "settings" && args[1] === "get" + ? { + status: 0, + stdout: JSON.stringify({ + scope: "global", + settings: { providers_v2_enabled: disabled ? "false" : "true" }, + }), + stderr: "", + } + : args[0] === "provider" && + args[1] === "get" && + args.includes("nemoclaw-hermes-provider-v1") + ? changed && backupStarted + ? { + status: 0, + stdout: + "Name: nemoclaw-hermes-provider-v1\nType: nemoclaw-hermes-inference-v1\nId: unowned-id\nResource version: 1\nCredential keys: OPENAI_API_KEY\nConfig keys: ", + stderr: "", + } + : { status: 1, stdout: "", stderr: "provider not found" } + : undefined; return result && { ...result, output: result.stdout || result.stderr }; }, }); @@ -187,15 +198,19 @@ describe("rebuildSandbox flow: target credentials", () => { (error: Error) => error.message, ); expect(outcome).toEqual( - changed ? expect.stringContaining("Replacement validation failed") : "rebuilt", + disabled + ? expect.stringContaining("provider policy could not be activated") + : changed + ? expect.stringContaining("Replacement validation failed") + : "rebuilt", ); - expect(harness.onboardSpy).toHaveBeenCalledTimes(changed ? 0 : 1); - expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + expect(harness.onboardSpy).toHaveBeenCalledTimes(changed || disabled ? 0 : 1); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledTimes(disabled ? 0 : 1); expect( harness.runOpenshellSpy.mock.calls.some( ([args]) => Array.isArray(args) && args[0] === "sandbox" && args[1] === "delete", ), - ).toBe(!changed); + ).toBe(!changed && !disabled); } finally { restoreEnv(); } diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts index 7ffaf49fa53..e5a315c5aa7 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts @@ -262,83 +262,110 @@ describe("inspectRebuildGatewayProviderRegistration", () => { }); describe("checkRebuildGatewayCredentialReuseOrBail", () => { - it.each(["missing", "owned", "unowned", "replaced", "indeterminate", "keyless"] as const)( - "checks receiptless migration target %s on recorded gateway", - async (state) => { - const native = { - schemaVersion: 1, - profileId: "nemoclaw-openai-inference-v1", - providerName: "nemoclaw-openai-api-v1", - providerId: "recorded-id", - } as const; - const providerAdapter = createCliOpenShellProviderAdapter(); - const get = vi.spyOn(providerAdapter, "getProvider").mockResolvedValue( - state === "missing" || state === "indeterminate" + it.each([ + "missing", + "owned", + "unowned", + "replaced", + "indeterminate", + "keyless", + "policy-disabled", + "policy-unavailable", + ] as const)("checks receiptless migration target %s on recorded gateway", async (state) => { + const native = { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + } as const; + const providerAdapter = createCliOpenShellProviderAdapter(); + const get = vi.spyOn(providerAdapter, "getProvider").mockResolvedValue( + state === "missing" || state === "indeterminate" || state.startsWith("policy-") + ? { + ok: false, + error: { + kind: "command", + reason: state === "indeterminate" ? "failed" : "not_found", + message: "unavailable", + }, + } + : { + ok: true, + value: { + name: native.providerName, + type: native.profileId, + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { + id: state === "replaced" ? "foreign" : native.providerId, + resourceVersion: 1, + }, + }, + }, + ); + const activatePolicy = vi + .spyOn(providerAdapter, "ensureProviderPolicyComposition") + .mockResolvedValue( + state.startsWith("policy-") ? { ok: false, error: { kind: "command", - reason: state === "missing" ? "not_found" : "failed", - message: "unavailable", + reason: state === "policy-disabled" ? "conflict" : "failed", + message: "policy unavailable", }, } - : { - ok: true, - value: { - name: native.providerName, - type: native.profileId, - credentialKeys: ["OPENAI_API_KEY"], - configKeys: [], - revision: { - id: state === "replaced" ? "foreign" : native.providerId, - resourceVersion: 1, - }, - }, - }, - ); - const readNativeAuthority = vi - .fn() - .mockReturnValue(state === "owned" || state === "replaced" ? native : undefined); - const outcome = checkRebuildGatewayCredentialReuseOrBail( - "alpha", - config({ - gatewayName: "nemoclaw", - provider: "openai-api", - credentialEnv: "OPENAI_API_KEY", - }), - state !== "keyless", - vi.fn(), - throwingBail, - { - providerAdapter, - readNativeAuthority, - readGatewayProviderMetadata: vi.fn(), - readRecordedProviderEndpoints: vi.fn(), - }, - ); - await expect( - outcome.then( - (result) => ({ result }), - (error) => ({ error: error.message }), - ), - ).resolves.toEqual( - state === "missing" || state === "owned" - ? { result: true } - : { error: expect.stringContaining("sandbox is untouched") }, + : { ok: true, value: undefined }, ); - expect( - get.mock.calls.every( - ([request]) => - request.target.kind === "named" && request.target.gatewayName === "nemoclaw", - ), - ).toBe(true); - expect( - readNativeAuthority.mock.calls.every( - ([gateway, profile]) => gateway === "nemoclaw" && profile === native.profileId, - ), - ).toBe(true); - }, - ); + const readNativeAuthority = vi + .fn() + .mockReturnValue(state === "owned" || state === "replaced" ? native : undefined); + const outcome = checkRebuildGatewayCredentialReuseOrBail( + "alpha", + config({ + gatewayName: "nemoclaw", + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + }), + state !== "keyless", + vi.fn(), + throwingBail, + { + providerAdapter, + readNativeAuthority, + readGatewayProviderMetadata: vi.fn(), + readRecordedProviderEndpoints: vi.fn(), + }, + ); + await expect( + outcome.then( + (result) => ({ result }), + (error) => ({ error: error.message }), + ), + ).resolves.toEqual( + state === "missing" || state === "owned" + ? { result: true } + : { error: expect.stringContaining("sandbox is untouched") }, + ); + expect(activatePolicy).toHaveBeenCalledTimes( + ["missing", "owned", "policy-disabled", "policy-unavailable"].includes(state) ? 1 : 0, + ); + expect( + activatePolicy.mock.calls.every( + ([request]) => request.target.kind === "named" && request.target.gatewayName === "nemoclaw", + ), + ).toBe(true); + expect( + get.mock.calls.every( + ([request]) => request.target.kind === "named" && request.target.gatewayName === "nemoclaw", + ), + ).toBe(true); + expect( + readNativeAuthority.mock.calls.every( + ([gateway, profile]) => gateway === "nemoclaw" && profile === native.profileId, + ), + ).toBe(true); + }); it("accepts an exact complete registry route and gateway provider identity", async () => { await expect( checkRebuildGatewayCredentialReuseOrBail("alpha", config(), false, vi.fn(), throwingBail, { diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.ts index aadb750f154..af7f3892596 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.ts @@ -360,18 +360,17 @@ export async function checkRebuildGatewayCredentialReuseOrBail( config.gatewayName, native.profileId, ); - const result = await (deps.providerAdapter ?? rebuildProviderAdapter()).getProvider({ + const providerAdapter = deps.providerAdapter ?? rebuildProviderAdapter(); + const result = await providerAdapter.getProvider({ providerName: native.providerName, target: { kind: "named", gatewayName: config.gatewayName }, }); - if ( + const absent = !result.ok && result.error.kind === "command" && result.error.reason === "not_found" && - !authority - ) - return true; - if ( + !authority; + const owned = result.ok && authority && authority.profileId === native.profileId && @@ -381,9 +380,17 @@ export async function checkRebuildGatewayCredentialReuseOrBail( result.value.type === native.profileId && result.value.configKeys.length === 0 && result.value.credentialKeys.length === 1 && - result.value.credentialKeys[0] === native.credentialEnv - ) - return true; + result.value.credentialKeys[0] === native.credentialEnv; + if (absent || owned) { + const policy = await providerAdapter.ensureProviderPolicyComposition({ + target: { kind: "named", gatewayName: config.gatewayName }, + }); + if (policy.ok) return true; + bail( + "Native rebuild migration provider policy could not be activated; sandbox is untouched.", + ); + return false; + } bail( "Native rebuild migration target ownership could not be verified; sandbox is untouched.", ); From f9d11ba49e380eceaafbac9e844bffaaf47b4965 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 15:47:41 -0700 Subject: [PATCH 127/133] test(rebuild): preserve legacy provider fixture identities Signed-off-by: Deepak Jain --- .../rebuild-credential-preflight.test.ts | 6 ++---- .../gateway-state-reconcile-2276.test.ts | 20 +++++++++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/test/credentials/rebuild-credential-preflight.test.ts b/test/credentials/rebuild-credential-preflight.test.ts index 093ef8e2a8a..c21fd4e08f5 100644 --- a/test/credentials/rebuild-credential-preflight.test.ts +++ b/test/credentials/rebuild-credential-preflight.test.ts @@ -15,7 +15,6 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; -import { nativeHostedProfile } from "../../src/lib/inference/native-hosted/profiles"; import { execTimeout, testTimeoutOptions } from "../helpers/timeouts"; const REPO_ROOT = path.join(import.meta.dirname, "../.."); @@ -52,8 +51,7 @@ function createFixture(opts: { providerRegistered = true, inferenceProbeHttpStatus = null, } = opts; - const native = nativeHostedProfile(provider); - const observedProvider = native?.providerName ?? provider; + const observedProvider = provider; const sandboxName = "my-assistant"; const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-2273-")); tmpFixtures.push(tmpDir); @@ -221,7 +219,7 @@ if (a[0] === "provider" && a[1] === "get") { process.stderr.write("Error: provider '${provider}' not found\\n"); process.exit(1); } - process.stdout.write("Name: ${observedProvider}\\nType: ${native?.profileId ?? "openai"}\\nId: 11111111-2222-4333-8444-555555555555\\nResource version: 1\\nCredential keys: ${credentialEnv}\\nConfig keys: ${native ? "" : "OPENAI_BASE_URL"}\\n"); + process.stdout.write("Name: ${observedProvider}\\nType: openai\\nId: 11111111-2222-4333-8444-555555555555\\nResource version: 1\\nCredential keys: ${credentialEnv}\\nConfig keys: OPENAI_BASE_URL\\n"); process.exit(0); } if (a[0] === "provider" && a[1] === "list") { diff --git a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts index 32a3dda657d..43322d383bf 100644 --- a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts +++ b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts @@ -185,12 +185,24 @@ if (args[0] === "inference" && args[1] === "get") { } if (args[0] === "provider" && args[1] === "get") { - process.stdout.write("Name: nemoclaw-nvidia-prod-v1\\nType: nemoclaw-nvidia-inference-v1\\nId: 11111111-2222-4333-8444-555555555555\\nResource version: 1\\nCredential keys: NVIDIA_INFERENCE_API_KEY\\nConfig keys: \\n"); - process.exit(0); + if (args.at(-1) === "nvidia-prod") { + process.stdout.write("Name: nvidia-prod\\nType: openai\\nId: 11111111-2222-4333-8444-555555555555\\nResource version: 1\\nCredential keys: NVIDIA_INFERENCE_API_KEY\\nConfig keys: OPENAI_BASE_URL\\n"); + process.exit(0); + } + process.stderr.write("Error: provider '" + args.at(-1) + "' not found\\n"); + process.exit(1); } if (args[0] === "provider" && args[1] === "list") { - process.stdout.write('[{"name":"nemoclaw-nvidia-prod-v1","credential_keys":["NVIDIA_INFERENCE_API_KEY"]}]\\n'); + process.stdout.write('[{"name":"nvidia-prod","credential_keys":["NVIDIA_INFERENCE_API_KEY"]}]\\n'); + process.exit(0); +} + +if (args[0] === "settings" && args[1] === "get") { + process.stdout.write(JSON.stringify({ + scope: "global", + settings: { providers_v2_enabled: "true" }, + })); process.exit(0); } @@ -304,7 +316,7 @@ if (a[0] === "image" && a[1] === "inspect") { const formatIndex = a.indexOf("--format"); const format = formatIndex >= 0 ? a[formatIndex + 1] : ""; if (format === "{{.Id}}") process.stdout.write("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\n"); - if (format === "{{json .RepoDigests}}") process.stdout.write("[]\\n"); + if (format === "{{json .RepoDigests}}") process.stdout.write('[{"name":"nvidia-prod","credential_keys":["NVIDIA_INFERENCE_API_KEY"]}]\\n'); process.exit(0); } if (a[0] === "tag" || a[0] === "rmi") process.exit(0); From 1dd440c065681ba9f830a2ac3290a99312d2d4b8 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 15:49:40 -0700 Subject: [PATCH 128/133] test(rebuild): retain empty image digest fixture Signed-off-by: Deepak Jain --- test/runtime/gateway/gateway-state-reconcile-2276.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts index 43322d383bf..80d63818cdc 100644 --- a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts +++ b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts @@ -316,7 +316,7 @@ if (a[0] === "image" && a[1] === "inspect") { const formatIndex = a.indexOf("--format"); const format = formatIndex >= 0 ? a[formatIndex + 1] : ""; if (format === "{{.Id}}") process.stdout.write("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\n"); - if (format === "{{json .RepoDigests}}") process.stdout.write('[{"name":"nvidia-prod","credential_keys":["NVIDIA_INFERENCE_API_KEY"]}]\\n'); + if (format === "{{json .RepoDigests}}") process.stdout.write("[]\\n"); process.exit(0); } if (a[0] === "tag" || a[0] === "rmi") process.exit(0); From 70999b9704ab75681a7b73633e9e3d8fd78a5c58 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 16:14:21 -0700 Subject: [PATCH 129/133] fix(start): preserve validated native inference selection Signed-off-by: Deepak Jain --- src/lib/actions/sandbox/start.test.ts | 76 +++++++++++++++++++++ src/lib/actions/sandbox/start.ts | 18 +++++ src/lib/inference/native-hosted/contract.ts | 7 +- 3 files changed, 100 insertions(+), 1 deletion(-) diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index 640616ae51c..28e6a213af7 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -17,6 +17,8 @@ import { createRuntimeProviderBundleRegistry } from "../../onboard/runtime-provi import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { type SandboxStartDeps, startSandbox } from "./start"; +import { buildSandboxInferenceInvocationCommand } from "./inference-invocation-probe"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; afterEach(() => { vi.restoreAllMocks(); @@ -348,6 +350,80 @@ describe("startSandbox native lifecycle", () => { expect(h.probeGatewayProcess).not.toHaveBeenCalled(); }); + it.each([ + ["openai-api", "nativeHostedProviderAttachment", "https://api.openai.com/v1/chat/completions"], + [ + "nvidia-prod", + "nativeNvidiaProviderAttachment", + "https://integrate.api.nvidia.com/v1/chat/completions", + ], + ["openai-api", undefined, "https://inference.local/v1/chat/completions"], + ] as const)( + "probes the recorded restart route for %s via %s", + async (provider, field, endpoint) => { + const profile = nativeHostedProfile(provider)!; + const commands: string[] = []; + const probeInferenceInvocation = vi.fn< + NonNullable + >(async (input) => { + commands.push(buildSandboxInferenceInvocationCommand(input)); + return { ok: true }; + }); + const h = harness({ probeInferenceInvocation }); + h.getSandbox.mockReturnValue( + sandbox({ + provider, + model: "model", + preferredInferenceApi: "openai-completions", + ...(field + ? { + [field]: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-owned", + }, + } + : {}), + }), + ); + await expect(startSandbox("my-sandbox", h.deps)).resolves.toEqual({ exitCode: 0 }); + expect(commands).toEqual([expect.stringContaining(endpoint)]); + expect(probeInferenceInvocation.mock.invocationCallOrder[0]).toBeGreaterThan( + h.verifyGateway.mock.invocationCallOrder[0], + ); + }, + ); + + it.each(["malformed", "mismatched"] as const)( + "refuses %s restart receipt without a probe", + async (state) => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "provider-owned", + }; + const probeInferenceInvocation = vi.fn< + NonNullable + >(async () => ({ ok: true })); + const h = harness({ probeInferenceInvocation }); + h.getSandbox.mockReturnValue( + sandbox({ + provider: state === "malformed" ? "nvidia-prod" : "openai-api", + model: "model", + nativeHostedProviderAttachment: + state === "malformed" ? { ...receipt, providerId: "" } : receipt, + nativeNvidiaProviderAttachment: receipt, + }), + ); + await expect(startSandbox("my-sandbox", h.deps)).rejects.toThrow( + "Native hosted provider attachment is invalid for the recorded inference provider", + ); + expect(probeInferenceInvocation).not.toHaveBeenCalled(); + }, + ); + it("waits for the Hermes gateway process to settle before checking gateway health", async () => { const probeGatewayProcess = vi .fn>() diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index 301d559feb7..52b3738f893 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -7,6 +7,8 @@ import type { OpenShellSandboxObserver } from "../../adapters/openshell/sandbox- import { retryUntilAsync } from "../../core/retry"; import { DEFAULT_SANDBOX_EXEC_TIMEOUT_MS } from "../../adapters/sandbox/command-transport"; import { cliName } from "../../onboard/branding"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; +import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia/contract"; import { classifyRegisteredPortableAgentLifecycle, qualifyLegacyHermesPortableLifecycleProfile, @@ -156,6 +158,21 @@ async function checkStartedSandboxInference( const provider = (sandbox.provider ?? "").trim(); if (!model || !provider) return null; const gatewayName = getPersistedSandboxTargetGatewayName(sandbox); + const recordedAttachment = + sandbox.nativeHostedProviderAttachment !== undefined + ? sandbox.nativeHostedProviderAttachment + : sandbox.nativeNvidiaProviderAttachment; + const nativeAttachment = normalizeNativeHostedProviderAttachment( + sandbox.nativeHostedProviderAttachment !== undefined + ? recordedAttachment + : normalizeNativeNvidiaProviderAttachment(recordedAttachment), + provider, + ); + if (recordedAttachment !== undefined && !nativeAttachment) { + throw new Error( + "Native hosted provider attachment is invalid for the recorded inference provider. Recreate the sandbox to restore inference.", + ); + } log(" Checking that the sandbox serves an agent request…"); const input = { sandboxName, @@ -164,6 +181,7 @@ async function checkStartedSandboxInference( provider, model, preferredInferenceApi: sandbox.preferredInferenceApi ?? null, + ...(nativeAttachment ? { nativeProvider: true } : {}), }; const probe = () => (deps.probeInferenceInvocation ?? probeSandboxInferenceInvocation)( diff --git a/src/lib/inference/native-hosted/contract.ts b/src/lib/inference/native-hosted/contract.ts index ea410bde666..afc0a4f5fd7 100644 --- a/src/lib/inference/native-hosted/contract.ts +++ b/src/lib/inference/native-hosted/contract.ts @@ -19,13 +19,18 @@ export class NativeHostedProviderError extends Error { export function normalizeNativeHostedProviderAttachment( value: unknown, + expectedProvider?: string, ): NativeHostedProviderAttachment | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; const receipt = value as Record; const profile = NATIVE_HOSTED_PROFILES.find( (entry) => entry.profileId === receipt.profileId && entry.providerName === receipt.providerName, ); - if (!profile) return undefined; + if ( + !profile || + (expectedProvider !== undefined && profile.logicalProvider !== expectedProvider.trim()) + ) + return undefined; if ( receipt.schemaVersion !== 1 || receipt.profileId !== profile.profileId || From 4d258c611f453792f07f7b25b870f090a068b73f Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 8 Oct 2026 16:17:19 -0700 Subject: [PATCH 130/133] fix(sandbox): preserve native hosted inference on restart Signed-off-by: Prekshi Vyas --- src/lib/actions/sandbox/start.test.ts | 59 +++++++++++++++++++++++++++ src/lib/actions/sandbox/start.ts | 6 +++ 2 files changed, 65 insertions(+) diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index 640616ae51c..1a6375b7f73 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -17,6 +17,8 @@ import { createRuntimeProviderBundleRegistry } from "../../onboard/runtime-provi import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { type SandboxStartDeps, startSandbox } from "./start"; +import { resolveSandboxInferenceInvocationEndpoint } from "./inference-invocation-probe"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; afterEach(() => { vi.restoreAllMocks(); @@ -639,6 +641,63 @@ describe("startSandbox native lifecycle", () => { expect(h.verifyGateway).toHaveBeenCalledOnce(); }); + it.each([ + { + provider: "openai-api", + attachmentKey: "nativeHostedProviderAttachment", + endpoint: "https://api.openai.com/v1/chat/completions", + }, + { + provider: "nvidia-prod", + attachmentKey: "nativeHostedProviderAttachment", + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + }, + { + provider: "nvidia-prod", + attachmentKey: "nativeNvidiaProviderAttachment", + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + }, + { + provider: "nvidia-prod", + attachmentKey: null, + endpoint: "https://inference.local/v1/chat/completions", + }, + ] as const)( + "probes $provider through its recorded $attachmentKey path after start", + async ({ provider, attachmentKey, endpoint }) => { + const profile = nativeHostedProfile(provider)!; + const probeInferenceInvocation = vi.fn< + NonNullable + >(async (input) => { + expect(resolveSandboxInferenceInvocationEndpoint(input)).toBe(endpoint); + return { ok: true }; + }); + const h = harness({ probeInferenceInvocation }); + h.getSandbox.mockReturnValue( + sandbox({ + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw-18080", + stopped: true, + provider, + model: provider === "nvidia-prod" ? "nvidia/nemotron-3-super-120b-a12b" : "gpt-4o", + preferredInferenceApi: "openai-completions", + ...(attachmentKey + ? { + [attachmentKey]: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "native-provider-id", + }, + } + : {}), + }), + ); + await expect(startSandbox("my-sandbox", h.deps)).resolves.toEqual({ exitCode: 0 }); + expect(probeInferenceInvocation).toHaveBeenCalledOnce(); + }, + ); + it("returns nonzero when the native gateway cannot serve an agent request", async () => { const probeInferenceInvocation = vi.fn( async () => diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index 301d559feb7..b3dd872dc1e 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -17,6 +17,7 @@ import { CURRENT_RUNTIME_PROVIDER_BUNDLES, type RuntimeProviderBundleRegistry, } from "../../onboard/runtime-provider/access"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { @@ -164,6 +165,11 @@ async function checkStartedSandboxInference( provider, model, preferredInferenceApi: sandbox.preferredInferenceApi ?? null, + ...(normalizeNativeHostedProviderAttachment( + sandbox.nativeHostedProviderAttachment ?? sandbox.nativeNvidiaProviderAttachment, + ) + ? { nativeProvider: true } + : {}), }; const probe = () => (deps.probeInferenceInvocation ?? probeSandboxInferenceInvocation)( From ccaa543cd9cea6cfe25d9e61c67a33dac18dc7b0 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 16:21:26 -0700 Subject: [PATCH 131/133] refactor(inference): remove superseded NVIDIA lifecycle Signed-off-by: Deepak Jain --- .../rebuild-provider-preflight.test.ts | 2 +- src/lib/inference/native-nvidia/index.ts | 472 ------------------ 2 files changed, 1 insertion(+), 473 deletions(-) delete mode 100644 src/lib/inference/native-nvidia/index.ts diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts index e5a315c5aa7..d2b57585d83 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts @@ -6,7 +6,7 @@ import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/prov import { NVIDIA_HOSTED_NATIVE_PROVIDER, NVIDIA_HOSTED_NATIVE_PROFILE_ID, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import * as openshellRuntime from "../../adapters/openshell/runtime"; import type { GatewayProviderMetadata } from "../../onboard/gateway-provider-metadata"; import { diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts deleted file mode 100644 index e449c06b9f6..00000000000 --- a/src/lib/inference/native-nvidia/index.ts +++ /dev/null @@ -1,472 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import path from "node:path"; - -import type { - OpenShellGatewayTarget, - OpenShellProviderAdapter, - OpenShellProviderError, - OpenShellProviderMetadata, -} from "../../adapters/openshell/sandbox-observer"; -import { REPOSITORY_ROOT } from "../../core/repository-root"; -import { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - type NativeNvidiaProviderAttachment, -} from "./contract"; - -export { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - normalizeNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "./contract"; - -export class NativeNvidiaProviderError extends Error { - constructor(message: string) { - super(message); - this.name = "NativeNvidiaProviderError"; - } -} - -export function nativeNvidiaProviderProfilePath(root = REPOSITORY_ROOT): string { - return path.join( - root, - "managed-inference", - "provider-profiles", - `${NVIDIA_HOSTED_NATIVE_PROFILE_ID}.yaml`, - ); -} - -export function isNativeNvidiaProvider(provider: string | null | undefined): boolean { - return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; -} - -export function resolveGatewayNativeNvidiaProviderAuthority(input: { - gatewayName: string; - gatewayAuthority?: NativeNvidiaProviderAttachment | null; - recordedAttachment?: NativeNvidiaProviderAttachment | null; -}): NativeNvidiaProviderAttachment | undefined { - const authorities = new Map(); - for (const receipt of [input.gatewayAuthority, input.recordedAttachment]) { - if (receipt) authorities.set(receipt.providerId, receipt); - } - if (authorities.size > 1) { - throw new NativeNvidiaProviderError( - `Gateway '${input.gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, - ); - } - return authorities.values().next().value; -} - -export function nativeInferenceProviderForSandbox( - provider: string | null | undefined, -): string | null { - const normalized = provider?.trim() || null; - return isNativeNvidiaProvider(normalized) ? NVIDIA_HOSTED_NATIVE_PROVIDER : normalized; -} - -function providerErrorDetail(error: OpenShellProviderError): string { - return error.message.trim() || "OpenShell did not provide a diagnostic."; -} - -async function requireNativeNvidiaProviderProfileBoundary( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, - profilePath = nativeNvidiaProviderProfilePath(), -): Promise { - const imported = await adapter.importProviderProfile({ target, profilePath }); - if (imported.ok) return; - const collision = - imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; - throw new NativeNvidiaProviderError( - collision - ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` - : `Could not verify OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, - ); -} - -function exactNativeProvider(metadata: OpenShellProviderMetadata): boolean { - return ( - metadata.name === NVIDIA_HOSTED_NATIVE_PROVIDER && - metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID && - metadata.configKeys.length === 0 && - metadata.credentialKeys.length === 1 && - metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && - Boolean(metadata.revision?.id) - ); -} - -export function nativeNvidiaProviderAttachmentFromMetadata( - metadata: OpenShellProviderMetadata, -): NativeNvidiaProviderAttachment { - if (!exactNativeProvider(metadata) || !metadata.revision) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' does not match the NemoClaw-owned NVIDIA inference boundary. No provider was changed.`, - ); - } - return { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: metadata.revision.id, - }; -} - -async function inspectNativeProvider( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, -): Promise { - const observed = await adapter.getProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (observed.ok) return observed.value; - if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; - throw new NativeNvidiaProviderError( - `Could not inspect OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(observed.error)}`, - ); -} - -function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { - return ( - error.kind === "timeout" || - (error.kind === "transport" && - (error.reason === "connection_loss" || error.reason === "unreachable")) || - (error.kind === "command" && error.reason === "uncertain") - ); -} - -function authorityPersistenceRecovery(gatewayName: string): string { - return `Run 'nemoclaw credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER} --yes' against gateway '${gatewayName}', then retry.`; -} - -async function removeNewNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const removed = await input.adapter.deleteProvider({ - target: input.target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!removed.ok && !mutationOutcomeMayBeAmbiguous(removed.error)) { - throw new NativeNvidiaProviderError( - `Could not remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(removed.error)}`, - ); - } - const after = await inspectNativeProvider(input.adapter, input.target); - if (after) { - const observed = nativeNvidiaProviderAttachmentFromMetadata(after); - const identity = - observed.providerId === input.expected.providerId ? "still exists" : "changed identity"; - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' ${identity} after cleanup.`, - ); - } -} - -/** Record provider authority or remove only the new, unreferenced provider. */ -export async function persistNativeNvidiaProviderAuthority(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - gatewayName: string; - receipt: NativeNvidiaProviderAttachment; - existing?: NativeNvidiaProviderAttachment; - readAuthority: (gatewayName: string) => NativeNvidiaProviderAttachment | undefined; - writeAuthority: (gatewayName: string, receipt: NativeNvidiaProviderAttachment) => void; -}): Promise { - try { - input.writeAuthority(input.gatewayName, input.receipt); - return; - } catch (writeError) { - const writeDetail = writeError instanceof Error ? writeError.message : String(writeError); - let observed: NativeNvidiaProviderAttachment | undefined; - try { - observed = input.readAuthority(input.gatewayName); - } catch (readError) { - const readDetail = readError instanceof Error ? readError.message : String(readError); - throw new NativeNvidiaProviderError( - `NemoClaw could not record or confirm ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Read failure: ${readDetail}`, - ); - } - if (observed?.providerId === input.receipt.providerId) return; - if (input.existing || observed) { - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained because this operation cannot prove that it is unreferenced. ${authorityPersistenceRecovery(input.gatewayName)}\n ${writeDetail}`, - ); - } - try { - await removeNewNativeNvidiaProvider({ - adapter: input.adapter, - target: input.target, - expected: input.receipt, - }); - } catch (cleanupError) { - const cleanupDetail = - cleanupError instanceof Error ? cleanupError.message : String(cleanupError); - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}', and cleanup did not complete. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Cleanup failure: ${cleanupDetail}`, - ); - } - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The newly created provider was removed. Retry the command.\n ${writeDetail}`, - ); - } -} - -/** Ensure the least-privilege NVIDIA profile and provider without retrying an ambiguous mutation. */ -export async function ensureNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - credentialValue: string | null; - reuseExistingCredential?: boolean; - expected?: NativeNvidiaProviderAttachment; - profilePath?: string; -}): Promise { - const { adapter, target } = input; - await requireNativeNvidiaProviderProfileBoundary( - adapter, - target, - input.profilePath ?? nativeNvidiaProviderProfilePath(), - ); - - const activatePolicy = async () => { - const policy = await adapter.ensureProviderPolicyComposition({ target }); - if (!policy.ok) { - throw new NativeNvidiaProviderError( - `Could not activate native NVIDIA provider policy: ${providerErrorDetail(policy.error)}`, - ); - } - }; - - const before = await inspectNativeProvider(adapter, target); - if (before) { - const receipt = nativeNvidiaProviderAttachmentFromMetadata(before); - if (!input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' already exists without a matching NemoClaw ownership receipt. No provider was changed.`, - ); - } - if (input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - await activatePolicy(); - if (!input.credentialValue) return receipt; - const updated = await adapter.updateProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], - config: [], - }); - if (!updated.ok && mutationOutcomeMayBeAmbiguous(updated.error)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm whether provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' accepted its credential update. No provider receipt was recorded.`, - ); - } - if (!updated.ok) { - throw new NativeNvidiaProviderError( - `Could not update OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(updated.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after its credential update.`, - ); - } - const observedReceipt = nativeNvidiaProviderAttachmentFromMetadata(observed); - if (observedReceipt.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity during its credential update. No provider receipt was recorded.`, - ); - } - return observedReceipt; - } - - if (input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - - if (!input.credentialValue && !input.reuseExistingCredential) { - throw new NativeNvidiaProviderError( - `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, - ); - } - await activatePolicy(); - const created = await adapter.createProvider({ - target, - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: input.credentialValue - ? [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }] - : [], - config: [], - fromExisting: !input.credentialValue, - }); - if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { - throw new NativeNvidiaProviderError( - `Could not create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(created.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after creation.`, - ); - } - return nativeNvidiaProviderAttachmentFromMetadata(observed); -} - -/** Prove that the exact NemoClaw-owned NVIDIA provider is attached to one sandbox. */ -export async function verifyNativeNvidiaProviderAttachment(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected?: NativeNvidiaProviderAttachment; -}): Promise { - await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (input.expected && input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const attachments = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!attachments.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, - ); - } - if (!attachments.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `Sandbox '${input.sandboxName}' does not have its native NVIDIA inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, - ); - } - return receipt; -} - -/** Attach native NVIDIA access and reconcile an ambiguous command through observation. */ -export async function ensureNativeNvidiaProviderAttached(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { - await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (receipt.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const before = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!before.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, - ); - } - if (before.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: false, - }; - } - const attached = await input.adapter.attachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { - throw new NativeNvidiaProviderError( - `Could not attach native NVIDIA provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, - ); - } - try { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: true, - }; - } catch (error) { - try { - await detachNativeNvidiaProvider(input); - } catch (detachError) { - const detail = error instanceof Error ? error.message : String(error); - const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); - throw new NativeNvidiaProviderError(`${detail}\n ${detachDetail}`); - } - throw error; - } -} - -/** Detach only the recorded native NVIDIA provider identity and prove absence. */ -export async function detachNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to detach OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const detached = await input.adapter.detachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { - throw new NativeNvidiaProviderError( - `Could not detach native NVIDIA provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, - ); - } - const after = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!after.ok || after.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm removal of native NVIDIA access from sandbox '${input.sandboxName}'.`, - ); - } -} From 9ee0a85a7a6f4bb00d4d957ca61604cab09c5ff0 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 8 Oct 2026 17:30:39 -0700 Subject: [PATCH 132/133] fix(inference): reconcile native policy integration owners Signed-off-by: Deepak Jain --- .../native-nvidia/network-policy.test.ts | 11 ++++- .../inference/native-nvidia/network-policy.ts | 6 ++- .../onboard/sandbox-create/orchestration.ts | 13 ++---- .../sandbox-create/rebuild-policy-handoff.ts | 17 +++++++- src/lib/state/registry/persistence.ts | 2 +- ...eepagents-code-direct-module-patch.test.ts | 42 ------------------- ...epagents-code-managed-model-params.test.ts | 42 +++++++++++++++++++ 7 files changed, 74 insertions(+), 59 deletions(-) diff --git a/src/lib/inference/native-nvidia/network-policy.test.ts b/src/lib/inference/native-nvidia/network-policy.test.ts index 9de714bf82b..554c9ba0ef7 100644 --- a/src/lib/inference/native-nvidia/network-policy.test.ts +++ b/src/lib/inference/native-nvidia/network-policy.test.ts @@ -6,7 +6,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import YAML from "yaml"; import { buildNativeNvidiaSandboxPolicy } from "./network-policy"; -import { nativeNvidiaProviderProfilePath } from "./index"; afterEach(() => vi.restoreAllMocks()); @@ -35,7 +34,15 @@ describe("native NVIDIA static policy preparation", () => { { condition: "another profile ID", override: { id: "other-profile" } }, { condition: "inference capability is disabled", override: { inference_capable: false } }, ])("rejects the parsed profile when $condition (#12822)", ({ override }) => { - const profile = YAML.parse(fs.readFileSync(nativeNvidiaProviderProfilePath(), "utf8")); + const profile = YAML.parse( + fs.readFileSync( + new URL( + "../../../../managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", + import.meta.url, + ), + "utf8", + ), + ); vi.spyOn(fs, "readFileSync").mockReturnValue(YAML.stringify({ ...profile, ...override })); expect(() => buildNativeNvidiaSandboxPolicy("version: 1\n")).toThrow( "checked-in provider profile is invalid", diff --git a/src/lib/inference/native-nvidia/network-policy.ts b/src/lib/inference/native-nvidia/network-policy.ts index 3fcf1ffa449..0a5293d5951 100644 --- a/src/lib/inference/native-nvidia/network-policy.ts +++ b/src/lib/inference/native-nvidia/network-policy.ts @@ -8,15 +8,17 @@ import YAML from "yaml"; import { parseCheckedInProviderProfileContract } from "../../adapters/openshell/provider-profile"; import { parseOpenShellPolicy } from "../../adapters/openshell/policy-boundary"; import { NVIDIA_HOSTED_NATIVE_PROFILE_ID } from "./contract"; -import { nativeNvidiaProviderProfilePath } from "./index"; +import { nativeHostedProviderProfilePath, nativeHostedProfile } from "../native-hosted"; const NATIVE_NVIDIA_INFERENCE_POLICY_KEY = "native_nvidia_inference"; /** Keep native access scoped to the same checked-in profile that owns its credential. */ export function buildNativeNvidiaSandboxPolicy(basePolicy: string): string { const parsed = { ...parseOpenShellPolicy(basePolicy).policy }; + const nativeProfile = nativeHostedProfile("nvidia-prod"); + if (!nativeProfile) throw new Error("Native NVIDIA provider profile is unavailable."); const profile = parseCheckedInProviderProfileContract( - fs.readFileSync(nativeNvidiaProviderProfilePath(), "utf8"), + fs.readFileSync(nativeHostedProviderProfilePath(nativeProfile), "utf8"), ); if ( !profile || diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index a21423e7a69..e9799943315 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -401,16 +401,9 @@ export function selectRebuildCreatePolicy( livePolicyPath: policySourcePath, ...(policySource === undefined ? {} : { livePolicySource: policySource }), replacementPolicy: generatedPolicy, - requiredNetworkPolicyKeys: [ - ...requiredNetworkPolicyKeys, - ...(usesNativeNvidiaProvider(inferenceProvider) ? ["native_nvidia_inference"] : []), - ], - removedNetworkPolicyKeys: [ - ...removedNetworkPolicyKeys, - ...(inferenceProvider !== null && !usesNativeNvidiaProvider(inferenceProvider) - ? ["native_nvidia_inference"] - : []), - ], + requiredNetworkPolicyKeys, + removedNetworkPolicyKeys, + inferenceProvider, requiredNetworkPolicySources, authorizedCredentialBindingProviders, }); diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts index faac085c290..abc7dda19fc 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts @@ -9,6 +9,7 @@ import { parseOpenShellPolicy, stripProviderComposedPolicies, } from "../../adapters/openshell/policy-boundary"; +import { NVIDIA_HOSTED_NATIVE_PROVIDER } from "../../inference/native-nvidia/contract"; import { isReviewedMessagingChannelPolicyUpgrade } from "../../messaging/channels/policy"; import { reconcileTeamsOutlookLoginCredentialBinding } from "../../policy/microsoft-login-credential-binding"; import { parseAndValidateSandboxPolicy } from "../../policy/sandbox-policy-validation"; @@ -314,6 +315,7 @@ export function mergeReplacementPolicyAccess( /** Materialize the single ephemeral policy input consumed by an explicit rebuild. */ export function materializeRebuildPolicyHandoff(input: { + readonly inferenceProvider?: string | null; readonly sandboxName?: string; readonly livePolicyPath: string; readonly livePolicySource?: string; @@ -330,8 +332,19 @@ export function materializeRebuildPolicyHandoff(input: { const merged = mergeReplacementPolicyAccess( liveSource, replacementSource, - input.requiredNetworkPolicyKeys, - input.removedNetworkPolicyKeys, + [ + ...(input.requiredNetworkPolicyKeys ?? []), + ...(input.inferenceProvider === NVIDIA_HOSTED_NATIVE_PROVIDER + ? ["native_nvidia_inference"] + : []), + ], + [ + ...(input.removedNetworkPolicyKeys ?? []), + ...(input.inferenceProvider != null && + input.inferenceProvider !== NVIDIA_HOSTED_NATIVE_PROVIDER + ? ["native_nvidia_inference"] + : []), + ], input.requiredNetworkPolicySources, input.sandboxName, ); diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index 32d4937ef43..841f0964e02 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -1,5 +1,5 @@ import { normalizeGatewayNativeHostedAuthorities } from "./native-nvidia-provider-authority-state"; -import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 diff --git a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts index 8c3aecbcc7c..756ce785232 100644 --- a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts @@ -482,48 +482,6 @@ check("disabled", False) ); }); - it.each(["openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", undefined])( - "maps the legacy native credential key only when a current binding exists [%#] (#12822)", - (placeholder) => { - const tempDir = createPatchedPackageFixture(); - const validation = String.raw` -import os -from deepagents_code import _nemoclaw_managed as managed -managed.assert_safe_runtime() -assert os.environ.get("NEMOCLAW_ATTACHED_PROVIDER_API_KEY") == (os.environ.get("NVIDIA_INFERENCE_API_KEY") or None) -managed._assert_safe_environment() -`; - const result = spawnSync("python3", ["-c", validation], { - env: { - PATH: process.env.PATH, - PYTHONPATH: tempDir, - NVIDIA_INFERENCE_API_KEY: placeholder, - NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "nemoclaw-openshell-provider", - }, - encoding: "utf8", - }); - expect(result.status, result.stderr).toBe(0); - }, - ); - - it("rejects a legacy placeholder that does not match the current native binding (#12822)", () => { - const tempDir = createPatchedPackageFixture(); - const result = spawnSync("python3", ["-m", "deepagents_code"], { - env: { - PATH: process.env.PATH, - PYTHONPATH: tempDir, - NVIDIA_INFERENCE_API_KEY: "openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", - NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "openshell:resolve:env:v2_NVIDIA_INFERENCE_API_KEY", - }, - encoding: "utf8", - }); - expect(result.status).not.toBe(0); - expect(result.stderr).toContain( - "runtime environment variable NEMOCLAW_ATTACHED_PROVIDER_API_KEY", - ); - expect(result.stdout).not.toContain("managed-posture-ok"); - }); - it.each([ "openshell:resolve:env:GITHUB_MCP_TOKEN", "openshell:resolve:env:v0_GITHUB_MCP_TOKEN", diff --git a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts index d1e46d794cc..313d30ce47a 100644 --- a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts @@ -175,6 +175,48 @@ print("native-managed-constructor-placeholder-ok") }); describe("native inference issued credentials", () => { + it.each(["openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", undefined])( + "maps the legacy native credential key only when a current binding exists [%#] (#12822)", + (placeholder) => { + const tempDir = createPatchedPackageFixture(); + const validation = String.raw` +import os +from deepagents_code import _nemoclaw_managed as managed +managed.assert_safe_runtime() +assert os.environ.get("NEMOCLAW_ATTACHED_PROVIDER_API_KEY") == (os.environ.get("NVIDIA_INFERENCE_API_KEY") or None) +managed._assert_safe_environment() +`; + const result = spawnSync("python3", ["-c", validation], { + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + NVIDIA_INFERENCE_API_KEY: placeholder, + NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "nemoclaw-openshell-provider", + }, + encoding: "utf8", + }); + expect(result.status, result.stderr).toBe(0); + }, + ); + + it("rejects a legacy placeholder that does not match the current native binding (#12822)", () => { + const tempDir = createPatchedPackageFixture(); + const result = spawnSync("python3", ["-m", "deepagents_code"], { + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + NVIDIA_INFERENCE_API_KEY: "openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", + NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "openshell:resolve:env:v2_NVIDIA_INFERENCE_API_KEY", + }, + encoding: "utf8", + }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + "runtime environment variable NEMOCLAW_ATTACHED_PROVIDER_API_KEY", + ); + expect(result.stdout).not.toContain("managed-posture-ok"); + }); + it.each([ ["nvidia-prod", "https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"], ["openai-api", "https://api.openai.com/v1", "OPENAI_API_KEY"], From 5533741c5a2a6a04888b41f9c1788c836643e293 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 8 Oct 2026 18:15:45 -0700 Subject: [PATCH 133/133] fix(inference): reuse native gateway credentials during rebuild Signed-off-by: Prekshi Vyas --- src/lib/onboard/setup-inference.test.ts | 27 +++++++++++++++---------- src/lib/onboard/setup-inference.ts | 6 +++++- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index abd125f18ba..ed35ea8f758 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -396,14 +396,16 @@ describe("native NVIDIA onboarding", () => { expect(verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); }); - it("reuses a gateway-owned provider for a fresh second sandbox", async () => { + it.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "hermes-provider"), + )("reuses $label gateway credentials without an unauthenticated host smoke", async (profile) => { const importProviderProfile = vi.fn(async () => ({ ok: true as const })); const getProvider = vi.fn(async () => ({ ok: true, value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], configKeys: [], revision: { id: "provider-id", resourceVersion: 4 }, }, @@ -411,6 +413,9 @@ describe("native NVIDIA onboarding", () => { const createProvider = vi.fn(); const updateProvider = vi.fn(); const updateSandbox = vi.fn(() => true); + const verifyOnboardInferenceSmoke = vi.fn(async () => { + throw new Error("HTTP 401: Header of type authorization was missing"); + }); const setupInference = createSetupInference({ checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => @@ -424,13 +429,13 @@ describe("native NVIDIA onboarding", () => { getSandbox: () => null, getNativeHostedProviderAuthority: () => ({ schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", + profileId: profile.profileId, + providerName: profile.providerName, providerId: "provider-id", }), upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), - verifyOnboardInferenceSmoke: vi.fn(async () => undefined), + verifyOnboardInferenceSmoke, isNonInteractive: () => true, hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, providerAdapter: { @@ -454,18 +459,18 @@ describe("native NVIDIA onboarding", () => { setupInference( "second", "nvidia/nemotron-3-super-120b-a12b", - "nvidia-prod", - "https://integrate.api.nvidia.com/v1", - "NVIDIA_INFERENCE_API_KEY", + profile.logicalProvider, + profile.endpoint, + profile.credentialEnv, null, [], { revalidateSandboxIdentity: () => undefined, - reuseGatewayCredentialWithoutLocalKey: true, }, ), ).resolves.toEqual({ ok: true }); + expect(verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); expect(createProvider).not.toHaveBeenCalled(); expect(updateProvider).not.toHaveBeenCalled(); expect(updateSandbox).toHaveBeenCalledWith( diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 5d55da1ca7d..8bf8449fdf0 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -779,6 +779,7 @@ export function createSetupInference( let hostLocalInferenceGatewayPortAuthority: number | undefined; let hostLocalInferenceRuntimeProviderId: string | undefined; let nativeHostedProviderAttachment: NativeHostedProviderAttachment | undefined; + let nativeGatewayCredentialOnly = false; const reserveRoute = (name: string, selectedProvider: string, selectedModel: string) => { if (routeReserved) return true; revalidateSandboxIdentity?.("reserve the sandbox inference route"); @@ -1017,6 +1018,9 @@ export function createSetupInference( reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, ...(providerAuthority ? { expected: providerAuthority } : {}), }); + // The verified provider owns this credential. A direct host smoke + // would send no authorization; sandbox readiness probes the attachment. + nativeGatewayCredentialOnly = provider !== "hermes-provider" && !credentialValue; const readAuthority = deps.getNativeHostedProviderAuthority && ((name: string) => deps.getNativeHostedProviderAuthority!(name, profile.profileId)); @@ -1222,7 +1226,7 @@ export function createSetupInference( deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", ); - } else if (options.skipHostInferenceSmoke === true) { + } else if (nativeGatewayCredentialOnly || options.skipHostInferenceSmoke === true) { deps.log(" Reusing existing gateway credential; skipping host inference smoke."); } else { await deps.verifyOnboardInferenceSmoke({