diff --git a/Dockerfile b/Dockerfile index 1e561a0f3f8..55e06fed87c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -684,13 +684,8 @@ COPY scripts/verify-wechat-runtime-lock.mts /usr/local/lib/nemoclaw/verify-wecha FROM scratch AS openclaw-runtime-payload -COPY scripts/lib/sandbox-init.sh /usr/local/lib/nemoclaw/sandbox-init.sh +COPY scripts/lib/sandbox-init.sh scripts/lib/entrypoint-env-wrapper.sh scripts/lib/sandbox-rlimits.sh scripts/lib/openclaw_device_approval_policy.py scripts/lib/openclaw_pairing_state.py scripts/lib/refresh-openclaw-wechat-placeholder.py /usr/local/lib/nemoclaw/ COPY --chmod=0444 scripts/lib/corporate-ca-runtime.sh /usr/local/lib/nemoclaw/corporate-ca-runtime.sh -COPY scripts/lib/entrypoint-env-wrapper.sh /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh -COPY scripts/lib/sandbox-rlimits.sh /usr/local/lib/nemoclaw/sandbox-rlimits.sh -COPY scripts/lib/openclaw_device_approval_policy.py /usr/local/lib/nemoclaw/openclaw_device_approval_policy.py -COPY scripts/lib/openclaw_pairing_state.py /usr/local/lib/nemoclaw/openclaw_pairing_state.py -COPY scripts/lib/refresh-openclaw-wechat-placeholder.py /usr/local/lib/nemoclaw/refresh-openclaw-wechat-placeholder.py COPY scripts/nemoclaw-start.sh /usr/local/bin/nemoclaw-start COPY scripts/managed-startup-hold.sh /usr/local/bin/nemoclaw-managed-startup-hold COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/ @@ -699,6 +694,8 @@ 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 --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/inference-credential.ts /src/lib/ +COPY src/lib/core/endpoint-url-safety.ts /src/lib/core/ +COPY src/lib/inference/native-local/agent-config.ts /src/lib/inference/native-local/ COPY src/lib/inference/native-provider/agent-config.ts src/lib/inference/native-provider/hosted.ts src/lib/inference/native-provider/contract.ts /src/lib/inference/native-provider/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ COPY --from=mcp-tool-discovery-runtime /opt/mcp-tool-discovery-runtime/dist/ /usr/local/lib/nemoclaw/mcp-tool-discovery-runtime/ diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 0c425289028..6ac404a685e 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial no-growth baseline for issue #10934 and Epic #10920. The epic reference remains fixed at fe18b2f004e2304c52db33cf7bb5895828197f9a. Current main is lower because #10722 removed the live Shields assertion suites before this ratchet landed. PR #10341 adds the accepted public deferred-install and same-home credential continuation boundary for Hermes and Deep Agents Code; existing per-file budgets remain unchanged. PR #13055 adds five explicitly approved assertions for the native Deep Agents Code OpenRouter request in the existing hosted OpenRouter target.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial no-growth baseline for issue #10934 and Epic #10920. The epic reference remains fixed at fe18b2f004e2304c52db33cf7bb5895828197f9a. Current main is lower because #10722 removed the live Shields assertion suites before this ratchet landed. PR #10341 adds the accepted public deferred-install and same-home credential continuation boundary for Hermes and Deep Agents Code; existing per-file budgets remain unchanged. PR #13055 adds five explicitly approved assertions for the native Deep Agents Code OpenRouter request in the existing hosted OpenRouter target. PR #13293 consolidates native-local cases into the existing OpenClaw switching owner. Removing duplicated deterministic metadata and direct mock requests lowers suite totals while retaining real authenticated and sentinel agent turns, lifecycle, model switching, credential isolation and sibling denial. Per-file transitive counts include existing imported helpers; no live files or suite assertion points are added.", "schemaVersion": 1, "issue": 10934, "epic": 10920, @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 186, "direct": { - "expectCalls": 1272, - "matcherAssertions": 1251, + "expectCalls": 1256, + "matcherAssertions": 1236, "nodeAssertions": 104, - "namedAssertionHelpers": 420, + "namedAssertionHelpers": 422, "failCalls": 0, "throwGuards": 50, - "objectFieldAssertions": 181, - "assertionPoints": 2006, + "objectFieldAssertions": 184, + "assertionPoints": 1996, "generatedProbeBlocks": 86, "generatedProbeConditions": 215 }, "unique": { - "expectCalls": 1694, - "matcherAssertions": 1668, + "expectCalls": 1678, + "matcherAssertions": 1653, "nodeAssertions": 127, - "namedAssertionHelpers": 664, + "namedAssertionHelpers": 666, "failCalls": 1, "throwGuards": 526, - "objectFieldAssertions": 258, - "assertionPoints": 3244, + "objectFieldAssertions": 261, + "assertionPoints": 3234, "generatedProbeBlocks": 209, "generatedProbeConditions": 721 }, @@ -95,7 +95,7 @@ "test/e2e/live/onboard-repair.test.ts": [22,26,22,26,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,51,1], + "test/e2e/live/openclaw-inference-switch.test.ts": [28,40,55,85,3], "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 75bc4b1ad25..3a022d3a016 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.\n\nPR #13293 consolidates OpenClaw native-local scenarios into the existing switching owner and removes duplicated deterministic metadata checks and the redundant mock curl probe. Suite totals fall by 16 expect calls and 10 assertion points without adding live files. Only the owning file transitive allocation grows because it now imports existing live helpers. Maintainer authorization: https://github.com/NVIDIA/NemoClaw/pull/13293#issuecomment-6211036786. This exact transition supports candidate CI; independent enforcement still verifies the maintainer record.", "schemaVersion": 1, "exceptions": [ { @@ -54,6 +54,10 @@ { "pullRequest": 13203, "changeSha256": "2648bafc4ce603c32746db6488c8d32ae5ad2d05c0414cb9ec5593f55e6a06b9" + }, + { + "pullRequest": 13293, + "changeSha256": "0466cf6b71d851c759490e4142ab6c20f9eec07dfa1787a2d8332ab5696cf154" } ] } diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index d903a85ea49..9aba8dacd84 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -41,7 +41,7 @@ "fanOut": { "defaultMax": 20, "maxByFile": { - "src/lib/actions/inference-set.ts": 31, + "src/lib/actions/inference-set.ts": 30, "src/lib/actions/sandbox/connect.ts": 41, "src/lib/actions/sandbox/destroy.ts": 27, "src/lib/actions/sandbox/doctor.ts": 26, diff --git a/docs/about/how-it-works.mdx b/docs/about/how-it-works.mdx index 3dacad97cc0..556abbd7a52 100644 --- a/docs/about/how-it-works.mdx +++ b/docs/about/how-it-works.mdx @@ -213,8 +213,9 @@ Refer to [Recover and Rebuild Sandboxes](../manage-sandboxes/operate-sandboxes/r New NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider selections use sandbox-attached OpenShell providers. The agent calls the selected provider API hostname, and OpenShell permits only the approved destination and request paths. New Deep Agents Code selections also use native providers for Ollama, standalone vLLM, llama.cpp, and qualifying local compatible endpoints. -Owned Local NVIDIA NIM, other custom endpoints, local providers for other agents, and Model Router retain `inference.local`. -Legacy Deep Agents Code standalone local sandboxes require backup and fresh recreation before native-provider onboarding; NemoClaw blocks their resume and rebuild. Owned Local NIM sandboxes retain the shared route and can resume or rebuild without a native attachment. +New OpenClaw Ollama, standalone vLLM, and llama.cpp selections also use sandbox-attached native providers. +Owned Local NVIDIA NIM, user-supplied compatible endpoints, Pi and Hermes local selections, retained OpenClaw shared local selections, and Model Router retain `inference.local`. +Legacy Deep Agents Code standalone local sandboxes require backup and fresh recreation before native-provider onboarding; NemoClaw blocks their resume and rebuild. An older OpenClaw Ollama, standalone vLLM, or llama.cpp sandbox without an attachment can retain its supported shared-route model switches, but cannot resume or rebuild. Back it up and re-onboard with `--fresh --name --recreate-sandbox`. Owned Local NIM sandboxes retain the shared route and can resume or rebuild without a native attachment. Refer to [About Inference Routing](../inference/about-inference-routing) for endpoints and route inspection. 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. diff --git a/docs/about/overview.mdx b/docs/about/overview.mdx index 20240460a80..5dba39c2673 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. NVIDIA Endpoints and supported fixed hosted providers use sandbox-attached native providers. New Deep Agents Code selections also use native providers for Ollama, standalone vLLM, llama.cpp, and qualifying local compatible endpoints. Owned Local NVIDIA NIM and other routes retain `inference.local`. OpenShell keeps provider credentials outside the sandbox. | +| Route inference | Connects supported hosted and local inference providers through OpenShell-managed routes. NVIDIA Endpoints and supported fixed hosted providers use sandbox-attached native providers. New Deep Agents Code selections also use native providers for Ollama, standalone vLLM, llama.cpp, and qualifying local compatible endpoints; new OpenClaw Ollama, standalone vLLM, and llama.cpp selections use native providers too. Owned Local NVIDIA NIM, user-supplied compatible endpoints, and retained shared local routes 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 2545dc21920..c54d2d6f9cc 100644 --- a/docs/deployment/deploy-to-headless-server.mdx +++ b/docs/deployment/deploy-to-headless-server.mdx @@ -275,6 +275,8 @@ Deep Agents Code does not expose a dashboard URL or gateway token. NVIDIA Endpoi +New OpenClaw Ollama, standalone vLLM, and llama.cpp selections use a sandbox-attached native provider. Local NVIDIA NIM and user-supplied compatible endpoints retain the shared `inference.local` route; an older local selection without an attachment may also retain it until a safe fresh recreation. + OpenClaw generates a new gateway token when the sandbox container starts with mutable configuration. Retrieve the dashboard URL or token again after the container starts or a replacement sandbox is created. diff --git a/docs/inference/choose-local-inference-server.mdx b/docs/inference/choose-local-inference-server.mdx index 6807367a0aa..a7559977714 100644 --- a/docs/inference/choose-local-inference-server.mdx +++ b/docs/inference/choose-local-inference-server.mdx @@ -12,7 +12,7 @@ content: NemoClaw supports operator-run servers and NemoClaw-managed runtime profiles for local inference. Choose the option that matches your host, model, and operational needs. -New Deep Agents Code sandboxes selecting Ollama, standalone vLLM, llama.cpp, or a qualifying local compatible endpoint send inference requests to a qualified host-local endpoint through a sandbox-attached OpenShell provider. OpenClaw, Pi, Hermes, and owned Local NVIDIA NIM continue to use `inference.local` for local inference. +New Deep Agents Code and OpenClaw sandboxes use sandbox-attached OpenShell providers for Ollama, standalone vLLM, and llama.cpp. Local NVIDIA NIM, Pi, and Hermes continue to use `inference.local`. Existing OpenClaw Ollama, standalone vLLM, and llama.cpp sandboxes without an attachment retain supported shared-route model switches, but cannot resume or rebuild. Back them up and re-onboard with `--fresh --name --recreate-sandbox`. Owned Local NVIDIA NIM sandboxes can resume or rebuild on their shared route. On native N1x Linux, use the Deferred managed-vLLM preview or enter standard onboarding explicitly. diff --git a/docs/inference/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index 3d3949e053d..097e1ac1c1a 100644 --- a/docs/inference/how-inference-routing-works.mdx +++ b/docs/inference/how-inference-routing-works.mdx @@ -37,7 +37,7 @@ For an endpoint returned by Hermes login, NemoClaw records its accepted public I A different destination cannot gain access through a later DNS change. Existing sandboxes without a native attachment retain their recorded shared route. -New Deep Agents Code selections of Ollama, standalone vLLM, llama.cpp, and qualifying local compatible endpoints use sandbox-attached providers for their qualified host-local endpoints. OpenClaw, Pi, Hermes, owned Local NVIDIA NIM, other custom endpoints, and Model Router retain the shared route. +New Deep Agents Code and OpenClaw selections for Ollama, standalone vLLM, and llama.cpp use a sandbox-attached provider for the qualified host-local endpoint. Deep Agents Code also uses one for qualified host-local compatible endpoints. Pi, Hermes, Local NVIDIA NIM, other custom endpoints, and Model Router retain the shared route. ```text Sandbox agent -> inference.local -> shared OpenShell route -> selected provider and model @@ -55,7 +55,7 @@ The sandbox does not receive the raw upstream API key. Local Ollama and local vLLM routes do not require the host `OPENAI_API_KEY`. NemoClaw uses provider-specific local tokens for those routes. For retained shared local routes, rebuilds migrate away from stale OpenAI credential requirements. -Legacy Deep Agents local sandboxes without an attachment require a backup and fresh recreation. +Legacy Deep Agents Code local sandboxes without an attachment require a backup and fresh recreation. Existing OpenClaw Ollama, standalone vLLM, and llama.cpp sandboxes without an attachment retain supported model switches on their shared route, but cannot resume or rebuild. Back one up and re-onboard with `--fresh --name --recreate-sandbox`. Owned Local NVIDIA NIM sandboxes retain the shared route and can resume or rebuild. When a rebuild reuses an automatically bridged compatible-endpoint route without a host API key, NemoClaw reapplies the config-only bridge rewrite without reading or passing the credential stored in OpenShell. diff --git a/docs/inference/switch-providers.mdx b/docs/inference/switch-providers.mdx index 53cc9582128..e2fc7fe0d40 100644 --- a/docs/inference/switch-providers.mdx +++ b/docs/inference/switch-providers.mdx @@ -48,7 +48,7 @@ Target a non-default sandbox by name. $$nemoclaw inference set --provider --model --sandbox ``` -For native NVIDIA and fixed hosted providers, NemoClaw updates only the selected sandbox attachment and verifies a request through its native endpoint. +For native NVIDIA and fixed hosted providers, NemoClaw updates only the selected sandbox attachment and verifies a request through its native endpoint. OpenClaw also keeps model switches on a recorded native Ollama, standalone vLLM, or llama.cpp attachment within that sandbox. OpenRouter requests include its attribution headers. If sandbox verification fails, NemoClaw tries to restore the previous inference selection and does not commit the agent configuration. @@ -58,8 +58,9 @@ If sandbox verification fails, NemoClaw tries to restore the previous inference For OpenClaw, NemoClaw updates the provider namespace and selected model in the running configuration. It adds or updates the requested model entry without removing other model entries in that provider. -For NVIDIA Endpoints and native hosted providers, it writes the attached provider's current scoped OpenShell credential reference into the native configuration. +For NVIDIA Endpoints, native hosted providers, and native local providers, it writes the attached provider's scoped OpenShell credential reference into the native configuration. This reference is not a raw provider credential. +A switch to a local provider without a matching sandbox-owned attachment stops before changing the shared route. Back up the sandbox and create a fresh one with the local selection. Existing shared-route local sandboxes can still change models through their recorded shared route where its owner supports that operation. After any changed configuration sync, NemoClaw restarts only the OpenClaw gateway and verifies its health. The sandbox remains running, but agent requests are briefly interrupted. After every changed synchronized route, NemoClaw verifies that the local CLI device has the managed gateway's required pairing scopes before it reports success. diff --git a/docs/inference/understand-provider-validation.mdx b/docs/inference/understand-provider-validation.mdx index 02fc5e709ce..440d0bbd294 100644 --- a/docs/inference/understand-provider-validation.mdx +++ b/docs/inference/understand-provider-validation.mdx @@ -57,6 +57,12 @@ The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat + + +New OpenClaw Ollama, standalone vLLM, and llama.cpp selections use their recorded sandbox-attached native provider for validation. Local NVIDIA NIM, user-supplied compatible endpoints, and retained shared local selections use `inference.local`. An older OpenClaw Ollama, standalone vLLM, or llama.cpp sandbox without a native attachment can use supported shared-route model switches, but cannot resume or rebuild. Back it up and re-onboard with `--fresh --name --recreate-sandbox`. Owned Local NVIDIA NIM sandboxes can resume or rebuild on the shared route. + + + ## Anthropic-Compatible Requests diff --git a/docs/inference/use-shared-gateway-routes.mdx b/docs/inference/use-shared-gateway-routes.mdx index 37a7b127e94..7198142c2fe 100644 --- a/docs/inference/use-shared-gateway-routes.mdx +++ b/docs/inference/use-shared-gateway-routes.mdx @@ -10,15 +10,15 @@ content: type: "how_to" --- -These rules apply to providers that still use the shared route, including owned Local NVIDIA NIM, retained legacy and other custom shared routes, and local routes for agents other than Deep Agents Code. -NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, Hermes Provider, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections use sandbox-attached native providers instead. Their selected provider path does not re-point the shared route. +These rules apply to providers that still use the shared route, including user-supplied compatible endpoints, Local NVIDIA NIM, and retained shared local selections. +NVIDIA Endpoints, fixed hosted providers, new Deep Agents Code local selections, and new OpenClaw Ollama, standalone vLLM, and llama.cpp selections use sandbox-attached providers. Their selected model or provider does not re-point the shared route. OpenShell exposes one shared inference route per gateway. NemoClaw records each sandbox's intended provider and model so compatible sandboxes can take turns using that route. ## Change the Live Route During Onboarding -Onboarding a sandbox with another valid provider or model warns immediately before it re-points the shared route. +Onboarding a sandbox with another valid shared-route provider or model warns immediately before it re-points the shared route. The warning names every affected registered sandbox and its recorded provider and model. Those sandboxes use the new live route until another onboarding run or connection re-points it again. @@ -39,7 +39,8 @@ Use `$$nemoclaw inference set` to change a registered sandbox's provider $$nemoclaw inference set --provider --model ``` -When only the provider or model differs, the command warns immediately before it re-points the shared route. +For a shared-route selection, when only the provider or model differs, the command warns immediately before it re-points the shared route. +An OpenClaw model switch on its recorded native local attachment keeps the shared route unchanged. The warning names every affected registered sandbox and its recorded provider and model. Those sandboxes use the new live route until `connect`, onboarding, or another `inference set` command re-points it. diff --git a/docs/inference/view-active-inference-route.mdx b/docs/inference/view-active-inference-route.mdx index 28dd8f6136d..cf573034fde 100644 --- a/docs/inference/view-active-inference-route.mdx +++ b/docs/inference/view-active-inference-route.mdx @@ -15,7 +15,7 @@ Use the NemoClaw CLI to read the selected inference provider and model. When the selected sandbox has a valid native provider attachment, the command reports the sandbox's recorded provider, model, and native endpoint without reading the shared gateway route. For providers that still use the shared route, the command reads the live OpenShell inference route. For a compatible custom provider on a shared route, the command also reports its persisted endpoint URL when the registry provider and model match the live route. -Native hosted providers are OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider. +Native hosted providers are OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider. New OpenClaw selections for Ollama, standalone vLLM, and llama.cpp also report their sandbox-attached local provider. Local NVIDIA NIM and generic compatible endpoints keep shared-route readback. Deep Agents Code also reports a recorded native local attachment for qualified Ollama, vLLM, llama.cpp, and host-local compatible endpoints. The displayed endpoint is the host-reachable address recorded for that sandbox. diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 6c7c8575096..45415a1a8cd 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -191,7 +191,8 @@ 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 a retained legacy `openrouter-api` shared route can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. -NVIDIA Endpoints and supported fixed hosted selections verify their recorded sandbox-attached provider and run the bounded model request at its native endpoint without the shared-route models probe. +NVIDIA Endpoints, supported fixed hosted selections, and new OpenClaw Ollama, standalone vLLM, and llama.cpp selections verify their recorded sandbox-attached provider and run the bounded model request at its native endpoint without the shared-route models probe. +Retained OpenClaw local selections with a valid shared route continue to use `inference.local` for supported model switches. An older OpenClaw Ollama, standalone vLLM, or llama.cpp sandbox without a native attachment cannot resume or rebuild. Back it up and re-onboard it with `--fresh --name --recreate-sandbox`. Owned Local NVIDIA NIM sandboxes retain the shared route and can resume or rebuild without a native attachment. 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/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 17917ed6cbe..693b17cb1c9 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -359,13 +359,13 @@ Inside the sandbox: ## Inference Routing Agent inference follows one of two OpenShell-managed paths. -Owned Local NVIDIA NIM, retained legacy and other custom shared routes, and local routes for agents other than Deep Agents Code use `inference.local` through the OpenShell gateway: +Owned Local NVIDIA NIM, user-supplied compatible endpoints, Pi and Hermes local selections, and retained legacy shared local routes use `inference.local` through the OpenShell gateway: ```text Supported agent runtime (sandbox) ──▶ inference.local ──▶ OpenShell gateway ──▶ Provider endpoint ``` -NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections use restricted providers attached to the sandbox. For example, NVIDIA Endpoints uses this path: +NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, plus new OpenClaw Ollama, standalone vLLM, and llama.cpp selections use restricted providers attached to the sandbox. For example, NVIDIA Endpoints uses this path: ```text Supported agent runtime (sandbox) ──▶ integrate.api.nvidia.com ──▶ NVIDIA Endpoints diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 2e3850eb6f1..b84cbed1a7e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1216,8 +1216,8 @@ 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. - NVIDIA Endpoints and supported fixed hosted selections verify their recorded sandbox-attached provider and request the model at its native endpoint without a shared-route models probe. - Retained legacy, custom, and local shared routes use `inference.local`. + NVIDIA Endpoints, supported fixed hosted selections, and new OpenClaw Ollama, standalone vLLM, and llama.cpp selections verify their recorded sandbox-attached provider and request the model at its native endpoint without a shared-route models probe. + Local NVIDIA NIM, user-supplied compatible endpoints, and retained shared local selections use `inference.local`. Their models probe must return HTTP 2xx, except that a retained legacy `openrouter-api` shared route 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`. @@ -1301,7 +1301,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, supported fixed hosted selections, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, `connect` does not inspect or change the unrelated shared route. +For NVIDIA Endpoints, supported fixed hosted selections, new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, and new OpenClaw Ollama, standalone vLLM, and llama.cpp selections, `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. @@ -1729,7 +1729,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. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, retained legacy and other custom shared routes, and local routes for other agents use `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. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, plus new OpenClaw Ollama, standalone vLLM, and llama.cpp selections, use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, user-supplied compatible endpoints, Pi and Hermes local selections, and retained shared local routes use `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` @@ -1744,7 +1744,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 sandboxes with native NVIDIA, fixed hosted, or Deep Agents Code native local provider attachments report their 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, fixed hosted, and Deep Agents Code native local provider 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, hosted, and Deep Agents Code native local 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 sandboxes with native NVIDIA, fixed hosted, or Deep Agents Code local or OpenClaw native local provider attachments report their 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, fixed hosted, and Deep Agents Code local or OpenClaw native local provider 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, hosted, and Deep Agents Code local or OpenClaw native local 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. @@ -1781,7 +1781,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. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, retained legacy and other custom shared routes, and local routes for other agents use `inference.local`. 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. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, plus new OpenClaw Ollama, standalone vLLM, and llama.cpp selections, use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, user-supplied compatible endpoints, Pi and Hermes local selections, and retained shared local routes use `inference.local`. 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 | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -1793,7 +1793,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 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 and Deep Agents local doctor checks verify the recorded provider identity and sandbox attachment, then require a successful inference request through the selected native endpoint. The native NVIDIA doctor probe 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 and Deep Agents Code and OpenClaw native local doctor checks verify the recorded provider identity and sandbox attachment, then require a successful inference request through the selected native endpoint. The native NVIDIA doctor probe 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. For a shared route, `$$nemoclaw doctor` sends no inference request, so it reports the `Inference (upstream)` state that it measured. @@ -1936,7 +1936,7 @@ The `Registered gateway binding` result depends on the sandbox registry: - For a registered sandbox with an invalid binding, the check fails, and `doctor` does not select, probe, or recover a gateway from that binding. - 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. Providers that still use the shared route 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. Fixed hosted providers and qualified Deep Agents local selections verify their recorded attachment and make an inference request to their native endpoint. +For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Providers that still use the shared route 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. Fixed hosted providers and qualified Deep Agents Code and OpenClaw local selections verify their recorded attachment and make an inference request to their native endpoint. A healthy shared route cannot satisfy that 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. @@ -3335,9 +3335,17 @@ 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. NVIDIA Endpoints, supported fixed hosted providers, and new Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, retained legacy and other custom shared routes use `inference.local`. 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. -Legacy Deep Agents local sandboxes without an attachment stop before rebuild. -Back up their data before running `nemo-deepagents onboard --fresh --name --recreate-sandbox`. +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. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. +Deep Agents also uses attached providers for qualified local endpoints. +Local NVIDIA NIM, other agents' local selections, and other custom endpoints retain the shared `inference.local` route. 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. +Legacy Deep Agents Code local sandboxes without an attachment stop before rebuild. Local NVIDIA NIM retains its shared rebuild path. +Back up the sandbox data before running `nemo-deepagents onboard --fresh --name --recreate-sandbox`. + + + + + +Legacy OpenClaw local sandboxes without a native attachment stop before rebuild. Back up the sandbox data before running `$$nemoclaw onboard --fresh --name --recreate-sandbox`. @@ -3603,7 +3611,7 @@ When at least one sandbox is registered and the named NemoClaw gateway is unreac ### `$$nemoclaw inference get` Show the provider and model for the selected inference path. -When the selected sandbox has a valid native NVIDIA, hosted, or Deep Agents Code native local provider attachment, the command reports its recorded provider, model, and native endpoint without reading the shared gateway route. +When the selected sandbox has a valid native NVIDIA, hosted, or Deep Agents Code local or OpenClaw native local provider attachment, the command reports its recorded provider, model, and native endpoint without reading the shared gateway route. For providers that still use the shared route, 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 selected inference path without the rest of the sandbox status output. @@ -3614,13 +3622,13 @@ $$nemoclaw inference get $$nemoclaw inference get --json ``` -A valid native NVIDIA, hosted, or Deep Agents Code native local attachment adds its native endpoint to the recorded provider-and-model output. +A valid native NVIDIA, hosted, or Deep Agents Code local or OpenClaw native local attachment adds its native endpoint to the recorded provider-and-model output. Other managed providers keep the provider-and-model output. Compatible providers on the shared route 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, hosted, or Deep Agents Code native local provider attachment, the command reports its recorded provider, model, and native endpoint without reading the shared gateway route. +When `` has a valid native NVIDIA, hosted, or Deep Agents Code local or OpenClaw native local provider attachment, the command reports its recorded provider, model, and native 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`. @@ -3641,7 +3649,7 @@ $$nemoclaw my-assistant inference get -Switch the active inference provider or model for a NemoClaw-managed OpenClaw sandbox. For NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider, the command attaches or updates the selected sandbox's native provider. Custom endpoints and local providers retain their existing shared OpenShell 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 OpenClaw sandbox. For NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider, the command attaches or updates the selected sandbox's native provider. Custom endpoints, Local NVIDIA NIM, and unmigrated local selections retain their existing shared OpenShell 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. @@ -3666,7 +3674,7 @@ The command is also available in sandbox-first form as `$$nemoclaw infere By default, the command syncs the default registered sandbox. -NVIDIA Endpoints and the five fixed hosted providers use sandbox-attached providers without changing the shared route. New Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections receive their native attachments during onboarding. `inference set` does not create those native local attachments; local switches through this command retain the shared-route workflow. The following route-conflict rules apply whenever the command changes the shared gateway route, including owned Local NVIDIA NIM, retained legacy and other custom shared routes, and local routes for other agents. +NVIDIA Endpoints and the five fixed hosted providers use sandbox-attached providers without changing the shared route. The following route-conflict rules apply to providers that still use the shared gateway route, including custom endpoints, Local NVIDIA NIM, and unmigrated local selections. 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. @@ -3689,7 +3697,7 @@ 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` to select the provider and model for the target sandbox. For NVIDIA Endpoints and the five fixed hosted providers, NemoClaw attaches or updates the selected sandbox's native provider and syncs its agent config without changing the shared route. `inference set` continues to use the shared-route workflow for local and custom provider switches, including owned Local NVIDIA NIM; use onboarding to create a new Deep Agents Code native local selection. 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. +Pass both `--provider` and `--model` to select the provider and model for the target sandbox. For NVIDIA Endpoints and the five fixed hosted providers, NemoClaw attaches or updates the selected sandbox's native provider and syncs its agent config without changing the shared route. OpenClaw model switches on recorded native Ollama, standalone vLLM, and llama.cpp attachments also leave the shared route unchanged; selecting a different local provider without an attachment requires a backup and fresh sandbox. Custom endpoints, Local NVIDIA NIM, and unmigrated local selections retain their existing shared-route workflow. 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. diff --git a/docs/reference/enterprise-readiness.mdx b/docs/reference/enterprise-readiness.mdx index 309a1e2c3ed..0bd8a5feec6 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. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, retained legacy and other custom shared routes, and local routes for other agents use `inference.local`. Refer to [How Inference Routing Works](../inference/about-inference-routing) for qualification and existing-sandbox boundaries. 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. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, plus new OpenClaw Ollama, standalone vLLM, and llama.cpp selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, user-supplied compatible endpoints, Pi and Hermes local selections, and retained shared local routes use `inference.local`. Refer to [How Inference Routing Works](../inference/about-inference-routing) for qualification and existing-sandbox boundaries. 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. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, retained legacy and other custom shared routes, and local routes for other agents use `inference.local`. Refer to [How Inference Routing Works](../inference/about-inference-routing) for qualification and existing-sandbox boundaries. +- Explain that inference credentials remain in OpenShell provider state, so the sandbox never holds provider keys. NVIDIA Endpoints, supported fixed hosted providers, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, plus new OpenClaw Ollama, standalone vLLM, and llama.cpp selections use native endpoints through sandbox-attached OpenShell providers. Owned Local NVIDIA NIM, user-supplied compatible endpoints, Pi and Hermes local selections, and retained shared local routes use `inference.local`. Refer to [How Inference Routing Works](../inference/about-inference-routing) for qualification and existing-sandbox boundaries. - 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/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 54d3045628c..390070a57ff 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -2068,7 +2068,7 @@ Verify that the inference provider endpoint is reachable from the host. Check th $$nemoclaw status ``` -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, including owned Local NVIDIA NIM, `status` probes `https://inference.local/v1/models` before it sends the request through `https://inference.local`. For NVIDIA Endpoints, fixed hosted selections, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections with a recorded native attachment, it verifies that attachment and sends the request to the selected native endpoint; 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 native providers retry 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. +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, including owned Local NVIDIA NIM, `status` probes `https://inference.local/v1/models` before it sends the request through `https://inference.local`. For NVIDIA Endpoints, fixed hosted selections, and new Deep Agents Code Ollama, standalone vLLM, llama.cpp, and qualifying host-local compatible selections, plus new OpenClaw Ollama, standalone vLLM, and llama.cpp selections with a recorded native attachment, it verifies that attachment and sends the request to the selected native endpoint; 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 native providers retry 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. diff --git a/scripts/generate-openclaw-config.mts b/scripts/generate-openclaw-config.mts index 087a42d961b..5d1a643c322 100755 --- a/scripts/generate-openclaw-config.mts +++ b/scripts/generate-openclaw-config.mts @@ -28,6 +28,7 @@ // NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION. import { nativeHostedAgentConfig } from "../src/lib/inference/native-provider/agent-config.ts"; +import { nativeLocalCredentialReference } from "../src/lib/inference/native-local/agent-config.ts"; import { hasProviderlessInferenceEnvironment } from "../src/lib/providerless-inference.ts"; import { managedInferenceApiKey } from "../src/lib/inference-credential.ts"; @@ -974,10 +975,14 @@ export function buildConfig(env: Env = process.env): JsonObject { }); } const nativeHosted = nativeHostedAgentConfig(upstreamProvider, inferenceBaseUrl); + const nativeLocal = ["ollama-local", "vllm-local", "llama-cpp-local"].includes(upstreamProvider) + ? nativeLocalCredentialReference(upstreamProvider, inferenceBaseUrl) + : null; const providers = { [providerKey]: { baseUrl: inferenceBaseUrl, - apiKey: nativeHosted?.apiKey ?? managedInferenceApiKey(inferenceBaseUrl, "unused"), + apiKey: + nativeHosted?.apiKey ?? nativeLocal ?? managedInferenceApiKey(inferenceBaseUrl, "unused"), ...(nativeHosted?.headers ? { headers: nativeHosted.headers } : {}), api: inferenceApi, timeoutSeconds: agentTimeout, diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index e5352424e88..5a44d928dee 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -207,6 +207,12 @@ describe("runInferenceGet", () => { sandboxName: undefined, endpointUrl: "http://host.openshell.internal:11435/v1", }, + { + agent: "openclaw", + provider: "ollama-local", + sandboxName: "alpha", + endpointUrl: "http://host.openshell.internal:11435/v1", + }, { agent: "langchain-deepagents-code", provider: "compatible-endpoint", @@ -218,7 +224,12 @@ describe("runInferenceGet", () => { async ({ agent, provider, sandboxName, endpointUrl }) => { const deps = createDeps(configuredRoute("stale-shared-provider", "stale-shared-model")); const sandbox = nativeLocalSandbox(); - const binding = { ...sandbox.nativeLocalProviderAttachment, provider, endpointUrl }; + const binding = { + ...sandbox.nativeLocalProviderAttachment, + provider, + endpointUrl, + ...(agent === "openclaw" ? { agent: "openclaw" as const } : {}), + }; deps.getSandbox = () => nativeLocalSandbox({ agent, diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index b9a2b724029..4c1cf9292dc 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -21,7 +21,10 @@ import { } from "../inference/gateway-route-compatibility"; import { parseHttpsPinRouteId } from "../inference/https-pin-runtime"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../inference/native-nvidia"; -import { NATIVE_LOCAL_CREDENTIAL_ENV } from "../inference/native-local/agent-config"; +import { + isLocalInferenceProvider, + NATIVE_LOCAL_CREDENTIAL_ENV, +} from "../inference/native-local/agent-config"; import { normalizeNativeLocalProviderAttachment } from "../inference/selection"; import { recordedNativeProviderAttachment } from "../inference/native-provider/recorded-selection"; import { hostedNativeProvider } from "../inference/native-provider/hosted"; @@ -363,7 +366,12 @@ export async function runInferenceGet( attachment.credentialEnv !== NATIVE_LOCAL_CREDENTIAL_ENV || typeof selectedSandbox.model !== "string" || !selectedSandbox.model.trim() || - selectedSandbox.agent !== "langchain-deepagents-code" + !(selectedSandbox.agent === "langchain-deepagents-code" + ? attachment.agent === undefined + : selectedSandbox.agent === "openclaw" && + attachment.agent === "openclaw" && + isLocalInferenceProvider(selectedSandbox.provider) && + !selectedSandbox.nimContainer) ) { throw new InferenceGetError( "Invalid native local provider attachment for the recorded inference selection", diff --git a/src/lib/actions/inference-set-context-window.test.ts b/src/lib/actions/inference-set-context-window.test.ts index 56a27ed0bf4..7fa1031ceab 100644 --- a/src/lib/actions/inference-set-context-window.test.ts +++ b/src/lib/actions/inference-set-context-window.test.ts @@ -13,6 +13,11 @@ import { } from "../../../test/helpers/inference-set"; describe("runInferenceSet context window", () => { + const legacyLocalEntry: SandboxEntry = { + name: "alpha", + agent: "openclaw", + provider: "ollama-local", + }; const ollamaConfig = (): ConfigObject => ({ agents: { defaults: { model: { primary: "inference/llama3.2:3b" } } }, models: { @@ -32,7 +37,12 @@ describe("runInferenceSet context window", () => { it("writes the recomputed context window into the in-sandbox config", async () => { const config = ollamaConfig(); - const deps = createDeps({ config, session: baseSession(), contextWindow: 16384 }); + const deps = createDeps({ + config, + entry: legacyLocalEntry, + session: baseSession(), + contextWindow: 16384, + }); await runInferenceSet({ provider: "ollama-local", model: "qwen2.5:7b", noVerify: true }, deps); @@ -47,7 +57,12 @@ describe("runInferenceSet context window", () => { it("drops another model's window and warns when the selected window is unknown (#12033)", async () => { const config = ollamaConfig(); - const deps = createDeps({ config, session: baseSession(), contextWindow: null }); + const deps = createDeps({ + config, + entry: legacyLocalEntry, + session: baseSession(), + contextWindow: null, + }); await runInferenceSet({ provider: "ollama-local", model: "qwen2.5:7b", noVerify: true }, deps); diff --git a/src/lib/actions/inference-set-local-provider.test.ts b/src/lib/actions/inference-set-local-provider.test.ts index ab63c4655e4..c714b3149f9 100644 --- a/src/lib/actions/inference-set-local-provider.test.ts +++ b/src/lib/actions/inference-set-local-provider.test.ts @@ -3,9 +3,16 @@ import { describe, expect, it } from "vitest"; import type { ConfigObject } from "../security/credential-filter"; +import type { SandboxEntry } from "../state/registry"; import { runInferenceSet } from "./inference-set"; import { baseSession, createDeps } from "../../../test/helpers/inference-set"; +const legacyLocalEntry: SandboxEntry = { + name: "alpha", + agent: "openclaw", + provider: "ollama-local", +}; + describe("runInferenceSet local-provider verification", () => { const localConfig = (): ConfigObject => ({ agents: { defaults: { model: { primary: "inference/qwen2.5:7b" } } }, @@ -20,7 +27,11 @@ describe("runInferenceSet local-provider verification", () => { }); it("forces --no-verify for a local provider whose host validation passes", async () => { - const deps = createDeps({ config: localConfig(), session: baseSession() }); + const deps = createDeps({ + config: localConfig(), + entry: legacyLocalEntry, + session: baseSession(), + }); await runInferenceSet({ provider: "ollama-local", model: "qwen2.5:7b" }, deps); @@ -34,7 +45,11 @@ describe("runInferenceSet local-provider verification", () => { // The reporter's exact input `ollama_local` must reach the local-provider // path as the canonical `ollama-local`, so host validation and the OpenShell // selection both use the normalized name (not the underscore spelling). - const deps = createDeps({ config: localConfig(), session: baseSession() }); + const deps = createDeps({ + config: localConfig(), + entry: legacyLocalEntry, + session: baseSession(), + }); await runInferenceSet({ provider: "ollama_local", model: "qwen2.5:7b" }, deps); @@ -54,6 +69,7 @@ describe("runInferenceSet local-provider verification", () => { it("warns and proceeds with --no-verify when the host stack is reachable despite a failed probe", async () => { const deps = createDeps({ config: localConfig(), + entry: legacyLocalEntry, session: baseSession(), localValidation: { ok: false, @@ -75,6 +91,7 @@ describe("runInferenceSet local-provider verification", () => { it("aborts without touching the route when the host stack is unreachable", async () => { const deps = createDeps({ config: localConfig(), + entry: legacyLocalEntry, session: baseSession(), localValidation: { ok: false, diff --git a/src/lib/actions/inference-set-openclaw-native-local.test.ts b/src/lib/actions/inference-set-openclaw-native-local.test.ts new file mode 100644 index 00000000000..1dbcc9496f6 --- /dev/null +++ b/src/lib/actions/inference-set-openclaw-native-local.test.ts @@ -0,0 +1,277 @@ +// 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 { + attachment, + fixture, + switchingFixture, +} from "../../../test/helpers/inference-set-openclaw-native-local"; +import { resolveOpenClawLocalSwitch } from "./inference-set/native-local"; +import { runInferenceSet } from "./inference-set"; + +vi.mock("../adapters/openshell/provider-policy", () => ({ + requireNativeProviderPolicy: vi.fn(async () => {}), +})); + +describe("OpenClaw native local live selection", () => { + it.each([ + { provider: "vllm-local", expected: {} }, + { provider: "ollama-local", expected: { prepare: true } }, + ])( + "keeps owned NIM shared only when selecting $provider still uses NIM", + async ({ provider, expected }) => { + const deps = fixture(); + await expect( + resolveOpenClawLocalSwitch({ + agentName: "openclaw", + provider, + sandboxName: "alpha", + gatewayName: "nemoclaw", + deps, + entry: { + name: "alpha", + agent: "openclaw", + provider: "vllm-local", + nimContainer: "owned-nim", + }, + }), + ).resolves.toEqual(expected); + }, + ); + + it("detaches and retires local authority before publishing a shared selection", async () => { + const deps = fixture(); + const detach = vi.spyOn(deps.providerAdapter, "detachProvider"); + const deletion = vi.spyOn(deps.providerAdapter, "deleteProvider"); + await runInferenceSet( + { + provider: "nvidia-router", + model: "routed-model", + sandboxName: "alpha", + }, + deps, + ); + expect(detach).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + providerName: attachment.providerName, + }), + ); + expect(deletion).toHaveBeenCalled(); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + provider: "nvidia-router", + nativeLocalProviderAttachment: undefined, + }), + ); + expect(deps.calls.clearNativeLocalProviderAuthority).toHaveBeenCalledWith(attachment); + }); + + it("preserves the switch failure when restoring local access also fails", async () => { + const deps = fixture(); + deps.calls.updateSandbox.mockReturnValue(false); + vi.spyOn(deps.providerAdapter, "attachProvider").mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "failed", message: "reattach rejected" }, + }); + await expect( + runInferenceSet( + { provider: "nvidia-router", model: "routed-model", sandboxName: "alpha" }, + deps, + ), + ).rejects.toThrow(/Failed to update NemoClaw registry.*restoring.*reattach rejected/s); + expect(deps.calls.clearNativeLocalProviderAuthority).not.toHaveBeenCalled(); + }); + + it("switches from Ollama to another local provider without changing the shared route", async () => { + const { deps } = switchingFixture(); + await expect( + runInferenceSet( + { + provider: "vllm-local", + model: "new-model", + sandboxName: "alpha", + }, + deps, + ), + ).resolves.toMatchObject({ provider: "vllm-local" }); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + provider: "vllm-local", + nativeLocalProviderAttachment: expect.objectContaining({ + agent: "openclaw", + provider: "vllm-local", + sandboxName: "alpha", + gatewayName: "nemoclaw", + }), + }), + ); + expect(deps.calls.clearNativeLocalProviderAuthority).toHaveBeenCalledWith(attachment); + expect( + deps.calls.captureOpenshell.mock.calls.some( + ([args]) => Array.isArray(args) && args[0] === "inference" && args[1] === "set", + ), + ).toBe(false); + }); + + it.each([ + { + stage: "attachment", + arrange: ({ deps, next }: ReturnType) => { + const attach = deps.providerAdapter.attachProvider; + deps.providerAdapter.attachProvider = async (request) => + request.providerName === next.providerName + ? { + ok: false, + error: { kind: "command", reason: "failed", message: "attachment rejected" }, + } + : attach(request); + }, + }, + { + stage: "registry", + arrange: ({ deps }: ReturnType) => { + deps.calls.updateSandbox.mockReturnValue(false); + }, + }, + ])("restores the prior local route after $stage failure", async ({ stage, arrange }) => { + const state = switchingFixture(); + const { deps, isPresent, isAttached } = state; + arrange(state); + await expect( + runInferenceSet({ provider: "vllm-local", model: "new-model", sandboxName: "alpha" }, deps), + ).rejects.toThrow( + stage === "attachment" ? /attachment rejected/ : /Failed to update NemoClaw registry/, + ); + expect(isPresent()).toBe(false); + expect(isAttached()).toBe(false); + const current = await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + }); + expect(current).toMatchObject({ ok: true, value: { names: [attachment.providerName] } }); + expect(deps.calls.clearNativeLocalProviderAuthority).not.toHaveBeenCalledWith(attachment); + }); + + it("restores prior access even when replacement retirement fails", async () => { + const { deps, next } = switchingFixture(); + deps.calls.updateSandbox.mockReturnValue(false); + vi.spyOn(deps.providerAdapter, "deleteProvider").mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "failed", message: "retirement rejected" }, + }); + await expect( + runInferenceSet({ provider: "vllm-local", model: "new-model", sandboxName: "alpha" }, deps), + ).rejects.toThrow(/Failed to update NemoClaw registry.*removal was not confirmed/s); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + }), + ).toMatchObject({ ok: true, value: { names: [attachment.providerName] } }); + expect(deps.getNativeLocalProviderAuthority?.(next.providerName)).toEqual(next); + expect(deps.calls.clearNativeLocalProviderAuthority).not.toHaveBeenCalled(); + }); + + it("identifies both retained providers when cleanup and restoration fail", async () => { + const { deps, next } = switchingFixture(); + deps.calls.updateSandbox.mockReturnValue(false); + vi.spyOn(deps.providerAdapter, "deleteProvider").mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "failed", message: "retirement rejected" }, + }); + const attach = deps.providerAdapter.attachProvider; + vi.spyOn(deps.providerAdapter, "attachProvider").mockImplementation(async (request) => + request.providerName === attachment.providerName + ? { + ok: false, + error: { kind: "command", reason: "failed", message: "restoration rejected" }, + } + : attach(request), + ); + const result = runInferenceSet( + { provider: "vllm-local", model: "new-model", sandboxName: "alpha" }, + deps, + ); + await expect(result).rejects.toThrow(/removal was not confirmed.*restoration rejected/s); + await expect(result).rejects.toThrow(attachment.providerName); + await expect(result).rejects.toThrow(next.providerName); + expect(deps.getNativeLocalProviderAuthority?.(next.providerName)).toEqual(next); + expect(deps.calls.clearNativeLocalProviderAuthority).not.toHaveBeenCalled(); + }); + + it("changes the selected model without touching the shared gateway route", async () => { + const deps = fixture(); + const result = await runInferenceSet( + { + provider: "ollama-local", + model: "new-model", + sandboxName: "alpha", + }, + deps, + ); + expect(result.provider).toBe("ollama-local"); + expect(deps.calls.probeSandboxRoute).toHaveBeenCalledWith( + expect.objectContaining({ + nativeProvider: true, + nativeLocalProviderAttachment: attachment, + agentName: "openclaw", + model: "new-model", + }), + ); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + model: "new-model", + nativeLocalProviderAttachment: attachment, + }), + ); + expect(deps.calls.setOpenClawConfigValues).toHaveBeenCalled(); + expect(deps.calls.restartSandboxGateway).toHaveBeenCalled(); + expect( + deps.calls.captureOpenshell.mock.calls.some( + ([args]) => Array.isArray(args) && args[0] === "inference" && args[1] === "set", + ), + ).toBe(false); + }); + + it("retries exact provider retirement after a committed route switch", async () => { + const deps = fixture(); + let pending = true; + const originalDelete = deps.providerAdapter.deleteProvider.bind(deps.providerAdapter); + vi.spyOn(deps.providerAdapter, "deleteProvider").mockImplementation(async (request) => + pending + ? { ok: false, error: { kind: "command", reason: "attached", message: "attached" } } + : originalDelete(request), + ); + deps.listNativeLocalProviderAuthorities = () => [attachment]; + await expect( + runInferenceSet( + { provider: "nvidia-router", model: "routed-model", sandboxName: "alpha" }, + deps, + ), + ).rejects.toThrow(/retry inference set/); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ nativeLocalProviderAttachment: undefined }), + ); + expect(deps.calls.clearNativeLocalProviderAuthority).not.toHaveBeenCalled(); + + pending = false; + deps.getSandbox = () => ({ + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-router", + model: "routed-model", + }); + await runInferenceSet( + { provider: "nvidia-router", model: "routed-model", sandboxName: "alpha" }, + deps, + ); + expect(deps.calls.clearNativeLocalProviderAuthority).toHaveBeenCalledWith(attachment); + }); +}); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 1fb402a08e9..b36d2f62233 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -9,6 +9,37 @@ import { runInferenceSet } from "./inference-set"; import { baseSession, createDeps } from "../../../test/helpers/inference-set"; describe("runInferenceSet OpenClaw routing", () => { + it("stops a switch to local when its runtime credential is unavailable", async () => { + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "gpt-5.4", + }, + }); + deps.getNativeLocalProviderAuthority = () => undefined; + deps.setNativeLocalProviderAuthority = vi.fn(); + deps.resolveLocalSwitchRuntime = () => { + throw new Error("local runtime credential unavailable"); + }; + await expect( + runInferenceSet( + { provider: "ollama-local", model: "local-model", sandboxName: "alpha" }, + deps, + ), + ).rejects.toThrow("local runtime credential unavailable"); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); + expect( + deps.calls.captureOpenshell.mock.calls.some( + ([args]) => Array.isArray(args) && args[0] === "inference" && args[1] === "set", + ), + ).toBe(false); + }); + it("requires recreation instead of silently migrating a legacy NVIDIA sandbox", async () => { const deps = createDeps({ config: {}, diff --git a/src/lib/actions/inference-set-patch-openclaw.test.ts b/src/lib/actions/inference-set-patch-openclaw.test.ts index fa0f6dd1495..cdf42cd06cd 100644 --- a/src/lib/actions/inference-set-patch-openclaw.test.ts +++ b/src/lib/actions/inference-set-patch-openclaw.test.ts @@ -13,6 +13,56 @@ function providerModels(config: ConfigObject, providerKey: string): ConfigObject } describe("patchOpenClawInferenceConfig", () => { + it("uses a local provider handle and clears it on departure", () => { + const config: ConfigObject = { + models: { providers: { inference: { apiKey: "unused", models: [] } } }, + }; + patchOpenClawInferenceConfig( + config, + "ollama-local", + "local-model", + "openai-completions", + undefined, + undefined, + undefined, + true, + "http://host.openshell.internal:11435/v1", + true, + ); + expect(config).toMatchObject({ + models: { + providers: { + inference: { + baseUrl: "http://host.openshell.internal:11435/v1", + apiKey: "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + }, + }, + }, + }); + patchOpenClawInferenceConfig( + config, + "nvidia-nim", + "nim-model", + "openai-completions", + undefined, + undefined, + undefined, + true, + undefined, + false, + ); + expect(config).toMatchObject({ + models: { + providers: { + inference: { + baseUrl: "https://inference.local/v1", + apiKey: "unused", + }, + }, + }, + }); + }); + it("replaces the vLLM credential when switching to native NVIDIA inference", () => { const config: ConfigObject = { models: { providers: { inference: { apiKey: "unused", models: [] } } }, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index dfad3661534..75a0989139b 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -23,7 +23,6 @@ import { ensureHttpsPinRuntimeAdapter, revokeHttpsPinRuntimeAdapterRoute, } from "../inference/https-pin-runtime-adapter"; -import { type ValidationResult, validateLocalProvider } from "../inference/local"; import { inferenceSelectionRegistryFields, type ReasoningEffortRequest, @@ -63,11 +62,28 @@ import { prepareNativeTransitionAuthority, prepareNativeSelection, isNativeInferenceSelection, + isLocalInferenceProvider, usesNativeConfigByDefault, rollbackNativeSelection, detachPreviousNativeBeforePublish, restorePreviousNativeAfterFailedPublish, nativeSelectionRegistryFields, + clearNativeLocalProviderAuthority, + listNativeLocalProviderAuthorities, + resolveOpenClawLocalSwitch, + resolveLocalSwitchRuntime, + prepareOpenClawLocalSwitch, + rollbackOpenClawLocalSwitch, + getNativeLocalProviderAuthority, + setNativeLocalProviderAuthority, + validateLocalProvider, + type ValidationResult, + detachPreviousOpenClawLocal, + restorePreviousOpenClawLocal, + retirePreviousOpenClawLocal, + reconcilePreviousOpenClawLocal, + openClawLocalProbeFields, + openClawLocalRegistryFields, } from "./inference-set/native"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; import { InferenceSetError, inferenceProbeRecoveryMessage } from "./inference-set-error"; @@ -184,6 +200,9 @@ function providerCommitFailureAfterSelection(options: { } export interface InferenceSetDeps extends InferenceGatewayRestartDeps { + resolveLocalSwitchRuntime?: typeof resolveLocalSwitchRuntime; + getNativeLocalProviderAuthority?: typeof getNativeLocalProviderAuthority; + setNativeLocalProviderAuthority?: typeof setNativeLocalProviderAuthority; getDefaultSandbox: () => string | null; getSandbox: (name: string) => SandboxEntry | null; listSandboxes: () => { @@ -194,6 +213,8 @@ export interface InferenceSetDeps extends InferenceGatewayRestartDeps { setNativeHostedProviderAuthority?: typeof registry.setNativeHostedProviderAuthority; getNativeNvidiaProviderAuthority?: typeof registry.getNativeNvidiaProviderAuthority; setNativeNvidiaProviderAuthority: typeof registry.setNativeNvidiaProviderAuthority; + clearNativeLocalProviderAuthority: typeof clearNativeLocalProviderAuthority; + listNativeLocalProviderAuthorities?: typeof listNativeLocalProviderAuthorities; updateSandbox: (name: string, updates: Partial) => boolean; getRequestedAgent: () => string | null | undefined; loadSession: () => onboardSession.Session | null; @@ -324,6 +345,9 @@ export const INFERENCE_SET_INSTALLER_PROVIDER_ALIASES = INSTALLER_PROVIDER_ALIAS function defaultDeps(): InferenceSetDeps { return { + resolveLocalSwitchRuntime, + getNativeLocalProviderAuthority, + setNativeLocalProviderAuthority, getDefaultSandbox: registry.getDefault, getSandbox: registry.getSandbox, listSandboxes: registry.listSandboxes, @@ -331,6 +355,8 @@ function defaultDeps(): InferenceSetDeps { setNativeHostedProviderAuthority: registry.setNativeHostedProviderAuthority, getNativeNvidiaProviderAuthority: registry.getNativeNvidiaProviderAuthority, setNativeNvidiaProviderAuthority: registry.setNativeNvidiaProviderAuthority, + clearNativeLocalProviderAuthority, + listNativeLocalProviderAuthorities, updateSandbox: registry.updateSandbox, getRequestedAgent: () => process.env.NEMOCLAW_AGENT, loadSession: onboardSession.loadSession, @@ -348,8 +374,7 @@ function defaultDeps(): InferenceSetDeps { providerAdapter: createDefaultInferenceSetProviderAdapter(), appendAuditEntry, log: console.log, - isLocalInferenceProvider: (provider) => - provider === "ollama-local" || provider === "vllm-local", + isLocalInferenceProvider, validateLocalProvider, ensureLocalProviderReachable, resolveContextWindowForModel, @@ -743,6 +768,7 @@ export function patchOpenClawInferenceConfig( preferredInferenceApi, nativeProvider, nativeEndpointUrl, + "openclaw", ); const inheritedMaxTokens = inheritPrimaryReplyBudget ? readOpenClawPrimaryReplyBudget(config) @@ -1263,13 +1289,17 @@ 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 selectingNative = isNativeInferenceSelection( - provider, + const localSwitch = await resolveOpenClawLocalSwitch({ + agentName, entry, - options.endpointUrl, - expectedGatewayName, + provider, + sandboxName, + gatewayName: expectedGatewayName, deps, - ); + }); + const selectingNative = + Boolean(localSwitch.selected || localSwitch.prepare) || + isNativeInferenceSelection(provider, entry, options.endpointUrl, expectedGatewayName, deps); const routeSandboxes = deps.listSandboxes().sandboxes; const preparedRoute = prepareInferenceSetRoute({ entry: routeEntry, @@ -1490,6 +1520,9 @@ async function runInferenceSetWithoutHostLock( let nativeRegistryCommitted = false; let previousNativeDetached = false; let previousNativeDetachCommitted = false; + let previousLocalDetached = false; + let previousLocalDetachCommitted = false; + let localRegistryCommitted = false; const restorePreviousInferenceSelection = async (): Promise => { if (selectingNative) { appliedInferenceSelection = false; @@ -1521,6 +1554,21 @@ async function runInferenceSetWithoutHostLock( return null; }; try { + await prepareOpenClawLocalSwitch({ + selection: localSwitch, + provider, + sandboxName, + gatewayName: preparedRoute.gatewayName, + deps, + beforeAttach: async () => { + previousLocalDetached ||= await detachPreviousOpenClawLocal({ + previous: localSwitch.previous, + selected: localSwitch.selected, + sandboxName, + deps, + }); + }, + }); const nativeSelection = await prepareNativeSelection({ selectingNative, provider, @@ -1650,7 +1698,7 @@ async function runInferenceSetWithoutHostLock( model, preferredInferenceApi: preMutationInferenceApi, ...(selectingNative ? { nativeProvider: true } : {}), - nativeEndpointUrl: nativeSelection.endpointUrl, + ...openClawLocalProbeFields(nativeSelection.endpointUrl, localSwitch.selected), }, previousProvider, previousModel, @@ -1709,6 +1757,12 @@ async function runInferenceSetWithoutHostLock( // Removing previous native access is a security gate for publishing another // route. Do not commit the non-native registry/config while the sandbox can // still use the credential-bearing attached provider. + previousLocalDetached ||= await detachPreviousOpenClawLocal({ + previous: localSwitch.previous, + selected: localSwitch.selected, + sandboxName, + deps, + }); previousNativeDetached ||= await detachPreviousNativeBeforePublish({ selectingNative, selectedProvider: provider, @@ -1745,8 +1799,10 @@ async function runInferenceSetWithoutHostLock( }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), ...nativeSelectionRegistryFields(nativeProviderAttachment, previousNativeDetached), - ...(nativeSelection.endpointUrl && !nativeProviderAttachment?.custom - ? { endpointUrl: nativeSelection.endpointUrl } + ...openClawLocalRegistryFields(localSwitch.selected, previousLocalDetached), + ...(!nativeProviderAttachment?.custom && + (nativeSelection.endpointUrl ?? localSwitch.selected?.endpointUrl) + ? { endpointUrl: nativeSelection.endpointUrl ?? localSwitch.selected?.endpointUrl } : {}), }); if ( @@ -1766,7 +1822,9 @@ async function runInferenceSetWithoutHostLock( ); } nativeRegistryCommitted = Boolean(nativeProviderAttachment); + localRegistryCommitted = Boolean(localSwitch.selected); previousNativeDetachCommitted = previousNativeDetached; + previousLocalDetachCommitted = previousLocalDetached; const preferredInferenceApi = explicitPreferredInferenceApi ?? @@ -1824,7 +1882,7 @@ async function runInferenceSetWithoutHostLock( model, preferredInferenceApi, contextWindow, - nativeSelection.endpointUrl, + nativeSelection.endpointUrl ?? localSwitch.selected?.endpointUrl, selectingNative, nativeNvidiaCredentialHandle, ); @@ -1849,7 +1907,7 @@ async function runInferenceSetWithoutHostLock( provider, reasoningEffortRequest, true, - nativeSelection.endpointUrl, + nativeSelection.endpointUrl ?? localSwitch.selected?.endpointUrl, selectingNative, ); } @@ -1952,6 +2010,13 @@ async function runInferenceSetWithoutHostLock( `Hermes configuration did not fully converge. Run '${CLI_NAME} ${sandboxName} rebuild' to converge it.`, ); } + await retirePreviousOpenClawLocal({ + previous: localSwitch.previous, + detached: previousLocalDetached, + sandboxName, + gatewayName: preparedRoute.gatewayName, + deps, + }); recordInferenceSetChange( sandboxName, [ @@ -1991,20 +2056,36 @@ async function runInferenceSetWithoutHostLock( error, deps, }); + const localRollbackFailure = await rollbackOpenClawLocalSwitch({ + selection: localSwitch, + committed: localRegistryCommitted, + sandboxName, + gatewayName: preparedRoute.gatewayName, + deps, + error, + }); + const failure = await restorePreviousOpenClawLocal({ + previous: localSwitch.previous, + detached: previousLocalDetached, + committed: previousLocalDetachCommitted, + sandboxName, + error: localRollbackFailure, + deps, + }); await restorePreviousNativeAfterFailedPublish({ detached: previousNativeDetached, committed: previousNativeDetachCommitted, previousAttachment: previousNativeAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, - error, + error: failure, deps, }); - if (!providerMutation) throw error; - if (ambiguousInferenceSelection) throw error; - if (restoredSelectionAfterProviderFailure) throw error; - const detail = error instanceof Error ? error.message : String(error); - const exitCode = error instanceof InferenceSetError ? error.exitCode : 1; + if (!providerMutation) throw failure; + if (ambiguousInferenceSelection) throw failure; + if (restoredSelectionAfterProviderFailure) throw failure; + const detail = failure instanceof Error ? failure.message : String(failure); + const exitCode = failure instanceof InferenceSetError ? failure.exitCode : 1; if (!appliedInferenceSelection) { if (providerMutation.action === "create") { try { @@ -2081,14 +2162,20 @@ export async function runInferenceSet( deps.runtimeProviders, ); const gatewayName = resolveSandboxGatewayName(lockedSelection.entry); - const mutation = await deps.withGatewayRouteMutationLock(gatewayName, () => - runInferenceSetWithoutHostLock( + const mutation = await deps.withGatewayRouteMutationLock(gatewayName, async () => { + await reconcilePreviousOpenClawLocal({ + entry: lockedSelection.entry, + sandboxName: selected.sandboxName, + gatewayName, + deps, + }); + return await runInferenceSetWithoutHostLock( { ...options, sandboxName: selected.sandboxName }, deps, gatewayName, runtimeProvider, - ), - ); + ); + }); // Retain the outer sandbox lifecycle lock so another process cannot replace // this sandbox between the committed write, an optional restart, and // device-scope convergence. diff --git a/src/lib/actions/inference-set/local-runtime.test.ts b/src/lib/actions/inference-set/local-runtime.test.ts new file mode 100644 index 00000000000..556f8bdfee0 --- /dev/null +++ b/src/lib/actions/inference-set/local-runtime.test.ts @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, expect, it, vi } from "vitest"; +import { resolveLocalSwitchRuntime } from "./local-runtime"; + +const mocks = vi.hoisted(() => ({ + managed: vi.fn(), + proxy: vi.fn(), + front: vi.fn(), + credential: vi.fn(), + endpoint: vi.fn(), +})); +vi.mock("../../inference/local", () => ({ + getLocalProviderBaseUrl: mocks.endpoint, + getManagedVllmProviderBinding: mocks.managed, + shouldFrontOllamaWithProxy: mocks.front, +})); +vi.mock("../../inference/ollama/proxy", () => ({ getOllamaProxyToken: mocks.proxy })); + +beforeEach(() => { + vi.resetAllMocks(); + mocks.endpoint.mockReturnValue("http://host.openshell.internal:8000/v1"); +}); + +it("keeps managed vLLM's endpoint and credential together", () => { + mocks.managed.mockReturnValue({ baseUrl: "http://10.1.2.3:8123/v1", apiKey: "managed-test-key" }); + expect(resolveLocalSwitchRuntime("vllm-local", mocks.credential)).toMatchObject({ + endpointUrl: "http://10.1.2.3:8123/v1", + credentialValue: "managed-test-key", + authMode: "authenticated", + }); + expect(mocks.credential).not.toHaveBeenCalled(); +}); + +it("does not fall back to a sentinel after managed vLLM credential failure", () => { + mocks.managed.mockImplementation(() => { + throw new Error("unsafe authentication"); + }); + expect(() => resolveLocalSwitchRuntime("vllm-local", mocks.credential)).toThrow( + "unsafe authentication", + ); + expect(mocks.endpoint).not.toHaveBeenCalled(); +}); + +it("uses the existing standalone vLLM sentinel without host cloud credentials", () => { + expect(resolveLocalSwitchRuntime("vllm-local", mocks.credential)).toMatchObject({ + credentialValue: "dummy", + authMode: "sentinel", + }); + expect(mocks.credential).not.toHaveBeenCalled(); +}); + +it("requires the existing Ollama proxy key when the proxy owns its route", () => { + mocks.front.mockReturnValue(true); + expect(() => resolveLocalSwitchRuntime("ollama-local", mocks.credential)).toThrow( + "proxy credential is unavailable", + ); + mocks.proxy.mockReturnValue("proxy-test-key"); + expect(resolveLocalSwitchRuntime("ollama-local", mocks.credential)).toMatchObject({ + credentialValue: "proxy-test-key", + authMode: "authenticated", + ownedProxy: true, + }); +}); + +it("uses only the named llama.cpp credential", () => { + expect(() => resolveLocalSwitchRuntime("llama-cpp-local", mocks.credential)).toThrow( + "llama.cpp credential is unavailable", + ); + mocks.credential.mockReturnValue("llama-test-key"); + expect(resolveLocalSwitchRuntime("llama-cpp-local", mocks.credential)).toMatchObject({ + endpointUrl: "http://host.openshell.internal:8081/v1", + credentialValue: "llama-test-key", + authMode: "authenticated", + }); + expect(mocks.credential).toHaveBeenLastCalledWith("NEMOCLAW_LLAMACPP_LOCAL_TOKEN"); +}); diff --git a/src/lib/actions/inference-set/local-runtime.ts b/src/lib/actions/inference-set/local-runtime.ts new file mode 100644 index 00000000000..bbb25dfca34 --- /dev/null +++ b/src/lib/actions/inference-set/local-runtime.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + getLocalProviderBaseUrl, + getManagedVllmProviderBinding, + shouldFrontOllamaWithProxy, +} from "../../inference/local"; +import { getOllamaProxyToken } from "../../inference/ollama/proxy"; +import { + LLAMA_CPP_CREDENTIAL_ENV, + LLAMA_CPP_GATEWAY_BASE_URL, +} from "../../inference/llama-cpp/contract"; +import { InferenceSetError } from "../inference-set-error"; + +export { validateLocalProvider, type ValidationResult } from "../../inference/local"; + +/** Read the endpoint and credential from the same runtime owners used by onboarding. */ +export function resolveLocalSwitchRuntime( + provider: string, + resolveCredential: (name: string) => string | null, +) { + if (provider === "vllm-local") { + const managed = getManagedVllmProviderBinding(); + return { + endpointUrl: managed?.baseUrl ?? getLocalProviderBaseUrl(provider), + credentialValue: managed?.apiKey ?? "dummy", + authMode: managed ? ("authenticated" as const) : ("sentinel" as const), + ownedProxy: false, + }; + } + if (provider === "ollama-local") { + const ownedProxy = shouldFrontOllamaWithProxy(); + const credentialValue = ownedProxy ? getOllamaProxyToken() : "ollama"; + if (!credentialValue) + throw new InferenceSetError( + "The existing Ollama proxy credential is unavailable. Restore its runtime before switching.", + ); + return { + endpointUrl: getLocalProviderBaseUrl(provider), + credentialValue, + authMode: ownedProxy ? ("authenticated" as const) : ("sentinel" as const), + ownedProxy, + }; + } + if (provider === "llama-cpp-local") { + const credentialValue = resolveCredential(LLAMA_CPP_CREDENTIAL_ENV); + if (!credentialValue) + throw new InferenceSetError( + "The existing llama.cpp credential is unavailable. Restore its runtime credential before switching.", + ); + return { + endpointUrl: LLAMA_CPP_GATEWAY_BASE_URL, + credentialValue, + authMode: "authenticated" as const, + ownedProxy: false, + }; + } + throw new InferenceSetError("Unsupported local provider selection."); +} diff --git a/src/lib/actions/inference-set/native-local.ts b/src/lib/actions/inference-set/native-local.ts new file mode 100644 index 00000000000..73d54edd782 --- /dev/null +++ b/src/lib/actions/inference-set/native-local.ts @@ -0,0 +1,255 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { InferenceSetDeps } from "../inference-set"; +import { InferenceSetError } from "../inference-set-error"; +import { isLocalInferenceProvider } from "../../inference/native-local/agent-config"; +import { + detachNativeLocalProvider, + ensureNativeLocalProviderAttached, + normalizeNativeLocalProviderAttachment, + retireNativeLocalProvider, + type NativeLocalProviderAttachment, + verifyNativeLocalProviderAttachment, +} from "../../inference/native-local/profile"; +import { prepareNativeLocalSelection } from "../../inference/native-local/selection"; +import type { SandboxEntry } from "../../state/registry"; + +export type OpenClawLocalSwitch = { + selected?: NativeLocalProviderAttachment; + previous?: NativeLocalProviderAttachment; + prepare?: boolean; +}; + +/** Reuse a matching attachment or prepare a new sandbox-owned local selection. */ +export async function resolveOpenClawLocalSwitch(input: { + agentName: string; + entry: SandboxEntry; + provider: string; + sandboxName: string; + gatewayName: string; + deps: InferenceSetDeps; +}): Promise { + if (input.agentName !== "openclaw") return {}; + const { entry, provider, sandboxName, gatewayName, deps } = input; + const previous = normalizeNativeLocalProviderAttachment(entry.nativeLocalProviderAttachment); + if (entry.nativeLocalProviderAttachment !== undefined && !previous) { + throw new InferenceSetError( + "Recorded native local provider ownership is invalid. Retain this sandbox for repair.", + 2, + ); + } + if (previous) { + if ( + previous.agent !== "openclaw" || + previous.sandboxName !== sandboxName || + previous.gatewayName !== gatewayName || + previous.provider !== entry.provider + ) { + throw new InferenceSetError( + "Recorded native local provider ownership does not match this sandbox. Retain it for repair.", + 2, + ); + } + await verifyNativeLocalProviderAttachment({ + adapter: deps.providerAdapter, + sandboxName, + expected: previous, + }); + } + if (!isLocalInferenceProvider(provider) || (provider === "vllm-local" && entry.nimContainer)) + return { previous }; + // A retained OpenClaw row may still own the historical shared route. + if (!previous && entry.provider === provider) return {}; + if (!previous || entry.provider !== provider) return { previous, prepare: true }; + return { selected: previous, previous }; +} + +export async function prepareOpenClawLocalSwitch(input: { + selection: OpenClawLocalSwitch; + provider: string; + sandboxName: string; + gatewayName: string; + deps: InferenceSetDeps; + beforeAttach: () => Promise; +}) { + if (!input.selection.prepare) return; + const { deps } = input; + if ( + !deps.resolveLocalSwitchRuntime || + !deps.getNativeLocalProviderAuthority || + !deps.setNativeLocalProviderAuthority + ) + throw new InferenceSetError("Native local provider ownership storage is unavailable."); + const runtime = deps.resolveLocalSwitchRuntime(input.provider, deps.resolveCredentialValue); + if (!runtime.endpointUrl) + throw new InferenceSetError("The local runtime endpoint is unavailable."); + input.selection.selected = await prepareNativeLocalSelection({ + adapter: deps.providerAdapter, + binding: { + agent: "openclaw", + provider: input.provider as NativeLocalProviderAttachment["provider"], + endpointUrl: runtime.endpointUrl, + authMode: runtime.authMode, + gatewayName: input.gatewayName, + sandboxName: input.sandboxName, + }, + credentialValue: runtime.credentialValue, + ownedProxy: runtime.ownedProxy, + readAuthority: deps.getNativeLocalProviderAuthority, + writeAuthority: deps.setNativeLocalProviderAuthority, + }); + // Local providers use the same injected credential name. Prepare first, then + // remove old access before attaching the new provider to avoid a collision. + await input.beforeAttach(); + await ensureNativeLocalProviderAttached({ + adapter: deps.providerAdapter, + sandboxName: input.sandboxName, + expected: input.selection.selected, + }); +} + +export async function rollbackOpenClawLocalSwitch(input: { + selection: OpenClawLocalSwitch; + committed: boolean; + sandboxName: string; + gatewayName: string; + deps: InferenceSetDeps; + error: unknown; +}): Promise { + if (!input.selection.prepare || input.committed || !input.selection.selected) return input.error; + try { + await detachNativeLocalProvider({ + adapter: input.deps.providerAdapter, + sandboxName: input.sandboxName, + expected: input.selection.selected, + }); + const result = await retireNativeLocalProvider({ + adapter: input.deps.providerAdapter, + expected: input.selection.selected, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + clearAuthority: input.deps.clearNativeLocalProviderAuthority, + }); + if (result.status === "attached") + throw new Error( + "The failed local selection remains attached; retain its authority for repair.", + ); + } catch (cleanupError) { + return new InferenceSetError( + `${input.error instanceof Error ? input.error.message : String(input.error)}\nLocal selection rollback failed for provider '${input.selection.selected.providerName}' (retained authority): ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`, + ); + } + return input.error; +} + +export function openClawLocalProbeFields( + nativeEndpointUrl?: string, + selected?: NativeLocalProviderAttachment, +) { + const endpointUrl = nativeEndpointUrl ?? selected?.endpointUrl; + return { + ...(endpointUrl ? { nativeEndpointUrl: endpointUrl } : {}), + ...(selected ? { nativeLocalProviderAttachment: selected, agentName: "openclaw" } : {}), + }; +} + +export function openClawLocalRegistryFields( + selected?: NativeLocalProviderAttachment, + previousDetached = false, +) { + if (selected) return { nativeLocalProviderAttachment: selected }; + return previousDetached ? { nativeLocalProviderAttachment: undefined } : {}; +} + +export async function detachPreviousOpenClawLocal(input: { + previous?: NativeLocalProviderAttachment; + selected?: NativeLocalProviderAttachment; + sandboxName: string; + deps: InferenceSetDeps; +}): Promise { + if (!input.previous || input.previous.providerName === input.selected?.providerName) return false; + await detachNativeLocalProvider({ + adapter: input.deps.providerAdapter, + sandboxName: input.sandboxName, + expected: input.previous, + }); + return true; +} + +export async function restorePreviousOpenClawLocal(input: { + previous?: NativeLocalProviderAttachment; + detached: boolean; + committed: boolean; + sandboxName: string; + error: unknown; + deps: InferenceSetDeps; +}): Promise { + if (!input.detached || input.committed || !input.previous) return input.error; + try { + await ensureNativeLocalProviderAttached({ + adapter: input.deps.providerAdapter, + sandboxName: input.sandboxName, + expected: input.previous, + }); + } catch (reattachError) { + const detail = input.error instanceof Error ? input.error.message : String(input.error); + const recoveryDetail = + reattachError instanceof Error ? reattachError.message : String(reattachError); + return new InferenceSetError( + `${detail}\n Native local provider access was detached before the failed switch, but restoring provider '${input.previous.providerName}' failed: ${recoveryDetail}. Retain this sandbox and its provider authority for repair.`, + input.error instanceof InferenceSetError ? input.error.exitCode : 1, + ); + } + return input.error; +} + +export async function retirePreviousOpenClawLocal(input: { + previous?: NativeLocalProviderAttachment; + detached: boolean; + sandboxName: string; + gatewayName: string; + deps: InferenceSetDeps; +}): Promise { + if (!input.detached || !input.previous) return; + const result = await retireNativeLocalProvider({ + adapter: input.deps.providerAdapter, + expected: input.previous, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + clearAuthority: input.deps.clearNativeLocalProviderAuthority, + }); + if (result.status === "attached") { + throw new InferenceSetError( + `OpenClaw sandbox '${input.sandboxName}' switched routes, but provider '${input.previous.providerName}' remains attached. Its exact cleanup authority was retained. Inspect its OpenShell attachments, then retry inference set for this sandbox to finish cleanup.`, + ); + } +} + +/** The gateway authority map preserves the exact detached provider after registry commit. */ +export async function reconcilePreviousOpenClawLocal(input: { + entry: SandboxEntry; + sandboxName: string; + gatewayName: string; + deps: InferenceSetDeps; +}): Promise { + if (input.entry.agent !== "openclaw") return; + const current = normalizeNativeLocalProviderAttachment(input.entry.nativeLocalProviderAttachment); + const candidates = + input.deps.listNativeLocalProviderAuthorities?.(input.sandboxName, input.gatewayName) ?? []; + for (const previous of candidates) { + if (current?.providerName === previous.providerName) continue; + const result = await retireNativeLocalProvider({ + adapter: input.deps.providerAdapter, + expected: previous, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + clearAuthority: input.deps.clearNativeLocalProviderAuthority, + }); + if (result.status === "attached") { + throw new InferenceSetError( + `OpenClaw sandbox '${input.sandboxName}' still has a pending provider cleanup for '${previous.providerName}'. Inspect its OpenShell attachments, then retry inference set for this sandbox. No new route was selected.`, + ); + } + } +} diff --git a/src/lib/actions/inference-set/native.ts b/src/lib/actions/inference-set/native.ts index 0ae5726bf76..e8bf737bcf1 100644 --- a/src/lib/actions/inference-set/native.ts +++ b/src/lib/actions/inference-set/native.ts @@ -5,6 +5,33 @@ import { managedInferenceApiKey, NVIDIA_INFERENCE_PLACEHOLDER } from "../../infe import type { InferenceSetDeps } from "../inference-set"; import type { ConfigObject } from "../../security/credential-filter"; import { nativeHostedAgentConfig } from "../../inference/native-provider/agent-config"; +import { + isLocalInferenceProvider, + nativeLocalCredentialReference, +} from "../../inference/native-local/agent-config"; +export { isLocalInferenceProvider }; +export { + resolveOpenClawLocalSwitch, + prepareOpenClawLocalSwitch, + rollbackOpenClawLocalSwitch, + detachPreviousOpenClawLocal, + restorePreviousOpenClawLocal, + retirePreviousOpenClawLocal, + openClawLocalProbeFields, + openClawLocalRegistryFields, +} from "./native-local"; +export { + getNativeLocalProviderAuthority, + setNativeLocalProviderAuthority, + clearNativeLocalProviderAuthority, + listNativeLocalProviderAuthorities, +} from "../../state/registry/native-local-provider-authority"; +export { reconcilePreviousOpenClawLocal } from "./native-local"; +export { + resolveLocalSwitchRuntime, + validateLocalProvider, + type ValidationResult, +} from "./local-runtime"; import { isSafeModelId } from "../../validation"; import { InferenceSetError } from "../inference-set-error"; import type { NativeProviderAttachment } from "../../inference/native-provider/contract"; @@ -352,11 +379,17 @@ export function nativeSelectionConfigCredentials( return { apiKey: native?.apiKey ?? + (isLocalInferenceProvider(provider) + ? nativeLocalCredentialReference(provider, baseUrl) + : null) ?? managedInferenceApiKey( baseUrl, typeof existingApiKey === "string" && existingApiKey && - existingApiKey !== NVIDIA_INFERENCE_PLACEHOLDER + existingApiKey !== NVIDIA_INFERENCE_PLACEHOLDER && + !/^openshell:resolve:env:(?:(?:v[0-9]{1,20}|s[a-f0-9]{64})_)?NEMOCLAW_LOCAL_INFERENCE_TOKEN$/u.test( + existingApiKey, + ) ? existingApiKey : "unused", ), 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 17f400318af..25569c750cf 100644 --- a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts @@ -2,9 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; import { makeMessagingPlan } from "../../../../test/helpers/messaging-plan-fixtures"; import { expectNoSandboxDelete } from "../../../../test/helpers/rebuild-delete-assertions"; -import { rebuildBackupPhase } from "../../../../test/helpers/rebuild-flow-harness"; +import { + rebuildBackupPhase, + nativeLocalProfile, +} from "../../../../test/helpers/rebuild-flow-harness"; import { createRebuildFlowHarness, installRebuildFlowTestHooks, @@ -83,6 +87,37 @@ function createNativeProviderRebuildHarness(replaced: boolean, provider = "nvidi return { harness, reads, providerName }; } +function createNativeLocalRebuildHarness(beforeBackup: () => void = () => {}) { + const binding = { + agent: "openclaw" as const, + provider: "llama-cpp-local" as const, + endpointUrl: "http://host.openshell.internal:8081/v1", + credentialEnv: "LLAMA_CPP_API_KEY", + authMode: "authenticated" as const, + sandboxName: "alpha", + gatewayName: "nemoclaw", + }; + const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned", + }; + const harness = createRebuildFlowHarness({ + sandboxEntry: { ...binding, model: MODEL, nativeLocalProviderAttachment: attachment }, + hydrateCredentialEnv: () => null, + beforeBackup, + runOpenshell: providerRuntime([]), + }); + configureSession(harness, binding.provider, binding.credentialEnv, { + endpointUrl: binding.endpointUrl, + }); + const verify = vi + .spyOn(nativeLocalProfile, "verifyRecordedNativeLocalProviderAttachment") + .mockResolvedValue(attachment); + return { harness, attachment, verify }; +} + function diagnostics(harness: Harness): string { return harness.errorSpy.mock.calls.flat().map(String).join("\n"); } @@ -211,6 +246,44 @@ describe("rebuildSandbox flow: credential preflight", () => { }, ); + it("rebuilds native OpenClaw without a shared provider after checking authority", async () => { + const { harness, attachment, verify } = createNativeLocalRebuildHarness(); + await expect( + harness.rebuildSandbox("alpha", ["--yes", "--verbose"], { + throwOnError: true, + }), + ).resolves.toBeUndefined(); + expect(harness.onboardSpy).toHaveBeenCalledOnce(); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + expect(verify).toHaveBeenLastCalledWith( + expect.objectContaining({ + expected: attachment, + sandboxName: "alpha", + gatewayName: "nemoclaw", + agent: "openclaw", + provider: "llama-cpp-local", + }), + ); + }); + + it("stops before deletion when native OpenClaw authority is detached during backup", async () => { + const { harness } = createNativeLocalRebuildHarness(() => { + vi.mocked(nativeLocalProfile.verifyRecordedNativeLocalProviderAttachment).mockRejectedValue( + new Error("detached during backup"), + ); + }); + await expect( + harness.rebuildSandbox("alpha", ["--yes", "--verbose"], { + throwOnError: true, + }), + ).rejects.toThrow( + "Native local provider attachment could not be verified before sandbox deletion", + ); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + expectNoSandboxDelete(harness.runOpenshellSpy); + expect(harness.onboardSpy).not.toHaveBeenCalled(); + }); + it("aborts before backup when the target provider and credential are missing", async () => { const harness = createRebuildFlowHarness({ sandboxEntry: { @@ -651,7 +724,7 @@ describe("rebuildSandbox flow: credential preflight", () => { expect(harness.onboardSpy).not.toHaveBeenCalled(); }); - it("skips credential hydration for local inference", async () => { + it("blocks legacy local inference before credential hydration", async () => { const harness = createRebuildFlowHarness({ sandboxEntry: { provider: "ollama-local", model: MODEL, credentialEnv: null }, hydrateCredentialEnv: () => { @@ -662,14 +735,14 @@ describe("rebuildSandbox flow: credential preflight", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); + ).rejects.toThrow("Legacy shared local inference cannot be rebuilt safely"); expect(harness.hydrateCredentialEnvSpy).not.toHaveBeenCalled(); - expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); }); it.each(["ollama-local", "vllm-local"])( - "migrates a legacy %s target away from OPENAI_API_KEY (#2519)", + "blocks a legacy %s target before backup (#2519)", async (provider) => { const harness = createRebuildFlowHarness({ sandboxEntry: { provider, model: MODEL, credentialEnv: "OPENAI_API_KEY" }, @@ -678,13 +751,10 @@ describe("rebuildSandbox flow: credential preflight", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); + ).rejects.toThrow("Legacy shared local inference cannot be rebuilt safely"); - const output = harness.logSpy.mock.calls.flat().map(String).join("\n"); - expect(output).toContain("GH #2519"); - expect(output).toContain(provider); - expect(harness.session.credentialEnv).toBeNull(); - expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + expect(harness.session.credentialEnv).toBe("OPENAI_API_KEY"); + expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); }, ); diff --git a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts index 298aa0f5116..e20c2d7af8c 100644 --- a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts @@ -405,7 +405,7 @@ describe("rebuildSandbox flow: lifecycle", () => { expect(harness.registryUpdateSpy).toHaveBeenCalledWith( "alpha", expect.objectContaining({ - provider: "ollama-local", + provider: "build", model: "nvidia/nemotron", webSearchEnabled: false, fromDockerfile: null, diff --git a/src/lib/actions/sandbox/rebuild-flow-target-session.test.ts b/src/lib/actions/sandbox/rebuild-flow-target-session.test.ts index 6eb6175e9df..6bfe8265be9 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-session.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-session.test.ts @@ -40,7 +40,7 @@ describe("rebuildSandbox flow: target session", () => { const harness = createRebuildFlowHarness({ sessionSandboxName, sandboxEntry: { - provider: "vllm-local", + provider: "build", model: "example/model", servingProfileProvenance: savedProfileProvenance, }, @@ -48,7 +48,7 @@ describe("rebuildSandbox flow: target session", () => { recreatedProvenance = session.servingProfileProvenance; }, }); - harness.session.provider = "vllm-local"; + harness.session.provider = "build"; harness.session.model = "example/model"; // Stale session metadata must not replace the sandbox's saved metadata. harness.session.servingProfileProvenance = { @@ -69,7 +69,7 @@ describe("rebuildSandbox flow: target session", () => { const harness = createRebuildFlowHarness({ sessionSandboxName, sandboxEntry: { - provider: "vllm-local", + provider: "build", model: "example/model", servingProfileProvenance: undefined, }, @@ -77,7 +77,7 @@ describe("rebuildSandbox flow: target session", () => { recreatedProvenance = session.servingProfileProvenance; }, }); - harness.session.provider = "vllm-local"; + harness.session.provider = "build"; harness.session.model = "example/model"; harness.session.servingProfileProvenance = savedProfileProvenance; @@ -140,11 +140,9 @@ describe("rebuildSandbox flow: target session", () => { } }); - it("carries only qualified N1x managed-vLLM replacement intent into recreate (#10955)", async () => { + it("stops an unattached N1x managed-vLLM rebuild before deleting the sandbox (#10955)", async () => { const restoreEnv = snapshotEnv(["NEMOCLAW_PROVIDER"]); process.env.NEMOCLAW_PROVIDER = "install-vllm"; - let seen: { provider: string | undefined; replacement: boolean } | null = null; - try { const harness = createRebuildFlowHarness({ applyPreset: () => true, @@ -157,12 +155,6 @@ describe("rebuildSandbox flow: target session", () => { hostLocalInferenceReceipt: null, nimContainer: null, }, - onboard: (_session, options) => { - seen = { - provider: process.env.NEMOCLAW_PROVIDER, - replacement: options.reinstallDeferredN1xManagedVllm === true, - }; - }, }); harness.session.provider = "vllm-local"; harness.session.model = "nvidia/Qwen3.6-35B-A3B-NVFP4"; @@ -172,9 +164,9 @@ describe("rebuildSandbox flow: target session", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); - - expect(seen).toEqual({ provider: "install-vllm", replacement: true }); + ).rejects.toThrow("Legacy shared local inference cannot be rebuilt safely"); + expectNoSandboxDelete(harness.runOpenshellSpy); + expect(harness.onboardSpy).not.toHaveBeenCalled(); expect(process.env.NEMOCLAW_PROVIDER).toBe("install-vllm"); } finally { restoreEnv(); diff --git a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts b/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts index db204bcaa4e..44b3dd8ac4b 100644 --- a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts +++ b/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts @@ -151,7 +151,7 @@ describe("rebuild local-provider recreation", () => { let setupResult: SetupResult | undefined; const routeApplier = makeRouteApplier(); harness = createRebuildFlowHarness({ - sandboxEntry: { provider, model, credentialEnv: null }, + sandboxEntry: { agent: "hermes", provider, model, credentialEnv: null }, onboard: async (session) => { const callsBeforeSetup = harness.runOpenshellSpy.mock.calls.map( (call) => call[0] as string[], @@ -231,7 +231,7 @@ describe("rebuild local-provider recreation", () => { }); expect(calls.some((args) => args[0] === "provider" && args[1] === "update")).toBe(false); expect(harness.restoreSandboxStateSpy).toHaveBeenCalledWith("alpha", harness.backupPath, { - targetAgentType: "openclaw", + targetAgentType: "hermes", }); }, ); diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index 9be15f0319e..946549927cb 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -76,6 +76,7 @@ import { } from "./rebuild-prepared-recovery"; import { inspectRebuildGatewayProviderRegistration, + verifyRebuildNativeLocalProviderBeforeDelete, validateRebuildHostInferenceCredential, shouldVerifyRebuildGatewayProvider, } from "./rebuild-provider-preflight"; @@ -858,7 +859,22 @@ async function rebuildSandboxUnlocked( const nativeAttachment = resumeConfig.nativeNvidiaProviderAttachment ?? resumeConfig.nativeHostedProviderAttachment; - if ( + if (resumeConfig.nativeLocalProviderAttachment !== undefined) { + try { + await verifyRebuildNativeLocalProviderBeforeDelete( + sandboxName, + resumeConfig, + recreateOptions.targetGatewayName, + runtimeSelection, + ); + } catch { + return { + ok: false, + message: + "Native local provider attachment could not be verified before sandbox deletion. Restore its recorded authority, then retry rebuild.", + }; + } + } else if ( !recreateOptions.rebuildProviderReconfigure && resumeConfig.provider && (nativeAttachment || shouldVerifyRebuildGatewayProvider(resumeConfig.provider)) diff --git a/src/lib/actions/sandbox/rebuild-preflight-guards.ts b/src/lib/actions/sandbox/rebuild-preflight-guards.ts index 1de2480fb2f..60e0016fd47 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-guards.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-guards.ts @@ -101,7 +101,9 @@ function hardRouteConflict( const local = normalizeNativeLocalProviderAttachment(target.nativeLocalProviderAttachment); if ( !local || - target.agent !== "langchain-deepagents-code" || + !(target.agent === "langchain-deepagents-code" + ? local.agent === undefined + : target.agent === "openclaw" && local.agent === "openclaw" && !target.nimContainer) || local.sandboxName !== sandboxName || local.gatewayName !== gatewayName || local.provider !== route.provider diff --git a/src/lib/actions/sandbox/rebuild-preflight-target-phase.test.ts b/src/lib/actions/sandbox/rebuild-preflight-target-phase.test.ts index f21029687c4..976c483e7df 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-target-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-target-phase.test.ts @@ -251,6 +251,9 @@ describe("rebuild legacy local route preflight", () => { }, { agent: "langchain-deepagents-code", provider: "ollama-local", createdAt: undefined }, { agent: "langchain-deepagents-code", provider: "vllm-local", createdAt: undefined }, + { agent: "openclaw", provider: "ollama-local", createdAt: undefined }, + { agent: "openclaw", provider: "vllm-local", createdAt: undefined }, + { agent: "openclaw", provider: "llama-cpp-local", createdAt: undefined }, { agent: "langchain-deepagents-code", provider: "ollama-local", @@ -281,6 +284,21 @@ describe("rebuild legacy local route preflight", () => { }, ); + it("leaves Local NIM on its existing shared rebuild path", () => { + const bail = vi.fn((message: string): never => { + throw new Error(message); + }); + const entry = { + name: "alpha", + agent: "openclaw", + provider: "vllm-local", + model: "nim-model", + nimContainer: "nim-alpha", + } as RebuildSandboxEntry; + expect(blockRebuildOnLegacySharedLocalRoute("alpha", entry, bail)).toBe(false); + expect(bail).not.toHaveBeenCalled(); + }); + it("leaves attached selections on their existing preflight path", () => { const bail = vi.fn((message: string): never => { throw new Error(message); diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts index eec5c841707..8bbdb733e79 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts @@ -18,6 +18,7 @@ import { checkRebuildGatewayCredentialReuseOrBail, checkRebuildGatewayProviderOrBail, inspectRebuildGatewayProviderRegistration, + verifyRebuildNativeLocalProviderBeforeDelete, shouldVerifyRebuildGatewayProvider, } from "./rebuild-provider-preflight"; import type { RebuildResumeConfig } from "./rebuild-resume-config"; @@ -76,9 +77,10 @@ const throwingBail = (message: string): never => { }; describe("native local rebuild credentials", () => { - function nativeFixture() { + function nativeFixture(openclaw = false) { const binding = { - provider: "compatible-endpoint" as const, + ...(openclaw ? { agent: "openclaw" as const } : {}), + provider: openclaw ? ("llama-cpp-local" as const) : ("compatible-endpoint" as const), endpointUrl: "http://host.openshell.internal:8000/v1", credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", authMode: "authenticated" as const, @@ -118,7 +120,8 @@ describe("native local rebuild credentials", () => { .spyOn(rebuildOnboardDependencies, "hydrateCredentialEnv") .mockReturnValue(null); const selection = config({ - agent: "langchain-deepagents-code", + agent: openclaw ? "openclaw" : "langchain-deepagents-code", + provider: binding.provider, endpointUrl: "http://localhost:8000/v1", nativeLocalProviderAttachment: attachment, }); @@ -158,6 +161,31 @@ describe("native local rebuild credentials", () => { expect(readShared).not.toHaveBeenCalled(); }); + it.each([false, true])( + "rechecks exact native authority at deletion for OpenClaw=%s", + async (openclaw) => { + const f = nativeFixture(openclaw); + const runtime = { gatewayName: "nemoclaw", workspace: "/test/workspace" }; + await expect( + verifyRebuildNativeLocalProviderBeforeDelete("alpha", f.selection, "nemoclaw", runtime), + ).resolves.toBeUndefined(); + expect(f.adapter.getProvider).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: f.attachment.providerName, + }); + await expect( + verifyRebuildNativeLocalProviderBeforeDelete("alpha", f.selection, "other", { + ...runtime, + gatewayName: "other", + }), + ).rejects.toThrow("authority does not match"); + f.adapter.listProviderAttachments.mockResolvedValue({ ok: true, value: { names: [] } }); + await expect( + verifyRebuildNativeLocalProviderBeforeDelete("alpha", f.selection, "nemoclaw", runtime), + ).rejects.toThrow(); + }, + ); + it("still rejects a staged host credential that cannot recreate native access (#13197)", async () => { const f = nativeFixture(); f.hydrate.mockReturnValue("test-only-rejected-key"); diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.ts index cd6dcc64c94..9bbc0d35f25 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.ts @@ -153,6 +153,25 @@ function rebuildProviderAdapter( ); } +/** Recheck the recorded local attachment at the last boundary before deletion. */ +export async function verifyRebuildNativeLocalProviderBeforeDelete( + sandboxName: string, + config: RebuildResumeConfig, + gatewayName: string, + runtimeSelection?: OpenShellRuntimeSelection, +): Promise { + if (runtimeSelection && runtimeSelection.gatewayName !== gatewayName) + throw new Error("Native local provider runtime does not match the rebuild gateway."); + await verifyRecordedNativeLocalProviderAttachment({ + adapter: rebuildProviderAdapter(runtimeSelection), + expected: config.nativeLocalProviderAttachment, + sandboxName, + gatewayName, + agent: config.agent, + provider: config.provider, + }); +} + export async function inspectRebuildGatewayProviderRegistration( provider: string, log: (msg: string) => void, diff --git a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts index becff08e5b1..a14ac5e6b36 100644 --- a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts @@ -110,7 +110,7 @@ describe("rebuild resume snapshot repair", () => { session = onboardSession.createSession({ sandboxName: "alpha", - provider: "ollama-local", + provider: "build", model: "nvidia/nemotron", lastCompletedStep: "gateway", status: "complete", @@ -216,7 +216,7 @@ describe("rebuild resume snapshot repair", () => { vi.spyOn(onboardSession, "markStepFailed").mockImplementation(() => loadSession()), vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha", - provider: "ollama-local", + provider: "build", model: "nvidia/nemotron", agent: null, nimContainer: null, @@ -237,7 +237,7 @@ describe("rebuild resume snapshot repair", () => { sandboxName: "alpha", gatewayName: "nemoclaw", route: { - provider: "ollama-local", + provider: "build", model: "nvidia/nemotron", endpointUrl: null, preferredInferenceApi: null, @@ -279,9 +279,16 @@ describe("rebuild resume snapshot repair", () => { blueprintDigest: null, }, } as never), - vi - .spyOn(openshellRuntime, "runOpenshell") - .mockReturnValue({ status: 0, output: "" } as never), + vi.spyOn(openshellRuntime, "runOpenshell").mockImplementation( + (args: string[]) => + ({ + status: 0, + output: + args[0] === "provider" && args[1] === "get" && args[2] === "build" + ? "Name: build\nType: openai\nCredential keys: \nConfig keys: \n" + : "", + }) as never, + ), vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ status: 1, output: "", diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index fb3cf324f1e..c2239c3aedf 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -787,63 +787,66 @@ const restartCases = restartProviders.flatMap((provider) => ); describe("startSandbox persisted native inference selection", () => { - it.each(["authenticated", "sentinel"] as const)( - "restarts DCode through its recorded %s local provider", - async (authMode) => { - const binding = { - provider: "compatible-endpoint" as const, - endpointUrl: "http://host.openshell.internal:8000/v1", - credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", - authMode, - gatewayName: "nemoclaw-19080", - sandboxName: "my-sandbox", - }; - const attachment = { - ...binding, - ...nativeLocalIdentity(binding), - schemaVersion: 1 as const, - providerId: "owned-local-provider-id", - }; - const endpoints: string[] = []; - const probeInferenceInvocation = vi.fn< - NonNullable - >(async (input) => { - endpoints.push(resolveSandboxInferenceInvocationEndpoint(input)); - return { ok: true }; - }); - const h = harness({ probeInferenceInvocation }); - h.getSandbox.mockReturnValue( - sandbox({ - stopped: true, - agent: "langchain-deepagents-code", - provider: binding.provider, - model: "local-model", - gatewayName: binding.gatewayName, - preferredInferenceApi: "openai-completions", - nativeLocalProviderAttachment: attachment, - }), - ); + it.each([ + ["langchain-deepagents-code", "authenticated"], + ["langchain-deepagents-code", "sentinel"], + ["openclaw", "authenticated"], + ["openclaw", "sentinel"], + ] as const)("restarts %s through its recorded %s local provider", async (agent, authMode) => { + const binding = { + provider: agent === "openclaw" ? ("vllm-local" as const) : ("compatible-endpoint" as const), + ...(agent === "openclaw" ? { agent } : {}), + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode, + gatewayName: "nemoclaw-19080", + sandboxName: "my-sandbox", + }; + const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-local-provider-id", + }; + const endpoints: string[] = []; + const probeInferenceInvocation = vi.fn< + NonNullable + >(async (input) => { + endpoints.push(resolveSandboxInferenceInvocationEndpoint(input)); + return { ok: true }; + }); + const h = harness({ probeInferenceInvocation }); + h.getSandbox.mockReturnValue( + sandbox({ + stopped: true, + agent, + provider: binding.provider, + model: "local-model", + gatewayName: binding.gatewayName, + preferredInferenceApi: "openai-completions", + nativeLocalProviderAttachment: attachment, + }), + ); - await expect(startSandbox("my-sandbox", h.deps)).resolves.toEqual({ exitCode: 0 }); - expect(probeInferenceInvocation).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - sandboxName: binding.sandboxName, - gatewayName: binding.gatewayName, - agentName: "langchain-deepagents-code", - provider: binding.provider, - model: "local-model", - nativeLocalProviderAttachment: attachment, - }), - {}, - expect.any(Number), - ); - expect(endpoints).toEqual([`${binding.endpointUrl}/chat/completions`]); - expect(h.updateSandbox).toHaveBeenCalledWith( - "my-sandbox", - expect.objectContaining({ stopped: false }), - ); - }, - ); + await expect(startSandbox("my-sandbox", h.deps)).resolves.toEqual({ exitCode: 0 }); + expect(endpoints).toEqual([`${binding.endpointUrl}/chat/completions`]); + expect(probeInferenceInvocation).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + sandboxName: binding.sandboxName, + gatewayName: binding.gatewayName, + agentName: agent, + provider: binding.provider, + model: "local-model", + nativeLocalProviderAttachment: attachment, + }), + {}, + expect.any(Number), + ); + expect(h.updateSandbox).toHaveBeenCalledWith( + "my-sandbox", + expect.objectContaining({ stopped: false }), + ); + }); const hermesEndpoint = "https://authenticated.nous.example/api/v1"; const hermesDefinition = hostedNativeProvider("hermes-provider", hermesEndpoint)!; diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index b6d9ee863a1..40ea6a60786 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -174,7 +174,9 @@ async function checkStartedSandboxInference( const input = { sandboxName, gatewayName, - ...(sandbox.agent === "langchain-deepagents-code" ? { agentName: sandbox.agent } : {}), + ...(sandbox.agent === "langchain-deepagents-code" || sandbox.agent === "openclaw" + ? { agentName: sandbox.agent } + : {}), provider, model, preferredInferenceApi: sandbox.preferredInferenceApi ?? null, diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index a1dc4f70948..cc37974a199 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -668,3 +668,24 @@ it.each([ ).inferenceBaseUrl, ).toBe(expected); }); + +it.each([ + ["openclaw", true, "http://host.openshell.internal:8000/v1"], + ["openclaw", false, "https://inference.local/v1"], + ["hermes", true, "https://inference.local/v1"], + ["pi", true, "https://inference.local/v1"], +] as const)( + "routes %s standalone vLLM with native attachment %s to %s", + (agent, attached, expected) => { + expect( + getSandboxInferenceConfig( + "fixture-model", + "vllm-local", + "openai-completions", + attached, + "http://host.openshell.internal:8000/v1", + agent, + ).inferenceBaseUrl, + ).toBe(expected); + }, +); diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 0bbff0d1aa1..1c529f9681e 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -455,9 +455,9 @@ export function getSandboxInferenceConfig( if ( useNativeProvider && - agentName === "langchain-deepagents-code" && + (agentName === "langchain-deepagents-code" || agentName === "openclaw") && nativeEndpointUrl && - usesNativeLocalInference(provider, nativeEndpointUrl) && + usesNativeLocalInferenceForAgent(agentName, provider, nativeEndpointUrl) && nativeLocalCredentialReference(provider, nativeEndpointUrl) ) { inferenceBaseUrl = nativeEndpointUrl; diff --git a/src/lib/inference/native-local.test.ts b/src/lib/inference/native-local.test.ts index 7a20211a73b..794907cd812 100644 --- a/src/lib/inference/native-local.test.ts +++ b/src/lib/inference/native-local.test.ts @@ -6,6 +6,7 @@ import { OLLAMA_PROXY_PORT } from "../core/ollama-proxy-port"; import { isProtectedLocalInferencePort } from "./gateway/local-endpoint-ports"; import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { isLocalInferenceProvider } from "./native-local/agent-config"; import { nativeLocalIdentity, nativeLocalCredentialReference, @@ -123,7 +124,7 @@ function fixture(selectedBinding: NativeLocalBinding = binding) { describe("native local inference", () => { it.each([ - { reason: "wrong agent", override: { agent: "openclaw" } }, + { reason: "wrong agent", override: { agent: "hermes" } }, { reason: "wrong provider", override: { provider: "compatible-endpoint" } }, { reason: "wrong sandbox", override: { sandboxName: "bob" } }, { reason: "wrong gateway", override: { gatewayName: "nemoclaw-8081" } }, @@ -238,7 +239,7 @@ describe("native local inference", () => { }); it.each([ - ["openclaw", false], + ["openclaw", true], ["langchain-deepagents-code", true], ["pi", false], ["hermes", false], @@ -249,7 +250,7 @@ describe("native local inference", () => { }); it("keeps an owned Local NIM selection on the shared route while standalone vLLM is native", () => { - expect(usesNativeLocalInferenceForAgent("openclaw", "vllm-local", null)).toBe(false); + expect(usesNativeLocalInferenceForAgent("openclaw", "vllm-local", null)).toBe(true); expect(usesNativeLocalInferenceForAgent("langchain-deepagents-code", "vllm-local", null)).toBe( true, ); @@ -262,9 +263,18 @@ describe("native local inference", () => { ).toBe(true); }); + it("classifies llama.cpp with the shared local-provider predicate used by inference set", () => { + expect(isLocalInferenceProvider("llama-cpp-local")).toBe(true); + }); + it("restricts the selected bridge to models and chat requests (#12558)", () => { const profile = prepareNativeLocalProfile(binding); expect(profile.document.binaries).toContain("/usr/bin/python3"); + expect(profile.document.binaries).not.toContain("/usr/local/bin/node"); + const openClawProfile = prepareNativeLocalProfile({ ...binding, agent: "openclaw" }); + expect(openClawProfile.document.binaries).toContain("/usr/local/bin/node"); + expect(openClawProfile.document.binaries).toContain("/usr/bin/python3"); + expect(openClawProfile.profileId).not.toBe(profile.profileId); expect(profile.document.binaries).not.toContain("/usr/local/bin/openclaw"); expect(profile.document.binaries).not.toContain("/opt/hermes/.venv/bin/python"); expect(profile.document.endpoints).toEqual([ @@ -578,3 +588,15 @@ it.each(["http://10.1.2.3:8000/v1", "http://host.openshell.internal:42103/v1"])( ).toBe(false); }, ); + +it("keeps Local NIM and generic compatible endpoints on the shared OpenClaw route", () => { + expect( + usesNativeLocalInferenceForAgent("openclaw", "vllm-local", binding.endpointUrl, true), + ).toBe(false); + expect( + usesNativeLocalInferenceForAgent("openclaw", "compatible-endpoint", binding.endpointUrl), + ).toBe(false); + expect(usesNativeLocalInferenceForAgent("openclaw", "vllm-local", binding.endpointUrl)).toBe( + true, + ); +}); diff --git a/src/lib/inference/native-local/agent-config.ts b/src/lib/inference/native-local/agent-config.ts index 0534fb23d56..3579067a16c 100644 --- a/src/lib/inference/native-local/agent-config.ts +++ b/src/lib/inference/native-local/agent-config.ts @@ -6,6 +6,10 @@ import { unsafeEndpointUrlViolation } from "../../core/endpoint-url-safety.ts"; export const NATIVE_LOCAL_CREDENTIAL_ENV = "NEMOCLAW_LOCAL_INFERENCE_TOKEN"; +export function isLocalInferenceProvider(provider: string | null | undefined): boolean { + return provider === "ollama-local" || provider === "vllm-local" || provider === "llama-cpp-local"; +} + /** The endpoint shape shared by local provider registration and agent credentials. */ export function qualifiedNativeLocalEndpointUrl(endpointUrl: string): string | null { if (!endpointUrl || unsafeEndpointUrlViolation(endpointUrl)) return null; diff --git a/src/lib/inference/native-local/contract.ts b/src/lib/inference/native-local/contract.ts index 7bddede7da2..bea570874a6 100644 --- a/src/lib/inference/native-local/contract.ts +++ b/src/lib/inference/native-local/contract.ts @@ -4,11 +4,15 @@ import { OLLAMA_PROXY_PORT } from "../../core/ollama-proxy-port"; import { VLLM_PORT } from "../../core/vllm-port"; import { createHash } from "node:crypto"; -import { qualifiedNativeLocalEndpointUrl } from "./agent-config"; +import { isLocalInferenceProvider, qualifiedNativeLocalEndpointUrl } from "./agent-config"; import { isValidName } from "../../../../nemoclaw/dist/shared/sandbox-name.cjs"; import type { NativeProviderAttachment } from "../native-provider/lifecycle"; -export { NATIVE_LOCAL_CREDENTIAL_ENV, nativeLocalCredentialReference } from "./agent-config"; +export { + NATIVE_LOCAL_CREDENTIAL_ENV, + isLocalInferenceProvider, + nativeLocalCredentialReference, +} from "./agent-config"; export type NativeLocalProvider = | "ollama-local" @@ -17,6 +21,7 @@ export type NativeLocalProvider = | "compatible-endpoint"; export type NativeLocalBinding = Readonly<{ provider: NativeLocalProvider; + agent?: "openclaw"; endpointUrl: string; credentialEnv: string; authMode: "authenticated" | "sentinel"; @@ -27,10 +32,6 @@ export type NativeLocalBinding = Readonly<{ }>; export type NativeLocalProviderAttachment = NativeProviderAttachment & NativeLocalBinding; -export function isLocalInferenceProvider(provider: string | null | undefined): boolean { - return provider === "ollama-local" || provider === "vllm-local" || provider === "llama-cpp-local"; -} - /** Consume only the host-reachable address already selected by the local runtime owner. */ export function normalizeNativeLocalBinding(value: unknown): NativeLocalBinding | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; @@ -38,6 +39,8 @@ export function normalizeNativeLocalBinding(value: unknown): NativeLocalBinding if ( (!isLocalInferenceProvider(input.provider as string) && input.provider !== "compatible-endpoint") || + (input.agent !== undefined && input.agent !== "openclaw") || + (input.agent === "openclaw" && !isLocalInferenceProvider(input.provider as string)) || typeof input.endpointUrl !== "string" || typeof input.credentialEnv !== "string" || !/^[A-Z][A-Z0-9_]*$/.test(input.credentialEnv) || @@ -54,6 +57,7 @@ export function normalizeNativeLocalBinding(value: unknown): NativeLocalBinding if (!endpointUrl) return undefined; return { provider: input.provider as NativeLocalProvider, + ...(input.agent === "openclaw" ? { agent: "openclaw" as const } : {}), endpointUrl, credentialEnv: input.credentialEnv, authMode: input.authMode, @@ -70,6 +74,7 @@ export function nativeLocalIdentity(binding: NativeLocalBinding) { .update( JSON.stringify([ normalized.provider, + ...(normalized.agent ? [normalized.agent] : []), normalized.endpointUrl, normalized.credentialEnv, normalized.authMode, @@ -166,9 +171,10 @@ export function usesNativeLocalInferenceForAgent( endpointUrl?: string | null, localNimSelected = false, ): boolean { + if (provider === "vllm-local" && localNimSelected) return false; return ( - !(provider === "vllm-local" && localNimSelected) && - agentName === "langchain-deepagents-code" && - usesNativeLocalInference(provider, endpointUrl) + (agentName === "langchain-deepagents-code" && + usesNativeLocalInference(provider, endpointUrl)) || + (agentName === "openclaw" && isLocalInferenceProvider(provider)) ); } diff --git a/src/lib/inference/native-local/profile.ts b/src/lib/inference/native-local/profile.ts index 6a3821a8aeb..d23ec658c1b 100644 --- a/src/lib/inference/native-local/profile.ts +++ b/src/lib/inference/native-local/profile.ts @@ -25,6 +25,7 @@ import { } from "./contract"; export { normalizeNativeLocalProviderAttachment }; +export type { NativeLocalProviderAttachment }; export function prepareNativeLocalProfile(input: NativeLocalBinding) { const binding = normalizeNativeLocalBinding(input); @@ -69,8 +70,11 @@ export function prepareNativeLocalProfile(input: NativeLocalBinding) { }, ], binaries: [ + // The provider-neutral onboarding smoke probe uses Python urllib. "/usr/bin/python3", - "/opt/venv/bin/python3", + ...(binding.agent === "openclaw" + ? ["/usr/local/bin/node", "/usr/bin/node"] + : ["/opt/venv/bin/python3"]), "/usr/local/bin/curl", "/usr/bin/curl", ], @@ -163,7 +167,8 @@ export async function verifyRecordedNativeLocalProviderAttachment(input: { const expected = normalizeNativeLocalProviderAttachment(input.expected); if ( !expected || - input.agent !== "langchain-deepagents-code" || + (input.agent !== "langchain-deepagents-code" && input.agent !== "openclaw") || + (input.agent === "openclaw" ? expected.agent !== "openclaw" : expected.agent !== undefined) || expected.provider !== input.provider || expected.sandboxName !== input.sandboxName || (input.gatewayName !== undefined && expected.gatewayName !== input.gatewayName) diff --git a/src/lib/inference/selection.ts b/src/lib/inference/selection.ts index d8d0cced07e..46fd79d07a7 100644 --- a/src/lib/inference/selection.ts +++ b/src/lib/inference/selection.ts @@ -23,6 +23,7 @@ export function hasLegacySharedLocalInferenceRoute(recorded: { }): boolean { return ( recorded.nativeLocalProviderAttachment === undefined && + !recorded.nimContainer && usesNativeLocalInferenceForAgent( recorded.agent ?? "openclaw", recorded.provider, diff --git a/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts b/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts index 3d20f61c230..7c01691f692 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-route-containment.test.ts @@ -3,9 +3,11 @@ import { describe, expect, it, vi } from "vitest"; -import type { - CurrentGatewayRouteCompatibilityCheck, - CurrentGatewayRouteDiscoveryPreflight, +import { + checkGatewayRouteCompatibility, + preflightGatewayRouteDiscovery, + type CurrentGatewayRouteCompatibilityCheck, + type CurrentGatewayRouteDiscoveryPreflight, } from "../../../inference/gateway-route-compatibility"; import { createSession, type Session, type SessionUpdates } from "../../../state/onboard-session"; import { @@ -571,36 +573,83 @@ it.each([undefined, "2026-10-01T00:00:00Z"])( }, ); -it("resumes an owned Local NIM DCode shared route without requiring a native attachment", async () => { +it.each(["openclaw", "langchain-deepagents-code"] as const)( + "resumes an owned Local NIM %s shared route without requiring a native attachment", + async (agentName) => { + const { deps, calls } = createDeps(); + deps.getSandboxRegistryEntry = () => ({ + name: "target-sandbox", + agent: agentName, + provider: "vllm-local", + model: "fixture-model", + endpointUrl: "https://inference.local/v1", + gatewayName: "nemoclaw-9090", + nimContainer: "nemoclaw-nim-owned", + }); + const session = createSession(); + session.provider = "vllm-local"; + session.model = "fixture-model"; + session.endpointUrl = "https://inference.local/v1"; + session.nimContainer = "nemoclaw-nim-owned"; + session.steps.provider_selection.status = "complete"; + + const options = resumeOptions(deps, session); + options.agent = { name: agentName } as never; + options.forceInferenceSetup = true; + await expect(handleProviderInferenceState(options)).resolves.toMatchObject({ + provider: "vllm-local", + model: "fixture-model", + }); + expect(calls.error).not.toHaveBeenCalled(); + expect(calls.setupNim).not.toHaveBeenCalled(); + expect(calls.setupInference).toHaveBeenCalledOnce(); + expect(calls.setupInference.mock.calls[0]?.at(-1)).toMatchObject({ + agentName, + localNimSelected: true, + }); + }, +); + +it("keeps a fresh OpenClaw native local endpoint independent of a shared peer", async () => { const { deps, calls } = createDeps(); - deps.getSandboxRegistryEntry = () => ({ - name: "target-sandbox", - agent: "langchain-deepagents-code", - provider: "vllm-local", - model: "fixture-model", - endpointUrl: "https://inference.local/v1", - gatewayName: "nemoclaw-9090", - nimContainer: "nemoclaw-nim-owned", - }); - const session = createSession(); - session.provider = "vllm-local"; - session.model = "fixture-model"; - session.endpointUrl = "https://inference.local/v1"; - session.nimContainer = "nemoclaw-nim-owned"; - session.steps.provider_selection.status = "complete"; - - const options = resumeOptions(deps, session); - options.agent = { name: "langchain-deepagents-code" } as never; - options.forceInferenceSetup = true; - await expect(handleProviderInferenceState(options)).resolves.toMatchObject({ - provider: "vllm-local", + const selection = { + ...fallbackSelection, + provider: "llama-cpp-local", model: "fixture-model", + endpointUrl: "http://host.openshell.internal:8081/v1", + credentialEnv: "NEMOCLAW_LLAMACPP_LOCAL_TOKEN", + preferredInferenceApi: "openai-completions", + }; + const peers = [ + { + name: "shared-peer", + agent: "openclaw", + gatewayName: "nemoclaw-9090", + provider: selection.provider, + model: selection.model, + endpointUrl: "http://host.openshell.internal:8082/v1", + credentialEnv: selection.credentialEnv, + preferredInferenceApi: selection.preferredInferenceApi, + }, + ]; + calls.preflightGatewayRouteDiscovery.mockImplementation((request) => + preflightGatewayRouteDiscovery({ ...request, sandboxes: peers }), + ); + calls.checkGatewayRouteCompatibility.mockImplementation((request) => + checkGatewayRouteCompatibility({ ...request, sandboxes: peers }), + ); + calls.setupNim.mockImplementation(async (_gpu, _sandbox, _agent, _recover, _gateway, guard) => { + guard?.(selection); + return selection; }); - expect(calls.error).not.toHaveBeenCalled(); - expect(calls.setupNim).not.toHaveBeenCalled(); + const options = resumeOptions(deps, createSession()); + await expect( + handleProviderInferenceState({ + ...options, + resume: false, + agent: { name: "openclaw" } as never, + }), + ).resolves.toMatchObject({ provider: "llama-cpp-local", model: "fixture-model" }); expect(calls.setupInference).toHaveBeenCalledOnce(); - expect(calls.setupInference.mock.calls[0]?.at(-1)).toMatchObject({ - agentName: "langchain-deepagents-code", - localNimSelected: true, - }); + expect(calls.error).not.toHaveBeenCalled(); }); diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 149d7c9c5f6..afdc4356bf2 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -93,6 +93,7 @@ export interface ProviderInferenceSetupOptions { /** Local NIM shares vllm-local's provider ID but keeps its existing route. */ localNimSelected?: boolean; gatewayName?: string; + nimContainer?: string | null; allowToolsIncompatible?: boolean; skipHostInferenceSmoke?: boolean; reuseGatewayCredentialWithoutLocalKey?: boolean; diff --git a/src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts b/src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts index 1cd310a3a64..2e067050d91 100644 --- a/src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts @@ -434,11 +434,11 @@ describe("sandbox route publication", () => { }); }); -function nativeRecreationHarness() { +function nativeRecreationHarness(agent: "langchain-deepagents-code" | "openclaw") { const session = createSession({ sandboxName: "saved" }); const row: SandboxEntry = { name: "saved", - agent: "langchain-deepagents-code", + agent, provider: "vllm-local", model: "meta-llama", endpointUrl: "http://host.openshell.internal:8000/v1", @@ -447,6 +447,7 @@ function nativeRecreationHarness() { }; const source = structuredClone(row); const attachment = nativeLocalSetupReceipt({ + ...(agent === "openclaw" ? { agent } : {}), provider: "vllm-local", sandboxName: "saved", gatewayName: "nemoclaw", @@ -482,49 +483,53 @@ function nativeRecreationHarness() { return { row, source, attachment, session, reserve, deps, calls, run }; } -describe("legacy DCode recreation publication", () => { - it("publishes the native attachment only at the post-backup replacement seam (#13197)", async () => { - const { row, source, attachment, session, reserve, deps, run } = nativeRecreationHarness(); - deps.createSandbox = async (...args: unknown[]) => { - expect(row).toEqual(source); - expect(reserve).not.toHaveBeenCalled(); - const intent = args.at(-2) as { - resolved: { inferenceProvider: string; nativeLocalProviderAttachment: unknown }; - reservePublishedRouteAfterBackup: () => Promise; +describe.each(["langchain-deepagents-code", "openclaw"] as const)( + "legacy %s recreation publication", + (agent) => { + it("publishes the native attachment only at the post-backup replacement seam (#13197)", async () => { + const { row, source, attachment, session, reserve, deps, run } = + nativeRecreationHarness(agent); + deps.createSandbox = async (...args: unknown[]) => { + expect(row).toEqual(source); + expect(reserve).not.toHaveBeenCalled(); + const intent = args.at(-2) as { + resolved: { inferenceProvider: string; nativeLocalProviderAttachment: unknown }; + reservePublishedRouteAfterBackup: () => Promise; + }; + expect(intent.resolved).toMatchObject({ + inferenceProvider: attachment.providerName, + nativeLocalProviderAttachment: attachment, + }); + await intent.reservePublishedRouteAfterBackup(); + expect(row.nativeLocalProviderAttachment).toEqual(attachment); + return "saved"; }; - expect(intent.resolved).toMatchObject({ - inferenceProvider: attachment.providerName, - nativeLocalProviderAttachment: attachment, - }); - await intent.reservePublishedRouteAfterBackup(); - expect(row.nativeLocalProviderAttachment).toEqual(attachment); - return "saved"; - }; - await run(); - expect(reserve).toHaveBeenCalledExactlyOnceWith( - "saved", - expect.objectContaining({ - nativeLocalProviderAttachment: attachment, - reservationSessionId: session.sessionId, - }), - ); - }); + await run(); + expect(reserve).toHaveBeenCalledExactlyOnceWith( + "saved", + expect.objectContaining({ + nativeLocalProviderAttachment: attachment, + reservationSessionId: session.sessionId, + }), + ); + }); - it("preserves the legacy source when backup rejects recreation (#13197)", async () => { - const { row, source, reserve, deps, run } = nativeRecreationHarness(); - deps.createSandbox = async () => { - throw new Error("backup refused"); - }; - await expect(run()).rejects.toThrow("backup refused"); - expect(reserve).not.toHaveBeenCalled(); - expect(row).toEqual(source); - }); + it("preserves the legacy source when backup rejects recreation (#13197)", async () => { + const { row, source, reserve, deps, run } = nativeRecreationHarness(agent); + deps.createSandbox = async () => { + throw new Error("backup refused"); + }; + await expect(run()).rejects.toThrow("backup refused"); + expect(reserve).not.toHaveBeenCalled(); + expect(row).toEqual(source); + }); - it("rejects a changed legacy source before starting recreation (#13197)", async () => { - const { row, reserve, calls, run } = nativeRecreationHarness(); - row.model = "another-model"; - await expect(run()).rejects.toThrow("legacy route ownership changed"); - expect(reserve).not.toHaveBeenCalled(); - expect(calls.createSandbox).not.toHaveBeenCalled(); - }); -}); + it("rejects a changed legacy source before starting recreation (#13197)", async () => { + const { row, reserve, calls, run } = nativeRecreationHarness(agent); + row.model = "another-model"; + await expect(run()).rejects.toThrow("legacy route ownership changed"); + expect(reserve).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + }); + }, +); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 226d2da10f4..b620dbccfc5 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -1314,11 +1314,13 @@ class SandboxStateFlow< ): SandboxEntry | null { const staged = this.options.stagedNativeLocalRecreation; if (!staged) return entry; + const agentName = (this.options.agent as { name?: string } | null)?.name ?? "openclaw"; if ( this.options.resume || !this.options.recreateSandbox(false) || !this.options.session?.sessionId || - (this.options.agent as { name?: string } | null)?.name !== "langchain-deepagents-code" || + (agentName !== "langchain-deepagents-code" && agentName !== "openclaw") || + staged.attachment.agent !== (agentName === "openclaw" ? "openclaw" : undefined) || staged.attachment.sandboxName !== sandboxName || staged.attachment.gatewayName !== this.options.gatewayName || staged.attachment.provider !== this.options.provider || diff --git a/src/lib/onboard/managed-startup/onboard-profile.ts b/src/lib/onboard/managed-startup/onboard-profile.ts index 26b629b7131..b3a3bb202e6 100644 --- a/src/lib/onboard/managed-startup/onboard-profile.ts +++ b/src/lib/onboard/managed-startup/onboard-profile.ts @@ -3,7 +3,11 @@ import type { SandboxMessagingPlan } from "../../messaging/manifest"; import type { ToolDisclosure } from "../../tool-disclosure"; -import { usesNativeLocalInference } from "../../inference/native-local/contract"; +import { + isLocalInferenceProvider, + usesNativeLocalInference, +} from "../../inference/native-local/contract"; +export { isLocalInferenceProvider }; import type { ResolvedCorporateCa } from "../corporate-ca-types"; import type { DcodeAutoApprovalMode } from "../dcode-auto-approval"; import type { HermesDashboardOnboardState } from "../hermes-dashboard"; @@ -96,14 +100,20 @@ export function resolveManagedStartupInferenceEndpoint(input: { localNimSelected?: boolean; nativeLocalProviderAttachment?: { endpointUrl: string }; }): string | null { - if (input.agentName !== "langchain-deepagents-code") return input.endpointUrl; - if (input.provider === "vllm-local" && input.localNimSelected) return input.endpointUrl; - if (usesNativeLocalInference(input.provider, input.endpointUrl)) { - if (!input.nativeLocalProviderAttachment) { + if (input.agentName === "langchain-deepagents-code") { + if (input.provider === "vllm-local" && input.localNimSelected) return input.endpointUrl; + if ( + usesNativeLocalInference(input.provider, input.endpointUrl) && + !input.nativeLocalProviderAttachment + ) { throw new Error("Deep Agents Code local inference requires its native provider attachment."); } + return input.nativeLocalProviderAttachment?.endpointUrl ?? input.endpointUrl; + } + if (input.agentName === "openclaw" && input.nativeLocalProviderAttachment) { + return input.nativeLocalProviderAttachment.endpointUrl; } - return input.nativeLocalProviderAttachment?.endpointUrl ?? input.endpointUrl; + return input.endpointUrl; } export class ManagedStartupOnboardProfileError extends Error { diff --git a/src/lib/onboard/managed-workload/native-local-startup-route.test.ts b/src/lib/onboard/managed-workload/native-local-startup-route.test.ts index 62eefcdcf7c..cd041ef8f67 100644 --- a/src/lib/onboard/managed-workload/native-local-startup-route.test.ts +++ b/src/lib/onboard/managed-workload/native-local-startup-route.test.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; -import { nativeLocalIdentity } from "../../inference/native-local/contract"; +import { + nativeLocalIdentity, + type NativeLocalProviderAttachment, +} from "../../inference/native-local/contract"; import { getSandboxInferenceConfig, resolveAgentInferenceApi } from "../../inference/config"; import { createManagedWorkloadOnboardRuntime } from "./onboard-orchestration"; @@ -40,7 +43,7 @@ function prepareProfile( agentName: AgentName, route: { endpointUrl: string | null; - attachment?: typeof nativeAttachment; + attachment?: NativeLocalProviderAttachment; provider?: string; localNimSelected?: boolean; nativeProvider?: boolean; @@ -122,15 +125,42 @@ it("rejects unattached Deep Agents Code native inference (#13197)", () => { ).toThrow("requires its native provider attachment"); }); -it("keeps owned Local NIM on the Deep Agents Code shared route without an attachment (#13116)", () => { - const prepared = prepareProfile("langchain-deepagents-code", { - provider: "vllm-local", - endpointUrl: "http://127.0.0.1:8000/v1", - localNimSelected: true, - nativeProvider: false, +it.each(["openclaw", "langchain-deepagents-code"] as const)( + "keeps owned Local NIM on the %s shared route without an attachment (#13116)", + (agentName) => { + const prepared = prepareProfile(agentName, { + provider: "vllm-local", + endpointUrl: "http://127.0.0.1:8000/v1", + localNimSelected: true, + nativeProvider: false, + }); + expect(prepared?.profile.inference).toMatchObject({ + upstreamProvider: "vllm-local", + routedBaseUrl: "https://inference.local/v1", + }); + }, +); + +it("routes new OpenClaw Ollama through its sandbox attachment", () => { + const localBinding = { + ...nativeBinding, + provider: "ollama-local" as const, + agent: "openclaw" as const, + }; + const attachment = { + ...localBinding, + ...nativeLocalIdentity(localBinding), + schemaVersion: 1 as const, + providerId: "local-fixture", + }; + const prepared = prepareProfile("openclaw", { + provider: "ollama-local", + endpointUrl: localBinding.endpointUrl, + attachment, }); expect(prepared?.profile.inference).toMatchObject({ - upstreamProvider: "vllm-local", - routedBaseUrl: "https://inference.local/v1", + upstreamProvider: "ollama-local", + routedBaseUrl: localBinding.endpointUrl, + upstreamEndpointUrl: null, }); }); diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index 11eaf241d0e..c741c06f266 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -24,6 +24,7 @@ import { isShippedManagedImageAgent } from "../managed-image/contract"; import { type BuiltManagedStartupOnboardProfile, buildManagedStartupOnboardProfile, + isLocalInferenceProvider, resolveManagedStartupInferenceEndpoint, type ManagedStartupOnboardProfileInput, } from "../managed-startup/onboard-profile"; @@ -399,7 +400,10 @@ export function createManagedWorkloadOnboardRuntime( } if (preparedProfile) return preparedProfile; const nativeLocalProviderAttachment = - input.agentName === "langchain-deepagents-code" + input.agentName === "langchain-deepagents-code" || + (input.agentName === "openclaw" && + input.nativeLocalProviderAttachment?.agent === "openclaw" && + isLocalInferenceProvider(input.provider)) ? input.nativeLocalProviderAttachment : undefined; const selectedModel = input.model?.trim() || ""; diff --git a/src/lib/onboard/openclaw/initial-inference-route.ts b/src/lib/onboard/openclaw/initial-inference-route.ts index f1c984b6955..393bd7084a5 100644 --- a/src/lib/onboard/openclaw/initial-inference-route.ts +++ b/src/lib/onboard/openclaw/initial-inference-route.ts @@ -144,7 +144,9 @@ const nativeInferenceRouteDeps: InitialOpenclawInferenceRouteDeps = { return { endpointUrl: entry.endpointUrl, nativeProvider: Boolean( - entry.nativeHostedProviderAttachment || entry.nativeNvidiaProviderAttachment, + entry.nativeHostedProviderAttachment || + entry.nativeNvidiaProviderAttachment || + entry.nativeLocalProviderAttachment, ), }; }, diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index a2ceabf41a0..79dabd6fec8 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -539,6 +539,9 @@ export function nativeLocalReservationStatus(input: { input.entry.nativeLocalProviderAttachment, ); return attachment && + (input.agentName === "openclaw" + ? attachment.agent === "openclaw" + : attachment.agent === undefined) && attachment.sandboxName === input.sandboxName && attachment.gatewayName === input.gatewayName && attachment.provider === input.provider && diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 691aa61d987..5689129b6ba 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -1314,7 +1314,7 @@ export function createSetupInference( !options.recreatePublishedSandbox || !options.deferPublishedRouteReservation || !options.reservationSessionId || - recorded.agent !== "langchain-deepagents-code" + (recorded.agent !== "langchain-deepagents-code" && recorded.agent !== "openclaw") ) { throw new Error("Recreate this beta sandbox before using native local inference."); } @@ -1330,6 +1330,10 @@ export function createSetupInference( adapter: deps.providerAdapter, binding: { provider: name as NativeLocalProvider, + ...((options.agentName ?? options.hostLocalInference?.request.application) === + "openclaw" + ? { agent: "openclaw" as const } + : {}), endpointUrl: hostReachableEndpoint, authMode: (name === "ollama-local" && value === "ollama") || diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index eaa8b32daa0..676ef23a88f 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -179,50 +179,53 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(probeInferenceInvocation).not.toHaveBeenCalled(); }); - it.each([DCODE_AGENT])( - "accepts a managed local provider's canonical application route for %s", - async (agentName) => { - const binding = { - ...localBinding, - provider: "llama-cpp-local" as const, - endpointUrl: "http://host.openshell.internal:8081/v1", - authMode: "authenticated" as const, - }; - const attachment = { - ...binding, - ...nativeLocalIdentity(binding), - schemaVersion: 1 as const, - providerId: "provider-1", - }; - const context = onboardInferenceVerificationContext( - "my-sandbox", - "my-gateway", - agentName, - { - provider: "llama-cpp-local", - model: "test-model", - endpointUrl: "https://inference.local/v1", - preferredInferenceApi: "openai-completions", - }, - { nativeLocalProviderAttachment: attachment }, - ); - const routeProbe = vi.fn(async () => ({ ok: true }) as const); - const deployment = await verifyDeployment( - "my-sandbox", - buildChain(), - makeDeps({ probeInferenceInvocation: routeProbe }), - { ...NO_RETRY, inferenceRouteContext: context.route }, - ); - expect(deployment.verification.inferenceRouteWorking).toBe(true); - expect(routeProbe).toHaveBeenCalledOnce(); - - const invocationProbe = vi.fn(async () => ({ ok: true }) as const); - expect(await probeOnboardInferenceInvocation(context.invocation, invocationProbe)).toEqual({ - ok: true, - }); - expect(invocationProbe).toHaveBeenCalledOnce(); - }, - ); + it.each([ + [DCODE_AGENT, "https://inference.local/v1"], + ["openclaw", "https://inference.local/v1"], + [DCODE_AGENT, "http://127.0.0.1:8081/v1"], + ["openclaw", "http://127.0.0.1:8081/v1"], + ])("accepts the selected local route for %s at %s", async (agentName, endpointUrl) => { + const binding = { + ...localBinding, + ...(agentName === "openclaw" ? { agent: "openclaw" as const } : {}), + provider: "llama-cpp-local" as const, + endpointUrl: "http://host.openshell.internal:8081/v1", + authMode: "authenticated" as const, + }; + const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "provider-1", + }; + const context = onboardInferenceVerificationContext( + "my-sandbox", + "my-gateway", + agentName, + { + provider: "llama-cpp-local", + model: "test-model", + endpointUrl, + preferredInferenceApi: "openai-completions", + }, + { nativeLocalProviderAttachment: attachment }, + ); + const routeProbe = vi.fn(async () => ({ ok: true }) as const); + const deployment = await verifyDeployment( + "my-sandbox", + buildChain(), + makeDeps({ probeInferenceInvocation: routeProbe }), + { ...NO_RETRY, inferenceRouteContext: context.route }, + ); + expect(deployment.verification.inferenceRouteWorking).toBe(true); + expect(routeProbe).toHaveBeenCalledOnce(); + + const invocationProbe = vi.fn(async () => ({ ok: true }) as const); + expect(await probeOnboardInferenceInvocation(context.invocation, invocationProbe)).toEqual({ + ok: true, + }); + expect(invocationProbe).toHaveBeenCalledOnce(); + }); it("rejects a native local attachment for a different selected endpoint in both probes", async () => { const context = onboardInferenceVerificationContext( diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 7cd3e11d7a1..cba22ba641e 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -45,6 +45,7 @@ import { type SandboxCommandExecutor, } from "./onboard/custom-openclaw-runtime-diagnosis"; import { GATEWAY_PORT, resolveGatewayLogPathForPort } from "./onboard/gateway/state-dir"; +import { gatewayReachableCompatibleEndpointUrl } from "./onboard/inference-providers/compatible-endpoint-gateway-route"; import { getMessagingProviderNamesForChannel } from "./onboard/messaging-reuse"; import { HOST_LOCAL_INFERENCE_APPLICATION_BASE_URL } from "./onboard/runtime-provider/host-local-inference-routing"; @@ -438,7 +439,7 @@ function matchesNativeLocalVerificationRoute( return true; const selected = normalizeNativeLocalBinding({ ...attachment, - endpointUrl: context.endpointUrl, + endpointUrl: gatewayReachableCompatibleEndpointUrl(attachment.provider, context.endpointUrl), }); return selected?.endpointUrl === attachment.endpointUrl; } @@ -1001,6 +1002,7 @@ export function onboardInferenceVerificationContext( agentName: string, flow: Pick & { endpointUrl?: string | null; + nimContainer?: string | null; }, attachment?: | (Pick< diff --git a/test/e2e/fixtures/fake-openai-compatible.ts b/test/e2e/fixtures/fake-openai-compatible.ts index e8c3003c341..3301284636e 100644 --- a/test/e2e/fixtures/fake-openai-compatible.ts +++ b/test/e2e/fixtures/fake-openai-compatible.ts @@ -38,6 +38,7 @@ export interface FakeOpenAiCompatibleServer { } export interface FakeOpenAiCompatibleServerOptions { + readonly additionalModels?: readonly string[]; readonly apiKey?: string; readonly chatContent?: string; readonly forbiddenMarkers?: readonly string[]; @@ -46,11 +47,15 @@ export interface FakeOpenAiCompatibleServerOptions { readonly requestCanaryMarker?: string; readonly host?: string; readonly maxModelLen?: number; + /** Advertise the bounded native fingerprint used by existing-server llama.cpp attachment. */ + readonly llamaCppFingerprint?: boolean; readonly model?: string; readonly port?: number; readonly progress: Pick & TestProgressCapability; readonly publicHost?: string; readonly requireAuth?: boolean; + /** Permit credentialless host preflight but validate any supplied bearer token. */ + readonly allowMissingAuth?: boolean; readonly requireAuthModels?: boolean; readonly responseText?: string; readonly toolCallOnCanary?: { readonly name: string; readonly arguments: string }; @@ -182,6 +187,7 @@ export async function startFakeOpenAiCompatibleServer( PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", NEMOCLAW_FAKE_OPENAI_API_KEY: options.apiKey ?? "", + NEMOCLAW_FAKE_OPENAI_ADDITIONAL_MODELS: JSON.stringify(options.additionalModels ?? []), NEMOCLAW_FAKE_OPENAI_CHAT_CONTENT: options.chatContent ?? "ok", NEMOCLAW_FAKE_OPENAI_ENVIRONMENT_FILE: environmentFile, NEMOCLAW_FAKE_OPENAI_FORBIDDEN_MARKERS: JSON.stringify(options.forbiddenMarkers ?? []), @@ -190,12 +196,14 @@ export async function startFakeOpenAiCompatibleServer( NEMOCLAW_FAKE_OPENAI_REPLY_FROM_PROMPT: options.replyFromPrompt ? "1" : "0", NEMOCLAW_FAKE_OPENAI_MAX_MODEL_LEN: options.maxModelLen !== undefined ? String(options.maxModelLen) : "", + NEMOCLAW_FAKE_OPENAI_LLAMA_CPP_FINGERPRINT: options.llamaCppFingerprint ? "1" : "0", NEMOCLAW_FAKE_OPENAI_MODEL: options.model ?? "test-model", NEMOCLAW_FAKE_OPENAI_PORT: String(options.port ?? 0), NEMOCLAW_FAKE_OPENAI_PORT_FILE: portFile, NEMOCLAW_FAKE_OPENAI_REQUEST_CANARY_MARKER: options.requestCanaryMarker ?? "", NEMOCLAW_FAKE_OPENAI_REQUESTS_FILE: requestsFile, NEMOCLAW_FAKE_OPENAI_REQUIRE_AUTH: options.requireAuth ? "1" : "0", + NEMOCLAW_FAKE_OPENAI_ALLOW_MISSING_AUTH: options.allowMissingAuth ? "1" : "0", NEMOCLAW_FAKE_OPENAI_REQUIRE_AUTH_MODELS: options.requireAuthModels ? "1" : "0", NEMOCLAW_FAKE_OPENAI_RESPONSE_TEXT: options.responseText ?? options.chatContent ?? "ok", NEMOCLAW_FAKE_OPENAI_TOOL_CALL_ON_CANARY: JSON.stringify( diff --git a/test/e2e/fixtures/inference-routing-openclaw-native.ts b/test/e2e/fixtures/inference-routing-openclaw-native.ts new file mode 100644 index 00000000000..3ef028d8547 --- /dev/null +++ b/test/e2e/fixtures/inference-routing-openclaw-native.ts @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { getSandbox } from "../../../src/lib/state/registry.ts"; +import { ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS } from "../../../tools/e2e/onboard-timeout-contract.mts"; +import { sandboxAccessEnv } from "./clients/sandbox.ts"; +import type { E2ETargetFixtures } from "./e2e-test.ts"; +import { startFakeOpenAiCompatibleServer } from "./fake-openai-compatible.ts"; +import { + cleanupSandbox, + inferenceSandboxName, + onboardSandbox, + requireLivePrerequisites, +} from "../live/inference-routing-helpers.ts"; + +type NativeOpenClawContext = Pick< + E2ETargetFixtures, + "artifacts" | "cleanup" | "host" | "progress" | "runtimeProvider" | "sandbox" +>; + +// The real OpenClaw process must consume its scoped native-local attachment. +// llama.cpp exercises authenticated attachment; vLLM exercises sentinel auth. +export async function onboardNativeOpenClaw( + authenticated: boolean, + { artifacts, cleanup, host, progress, runtimeProvider, sandbox }: NativeOpenClawContext, +) { + await requireLivePrerequisites(host, runtimeProvider); + const owner = inferenceSandboxName(authenticated ? "e2e-oc-auth" : "e2e-oc-none"); + const model = "nemoclaw-openclaw-native-local"; + const switchedModel = "nemoclaw-openclaw-native-local-switched"; + const apiKey = authenticated ? "sk-openclaw-native-TEST-NOT-A-REAL-VALUE" : "dummy"; + const fake = await startFakeOpenAiCompatibleServer({ + apiKey, + model, + additionalModels: authenticated ? [switchedModel] : [], + chatContent: "PONG", + host: "0.0.0.0", + port: authenticated ? 8081 : 8000, + publicHost: "host.openshell.internal", + requireAuth: true, + allowMissingAuth: !authenticated, + requireAuthModels: authenticated, + llamaCppFingerprint: authenticated, + progress, + }); + cleanup.add(`close ${owner} endpoint`, async () => { + try { + await artifacts.writeJson(`${owner}-requests.json`, fake.requests()); + } finally { + await fake.close(); + } + }); + cleanup.add(`remove ${owner}`, () => cleanupSandbox(host, sandbox, owner, { strict: true })); + await cleanupSandbox(host, sandbox, owner); + await artifacts.target.declare({ + id: `openclaw-native-local-${authenticated ? "authenticated" : "credentialless"}`, + contract: [ + "OpenClaw consumes its native local endpoint after onboarding", + ...(authenticated + ? [ + "rebuild and restart preserve the attachment", + "an unattached sibling cannot reach the endpoint", + "the raw credential is absent from sandbox observations", + ] + : ["credentialless vLLM uses sentinel authentication"]), + ], + model, + switchedModel, + }); + const onboard = await onboardSandbox( + artifacts, + owner, + { + NEMOCLAW_AGENT: "openclaw", + NEMOCLAW_PROVIDER: authenticated ? "llama-cpp" : "vllm", + NEMOCLAW_MODEL: model, + ...(authenticated ? { NEMOCLAW_LLAMACPP_LOCAL_TOKEN: apiKey } : {}), + }, + [apiKey], + `${owner}-onboard`, + progress, + ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS, + ); + return { + owner, + model, + switchedModel, + apiKey, + fake, + onboard, + attachment: getSandbox(owner)?.nativeLocalProviderAttachment, + }; +} + +export async function requestNativeOpenClaw( + owner: string, + apiKey: string, + fake: Awaited>, + host: NativeOpenClawContext["host"], + model = "nemoclaw-openclaw-native-local", +) { + const requestOffset = fake.requests().length; + const turn = await host.nemoclaw( + [ + owner, + "agent", + "--agent", + "main", + "--json", + "--session-id", + `${owner}-${Date.now()}`, + "-m", + "Reply with exactly one word: PONG", + ], + { + artifactName: `${owner}-turn`, + env: sandboxAccessEnv(), + timeoutMs: 5 * 60_000, + redactionValues: [apiKey], + }, + ); + const requests = fake + .requests() + .slice(requestOffset) + .filter((request) => request.model === model); + return { turn, requests }; +} diff --git a/test/e2e/lib/fake-openai-compatible-api.mts b/test/e2e/lib/fake-openai-compatible-api.mts index b1809555935..7de0d0c5d20 100755 --- a/test/e2e/lib/fake-openai-compatible-api.mts +++ b/test/e2e/lib/fake-openai-compatible-api.mts @@ -14,6 +14,16 @@ const logFile = process.env.NEMOCLAW_FAKE_OPENAI_LOG_FILE || ""; const requestsFile = process.env.NEMOCLAW_FAKE_OPENAI_REQUESTS_FILE || ""; const environmentFile = process.env.NEMOCLAW_FAKE_OPENAI_ENVIRONMENT_FILE || ""; const model = process.env.NEMOCLAW_FAKE_OPENAI_MODEL || "test-model"; +const additionalModels = (() => { + try { + const value = JSON.parse(process.env.NEMOCLAW_FAKE_OPENAI_ADDITIONAL_MODELS || "[]"); + return Array.isArray(value) + ? value.filter((entry): entry is string => typeof entry === "string") + : []; + } catch { + return []; + } +})(); // Optional runtime context window advertised on /v1/models, mirroring vLLM's // max_model_len so onboarding can probe a real endpoint's context (#6177). const maxModelLen = (() => { @@ -22,10 +32,12 @@ const maxModelLen = (() => { })(); const apiKey = process.env.NEMOCLAW_FAKE_OPENAI_API_KEY || ""; const requireAuth = process.env.NEMOCLAW_FAKE_OPENAI_REQUIRE_AUTH === "1"; +const allowMissingAuth = process.env.NEMOCLAW_FAKE_OPENAI_ALLOW_MISSING_AUTH === "1"; // Opt-in auth enforcement on GET /v1/models specifically (real vLLM launched // with --api-key gates it). Separate from requireAuth so existing tests, whose // readiness probe hits /v1/models unauthenticated, keep working. See #6177. const requireAuthModels = process.env.NEMOCLAW_FAKE_OPENAI_REQUIRE_AUTH_MODELS === "1"; +const llamaCppFingerprint = process.env.NEMOCLAW_FAKE_OPENAI_LLAMA_CPP_FINGERPRINT === "1"; const chatContent = process.env.NEMOCLAW_FAKE_OPENAI_CHAT_CONTENT || "ok"; const responseText = process.env.NEMOCLAW_FAKE_OPENAI_RESPONSE_TEXT || chatContent; const replyFromPrompt = process.env.NEMOCLAW_FAKE_OPENAI_REPLY_FROM_PROMPT === "1"; @@ -117,7 +129,7 @@ function sendResponseSse(res: ServerResponse, text: string): void { } function isAuthOk(req: IncomingMessage): boolean { - if (!requireAuth) return true; + if (!requireAuth || (allowMissingAuth && req.headers.authorization === undefined)) return true; return req.headers.authorization === `Bearer ${apiKey}`; } @@ -229,6 +241,39 @@ function requestedCanaryToolCall(payload: JsonObject, raw: Buffer): JsonObject | const server = createServer(async (req, res) => { const path = requestPath(req); + if ( + llamaCppFingerprint && + req.method === "GET" && + ["/health", "/props", "/metrics"].includes(path) + ) { + const authorized = isAuthOk(req); + recordRequest({ + method: "GET", + path, + bodyBytes: 0, + auth: authorized ? "ok" : "missing", + authorizationSent: Boolean(req.headers.authorization), + }); + if (!authorized) { + sendJson(res, 401, { error: { message: "missing bearer credential" } }); + } else if (path === "/health") { + sendJson(res, 200, { status: "ok" }); + } else if (path === "/props") { + sendJson(res, 200, { + model_path: "/models/fake.gguf", + model_alias: + new URL(req.url || "/props", "http://fake-openai-compatible.local").searchParams.get( + "model", + ) || model, + total_slots: 1, + default_generation_settings: { params: {} }, + }); + } else { + sendJson(res, 501, { error: { type: "not_supported_error" } }); + } + return; + } + if (req.method === "GET" && ["/v1/models", "/models"].includes(path)) { const modelsAuthOk = !requireAuthModels || req.headers.authorization === `Bearer ${apiKey}`; log(`GET ${path} auth=${modelsAuthOk ? "ok" : "missing"}`); @@ -248,9 +293,21 @@ const server = createServer(async (req, res) => { sendJson(res, 401, { error: { message: "missing bearer credential" } }); return; } - const modelEntry: JsonObject = { id: model, object: "model" }; - if (maxModelLen !== null) modelEntry.max_model_len = maxModelLen; - sendJson(res, 200, { object: "list", data: [modelEntry] }); + const entries = [model, ...additionalModels].map((servedModel) => { + const modelEntry: JsonObject = { id: servedModel, object: "model" }; + if (llamaCppFingerprint) { + modelEntry.owned_by = "llamacpp"; + modelEntry.meta = { + n_vocab: 32000, + n_ctx: maxModelLen ?? 8192, + n_ctx_train: 8192, + n_embd: 4096, + }; + } + if (maxModelLen !== null) modelEntry.max_model_len = maxModelLen; + return modelEntry; + }); + sendJson(res, 200, { object: "list", data: entries }); return; } diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 7e3a6c738cb..99368533daa 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -1,14 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -/** - * Preserve the script's real user-visible boundary: install.sh onboards an - * OpenClaw sandbox, `nemoclaw inference set` switches the running route, then - * 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. - */ +// Hosted switching and native local routing share the OpenClaw live contract. import fs from "node:fs"; import http, { type Server } from "node:http"; @@ -26,6 +19,7 @@ import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText, shellQuote } from "../fixtures/clients/command.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import { + sandboxAccessEnv, type SandboxClient, trustedSandboxShellScript, validateSandboxName, @@ -38,10 +32,12 @@ import { requireCompatibleAnthropicProviderAbsent, } from "../fixtures/compatible-anthropic-switch.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; -import type { FakeOpenAiCompatibleServer } from "../fixtures/fake-openai-compatible.ts"; +import { + startFakeOpenAiCompatibleServer, + type FakeOpenAiCompatibleServer, +} from "../fixtures/fake-openai-compatible.ts"; import { requireHostedInferenceConfig } from "../fixtures/hosted-inference.ts"; import { selectedE2eManagedImageReference } from "../fixtures/managed-image-receipt.ts"; -import type { TestProgress } from "../fixtures/progress.ts"; import { inferenceResponseModel, inferenceSetAttemptCount, @@ -60,7 +56,6 @@ import { classifyExhaustedPostSwitchEvidence, classifyOpenClawPostSwitchInferenceAttempt, classifyUnavailableInitialProviderEvidence, - MOCK_BASELINE_MODEL, mockBaselineInference, parseOpenClawGatewayModelRun, startMockOpenClawBaselineProvider, @@ -73,6 +68,26 @@ import { requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; +import { + ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS, + ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS, + OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS, +} from "../../../tools/e2e/onboard-timeout-contract.mts"; +import { + onboardNativeOpenClaw, + requestNativeOpenClaw, +} from "../fixtures/inference-routing-openclaw-native.ts"; +import { assertAgentExecutionSucceeded } from "./gpu-e2e-helpers.ts"; +import { hostedCredentialScanCommand } from "./inference-routing-credential-scan.ts"; +import { + cleanupSandbox, + expectOnboardSuccess, + inferenceSandboxName, + onboardSandbox, +} from "./inference-routing-helpers.ts"; + +process.env.NEMOCLAW_CLI_BIN ??= CLI_ENTRYPOINT; + 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; @@ -103,59 +118,15 @@ interface AnthropicResponse { content?: Array<{ text?: unknown }>; } -interface OpenClawModelConfig { - id?: unknown; - name?: unknown; - contextWindow?: unknown; - maxTokens?: unknown; -} - -interface OpenClawConfig { - agents?: { - defaults?: { - model?: { - primary?: unknown; - }; - }; - }; - models?: { - providers?: Record< - string, - { - baseUrl?: unknown; - apiKey?: unknown; - api?: unknown; - models?: OpenClawModelConfig[]; - } - >; - }; -} - interface SandboxRegistry { sandboxes?: Record< string, { - provider?: unknown; - model?: unknown; - endpointUrl?: unknown; - credentialEnv?: unknown; - preferredInferenceApi?: unknown; - nimContainer?: unknown; nativeNvidiaProviderAttachment?: unknown; } >; } -interface OnboardSession { - sandboxName?: unknown; - provider?: unknown; - model?: unknown; - endpointUrl?: unknown; - credentialEnv?: unknown; - preferredInferenceApi?: unknown; - nimContainer?: unknown; -} - interface MockAnthropicProvider { endpointUrl: string; requests(): readonly MockAnthropicRequest[]; @@ -170,70 +141,6 @@ interface MockAnthropicRequest { toolCount: number | null; } -function proveMockBaselineAuthentication( - baseline: Pick | undefined, - sandbox: SandboxClient, - home: string, - artifacts: { writeJson(path: string, value: unknown): Promise }, -): Promise { - return baseline - ? proveSelectedMockBaselineAuthentication(baseline, sandbox, home, artifacts) - : Promise.resolve(expect(baseline).toBeUndefined()); -} - -async function proveSelectedMockBaselineAuthentication( - baseline: Pick, - sandbox: SandboxClient, - home: string, - artifacts: { writeJson(path: string, value: unknown): Promise }, -): Promise { - // Ignore incidental onboarding traffic. The fixture appends its ledger row - // before responding, so this awaited POST is the publication barrier for the - // requests sliced from this offset. - const requestOffset = baseline.requests().length; - const payload = { - model: MOCK_BASELINE_MODEL, - messages: [{ role: "user", content: "reply with OK" }], - max_tokens: 8, - }; - const probe = await sandboxShell( - sandbox, - home, - SWITCH_NATIVE_CUSTOM - ? `${nativeHostedAuthHeaderScript({ credentialEnv: "COMPATIBLE_API_KEY", api: "openai-completions" })}; curl -fsS --max-time 60 ${shellQuote(`${baseline.baseUrl}/chat/completions`)} -H "$AUTH_HEADER" -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null` - : `curl -fsS --max-time 60 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null`, - { - artifactName: "baseline-explicit-authenticated-inference-post", - timeoutMs: 90_000, - }, - ); - const requests = baseline.requests().slice(requestOffset); - const artifactName = "baseline-explicit-authenticated-inference-requests.json"; - const phase = "install and onboard baseline OpenClaw"; - const requestEvidence = requests - .slice(0, 20) - .map(({ auth, method, model, path }) => ({ auth, method, model, path })); - await artifacts.writeJson(artifactName, { - phase, - requestCount: requests.length, - requests: requestEvidence, - truncated: requests.length > requestEvidence.length, - }); - expect(probe.exitCode, `${phase}: explicit baseline inference failed; see ${artifactName}`).toBe( - 0, - ); - const expectedRequest = expect.objectContaining({ - auth: "ok", - method: "POST", - model: MOCK_BASELINE_MODEL, - path: "/v1/chat/completions", - }); - expect( - requests, - `${phase}: explicit verification probe did not reach the authenticated fixture; see ${artifactName}`, - ).toContainEqual(expectedRequest); -} - function parsePortEnv(name: string, fallback: number): number { const raw = process.env[name]; if (!raw) return fallback; @@ -432,7 +339,6 @@ async function startMockAnthropicProvider(host: HostCliClient): Promise { - const registryPath = path.join(home, ".nemoclaw", "sandboxes.json"); - const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")) as SandboxRegistry; - const sandbox = registry.sandboxes?.[SANDBOX_NAME]; - expect(sandbox?.provider).toBe(SWITCH_PROVIDER); - expect(sandbox?.model).toBe(SWITCH_MODEL); - expect(sandbox?.nimContainer).toBeNull(); - switch (SWITCH_PROVIDER) { - case "compatible-endpoint": - expect(sandbox?.endpointUrl).toBeNull(); - expect(sandbox?.credentialEnv).toBeNull(); - expect(sandbox?.preferredInferenceApi).toBe("openai-completions"); - break; - case "compatible-anthropic-endpoint": - expect(sandbox?.endpointUrl).toBe( - process.env.NEMOCLAW_SWITCH_ENDPOINT_URL ?? options.mockProvider?.endpointUrl, - ); - expect(sandbox?.credentialEnv).toBe("COMPATIBLE_ANTHROPIC_API_KEY"); - expect(sandbox?.preferredInferenceApi).toBe("anthropic-messages"); - break; - default: - expect(sandbox?.endpointUrl).toBeNull(); - expect(sandbox?.credentialEnv).toBe(sandbox?.provider === SWITCH_PROVIDER ? null : undefined); - expect(sandbox?.preferredInferenceApi).toBeNull(); - } - - const sessionPath = path.join(home, ".nemoclaw", "onboard-session.json"); - const session = JSON.parse(fs.readFileSync(sessionPath, "utf8")) as OnboardSession; - expect(Object.keys(session).length, "onboard session is empty").toBeGreaterThan(0); - expect(session.sandboxName).toBe(SANDBOX_NAME); - expect(session.provider).toBe(SWITCH_PROVIDER); - expect(session.model).toBe(SWITCH_MODEL); - expect(session.nimContainer).toBeNull(); switch (SWITCH_PROVIDER) { - case "compatible-endpoint": - expect(session.preferredInferenceApi).toBe("openai-completions"); - break; - case "compatible-anthropic-endpoint": - expect(session.preferredInferenceApi).toBe("anthropic-messages"); - break; - case PUBLIC_NVIDIA_SWITCH_PROVIDER: + case PUBLIC_NVIDIA_SWITCH_PROVIDER: { + const registryPath = path.join(home, ".nemoclaw", "sandboxes.json"); + const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")) as SandboxRegistry; 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", - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, - ].join("\n"), - ); - break; + await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "native-nvidia-provider-attachment-after-switch", + env: commandEnv(home), + logicalProvider: SWITCH_PROVIDER, + receipt: registry.sandboxes?.[SANDBOX_NAME]?.nativeNvidiaProviderAttachment, + sandbox, + sandboxName: SANDBOX_NAME, + }), + ).toBe(PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE); + } } } -async function readAndAssertOpenClawConfig( +// Source tests own serialized config and registry/session field values. This +// live owner retains the actual configuration read and real gateway requests. +async function recordOpenClawConfig( sandbox: SandboxClient, home: string, expected: { @@ -631,7 +491,7 @@ async function readAndAssertOpenClawConfig( nativeNvidia?: boolean; nativeCustomEndpoint?: string; }, -): Promise { +): Promise { const configResult = await readOpenClawConfig(sandbox, SANDBOX_NAME, { nativeNvidia: expected.nativeNvidia, nativeCustomApi: expected.nativeCustomEndpoint ? expected.inferenceApi : undefined, @@ -640,63 +500,6 @@ async function readAndAssertOpenClawConfig( timeoutMs: COMMAND_TIMEOUT_MS, }); expect(configResult.exitCode, resultText(configResult)).toBe(0); - const config = JSON.parse(configResult.stdout) as OpenClawConfig; - const expectedProviderKey = - expected.inferenceApi === "anthropic-messages" ? "anthropic" : "inference"; - const expectedPrimary = `${expectedProviderKey}/${expected.model}`; - const provider = config.models?.providers?.[expectedProviderKey]; - const selectedModel = provider?.models?.find((entry) => entry.id === expected.model); - - expect(config.agents?.defaults?.model?.primary).toBe(expectedPrimary); - expect(provider?.baseUrl).toBe( - expected.nativeCustomEndpoint ?? - (expected.nativeNvidia - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : expected.inferenceApi === "anthropic-messages" - ? "https://inference.local" - : "https://inference.local/v1"), - ); - expect(provider?.apiKey).toBe( - expected.nativeNvidia || expected.nativeCustomEndpoint ? undefined : "unused", - ); - expect(provider?.api).toBe(expected.inferenceApi); - expect(selectedModel?.name).toBe(expectedPrimary); - return selectedModel; -} - -async function assertOpenClawConfig( - sandbox: SandboxClient, - home: string, - expected: { - model: string; - inferenceApi: string; - artifactName: string; - nativeNvidia?: boolean; - nativeCustomEndpoint?: string; - }, -): Promise { - const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); - expect( - expected.inferenceApi === "anthropic-messages" - ? typeof selectedModel?.maxTokens === "number" && selectedModel.maxTokens > 0 - : selectedModel?.maxTokens === undefined, - ).toBe(true); -} - -async function assertInitialOpenClawConfig( - sandbox: SandboxClient, - home: string, - expected: { - model: string; - inferenceApi: string; - artifactName: string; - nativeNvidia?: boolean; - nativeCustomEndpoint?: string; - }, -): Promise { - const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); - expect(selectedModel?.contextWindow).toBeUndefined(); - expect(selectedModel?.maxTokens).toBeUndefined(); } function httpStatusFromResponse(response: string): string { @@ -996,66 +799,6 @@ exit "$rc" ); } -async function runInitialRouteLifecycle(options: { - nativeCustomEndpoint?: string; - artifacts: ArtifactSink; - baselineProvider?: Pick; - home: string; - host: HostCliClient; - model: string; - progress: Pick; - redactionValues: string[]; - sandbox: SandboxClient; -}): Promise { - const verify = async (artifactSuffix: string): Promise => { - await assertInitialOpenClawConfig(options.sandbox, options.home, { - model: options.model, - inferenceApi: "openai-completions", - artifactName: `read-openclaw-initial-route-${artifactSuffix}`, - nativeCustomEndpoint: options.nativeCustomEndpoint, - }); - await checkOpenClawGatewayInference( - options.host, - options.home, - options.artifacts, - { - model: options.model, - inferenceApi: "openai-completions", - artifactName: `openclaw-gateway-inference-initial-route-${artifactSuffix}`, - phase: `prove initial custom-image route ${artifactSuffix}`, - }, - undefined, - options.baselineProvider, - ); - }; - const requireLifecycleSuccess = (result: ShellProbeResult): void => { - expect(result.exitCode, resultText(result)).toBe(0); - }; - - options.progress.phase("prove the selected route after custom-image onboarding"); - await verify("after-onboard"); - - options.progress.phase("prove the selected route after gateway restart"); - const restart = await options.host.nemoclaw([SANDBOX_NAME, "gateway", "restart"], { - artifactName: "restart-openclaw-initial-custom-route", - env: commandEnv(options.home), - redactionValues: options.redactionValues, - timeoutMs: COMMAND_TIMEOUT_MS, - }); - requireLifecycleSuccess(restart); - await verify("after-restart"); - - options.progress.phase("prove the selected route after rebuild"); - const rebuild = await options.host.nemoclaw([SANDBOX_NAME, "rebuild", "--yes", "--verbose"], { - artifactName: "rebuild-openclaw-initial-custom-route", - env: commandEnv(options.home), - redactionValues: options.redactionValues, - timeoutMs: INSTALL_TIMEOUT_MS, - }); - requireLifecycleSuccess(rebuild); - await verify("after-rebuild"); -} - // The pure reply-matching and mock-baseline-config assertions that previously // lived here as test(...) blocks (which only run under the opt-in live lane) // are covered in the fast e2e-support project instead: @@ -1163,25 +906,16 @@ test( "the selected runtime is available and an authenticated compatible baseline endpoint is staged", "nemoclaw onboard --non-interactive --from onboards an OpenClaw sandbox from a custom Dockerfile", "fresh custom-image onboarding replaces the baked primary route with the selected model", - "stale baked context-window and output-token limits are absent after gateway restart and rebuild", "the selected route completes real OpenClaw gateway inference before and after both lifecycle operations", "when staged, the authenticated baseline fixture receives each selected-model OpenClaw gateway request", - "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", "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 returns PONG from the switched model", "OpenClaw gateway model inference answers through the switched route without agent tools", ], }); - expect( - fs.existsSync(CLI_ENTRYPOINT), - "run `npm run build:cli` before live repo CLI targets", - ).toBe(true); - await runtimeProvider.requireAvailable({ artifactName: "prereq-runtime-info-openclaw-inference-switch", scenarioLabel: "OpenClaw inference switch", @@ -1281,7 +1015,6 @@ test( skip(unavailable.reason); } expect(onboard.exitCode, onboardText).toBe(0); - await proveMockBaselineAuthentication(baselineProvider, sandbox, home, artifacts); await approveOpenClawAdminScope( host, @@ -1291,17 +1024,53 @@ test( redactionValues, false, ); - await runInitialRouteLifecycle({ - nativeCustomEndpoint: nativeBaselineHost ? baseline.endpointUrl : undefined, - artifacts, - baselineProvider, - home, - host, - model: baseline.model, - progress, - redactionValues, - sandbox, + const verifyInitialRoute = async (artifactSuffix: string): Promise => { + await recordOpenClawConfig(sandbox, home, { + model: baseline.model, + inferenceApi: "openai-completions", + artifactName: `read-openclaw-initial-route-${artifactSuffix}`, + nativeCustomEndpoint: nativeBaselineHost ? baseline.endpointUrl : undefined, + }); + await checkOpenClawGatewayInference( + host, + home, + artifacts, + { + model: baseline.model, + inferenceApi: "openai-completions", + artifactName: `openclaw-gateway-inference-initial-route-${artifactSuffix}`, + phase: `prove initial custom-image route ${artifactSuffix}`, + }, + undefined, + baselineProvider, + ); + }; + const requireLifecycleSuccess = (result: ShellProbeResult): void => { + expect(result.exitCode, resultText(result)).toBe(0); + }; + + progress.phase("prove the selected route after custom-image onboarding"); + await verifyInitialRoute("after-onboard"); + + progress.phase("prove the selected route after gateway restart"); + const restart = await host.nemoclaw([SANDBOX_NAME, "gateway", "restart"], { + artifactName: "restart-openclaw-initial-custom-route", + env: commandEnv(home), + redactionValues: redactionValues, + timeoutMs: COMMAND_TIMEOUT_MS, + }); + requireLifecycleSuccess(restart); + await verifyInitialRoute("after-restart"); + + progress.phase("prove the selected route after rebuild"); + const rebuild = await host.nemoclaw([SANDBOX_NAME, "rebuild", "--yes", "--verbose"], { + artifactName: "rebuild-openclaw-initial-custom-route", + env: commandEnv(home), + redactionValues: redactionValues, + timeoutMs: INSTALL_TIMEOUT_MS, }); + requireLifecycleSuccess(rebuild); + await verifyInitialRoute("after-rebuild"); progress.phase("prepare the switched provider and endpoint"); if (SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1") { @@ -1328,10 +1097,6 @@ test( redactionValues, false, ); - const apiFamilyChanges = SWITCH_MOCK_ANTHROPIC === "1"; - expect(SWITCH_INFERENCE_API).toBe( - apiFamilyChanges ? "anthropic-messages" : "openai-completions", - ); const pidBefore = await openclawGatewayPid(sandbox, home); const switchResult = await runOpenClawInferenceSetWithRetry( host, @@ -1342,12 +1107,6 @@ test( artifacts, ); expect(switchResult.exitCode, resultText(switchResult)).toBe(0); - expect( - resultText(switchResult).includes( - `Restarting the OpenClaw gateway in '${SANDBOX_NAME}' to apply the updated inference configuration`, - ), - `managed config restart marker mismatch: ${resultText(switchResult)}`, - ).toBe(true); const pidAfter = await openclawGatewayPid(sandbox, home); const gatewayPidStable = pidBefore && pidAfter ? pidBefore === pidAfter : null; @@ -1367,14 +1126,14 @@ test( const routeState = JSON.parse(route.stdout) as { provider?: unknown; model?: unknown }; expect(routeState.provider).toBe(SWITCH_PROVIDER); expect(routeState.model).toBe(SWITCH_MODEL); - await assertOpenClawConfig(sandbox, home, { + await recordOpenClawConfig(sandbox, home, { model: SWITCH_MODEL, inferenceApi: SWITCH_INFERENCE_API, artifactName: "read-openclaw-config-after-inference-switch", nativeNvidia: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, nativeCustomEndpoint: SWITCH_NATIVE_CUSTOM ? switchBinding!.endpointUrl : undefined, }); - await assertRegistryAndSession(home, { mockProvider, sandbox }); + await verifyNativeNvidiaAttachmentAfterSwitch(home, sandbox); progress.phase("prove sandbox and OpenClaw gateway inference"); const inference = await checkSandboxInference( @@ -1430,7 +1189,6 @@ test( runtimeProviderAvailable: true, customImageOnboardingCompleted: onboard.exitCode === 0, customImageInitialRouteSelected: true, - customImageModelMetadataPreserved: true, customImageRouteSurvivedGatewayRestart: true, customImageRouteSurvivedRebuild: true, customImageGatewayReachedBaselineFixture: baselineProvider ? true : null, @@ -1438,8 +1196,6 @@ test( gatewayRestartExpected: true, gatewayPidStable, routeChecked: true, - configChecked: true, - registryAndSessionChecked: true, inferenceLocalPong: true, inferenceLocalModelMatched: true, openClawGatewayInferencePong: true, @@ -1447,3 +1203,233 @@ test( }); }, ); + +test( + "TC-INF-17 OpenClaw uses authenticated native local inference after rebuild and restart (#12975)", + { + timeout: OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS, + meta: { + e2ePhases: [ + "confirm live inference prerequisites", + "onboard native OpenClaw owner", + "rebuild native OpenClaw owner", + "restart native OpenClaw owner", + "onboard shared-route sibling", + "record shared route before model switch", + "switch native OpenClaw model", + "verify shared route unchanged", + "request inference through OpenClaw", + "check credential isolation", + "verify owner reachability", + "verify sibling denial", + ], + }, + }, + async ({ artifacts, cleanup, host, progress, runtimeProvider, sandbox }) => { + progress.phase("onboard native OpenClaw owner"); + const selected = await onboardNativeOpenClaw(true, { + artifacts, + cleanup, + host, + progress, + runtimeProvider, + sandbox, + }); + const { owner, model, switchedModel, apiKey, fake, onboard, attachment } = selected; + expectOnboardSuccess(onboard, `${owner} onboard`); + progress.phase("rebuild native OpenClaw owner"); + const rebuild = await host.nemoclaw([owner, "rebuild", "--yes", "--verbose"], { + artifactName: `${owner}-rebuild`, + env: { ...buildAvailabilityProbeEnv(), NEMOCLAW_LLAMACPP_LOCAL_TOKEN: apiKey }, + redactionValues: [apiKey], + timeoutMs: 20 * 60_000, + }); + expect(rebuild.exitCode, resultText(rebuild)).toBe(0); + progress.phase("restart native OpenClaw owner"); + const stop = await host.nemoclaw([owner, "stop"], { + artifactName: `${owner}-stop`, + env: sandboxAccessEnv(), + timeoutMs: 120_000, + }); + expect(stop.exitCode, resultText(stop)).toBe(0); + const start = await host.nemoclaw([owner, "start"], { + artifactName: `${owner}-start`, + env: sandboxAccessEnv(), + timeoutMs: 120_000, + }); + expect(start.exitCode, resultText(start)).toBe(0); + progress.phase("onboard shared-route sibling"); + const sibling = inferenceSandboxName("e2e-oc-peer"); + const peerEndpoint = await startFakeOpenAiCompatibleServer({ + apiKey, + model, + host: "0.0.0.0", + publicHost: "host.openshell.internal", + requireAuth: true, + progress, + }); + cleanup.add(`close ${sibling} endpoint`, () => peerEndpoint.close()); + cleanup.add(`remove ${sibling}`, () => + cleanupSandbox(host, sandbox, sibling, { strict: true }), + ); + await cleanupSandbox(host, sandbox, sibling); + const peer = await onboardSandbox( + artifacts, + sibling, + { + NEMOCLAW_AGENT: "openclaw", + NEMOCLAW_PROVIDER: "custom", + NEMOCLAW_MODEL: model, + NEMOCLAW_ENDPOINT_URL: peerEndpoint.baseUrl, + NEMOCLAW_PREFERRED_API: "openai-completions", + COMPATIBLE_API_KEY: apiKey, + }, + [apiKey], + `${sibling}-onboard`, + progress, + ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS, + ); + expectOnboardSuccess(peer, `${sibling} onboard`); + progress.phase("record shared route before model switch"); + const sharedBefore = await sandbox.openshell(["inference", "get", "-g", "nemoclaw"], { + artifactName: `${owner}-shared-route-before-switch`, + env: buildAvailabilityProbeEnv(), + timeoutMs: 30_000, + }); + expect(sharedBefore.exitCode, resultText(sharedBefore)).toBe(0); + progress.phase("switch native OpenClaw model"); + const switched = await host.nemoclaw( + ["inference", "set", "--provider", "llama-cpp", "--model", switchedModel, "--sandbox", owner], + { + artifactName: `${owner}-model-switch`, + env: { ...buildAvailabilityProbeEnv(), NEMOCLAW_LLAMACPP_LOCAL_TOKEN: apiKey }, + redactionValues: [apiKey], + timeoutMs: 5 * 60_000, + }, + ); + expect(switched.exitCode, resultText(switched)).toBe(0); + progress.phase("verify shared route unchanged"); + const sharedAfter = await sandbox.openshell(["inference", "get", "-g", "nemoclaw"], { + artifactName: `${owner}-shared-route-after-switch`, + env: buildAvailabilityProbeEnv(), + timeoutMs: 30_000, + }); + expect(sharedAfter.exitCode).toBe(sharedBefore.exitCode); + expect(sharedAfter.stdout).toBe(sharedBefore.stdout); + progress.phase("request inference through OpenClaw"); + const { turn, requests } = await requestNativeOpenClaw( + owner, + apiKey, + fake, + host, + switchedModel, + ); + expect(turn.exitCode, resultText(turn)).toBe(0); + assertAgentExecutionSucceeded(turn.stdout, "inference", switchedModel); + expect( + requests.some((request) => request.path === "/v1/chat/completions" && request.auth === "ok"), + ).toBe(true); + progress.phase("check credential isolation"); + const scan = await sandbox.exec(owner, hostedCredentialScanCommand(apiKey), { + artifactName: `${owner}-credential-scan`, + env: sandboxAccessEnv(), + timeoutMs: 60_000, + redactionValues: [apiKey], + }); + expect(scan.exitCode, resultText(scan)).toBe(0); + expect(JSON.parse(scan.stdout)).toMatchObject({ + environmentClean: true, + processesClean: true, + sampledFilesClean: true, + canaryDetected: true, + }); + progress.phase("verify owner reachability"); + const beforeOwnerProbe = fake.requests().length; + const ownerProbe = await sandbox.exec( + owner, + [ + "curl", + "--fail", + "--max-time", + "15", + "--header", + `Authorization: Bearer ${apiKey}`, + `${attachment!.endpointUrl}/models`, + ], + { + artifactName: `${owner}-owner-reachability`, + env: sandboxAccessEnv(), + timeoutMs: 30_000, + redactionValues: [apiKey], + }, + ); + expect(ownerProbe.exitCode, resultText(ownerProbe)).toBe(0); + expect( + fake + .requests() + .slice(beforeOwnerProbe) + .some((request) => request.path.endsWith("/models") && request.auth === "ok"), + ).toBe(true); + progress.phase("verify sibling denial"); + const beforeDenied = fake.requests().length; + const denied = await sandbox.exec( + sibling, + [ + "curl", + "--fail", + "--max-time", + "15", + "--header", + `Authorization: Bearer ${apiKey}`, + `${attachment!.endpointUrl}/models`, + ], + { + artifactName: `${sibling}-owner-denial`, + env: sandboxAccessEnv(), + timeoutMs: 30_000, + redactionValues: [apiKey], + }, + ); + expect(denied.exitCode).not.toBe(0); + expect(fake.requests()).toHaveLength(beforeDenied); + }, +); + +test( + "TC-INF-18 OpenClaw uses a credentialless native local vLLM endpoint (#12975)", + { + timeout: ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS, + meta: { + e2ePhases: [ + "confirm live inference prerequisites", + "onboard native OpenClaw owner", + "request inference through OpenClaw", + ], + }, + }, + async ({ artifacts, cleanup, host, progress, runtimeProvider, sandbox }) => { + progress.phase("onboard native OpenClaw owner"); + const { owner, apiKey, fake, onboard } = await onboardNativeOpenClaw(false, { + artifacts, + cleanup, + host, + progress, + runtimeProvider, + sandbox, + }); + expectOnboardSuccess(onboard, `${owner} onboard`); + progress.phase("request inference through OpenClaw"); + const { turn, requests } = await requestNativeOpenClaw(owner, apiKey, fake, host); + expect(turn.exitCode, resultText(turn)).toBe(0); + assertAgentExecutionSucceeded(turn.stdout, "inference", "nemoclaw-openclaw-native-local"); + expect( + requests.some( + (request) => + request.path === "/v1/chat/completions" && + request.auth === "ok" && + request.authorizationSent === true, + ), + ).toBe(true); + expect(requests.every((request) => request.auth === "ok")).toBe(true); + }, +); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index ba0c41505a2..b3b27565813 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -60,6 +60,7 @@ "src/lib/inference/llama-cpp/managed-selection.test.ts", "src/lib/inference/llama-cpp/managed-installer.test.ts", "src/lib/onboard/setup-nim-flow.test.ts", + "test/onboarding/onboard-host-local-inference-routing.test.ts", "test/security/admin-approval-helper.test.ts", "test/e2e/support/pr-self-hosted-llama-selector.test.ts", "test/e2e/support/onboard-timeout-contract.test.ts", @@ -188,6 +189,7 @@ ], "fast": [ "src/lib/inference/native-local.test.ts", + "test/onboarding/onboard-host-local-inference-routing.test.ts", "test/agents/deepagents/langchain-deepagents-code-config.test.ts", "nemoclaw/src/shared/openshell-gateway-health-sdk.test.ts", "nemoclaw/src/blueprint/runner.test.ts", @@ -850,6 +852,7 @@ { "live": "test/e2e/live/openclaw-inference-switch.test.ts", "liveSources": [ + "test/e2e/fixtures/inference-routing-openclaw-native.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", "test/e2e/live/openclaw-admin-scope.ts", "test/e2e/live/public-nvidia-switch-provider.ts", @@ -859,6 +862,11 @@ "test/e2e/fixtures/managed-image-receipt.ts" ], "fast": [ + "src/lib/inference/native-local.test.ts", + "src/lib/actions/inference-set-openclaw-native-local.test.ts", + "src/lib/actions/inference-set-openclaw-run.test.ts", + "test/onboarding/onboard-host-local-inference-routing.test.ts", + "test/e2e/support/onboard-timeout-contract.test.ts", "src/lib/actions/inference-get.test.ts", "src/lib/actions/inference-set-patch-openclaw.test.ts", "src/lib/actions/inference-set-compatible-provider.test.ts", diff --git a/test/e2e/support/hosted-inference.test.ts b/test/e2e/support/hosted-inference.test.ts index 34647f39d12..bcbaedcef19 100644 --- a/test/e2e/support/hosted-inference.test.ts +++ b/test/e2e/support/hosted-inference.test.ts @@ -644,6 +644,51 @@ printf '{"data":[]}' }); }); + it.each([ + [false, undefined, 401], + [true, undefined, 200], + [false, "Bearer dummy", 200], + [true, "Bearer dummy", 200], + [false, "Bearer wrong", 401], + [true, "Bearer wrong", 401], + ] as const)( + "validates optional bearer authentication (%s, %s)", + async (allowMissingAuth, authorization, status) => { + const progress = startTestProgress( + "optional local authentication", + ["serve compatible API", "validate authentication"], + { + logLine: () => {}, + }, + ); + const fake = await startFakeOpenAiCompatibleServer({ + apiKey: "dummy", + model: "local-model", + requireAuth: true, + allowMissingAuth, + progress, + }); + try { + const response = await fetch(`${fake.baseUrl}/chat/completions`, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(authorization === undefined ? {} : { Authorization: authorization }), + }, + body: JSON.stringify({ + model: "local-model", + messages: [{ role: "user", content: "ping" }], + }), + }); + expect(response.status).toBe(status); + await response.text(); + } finally { + await fake.close(); + progress.stop(); + } + }, + ); + it("serves fake OpenAI-compatible chat and responses contracts", async () => { const progressLines: string[] = []; const progress = startTestProgress( diff --git a/test/e2e/support/onboard-timeout-contract.test.ts b/test/e2e/support/onboard-timeout-contract.test.ts index 011798dfb53..38b6a97ce74 100644 --- a/test/e2e/support/onboard-timeout-contract.test.ts +++ b/test/e2e/support/onboard-timeout-contract.test.ts @@ -14,6 +14,8 @@ import { DCODE_TYPED_TARGET_TIMEOUT_MINUTES, LIVE_TARGET_BASE_TEST_TIMEOUT_MS, INFERENCE_ROUTING_TARGET_TIMEOUT_MINUTES, + OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS, + OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES, liveTargetTimeoutContract, ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS, ONBOARD_NO_RECREATE_COMMAND_TIMEOUT_MS, @@ -38,7 +40,12 @@ import { CONFIG_EXPORT_EXPECTATIONS, type ConfigExportExpectation } from "../reg const MINUTE_MS = 60_000; const finalHandoffTimeoutMs = getDockerGpuSupervisorReconnectTimeoutSecs(1, {}) * 1_000; -const affectedTargetIds = ["inference-routing", "onboard-repair", "onboard-resume"] as const; +const affectedTargetIds = [ + "inference-routing", + "inference-routing-openclaw-native", + "onboard-repair", + "onboard-resume", +] as const; const timeoutContractPath = "tools/e2e/onboard-timeout-contract.mts"; const commandDiagnosticHeadroomMs = 10 * MINUTE_MS; const testHeadroomMs = 10 * MINUTE_MS; @@ -115,6 +122,19 @@ describe("onboard final-handoff timeout contract", () => { ); }); + it("contains both serial OpenClaw native-local scenarios and their finalization", () => { + expect(OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS).toBeGreaterThanOrEqual( + DCODE_NATIVE_LOCAL_TEST_TIMEOUT_MS + 5 * MINUTE_MS, + ); + expect( + catalogueTarget("inference-routing-openclaw-native").timeoutMinutes * MINUTE_MS, + ).toBeGreaterThanOrEqual( + OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS + + ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS + + jobHeadroomMs, + ); + }); + it("pins the reviewed command, test, and target timeout values", () => { expect({ finalHandoffCommandMinutes: ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS / MINUTE_MS, @@ -122,6 +142,8 @@ describe("onboard final-handoff timeout contract", () => { singleFinalHandoffTargetMinutes: ONBOARD_SINGLE_FINAL_HANDOFF_TARGET_TIMEOUT_MINUTES, dcodeNativeLocalTestMinutes: DCODE_NATIVE_LOCAL_TEST_TIMEOUT_MS / MINUTE_MS, inferenceRoutingTargetMinutes: INFERENCE_ROUTING_TARGET_TIMEOUT_MINUTES, + openClawNativeLocalTestMinutes: OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS / MINUTE_MS, + openClawNativeLocalTargetMinutes: OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES, noRecreateCommandMinutes: ONBOARD_NO_RECREATE_COMMAND_TIMEOUT_MS / MINUTE_MS, configExportCommandMinutes: CONFIG_EXPORT_COMMAND_TIMEOUT_MS / MINUTE_MS, configExportPinnedV1ConsumerMinutes: CONFIG_EXPORT_PINNED_V1_CONSUMER_TIMEOUT_MS / MINUTE_MS, @@ -142,6 +164,8 @@ describe("onboard final-handoff timeout contract", () => { singleFinalHandoffTargetMinutes: 75, dcodeNativeLocalTestMinutes: 117.5, inferenceRoutingTargetMinutes: 243, + openClawNativeLocalTestMinutes: 122.5, + openClawNativeLocalTargetMinutes: 193, noRecreateCommandMinutes: 15, configExportCommandMinutes: 2, configExportPinnedV1ConsumerMinutes: 10, @@ -165,6 +189,11 @@ describe("onboard final-handoff timeout contract", () => { DCODE_NATIVE_LOCAL_TEST_TIMEOUT_MS, INFERENCE_ROUTING_TARGET_TIMEOUT_MINUTES, ], + [ + "inference-routing-openclaw-native", + OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS + ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS, + OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES, + ], ["onboard-resume", ONBOARD_RESUME_TEST_TIMEOUT_MS, ONBOARD_RESUME_TARGET_TIMEOUT_MINUTES], ["onboard-repair", ONBOARD_REPAIR_TEST_TIMEOUT_MS, ONBOARD_REPAIR_TARGET_TIMEOUT_MINUTES], ] as const)( @@ -177,7 +206,7 @@ describe("onboard final-handoff timeout contract", () => { }, ); - it("selects both affected targets when the shared timeout contract changes", () => { + it("selects each affected target when the shared timeout contract changes", () => { expect( catalogueTargetsForChangedFiles([timeoutContractPath]) .map((target) => target.id) diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 45cc351fd75..3b739488ea3 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -102,7 +102,7 @@ describe("E2E workflow plan", () => { }), ]); expect(plan.hermesSelected).toBe(true); - expect(plan.coverageMatrix).toHaveLength(79); + expect(plan.coverageMatrix).toHaveLength(80); expect(selectedWorkflowJobs(plan)).toEqual([ "catalogue-github-read", "catalogue-nvidia-api", @@ -155,7 +155,7 @@ describe("E2E workflow plan", () => { "ubuntu-repo-cloud-openclaw", ]); expect(plan.testMatrix).toEqual([]); - expect(catalogueIds).toHaveLength(48); + expect(catalogueIds).toHaveLength(49); expect(catalogueIds).not.toEqual( expect.arrayContaining([ "bootstrap-install-smoke", @@ -267,6 +267,16 @@ describe("E2E workflow plan", () => { ); }); + it.each([ + "src/lib/actions/inference-set/native-local.ts", + "src/lib/actions/inference-set/local-runtime.ts", + "src/lib/inference/native-local/profile.ts", + ])("selects native OpenClaw live evidence when %s changes", (changedFile) => { + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + "inference-routing-openclaw-native", + ); + }); + it.each([ "src/lib/onboard/runtime-provider/contract.ts", "src/lib/onboard/runtime-provider/docker.ts", diff --git a/test/generation/generate-openclaw-config-llamacpp-compat.test.ts b/test/generation/generate-openclaw-config-llamacpp-compat.test.ts index d3ce4b6b9d0..b7df726d090 100644 --- a/test/generation/generate-openclaw-config-llamacpp-compat.test.ts +++ b/test/generation/generate-openclaw-config-llamacpp-compat.test.ts @@ -37,3 +37,29 @@ describe("managed llama.cpp OpenClaw compatibility", () => { expect(model.compat?.toolSchemaProfile).toBeUndefined(); }); }); + +describe("native local OpenClaw generation", () => { + it("writes a scoped local credential reference for an attached endpoint", () => { + const config = buildConfig({ + ...baseOpenClawGenerationEnv(), + NEMOCLAW_MODEL: "local-model", + NEMOCLAW_PROVIDER_KEY: "inference", + NEMOCLAW_UPSTREAM_PROVIDER: "ollama-local", + NEMOCLAW_PRIMARY_MODEL_REF: "inference/local-model", + NEMOCLAW_INFERENCE_BASE_URL: "http://host.openshell.internal:11435/v1", + NEMOCLAW_INFERENCE_API: "openai-completions", + }); + expect(config.models.providers.inference).toMatchObject({ + baseUrl: "http://host.openshell.internal:11435/v1", + apiKey: "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + }); + }); + + it("keeps a shared local selection on inference.local", () => { + const config = buildLlamaCppConfig("vllm-local"); + expect(config.models.providers.inference).toMatchObject({ + baseUrl: "https://inference.local/v1", + apiKey: "unused", + }); + }); +}); diff --git a/test/helpers/inference-set-openclaw-native-local.ts b/test/helpers/inference-set-openclaw-native-local.ts new file mode 100644 index 00000000000..40fc328f432 --- /dev/null +++ b/test/helpers/inference-set-openclaw-native-local.ts @@ -0,0 +1,135 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + nativeLocalIdentity, + type NativeLocalProviderAttachment, +} from "../../src/lib/inference/native-local/contract"; +import type { ConfigObject } from "../../src/lib/security/credential-filter"; +import { createDeps } from "./inference-set"; + +const binding = { + agent: "openclaw" as const, + provider: "ollama-local" as const, + endpointUrl: "http://host.openshell.internal:11435/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel" as const, + gatewayName: "nemoclaw", + sandboxName: "alpha", +}; +export const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-local-provider", +}; + +export function fixture() { + const config: ConfigObject = { + agents: { defaults: { model: { primary: "inference/old-model" } } }, + models: { + providers: { + inference: { + baseUrl: binding.endpointUrl, + apiKey: "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + api: "openai-completions", + models: [{ id: "old-model" }], + }, + }, + }, + }; + return createDeps({ + config, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: binding.provider, + model: "old-model", + endpointUrl: binding.endpointUrl, + preferredInferenceApi: "openai-completions", + nativeLocalProviderAttachment: attachment, + }, + }); +} + +export function switchingFixture() { + const deps = fixture(); + const nextBinding = { + ...binding, + provider: "vllm-local" as const, + endpointUrl: "http://host.openshell.internal:8000/v1", + }; + const next = { + ...nextBinding, + ...nativeLocalIdentity(nextBinding), + schemaVersion: 1 as const, + providerId: "new-local-provider", + }; + let present = false; + let attached = false; + const authorities = new Map(); + deps.getNativeLocalProviderAuthority = (name) => authorities.get(name); + deps.setNativeLocalProviderAuthority = (receipt) => { + authorities.set(receipt.providerName, receipt); + }; + deps.resolveLocalSwitchRuntime = () => ({ + endpointUrl: next.endpointUrl, + credentialValue: "dummy", + authMode: "sentinel", + ownedProxy: false, + }); + const adapter = deps.providerAdapter; + const original = { ...adapter }; + adapter.importProviderProfile = async () => ({ ok: true }); + adapter.inspectProviderProfile = async (request) => + request.profileType === next.profileId + ? { ok: true, value: { credentialKeys: [next.credentialEnv] } } + : original.inspectProviderProfile(request); + adapter.getProvider = async (request) => + request.providerName === next.providerName + ? present + ? { + ok: true, + value: { + name: next.providerName, + type: next.profileId, + credentialKeys: [next.credentialEnv], + configKeys: [], + revision: { id: next.providerId, resourceVersion: 1 }, + }, + } + : { ok: false, error: { kind: "command", reason: "not_found", message: "not found" } } + : original.getProvider(request); + adapter.createProvider = async (request) => { + if (request.name !== next.providerName) return original.createProvider(request); + present = true; + return { ok: true }; + }; + adapter.attachProvider = async (request) => { + if (request.providerName !== next.providerName) return original.attachProvider(request); + attached = true; + return { ok: true }; + }; + adapter.detachProvider = async (request) => { + if (request.providerName !== next.providerName) return original.detachProvider(request); + const changed = attached; + attached = false; + return { ok: true, value: { changed } }; + }; + adapter.listProviderAttachments = async (request) => { + const result = await original.listProviderAttachments(request); + return result.ok + ? { + ok: true, + value: { names: [...result.value.names, ...(attached ? [next.providerName] : [])] }, + } + : result; + }; + adapter.deleteProvider = async (request) => { + if (request.providerName !== next.providerName) return original.deleteProvider(request); + present = false; + return { ok: true }; + }; + return { deps, next, isPresent: () => present, isAttached: () => attached }; +} diff --git a/test/helpers/inference-set.ts b/test/helpers/inference-set.ts index 161827eedb9..6f50c714171 100644 --- a/test/helpers/inference-set.ts +++ b/test/helpers/inference-set.ts @@ -15,6 +15,7 @@ import type { OpenShellProviderAdapter } from "../../src/lib/adapters/openshell/ import { createCliOpenShellProviderAdapter } from "../../src/lib/adapters/openshell/provider-adapter-cli"; import { HOSTED_NATIVE_PROVIDERS } from "../../src/lib/inference/native-provider/hosted"; import { fixedNativeProvider } from "../../src/lib/inference/native-provider/fixed"; +import { isLocalInferenceProvider } from "../../src/lib/inference/native-local/agent-config"; import type { NativeProviderAttachment } from "../../src/lib/inference/native-provider/contract"; import type { AgentConfigTarget } from "../../src/lib/sandbox/config"; import type { ConfigObject, ConfigValue } from "../../src/lib/security/credential-filter"; @@ -75,18 +76,31 @@ function nativeAwareProviderAdapter( base: OpenShellProviderAdapter, entries: SandboxEntry[], ): OpenShellProviderAdapter { - const definitions = [fixedNativeProvider("nvidia-prod")!, ...HOSTED_NATIVE_PROVIDERS]; + const localReceipts = entries.flatMap((entry) => + entry.nativeLocalProviderAttachment ? [entry.nativeLocalProviderAttachment] : [], + ); + const definitions = [ + fixedNativeProvider("nvidia-prod")!, + ...HOSTED_NATIVE_PROVIDERS, + ...localReceipts, + ]; const receipts = entries.flatMap((entry) => - [entry.nativeNvidiaProviderAttachment, entry.nativeHostedProviderAttachment].filter( - (receipt): receipt is NativeProviderAttachment => !!receipt, - ), + [ + entry.nativeNvidiaProviderAttachment, + entry.nativeHostedProviderAttachment, + entry.nativeLocalProviderAttachment, + ].filter((receipt): receipt is NativeProviderAttachment => !!receipt), ); const present = new Set(receipts.map((receipt) => receipt.providerName)); const attachments = new Map( entries.map((entry) => [ entry.name, new Set( - [entry.nativeNvidiaProviderAttachment, entry.nativeHostedProviderAttachment] + [ + entry.nativeNvidiaProviderAttachment, + entry.nativeHostedProviderAttachment, + entry.nativeLocalProviderAttachment, + ] .filter((receipt) => !!receipt) .map((receipt) => receipt!.providerName), ), @@ -97,6 +111,12 @@ function nativeAwareProviderAdapter( return { ...base, ensureProviderPolicyComposition: async () => ({ ok: true, value: undefined }), + inspectProviderProfile: async (request) => { + const local = localReceipts.find((receipt) => receipt.profileId === request.profileType); + return local + ? { ok: true, value: { credentialKeys: [local.credentialEnv] } } + : await base.inspectProviderProfile(request); + }, importProviderProfile: async (request) => definitions.some((definition) => request.profilePath.endsWith(`${definition.profileId}.yaml`)) ? { ok: true } @@ -155,6 +175,11 @@ function nativeAwareProviderAdapter( ok: true, value: { names: [...(attachments.get(request.sandboxName) ?? [])] }, }), + deleteProvider: async (request) => { + if (!definitionFor(request.providerName)) return await base.deleteProvider(request); + present.delete(request.providerName); + return { ok: true }; + }, }; } @@ -289,6 +314,7 @@ export function createDeps(options: { withGatewayRouteMutationLock?: InferenceSetDeps["withGatewayRouteMutationLock"]; getNativeNvidiaProviderAuthority?: InferenceSetDeps["getNativeNvidiaProviderAuthority"]; setNativeNvidiaProviderAuthority?: InferenceSetDeps["setNativeNvidiaProviderAuthority"]; + clearNativeLocalProviderAuthority?: InferenceSetDeps["clearNativeLocalProviderAuthority"]; }): InferenceSetDeps & { calls: { captureOpenshell: ReturnType; @@ -315,6 +341,7 @@ export function createDeps(options: { settleOpenClawPairing: ReturnType; withGatewayRouteMutationLock: ReturnType; setNativeNvidiaProviderAuthority: ReturnType; + clearNativeLocalProviderAuthority: ReturnType; }; getSession: () => Session | null; } { @@ -392,6 +419,7 @@ export function createDeps(options: { await operation()), ), setNativeNvidiaProviderAuthority: vi.fn(), + clearNativeLocalProviderAuthority: vi.fn(), }; const providerAdapter = options.providerAdapter ?? @@ -450,6 +478,8 @@ export function createDeps(options: { getNativeNvidiaProviderAuthority: options.getNativeNvidiaProviderAuthority, setNativeNvidiaProviderAuthority: options.setNativeNvidiaProviderAuthority ?? calls.setNativeNvidiaProviderAuthority, + clearNativeLocalProviderAuthority: + options.clearNativeLocalProviderAuthority ?? calls.clearNativeLocalProviderAuthority, updateSandbox: calls.updateSandbox, getRequestedAgent: () => options.requestedAgent, loadSession: () => session, @@ -478,8 +508,7 @@ export function createDeps(options: { providerAdapter, appendAuditEntry: calls.appendAuditEntry, log: calls.log, - isLocalInferenceProvider: (provider) => - provider === "ollama-local" || provider === "vllm-local", + isLocalInferenceProvider, validateLocalProvider: calls.validateLocalProvider, ensureLocalProviderReachable: calls.ensureLocalProviderReachable, resolveContextWindowForModel: calls.resolveContextWindowForModel, diff --git a/test/helpers/rebuild-flow-generic-harness.ts b/test/helpers/rebuild-flow-generic-harness.ts index 95ddd77e202..61a3faa4c31 100644 --- a/test/helpers/rebuild-flow-generic-harness.ts +++ b/test/helpers/rebuild-flow-generic-harness.ts @@ -460,7 +460,7 @@ export function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): session.sandboxName = overrides.sessionSandboxName ?? session.sandboxName; const currentSandboxEntry = { name: "alpha", - provider: "ollama-local", + provider: "build", model: "nvidia/nemotron", policies: ["npm"], agent: null, diff --git a/test/helpers/rebuild-flow-harness.ts b/test/helpers/rebuild-flow-harness.ts index 7b716932598..993bfcf52ca 100644 --- a/test/helpers/rebuild-flow-harness.ts +++ b/test/helpers/rebuild-flow-harness.ts @@ -47,6 +47,9 @@ export const mcpBridgeSource = requireDist("./mcp-bridge-source.js"); export const messaging = requireDist("../../messaging/index.js"); export const messagingHostForwardLifecycle = requireDist("./messaging-host-forward-lifecycle.js"); export const mutableConfigPerms = requireDist("../../sandbox/mutable-config-perms.js"); +export const nativeLocalProfile = requireDist( + "../../inference/native-local/profile.js", +) as typeof import("../../src/lib/inference/native-local/profile"); export const nim = requireDist("../../inference/nim.js"); export const onboardCredentialEnv = requireDist("../../onboard/credential-env.js"); export const managedWorkloadRebuild = requireDist( diff --git a/test/helpers/rebuild-flow-test-support.ts b/test/helpers/rebuild-flow-test-support.ts index 0dabdfd0c01..109774da789 100644 --- a/test/helpers/rebuild-flow-test-support.ts +++ b/test/helpers/rebuild-flow-test-support.ts @@ -239,7 +239,7 @@ export function createRebuildFlowSession(machineSnapshotVersion: number): Rebuil updatedAt: "2026-06-01T00:00:00.000Z", sandboxName: "alpha", agent: null, - provider: "ollama-local", + provider: "build", model: "nvidia/nemotron", credentialEnv: null, checkpoint: null, diff --git a/test/onboarding/onboard-host-local-inference-routing.test.ts b/test/onboarding/onboard-host-local-inference-routing.test.ts index 54dac0a6093..e84a5bebd60 100644 --- a/test/onboarding/onboard-host-local-inference-routing.test.ts +++ b/test/onboarding/onboard-host-local-inference-routing.test.ts @@ -39,10 +39,14 @@ const NETWORK_AUTHORITY = "3".repeat(64); const MODEL = "qwen3.5-9b"; const SANDBOX = "host-local-agent"; const APPLICATIONS = ["openclaw", "hermes", "langchain-deepagents-code"] as const; -const SHARED_APPLICATIONS = ["openclaw", "hermes"] as const; +const SHARED_APPLICATIONS = ["hermes"] as const; const PUBLISHED_RESUME_ROLLBACK_CASES = SHARED_APPLICATIONS.flatMap((application) => (["running", "stopped"] as const).map((stateAtEntry) => ({ application, stateAtEntry })), ); +const NATIVE_RESUME_ROLLBACK_CASES = (["openclaw", "langchain-deepagents-code"] as const).flatMap( + (application) => + (["running", "stopped"] as const).map((stateAtEntry) => ({ application, stateAtEntry })), +); const writer: HostLocalInferenceReceiptWriter = { transactionId: "f".repeat(64), targetSha256: "1".repeat(64), @@ -430,6 +434,34 @@ function llamaFixture(application: HostLocalInferenceApplication) { } describe("onboard host-local inference routing", () => { + it("attaches OpenClaw local inference to its sandbox without changing the shared route", async () => { + const route = fixture("openclaw", "ollama"); + const harness = createHarness(); + + await expect( + harness.setupInference(SANDBOX, MODEL, "ollama-local", null, null, null, [], { + gatewayName: "nemoclaw", + hostLocalInference: route.selection, + }), + ).resolves.toEqual({ ok: true }); + + expect(harness.native.adapter.createProvider).toHaveBeenCalledOnce(); + expect(harness.commands).toEqual([]); + expect(harness.updateSandbox).toHaveBeenCalledWith( + SANDBOX, + expect.objectContaining({ + provider: "ollama-local", + model: MODEL, + nativeLocalProviderAttachment: expect.objectContaining({ + agent: "openclaw", + sandboxName: SANDBOX, + }), + }), + ); + expect(route.gatewayCommit).toHaveBeenCalledOnce(); + expect(route.gatewayRollback).not.toHaveBeenCalled(); + }); + it("retires an unreserved Deep Agents Code native provider after managed runtime pre-commit fails (#13197)", async () => { const route = fixture("langchain-deepagents-code", "vllm", { validationError: new Error("managed runtime pre-commit refused"), @@ -739,36 +771,35 @@ describe("onboard host-local inference routing", () => { expect(harness.errors.join(" ")).toContain("mismatched host-local-inference authority"); }); - it.each([ - ["nim", 8001], - ["vllm", 8000], - ] as const)("starts managed %s through the injected provider", async (service, port) => { - const route = fixture("openclaw", service); - const legacyRun = vi.fn(); - const legacyValidate = vi.fn(); - const harness = createHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" ? { status: 1 } : undefined, - overrides: { - applyLocalInferenceRoute: undefined, - run: legacyRun, - validateLocalProvider: legacyValidate, - }, - }); + it.each(["nim", "vllm"] as const)( + "starts managed %s through the injected provider", + async (service) => { + const route = fixture("openclaw", service); + const legacyRun = vi.fn(); + const legacyValidate = vi.fn(); + const harness = createHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" ? { status: 1 } : undefined, + overrides: { + applyLocalInferenceRoute: undefined, + run: legacyRun, + validateLocalProvider: legacyValidate, + }, + }); - await expect( - harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { - hostLocalInference: route.selection, - }), - ).resolves.toEqual({ ok: true }); + await expect( + harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { + hostLocalInference: route.selection, + }), + ).resolves.toEqual({ ok: true }); - expect(harness.commands.some(({ command }) => command.includes(`:${String(port)}/v1`))).toBe( - true, - ); - expect(legacyRun).not.toHaveBeenCalled(); - expect(legacyValidate).not.toHaveBeenCalled(); - expect(route.gatewayCommit).toHaveBeenCalledOnce(); - }); + expect(harness.native.adapter.createProvider).toHaveBeenCalledOnce(); + expect(harness.commands).toEqual([]); + expect(legacyRun).not.toHaveBeenCalled(); + expect(legacyValidate).not.toHaveBeenCalled(); + expect(route.gatewayCommit).toHaveBeenCalledOnce(); + }, + ); it.each(APPLICATIONS)( "recovers an interrupted exact %s managed start before route commit", @@ -851,10 +882,10 @@ describe("onboard host-local inference routing", () => { }, ); - it.each(["running", "stopped"] as const)( - "restores DCode native provider resume state %s after registration fails (#13197)", - async (stateAtEntry) => { - const route = fixture("langchain-deepagents-code", "vllm", { + it.each(NATIVE_RESUME_ROLLBACK_CASES)( + "restores $application native provider resume state $stateAtEntry after registration fails (#12975)", + async ({ application, stateAtEntry }) => { + const route = fixture(application, "vllm", { resume: true, priorState: "absent", resumeStateAtEntry: stateAtEntry, @@ -934,7 +965,7 @@ describe("onboard host-local inference routing", () => { ] as const)( "retains the $service gateway and runtime after an ambiguous route mutation", async ({ provider, service }) => { - const route = fixture("openclaw", service); + const route = fixture("hermes", service); const harness = createHarness({ overrides: { applyLocalInferenceRoute: undefined, @@ -1014,7 +1045,7 @@ describe("onboard host-local inference routing", () => { }); it("never emits a raw secret-bearing gateway provider failure", async () => { - const route = fixture("openclaw", "vllm"); + const route = fixture("hermes", "vllm"); const providerFailures = { "provider get": { status: 1 }, "provider create": { @@ -1044,6 +1075,34 @@ describe("onboard host-local inference routing", () => { expect(route.events.slice(-2)).toEqual(["gateway-rollback", "runtime-rollback"]); }); + it("redacts a failed OpenClaw sandbox provider registration before rollback (#12975)", async () => { + const route = fixture("openclaw", "vllm"); + const harness = createHarness(); + harness.native.adapter.createProvider.mockResolvedValue({ + ok: false, + error: { + kind: "command", + reason: "failed", + message: + "https://gateway-user:gateway-password@gateway.example/v1?token=gateway-query OPENAI_API_KEY=gateway-env-secret", + }, + }); + + await expect( + harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { + hostLocalInference: route.selection, + }), + ).rejects.toThrow("EXIT_CALLED:1"); + + const evidence = harness.errors.join(" "); + expect(evidence).not.toContain("gateway-user"); + expect(evidence).not.toContain("gateway-password"); + expect(evidence).not.toContain("gateway-query"); + expect(evidence).not.toContain("gateway-env-secret"); + expect(harness.updateSandbox).not.toHaveBeenCalled(); + expect(route.events.slice(-2)).toEqual(["gateway-rollback", "runtime-rollback"]); + }); + it.each(APPLICATIONS)( "rolls back %s when provider authority revalidation fails before commit", async (application) => { diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index d3755dcfd8a..c3adeb6fcc2 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -282,7 +282,7 @@ describe("compiled rebuild owning-registry worker", () => { it("binds a valid rebuild descriptor to the selected sibling registry root", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-sibling-root-")); try { - writeSiblingRegistry(home); + writeSiblingRegistry(home, { provider: "nvidia-prod" }); const recoveryManifest = writeRecoveryFixture(home); vi.stubEnv("HOME", home); vi.stubEnv("NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "1"); diff --git a/tools/e2e/onboard-timeout-contract.mts b/tools/e2e/onboard-timeout-contract.mts index f5f011b54a8..afcc61de3d6 100644 --- a/tools/e2e/onboard-timeout-contract.mts +++ b/tools/e2e/onboard-timeout-contract.mts @@ -49,6 +49,19 @@ export const INFERENCE_ROUTING_TARGET_TIMEOUT_MINUTES = (DCODE_NATIVE_LOCAL_TEST_TIMEOUT_MS + ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS) / MINUTE_MS, ); +// The separate OpenClaw native-local target owns the same two-onboard lifecycle +// as TC-INF-15, then switches its recorded model before the real agent turn. +// Keep its serial job below the hosted runner's maximum while preserving the +// existing inference-routing target's reviewed timeout. +export const OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS = + DCODE_NATIVE_LOCAL_TEST_TIMEOUT_MS + 5 * MINUTE_MS; +export const OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES = Math.ceil( + (OPENCLAW_NATIVE_LOCAL_TEST_TIMEOUT_MS + + ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS + + ONBOARD_JOB_HEADROOM_MS) / + MINUTE_MS, +); + // The typed DCode target runs onboarding, its invalid-credential lifecycle, // state validation, and the ordered cloud checks. Those checks can consume 96 // minutes of command deadlines before automatic config export; retain the same diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index b7a298a9e84..fc4d8a192d4 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -23,6 +23,7 @@ import { ONBOARD_REPAIR_TARGET_TIMEOUT_MINUTES, ONBOARD_RESUME_TARGET_TIMEOUT_MINUTES, INFERENCE_ROUTING_TARGET_TIMEOUT_MINUTES, + OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES, } from "./onboard-timeout-contract.mts"; import { HERMES_ACP_E2E_OWNING_PATHS } from "./hermes-acp-owning-paths.mts"; import { @@ -1056,6 +1057,29 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ cloudflared: true, owningPaths: ["tools/e2e/onboard-timeout-contract.mts"], }), + managedRuntimeTarget("inference-routing-openclaw-native", { + testFile: "test/e2e/live/openclaw-inference-switch.test.ts", + selector: "^TC-INF-1", + displayName: "Inference: OpenClaw native local requests and isolation", + agentRuntime: "openclaw", + environmentOrInferenceEndpoint: + "Ubuntu; authenticated llama.cpp and credentialless vLLM fixtures", + profile: "standard", + timeoutMinutes: OPENCLAW_NATIVE_LOCAL_TARGET_TIMEOUT_MINUTES, + installMode: "none", + restoreCli: true, + exposeCliBin: false, + owningPaths: [ + "src/lib/actions/inference-set/native-local.ts", + "src/lib/actions/inference-set/local-runtime.ts", + "src/lib/inference/native-local/", + "src/lib/onboard/openclaw/initial-inference-route.ts", + "src/lib/onboard/setup-inference.ts", + "src/lib/actions/sandbox/rebuild-preflight-guards.ts", + "test/e2e/fixtures/inference-routing-openclaw-native.ts", + "tools/e2e/onboard-timeout-contract.mts", + ], + }), dockerOnlyTarget("llama-cpp-generic-gpu", { displayName: "Inference: completes an agent turn with llama.cpp on a generic NVIDIA GPU", agentRuntime: "openclaw", @@ -1238,6 +1262,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }, }), managedRuntimeTarget("openclaw-inference-switch", { + selector: "^openclaw-inference-switch:", displayName: "Inference: OpenClaw switches to native NVIDIA and remains responsive", agentRuntime: "openclaw", environmentOrInferenceEndpoint: "Ubuntu; native NVIDIA Endpoints provider", @@ -1281,6 +1306,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ }, }), managedRuntimeTarget("openclaw-compatible-anthropic-inference-switch", { + selector: "^openclaw-inference-switch:", targetId: "openclaw-inference-switch", displayName: "Inference: OpenClaw switches to an Anthropic-compatible endpoint", agentRuntime: "openclaw",