diff --git a/Dockerfile b/Dockerfile index 1e561a0f3f8..f7104bef3fc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -699,6 +699,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 --chmod=0444 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/ @@ -1550,20 +1552,17 @@ COPY --from=openclaw-runtime-payload /src/ /src/ COPY --from=openclaw-runtime-payload /usr/local/share/ /usr/local/share/ RUN chmod 755 /scripts/generate-openclaw-config.mts \ - /scripts/validate-openclaw-tool-search.mts /src /src/lib \ - && chmod 444 /src/lib/*.ts \ + /scripts/validate-openclaw-tool-search.mts /src /src/lib /src/lib/core \ + && chmod 444 /src/lib/*.ts /src/lib/inference/native-local/agent-config.ts \ && chmod 755 /usr/local/share/nemoclaw \ /usr/local/share/nemoclaw/openclaw-plugins \ && find /usr/local/share/nemoclaw/openclaw-plugins -type d -exec chmod 755 {} + \ && find /usr/local/share/nemoclaw/openclaw-plugins -type f -exec chmod 644 {} + -# Build args for config that varies per deployment. # nemoclaw onboard passes these at image build time. ARG NEMOCLAW_MODEL=nvidia/nemotron-3-super-120b-a12b ARG NEMOCLAW_INFERENCE_PROVIDER_ID=inference -# Keep selected upstream and catalog preset distinct from the managed -# "inference" route. The generator uses them for provider and profile settings. -# Empty defaults retain the standard managed-route behavior. +# Provider and preset select agent config. ARG NEMOCLAW_UPSTREAM_PROVIDER= ARG NEMOCLAW_SERVING_PRESET= ARG NEMOCLAW_PRIMARY_MODEL_REF=inference/nvidia/nemotron-3-super-120b-a12b @@ -1949,9 +1948,8 @@ RUN chmod 755 /usr/local/bin/nemoclaw-start /usr/local/bin/nemoclaw-codex-acp \ /usr/local/bin/nemoclaw-managed-startup-hold \ /usr/local/lib/nemoclaw/sandbox-init.sh \ /scripts/generate-openclaw-config.mts \ - /scripts/validate-openclaw-tool-search.mts /src /src/lib \ - && chmod 444 /src/lib/*.ts \ - /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh \ + /scripts/validate-openclaw-tool-search.mts /src /src/lib /src/lib/core \ + && chmod 444 /src/lib/*.ts /src/lib/inference/native-local/agent-config.ts \ && chmod 444 /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh \ /usr/local/lib/nemoclaw/sandbox-rlimits.sh \ && chmod 644 /usr/local/lib/nemoclaw/openclaw_device_approval_policy.py \ diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index 3a3e1375a8d..b3ec628c4da 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -156,6 +156,8 @@ COPY agents/langchain-deepagents-code/generate-config-entrypoint.ts /opt/nemocla COPY agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts COPY src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts COPY src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts +COPY src/lib/core/endpoint-url-safety.ts /opt/nemoclaw-deepagents-code/src/lib/core/endpoint-url-safety.ts +COPY src/lib/inference/native-local/agent-config.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-local/agent-config.ts COPY src/lib/inference/native-provider/agent-config.ts src/lib/inference/native-provider/hosted.ts src/lib/inference/native-provider/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-provider/ COPY agents/langchain-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py COPY agents/langchain-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py @@ -190,7 +192,7 @@ COPY nemoclaw-blueprint/ /opt/nemoclaw-blueprint/ # regressionTest: the stripped-base gate must reach this marker, then fail import. # removalCondition: remove when installation validates dependencies atomically. # hadolint ignore=DL4006 -RUN chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-quickjs.py /usr/local/lib/nemoclaw/validate-quickjs-runtime.py /opt/nemoclaw-deepagents-code/validate-nemotron-ultra-profile.py /opt/nemoclaw-deepagents-code/progressive_tool_disclosure.py /opt/nemoclaw-deepagents-code/nemoclaw_observability.py /opt/nemoclaw-deepagents-code/validate-progressive-tool-disclosure.py /opt/nemoclaw-deepagents-code/validate-observability.py /opt/nemoclaw-deepagents-code/validate-read-only-mcp-call.py /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh /etc/profile.d/nemoclaw-dcode.sh /usr/local/lib/nemoclaw/nemoclaw_read_only_mcp.py \ +RUN chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/src/lib/core/endpoint-url-safety.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-local/agent-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-quickjs.py /usr/local/lib/nemoclaw/validate-quickjs-runtime.py /opt/nemoclaw-deepagents-code/validate-nemotron-ultra-profile.py /opt/nemoclaw-deepagents-code/progressive_tool_disclosure.py /opt/nemoclaw-deepagents-code/nemoclaw_observability.py /opt/nemoclaw-deepagents-code/validate-progressive-tool-disclosure.py /opt/nemoclaw-deepagents-code/validate-observability.py /opt/nemoclaw-deepagents-code/validate-read-only-mcp-call.py /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh /etc/profile.d/nemoclaw-dcode.sh /usr/local/lib/nemoclaw/nemoclaw_read_only_mcp.py \ && chmod 755 /usr/local/bin/nemoclaw-start /usr/local/bin/nemoclaw-managed-startup-hold /usr/local/lib/nemoclaw/dcode-wrapper.sh /usr/local/lib/nemoclaw/dcode-launcher.sh /usr/local/lib/nemoclaw/dcode-session-supervisor.py \ && test "$(stat -c '%u:%g:%a' /usr/local/lib/nemoclaw/dcode-session-supervisor.py)" = "0:0:755" \ && install -o root -g root -m 0755 /usr/local/lib/nemoclaw/dcode-launcher.sh /usr/local/lib/nemoclaw/dcode-managed-exec \ diff --git a/agents/langchain-deepagents-code/dcode-wrapper.sh b/agents/langchain-deepagents-code/dcode-wrapper.sh index ebb6d6f2a7a..84042182d85 100755 --- a/agents/langchain-deepagents-code/dcode-wrapper.sh +++ b/agents/langchain-deepagents-code/dcode-wrapper.sh @@ -462,7 +462,10 @@ is_openshell_env_placeholder_for_name() { esac canonical="${OPENSHELL_ENV_PLACEHOLDER_PREFIX}${name}" - [ "$value" = "$canonical" ] && return 0 + if [ "$value" = "$canonical" ]; then + [ "$name" != "NEMOCLAW_LOCAL_INFERENCE_TOKEN" ] + return $? + fi revision_prefix="${OPENSHELL_ENV_PLACEHOLDER_PREFIX}v" stable_prefix="${OPENSHELL_ENV_PLACEHOLDER_PREFIX}s" @@ -691,6 +694,10 @@ if is_openshell_env_placeholder_for_name NVIDIA_INFERENCE_API_KEY "${NVIDIA_INFE export NEMOCLAW_ATTACHED_PROVIDER_API_KEY="$NVIDIA_INFERENCE_API_KEY" fi +if [ "${NEMOCLAW_LOCAL_INFERENCE_TOKEN+x}" = x ] && ! is_openshell_env_placeholder_for_name NEMOCLAW_LOCAL_INFERENCE_TOKEN "$NEMOCLAW_LOCAL_INFERENCE_TOKEN"; then + refuse_invalid_openshell_placeholder "runtime environment variable" NEMOCLAW_LOCAL_INFERENCE_TOKEN +fi + assert_no_secret_runtime_env assert_no_secret_env_file assert_no_auth_store_credentials diff --git a/agents/langchain-deepagents-code/generate-config.ts b/agents/langchain-deepagents-code/generate-config.ts index 588cc43dd15..7c99d4776f7 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -6,6 +6,10 @@ // SECURITY: this file writes only non-secret provider/model metadata. Real // provider credentials stay outside ~/.deepagents files. +import { + nativeLocalCredentialReference, + NATIVE_LOCAL_CREDENTIAL_ENV, +} from "../../src/lib/inference/native-local/agent-config.ts"; import { nativeHostedAgentConfig } from "../../src/lib/inference/native-provider/agent-config.ts"; import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; @@ -166,8 +170,9 @@ function providerConfigLines( upstreamProvider: string, ): string[] { const nativeHosted = nativeHostedAgentConfig(upstreamProvider, baseUrl); - const apiKeyEnv = - baseUrl === NVIDIA_HOSTED_NATIVE_ENDPOINT + const apiKeyEnv = nativeLocalCredentialReference(upstreamProvider, baseUrl) + ? NATIVE_LOCAL_CREDENTIAL_ENV + : baseUrl === NVIDIA_HOSTED_NATIVE_ENDPOINT ? ATTACHED_PROVIDER_API_KEY_ENV : (nativeHosted?.credentialEnv ?? MANAGED_INFERENCE_API_KEY_ENV); return [ diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index c864a3dad8b..2899d4e068b 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -1080,12 +1080,34 @@ def managed_inference_base_url() -> str: def managed_inference_api_key(base_url: str) -> str: """Select the non-secret credential for the validated image-owned route.""" + parsed = urlparse(base_url) + host = parsed.hostname or "" + local_host = host in {"host.openshell.internal", "host.docker.internal"} + try: + address = ipaddress.IPv4Address(host) + local_host = any(address in ipaddress.IPv4Network(network) for network in ( + "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16" + )) + except ipaddress.AddressValueError: + # Keep the host-alias result above; every other non-IPv4 name remains untrusted. + pass + upstream_provider = _managed_upstream_provider() + if parsed.scheme == "http" and local_host and upstream_provider in { + "ollama-local", "vllm-local", "llama-cpp-local", "compatible-endpoint" + }: + value = os.environ.get("NEMOCLAW_LOCAL_INFERENCE_TOKEN", "") + if re.fullmatch( + r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NEMOCLAW_LOCAL_INFERENCE_TOKEN", + value, + ) is None: + raise RuntimeError("native local inference requires an issued OpenShell credential reference") + return value if base_url == "https://integrate.api.nvidia.com/v1": name = "NVIDIA_INFERENCE_API_KEY" provider = "NVIDIA" - elif base_url == "https://openrouter.ai/api/v1" and ( - upstream_provider := _managed_upstream_provider() - ) in _OPENROUTER_DISPLAY_PROVIDER_ALIASES | {"compatible-endpoint"}: + elif base_url == "https://openrouter.ai/api/v1" and upstream_provider in ( + _OPENROUTER_DISPLAY_PROVIDER_ALIASES | {"compatible-endpoint"} + ): name = ( "COMPATIBLE_API_KEY" if upstream_provider == "compatible-endpoint" diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 3717e8a8a38..fa5549e0228 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,10 +15,10 @@ "testFileCount": 77, "liveFileCount": 186, "direct": { - "expectCalls": 1260, - "matcherAssertions": 1239, + "expectCalls": 1262, + "matcherAssertions": 1241, "nodeAssertions": 104, - "namedAssertionHelpers": 417, + "namedAssertionHelpers": 415, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 177, @@ -27,14 +27,14 @@ "generatedProbeConditions": 215 }, "unique": { - "expectCalls": 1683, - "matcherAssertions": 1657, + "expectCalls": 1686, + "matcherAssertions": 1660, "nodeAssertions": 127, - "namedAssertionHelpers": 661, + "namedAssertionHelpers": 659, "failCalls": 1, "throwGuards": 526, "objectFieldAssertions": 254, - "assertionPoints": 3226, + "assertionPoints": 3227, "generatedProbeBlocks": 208, "generatedProbeConditions": 720 }, @@ -60,7 +60,7 @@ "test/e2e/live/dashboard-remote-bind.test.ts": [16,14,16,16,3], "test/e2e/live/deferred-onboarding.test.ts": [12,14,12,14,0], "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], - "test/e2e/live/double-onboard.test.ts": [42,47,42,47,0], + "test/e2e/live/double-onboard.test.ts": [45,50,45,50,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], @@ -73,7 +73,7 @@ "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], "test/e2e/live/inference-routing-provider-smoke.test.ts": [27,40,38,59,1], - "test/e2e/live/inference-routing.test.ts": [36,51,48,89,15], + "test/e2e/live/inference-routing.test.ts": [35,48,47,86,15], "test/e2e/live/issue-4434-tui-unreachable-inference.test.ts": [28,32,28,32,0], "test/e2e/live/issue-4462-scope-upgrade-approval.test.ts": [8,18,8,18,0], "test/e2e/live/issue-9880-staging-launchable.test.ts": [0,0,0,0,0], @@ -81,7 +81,7 @@ "test/e2e/live/launch-readiness-lease-acceptance.test.ts": [6,6,6,10,6], "test/e2e/live/launchable-smoke.test.ts": [14,29,14,29,3], "test/e2e/live/llama-cpp-generic-gpu.test.ts": [17,35,33,61,2], - "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,13,28,0], + "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,14,29,0], "test/e2e/live/managed-image-multiarch-startup.test.ts": [1,1,1,7,0], "test/e2e/live/managed-image-protected-runtime.test.ts": [0,0,40,77,15], "test/e2e/live/mcp-bridge.test.ts": [39,138,193,518,46], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 9b44751989d..d9b6a3911df 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #12977 keeps the approved native-local agent and sibling-policy coverage in existing targets and adds one live assertion for a fresh selected-model request around each managed agent turn, including credentialless DCode before and after restart. Rebecca approved this exact transition: https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6192975716. The candidate entry supports local validation; independent CI still verifies the exact maintainer approval on the PR. Remove after #12977 merges.", "schemaVersion": 1, "exceptions": [ { @@ -35,6 +35,10 @@ "pullRequest": 12958, "changeSha256": "96e09e5e48df3a94e93f7122758571ed078440f6330467c98d45f0a71b11d91c" }, + { + "pullRequest": 12977, + "changeSha256": "c0c7f7df24942dcb4d7c28d7fd02d65b4ee344d83782425f572521d77edc5ea1" + }, { "pullRequest": 13051, "changeSha256": "b85fb3a4316d2656bda395a30a01a958fd75e5a5325e6457c6bc1be81ac6b2b8" diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index 3810a03c843..d70ab66749d 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -190,7 +190,7 @@ "name": "LangChain Deep Agents Code", "status": "tested", "default": false, - "notes": "Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861." + "notes": "Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. New local selections, including qualified host-local compatible endpoints, use sandbox-attached OpenShell providers. Other custom endpoints and existing shared-route sandboxes use `inference.local` while OpenShell remains pinned to 0.0.116. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861." } ], @@ -208,7 +208,7 @@ { "name": "Managed inference", "status": "tested", - "notes": "Provider-routed model calls through OpenShell, transparent to the agent. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table." + "notes": "Provider-routed model calls through OpenShell, transparent to the agent. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. New OpenClaw and LangChain Deep Agents Code local selections, including qualified host-local compatible endpoints, use sandbox-attached OpenShell providers. Hermes and Pi local selections, other custom endpoints, and existing shared-route sandboxes use `inference.local` while OpenShell remains pinned to 0.0.116. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table." }, { "name": "Declarative network policy", diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index d903a85ea49..e0aa3229719 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -23,7 +23,7 @@ "src/lib/core/url-utils.ts": 22, "src/lib/core/wait.ts": 30, "src/lib/credentials/store.ts": 44, - "src/lib/inference/config.ts": 27, + "src/lib/inference/config.ts": 28, "src/lib/messaging/channels/index.ts": 23, "src/lib/onboard/gateway-binding.ts": 49, "src/lib/platform.ts": 20, @@ -52,8 +52,10 @@ "src/lib/actions/uninstall/run-plan.ts": 25, "src/lib/inference/local.ts": 22, "src/lib/inference/onboard-probes.ts": 21, + "src/lib/onboard/sandbox-registration.ts": 21, "src/lib/inference/vllm.ts": 20, "src/lib/onboard.ts": 192, + "src/lib/onboard/managed-workload/onboard-orchestration.ts": 21, "src/lib/onboard/sandbox-gpu-create-run-attempt.ts": 18, "src/lib/onboard/machine/handlers/sandbox.ts": 21, "src/lib/policy/index.ts": 22, diff --git a/docs/about/ecosystem-deepagents.mdx b/docs/about/ecosystem-deepagents.mdx index 15768379e7a..254809513fe 100644 --- a/docs/about/ecosystem-deepagents.mdx +++ b/docs/about/ecosystem-deepagents.mdx @@ -74,7 +74,7 @@ The following table compares custom OpenShell integration with `nemo-deepagents | Capability | Custom OpenShell + Deep Agents | `nemo-deepagents onboard` | |---|---|---| | Sandbox isolation | You define and apply OpenShell seccomp, Landlock, network namespace isolation, and no-new-privileges policy. | NemoClaw applies the managed Deep Agents policy through the blueprint and requires the runtime checks that the managed agent runtime depends on. | -| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding and keeps provider credentials outside the sandbox. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. | +| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding and keeps provider credentials outside the sandbox. NVIDIA Endpoints and fixed hosted providers use attached provider endpoints. Eligible new local selections use them after native provider attachment. Custom endpoints that do not qualify for native attachment and existing legacy routes retain `inference.local`. | | Image hardening | Depends on your base image and install steps. | NemoClaw installs the pinned Deep Agents Code package in `/opt/venv`, uses managed launchers, and rejects unsupported runtime paths such as unmanaged MCP autoloading, nested sandbox providers, and alternate model routes. | | Filesystem policy | You define read-only and read-write paths in policy YAML. | NemoClaw defines a targeted layout: system paths are read-only, `/sandbox` and `/tmp` are writable, and Deep Agents state lives under `/sandbox/.deepagents`. | | Inference setup | You configure OpenShell inference routing and Deep Agents provider settings manually. | NemoClaw validates the selected provider from the host, configures the OpenShell route, and writes `/sandbox/.deepagents/config.toml` for the managed OpenAI-compatible path. | diff --git a/docs/about/how-it-works.mdx b/docs/about/how-it-works.mdx index caaa85dbfea..aaa8753ffca 100644 --- a/docs/about/how-it-works.mdx +++ b/docs/about/how-it-works.mdx @@ -212,7 +212,11 @@ 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. -Existing shared-route sandboxes, user-supplied endpoints, local providers, and Model Router retain `inference.local`. +New OpenClaw and Deep Agents Code local selections that qualify for native provider attachment use sandbox-attached OpenShell providers. +Existing local sandboxes can keep using `inference.local` while OpenShell 0.0.116 is pinned. +If an OpenClaw or Deep Agents Code sandbox records a local route that qualifies for native attachment but lacks that attachment, resume or rebuild stops before changing the sandbox. +Back up that sandbox, then re-onboard it with `--fresh --name --recreate-sandbox`. +User-supplied endpoints that do not qualify for native attachment, Hermes local selections, and Model Router continue to use the shared route. 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 c275b9014b8..0a0bf042bb0 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. Custom and local providers 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, fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use sandbox-attached providers. Other custom endpoints, Hermes local selections, and existing legacy routes use `inference.local` on the pinned OpenShell release. 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 f85985d8bbb..8b55daa956f 100644 --- a/docs/deployment/deploy-to-headless-server.mdx +++ b/docs/deployment/deploy-to-headless-server.mdx @@ -269,7 +269,7 @@ unset TOKEN -Deep Agents Code does not expose a dashboard URL or gateway token. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the OpenShell-managed `inference.local` route. +Deep Agents Code does not expose a dashboard URL or gateway token. NVIDIA Endpoints, supported fixed hosted providers, and new local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints and existing legacy routes retain the OpenShell-managed `inference.local` route on the pinned release. diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index d3a27b82b68..5c3e8c5d7ce 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -165,7 +165,7 @@ The wizard asks for an inference provider, model, required credential, and sandb When you edit inference, NemoClaw clears the credential staged for the discarded selection. NemoClaw preserves the sandbox name. When you edit the sandbox name, NemoClaw preserves the inference selection. The sandbox prompt shows the prior name as its default. After you apply the configuration, routine editing ends. If inference setup fails and offers a `back` recovery action, you can return to provider and model selection and then review the updated configuration again. Provider registration, inference setup, policy selection, and sandbox creation then continue forward. The default Deep Agents sandbox name is `deepagents-code`. Use a distinct name, such as `my-deepagents`, when you run Deep Agents, Hermes, and OpenClaw sandboxes side by side. Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) for provider-specific prompts. -The image installs hash-locked Deep Agents Code `0.1.71` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. NVIDIA Endpoints uses `https://integrate.api.nvidia.com/v1` through a least-privilege OpenShell provider attached to the sandbox. Supported fixed hosted providers also use their native endpoints through sandbox-attached providers. Custom and local providers retain `https://inference.local/v1`. Both paths put a scoped placeholder in the agent config instead of the real provider key. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.15`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading NemoClaw so their image includes the pinned runtime and profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. +The image installs hash-locked Deep Agents Code `0.1.71` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. NVIDIA Endpoints uses `https://integrate.api.nvidia.com/v1` through a least-privilege OpenShell provider attached to the sandbox. Supported fixed hosted providers also use their native endpoints through sandbox-attached providers. Custom endpoints that do not qualify for native attachment and existing legacy local routes retain `https://inference.local/v1` on the pinned OpenShell release; eligible new local selections use attached native endpoints. Both paths put a scoped placeholder in the agent config instead of the real provider key. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.15`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading NemoClaw so their image includes the pinned runtime and profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. diff --git a/docs/get-started/quickstart-pi.mdx b/docs/get-started/quickstart-pi.mdx index 66dc618ce80..e7dd3bc7308 100644 --- a/docs/get-started/quickstart-pi.mdx +++ b/docs/get-started/quickstart-pi.mdx @@ -49,7 +49,7 @@ For an existing installation, run the canonical onboarding command. nemoclaw onboard --agent pi --name my-pi ``` -Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. The credential remains in OpenShell provider state across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. +Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. The credential remains in OpenShell provider state across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. Stock onboarding selects a Pi managed-image digest. It does not build the Pi Dockerfile on the host. The reviewed Dockerfile is a trusted CI image-build source, not a user onboarding mechanism. A missing, incomplete, mutable, or inconsistent image contract fails before sandbox creation. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index 03d8b724438..f651f3aba8f 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -382,7 +382,7 @@ Use these details when your first-run path needs more control. After confirmation, NemoClaw registers the selected provider with OpenShell. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. - Custom and local providers retain the shared `inference.local` route. + Other custom endpoints and existing legacy local routes retain `inference.local` on the pinned OpenShell release. New OpenClaw local selections use sandbox-attached providers. The wizard asks whether to enable web search and offers Brave Search or Tavily Search. Provide `BRAVE_API_KEY` for Brave Search or `TAVILY_API_KEY` for Tavily Search when prompted. NemoClaw validates the selected key before it creates the sandbox, registers a sandbox-scoped OpenShell provider, and writes only an OpenShell resolver placeholder into the OpenClaw configuration. diff --git a/docs/inference/choose-local-inference-server.mdx b/docs/inference/choose-local-inference-server.mdx index bf94e8278ee..014427977c1 100644 --- a/docs/inference/choose-local-inference-server.mdx +++ b/docs/inference/choose-local-inference-server.mdx @@ -12,8 +12,9 @@ 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. -The agent inside the sandbox sends inference traffic to `inference.local`. -OpenShell intercepts that traffic and forwards it to the local endpoint configured during onboarding. +New OpenClaw and Deep Agents Code sandboxes use attached OpenShell providers for Ollama, vLLM, llama.cpp, and qualified host-local compatible endpoints. +Local NVIDIA NIM, other custom endpoints, Hermes local selections, and existing shared-route sandboxes use `inference.local` while OpenShell 0.0.116 remains pinned. +Refer to [How Inference Routing Works](../about-inference-routing) for route verification and migration. On native N1x Linux, use the Deferred managed-vLLM preview or enter standard onboarding explicitly. @@ -130,7 +131,8 @@ The profile performs these actions: - Never publishes the Docker host port on `0.0.0.0` or `::`. - Reuses the owner-only host-global managed-vLLM API key. -After the runtime passes its readiness check, onboarding registers the provider at `https://inference.local` inside the sandbox. +After the runtime passes its readiness check, new OpenClaw and Deep Agents Code sandboxes use an attached OpenShell provider. +Hermes uses `https://inference.local` while OpenShell 0.0.116 remains pinned. OpenShell reaches the authenticated server through the private bridge binding, while host-side readiness and recovery use the loopback binding. Verify the sandbox route: diff --git a/docs/inference/custom-endpoint-security.mdx b/docs/inference/custom-endpoint-security.mdx index e96812759ea..99e62593aed 100644 --- a/docs/inference/custom-endpoint-security.mdx +++ b/docs/inference/custom-endpoint-security.mdx @@ -13,9 +13,10 @@ NemoClaw keeps provider credentials on the host and validates explicit custom en ## Protect Provider Credentials -The agent inside the sandbox sends requests to `inference.local` instead of connecting to the upstream endpoint directly. -OpenShell forwards the traffic and injects the provider credential at egress. -The sandbox does not receive the raw API key. +For qualified host-local OpenAI-compatible endpoints, new OpenClaw and Deep Agents Code sandboxes use a sandbox-attached OpenShell provider at the host-local endpoint. +The agent presents an opaque credential reference, and OpenShell injects the provider credential at egress. +Other custom endpoints, Hermes, and retained legacy routes use `inference.local`, where OpenShell forwards the request and injects the credential. +Neither path exposes the raw upstream API key to the sandbox. Use `COMPATIBLE_API_KEY` for an OpenAI-compatible endpoint that requires authentication. For an HTTP endpoint on `localhost`, `127.0.0.1`, or `[::1]`, you can select no authentication on the port selected by `NEMOCLAW_VLLM_PORT` (`8000` by default) or port `11434`. diff --git a/docs/inference/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index 391e13918ff..010b6a2e382 100644 --- a/docs/inference/how-inference-routing-works.mdx +++ b/docs/inference/how-inference-routing-works.mdx @@ -36,11 +36,12 @@ OpenRouter attribution headers remain in the managed agent configuration. For an endpoint returned by Hermes login, NemoClaw records its accepted public IP addresses and restricts the provider and sandbox policy to those addresses. A different destination cannot gain access through a later DNS change. -Existing sandboxes without a native attachment retain their recorded shared route. -User-supplied endpoints, local inference, and Model Router also retain the shared route in this migration. +New OpenClaw and Deep Agents Code local selections, including qualified host-local `compatible-endpoint` routes, use sandbox-attached OpenShell providers. Each provider profile restricts the destination, request paths, executable, and endpoint-bound credential. Existing local sandboxes can continue running on their shared route while NemoClaw pins OpenShell 0.0.116. Other user-supplied endpoints, Hermes local selections, and Model Router still use the shared route in this release. + +OpenClaw and Deep Agents Code local sandboxes without a native provider attachment cannot resume or rebuild on that shared route. NemoClaw stops at resume or rebuild preflight, before changing the sandbox. Back up the sandbox, then re-onboard with `--fresh --name --recreate-sandbox` to attach a native provider. OpenShell 0.1.0 and later remove `inference.local`, so complete this replacement before upgrading OpenShell. The future upgrade must also migrate or retire remaining custom, Hermes local, and Model Router shared routes. This release does not migrate any of them automatically. ```text -Sandbox agent -> inference.local -> shared OpenShell route -> selected provider and model +Shared-route agent -> inference.local -> OpenShell gateway -> selected provider and model ``` Use `$$nemoclaw inference get` to inspect the selected sandbox's recorded route. @@ -54,14 +55,14 @@ 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. -Rebuilds of legacy local-inference sandboxes migrate away from stale OpenAI credential requirements. +New local selections use endpoint-bound credentials without a host `OPENAI_API_KEY`. 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. ## Deep Agents Configuration -For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with a managed OpenAI-compatible provider, a scoped placeholder API key, and `use_responses_api = false`. Supported native hosted selections use the endpoints above. Shared-route selections retain `https://inference.local/v1`. +For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with a managed OpenAI-compatible provider, a scoped placeholder API key, and `use_responses_api = false`. Native hosted selections use the endpoints above; new local selections use the qualified host-local endpoint from their attached provider. Existing shared-route sandboxes and other custom selections use `https://inference.local/v1` while running on OpenShell 0.0.116. The managed `dcode` runtime uses Chat Completions through OpenShell even when a compatible endpoint also supports the Responses API. diff --git a/docs/inference/model-capability-audit.mdx b/docs/inference/model-capability-audit.mdx index 33b6a409dc9..800f7613c3a 100644 --- a/docs/inference/model-capability-audit.mdx +++ b/docs/inference/model-capability-audit.mdx @@ -124,9 +124,9 @@ When importing a completed row from an issue comment, preserve the commit SHA, w | OpenClaw primary agent | OpenAI | Any model from `REMOTE_MODEL_OPTIONS.openai` | Sandbox-attached native OpenAI provider at `https://api.openai.com/v1`. | `not-yet-run` | Add one evidence row per model before changing state. | Record Responses or Chat Completions behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Anthropic | Any model from `REMOTE_MODEL_OPTIONS.anthropic` | Sandbox-attached native Anthropic provider at `https://api.anthropic.com` with `anthropic-messages`. | `not-yet-run` | Add one evidence row per model before changing state. | Record native Anthropic Messages behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Gemini | Any model from `REMOTE_MODEL_OPTIONS.gemini` | Sandbox-attached native Gemini provider at `https://generativelanguage.googleapis.com/v1beta/openai/`. | `not-yet-run` | Add one evidence row per model before changing state. | Record provider state and tool-result continuation behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | -| OpenClaw primary agent | Local Ollama | Default `nemotron-3-nano:30b` or any installed model selected by onboarding. | Managed `inference.local` route to the host Ollama proxy. | `not-yet-run` | Add local daemon, model tag, and trajectory evidence before changing state. | Record tool capability, streaming usage, and local proxy behavior. | Add one row per audited local model tag. | `src/lib/inference/local.ts`, `src/lib/inference/config.ts`. | -| OpenClaw primary agent | Local vLLM | Any model from `VLLM_MODELS`. | Managed `inference.local` route to the host vLLM server. | `not-yet-run` | Add vLLM serve flags, model id, and trajectory evidence before changing state. | Record parser flags, reasoning parser, and tool-call parser behavior. | Add one row per audited vLLM model id. | `src/lib/inference/vllm-models.ts`, `src/lib/inference/config.ts`. | -| OpenClaw primary agent | Other OpenAI-compatible endpoint | User-selected `custom-model` or another configured model id. | Managed `inference.local` route to the compatible endpoint. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record endpoint API path forcing and store/streaming assumptions. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | +| OpenClaw primary agent | Local Ollama | Default `nemotron-3-nano:30b` or any installed model selected by onboarding. | Sandbox-attached OpenShell provider at the host Ollama endpoint; retained legacy routes use `inference.local`. | `not-yet-run` | Add local daemon, model tag, and trajectory evidence before changing state. | Record tool capability, streaming usage, and local proxy behavior. | Add one row per audited local model tag. | `src/lib/inference/local.ts`, `src/lib/inference/config.ts`. | +| OpenClaw primary agent | Local vLLM | Any model from `VLLM_MODELS`. | Sandbox-attached OpenShell provider at the host vLLM endpoint; retained legacy routes use `inference.local`. | `not-yet-run` | Add vLLM serve flags, model id, and trajectory evidence before changing state. | Record parser flags, reasoning parser, and tool-call parser behavior. | Add one row per audited vLLM model id. | `src/lib/inference/vllm-models.ts`, `src/lib/inference/config.ts`. | +| OpenClaw primary agent | Other OpenAI-compatible endpoint | User-selected `custom-model` or another configured model id. | Sandbox-attached OpenShell provider for qualified host-local endpoints; other endpoints and retained legacy routes use `inference.local`. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record endpoint API path forcing and store/streaming assumptions. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | | OpenClaw primary agent | Other Anthropic-compatible endpoint | User-selected `custom-anthropic-model` or another configured model id. | `anthropic` route when supported, otherwise managed compatible route. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record native Anthropic Messages or compatible-route transport behavior. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | | Hermes sandbox API | Hermes Provider | Default `moonshotai/kimi-k2.6` or any model from `HERMES_PROVIDER_MODEL_OPTIONS`. | Hermes Provider route through NemoClaw managed inference. | `not-yet-run` | Add Hermes session, request dump, logs, and local API evidence before changing state. | Generated config uses native `tools.tool_search.enabled: on` with snake-case 5/20 limits; core tools stay direct while deferred MCP and non-core plugin tools use structured search, describe, and call. | Verify a deferred-tool trajectory and keep it separate from OpenClaw `mode: tools` evidence. | `agents/hermes/config/managed-policy.ts`, `test/generation/generate-hermes-config.test.ts`. | | Deep Agents interactive `dcode` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add separate default-disabled and thread-opt-in terminal transcripts, host status output, reset evidence, and route evidence before changing state. | The managed Ultra profile preserves required nonempty tool-call content and rejects the observed literal `[content]` execute placeholder before shell dispatch; optional `thread-opt-in` remains a per-thread approval affordance. | Verify a terminal task with approval prompts intact, then separately verify explicit thread activation, reset behavior, policy enforcement, placeholder rejection, and no provider credential in sandbox-visible files. | `agents/langchain-deepagents-code/generate-config.ts`, `agents/langchain-deepagents-code/profile-plugin`, `docs/get-started/quickstart-langchain-deepagents-code`. | diff --git a/docs/inference/set-up-llama-cpp.mdx b/docs/inference/set-up-llama-cpp.mdx index b0b0aa16143..9592fa353ff 100644 --- a/docs/inference/set-up-llama-cpp.mdx +++ b/docs/inference/set-up-llama-cpp.mdx @@ -11,13 +11,15 @@ content: --- NemoClaw provides two first-class llama.cpp paths. You can attach an authenticated server that you operate, or let NemoClaw select and materialize a compatible repository-owned profile. -Both paths are experimental and use OpenAI Chat Completions through `https://inference.local/v1`. +Both paths are experimental and use OpenAI Chat Completions. +New OpenClaw and Deep Agents Code sandboxes use a sandbox-attached OpenShell provider at the host-local endpoint. +Hermes and retained legacy routes use `https://inference.local/v1`. ## Choose a llama.cpp Path | Path | NemoClaw manages | You manage | Use it when | |---|---|---|---| -| Existing server | Provider registration, route validation, and sandbox traffic through `inference.local`. | The server binary or container, GGUF file, launch configuration, credential, upgrades, and lifecycle. | Your authenticated server already satisfies the llama.cpp fingerprint contract on loopback port `8081`. | +| Existing server | Provider registration, route validation, and credential injection at sandbox egress. | The server binary or container, GGUF file, launch configuration, credential, upgrades, and lifecycle. | Your authenticated server already satisfies the llama.cpp fingerprint contract on loopback port `8081`. | | Managed NVIDIA GPU host | The exact YAML-selected image, GGUF acquisition and verification, launch configuration, credential, Docker lifecycle, diagnostics, and cleanup. | A qualified DGX Spark Arm64, Linux x86_64 NVIDIA GPU, or Windows WSL N1x or Station GB300 host, plus the recipe readiness requirements and any required Hugging Face credential. | You want a repository-owned managed llama.cpp profile without managing `llama-server` directly. | Compared with other local options, Ollama emphasizes a simple local model workflow, while managed vLLM provides host-specific NVIDIA GPU profiles and broader model selection. @@ -247,7 +249,7 @@ Onboarding performs these actions: - Verifies the GGUF size and SHA-256 digest before it starts the runtime. - Runs the authenticated container as the current non-root user with one NVIDIA GPU and no CPU fallback. - Starts a host-owned private bridge on `127.0.0.1:8081` and connects the container to a Docker internal network without a Docker-published port. -- Registers `llama-cpp-local` and routes agent traffic through `https://inference.local/v1`. +- Registers the local provider and attaches it to new OpenClaw and Deep Agents Code sandboxes. Hermes and retained legacy routes use `llama-cpp-local` through `https://inference.local/v1`. The runtime cannot download a model and has no egress on its internal Docker network. The recipe disables the Web UI, slot inspection, server tools, agent mode, Model Context Protocol proxy, router, and multimodal projection. diff --git a/docs/inference/set-up-openai-compatible-endpoint.mdx b/docs/inference/set-up-openai-compatible-endpoint.mdx index 3ffd7fdd5e5..1cc3af2473b 100644 --- a/docs/inference/set-up-openai-compatible-endpoint.mdx +++ b/docs/inference/set-up-openai-compatible-endpoint.mdx @@ -13,8 +13,9 @@ content: Use the custom OpenAI-compatible provider for servers that implement `/v1/chat/completions` or a compatible `/v1/responses` API. Examples include vLLM, TensorRT-LLM, llama.cpp, LocalAI, and other compatible servers. -The agent connects to `inference.local` inside the sandbox. -OpenShell forwards that traffic to the endpoint configured during onboarding. +New OpenClaw and Deep Agents Code sandboxes use an attached OpenShell provider for qualified host-local HTTP endpoints. +Hermes and other custom endpoint routes use `inference.local` while OpenShell 0.0.116 remains pinned. +Refer to [How Inference Routing Works](../about-inference-routing) for route verification and migration. ## Start the Server @@ -61,8 +62,9 @@ Enter the server base URL and the model ID reported by the server. Use a host-routable URL such as `http://localhost:8000/v1` when you want onboarding to verify the API, tool-calling, and streaming paths before gateway registration. To qualify for automatic rewriting, an HTTP endpoint URL must use the loopback host `localhost`, `127.0.0.1`, or `[::1]`. Automatic rewriting is limited to the port selected by `NEMOCLAW_VLLM_PORT` (`8000` by default) and ports `11434` and `11435`. -NemoClaw validates the entered URL from the host and registers the OpenShell gateway route through `host.openshell.internal:` for sandbox traffic. -Sandbox inference requests continue to use the base `inference.local` policy, so the managed compatible-endpoint route does not require adding the `local-inference` preset. +NemoClaw validates the entered URL from the host and rewrites qualified loopback URLs through `host.openshell.internal:` for sandbox traffic. +New OpenClaw and Deep Agents Code sandboxes use an attached provider for that route. +Other custom endpoint routes use the base `inference.local` policy and do not require the `local-inference` preset. For authenticated endpoints, NemoClaw leaves URLs without an explicit port, URLs on `:80` or another privileged port, and URLs on unsupported ports unchanged. Those authenticated URLs require a separately compatible runtime topology and network policy. This rewrite depends on an OpenShell topology that resolves `host.openshell.internal` inside the sandbox; if that bridge is unavailable, onboarding can still validate the host URL, but `$$nemoclaw status` is the authoritative runtime check. diff --git a/docs/inference/set-up-vllm.mdx b/docs/inference/set-up-vllm.mdx index 07ef11021e0..f5755c44f04 100644 --- a/docs/inference/set-up-vllm.mdx +++ b/docs/inference/set-up-vllm.mdx @@ -32,7 +32,9 @@ Do not expose the port to your LAN or the internet. An authenticated fixed profile publishes the configured host port on exactly two host addresses: `127.0.0.1` and the private IPv4 gateway of the `openshell-docker` bridge. The container continues to listen on its recipe-owned internal port `8000`. It never publishes that host port on `0.0.0.0` or `::`. -The provider route remains `https://inference.local` inside the sandbox, and OpenShell reaches the server through the private bridge binding. +New OpenClaw and Deep Agents Code local selections use a sandbox-attached provider at the qualified host-local endpoint. +Hermes and retained legacy selections use `https://inference.local`. +OpenShell reaches the server through the private bridge binding. The managed Muse Glimmer profile uses the same bearer-protected listener and two-address publication boundary. The qualified two-DGX Spark and two-DGX Station paths use bearer-protected `/v1` routes and Docker host networking on both runtime containers; network isolation remains required for other endpoints and distributed traffic. diff --git a/docs/inference/understand-provider-validation.mdx b/docs/inference/understand-provider-validation.mdx index e1ba247d649..d9241ff62a6 100644 --- a/docs/inference/understand-provider-validation.mdx +++ b/docs/inference/understand-provider-validation.mdx @@ -52,7 +52,7 @@ If the last retry fails or times out, validation stops without another Chat Comp -The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. +The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. `NEMOCLAW_PREFERRED_API` does not change that runtime selection. @@ -109,7 +109,8 @@ Verify that route from inside the sandbox after onboarding. -For OpenClaw, the compatible endpoint check validates `inference.local` from inside the sandbox only when the selected provider is `compatible-endpoint`. +For OpenClaw, the `compatible-endpoint` check probes the selected inference path from inside the sandbox. +Qualified host-local selections use their attached provider; other compatible endpoints use `inference.local`. The check runs whether or not you select a messaging channel and stops onboarding if the route fails. diff --git a/docs/inference/use-shared-gateway-routes.mdx b/docs/inference/use-shared-gateway-routes.mdx index 112040a236d..d0a311e60e4 100644 --- a/docs/inference/use-shared-gateway-routes.mdx +++ b/docs/inference/use-shared-gateway-routes.mdx @@ -10,8 +10,8 @@ content: type: "how_to" --- -These rules apply to providers that still use the shared route, including user-supplied compatible endpoints and local providers. -NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider use sandbox-attached native providers instead. Changing their selected model or provider does not re-point the shared route. +These rules apply to providers that still use the shared route, including user-supplied compatible endpoints outside the qualified host-local OpenClaw and Deep Agents Code route, Hermes local selections, Model Router, and existing local sandboxes while OpenShell 0.0.116 is pinned. OpenClaw and Deep Agents Code local sandboxes without a native attachment must be backed up and freshly re-onboarded before resume, rebuild, or an OpenShell upgrade. +NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, Hermes Provider, and new OpenClaw or Deep Agents Code local selections use sandbox-attached native providers instead. Changing 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. diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 7ca7e596600..0cf877b2bf3 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -322,6 +322,7 @@ A valid credential stored in OpenShell does not bypass validation of a supplied Use the recovery guidance that matches the reported check: +- If an OpenClaw or Deep Agents Code local sandbox still records a shared route without a native provider attachment, back up its data and freshly re-onboard it with `--fresh --name --recreate-sandbox`. Rebuild stops before backup or deletion; it cannot convert that legacy route. Complete the replacement before upgrading OpenShell beyond 0.0.116. - Verify the sandbox name when its registry entry is missing. - Follow the printed OpenShell gateway recovery steps when the gateway schema is incompatible. - Correct the exported API key when rebuild reports `the host inference credential could not be validated`. @@ -345,7 +346,7 @@ Use the recovery guidance that matches the reported check: before deletion if the handoff is missing or changed. -A gateway that reports no live inference route does not stop the rebuild. Replacement onboarding configures and verifies the recorded route before it recreates the sandbox. +A gateway that reports no live inference route does not stop rebuild for supported selections. Replacement onboarding configures and verifies the recorded route before it recreates the sandbox. The rebuild command preserves the mounted workspace and carries the complete diff --git a/docs/manage-sandboxes/workspace-files.mdx b/docs/manage-sandboxes/workspace-files.mdx index 0d77554ed7a..94817b5a70b 100644 --- a/docs/manage-sandboxes/workspace-files.mdx +++ b/docs/manage-sandboxes/workspace-files.mdx @@ -283,7 +283,7 @@ Deep Agents Code normally creates the `/sandbox/.deepagents/agent/` paths below | Path | Purpose | |---|---| -| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path, using native endpoints for NVIDIA Endpoints and supported fixed hosted providers, or shared `inference.local` routes for custom and local providers. | +| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path. NVIDIA Endpoints and fixed hosted providers use attached provider endpoints. Eligible new local selections use them after native provider attachment. Custom endpoints that do not qualify for native attachment and existing legacy routes retain `inference.local` on the pinned release. | | `/sandbox/.deepagents/.state/` | Deep Agents Code runtime state, including persisted session and MCP-related state. | | `/sandbox/.deepagents/agent/AGENTS.md` | Global memory file for the default Deep Agents Code agent, loaded at session start. | | `/sandbox/.deepagents/agent/memories/` | Topic-specific markdown memories that Deep Agents Code can read and update across sessions. | diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 9339ceeb573..512dc2b6b12 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -29,8 +29,8 @@ graph LR USER(["👤 User"]):::user subgraph EXTERNAL["External Services"] - SHARED_INFERENCE["Shared-route inference providers
Custom endpoints · Ollama
vLLM · Model Router
"]:::external - NVIDIA_INFERENCE["Native inference providers
NVIDIA · fixed hosted providers"]:::external + SHARED_INFERENCE["Shared-route inference providers
Other custom · legacy local
Hermes local · Model Router
"]:::external + NVIDIA_INFERENCE["Attached inference providers
NVIDIA · fixed hosted
OpenClaw and DCode local
"]:::external INTEGRATIONS["Integration APIs
MCP · GitHub · package indexes"]:::external INTERNET["Internet
PyPI · npm · GitHub · APIs"]:::external end @@ -65,7 +65,7 @@ graph LR BP -->|"Defines sandbox
shape + policies"| SANDBOX STATE -->|"Backup + restore"| SANDBOX - AGENT -->|"Custom and local requests
inference.local · placeholder credentials"| GW + AGENT -->|"Shared-route requests
inference.local · placeholder credentials"| GW GW -->|"Shared-route request with
credential injected"| SHARED_INFERENCE AGENT -->|"Attached native provider
restricted request · placeholder credential"| NVIDIA_INFERENCE @@ -171,8 +171,8 @@ graph TB end end - SHARED_INFER["Shared-route inference provider
Custom endpoints · Ollama
vLLM · Model Router
"]:::external - NVIDIA_INFER["Native inference providers
NVIDIA · fixed hosted providers"]:::external + SHARED_INFER["Shared-route inference provider
Other custom · legacy local
Hermes local · Model Router
"]:::external + NVIDIA_INFER["Attached inference providers
NVIDIA · fixed hosted
OpenClaw and DCode local
"]:::external CLI -->|"openshell CLI
(orchestrates)"| GW GW -->|"creates/recreates
Docker-driver sandbox"| SANDBOX @@ -195,12 +195,12 @@ Layering from top to bottom: | Docker daemon | Host service | Runs the Docker-driver sandbox container and, on affected Linux hosts, the optional gateway compatibility container. | | Sandbox container | Docker container | Runs the selected supported agent runtime and NemoClaw integration under Landlock + seccomp + netns. | | OpenShell L7 proxy | Gateway process | Intercepts shared-route agent egress and rewrites `Authorization` headers (Bearer/Bot) and URL-path segments to inject the real credential at the network boundary. | -| OpenShell attached native provider | Provider profile attached to the sandbox | Restricts NVIDIA and fixed hosted provider egress by host, method, path, and binary, then rewrites the placeholder credential at the egress boundary. | +| OpenShell attached native provider | Provider profile attached to the sandbox | Restricts NVIDIA, fixed hosted, and new OpenClaw or Deep Agents Code local provider egress by host, method, path, and binary, then rewrites the placeholder credential at the egress boundary. | NemoClaw never gives the sandbox a raw provider key. At onboard time it registers credentials with OpenShell's provider and placeholder system. Shared routes use the gateway L7 proxy to substitute the real value at egress. -NVIDIA Endpoints and supported fixed hosted providers use sandbox-attached provider profiles to enforce restricted requests and replace placeholder credentials at egress. +NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw and Deep Agents Code local selections use sandbox-attached provider profiles to restrict requests and replace placeholder credentials at egress. The CLI helper `isInferenceRouteReady` (in `src/lib/onboard.ts`) is a host-side readiness check used by the resume flow to decide whether the active route already covers the chosen provider and model. It is not a runtime component. @@ -358,13 +358,13 @@ Inside the sandbox: ## Inference Routing Agent inference follows one of two OpenShell-managed paths. -Custom and local providers retain the shared `inference.local` route through the OpenShell gateway: +Other custom endpoints, Hermes local selections, and existing legacy local routes use `inference.local` through the pinned OpenShell 0.0.116 gateway: ```text Supported agent runtime (sandbox) ──▶ inference.local ──▶ OpenShell gateway ──▶ Provider endpoint ``` -NVIDIA Endpoints and supported fixed hosted providers use restricted providers attached to the sandbox. For example, NVIDIA Endpoints uses this path: +NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections, including qualified host-local `compatible-endpoint` routes, 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 743022336ec..edc2ec5efce 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1207,7 +1207,7 @@ During that lease, another `launch` still verifies these conditions: - The recorded inference selection matches its provider path, and every configured route serves a valid response to a bounded request for the recorded model. 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`. + Retained legacy and other custom selections use `inference.local`; new OpenClaw local selections use attached native endpoints, while Hermes local routing remains shared. 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`. @@ -1217,7 +1217,7 @@ During that lease, another `launch` still verifies these conditions: - The recorded inference selection matches its provider path, and every configured route serves a valid response to a bounded request for the recorded model. 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`. + Retained legacy and other custom selections use `inference.local`; new Deep Agents Code local selections use attached native endpoints. 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. @@ -1719,7 +1719,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 and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. 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 OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. 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` @@ -1767,7 +1767,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 and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. 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 OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. 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 | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -2123,7 +2123,7 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet`
-`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. +`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. @@ -2710,7 +2710,7 @@ unset LOCAL_MCP_TOKEN Preview or apply the one-time conversion from the retired host-registry representation and legacy agent adapter file to the agent's native MCP configuration. The preview is read-only and is the default. Pass `--apply` to authorize native materialization and legacy cleanup only after the native result verifies successfully. Native state wins: when the native and legacy definitions conflict, migration stops before any mutation and requires you to resolve the conflict explicitly. -OpenClaw converts managed Mcporter entries into `openclaw.json` `mcp.servers`. Deep Agents carries legacy `.deepagents/.nemoclaw-mcp.json` entries through a normal rebuild into `.deepagents/.mcp.json`, then removes the verified legacy projection. Hermes already uses native `config.yaml` and ordinarily requires no file conversion. Existing OpenShell policy, provider, attachment, and credential state are reused; migration never copies a raw credential into agent configuration. The live OpenShell policy owns denied-tool selectors, and a conflicting legacy-registry selector stops before mutation. OpenClaw migration reloads and verifies the running gateway before legacy cleanup. +OpenClaw converts managed Mcporter entries into `openclaw.json` `mcp.servers`. Deep Agents carries legacy `.deepagents/.nemoclaw-mcp.json` entries through a normal rebuild into `.deepagents/.mcp.json`, then removes the existing legacy projection. Hermes already uses native `config.yaml` and ordinarily requires no file conversion. Existing OpenShell policy, provider, attachment, and credential state are reused; migration never copies a raw credential into agent configuration. The live OpenShell policy owns denied-tool selectors, and a conflicting legacy-registry selector stops before mutation. OpenClaw migration reloads and verifies the running gateway before legacy cleanup. ```bash $$nemoclaw my-assistant mcp migrate @@ -3320,7 +3320,7 @@ After the rebuild succeeds, retrieve the replacement token with `nemohermes my-a -After restore, the command starts Deep Agents with the complete source native home, including `config.toml`, hooks, skills, memories, histories, packages, and unrelated native entries. Before changing the sandbox, rebuild verifies that the recorded provider path is still reachable and that the target provider, model, reasoning settings, web search selection, base image, current agent MCP source, and current live OpenShell policy can be captured. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers 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. +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 OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. 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. @@ -3624,7 +3624,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. New OpenClaw local selections, including qualified host-local `compatible-endpoint` routes, use an attached native provider; other custom endpoints retain their 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. @@ -3649,7 +3649,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. The following route-conflict rules apply to providers that still use the shared gateway route, including custom endpoints and local providers. +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 other custom endpoints and Hermes local providers. 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. @@ -3672,7 +3672,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. Custom endpoints and local providers 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. +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. For OpenClaw, new local selections, including qualified host-local `compatible-endpoint` routes, use an attached native provider; other custom endpoints retain the shared-route workflow. Hermes local selections continue to use the shared route. NemoClaw resolves the OpenShell gateway from the target sandbox's recorded gateway binding, including non-default `NEMOCLAW_GATEWAY_PORT` deployments. Do not run `openshell inference set` directly on a shared NemoClaw gateway because that bypasses registry compatibility checks and can break other sandboxes. When either flag is missing, `$$nemoclaw inference set` reports both required flags without suggesting a raw OpenShell command. The command updates the host registry after the selected inference path changes. diff --git a/docs/reference/enterprise-readiness.mdx b/docs/reference/enterprise-readiness.mdx index 987bb92dcec..c8cd6929bc6 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 and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. 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 OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. 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 and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. +- Explain that inference credentials remain in OpenShell provider state, so the sandbox never holds provider keys. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. - Frame centralized fleet management, operator RBAC, enterprise SSO, and multi-tenant isolation as roadmap-only or out of scope today, and avoid presenting them as current capabilities. - Position cost controls and spend limits as provider-owned, and recommend setting provider-side limits for unattended agents. - When a customer hits a known limitation, point to the workaround in this guide and the tracked issue rather than promising a fix date. diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index 11cd4b49639..cdf9ecbc0d3 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -78,7 +78,7 @@ Hermes baseline endpoint groups are declared by the Hermes agent policy addition | Policy | Endpoints | Binaries | Rules | | --- | --- | --- | --- | -| `managed_inference` | `inference.local:443` | `/usr/local/bin/dcode`, `/opt/venv/bin/python3*`, `/opt/venv/lib/python3.13/**` | POST to OpenAI-compatible completion and embedding paths, GET to model listings | +| `managed_inference` | `inference.local:443` for shared-route selections | `/usr/local/bin/dcode`, `/opt/venv/bin/python3*`, `/opt/venv/lib/python3.13/**` | POST to OpenAI-compatible completion and embedding paths, GET to model listings | | `github` | `github.com:443`, `api.github.com:443`, `raw.githubusercontent.com:443` | `/usr/bin/git`, `/usr/local/bin/dcode`, `/opt/venv/bin/python3*` | Full access to `github.com` and `api.github.com`; GET and HEAD only to `raw.githubusercontent.com` | | `pypi` | `pypi.org:443`, `files.pythonhosted.org:443` | `/opt/venv/bin/python3*`, `/opt/venv/bin/pip3*` | GET for package installation | @@ -90,9 +90,9 @@ When you select NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1 This attached provider is the effective NVIDIA Endpoints route. Its profile permits only `GET /v1/models` and `POST /v1/chat/completions` at `integrate.api.nvidia.com:443` from the listed agent-runtime and readiness-verification binaries. The NVIDIA API key remains in OpenShell provider state and does not enter the sandbox. -OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider also use sandbox-attached native providers. NemoClaw derives the `native_hosted_inference` policy from the selected provider profile, restricting endpoint hosts, request paths, methods, and agent-runtime binaries. OpenShell replaces credential placeholders at that boundary; raw provider credentials remain outside the sandbox. Retained legacy routes, custom endpoints, and local providers continue to use the shared `inference.local` route. +OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider also use sandbox-attached native providers. NemoClaw derives the `native_hosted_inference` policy from the selected provider profile, restricting endpoint hosts, request paths, methods, and agent-runtime binaries. New OpenClaw and Deep Agents Code local selections use attached host-local provider profiles with endpoint-bound credentials. OpenShell replaces credential placeholders at that boundary; raw provider credentials remain outside the sandbox. Existing legacy routes, other custom endpoints, Hermes local selections, and Model Router still use the shared `inference.local` route on the pinned release. -All endpoints use TLS termination and are enforced at port 443. +The hosted inference providers above use TLS on port 443. Attached local providers use their qualified HTTP port. @@ -219,7 +219,7 @@ Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced ### Inference -NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. In both cases, OpenShell mediates inference traffic and keeps provider credentials outside the sandbox. +NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom selections and existing legacy shared routes use `inference.local`. In both cases, OpenShell mediates inference traffic and keeps provider credentials outside the sandbox. diff --git a/docs/reference/pi-support.mdx b/docs/reference/pi-support.mdx index eebbb4bfc70..b63087bc4db 100644 --- a/docs/reference/pi-support.mdx +++ b/docs/reference/pi-support.mdx @@ -60,7 +60,7 @@ Each receipt must match the protected inputs and an image digest in the candidat Pi reads a generated `/sandbox/.pi/agent/models.json` file. The file contains the model, managed route, API family, and a non-secret route placeholder. It does not contain the upstream provider credential. -The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. Direct unmanaged provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. +The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. Direct unmanaged provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. For OpenRouter, Pi uses `https://openrouter.ai/api/v1` through its recorded native provider. Readiness requires a successful bounded inference request for the selected model. diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index 82919309a7b..65247a57f57 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -65,7 +65,7 @@ Pick the matching onboarding entry point for each agent. |-------|--------|---------|-------| | OpenClaw | Tested | Yes | Default agent runtime. Onboard with `nemoclaw onboard` (no `--agent` flag required). | | Hermes | Tested | No | First-class agent with dedicated CLI (`nemohermes`), Dockerfile, manifest, docs, and Hermes E2E coverage in `.github/workflows/e2e.yaml` (`hermes-e2e`, `hermes-*`, and Hermes rebuild/switch jobs). Onboard with `nemohermes onboard` or `nemoclaw onboard --agent hermes`. Unlocks the Hermes Provider inference route. Known structural gaps: model-provider compatibility registry is empty (backfilled after failures, see `nemoclaw-blueprint/model-specific-setup/hermes/README.md`); no Hermes-specific unit tests in `nemoclaw/src/`; macOS and WSL CI suites do not differentiate agents. Suitable for evaluation and the documented onboarding paths; production parity with OpenClaw is not yet asserted. | -| LangChain Deep Agents Code | Tested | No | Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861. | +| LangChain Deep Agents Code | Tested | No | Terminal-oriented coding agent runtime with no in-sandbox gateway or dashboard, built on the Deep Agents SDK. Its manifest is `agents/langchain-deepagents-code/manifest.yaml`, and its binary is `dcode`. Onboard with `nemo-deepagents onboard` or `nemoclaw onboard --agent langchain-deepagents-code`, and follow [the quickstart](/user-guide/deepagents/get-started/quickstart). NemoClaw runs it as a managed agent runtime: unmanaged sandbox, Model Context Protocol (MCP) server, and shell overrides are rejected, and credential-bearing proxy URLs are dropped from persisted shell environment values. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. New local selections, including qualified host-local compatible endpoints, use sandbox-attached OpenShell providers. Other custom endpoints and existing shared-route sandboxes use `inference.local` while OpenShell remains pinned to 0.0.116. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861. | {/* agent-status:end */} ## Platforms @@ -135,7 +135,7 @@ Each row below is a launch-facing capability claim that NemoClaw makes in docs, |------------|--------|-------| | Guided onboarding | Tested | Single-command interactive wizard (`$$nemoclaw onboard`) that walks the user through inference provider selection, credential setup, and sandbox creation or update. It opens the agent dashboard when the selected runtime provides one. Non-interactive mode is supported with `--non-interactive` and `NEMOCLAW_*` environment variables for CI and scripted installs. | | Sandboxed execution | Tested with limitations | Landlock, seccomp, network namespace isolation, no-new-privileges, privilege dropping, and process limits (nproc 512 at `scripts/lib/sandbox-rlimits.sh:8`) are tested and on by default. OpenShell owns capability enforcement for managed entrypoints, exec processes, and connect shells; those paths do not call NemoClaw capability handling. Direct container runtimes that explicitly override the image user to root retain the existing compatibility drop and required `setpriv` transition. Direct container launches must configure capabilities at the container runtime. | -| Managed inference | Tested | Provider-routed model calls through OpenShell, transparent to the agent. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table. | +| Managed inference | Tested | Provider-routed model calls through OpenShell, transparent to the agent. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. New OpenClaw and LangChain Deep Agents Code local selections, including qualified host-local compatible endpoints, use sandbox-attached OpenShell providers. Hermes and Pi local selections, other custom endpoints, and existing shared-route sandboxes use `inference.local` while OpenShell remains pinned to 0.0.116. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table. | | Declarative network policy | Tested | YAML-defined egress with policy presets. Presets include `slack`, `discord`, `telegram`, `weather`, `openclaw-pricing`, `huggingface`, `npm`, `pypi`, `brew`, and others. Hot-reloadable at runtime with `$$nemoclaw policy add`. | | State persistence and rebuild transfer | Tested | OpenShell preserves the native agent home during routine lifecycle operations. Before destructive replacement, NemoClaw archives and integrity-checks the complete native home/workspace, then restores it into the replacement sandbox. | | Agent skills | Tested | Packaged agent skills are discoverable by Cursor, Claude Code, and other coding assistants under `.agents/skills/`. Skills also install into the sandbox with `$$nemoclaw skill install`. | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 7af29d8efd5..eddc90cb6ce 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -2192,7 +2192,7 @@ $$nemoclaw onboard --fresh --name --recreate-sandbox -Every OpenClaw onboarding run with a custom OpenAI-compatible endpoint sends a validation request through `inference.local` from inside the sandbox, even when you select no messaging channel. +OpenClaw onboarding sends a validation request from inside the sandbox, even when you select no messaging channel. Supported host-local OpenAI-compatible endpoints use the sandbox-attached native provider; other custom OpenAI-compatible endpoints use `inference.local`. If that sandbox validation request fails, fix the compatible-endpoint base URL, credentials, model, or network route before continuing onboarding. Messaging setup is not the root cause. diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index 4cc6be7f8df..b1e4655989e 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -114,7 +114,7 @@ NemoClaw allows a credential source only in the process that is intended to hold | Execution path | Rule | |---|---| -| Host-brokered provider | Discover and use host credentials only through OpenShell-managed providers. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. The sandbox receives no raw host credential. | +| Host-brokered provider | Discover and use host credentials only through OpenShell-managed providers. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. The sandbox receives no raw host credential. | | Sandbox-direct provider | Keep only credential sources that are deliberately provisioned and reachable inside the sandbox. | | Ambient metadata provider | Disable SDK discovery when the metadata endpoint cannot exist across the sandbox boundary. Do not make an internal or link-local endpoint reachable merely to satisfy an automatic probe. | | New agent or provider | Declare the enabled credential sources and add agent-specific tests proving that unavailable sources are not probed. | @@ -144,7 +144,7 @@ NemoClaw's host-local Amazon Bedrock adapter runs outside this sandbox credentia #### Hermes Managed Inference Credential Discovery -NemoClaw configures Hermes with a custom provider. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. The shipped Hermes image does not install the optional native Bedrock dependency. +NemoClaw configures Hermes with a custom provider. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. The shipped Hermes image does not install the optional native Bedrock dependency. AWS credential discovery for supported Bedrock inference therefore remains in NemoClaw's host-local adapter, outside the sandbox. If direct Hermes Bedrock support is added later, it must apply the same unavailable-metadata rule and include Hermes-specific credential-probe acceptance tests before it is enabled. @@ -153,7 +153,7 @@ If direct Hermes Bedrock support is added later, it must apply the same unavaila #### Deep Agents Managed Inference Credential Discovery -NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route. NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. +NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. The sandbox receives a placeholder route key, not the upstream provider credential. The managed launchers reject credential-shaped environment values and upstream auth files before Deep Agents Code starts, so provider discovery stays on the host-side OpenShell boundary. If you need a new sandbox-direct credential source, design it as an explicit provider or MCP integration instead of placing secrets in `/sandbox/.deepagents`. @@ -327,7 +327,7 @@ The agent never receives the provider API key. | Aspect | Detail | |---|---| -| Default | NVIDIA Endpoints and supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers. Custom and local providers retain the shared `inference.local` route. OpenShell owns the credential and upstream endpoint in both cases. | +| Default | NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Other custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. OpenShell owns the credential and upstream endpoint in both cases. | | What you can change | You select a supported provider. NemoClaw selects and enforces that provider's managed path. | | Risk if bypassed | Adding an unowned provider endpoint to network policy bypasses NemoClaw's managed provider boundary and could let an agent use a stolen or hardcoded key. The NVIDIA Endpoints path is not a bypass: its checked-in OpenShell provider profile restricts the endpoint, methods, paths, and binaries, then rewrites a placeholder credential at the egress boundary. | | Recommendation | Do not add inference provider hosts to network policy for NemoClaw model traffic. Use the provider path created by onboarding. The `claude-code` preset is a separate opt-in exception for running the Claude Code CLI with its own credentials, not a way to configure NemoClaw inference. | diff --git a/nemoclaw/src/shared/credential-filter-boundary.cts b/nemoclaw/src/shared/credential-filter-boundary.cts index bf35b846f34..487c969a0d6 100644 --- a/nemoclaw/src/shared/credential-filter-boundary.cts +++ b/nemoclaw/src/shared/credential-filter-boundary.cts @@ -133,6 +133,7 @@ const SAFE_CREDENTIAL_PLACEHOLDER_LITERALS: ReadonlySet = new Set([ // Hermes requires an sk-prefixed value in its config, but OpenShell replaces // this reserved non-secret sentinel at the proxy boundary before inference. "sk-OPENSHELL-PROXY-REWRITE", + "sk-OPENSHELL-RESOLVE-ENV-NEMOCLAW_LOCAL_INFERENCE_TOKEN", CREDENTIAL_PLACEHOLDER, ]); diff --git a/nemoclaw/src/shared/credential-filter-boundary.test.ts b/nemoclaw/src/shared/credential-filter-boundary.test.ts index cf00dccce18..6f70aeaa5a3 100644 --- a/nemoclaw/src/shared/credential-filter-boundary.test.ts +++ b/nemoclaw/src/shared/credential-filter-boundary.test.ts @@ -134,10 +134,23 @@ describe("shared credential filter", () => { "openshell:resolve:env:GITHUB_TOKEN", "Bearer openshell:resolve:env:REMOTE_MCP_TOKEN", "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_TOKEN", + "sk-OPENSHELL-RESOLVE-ENV-NEMOCLAW_LOCAL_INFERENCE_TOKEN", ])("preserves credential reference %s (#8291)", (value) => { expect(isSafeCredentialPlaceholder(value), value).toBe(true); }); + it("preserves only the fixed Hermes local-provider alias during rebuild (#12558)", () => { + expect( + stripCredentials({ + api_key: "sk-OPENSHELL-RESOLVE-ENV-NEMOCLAW_LOCAL_INFERENCE_TOKEN", + other_api_key: "sk-OPENSHELL-RESOLVE-ENV-untrusted-value", + }), + ).toEqual({ + api_key: "sk-OPENSHELL-RESOLVE-ENV-NEMOCLAW_LOCAL_INFERENCE_TOKEN", + other_api_key: CREDENTIAL_PLACEHOLDER, + }); + }); + it("does not trust the NVIDIA inference environment reference outside its generated route (#13018)", () => { expect(isSafeCredentialPlaceholder("${NVIDIA_INFERENCE_API_KEY}")).toBe(false); expect(stripCredentials({ apiKey: "${NVIDIA_INFERENCE_API_KEY}" })).toEqual({ diff --git a/scripts/checks/test-create-require-budget.mts b/scripts/checks/test-create-require-budget.mts index e5245d02c19..ccaf26156c3 100644 --- a/scripts/checks/test-create-require-budget.mts +++ b/scripts/checks/test-create-require-budget.mts @@ -23,7 +23,6 @@ export const CLI_CREATE_REQUIRE_FILES = [ "src/lib/actions/sandbox/gateway-state-drift.test.ts", "src/lib/actions/sandbox/gateway-state-hints.test.ts", "src/lib/actions/sandbox/rebuild-agent-base-image-preflight.test.ts", - "src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts", "src/lib/actions/sandbox/rebuild-resume-config.test.ts", "src/lib/actions/sandbox/rebuild-resume-reasoning.test.ts", "src/lib/actions/sandbox/sandbox-gateway-routing.test.ts", diff --git a/scripts/generate-openclaw-config.mts b/scripts/generate-openclaw-config.mts index ad838f3609a..8a4d0956619 100755 --- a/scripts/generate-openclaw-config.mts +++ b/scripts/generate-openclaw-config.mts @@ -27,6 +27,7 @@ // NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME, NEMOCLAW_OPENCLAW_OTEL_SAMPLE_RATE, // NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION. +import { nativeLocalCredentialReference } from "../src/lib/inference/native-local/agent-config.ts"; import { nativeHostedAgentConfig } from "../src/lib/inference/native-provider/agent-config.ts"; import { hasProviderlessInferenceEnvironment } from "../src/lib/providerless-inference.ts"; @@ -977,7 +978,10 @@ export function buildConfig(env: Env = process.env): JsonObject { const providers = { [providerKey]: { baseUrl: inferenceBaseUrl, - apiKey: nativeHosted?.apiKey ?? managedInferenceApiKey(inferenceBaseUrl, "unused"), + apiKey: + nativeLocalCredentialReference(env.NEMOCLAW_UPSTREAM_PROVIDER, inferenceBaseUrl) ?? + nativeHosted?.apiKey ?? + managedInferenceApiKey(inferenceBaseUrl, "unused"), ...(nativeHosted?.headers ? { headers: nativeHosted.headers } : {}), api: inferenceApi, timeoutSeconds: agentTimeout, diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index eb8620d1992..31b37e16d83 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -841,6 +841,7 @@ PYPLACEHOLDERSTATE NEMOCLAW_PROVIDER_PLACEHOLDER_KEYS="$keys" \ NEMOCLAW_PROVIDER_PLACEHOLDER_RUNTIME_STATE="$_placeholder_runtime_state" \ /usr/bin/python3 -I - "$config_file" <<'PYPLACEHOLDERS' +import ipaddress import json import os import re @@ -848,6 +849,7 @@ import subprocess import sys import stat import tempfile +from urllib.parse import urlsplit config_file = sys.argv[1] prefix = "openshell:resolve:env:" @@ -922,6 +924,32 @@ native_keys = { } endpoint = native.get("baseUrl") if isinstance(native, dict) else None key = native_keys.get(endpoint.rstrip("/")) if isinstance(endpoint, str) else None +if not key and isinstance(endpoint, str): + try: + parsed = urlsplit(endpoint) + host = parsed.hostname or "" + private_ipv4 = False + try: + address = ipaddress.IPv4Address(host) + private_ipv4 = any( + address in network + for network in ( + ipaddress.IPv4Network("10.0.0.0/8"), + ipaddress.IPv4Network("172.16.0.0/12"), + ipaddress.IPv4Network("192.168.0.0/16"), + ) + ) + except ipaddress.AddressValueError: + pass + if ( + parsed.scheme == "http" + and not parsed.username + and not parsed.password + and (private_ipv4 or host in ("host.openshell.internal", "host.docker.internal")) + ): + key = "NEMOCLAW_LOCAL_INFERENCE_TOKEN" + except ValueError: + pass if key: scoped = re.compile(rf"^{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{key}$") saved = native.get("apiKey") diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index bbbe6de5052..d1f49bc27e7 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -6,6 +6,7 @@ import os from "node:os"; import { describe, expect, it, vi } from "vitest"; import { HOSTED_NATIVE_PROVIDERS } from "../inference/native-provider/hosted"; +import { nativeLocalIdentity, type NativeLocalBinding } from "../inference/native-local/contract"; import { buildHttpsPinRouteBaseUrl } from "../inference/https-pin-runtime"; import { managedLlamaCppStatePaths, @@ -33,6 +34,31 @@ function configuredRoute(provider: string, model: string): OpenShellInferenceRou return { ok: true, value: { state: "configured", route: { provider, model } } }; } +function nativeLocalSandbox(overrides: Record = {}) { + const binding: NativeLocalBinding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11435/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "alpha", + }; + return { + name: "alpha", + agent: "openclaw", + provider: binding.provider, + model: "qwen2.5:7b", + gatewayName: binding.gatewayName, + nativeLocalProviderAttachment: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-provider-id", + }, + ...overrides, + }; +} + function createDeps(fixture: OpenShellInferenceRouteResult): InferenceGetDeps & { log: ReturnType; observeInferenceRoute: ReturnType; @@ -173,6 +199,118 @@ function expectBoundedAffectedDiagnostics(result: InferenceGetResult, output: st } describe("runInferenceGet", () => { + it.each([ + { + agent: "openclaw", + provider: "ollama-local", + sandboxName: undefined, + endpointUrl: "http://host.openshell.internal:11435/v1", + }, + { + agent: "langchain-deepagents-code", + provider: "compatible-endpoint", + sandboxName: "alpha", + endpointUrl: "http://10.42.0.3:8999/v1", + }, + ] as const)( + "reads a recorded native-local $agent route without consulting the shared gateway (#12975)", + async ({ agent, provider, sandboxName, endpointUrl }) => { + const deps = createDeps(configuredRoute("stale-shared-provider", "stale-shared-model")); + const sandbox = nativeLocalSandbox(); + const binding = { ...sandbox.nativeLocalProviderAttachment, provider, endpointUrl }; + deps.getSandbox = () => + nativeLocalSandbox({ + agent, + provider, + nativeLocalProviderAttachment: { ...binding, ...nativeLocalIdentity(binding) }, + }); + deps.getDefaultSandbox = () => "alpha"; + + await expect(runInferenceGet({ json: true, sandboxName }, deps)).resolves.toEqual({ + provider, + model: "qwen2.5:7b", + endpointUrl, + }); + expect(deps.observeInferenceRoute).not.toHaveBeenCalled(); + expect(JSON.parse(deps.log.mock.calls[0][0])).toEqual({ + provider, + model: "qwen2.5:7b", + endpointUrl, + }); + }, + ); + + it("prints the selected native-local provider, model, and endpoint (#12975)", async () => { + const deps = createDeps(configuredRoute("stale-shared-provider", "stale-shared-model")); + deps.getSandbox = () => nativeLocalSandbox(); + + await runInferenceGet({ sandboxName: "alpha" }, deps); + + expect(deps.log.mock.calls.map(([line]) => line)).toEqual([ + "Provider: ollama-local", + "Model: qwen2.5:7b", + "Endpoint: http://host.openshell.internal:11435/v1", + ]); + expect(deps.observeInferenceRoute).not.toHaveBeenCalled(); + }); + + it.each([{ json: true }, { json: false }])( + "withholds an opaque native-local endpoint path in json=$json output (#12975)", + async ({ json }) => { + const deps = createDeps(configuredRoute("stale-shared-provider", "stale-shared-model")); + const sandbox = nativeLocalSandbox(); + const endpointUrl = "http://host.openshell.internal:11435/opaque-tenant-credential/v1"; + const binding = { ...sandbox.nativeLocalProviderAttachment, endpointUrl }; + deps.getSandbox = () => + nativeLocalSandbox({ + nativeLocalProviderAttachment: { ...binding, ...nativeLocalIdentity(binding) }, + }); + + await expect(runInferenceGet({ sandboxName: "alpha", json }, deps)).resolves.toEqual({ + provider: "ollama-local", + model: "qwen2.5:7b", + endpointStatus: "withheld", + endpointRecovery: ENDPOINT_RECOVERY.withheld, + }); + expect(deps.log.mock.calls.flat().join("\n")).not.toContain("opaque-tenant-credential"); + expect(deps.observeInferenceRoute).not.toHaveBeenCalled(); + }, + ); + + it.each([ + { label: "invalid attachment", overrides: { nativeLocalProviderAttachment: {} } }, + { label: "provider mismatch", overrides: { provider: "vllm-local" } }, + { label: "sandbox mismatch", overrides: { name: "beta" } }, + { label: "gateway mismatch", overrides: { gatewayName: "nemoclaw-19090" } }, + { + label: "missing recorded gateway", + overrides: { gatewayName: undefined, gatewayPort: 8080 }, + }, + { label: "agent mismatch", overrides: { agent: "hermes" } }, + { + label: "credential boundary mismatch", + overrides: { + nativeLocalProviderAttachment: (() => { + const attachment = nativeLocalSandbox().nativeLocalProviderAttachment; + const binding = { ...attachment, credentialEnv: "UNRELATED_TOKEN" }; + return { ...binding, ...nativeLocalIdentity(binding) }; + })(), + }, + }, + ])( + "rejects a native-local $label without reporting the shared route (#12975)", + async ({ overrides }) => { + const deps = createDeps(configuredRoute("stale-shared-provider", "stale-shared-model")); + deps.getSandbox = () => nativeLocalSandbox(overrides); + + await expect(runInferenceGet({ sandboxName: "alpha" }, deps)).rejects.toThrow( + "Invalid native local provider attachment for the recorded inference selection", + ); + expect(deps.observeInferenceRoute).not.toHaveBeenCalled(); + expect(deps.log).not.toHaveBeenCalled(); + }, + ); + it("reads a recorded native NVIDIA route without consulting the shared gateway route", async () => { const deps = createDeps(configuredRoute("stale-provider", "stale-model")); const sandbox = { diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index 352f7f08f86..2ef11a8191d 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -21,6 +21,8 @@ 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 { normalizeNativeLocalProviderAttachment } from "../inference/selection"; import { recordedNativeProviderAttachment } from "../inference/native-provider/recorded-selection"; import { hostedNativeProvider } from "../inference/native-provider/hosted"; import { inspectManagedLlamaCppOwnership } from "../inference/llama-cpp/managed-state"; @@ -311,7 +313,11 @@ export async function runInferenceGet( const selectedSandbox = selectedSandboxName ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) : null; - if (selectedSandbox && recordedNativeProviderAttachment(selectedSandbox)) { + if ( + selectedSandbox && + selectedSandbox.nativeLocalProviderAttachment === undefined && + recordedNativeProviderAttachment(selectedSandbox) + ) { const payload: InferenceGetResult = { provider: selectedSandbox.provider ?? null, model: selectedSandbox.model ?? null, @@ -332,6 +338,62 @@ export async function runInferenceGet( } return payload; } + if (selectedSandbox?.nativeLocalProviderAttachment !== undefined) { + const attachment = normalizeNativeLocalProviderAttachment( + selectedSandbox.nativeLocalProviderAttachment, + ); + let recordedGatewayName: string | undefined; + try { + recordedGatewayName = getPersistedSandboxTargetGatewayName(selectedSandbox); + } catch { + // A malformed binding must not make the shared gateway appear selected. + } + if ( + !attachment || + selectedSandbox.nativeHostedProviderAttachment !== undefined || + selectedSandbox.nativeNvidiaProviderAttachment !== undefined || + !isPublishedSandboxRegistration(selectedSandbox) || + selectedSandbox.name !== selectedSandboxName || + attachment.sandboxName !== selectedSandbox.name || + attachment.gatewayName !== recordedGatewayName || + attachment.gatewayName !== selectedSandbox.gatewayName || + attachment.provider !== selectedSandbox.provider || + attachment.credentialEnv !== NATIVE_LOCAL_CREDENTIAL_ENV || + typeof selectedSandbox.model !== "string" || + !selectedSandbox.model.trim() || + (selectedSandbox.agent !== "openclaw" && + selectedSandbox.agent !== "langchain-deepagents-code") + ) { + throw new InferenceGetError( + "Invalid native local provider attachment for the recorded inference selection", + ); + } + const endpoint = + !valueLooksLikeSecret(attachment.endpointUrl) && + endpointPathIsCredentialFreeForDisplay(attachment.endpointUrl) + ? { endpointUrl: attachment.endpointUrl } + : endpointOmission("withheld"); + const payload: InferenceGetResult = { + provider: selectedSandbox.provider, + model: selectedSandbox.model, + ...endpoint, + }; + if (!options.quiet) { + if (options.json) { + deps.log(JSON.stringify(payload, null, 2)); + } else { + deps.log(`Provider: ${formatRouteValueForDisplay(payload.provider)}`); + deps.log(`Model: ${formatRouteValueForDisplay(payload.model)}`); + if (payload.endpointUrl) { + deps.log(`Endpoint: ${formatRouteValueForDisplay(payload.endpointUrl)}`); + } else if (payload.endpointStatus && payload.endpointRecovery) { + deps.log(`Endpoint: unavailable (${payload.endpointStatus})`); + deps.log(`Action: ${payload.endpointRecovery}`); + } + } + } + return payload; + } let gatewayName: string; try { gatewayName = deps.getSandboxTargetGatewayName(options.sandboxName); diff --git a/src/lib/actions/inference-set-context-window.test.ts b/src/lib/actions/inference-set-context-window.test.ts index 56a27ed0bf4..d6bdcafc780 100644 --- a/src/lib/actions/inference-set-context-window.test.ts +++ b/src/lib/actions/inference-set-context-window.test.ts @@ -10,6 +10,7 @@ import { baseSession, createCompatibleProviderCapture, createDeps, + nativeLocalTestReceipt, } from "../../../test/helpers/inference-set"; describe("runInferenceSet context window", () => { @@ -64,6 +65,7 @@ describe("runInferenceSet context window", () => { name: "alpha", agent: "openclaw", provider: "ollama-local", + nativeLocalProviderAttachment: nativeLocalTestReceipt(), model: "llama3.2:3b", endpointUrl: null, preferredInferenceApi: "openai-completions", @@ -93,6 +95,7 @@ describe("runInferenceSet context window", () => { name: "alpha", agent: "openclaw", provider: "ollama-local", + nativeLocalProviderAttachment: nativeLocalTestReceipt(), model: "qwen2.5:7b", endpointUrl: null, preferredInferenceApi: "openai-completions", @@ -126,7 +129,7 @@ describe("runInferenceSet context window", () => { agent: "openclaw", provider: previousProvider, model: "llama3.2:3b", - endpointUrl: "http://host.openshell.internal:8000/v1", + endpointUrl: "http://host.openshell.internal:18767/v1", credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-completions", }; @@ -167,7 +170,7 @@ describe("runInferenceSet context window", () => { const options = { provider: "compatible-endpoint", model: "llama3.2:3b", - endpointUrl: "http://host.openshell.internal:11434/v1", + endpointUrl: "http://host.openshell.internal:18768/v1", credentialEnv: "COMPATIBLE_API_KEY", inferenceApi: "openai-completions", noVerify: true, @@ -193,6 +196,7 @@ describe("runInferenceSet context window", () => { name: "alpha", agent: "openclaw", provider: "ollama-local", + nativeLocalProviderAttachment: nativeLocalTestReceipt(), model: "llama3.2:3b", }; let rejectReceipt = failure === "receipt"; diff --git a/src/lib/actions/inference-set-degraded-state.test.ts b/src/lib/actions/inference-set-degraded-state.test.ts index 0357b839a69..b28dd749718 100644 --- a/src/lib/actions/inference-set-degraded-state.test.ts +++ b/src/lib/actions/inference-set-degraded-state.test.ts @@ -176,7 +176,7 @@ describe("runInferenceSet degraded state handling", () => { model: "openai/gpt-5.4-mini", endpointUrl: initiallyPresent ? "https://new.example/v1" - : "http://host.openshell.internal:11434/v1", + : "http://host.openshell.internal:18767/v1", credentialEnv: "COMPATIBLE_API_KEY", inferenceApi: "openai-completions", noVerify: true, diff --git a/src/lib/actions/inference-set-live-rollback.test.ts b/src/lib/actions/inference-set-live-rollback.test.ts index a09ca2732cc..84ed841ecbb 100644 --- a/src/lib/actions/inference-set-live-rollback.test.ts +++ b/src/lib/actions/inference-set-live-rollback.test.ts @@ -2,8 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +vi.mock("../adapters/openshell/provider-policy", () => ({ + requireNativeProviderPolicy: vi.fn(async () => {}), +})); + import { runInferenceSet } from "./inference-set"; -import { createCompatibleProviderCapture, createDeps } from "../../../test/helpers/inference-set"; +import { + createCompatibleProviderCapture, + createDeps, + nativeLocalTestReceipt, + createFailingNativeLocalRestoreAdapter, +} from "../../../test/helpers/inference-set"; describe("runInferenceSet live rollback authority", () => { it("does not reapply or report restoration when the observed route already matches the rejected route", async () => { @@ -83,3 +92,176 @@ describe("runInferenceSet live rollback authority", () => { expect(probeSandboxRoute).toHaveBeenCalledTimes(3); }); }); + +describe("native to shared inference rollback", () => { + it.each([ + { provider: "ollama-local", nativeLocalProviderAttachment: nativeLocalTestReceipt() }, + { + provider: "nvidia-prod", + nativeNvidiaProviderAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + ])( + "restores the peer shared route after a rejected switch from $provider (#12558)", + async (previous) => { + const before = { provider: "peer-provider", model: "peer-model" }; + const setInferenceRoute = vi.fn(async () => ({ ok: true as const })); + const deps = createDeps({ + config: {}, + entry: { name: "alpha", agent: "openclaw", model: "old-model", ...previous }, + captureOpenshell: createCompatibleProviderCapture({ + name: "compatible-endpoint", + type: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + configKey: "OPENAI_BASE_URL", + initiallyPresent: false, + }), + inferenceRouteObserver: { + observeInferenceRoute: vi.fn(async () => ({ + ok: true as const, + value: { state: "configured" as const, route: before }, + })), + }, + inferenceRouteMutator: { setInferenceRoute }, + probeSandboxRoute: vi.fn(async () => ({ + ok: false as const, + detail: "sandbox rejected route", + httpStatus: 400, + })), + }); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "rejected-model", + endpointUrl: "http://host.openshell.internal:18767/v1", + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions", + noVerify: true, + }, + deps, + ), + ).rejects.toThrow("sandbox rejected route"); + expect(setInferenceRoute).toHaveBeenLastCalledWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + route: before, + verification: "skip", + }); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }, + ); +}); + +it("preserves the original failure and detaches NVIDIA after local restoration fails (#12558)", async () => { + const previous = nativeLocalTestReceipt(); + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + provider: "ollama-local", + model: "old-model", + nativeLocalProviderAttachment: previous, + }, + updateSandbox: () => false, + }); + const { adapter, detachProvider } = createFailingNativeLocalRestoreAdapter( + deps.providerAdapter, + previous, + ); + await expect( + runInferenceSet( + { provider: "nvidia-prod", model: "model-a" }, + { ...deps, providerAdapter: adapter }, + ), + ).rejects.toThrow(/Failed to update NemoClaw registry[\s\S]*local restoration unavailable/); + expect(detachProvider).toHaveBeenCalledWith( + expect.objectContaining({ providerName: "nemoclaw-nvidia-prod-v1" }), + ); +}); + +describe("native local to shared inference without a prior gateway route", () => { + function fixture(probeOk: boolean) { + const previous = nativeLocalTestReceipt(); + const setInferenceRoute = vi.fn(async () => ({ ok: true as const })); + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + provider: "ollama-local", + model: "old-model", + nativeLocalProviderAttachment: previous, + }, + captureOpenshell: createCompatibleProviderCapture({ + name: "compatible-endpoint", + type: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + configKey: "OPENAI_BASE_URL", + initiallyPresent: false, + }), + inferenceRouteObserver: { + observeInferenceRoute: vi.fn(async () => ({ + ok: true as const, + value: { state: "unconfigured" as const }, + })), + }, + inferenceRouteMutator: { setInferenceRoute }, + probeSandboxRoute: vi.fn(async () => ({ + ok: probeOk, + detail: "sandbox rejected route", + httpStatus: 400, + })), + }); + const { adapter, detachProvider } = createFailingNativeLocalRestoreAdapter( + { + ...deps.providerAdapter, + listProviderAttachments: async () => ({ ok: true as const, value: { names: [] } }), + }, + previous, + ); + return { + deps: { ...deps, providerAdapter: adapter }, + previous, + detachProvider, + setInferenceRoute, + request: { + provider: "compatible-endpoint", + model: "new-model", + endpointUrl: "http://host.openshell.internal:18767/v1", + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions" as const, + noVerify: true, + }, + }; + } + + it("publishes the verified shared route and detaches prior native access (#12558)", async () => { + const f = fixture(true); + await runInferenceSet(f.request, f.deps); + expect(f.setInferenceRoute).toHaveBeenCalledTimes(1); + expect(f.detachProvider).toHaveBeenCalledWith( + expect.objectContaining({ providerName: f.previous.providerName }), + ); + expect(f.deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + provider: "compatible-endpoint", + nativeLocalProviderAttachment: undefined, + }), + ); + }); + + it("preserves native access and registry authority when the shared probe fails (#12558)", async () => { + const f = fixture(false); + await expect(runInferenceSet(f.request, f.deps)).rejects.toThrow("sandbox rejected route"); + expect(f.setInferenceRoute).toHaveBeenCalledTimes(1); + expect(f.detachProvider).not.toHaveBeenCalled(); + expect(f.deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(f.deps.getSandbox("alpha")?.nativeLocalProviderAttachment).toEqual(f.previous); + }); +}); diff --git a/src/lib/actions/inference-set-local-provider.test.ts b/src/lib/actions/inference-set-local-provider.test.ts index ab63c4655e4..d4df74bbb30 100644 --- a/src/lib/actions/inference-set-local-provider.test.ts +++ b/src/lib/actions/inference-set-local-provider.test.ts @@ -19,14 +19,23 @@ describe("runInferenceSet local-provider verification", () => { }, }); - it("forces --no-verify for a local provider whose host validation passes", async () => { + it("uses a native sandbox request without changing the gateway route (#12558)", async () => { const deps = createDeps({ config: localConfig(), session: baseSession() }); await runInferenceSet({ provider: "ollama-local", model: "qwen2.5:7b" }, deps); expect(deps.calls.validateLocalProvider).toHaveBeenCalledWith("ollama-local"); - const args = deps.calls.captureOpenshell.mock.calls[0][0] as string[]; - expect(args).toContain("--no-verify"); + expect(deps.calls.captureOpenshell.mock.calls.some(([args]) => args[0] === "inference")).toBe( + false, + ); + expect(deps.calls.probeSandboxRoute).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + nativeLocalProviderAttachment: expect.objectContaining({ + endpointUrl: "http://host.openshell.internal:11435/v1", + }), + }), + ); expect(deps.calls.ensureLocalProviderReachable).not.toHaveBeenCalled(); }); @@ -43,7 +52,7 @@ describe("runInferenceSet local-provider verification", () => { .map((call) => call[0]) .flat() .map(String); - expect(openshellArgs).toContain("ollama-local"); + expect(openshellArgs).not.toContain("inference"); expect(openshellArgs).not.toContain("ollama_local"); expect(deps.calls.updateSandbox).toHaveBeenCalledWith( "alpha", @@ -51,7 +60,7 @@ describe("runInferenceSet local-provider verification", () => { ); }); - it("warns and proceeds with --no-verify when the host stack is reachable despite a failed probe", async () => { + it("requires a sandbox-native probe when host reachability recovers (#12558)", async () => { const deps = createDeps({ config: localConfig(), session: baseSession(), @@ -66,8 +75,17 @@ describe("runInferenceSet local-provider verification", () => { await runInferenceSet({ provider: "ollama-local", model: "qwen2.5:7b" }, deps); expect(deps.calls.ensureLocalProviderReachable).toHaveBeenCalledWith("ollama-local"); - const args = deps.calls.captureOpenshell.mock.calls[0][0] as string[]; - expect(args).toContain("--no-verify"); + expect(deps.calls.captureOpenshell.mock.calls.some(([args]) => args[0] === "inference")).toBe( + false, + ); + expect(deps.calls.probeSandboxRoute).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + nativeLocalProviderAttachment: expect.objectContaining({ + endpointUrl: "http://host.openshell.internal:11435/v1", + }), + }), + ); const logged = deps.calls.log.mock.calls.map((a) => String(a[0])).join("\n"); expect(logged).toMatch(/reachable/); }); @@ -90,6 +108,19 @@ describe("runInferenceSet local-provider verification", () => { expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); + it("does not change selection when the gateway prerequisite is missing (#12558)", async () => { + const deps = createDeps({ config: localConfig(), session: baseSession() }); + deps.requireNativeProviderPolicy = async () => { + throw new Error("composition disabled"); + }; + await expect( + runInferenceSet({ provider: "ollama-local", model: "qwen2.5:7b" }, deps), + ).rejects.toThrow("composition disabled"); + expect(deps.calls.captureOpenshell).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); + }); + it("does not run local validation or mutate the shared route for native cloud providers", async () => { const deps = createDeps({ config: localConfig(), diff --git a/src/lib/actions/inference-set-native-local-retirement.test.ts b/src/lib/actions/inference-set-native-local-retirement.test.ts new file mode 100644 index 00000000000..ba310c40262 --- /dev/null +++ b/src/lib/actions/inference-set-native-local-retirement.test.ts @@ -0,0 +1,162 @@ +// 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 { retireUnselectedNativeLocalProviders } from "../inference/native-local/selection"; +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { runInferenceSet } from "./inference-set"; +import { createDeps, nativeLocalTestReceipt } from "../../../test/helpers/inference-set"; +import type { NativeLocalProviderAttachment } from "../inference/native-local/contract"; + +function fixture() { + const previous = { + ...nativeLocalTestReceipt("ollama-local", "http://host.openshell.internal:11434/v1"), + providerId: "previous-id", + }; + const selected = nativeLocalTestReceipt(); + const authorities = new Map([ + [previous.providerName, previous], + [selected.providerName, selected], + ]); + const providers = new Map(authorities); + const deps = createDeps({ config: {}, entry: { name: "alpha", agent: "openclaw" } }); + const entry = deps.getSandbox("alpha")!; + deps.calls.updateSandbox.mockImplementation((_name, updates) => { + Object.assign(entry, updates); + return true; + }); + const getProvider = vi.fn(async ({ providerName }: { providerName: string }) => { + const found = providers.get(providerName); + return found + ? { + ok: true as const, + value: { + name: found.providerName, + type: found.profileId, + credentialKeys: [found.credentialEnv], + configKeys: [], + revision: { id: found.providerId, resourceVersion: 1 }, + }, + } + : { + ok: false as const, + error: { kind: "command" as const, reason: "not_found" as const, message: "absent" }, + }; + }); + const deleteProvider = vi.fn( + async ({ providerName }: { providerName: string }) => { + providers.delete(providerName); + return { ok: true as const }; + }, + ); + const listNativeLocalProviderAuthorities = vi.fn(() => [...authorities.values()]); + const clearNativeLocalProviderAuthority = vi.fn((receipt: NativeLocalProviderAttachment) => { + authorities.delete(receipt.providerName); + }); + return { + previous, + selected, + authorities, + providers, + entry, + getProvider, + deleteProvider, + deps: { + ...deps, + providerAdapter: { ...deps.providerAdapter, getProvider, deleteProvider }, + listNativeLocalProviderAuthorities, + clearNativeLocalProviderAuthority, + }, + }; +} + +describe("committed native selection provider cleanup", () => { + it("retires previously detached providers after committing the selected route (#12558)", async () => { + const f = fixture(); + await runInferenceSet({ provider: "ollama-local", model: "model-a" }, f.deps); + expect(f.entry.nativeLocalProviderAttachment).toEqual(f.selected); + expect(f.deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: f.previous.providerName, + }); + expect([...f.authorities.keys()]).toEqual([f.selected.providerName]); + expect([...f.providers.keys()]).toEqual([f.selected.providerName]); + }); + it("does not retire providers before registry publication commits (#12558)", async () => { + const f = fixture(); + f.deps.calls.updateSandbox.mockReturnValue(false); + await expect( + runInferenceSet({ provider: "ollama-local", model: "model-a" }, f.deps), + ).rejects.toThrow("Failed to update NemoClaw registry"); + expect(f.deleteProvider).not.toHaveBeenCalled(); + expect([...f.authorities.keys()]).toEqual([f.previous.providerName, f.selected.providerName]); + }); + + it("retains committed selection and cleanup authority after uncertain deletion, then reconciles absence (#12558)", async () => { + const f = fixture(); + f.deleteProvider.mockImplementationOnce(async ({ providerName }) => { + f.providers.delete(providerName); + f.getProvider.mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + }); + throw new Error("delete response lost"); + }); + await expect( + runInferenceSet({ provider: "ollama-local", model: "model-a" }, f.deps), + ).rejects.toThrow("delete response lost"); + expect(f.entry.nativeLocalProviderAttachment).toEqual(f.selected); + expect(f.authorities.has(f.previous.providerName)).toBe(true); + await runInferenceSet({ provider: "ollama-local", model: "model-a" }, f.deps); + expect(f.deleteProvider).toHaveBeenCalledTimes(1); + expect([...f.authorities.keys()]).toEqual([f.selected.providerName]); + }); + + it("retains authority and rejects cleanup when a provider identity changed (#12558)", async () => { + const f = fixture(); + f.providers.set(f.previous.providerName, { ...f.previous, providerId: "replacement-id" }); + await expect( + runInferenceSet({ provider: "ollama-local", model: "model-a" }, f.deps), + ).rejects.toThrow("identity changed"); + expect(f.deleteProvider).not.toHaveBeenCalled(); + expect(f.authorities.has(f.previous.providerName)).toBe(true); + expect(f.entry.nativeLocalProviderAttachment).toEqual(f.selected); + }); + + it("clears confirmed absent provider authority without another delete (#12558)", async () => { + const f = fixture(); + f.providers.delete(f.previous.providerName); + await runInferenceSet({ provider: "ollama-local", model: "model-a" }, f.deps); + expect(f.deleteProvider).not.toHaveBeenCalled(); + expect([...f.authorities.keys()]).toEqual([f.selected.providerName]); + }); + + it("retains authority when OpenShell still observes the old provider attached (#12558)", async () => { + const f = fixture(); + f.deleteProvider.mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "attached", message: "still attached" }, + }); + await expect( + runInferenceSet({ provider: "ollama-local", model: "model-a" }, f.deps), + ).rejects.toThrow("remains attached"); + expect(f.authorities.has(f.previous.providerName)).toBe(true); + expect(f.providers.has(f.previous.providerName)).toBe(true); + expect(f.entry.nativeLocalProviderAttachment).toEqual(f.selected); + }); + + it("retires current and retained authorities after confirmed sandbox destruction (#12558)", async () => { + const f = fixture(); + await retireUnselectedNativeLocalProviders({ + adapter: f.deps.providerAdapter, + sandboxName: "alpha", + gatewayName: "nemoclaw", + destroyedAttachment: f.selected, + listAuthorities: f.deps.listNativeLocalProviderAuthorities, + clearAuthority: f.deps.clearNativeLocalProviderAuthority, + }); + expect(f.deleteProvider).toHaveBeenCalledTimes(2); + expect(f.authorities.size).toBe(0); + expect(f.providers.size).toBe(0); + }); +}); diff --git a/src/lib/actions/inference-set-native-local.test.ts b/src/lib/actions/inference-set-native-local.test.ts new file mode 100644 index 00000000000..f6f8ee96765 --- /dev/null +++ b/src/lib/actions/inference-set-native-local.test.ts @@ -0,0 +1,324 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { nativeSelectionConfigCredentials } from "./inference-set/native"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { nativeLocalIdentity, type NativeLocalBinding } from "../inference/native-local/contract"; +import { prepareNativeLocalSelection } from "../inference/native-local/selection"; +import { + ensureNativeLocalProviderAttached, + detachNativeLocalProvider, +} from "../inference/native-local/profile"; +import { + prepareNativeLocalSwitch, + rollbackNativeLocalSelection, + detachPreviousNativeLocalBeforePublish, +} from "./inference/native-local"; + +vi.mock("../inference/native-local/selection", () => ({ prepareNativeLocalSelection: vi.fn() })); +vi.mock("../inference/native-local/profile", () => ({ + ensureNativeLocalProviderAttached: vi.fn(), + detachNativeLocalProvider: vi.fn(), +})); +const binding: NativeLocalBinding = { + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + gatewayName: "selected", + sandboxName: "alice", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", +}; +const previous = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "previous-id", +}; +const nextBinding = { ...binding, endpointUrl: "http://host.openshell.internal:11434/v1" }; +const next = { + ...nextBinding, + ...nativeLocalIdentity(nextBinding), + schemaVersion: 1 as const, + providerId: "next-id", +}; +beforeEach(() => { + vi.resetAllMocks(); + vi.mocked(prepareNativeLocalSelection).mockResolvedValue(next); + vi.mocked(ensureNativeLocalProviderAttached).mockResolvedValue({ receipt: next, changed: true }); +}); +function fixture() { + const listProviderAttachments = vi.fn(async () => ({ ok: true as const, value: { names: [] } })); + return { + local: { + getLocalProviderBaseUrl: vi.fn(() => "http://host.openshell.internal:11434/v1"), + getManagedVllmProviderBinding: vi.fn(() => null), + shouldFrontOllamaWithProxy: vi.fn(() => false), + }, + provider: "compatible-endpoint", + gatewayName: "selected", + sandboxName: "alice", + previous, + binding: { + baseUrl: next.endpointUrl, + token: "test-only-secret", + credentialEnv: "COMPATIBLE_API_KEY", + providerType: "openai" as const, + }, + adapter: { listProviderAttachments } as unknown as OpenShellProviderAdapter, + resolveCredentialValue: vi.fn(() => { + throw new Error("unexpected host credential read"); + }), + }; +} +describe("native local inference replacement", () => { + it("keeps model-only changes inside existing OpenShell credential custody (#12558)", async () => { + const input = fixture(); + vi.mocked(ensureNativeLocalProviderAttached).mockResolvedValue({ + receipt: previous, + changed: false, + }); + await expect(prepareNativeLocalSwitch({ ...input, binding: null })).resolves.toMatchObject({ + receipt: previous, + previousDetached: false, + }); + expect(prepareNativeLocalSelection).not.toHaveBeenCalled(); + expect(detachNativeLocalProvider).not.toHaveBeenCalled(); + expect(input.resolveCredentialValue).not.toHaveBeenCalled(); + }); + it("removes the previous endpoint only from the selected sandbox before attaching its replacement (#12558)", async () => { + const input = fixture(); + await expect(prepareNativeLocalSwitch(input)).resolves.toMatchObject({ + receipt: next, + previousDetached: true, + }); + expect(detachNativeLocalProvider).toHaveBeenCalledExactlyOnceWith({ + adapter: input.adapter, + sandboxName: "alice", + expected: previous, + }); + expect(ensureNativeLocalProviderAttached).toHaveBeenCalledExactlyOnceWith({ + adapter: input.adapter, + sandboxName: "alice", + expected: next, + }); + expect(vi.mocked(detachNativeLocalProvider).mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(ensureNativeLocalProviderAttached).mock.invocationCallOrder[0], + ); + }); + it("restores previous access after a rejected attachment is confirmed absent (#12558)", async () => { + const input = fixture(); + vi.mocked(ensureNativeLocalProviderAttached).mockRejectedValueOnce( + new Error("attachment denied"), + ); + await expect(prepareNativeLocalSwitch(input)).rejects.toThrow("attachment denied"); + expect(input.adapter.listProviderAttachments).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "selected" }, + sandboxName: "alice", + }); + expect(ensureNativeLocalProviderAttached).toHaveBeenLastCalledWith({ + adapter: input.adapter, + sandboxName: "alice", + expected: previous, + }); + }); + it("reports both attachment and restoration failures (#12558)", async () => { + const input = fixture(); + vi.mocked(ensureNativeLocalProviderAttached) + .mockRejectedValueOnce(new Error("attachment denied")) + .mockRejectedValueOnce(new Error("restore unavailable")); + await expect(prepareNativeLocalSwitch(input)).rejects.toThrow( + /attachment denied[\s\S]*restoring the previous native local provider attachment also failed: restore unavailable/i, + ); + }); + it("does not mutate again when failed attachment observation is inconclusive (#12558)", async () => { + const input = fixture(); + vi.mocked(input.adapter.listProviderAttachments).mockResolvedValue({ + ok: false, + error: { kind: "transport", reason: "connection_loss", message: "lost" }, + } as never); + vi.mocked(ensureNativeLocalProviderAttached).mockRejectedValueOnce( + new Error("attachment unknown"), + ); + await expect(prepareNativeLocalSwitch(input)).rejects.toThrow("could not be reconciled"); + expect(ensureNativeLocalProviderAttached).toHaveBeenCalledTimes(1); + expect(detachNativeLocalProvider).toHaveBeenCalledTimes(1); + }); +}); + +describe("native local selection compensation", () => { + function rollbackInput() { + return { + adapter: fixture().adapter, + sandboxName: "alice", + provider: "compatible-endpoint", + attachment: next, + previous, + attachmentChanged: true, + registryCommitted: false, + previousDetached: true, + previousDetachCommitted: false, + getSandbox: vi.fn(() => ({ + name: "alice", + provider: "compatible-endpoint", + nativeLocalProviderAttachment: previous, + })), + }; + } + it("restores the old endpoint after an uncommitted same-provider switch (#12558)", async () => { + await rollbackNativeLocalSelection(rollbackInput()); + expect(detachNativeLocalProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ expected: next }), + ); + expect(ensureNativeLocalProviderAttached).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ expected: previous }), + ); + expect(vi.mocked(detachNativeLocalProvider).mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(ensureNativeLocalProviderAttached).mock.invocationCallOrder[0]!, + ); + }); + it("retains the new attachment after a registry write committed but its response was lost (#12558)", async () => { + const input = rollbackInput(); + input.getSandbox.mockReturnValue({ + name: "alice", + provider: "compatible-endpoint", + nativeLocalProviderAttachment: next, + }); + await rollbackNativeLocalSelection(input); + expect(detachNativeLocalProvider).not.toHaveBeenCalled(); + expect(ensureNativeLocalProviderAttached).not.toHaveBeenCalled(); + }); + it("restores native access when a same-provider departure was not published (#12558)", async () => { + const input = rollbackInput(); + await rollbackNativeLocalSelection({ + ...input, + attachment: undefined, + attachmentChanged: false, + }); + expect(detachNativeLocalProvider).not.toHaveBeenCalled(); + expect(ensureNativeLocalProviderAttached).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ expected: previous, sandboxName: "alice" }), + ); + }); + it("keeps a same-provider departure after its registry response was lost (#12558)", async () => { + const input = rollbackInput(); + await rollbackNativeLocalSelection({ + ...input, + attachment: undefined, + attachmentChanged: false, + getSandbox: () => ({ name: "alice", provider: "compatible-endpoint" }), + }); + expect(detachNativeLocalProvider).not.toHaveBeenCalled(); + expect(ensureNativeLocalProviderAttached).not.toHaveBeenCalled(); + }); + it("retains authority without mutation when a persisted receipt is malformed (#12558)", async () => { + const input = rollbackInput(); + await expect( + rollbackNativeLocalSelection({ + ...input, + attachment: undefined, + attachmentChanged: false, + getSandbox: () => ({ + name: "alice", + provider: "compatible-endpoint", + nativeLocalProviderAttachment: { ...previous, providerId: "" }, + }), + }), + ).rejects.toThrow("Malformed native local provider attachment"); + expect(detachNativeLocalProvider).not.toHaveBeenCalled(); + expect(ensureNativeLocalProviderAttached).not.toHaveBeenCalled(); + }); + it("retains provider authority when registry observation fails (#12558)", async () => { + const input = rollbackInput(); + input.getSandbox.mockImplementation(() => { + throw new Error("registry unavailable"); + }); + await expect(rollbackNativeLocalSelection(input)).rejects.toThrow("registry unavailable"); + expect(detachNativeLocalProvider).not.toHaveBeenCalled(); + expect(ensureNativeLocalProviderAttached).not.toHaveBeenCalled(); + }); +}); + +describe.each([ + { + operation: "native replacement", + execute: (input: ReturnType) => prepareNativeLocalSwitch(input), + }, + { + operation: "shared publication", + execute: (input: ReturnType) => + detachPreviousNativeLocalBeforePublish({ + adapter: input.adapter, + sandboxName: input.sandboxName, + previous: input.previous, + detached: false, + }), + }, +])("native local detach compensation during $operation", ({ execute }) => { + it("restores previous access after an inconclusive detach (#12558)", async () => { + const input = fixture(); + vi.mocked(detachNativeLocalProvider).mockRejectedValueOnce( + new Error("detach readback unavailable"), + ); + await expect(execute(input)).rejects.toThrow("detach readback unavailable"); + expect(ensureNativeLocalProviderAttached).toHaveBeenCalledExactlyOnceWith({ + adapter: input.adapter, + sandboxName: "alice", + expected: previous, + }); + }); + it("reports failed restoration without claiming access was restored (#12558)", async () => { + const input = fixture(); + vi.mocked(detachNativeLocalProvider).mockRejectedValueOnce( + new Error("detach readback unavailable"), + ); + vi.mocked(ensureNativeLocalProviderAttached).mockRejectedValueOnce( + new Error("restore unavailable"), + ); + await expect(execute(input)).rejects.toThrow( + /detach readback unavailable[\s\S]*restoring the previous native local provider attachment also failed: restore unavailable/i, + ); + }); +}); + +describe("native-local credential references during provider changes", () => { + it.each([ + "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + "openshell:resolve:env:v42_NEMOCLAW_LOCAL_INFERENCE_TOKEN", + `openshell:resolve:env:s${"a".repeat(64)}_NEMOCLAW_LOCAL_INFERENCE_TOKEN`, + ])("does not reuse a local reference for a public endpoint: %s", (reference) => { + expect( + nativeSelectionConfigCredentials( + "compatible-endpoint", + "https://api.example.com/v1", + reference, + {}, + ), + ).toEqual({ apiKey: "unused" }); + }); + + it.each(["operator-api-key", "openshell:resolve:env:v42_OTHER_KEY"])( + "preserves unrelated credentials for a public endpoint: %s", + (apiKey) => { + expect( + nativeSelectionConfigCredentials( + "compatible-endpoint", + "https://api.example.com/v1", + apiKey, + {}, + ), + ).toEqual({ apiKey }); + }, + ); + + it("selects the canonical local reference for the new local attachment", () => { + expect( + nativeSelectionConfigCredentials( + "ollama-local", + "http://host.openshell.internal:11434/v1", + "operator-api-key", + {}, + ), + ).toEqual({ apiKey: "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN" }); + }); +}); diff --git a/src/lib/actions/inference-set-no-auth-compatible.test.ts b/src/lib/actions/inference-set-no-auth-compatible.test.ts index a3a721aa949..e62923c0e89 100644 --- a/src/lib/actions/inference-set-no-auth-compatible.test.ts +++ b/src/lib/actions/inference-set-no-auth-compatible.test.ts @@ -8,39 +8,27 @@ import { baseSession, createCompatibleProviderCapture, createDeps, + nativeLocalTestReceipt, } from "../../../test/helpers/inference-set"; -const NO_AUTH_ENDPOINT_URL = "http://127.0.0.1:11434/v1"; -const NO_AUTH_CREDENTIAL_ENV = "NEMOCLAW_OLLAMA_PROXY_TOKEN"; - const CONFIG = { agents: { defaults: { model: { primary: "inference/model-a" } } }, models: { providers: { inference: { api: "openai-completions", models: [] } } }, }; - -function noAuthEntry(): SandboxEntry { +const NO_AUTH_ENDPOINT_URL = "http://127.0.0.1:11434/v1"; +const NO_AUTH_CREDENTIAL_ENV = "NEMOCLAW_OLLAMA_PROXY_TOKEN"; +function noAuthEntry() { return { name: "alpha", agent: "openclaw", provider: "compatible-endpoint", model: "model-a", endpointUrl: NO_AUTH_ENDPOINT_URL, - endpointSource: "onboard", - credentialEnv: NO_AUTH_CREDENTIAL_ENV, - preferredInferenceApi: "openai-completions", - } as SandboxEntry; -} - -function noAuthSession() { - return baseSession({ - provider: "compatible-endpoint", - model: "model-a", - endpointUrl: NO_AUTH_ENDPOINT_URL, + endpointSource: "onboard" as const, credentialEnv: NO_AUTH_CREDENTIAL_ENV, - preferredInferenceApi: "openai-completions", - }); + preferredInferenceApi: "openai-completions" as const, + }; } - function noAuthProviderCapture( options: { credentialEnv?: string; initiallyPresent?: boolean } = {}, ) { @@ -52,111 +40,98 @@ function noAuthProviderCapture( initiallyPresent: options.initiallyPresent ?? true, }); } - -function inferenceSetArgs(captureOpenshell: ReturnType): string[][] { - return captureOpenshell.mock.calls +function inferenceSetArgs(capture: ReturnType) { + return capture.mock.calls .filter(([args]) => args[0] === "inference" && args[1] === "set") .map(([args]) => args); } - -function providerMutationArgs( - captureOpenshell: ReturnType, -): string[][] { - return captureOpenshell.mock.calls - .filter(([args]) => args[0] === "provider" && (args[1] === "create" || args[1] === "update")) +function providerMutationArgs(capture: ReturnType) { + return capture.mock.calls + .filter(([args]) => args[0] === "provider" && ["create", "update"].includes(args[1])) .map(([args]) => args); } -describe("runInferenceSet on a loopback no-auth compatible endpoint", () => { - it("accepts the recorded provider, model, and endpoint URL without replacing the provider", async () => { - const captureOpenshell = noAuthProviderCapture(); +describe("inference selection for existing no-auth endpoints", () => { + it("requires recreation before migrating a beta sandbox's local route (#12558)", async () => { const deps = createDeps({ config: CONFIG, entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, + session: baseSession(noAuthEntry()), }); - - await runInferenceSet( - { - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - }, - deps, - ); - - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - // The gateway route is the proxy's sandbox-bridge address, so host-side - // verification is replaced by the sandbox-side invocation probe. - expect(inferenceSetArgs(captureOpenshell)).toEqual([ - [ - "inference", - "set", - "-g", - "nemoclaw", - "--no-verify", - "--provider", - "compatible-endpoint", - "--model", - "model-b", - ], - ]); - expect(deps.calls.probeSandboxRoute).toHaveBeenCalledWith({ - gatewayName: "nemoclaw", - sandboxName: "alpha", - provider: "compatible-endpoint", - model: "model-b", - preferredInferenceApi: "openai-completions", + await expect( + runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps), + ).rejects.toThrow("Recreate this beta sandbox"); + expect(deps.calls.captureOpenshell).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + it("reuses native custody for model changes without reading the host credential (#12558)", async () => { + const receipt = nativeLocalTestReceipt("compatible-endpoint"); + const entry = { ...noAuthEntry(), nativeLocalProviderAttachment: receipt }; + const deps = createDeps({ + config: structuredClone(CONFIG), + entry, + session: baseSession(entry), }); - expect( - deps.calls.updateSandbox.mock.calls - .filter(([, fields]) => fields.provider !== undefined) - .at(-1), - ).toEqual([ - "alpha", + const prepare = vi.spyOn(deps, "prepareNativeLocalSwitch"); + const resolve = vi.spyOn(deps, "resolveCredentialValue"); + await runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps); + expect(prepare).toHaveBeenCalledWith( + expect.objectContaining({ previous: receipt, binding: null }), + ); + expect(resolve).not.toHaveBeenCalled(); + expect(deps.calls.captureOpenshell.mock.calls.some(([args]) => args[0] === "inference")).toBe( + false, + ); + expect(deps.calls.probeSandboxRoute).toHaveBeenCalledWith( expect.objectContaining({ - provider: "compatible-endpoint", model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - credentialEnv: NO_AUTH_CREDENTIAL_ENV, - preferredInferenceApi: "openai-completions", + nativeLocalProviderAttachment: expect.objectContaining({ providerId: receipt.providerId }), }), - ]); + ); }); - - it("skips host-side verification when no endpoint options are passed", async () => { - const captureOpenshell = noAuthProviderCapture(); + it("does not fall back to the managed route when native inference fails (#12558)", async () => { + const entry = { + ...noAuthEntry(), + nativeLocalProviderAttachment: nativeLocalTestReceipt("compatible-endpoint"), + }; const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, + config: structuredClone(CONFIG), + entry, + session: baseSession(entry), + probeSandboxRoute: async () => ({ ok: false, detail: "native rejected", httpStatus: 401 }), }); - - await runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps); - - expect(inferenceSetArgs(captureOpenshell)).toEqual([ - [ - "inference", - "set", - "-g", - "nemoclaw", - "--no-verify", - "--provider", - "compatible-endpoint", - "--model", - "model-b", - ], - ]); - expect(deps.calls.probeSandboxRoute).toHaveBeenCalled(); - expect( - deps.calls.updateSandbox.mock.calls - .filter(([, fields]) => fields.provider !== undefined) - .at(-1), - ).toEqual(["alpha", expect.objectContaining({ credentialEnv: NO_AUTH_CREDENTIAL_ENV })]); + await expect( + runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps), + ).rejects.toThrow("native rejected"); + expect(deps.calls.captureOpenshell.mock.calls.some(([args]) => args[0] === "inference")).toBe( + false, + ); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + it("rejects an explicit credential binding that differs from recorded no-auth ownership (#12558)", async () => { + const entry = { + ...noAuthEntry(), + nativeLocalProviderAttachment: nativeLocalTestReceipt("compatible-endpoint"), + }; + const deps = createDeps({ + config: structuredClone(CONFIG), + entry, + session: baseSession(entry), + }); + const prepare = vi.spyOn(deps, "prepareNativeLocalSwitch"); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "model-b", + endpointUrl: NO_AUTH_ENDPOINT_URL, + credentialEnv: "FOREIGN_TOKEN", + }, + deps, + ), + ).rejects.toThrow(/credential/); + expect(prepare).not.toHaveBeenCalled(); }); - it("keeps a recorded legacy no-auth route after the proxy port moves", async () => { vi.stubEnv("NEMOCLAW_OLLAMA_PROXY_PORT", "12435"); vi.resetModules(); @@ -166,10 +141,7 @@ describe("runInferenceSet on a loopback no-auth compatible endpoint", () => { import("../../../test/helpers/inference-set"), ]); const endpointUrl = "http://127.0.0.1:11435/v1"; - const entry = { - ...noAuthEntry(), - endpointUrl, - } as SandboxEntry; + const entry = { ...noAuthEntry(), endpointUrl } as SandboxEntry; const session = support.baseSession({ provider: "compatible-endpoint", model: "model-a", @@ -185,10 +157,7 @@ describe("runInferenceSet on a loopback no-auth compatible endpoint", () => { initiallyPresent: true, }); const deps = support.createDeps({ - config: { - agents: { defaults: { model: { primary: "inference/model-a" } } }, - models: { providers: { inference: { api: "openai-completions", models: [] } } }, - }, + config: structuredClone(CONFIG), entry, session, captureOpenshell, @@ -223,233 +192,13 @@ describe("runInferenceSet on a loopback no-auth compatible endpoint", () => { .at(-1), ).toEqual([ "alpha", - expect.objectContaining({ - endpointUrl, - credentialEnv: NO_AUTH_CREDENTIAL_ENV, - }), + expect.objectContaining({ endpointUrl, credentialEnv: NO_AUTH_CREDENTIAL_ENV }), ]); } finally { vi.unstubAllEnvs(); vi.resetModules(); } }); - - it("removes the previous model's context window when the endpoint has no authoritative probe", async () => { - const config = { - agents: { defaults: { model: { primary: "inference/model-a" } } }, - models: { - providers: { - inference: { - api: "openai-completions", - models: [{ id: "model-a", name: "inference/model-a", contextWindow: 16384 }], - }, - }, - }, - }; - const deps = createDeps({ - config, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell: noAuthProviderCapture(), - contextWindow: null, - }); - - await runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps); - - expect(config.models.providers.inference.models[0]).not.toHaveProperty("contextWindow"); - expect(deps.calls.log.mock.calls.flat().join("\n")).toMatch( - /could not determine the context window/i, - ); - }); - - it("refuses a foreign live binding before selecting the route with no endpoint options", async () => { - const captureOpenshell = noAuthProviderCapture({ credentialEnv: "COMPATIBLE_API_KEY" }); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - }); - - await expect( - runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps), - ).rejects.toThrow(/malformed, foreign/); - - expect(inferenceSetArgs(captureOpenshell)).toEqual([]); - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - expect(deps.calls.probeSandboxRoute).not.toHaveBeenCalled(); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); - }); - - it("refuses a provider without a revision before route mutation (#9806)", async () => { - const captureOpenshell = noAuthProviderCapture(); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - }); - const getProvider = vi.spyOn(deps.providerAdapter, "getProvider").mockResolvedValue({ - ok: true as const, - value: { - name: "compatible-endpoint", - type: "openai", - credentialKeys: [NO_AUTH_CREDENTIAL_ENV], - configKeys: ["OPENAI_BASE_URL"], - revision: null, - }, - }); - - await expect( - runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps), - ).rejects.toThrow(/without a revision/); - - expect(inferenceSetArgs(captureOpenshell)).toEqual([]); - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - expect(getProvider).toHaveBeenCalledExactlyOnceWith({ - target: { kind: "named", gatewayName: "nemoclaw" }, - providerName: "compatible-endpoint", - }); - expect(deps.calls.probeSandboxRoute).not.toHaveBeenCalled(); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - }); - - it("refuses an absent provider before selecting the route with no endpoint options", async () => { - const captureOpenshell = noAuthProviderCapture({ initiallyPresent: false }); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - }); - - await expect( - runInferenceSet({ provider: "compatible-endpoint", model: "model-b" }, deps), - ).rejects.toThrow(/Rerun onboarding to restore the provider/); - - expect(inferenceSetArgs(captureOpenshell)).toEqual([]); - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - }); - - it("retries the sandbox probe when it fails before reaching an HTTP status", async () => { - const captureOpenshell = noAuthProviderCapture(); - const probeSandboxRoute = vi - .fn() - .mockReturnValueOnce({ - ok: false as const, - detail: "sandbox inference invocation probe exited with status 6", - httpStatus: null, - }) - .mockReturnValue({ ok: true as const }); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - probeSandboxRoute, - }); - - await runInferenceSet( - { - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - }, - deps, - ); - - expect(probeSandboxRoute).toHaveBeenCalledTimes(2); - expect(deps.calls.sleep.mock.calls).toEqual([[6_000], [2_000]]); - expect(deps.calls.log).toHaveBeenCalledWith( - " Waiting 2s for OpenShell route convergence after the sandbox probe did not receive an HTTP status (probe 1/3)...", - ); - expect( - deps.calls.updateSandbox.mock.calls - .filter(([, fields]) => fields.provider !== undefined) - .at(-1), - ).toEqual([ - "alpha", - expect.objectContaining({ model: "model-b", credentialEnv: NO_AUTH_CREDENTIAL_ENV }), - ]); - }); - - it("rejects an explicit credential-env that is not the recorded no-auth binding", async () => { - const captureOpenshell = noAuthProviderCapture(); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - }); - - await expect( - runInferenceSet( - { - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - credentialEnv: "COMPATIBLE_API_KEY", - }, - deps, - ), - ).rejects.toThrow( - /credential-env for 'compatible-endpoint' must be 'NEMOCLAW_OLLAMA_PROXY_TOKEN'/, - ); - - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - }); - - it("still refuses a live provider whose binding does not match the recorded provenance", async () => { - const captureOpenshell = noAuthProviderCapture({ credentialEnv: "COMPATIBLE_API_KEY" }); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - }); - - await expect( - runInferenceSet( - { - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - }, - deps, - ), - ).rejects.toThrow(/malformed, foreign/); - - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - }); - - it("refuses to recreate a provider whose no-auth binding only onboarding can rebuild", async () => { - const captureOpenshell = noAuthProviderCapture({ initiallyPresent: false }); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - }); - - await expect( - runInferenceSet( - { - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - }, - deps, - ), - ).rejects.toThrow(/Rerun onboarding to restore the provider/); - - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - }); - it("keeps host-side verification and the canonical credential for an authenticated endpoint", async () => { const captureOpenshell = createCompatibleProviderCapture({ name: "compatible-endpoint", diff --git a/src/lib/actions/inference-set-openrouter.test.ts b/src/lib/actions/inference-set-openrouter.test.ts index 23b8c2fa7b2..a39e97753de 100644 --- a/src/lib/actions/inference-set-openrouter.test.ts +++ b/src/lib/actions/inference-set-openrouter.test.ts @@ -199,7 +199,7 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), ).rejects.toThrow( - /Sandbox-side verification rejected.*previous inference selection.*was not changed/s, + /Sandbox-side verification rejected.*previous OpenShell inference selection was restored/s, ); expect(routeSelections(deps)).toEqual([]); @@ -218,7 +218,7 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), - ).rejects.toThrow(/previous inference selection.*was not changed/); + ).rejects.toThrow(/previous OpenShell inference selection was restored/); expect(deps.calls.probeSandboxRoute).toHaveBeenCalledTimes(3); expect(routeSelections(deps)).toEqual([]); @@ -231,7 +231,7 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), - ).rejects.toThrow(/sandbox dial failed.*previous inference selection.*was not changed/s); + ).rejects.toThrow(/sandbox dial failed.*previous OpenShell inference selection was restored/s); expect(routeSelections(deps)).toEqual([]); expectNoConfigCommit(deps); diff --git a/src/lib/actions/inference-set-provider-diagnostics.test.ts b/src/lib/actions/inference-set-provider-diagnostics.test.ts index b2810dcb506..e87f94e0067 100644 --- a/src/lib/actions/inference-set-provider-diagnostics.test.ts +++ b/src/lib/actions/inference-set-provider-diagnostics.test.ts @@ -11,6 +11,7 @@ import { classifyGatewayProviderNames, isBridgeProviderName } from "../credentia import { buildInferenceSetFailure, queryRegisteredGatewayProviders, + rejectInferenceSelectionProbe, } from "./inference-set-provider-diagnostics"; const STATIC_WARNING = @@ -117,3 +118,63 @@ describe("inference set provider diagnostics", () => { expect(providerAdapter.listProviders).not.toHaveBeenCalled(); }); }); + +describe("failed inference selection recovery", () => { + const selection = { + nativeLocal: false, + sandboxName: "alice", + provider: "new-provider", + model: "new-model", + detail: "model invocation rejected", + previousProvider: "old-provider", + previousModel: "old-model", + }; + + it("retains the probe failure and recovery guidance when restoration rejects", async () => { + const error = await rejectInferenceSelectionProbe({ + ...selection, + restorePreviousSelection: async () => { + throw new Error("restore transport failed"); + }, + }).catch((error: Error) => error); + expect(error.name).toBe("InferenceSetError"); + expect(error.message).toContain("model invocation rejected"); + expect(error.message).toContain("restore transport failed"); + expect(error.message).toContain("Re-run onboarding before using this route."); + }); + + it("redacts credential values from a rejected restore operation", async () => { + const error = await rejectInferenceSelectionProbe({ + ...selection, + restorePreviousSelection: async () => { + throw new Error("restore failed: api_key=fixture-private-key"); + }, + }).catch((error: Error) => error); + expect(error.message).toContain("model invocation rejected"); + expect(error.message).toContain("restore failed"); + expect(error.message).not.toContain("fixture-private-key"); + }); + + it("reports successful restoration without masking the rejected probe", async () => { + await expect( + rejectInferenceSelectionProbe({ + ...selection, + restorePreviousSelection: async () => null, + }), + ).rejects.toThrow( + "model invocation rejected. The previous OpenShell inference selection was restored", + ); + }); + + it("does not restore a shared route after a native-local probe fails", async () => { + const restorePreviousSelection = vi.fn(); + await expect( + rejectInferenceSelectionProbe({ + ...selection, + nativeLocal: true, + restorePreviousSelection, + }), + ).rejects.toThrow("Native local inference verification failed"); + expect(restorePreviousSelection).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/inference-set-provider-diagnostics.ts b/src/lib/actions/inference-set-provider-diagnostics.ts index cfb83edbb52..486e038208d 100644 --- a/src/lib/actions/inference-set-provider-diagnostics.ts +++ b/src/lib/actions/inference-set-provider-diagnostics.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { InferenceSetError } from "./inference-set-error"; import type { OpenShellInferenceRouteMutationError } from "../adapters/openshell/inference-route"; import { type CaptureOpenShellInferenceRoute, @@ -85,3 +86,39 @@ export async function buildInferenceSetFailure( message: `${error.message}${providerLine}${tip}${recovery}`, }; } + +/** Report the failed path after its owning compensation, without implying native fallback. */ +export async function rejectInferenceSelectionProbe(input: { + nativeLocal: boolean; + sandboxName: string; + provider: string; + model: string; + detail: string; + previousProvider: string; + previousModel: string; + restorePreviousSelection: () => Promise; +}): Promise { + if (input.nativeLocal) { + throw new InferenceSetError( + `Native local inference verification failed for '${input.sandboxName}': ${input.detail}. No new inference selection was committed.`, + ); + } + let restoreFailure: string | null; + try { + restoreFailure = await input.restorePreviousSelection(); + } catch (error) { + restoreFailure = redactInferenceSetRouteDiagnostic( + (error instanceof Error ? error.message : String(error)) || "Unknown restoration error", + ); + } + if (restoreFailure) { + throw new InferenceSetError( + `Sandbox-side verification rejected provider '${input.provider}' / '${input.model}': ${input.detail}. ` + + `Failed to restore the previous OpenShell inference selection '${input.previousProvider}' / '${input.previousModel}': ${restoreFailure}. Re-run onboarding before using this route.`, + ); + } + throw new InferenceSetError( + `Sandbox-side verification rejected provider '${input.provider}' / '${input.model}': ${input.detail}. ` + + `The previous OpenShell inference selection was restored to '${input.previousProvider}' / '${input.previousModel}'.`, + ); +} diff --git a/src/lib/actions/inference-set-provider.ts b/src/lib/actions/inference-set-provider.ts index 895b2668c46..9c7d33f861c 100644 --- a/src/lib/actions/inference-set-provider.ts +++ b/src/lib/actions/inference-set-provider.ts @@ -683,3 +683,53 @@ export function recordInferenceSetFailure( gatewayName, ); } + +export { retireUnselectedNativeLocalProviders } from "../inference/native-local/selection"; + +// Provider selection owns attachment preparation and compensation for both paths. +export { + prepareNativeLocalSwitch, + rollbackNativeLocalSelection, + prepareNativeLocalSelectionBoundary, + detachPreviousNativeLocalBeforePublish, + nativeLocalSelectionRegistryFields, +} from "./inference/native-local"; +export { requireNativeProviderPolicy } from "../adapters/openshell/provider-policy"; +export { + usesNativeLocalInference, + normalizeNativeLocalProviderAttachment, +} from "../inference/native-local/contract"; +export { + detachNativeLocalProvider, + ensureNativeLocalProviderAttached, +} from "../inference/native-local/profile"; + +/** Restore only a distinct observed shared route; native providers own their compensation. */ +export async function restoreSharedInferenceSelection(input: { + nativeSelection: boolean; + rollbackRoute: { provider: string; model: string } | null; + provider: string; + model: string; + gatewayName: string; + mutator: import("../adapters/openshell/inference-route").OpenShellInferenceRouteMutator; +}): Promise { + if (input.nativeSelection) return null; + const rollbackRoute = input.rollbackRoute; + if (!rollbackRoute) return "the pre-mutation gateway route was not configured"; + if (rollbackRoute.provider === input.provider && rollbackRoute.model === input.model) { + return ( + `the route observed immediately before this attempt already selected '${input.provider}' / '${input.model}', ` + + "so there is no distinct prior inference selection to restore" + ); + } + const result = await input.mutator.setInferenceRoute({ + target: { kind: "named", gatewayName: input.gatewayName }, + route: rollbackRoute, + verification: "skip", + }); + if (result.ok) return null; + if (!result.ambiguous && result.error.kind === "command" && result.error.exitCode !== null) { + return `the restore command exited with status ${String(result.error.exitCode)}`; + } + return result.error.message; +} diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index cb2b42d4a74..c052e1daab7 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1,6 +1,21 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { rejectInferenceSelectionProbe } from "./inference-set-provider-diagnostics"; +import { + type NativeLocalProviderAttachment, + usesNativeLocalInferenceForAgent, +} from "../inference/config"; +import { + requireNativeProviderPolicy, + prepareNativeLocalSwitch, + rollbackNativeLocalSelection, + restoreSharedInferenceSelection, + prepareNativeLocalSelectionBoundary, + detachPreviousNativeLocalBeforePublish, + nativeLocalSelectionRegistryFields, + retireUnselectedNativeLocalProviders, +} from "./inference-set-provider"; import { captureResolvedOpenshellAsync, getOpenshellBinary } from "../adapters/openshell/runtime"; import type { OpenShellInferenceRouteObservation, @@ -23,7 +38,13 @@ import { ensureHttpsPinRuntimeAdapter, revokeHttpsPinRuntimeAdapterRoute, } from "../inference/https-pin-runtime-adapter"; -import { type ValidationResult, validateLocalProvider } from "../inference/local"; +import { + type ValidationResult, + validateLocalProvider, + getLocalProviderBaseUrl, + getManagedVllmProviderBinding, + shouldFrontOllamaWithProxy, +} from "../inference/local"; import { inferenceSelectionRegistryFields, type ReasoningEffortRequest, @@ -69,7 +90,7 @@ import { nativeSelectionRegistryFields, } from "./inference-set/native"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; -import { InferenceSetError, inferenceProbeRecoveryMessage } from "./inference-set-error"; +import { InferenceSetError } from "./inference-set-error"; import { completeInferencePostCommit, defaultInferenceGatewayRestart, @@ -183,12 +204,18 @@ function providerCommitFailureAfterSelection(options: { } export interface InferenceSetDeps extends InferenceGatewayRestartDeps { + requireNativeProviderPolicy?: typeof requireNativeProviderPolicy; getDefaultSandbox: () => string | null; getSandbox: (name: string) => SandboxEntry | null; listSandboxes: () => { sandboxes: SandboxEntry[]; defaultSandbox: string | null; }; + prepareNativeLocalSwitch?: typeof prepareNativeLocalSwitch; + getNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").getNativeLocalProviderAuthority; + setNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").setNativeLocalProviderAuthority; + listNativeLocalProviderAuthorities?: typeof import("../state/registry/native-local-provider-authority").listNativeLocalProviderAuthorities; + clearNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").clearNativeLocalProviderAuthority; getNativeHostedProviderAuthority?: typeof registry.getNativeHostedProviderAuthority; setNativeHostedProviderAuthority?: typeof registry.setNativeHostedProviderAuthority; getNativeNvidiaProviderAuthority?: typeof registry.getNativeNvidiaProviderAuthority; @@ -1260,13 +1287,20 @@ 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( + const selectingNativeLocal = usesNativeLocalInferenceForAgent( + agentName, provider, - entry, - options.endpointUrl, - expectedGatewayName, - deps, + options.endpointUrl ?? (entry.provider === provider ? entry.endpointUrl : null), ); + const selectingNative = + selectingNativeLocal || + isNativeInferenceSelection(provider, entry, options.endpointUrl, expectedGatewayName, deps); + const previousNativeLocalAttachment = await prepareNativeLocalSelectionBoundary({ + entry, + selectingNativeLocal, + gatewayName: expectedGatewayName, + requirePolicy: deps.requireNativeProviderPolicy, + }); const routeSandboxes = deps.listSandboxes().sandboxes; const preparedRoute = prepareInferenceSetRoute({ entry: routeEntry, @@ -1461,7 +1495,7 @@ async function runInferenceSetWithoutHostLock( httpsPinProviderBinding: Boolean(httpsPinProviderBinding), probeDirectSandboxBridge: probeSandboxRoute, rollbackRoute: Boolean(rollbackRoute), - previousNativeAttachment: Boolean(previousNativeAttachment), + previousNativeAttachment: Boolean(previousNativeAttachment || previousNativeLocalAttachment), }) ) { throw new InferenceSetError( @@ -1479,6 +1513,11 @@ async function runInferenceSetWithoutHostLock( let providerMutation: Awaited> | null = null; let assertProviderCurrentBeforeSelection: (() => Promise) | null = null; + let nativeLocalProviderAttachment: NativeLocalProviderAttachment | undefined; + let nativeLocalAttachmentChanged = false; + let nativeLocalRegistryCommitted = false; + let previousNativeLocalDetached = false; + let previousNativeLocalDetachCommitted = false; let nativeNvidiaCredentialHandle: string | undefined; let nativeProviderAttachment: NativeProviderAttachment | undefined; let nativeAttachmentChanged = false; @@ -1486,38 +1525,20 @@ async function runInferenceSetWithoutHostLock( let previousNativeDetached = false; let previousNativeDetachCommitted = false; const restorePreviousInferenceSelection = async (): Promise => { - if (selectingNative) { - appliedInferenceSelection = false; - return null; - } - if (!rollbackRoute) return "the pre-mutation gateway route was not configured"; - if (rollbackRoute.provider === provider && rollbackRoute.model === model) { - return ( - `the route observed immediately before this attempt already selected '${provider}' / '${model}', ` + - "so there is no distinct prior inference selection to restore" - ); - } - const restoreResult = await deps.inferenceRouteMutator.setInferenceRoute({ - target: { kind: "named", gatewayName: preparedRoute.gatewayName }, - route: rollbackRoute, - verification: "skip", + const detail = await restoreSharedInferenceSelection({ + nativeSelection: selectingNative, + rollbackRoute, + provider, + model, + gatewayName: preparedRoute.gatewayName, + mutator: deps.inferenceRouteMutator, }); - if (!restoreResult.ok) { - if ( - !restoreResult.ambiguous && - restoreResult.error.kind === "command" && - restoreResult.error.exitCode !== null - ) { - return `the restore command exited with status ${String(restoreResult.error.exitCode)}`; - } - return restoreResult.error.message; - } - appliedInferenceSelection = false; - return null; + if (detail === null) appliedInferenceSelection = false; + return detail; }; try { const nativeSelection = await prepareNativeSelection({ - selectingNative, + selectingNative: selectingNative && !selectingNativeLocal, provider, expectedAttachment: nativeProviderAuthority, gatewayName: preparedRoute.gatewayName, @@ -1534,7 +1555,27 @@ async function runInferenceSetWithoutHostLock( read: deps.readNativeNvidiaCredentialHandle, }); const providerBinding = httpsPinProviderBinding ?? directProviderBinding; - if (providerBinding) { + if (selectingNativeLocal) { + const selected = await (deps.prepareNativeLocalSwitch ?? prepareNativeLocalSwitch)({ + local: { + getLocalProviderBaseUrl, + getManagedVllmProviderBinding, + shouldFrontOllamaWithProxy, + }, + provider, + sandboxName, + gatewayName: preparedRoute.gatewayName, + previous: previousNativeLocalAttachment, + binding: directProviderBinding, + adapter: deps.providerAdapter, + resolveCredentialValue: deps.resolveCredentialValue, + readAuthority: deps.getNativeLocalProviderAuthority, + writeAuthority: deps.setNativeLocalProviderAuthority, + }); + nativeLocalProviderAttachment = selected.receipt; + nativeLocalAttachmentChanged = selected.changed; + previousNativeLocalDetached = selected.previousDetached; + } else if (providerBinding) { providerMutation = await prepareInferenceSetProviderBinding({ gatewayName: preparedRoute.gatewayName, providerName: provider, @@ -1631,7 +1672,9 @@ async function runInferenceSetWithoutHostLock( model, preferredInferenceApi: preMutationInferenceApi, ...(selectingNative ? { nativeProvider: true } : {}), - nativeEndpointUrl: nativeSelection.endpointUrl, + nativeLocalProviderAttachment, + nativeEndpointUrl: + nativeLocalProviderAttachment?.endpointUrl ?? nativeSelection.endpointUrl, }, previousProvider, previousModel, @@ -1667,23 +1710,16 @@ async function runInferenceSetWithoutHostLock( }; } if (!probe.ok) { - const restoreFailure = await restorePreviousInferenceSelection(); - if (restoreFailure) { - throw new InferenceSetError( - `Sandbox-side verification rejected provider '${provider}' / '${model}': ${probe.detail}. ` + - `Failed to restore the previous OpenShell inference selection '${rollbackRoute?.provider ?? previousProvider}' / ` + - `'${rollbackRoute?.model ?? previousModel}': ${restoreFailure}. Re-run onboarding before using this route.`, - ); - } - const recovery = inferenceProbeRecoveryMessage( - selectingNative, - previousProvider, - previousModel, - rollbackRoute, - ); - throw new InferenceSetError( - `Sandbox-side verification rejected provider '${provider}' / '${model}': ${probe.detail}. ${recovery}`, - ); + await rejectInferenceSelectionProbe({ + nativeLocal: selectingNativeLocal, + sandboxName, + provider, + model, + detail: probe.detail, + previousProvider: rollbackRoute?.provider ?? previousProvider, + previousModel: rollbackRoute?.model ?? previousModel, + restorePreviousSelection: restorePreviousInferenceSelection, + }); } } @@ -1699,6 +1735,14 @@ async function runInferenceSetWithoutHostLock( deps, }); + previousNativeLocalDetached = await detachPreviousNativeLocalBeforePublish({ + adapter: deps.providerAdapter, + sandboxName, + detached: previousNativeLocalDetached, + previous: previousNativeLocalAttachment, + next: nativeLocalProviderAttachment, + }); + // Write minimal registry state before any sandbox-facing config read so the // gateway and registry cannot split if the in-sandbox layer is unavailable. const registryFields = (preferredInferenceApi: string | null) => ({ @@ -1724,8 +1768,16 @@ async function runInferenceSetWithoutHostLock( nimContainer: registryMetadata.nimContainer ?? null, }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), + ...nativeLocalSelectionRegistryFields( + nativeLocalProviderAttachment, + previousNativeLocalDetached, + ), ...nativeSelectionRegistryFields(nativeProviderAttachment, previousNativeDetached), - ...(nativeSelection.endpointUrl ? { endpointUrl: nativeSelection.endpointUrl } : {}), + ...(nativeLocalProviderAttachment?.endpointUrl + ? { endpointUrl: nativeLocalProviderAttachment.endpointUrl } + : nativeSelection.endpointUrl + ? { endpointUrl: nativeSelection.endpointUrl } + : {}), }); if ( !deps.updateSandbox( @@ -1743,6 +1795,8 @@ async function runInferenceSetWithoutHostLock( `Failed to update NemoClaw registry for sandbox '${sandboxName}'.`, ); } + nativeLocalRegistryCommitted = Boolean(nativeLocalProviderAttachment); + previousNativeLocalDetachCommitted = previousNativeLocalDetached; nativeRegistryCommitted = Boolean(nativeProviderAttachment); previousNativeDetachCommitted = previousNativeDetached; @@ -1802,7 +1856,7 @@ async function runInferenceSetWithoutHostLock( model, preferredInferenceApi, contextWindow, - nativeSelection.endpointUrl, + nativeLocalProviderAttachment?.endpointUrl ?? nativeSelection.endpointUrl, selectingNative, nativeNvidiaCredentialHandle, ); @@ -1827,7 +1881,7 @@ async function runInferenceSetWithoutHostLock( provider, reasoningEffortRequest, true, - nativeSelection.endpointUrl, + nativeLocalProviderAttachment?.endpointUrl ?? nativeSelection.endpointUrl, selectingNative, ); } @@ -1958,29 +2012,58 @@ async function runInferenceSetWithoutHostLock( expectedGatewayName, ); if (error instanceof OpenClawInferenceConfigSyncError) throw error; - await restorePreviousNativeAfterFailedPublish({ + let failure = await rollbackNativeLocalSelection({ + adapter: deps.providerAdapter, + sandboxName, + provider, + attachment: nativeLocalProviderAttachment, + previous: previousNativeLocalAttachment, + attachmentChanged: nativeLocalAttachmentChanged, + registryCommitted: nativeLocalRegistryCommitted, + previousDetached: previousNativeLocalDetached, + previousDetachCommitted: previousNativeLocalDetachCommitted, + getSandbox: deps.getSandbox, + }).then( + () => error, + (rollbackError: unknown) => { + const detail = error instanceof Error ? error.message : String(error); + const rollbackDetail = + rollbackError instanceof Error ? rollbackError.message : String(rollbackError); + return new InferenceSetError( + `${detail}\n Native local access compensation failed: ${rollbackDetail}`, + error instanceof InferenceSetError ? error.exitCode : 1, + ); + }, + ); + failure = await restorePreviousNativeAfterFailedPublish({ detached: previousNativeDetached, committed: previousNativeDetachCommitted, previousAttachment: previousNativeAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, - error, + error: failure, deps, - }); - await rollbackNativeSelection({ + }).then( + () => failure, + (rollbackError: unknown) => rollbackError, + ); + failure = await rollbackNativeSelection({ attachmentChanged: nativeAttachmentChanged, registryCommitted: nativeRegistryCommitted, attachment: nativeProviderAttachment, 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; + }).then( + () => failure, + (rollbackError: unknown) => rollbackError, + ); + 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 { @@ -2079,6 +2162,19 @@ export async function runInferenceSet( recordInferenceSetResult(selected.sandboxName, "failed", "partial", gatewayName); throw error; } + const committed = deps.getSandbox(selected.sandboxName); + if (!committed) + throw new InferenceSetError( + "Sandbox cleanup authority is unavailable after inference selection.", + ); + await retireUnselectedNativeLocalProviders({ + adapter: deps.providerAdapter, + sandboxName: selected.sandboxName, + gatewayName, + selected: committed.nativeLocalProviderAttachment, + listAuthorities: deps.listNativeLocalProviderAuthorities, + clearAuthority: deps.clearNativeLocalProviderAuthority, + }); completeInferenceSetTelemetry(selected.sandboxName, gatewayName); return mutation.result; }); diff --git a/src/lib/actions/inference-set/native.ts b/src/lib/actions/inference-set/native.ts index 1ea2a0a4ffa..8dcb8a37208 100644 --- a/src/lib/actions/inference-set/native.ts +++ b/src/lib/actions/inference-set/native.ts @@ -5,6 +5,10 @@ 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 { + nativeLocalCredentialReference, + NATIVE_LOCAL_RUNTIME_REFERENCE_PATTERN, +} from "../../inference/native-local/agent-config"; import { isSafeModelId } from "../../validation"; import { InferenceSetError } from "../inference-set-error"; import type { NativeProviderAttachment } from "../../inference/native-provider/contract"; @@ -282,12 +286,15 @@ export function nativeSelectionConfigCredentials( const native = nativeHostedAgentConfig(provider, baseUrl); return { apiKey: + nativeLocalCredentialReference(provider, baseUrl) ?? native?.apiKey ?? managedInferenceApiKey( baseUrl, typeof existingApiKey === "string" && existingApiKey && - existingApiKey !== NVIDIA_INFERENCE_PLACEHOLDER + existingApiKey !== NVIDIA_INFERENCE_PLACEHOLDER && + existingApiKey !== "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN" && + !new RegExp(NATIVE_LOCAL_RUNTIME_REFERENCE_PATTERN, "u").test(existingApiKey) ? existingApiKey : "unused", ), diff --git a/src/lib/actions/inference/native-local.ts b/src/lib/actions/inference/native-local.ts new file mode 100644 index 00000000000..9670ea511b8 --- /dev/null +++ b/src/lib/actions/inference/native-local.ts @@ -0,0 +1,250 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { requireNativeProviderPolicy } from "../../adapters/openshell/provider-policy"; +import { InferenceSetError } from "../inference-set-error"; +import type { SandboxEntry } from "../../state/registry"; +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; +import { + LLAMA_CPP_CREDENTIAL_ENV, + LLAMA_CPP_GATEWAY_BASE_URL, +} from "../../inference/llama-cpp/contract"; +import { getOllamaProxyToken } from "../../inference/ollama/proxy"; +import { + normalizeNativeLocalProviderAttachment, + usesNativeLocalInference, + type NativeLocalProvider, + type NativeLocalProviderAttachment, +} from "../../inference/native-local/contract"; +import { + ensureNativeLocalProviderAttached, + detachNativeLocalProvider, +} from "../../inference/native-local/profile"; +import { prepareNativeLocalSelection } from "../../inference/native-local/selection"; +import type { InferenceSetProviderBinding } from "../inference-set-route-containment"; + +export async function prepareNativeLocalSwitch(input: { + local: Pick< + typeof import("../../inference/local"), + "getLocalProviderBaseUrl" | "getManagedVllmProviderBinding" | "shouldFrontOllamaWithProxy" + >; + provider: string; + gatewayName: string; + sandboxName: string; + previous?: NativeLocalProviderAttachment; + binding: InferenceSetProviderBinding | null; + adapter: OpenShellProviderAdapter; + resolveCredentialValue: (name: string) => string; + readAuthority?: Parameters[0]["readAuthority"]; + writeAuthority?: Parameters[0]["writeAuthority"]; +}) { + if (input.previous?.provider === input.provider && !input.binding) { + return { + ...(await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + expected: input.previous, + sandboxName: input.sandboxName, + })), + previousDetached: false, + }; + } + const vllm = input.provider === "vllm-local" ? input.local.getManagedVllmProviderBinding() : null; + const proxy = input.provider === "ollama-local" && input.local.shouldFrontOllamaWithProxy(); + const endpointUrl = + input.binding?.baseUrl ?? + vllm?.baseUrl ?? + (input.provider === "llama-cpp-local" + ? LLAMA_CPP_GATEWAY_BASE_URL + : input.local.getLocalProviderBaseUrl(input.provider)); + if (!endpointUrl) + throw new Error("The local inference endpoint is unavailable. Run onboarding to qualify it."); + const credentialValue = + input.binding?.token ?? + vllm?.apiKey ?? + (input.provider === "ollama-local" + ? proxy + ? getOllamaProxyToken() + : "ollama" + : input.provider === "vllm-local" + ? "dummy" + : input.resolveCredentialValue(LLAMA_CPP_CREDENTIAL_ENV)); + const receipt = await prepareNativeLocalSelection({ + adapter: input.adapter, + binding: { + provider: input.provider as NativeLocalProvider, + gatewayName: input.gatewayName, + sandboxName: input.sandboxName, + endpointUrl, + authMode: + !input.binding && !vllm && !proxy && input.provider !== "llama-cpp-local" + ? "sentinel" + : "authenticated", + }, + credentialValue: credentialValue || null, + ownedProxy: proxy, + readAuthority: input.readAuthority, + writeAuthority: input.writeAuthority, + }); + const previousDetached = Boolean( + input.previous && input.previous.providerName !== receipt.providerName, + ); + try { + if (previousDetached) + await detachNativeLocalProvider({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous!, + }); + const attached = await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + expected: receipt, + sandboxName: input.sandboxName, + }); + return { ...attached, previousDetached }; + } catch (error) { + const observed = await input.adapter.listProviderAttachments({ + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + }); + if (!observed.ok || observed.value.names.includes(receipt.providerName)) + throw new Error( + "Native attachment failure could not be reconciled. Provider ownership was retained; inspect sandbox attachments before retrying.", + { cause: error }, + ); + if (previousDetached) { + try { + await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous!, + }); + } catch (restoreError) { + throw nativeLocalRestorationFailure(error, restoreError); + } + } + throw error; + } +} + +/** Observe durable selection before compensating a failed provider replacement. */ +export async function rollbackNativeLocalSelection(input: { + adapter: OpenShellProviderAdapter; + sandboxName: string; + provider: string; + attachment?: NativeLocalProviderAttachment; + previous?: NativeLocalProviderAttachment; + attachmentChanged: boolean; + registryCommitted: boolean; + previousDetached: boolean; + previousDetachCommitted: boolean; + getSandbox: typeof import("../../state/registry").getSandbox; +}): Promise { + if (!input.attachment && !input.previous) return; + const entry = input.getSandbox(input.sandboxName); + const recorded = normalizeNativeLocalProviderAttachment(entry?.nativeLocalProviderAttachment); + if (entry?.nativeLocalProviderAttachment !== undefined && !recorded) { + throw new Error( + "Malformed native local provider attachment; compensation requires valid authority.", + ); + } + const committed = + input.registryCommitted || + Boolean( + recorded && + recorded.providerId === input.attachment?.providerId && + recorded.providerName === input.attachment?.providerName, + ); + const previousDetachCommitted = + input.previousDetachCommitted || + committed || + (input.previousDetached && + !input.attachment && + entry?.provider === input.provider && + entry.nativeLocalProviderAttachment === undefined); + if (input.attachmentChanged && !committed && input.attachment) { + await detachNativeLocalProvider({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.attachment, + }); + } + if (input.previousDetached && !previousDetachCommitted && input.previous) { + await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous, + }); + } +} + +export async function prepareNativeLocalSelectionBoundary(input: { + entry: SandboxEntry; + selectingNativeLocal: boolean; + gatewayName: string; + requirePolicy?: typeof requireNativeProviderPolicy; +}) { + if (input.selectingNativeLocal) + await (input.requirePolicy ?? requireNativeProviderPolicy)(input.gatewayName); + const previous = normalizeNativeLocalProviderAttachment( + input.entry.nativeLocalProviderAttachment, + ); + if ( + input.selectingNativeLocal && + usesNativeLocalInference(input.entry.provider, input.entry.endpointUrl) && + !previous + ) { + throw new InferenceSetError( + "Recreate this beta sandbox before changing its native local inference selection.", + 2, + ); + } + return previous; +} + +export async function detachPreviousNativeLocalBeforePublish(input: { + adapter: OpenShellProviderAdapter; + sandboxName: string; + detached: boolean; + previous?: NativeLocalProviderAttachment; + next?: NativeLocalProviderAttachment; +}): Promise { + if (input.detached || !input.previous || input.previous.providerName === input.next?.providerName) + return input.detached; + try { + await detachNativeLocalProvider({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous, + }); + } catch (error) { + try { + await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous, + }); + } catch (restoreError) { + throw nativeLocalRestorationFailure(error, restoreError); + } + throw error; + } + return true; +} + +function nativeLocalRestorationFailure(original: unknown, restoration: unknown): Error { + const originalDetail = original instanceof Error ? original.message : String(original); + const restorationDetail = + restoration instanceof Error ? restoration.message : String(restoration); + return new Error( + `${originalDetail}\n Restoring the previous native local provider attachment also failed: ${restorationDetail}`, + { cause: new AggregateError([original, restoration]) }, + ); +} + +export function nativeLocalSelectionRegistryFields( + attachment: NativeLocalProviderAttachment | undefined, + previousDetached: boolean, +) { + if (attachment) return { nativeLocalProviderAttachment: attachment }; + return previousDetached ? { nativeLocalProviderAttachment: undefined } : {}; +} diff --git a/src/lib/actions/sandbox/agents/managed-workload-rebuild-profile.ts b/src/lib/actions/sandbox/agents/managed-workload-rebuild-profile.ts index 81c3008f905..041a52302c0 100644 --- a/src/lib/actions/sandbox/agents/managed-workload-rebuild-profile.ts +++ b/src/lib/actions/sandbox/agents/managed-workload-rebuild-profile.ts @@ -95,8 +95,8 @@ export function prepareManagedRebuildProfileHandoff(input: { resumeConfig.provider, resumeConfig.model, resumeConfig.preferredInferenceApi, - Boolean(nativeAttachment), - nativeAttachment?.endpointUrl, + Boolean(nativeAttachment || resumeConfig.nativeLocalProviderAttachment), + resumeConfig.nativeLocalProviderAttachment?.endpointUrl ?? nativeAttachment?.endpointUrl, ); const upstreamProvider = agent === "hermes" && resumeConfig.provider === "hermes-provider" diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 3fb53f88832..5a3c4d274a9 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -1718,7 +1718,7 @@ async function ensureSandboxInferenceRouteUnlocked( const { provider, model } = inference; const gatewayName = getPersistedSandboxTargetGatewayName(sb); const nativeAttachment = getNativeProviderAttachment(sb); - if (nativeAttachment) { + if (nativeAttachment || sb.nativeLocalProviderAttachment !== undefined) { await requireNativeInferenceHealth({ sandboxName, gatewayName, @@ -1879,7 +1879,10 @@ async function ensureSandboxInferenceRoute( if (!snapshot) return { sandbox: null, routeHealthy: null }; if (registry.getSandboxEntryInference(snapshot).kind !== "configured") return { sandbox: snapshot, routeHealthy: null }; - if (getNativeProviderAttachment(snapshot)) { + if ( + getNativeProviderAttachment(snapshot) || + snapshot.nativeLocalProviderAttachment !== undefined + ) { return ensureSandboxInferenceRouteUnlocked(sandboxName, agent, { quiet }); } const gatewayName = getPersistedSandboxTargetGatewayName(snapshot); diff --git a/src/lib/actions/sandbox/destroy-execution.ts b/src/lib/actions/sandbox/destroy-execution.ts index 85b5eab6e76..cb2946c8a55 100644 --- a/src/lib/actions/sandbox/destroy-execution.ts +++ b/src/lib/actions/sandbox/destroy-execution.ts @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { finishTelemetryOperation, recordTelemetryTarget } from "../telemetry/operation"; - +import { retireUnselectedNativeLocalProviders } from "../../inference/native-local/selection"; +import { createManagedProviderAdapter } from "../../adapters/openshell/managed-provider-adapter"; +import { listNativeLocalProviderAuthorities } from "../../state/registry/native-local-provider-authority"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; @@ -950,6 +952,9 @@ export async function executeSandboxDestroy({ pendingCreateIdentity?.gatewayName ?? destroyRuntimeSelection?.gatewayName ?? deleteGatewayName; + const hasNativeLocalAuthority = + Boolean(sandbox?.nativeLocalProviderAttachment) || + listNativeLocalProviderAuthorities(sandboxName, effectiveDeleteGatewayName).length > 0; // A successful preflight absence is already the required OpenShell // lifecycle proof. Do not issue a later mutable-name delete that could // target a same-name replacement created after that observation. @@ -1015,6 +1020,7 @@ export async function executeSandboxDestroy({ force && !hasMcpOwnership && !hasHostLocalInferenceOwnership && + !hasNativeLocalAuthority && portableContainerAuthority === undefined; if (deleteFailed && !forcedLocalCleanup) { @@ -1028,7 +1034,7 @@ export async function executeSandboxDestroy({ gatewayUnreachable, ...(timedOut ? { timedOut: true as const } : {}), hostLocalInferenceOwnershipRequiresGateway: - gatewayUnreachable && hasHostLocalInferenceOwnership, + gatewayUnreachable && (hasHostLocalInferenceOwnership || hasNativeLocalAuthority), mcpOwnershipRequiresGateway: gatewayUnreachable && hasMcpOwnership, mcpRecoveryFailure, portableLifecycleOwnershipRequiresGateway: @@ -1176,3 +1182,26 @@ export async function recordDestroyCompletion( }); if (exitCode !== undefined) await finishTelemetryOperation(exitCode); } + +/** Retire native credentials only after the caller confirms sandbox deletion. */ +export async function retireDestroyedSandboxNativeLocalProvider( + sandbox: SandboxEntry, + gatewayName: string, + runOpenshell: DestroyRunOpenshell, + runtimeSelection?: OpenShellRuntimeSelection, +): Promise { + const selectedRunOpenshell: DestroyRunOpenshell | undefined = runtimeSelection + ? (args, options = {}) => + runOpenshell(args, { + ...options, + env: buildSelectedOpenShellSubprocessEnv(runtimeSelection), + replaceEnv: true, + }) + : undefined; + await retireUnselectedNativeLocalProviders({ + adapter: createManagedProviderAdapter(selectedRunOpenshell), + destroyedAttachment: sandbox.nativeLocalProviderAttachment, + sandboxName: sandbox.name, + gatewayName, + }); +} diff --git a/src/lib/actions/sandbox/destroy-native-local.test.ts b/src/lib/actions/sandbox/destroy-native-local.test.ts new file mode 100644 index 00000000000..73bba948b97 --- /dev/null +++ b/src/lib/actions/sandbox/destroy-native-local.test.ts @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + createDestroyHarness, + resetDestroyModuleCache, +} from "../../../../test/helpers/destroy-flow-test-harness"; +import { serializedLlamaCppHostLocalInferenceReceipt } from "../../../../test/helpers/host-local-inference-receipt"; +import type { SandboxEntry } from "../../state/registry"; +import { + nativeLocalIdentity, + type NativeLocalBinding, +} from "../../inference/native-local/contract"; +import { retireDestroyedSandboxNativeLocalProvider } from "./destroy-execution"; + +const binding: NativeLocalBinding = { + provider: "llama-cpp-local", + endpointUrl: "http://host.openshell.internal:8080/v1", + credentialEnv: "NEMOCLAW_LLAMACPP_LOCAL_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", +}; +const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-provider-id", +}; + +describe("native local provider destroy", () => { + let home: string; + beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-destroy-")); + vi.stubEnv("HOME", home); + vi.stubEnv("OPENSHELL_GATEWAY", "nemoclaw-19080"); + vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + }); + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + resetDestroyModuleCache(); + fs.rmSync(home, { force: true, recursive: true }); + }); + + it( + "releases the runtime cleanup lease and preserves registry authority when provider retirement fails (#12558)", + { timeout: 30_000 }, + async () => { + const abort = vi.fn(); + const cleanup = vi.fn(() => ({ ok: true as const, removed: [], preserved: [] })); + const harness = createDestroyHarness({ + provider: "llama-cpp-local", + hostLocalInferenceReceipt: serializedLlamaCppHostLocalInferenceReceipt(), + registryEntryOverrides: { nativeLocalProviderAttachment: attachment }, + preparedManagedLlamaCppRuntimeCleanup: { abort, cleanup }, + }); + harness.retireNativeLocalProviderSpy.mockRejectedValueOnce( + new Error("provider ownership uncertain"), + ); + await expect(harness.destroySandbox("alpha", { yes: true })).rejects.toThrow( + "provider ownership uncertain", + ); + expect(abort).toHaveBeenCalledOnce(); + expect(cleanup).not.toHaveBeenCalled(); + expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); + }, + ); + + it("retains native provider authority when forced deletion cannot reach the gateway (#12558)", async () => { + const harness = createDestroyHarness({ + deleteStatus: 1, + deleteOutput: "connection refused", + registryEntryOverrides: { nativeLocalProviderAttachment: attachment }, + }); + await expect(harness.destroySandbox("alpha", { yes: true, force: true })).rejects.toThrow( + "process.exit(1)", + ); + expect(harness.retireNativeLocalProviderSpy).not.toHaveBeenCalled(); + expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); + }); + it("retains detached provider cleanup authority after an unreachable forced destroy (#12558)", async () => { + const harness = createDestroyHarness({ deleteStatus: 1, deleteOutput: "connection refused" }); + const authority = harness.nativeLocalProviderAuthority; + authority.setNativeLocalProviderAuthority(attachment); + await expect(harness.destroySandbox("alpha", { yes: true, force: true })).rejects.toThrow( + "process.exit(1)", + ); + expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); + expect(authority.getNativeLocalProviderAuthority(attachment.providerName)).toEqual(attachment); + }); + + it("runs native authority cleanup after confirmed destroy even when the current route is shared (#12558)", async () => { + const harness = createDestroyHarness({}); + await harness.destroySandbox("alpha", { yes: true }); + expect(harness.retireNativeLocalProviderSpy).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ name: "alpha" }), + "nemoclaw-19080", + expect.any(Function), + undefined, + ); + expect(harness.removeSandboxSpy).toHaveBeenCalledOnce(); + }); + + it("retires the native provider in the selected OpenShell workspace (#12975)", async () => { + vi.stubEnv("OPENSHELL_WORKSPACE", "ambient-workspace"); + const runOpenshell = vi.fn(() => ({ + status: 1, + stdout: "", + stderr: `Error: provider '${attachment.providerName}' not found`, + })); + const sandbox = { + name: "alpha", + nativeLocalProviderAttachment: attachment, + } as SandboxEntry; + + await retireDestroyedSandboxNativeLocalProvider(sandbox, binding.gatewayName, runOpenshell, { + gatewayName: binding.gatewayName, + workspace: "owned-workspace", + }); + + expect(runOpenshell).toHaveBeenCalledWith( + expect.arrayContaining(["provider", "get", attachment.providerName]), + expect.objectContaining({ + replaceEnv: true, + env: expect.objectContaining({ + OPENSHELL_GATEWAY: binding.gatewayName, + OPENSHELL_WORKSPACE: "owned-workspace", + }), + }), + ); + }); +}); diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 74becad57c7..cb31b7aecb0 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -60,6 +60,7 @@ import { import { executeSandboxDestroy, recordDestroyCompletion, + retireDestroyedSandboxNativeLocalProvider, preparePortableDemoSandboxDestroyAuthority, redactDestroyError, retirePortableLifecycleAuthority, @@ -1148,6 +1149,17 @@ async function destroySandboxUnlocked( if (!deleteSucceededOrAlreadyGone) { preparedManagedLlamaCppCleanup?.abort(); } + if (deleteSucceededOrAlreadyGone && sandbox) { + await retireDestroyedSandboxNativeLocalProvider( + sandbox, + cleanupGatewayName, + runOpenshell, + destroyRuntimeSelection, + ).catch((error) => { + preparedManagedLlamaCppCleanup?.abort(); + throw error; + }); + } if (deleteSucceededOrAlreadyGone && sandbox) { abortPreparedCleanupOnError(() => stopDestroyedSandboxProxy(sandboxName, sandbox, listRegisteredSandboxes, { diff --git a/src/lib/actions/sandbox/doctor-inference.test.ts b/src/lib/actions/sandbox/doctor-inference.test.ts index f8b8fe1c446..22c9e5a0010 100644 --- a/src/lib/actions/sandbox/doctor-inference.test.ts +++ b/src/lib/actions/sandbox/doctor-inference.test.ts @@ -8,6 +8,7 @@ import { import { describe, expect, it, vi } from "vitest"; import type { ProviderHealthStatus } from "../../inference/health"; import { collectInferenceChecks, collectManagedLlamaCppDoctorChecks } from "./doctor-inference"; +import { nativeLocalTestReceipt } from "../../../../test/helpers/inference-set"; const endpoint = "https://inference.local/v1/models"; @@ -517,3 +518,28 @@ describe("hosted native doctor", () => { }, ); }); + +it("fails a reachable native local route when gateway authority is missing", async () => { + const verify = vi.fn(); + const probe = vi.fn(); + const checks = await collectInferenceChecks( + "alpha", + { + provider: "ollama-local", + model: "model", + nativeLocalProviderAttachment: nativeLocalTestReceipt(), + }, + true, + { + verifyNativeLocalStatusAttachmentImpl: verify, + nativeLocalInvocationProbe: probe, + probeProviderHealthImpl: () => null, + includeServingProcessCheck: false, + }, + ); + expect(checks).toContainEqual( + expect.objectContaining({ label: "Inference route (native local)", status: "fail" }), + ); + expect(verify).not.toHaveBeenCalled(); + expect(probe).not.toHaveBeenCalled(); +}); diff --git a/src/lib/actions/sandbox/doctor-inference.ts b/src/lib/actions/sandbox/doctor-inference.ts index 39e0e06d064..0ac1d58554f 100644 --- a/src/lib/actions/sandbox/doctor-inference.ts +++ b/src/lib/actions/sandbox/doctor-inference.ts @@ -1,6 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeLocalProviderAttachment, + type NativeLocalProviderAttachment, +} from "../../inference/native-local/contract"; +import { + verifyNativeLocalStatusAttachment, + runSandboxInferenceInvocationProbe, +} from "./inference-route-health"; + import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import { hostedNativeProviderForAttachment } from "../../inference/native-provider/hosted-attachment"; import { @@ -38,6 +47,7 @@ export type DoctorInferenceRoute = { /** Sandbox route endpoint recorded at onboard; selects the bearerless local vLLM host port. */ recordedEndpointUrl?: string | null; agentName?: string | null; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; nativeHostedProviderAttachment?: unknown; preferredInferenceApi?: string | null; @@ -93,11 +103,69 @@ type DoctorInferenceDeps = { probeProviderHealthImpl?: typeof probeProviderHealth; probeSandboxInferenceGatewayHealthImpl?: typeof probeSandboxInferenceGatewayHealth; probeSandboxNativeNvidiaModelsHealthImpl?: typeof probeSandboxNativeNvidiaModelsHealth; + verifyNativeLocalStatusAttachmentImpl?: typeof verifyNativeLocalStatusAttachment; + nativeLocalInvocationProbe?: typeof runSandboxInferenceInvocationProbe; verifyNativeNvidiaStatusAttachmentImpl?: typeof verifyNativeNvidiaStatusAttachment; /** False for terminal agents that do not have a long-running gateway serving process. */ includeServingProcessCheck?: boolean; }; +async function collectNativeLocalRouteProbe( + sandboxName: string, + route: DoctorInferenceRoute, + sandboxReachable: boolean, + deps: DoctorInferenceDeps, +): Promise { + const expected = normalizeNativeLocalProviderAttachment(route.nativeLocalProviderAttachment); + const endpoint = expected ? `${expected.endpointUrl}/chat/completions` : ""; + if (!sandboxReachable) { + return { + ok: false, + probed: false, + providerLabel: "Native local inference", + endpoint, + detail: "skipped because the sandbox is not reachable through its named gateway", + }; + } + try { + if (!deps.gatewayName || !expected) + throw new Error("Native local provider ownership or gateway binding is unavailable."); + await (deps.verifyNativeLocalStatusAttachmentImpl ?? verifyNativeLocalStatusAttachment)({ + sandboxName, + gatewayName: deps.gatewayName, + expected, + }); + const result = await (deps.nativeLocalInvocationProbe ?? runSandboxInferenceInvocationProbe)({ + sandboxName, + gatewayName: deps.gatewayName, + provider: route.provider!, + model: route.model!, + preferredInferenceApi: "openai-completions", + nativeLocalProviderAttachment: expected, + agentName: route.agentName, + }); + return { + ok: result.ok, + probed: true, + providerLabel: "Native local inference", + endpoint, + detail: result.ok + ? "The selected model answered through the attached native provider." + : result.detail, + ...(result.ok ? {} : { failureLabel: "unreachable" as const }), + }; + } catch (error) { + return { + ok: false, + probed: false, + providerLabel: "Native local inference", + endpoint, + detail: formatUntrustedProbeDetail(error instanceof Error ? error.message : String(error)), + failureLabel: "unreachable", + }; + } +} + async function collectNativeNvidiaRouteProbe( sandboxName: string, route: DoctorInferenceRoute, @@ -389,23 +457,27 @@ export async function collectInferenceChecks( const effortCheck = reasoningEffortCheck(route); if (effortCheck) checks.push(effortCheck); const nativeNvidia = isNativeNvidiaProvider(route.provider); - const nativeHosted = route.nativeHostedProviderAttachment !== undefined; - const routeProbe = nativeHosted - ? await collectNativeHostedRouteProbe(sandboxName, route, sandboxReachable, deps) - : nativeNvidia - ? await collectNativeNvidiaRouteProbe(sandboxName, route, sandboxReachable, deps) - : await collectInferenceRouteProbe( - sandboxName, - sandboxReachable, - deps.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth, - deps.gatewayName, - ); - pushInferenceHealthCheck(checks, routeProbe, { - label: nativeHosted - ? "Inference route (native hosted)" + const nativeLocal = route.nativeLocalProviderAttachment !== undefined; + const routeProbe = nativeLocal + ? await collectNativeLocalRouteProbe(sandboxName, route, sandboxReachable, deps) + : route.nativeHostedProviderAttachment !== undefined + ? await collectNativeHostedRouteProbe(sandboxName, route, sandboxReachable, deps) : nativeNvidia - ? "Inference route (native NVIDIA)" - : "Inference route (gateway)", + ? await collectNativeNvidiaRouteProbe(sandboxName, route, sandboxReachable, deps) + : await collectInferenceRouteProbe( + sandboxName, + sandboxReachable, + deps.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth, + deps.gatewayName, + ); + pushInferenceHealthCheck(checks, routeProbe, { + label: nativeLocal + ? "Inference route (native local)" + : route.nativeHostedProviderAttachment !== undefined + ? "Inference route (native hosted)" + : nativeNvidia + ? "Inference route (native NVIDIA)" + : "Inference route (gateway)", }); for (const diagnostic of collectProviderHealthDiagnostics( route, diff --git a/src/lib/actions/sandbox/doctor-observation-failure.test.ts b/src/lib/actions/sandbox/doctor-observation-failure.test.ts index d1347f70806..2c9ebf37b8d 100644 --- a/src/lib/actions/sandbox/doctor-observation-failure.test.ts +++ b/src/lib/actions/sandbox/doctor-observation-failure.test.ts @@ -6,6 +6,9 @@ import type { OpenShellSandboxError } from "../../adapters/openshell/sandbox-obs const mocks = vi.hoisted(() => ({ listSandboxes: vi.fn(), + getSandbox: vi.fn(), + captureOpenshell: vi.fn(() => ({ status: 0, output: "" })), + collectInferenceChecks: vi.fn(() => []), })); vi.mock("../../adapters/openshell/sandbox-observer-cli", async (importOriginal) => { @@ -22,7 +25,7 @@ vi.mock("../../adapters/openshell/resolve", () => ({ })); vi.mock("../../adapters/openshell/runtime", () => ({ - captureOpenshell: () => ({ status: 0, output: "" }), + captureOpenshell: mocks.captureOpenshell, })); vi.mock("../../agent/defs", () => ({ @@ -62,14 +65,16 @@ vi.mock("../../onboard/runtime-provider/access", () => ({ })); vi.mock("../../state/registry", () => ({ - getSandbox: () => null, + getSandbox: mocks.getSandbox, + getConfiguredMessagingChannelsFromEntry: () => [], + getDisabledMessagingChannelsFromEntry: () => [], })); vi.mock("./doctor-inference", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - collectInferenceChecks: () => [], + collectInferenceChecks: mocks.collectInferenceChecks, collectManagedLlamaCppDoctorChecks: () => [], resolveDoctorReasoningEffort: () => undefined, }; @@ -101,10 +106,14 @@ vi.mock("./doctor-system-checks", async (importOriginal) => { }); import { runSandboxDoctor } from "./doctor"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; describe("doctor live sandbox observation", () => { beforeEach(() => { mocks.listSandboxes.mockReset(); + mocks.getSandbox.mockReturnValue(null); + mocks.captureOpenshell.mockClear(); + mocks.collectInferenceChecks.mockClear(); }); it.each<{ @@ -154,3 +163,50 @@ describe("doctor live sandbox observation", () => { }, ); }); + +describe("doctor native local selection", () => { + it("passes recorded native access to diagnostics without reading a peer shared route (#12558)", async () => { + const binding = { + provider: "ollama-local" as const, + endpointUrl: "http://host.openshell.internal:11434/v1", + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel" as const, + }; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "local-id", + }; + mocks.getSandbox.mockReturnValue({ + name: "alpha", + agent: "openclaw", + provider: "ollama-local", + model: "local-model", + gatewayName: binding.gatewayName, + nativeLocalProviderAttachment: receipt, + }); + mocks.listSandboxes.mockResolvedValue({ + ok: false, + error: { kind: "transport", reason: "unreachable", message: "sandbox unavailable" }, + }); + await runSandboxDoctor("alpha", ["--json"], { quietJson: true }); + expect(mocks.captureOpenshell).not.toHaveBeenCalledWith( + expect.arrayContaining(["inference", "get"]), + expect.anything(), + ); + expect(mocks.collectInferenceChecks).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + provider: "ollama-local", + model: "local-model", + nativeLocalProviderAttachment: receipt, + }), + false, + expect.anything(), + ); + mocks.getSandbox.mockReturnValue(null); + }); +}); diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index 292319737f0..cfa3c9a7f5f 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -389,9 +389,11 @@ async function resolveInferenceRoute( gatewayName: string | null, ): Promise { const recordedNativeNvidia = isNativeNvidiaProvider(sb?.provider); + const recordedNativeLocal = sb?.nativeLocalProviderAttachment !== undefined; let live: { provider: string; model: string } | null = null; if ( !recordedNativeNvidia && + !recordedNativeLocal && sb?.nativeHostedProviderAttachment === undefined && openshellBin && openshellConnected && @@ -411,6 +413,9 @@ async function resolveInferenceRoute( effectiveReasoningEffort: resolveDoctorReasoningEffort(sb), recordedEndpointUrl: sb?.endpointUrl, agentName: sb?.agent, + ...(recordedNativeLocal + ? { nativeLocalProviderAttachment: sb?.nativeLocalProviderAttachment } + : {}), preferredInferenceApi: sb?.preferredInferenceApi, ...(sb?.nativeHostedProviderAttachment !== undefined ? { nativeHostedProviderAttachment: sb.nativeHostedProviderAttachment } diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 182c9219468..be608c163dd 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -5,6 +5,7 @@ import { SandboxCommandTransportError } from "../../adapters/sandbox/command-tra import { spawnSync } from "node:child_process"; import { getChatCompletionsProbePayload } from "../../inference/openai-probe-models"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; import { existsSync, mkdtempSync, @@ -703,6 +704,69 @@ describe("native inference transport failures", () => { }); }); +it.each(["v42", `s${"a".repeat(64)}`])( + "preserves native local invocation credential identity %s", + (identity) => { + const binding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: input.sandboxName, + } as const; + const reference = `openshell:resolve:env:${identity}_${binding.credentialEnv}`; + const result = runProbeCommandWithBody( + "200", + "{}", + tmpdir(), + { + ...input, + provider: binding.provider, + nativeLocalProviderAttachment: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "owned", + }, + }, + { [binding.credentialEnv]: reference }, + ); + expect(result.argv).toContain(`Authorization: Bearer ${reference}`); + }, +); + +it.each(["", "opaque-host-secret-must-not-leak", "openshell:resolve:env:v42_OTHER_KEY"])( + "rejects invalid native local credential candidate %# before curl", + (reference) => { + const binding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: input.sandboxName, + } as const; + const command = buildSandboxInferenceInvocationCommand({ + ...input, + provider: binding.provider, + nativeLocalProviderAttachment: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "owned", + }, + }); + const result = spawnSync("/bin/sh", ["-c", command], { + env: { PATH: process.env.PATH, [binding.credentialEnv]: reference }, + encoding: "utf8", + timeout: 5000, + }); + expect(result.status).toBe(2); + expect(result.stdout).toBe(""); + }, +); + it.each([ "", "opaque-real-token", diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index c062fdfab04..321b2369fa9 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_LOCAL_AUTH_HEADER_SCRIPT } from "../../inference/native-local/agent-config"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; import { nativeHostedAgentConfig } from "../../inference/native-provider/agent-config"; @@ -15,7 +16,11 @@ import { selectedOpenShellGateway, } from "../../adapters/openshell/sandbox-observer"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; -import { getSandboxInferenceConfig } from "../../inference/config"; +import { + getSandboxInferenceConfig, + normalizeNativeLocalProviderAttachment, + type NativeLocalProviderAttachment, +} from "../../inference/config"; import { isNativeNvidiaProvider, NVIDIA_HOSTED_NATIVE_ENDPOINT, @@ -51,6 +56,7 @@ export type SandboxInferenceInvocationInput = { model: string; preferredInferenceApi: string | null; nativeProvider?: boolean; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeEndpointUrl?: string; }; @@ -85,15 +91,26 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { headers: string[]; payload: Record; } { + const local = normalizeNativeLocalProviderAttachment(input.nativeLocalProviderAttachment); + if ( + input.nativeLocalProviderAttachment && + (!local || + local.sandboxName !== input.sandboxName || + local.provider !== input.provider || + (input.gatewayName && local.gatewayName !== input.gatewayName)) + ) + throw new Error("Native local inference probe authority changed."); const config = getSandboxInferenceConfig( input.model, input.provider, input.preferredInferenceApi, + input.nativeProvider ?? Boolean(local), + local?.endpointUrl ?? null, ); const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); const hosted = hostedNativeProvider(input.provider, input.nativeEndpointUrl); const nativeHosted = input.nativeProvider === true ? hosted : undefined; - if (input.nativeProvider === true && !useNativeNvidia && !nativeHosted) { + if (input.nativeProvider === true && !useNativeNvidia && !nativeHosted && !local) { throw new Error("Unsupported native inference probe selection"); } const baseUrl = ( @@ -107,7 +124,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { ).replace(/\/+$/u, ""); // Gemini's existing OpenAI-compatible API ends in /v1beta/openai, not /v1. const apiBaseUrl = - nativeHosted && config.inferenceApi !== "anthropic-messages" + (local || nativeHosted) && config.inferenceApi !== "anthropic-messages" ? baseUrl : baseUrl.endsWith("/v1") ? baseUrl @@ -177,15 +194,20 @@ export function buildSandboxInferenceInvocationCommand( ): string { const request = buildProbeRequest(input); const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); + const useNativeLocal = Boolean( + normalizeNativeLocalProviderAttachment(input.nativeLocalProviderAttachment), + ); const nativeHosted = input.nativeProvider === true ? hostedNativeProvider(input.provider, input.nativeEndpointUrl) : undefined; const nativeAuth = useNativeNvidia ? NATIVE_NVIDIA_AUTH_HEADER_SCRIPT - : nativeHosted - ? nativeHostedAuthHeaderScript(nativeHosted.logicalProvider) - : undefined; + : useNativeLocal + ? NATIVE_LOCAL_AUTH_HEADER_SCRIPT + : nativeHosted + ? nativeHostedAuthHeaderScript(nativeHosted.logicalProvider) + : undefined; const headerArgs = ["Content-Type: application/json", ...request.headers] .map((header) => `-H ${shellQuote(header)}`) @@ -305,6 +327,9 @@ export async function probeSandboxInferenceInvocation( input.model, input.provider, input.preferredInferenceApi, + input.nativeProvider ?? Boolean(input.nativeLocalProviderAttachment), + normalizeNativeLocalProviderAttachment(input.nativeLocalProviderAttachment)?.endpointUrl ?? + null, ).inferenceApi; if (httpStatus !== null && validateInferenceResponseBody(inferenceApi, body).ok) { return { ok: true }; diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 18f32cbbb1a..91578ce6964 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -1,6 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeLocalProviderAttachment, + type NativeLocalProviderAttachment, +} from "../../inference/native-local/contract"; +import { verifyNativeLocalProviderAttachment } from "../../inference/native-local/profile"; import type { SandboxEntry } from "../../state/registry/types"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; @@ -69,6 +74,23 @@ export async function verifyNativeNvidiaStatusAttachment(input: { }); } +export type VerifyNativeLocalStatusAttachment = (input: { + gatewayName: string; + sandboxName: string; + expected: NativeLocalProviderAttachment; +}) => Promise; + +export const verifyNativeLocalStatusAttachment: VerifyNativeLocalStatusAttachment = async ( + input, +) => { + if (input.expected.gatewayName !== input.gatewayName) + throw new Error("Native local provider gateway authority changed."); + await verifyNativeLocalProviderAttachment({ + adapter: createCliOpenShellProviderAdapter(), + sandboxName: input.sandboxName, + expected: input.expected, + }); +}; export type VerifyNativeHostedStatusAttachment = (input: { gatewayName: string; sandboxName: string; @@ -373,6 +395,7 @@ function buildInvokedRouteHealth( export type SandboxInferenceRouteHealthContext = { provider: string | null; nativeNvidia?: boolean; + nativeLocalEndpoint?: string; nativeProvider?: boolean; nativeEndpointUrl?: string; model?: string | null; @@ -409,6 +432,25 @@ export function buildSandboxInferenceRouteHealth( invocation: SandboxInferenceInvocationResult | null, context: SandboxInferenceRouteHealthContext, ): ProviderHealthStatus { + if (context.nativeLocalEndpoint) { + return { + ok: invocation?.ok === true, + probed: invocation !== null, + providerLabel: "Native local inference", + endpoint: `${context.nativeLocalEndpoint}/chat/completions`, + detail: invocation?.ok + ? "The attached provider served a native local inference request." + : invocation + ? `Native local inference failed: ${invocation.detail}` + : "Native local inference could not be verified inside the sandbox.", + ...(invocation?.ok + ? {} + : { + failureLabel: classifyInferenceInvocationFailureLabel(invocation?.httpStatus ?? null), + }), + subprobes: providerHealthDiagnostics(providerHealth, invocation?.ok === true), + }; + } const definition = fixedNativeProvider(context.provider); if ((context.nativeProvider || context.nativeNvidia) && definition) { const endpoint = @@ -522,15 +564,25 @@ export function readNativeStatusSelection(entry: SandboxEntry | null | undefined let attachment: NativeProviderAttachment | undefined; let failure: string | null = null; try { - attachment = entry ? recordedNativeProviderAttachment(entry) : undefined; + if (entry?.nativeLocalProviderAttachment !== undefined) { + attachment = normalizeNativeLocalProviderAttachment(entry.nativeLocalProviderAttachment); + if (!attachment) + failure = + "Recorded native local provider ownership is invalid; no inference request was sent."; + } else { + attachment = entry ? recordedNativeProviderAttachment(entry) : undefined; + } } catch { failure = "Recorded native provider ownership is invalid; no inference request was sent."; } - const definition = hostedNativeProvider(entry?.provider, attachment?.endpointUrl); + const local = entry?.nativeLocalProviderAttachment !== undefined; + const definition = local ? null : hostedNativeProvider(entry?.provider, attachment?.endpointUrl); return { attachment, failure, - label: definition?.label ?? "NVIDIA", - endpoint: definition?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT, + label: local ? "local" : (definition?.label ?? "NVIDIA"), + endpoint: local + ? (attachment?.endpointUrl ?? "") + : (definition?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT), }; } diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index dfe0e157f1f..72e742d2d61 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -828,7 +828,9 @@ async function captureLaunchIdentity( } const inferenceSelection = normalizeInferenceSelection(entry); const inference = registry.getSandboxEntryInference(entry); - const nativeProvider = Boolean(getNativeProviderAttachment(entry)); + const nativeProvider = + Boolean(getNativeProviderAttachment(entry)) || + entry.nativeLocalProviderAttachment !== undefined; let liveInference: { provider: string; model: string } | null = null; if (!nativeProvider) { const inferenceGetStartedAt = performance.now(); diff --git a/src/lib/actions/sandbox/launch-readiness/health-native-local.test.ts b/src/lib/actions/sandbox/launch-readiness/health-native-local.test.ts new file mode 100644 index 00000000000..ed81416c9f6 --- /dev/null +++ b/src/lib/actions/sandbox/launch-readiness/health-native-local.test.ts @@ -0,0 +1,73 @@ +// 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 { + nativeLocalIdentity, + type NativeLocalBinding, +} from "../../../inference/native-local/contract"; +import { LaunchReadinessEvidenceError, requireNativeInferenceHealth } from "./health"; + +const binding: NativeLocalBinding = { + provider: "vllm-local", + endpointUrl: "http://host.openshell.internal:8000/v1", + gatewayName: "selected", + sandboxName: "alice", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", +}; +const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned", +}; + +describe.each(["openclaw", "langchain-deepagents-code"])( + "%s native-local readiness", + (agentName) => { + function fixture(provider: string) { + return { + sandboxName: "alice", + gatewayName: "selected", + agentName, + entry: { + name: "alice", + provider, + model: "model-a", + nativeLocalProviderAttachment: receipt, + }, + deps: { + verifyNativeLocalAttachment: vi.fn(async () => {}), + inferenceInvocationProbe: vi.fn(async () => ({ ok: true as const })), + }, + }; + } + + it("rejects a receipt for a different selected provider before any probe", async () => { + const input = fixture("llama-cpp-local"); + await expect(requireNativeInferenceHealth(input)).rejects.toBeInstanceOf( + LaunchReadinessEvidenceError, + ); + expect(input.deps.verifyNativeLocalAttachment).not.toHaveBeenCalled(); + expect(input.deps.inferenceInvocationProbe).not.toHaveBeenCalled(); + }); + + it("verifies and invokes the provider selected by the matching receipt", async () => { + const input = fixture("vllm-local"); + await expect(requireNativeInferenceHealth(input)).resolves.toBe(true); + expect(input.deps.verifyNativeLocalAttachment).toHaveBeenCalledExactlyOnceWith({ + sandboxName: "alice", + gatewayName: "selected", + expected: receipt, + }); + expect(input.deps.inferenceInvocationProbe).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + provider: "vllm-local", + model: "model-a", + nativeLocalProviderAttachment: receipt, + }), + ); + }); + }, +); diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index 3ae684f2113..7506026c8dd 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -1,6 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeLocalProviderAttachment } from "../../../inference/native-local/contract"; +import { verifyNativeLocalStatusAttachment } from "../inference-route-health"; + import { captureOpenshell } from "../../../adapters/openshell/runtime"; import { createCliOpenShellProviderAdapter } from "../../../adapters/openshell/provider-adapter-cli"; import type { OpenShellSandboxBufferedCommandExecutor } from "../../../adapters/openshell/sandbox-command"; @@ -81,6 +84,7 @@ export interface LaunchReadinessHealthDeps { gatewayName: string, ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; + verifyNativeLocalAttachment?: typeof verifyNativeLocalStatusAttachment; verifyNativeNvidiaAttachment?: (input: { sandboxName: string; gatewayName: string; @@ -225,6 +229,31 @@ export async function requireNativeInferenceHealth(input: { entry: SandboxEntry; deps: LaunchReadinessHealthDeps; }): Promise { + if (input.entry.nativeLocalProviderAttachment !== undefined) { + const expected = normalizeNativeLocalProviderAttachment( + input.entry.nativeLocalProviderAttachment, + ); + if (!expected || !input.entry.model || input.entry.provider !== expected.provider) + throw new LaunchReadinessEvidenceError(); + await (input.deps.verifyNativeLocalAttachment ?? verifyNativeLocalStatusAttachment)({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + expected, + }); + const result = await ( + input.deps.inferenceInvocationProbe ?? runSandboxInferenceInvocationProbe + )({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + agentName: input.agentName, + provider: expected.provider, + model: input.entry.model, + preferredInferenceApi: "openai-completions", + nativeLocalProviderAttachment: expected, + }); + if (!result.ok) throw new LaunchReadinessObservationError("health", "inference request"); + return true; + } const expected = getNativeProviderAttachment(input.entry); if (!expected) return false; const provider = normalizedString(input.entry.provider); @@ -373,7 +402,7 @@ export async function requireLaunchSemanticHealth( } if (inferenceConfigured) { const inferenceStartedAt = performance.now(); - if (getNativeProviderAttachment(entry)) { + if (getNativeProviderAttachment(entry) || entry.nativeLocalProviderAttachment !== undefined) { try { await requireNativeInferenceHealth({ sandboxName, diff --git a/src/lib/actions/sandbox/rebuild-dcode-target.test.ts b/src/lib/actions/sandbox/rebuild-dcode-target.test.ts index eabcff3625b..2a63ac1d014 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-target.test.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-target.test.ts @@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; + import { resolveDcodeRebuildTarget } from "./rebuild-dcode-target"; describe("resolveDcodeRebuildTarget", () => { @@ -33,3 +35,50 @@ describe("resolveDcodeRebuildTarget", () => { expect(target).not.toHaveProperty("dashboardPort"); }); }); + +describe("DCode native local rebuild authority", () => { + const binding = { + provider: "vllm-local", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "alpha", + } as const; + const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "owned", + }; + const entry = { + name: "alpha", + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw", + gatewayPort: 8080, + }; + const config = { provider: binding.provider, model: "model", preferredInferenceApi: null }; + it.each([null, {}, { ...attachment, providerId: "" }, { ...attachment, schemaVersion: 2 }])( + "rejects malformed local authority before selecting a target (%j)", + (receipt) => { + expect(() => + resolveDcodeRebuildTarget( + { ...entry, nativeLocalProviderAttachment: receipt }, + config, + 8080, + ), + ).toThrow("Malformed native local provider attachment"); + }, + ); + it.each([attachment, undefined])( + "preserves valid native local or absent legacy authority (%j)", + (receipt) => { + const result = resolveDcodeRebuildTarget( + { ...entry, nativeLocalProviderAttachment: receipt }, + config, + 8080, + ); + expect(result.nativeLocalProviderAttachment).toEqual(receipt); + }, + ); +}); diff --git a/src/lib/actions/sandbox/rebuild-dcode-target.ts b/src/lib/actions/sandbox/rebuild-dcode-target.ts index 1b5bca8ddcd..74e41f807af 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-target.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-target.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeLocalProviderAttachment, + type NativeLocalProviderAttachment, +} from "../../inference/native-local/contract"; import { GATEWAY_PORT } from "../../core/ports"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import { @@ -15,6 +19,7 @@ export type DcodeRebuildRegistryEntry = SandboxGatewayBinding & { agent?: string | null; dashboardPort?: number | null; nativeNvidiaProviderAttachment?: unknown; + nativeLocalProviderAttachment?: unknown; nativeHostedProviderAttachment?: unknown; }; @@ -26,6 +31,7 @@ export type DcodeRebuildResumeConfig = { }; export type ResolvedDcodeRebuildTarget = { + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeProvider?: boolean; nativeEndpointUrl?: string; agent: typeof DCODE_AGENT_NAME; @@ -66,6 +72,12 @@ export function resolveDcodeRebuildTarget( `Re-run with NEMOCLAW_GATEWAY_PORT=${gatewayPort}.`, ); } + const nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( + entry.nativeLocalProviderAttachment, + ); + if (entry.nativeLocalProviderAttachment !== undefined && !nativeLocalProviderAttachment) { + throw new Error("Malformed native local provider attachment; sandbox is untouched"); + } const nativeAttachment = recordedNativeProviderAttachment({ ...entry, provider: resumeConfig.provider, @@ -77,6 +89,7 @@ export function resolveDcodeRebuildTarget( provider: requiredString(resumeConfig.provider, "inference provider"), model: requiredString(resumeConfig.model, "inference model"), preferredInferenceApi: resumeConfig.preferredInferenceApi, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeAttachment ? { nativeProvider: true, @@ -85,5 +98,8 @@ export function resolveDcodeRebuildTarget( : {}), } : {}), + ...(nativeLocalProviderAttachment + ? { nativeProvider: true, nativeEndpointUrl: nativeLocalProviderAttachment.endpointUrl } + : {}), }; } 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..892829ced0d 100644 --- a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts @@ -15,6 +15,8 @@ import { nativeProviderRebuildScenario, } from "./rebuild-flow-test-fixtures"; +import { nativeLocalRebuildAttachment } from "../../../../test/helpers/rebuild-flow-test-support"; + type Harness = ReturnType; const MODEL = "test/model"; @@ -653,7 +655,12 @@ describe("rebuildSandbox flow: credential preflight", () => { it("skips credential hydration for local inference", async () => { const harness = createRebuildFlowHarness({ - sandboxEntry: { provider: "ollama-local", model: MODEL, credentialEnv: null }, + sandboxEntry: { + provider: "ollama-local", + model: MODEL, + credentialEnv: null, + nativeLocalProviderAttachment: nativeLocalRebuildAttachment("ollama-local"), + }, hydrateCredentialEnv: () => { throw new Error("local inference must not hydrate a credential"); }, @@ -668,11 +675,16 @@ describe("rebuildSandbox flow: credential preflight", () => { expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); }); - it.each(["ollama-local", "vllm-local"])( - "migrates a legacy %s target away from OPENAI_API_KEY (#2519)", + it.each(["ollama-local", "vllm-local"] as const)( + "migrates an attached %s target away from legacy OPENAI_API_KEY (#2519)", async (provider) => { const harness = createRebuildFlowHarness({ - sandboxEntry: { provider, model: MODEL, credentialEnv: "OPENAI_API_KEY" }, + sandboxEntry: { + provider, + model: MODEL, + credentialEnv: "OPENAI_API_KEY", + nativeLocalProviderAttachment: nativeLocalRebuildAttachment(provider), + }, }); configureSession(harness, provider, "OPENAI_API_KEY"); diff --git a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts index 298aa0f5116..101c9fa9fcd 100644 --- a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts @@ -212,6 +212,26 @@ describe("rebuildSandbox flow: lifecycle", () => { expectNoSandboxDelete(harness.runOpenshellSpy); }); + it("stops a legacy local route before rebuild effects (#12975)", async () => { + const harness = createRebuildFlowHarness({ + sandboxEntry: { + createdAt: "2026-09-01T00:00:00Z", + agent: "openclaw", + provider: "ollama-local", + model: "local-model", + }, + }); + + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).rejects.toThrow("Legacy shared local inference cannot be rebuilt safely"); + expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); + expect(harness.onboardSpy).not.toHaveBeenCalled(); + expect(harness.registryUpdateSpy).not.toHaveBeenCalled(); + expect(harness.removeSandboxRegistryEntryWithReceiptSpy).not.toHaveBeenCalled(); + expectNoSandboxDelete(harness.runOpenshellSpy); + }); + it("blocks an unsafe removed-immutability record before rebuild effects", async () => { const stateDir = createHarnessTempDir("nemoclaw-rebuild-unsafe-retired-state-"); fs.mkdirSync(path.join(stateDir, "shields-alpha.json")); @@ -405,7 +425,7 @@ describe("rebuildSandbox flow: lifecycle", () => { expect(harness.registryUpdateSpy).toHaveBeenCalledWith( "alpha", expect.objectContaining({ - provider: "ollama-local", + provider: "nvidia-router", model: "nvidia/nemotron", webSearchEnabled: false, fromDockerfile: null, diff --git a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts index 41d0629a774..7cc0c6f5ae2 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts @@ -12,6 +12,7 @@ import { installRebuildFlowTestHooks, snapshotEnv, } from "../../../../test/helpers/rebuild-flow-generic-harness"; +import { nativeLocalRebuildAttachment } from "../../../../test/helpers/rebuild-flow-test-support"; describe("rebuildSandbox flow: target credentials", () => { installRebuildFlowTestHooks(); @@ -168,7 +169,13 @@ describe("rebuildSandbox flow: target credentials", () => { }); it("ignores a stale matching-session credential for a resolved local target", async () => { - const harness = createRebuildFlowHarness(); + const harness = createRebuildFlowHarness({ + sandboxEntry: { + provider: "ollama-local", + nativeLocalProviderAttachment: nativeLocalRebuildAttachment("ollama-local"), + }, + }); + harness.session.provider = "ollama-local"; harness.session.credentialEnv = "NVIDIA_INFERENCE_API_KEY"; await expect( 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..067dfe2c2ea 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-session.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-session.test.ts @@ -9,6 +9,7 @@ import { snapshotEnv, } from "../../../../test/helpers/rebuild-flow-generic-harness"; import type { ServingProfileProvenance } from "../../inference/serving/profile-provenance"; +import { nativeLocalRebuildAttachment } from "../../../../test/helpers/rebuild-flow-test-support"; const savedProfileProvenance: ServingProfileProvenance = { schemaVersion: 1, @@ -41,6 +42,7 @@ describe("rebuildSandbox flow: target session", () => { sessionSandboxName, sandboxEntry: { provider: "vllm-local", + nativeLocalProviderAttachment: nativeLocalRebuildAttachment("vllm-local"), model: "example/model", servingProfileProvenance: savedProfileProvenance, }, @@ -70,6 +72,7 @@ describe("rebuildSandbox flow: target session", () => { sessionSandboxName, sandboxEntry: { provider: "vllm-local", + nativeLocalProviderAttachment: nativeLocalRebuildAttachment("vllm-local"), model: "example/model", servingProfileProvenance: undefined, }, @@ -150,6 +153,7 @@ describe("rebuildSandbox flow: target session", () => { applyPreset: () => true, sandboxEntry: { provider: "vllm-local", + nativeLocalProviderAttachment: nativeLocalRebuildAttachment("vllm-local"), model: "nvidia/Qwen3.6-35B-A3B-NVFP4", endpointUrl: null, endpointSource: null, diff --git a/src/lib/actions/sandbox/rebuild-legacy-local-route-preflight.test.ts b/src/lib/actions/sandbox/rebuild-legacy-local-route-preflight.test.ts new file mode 100644 index 00000000000..cdea5dfb6b3 --- /dev/null +++ b/src/lib/actions/sandbox/rebuild-legacy-local-route-preflight.test.ts @@ -0,0 +1,80 @@ +// 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 { parseSandboxRegistryEntries } from "../../state/registry-normalization"; +import type { RebuildSandboxEntry } from "./rebuild-flow-helpers"; +import { blockRebuildOnLegacySharedLocalRoute } from "./rebuild-preflight-phase"; + +describe("rebuild legacy local route preflight", () => { + it.each([ + { agent: "openclaw", provider: "ollama-local", recordedAt: "2026-09-01T00:00:00Z" }, + { agent: "openclaw", provider: "ollama-local", recordedAt: undefined }, + { agent: "openclaw", provider: "vllm-local", recordedAt: "2026-09-01T00:00:00Z" }, + { + agent: "langchain-deepagents-code", + provider: "ollama-local", + recordedAt: "2026-09-01T00:00:00Z", + }, + { agent: "langchain-deepagents-code", provider: "ollama-local", recordedAt: undefined }, + ])( + "warns before rebuilding an existing $agent $provider sandbox", + ({ agent, provider, recordedAt }) => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const bail = vi.fn((message: string): never => { + throw new Error(message); + }); + const entry = { + name: "alpha", + ...(recordedAt ? { createdAt: recordedAt } : {}), + agent, + provider, + model: "local-model", + } as RebuildSandboxEntry; + + const [, persisted] = parseSandboxRegistryEntries( + JSON.parse(JSON.stringify({ alpha: entry })), + )[0]!; + expect(() => blockRebuildOnLegacySharedLocalRoute("alpha", persisted, bail)).toThrow( + "Legacy shared local inference cannot be rebuilt safely", + ); + expect(error.mock.calls.flat().join("\n")).toContain("Back up the sandbox"); + expect(bail).toHaveBeenCalledOnce(); + }, + ); + + it("leaves attached and unpublished selections on their existing preflight path", () => { + const bail = vi.fn((message: string): never => { + throw new Error(message); + }); + const entry = { + name: "alpha", + createdAt: "2026-09-01T00:00:00Z", + agent: "openclaw", + provider: "ollama-local", + model: "local-model", + nativeLocalProviderAttachment: {}, + } as RebuildSandboxEntry; + expect(blockRebuildOnLegacySharedLocalRoute("alpha", entry, bail)).toBe(false); + expect( + blockRebuildOnLegacySharedLocalRoute( + "alpha", + { + ...entry, + createdAt: undefined, + pendingRouteReservation: true, + nativeLocalProviderAttachment: undefined, + }, + bail, + ), + ).toBe(false); + expect( + blockRebuildOnLegacySharedLocalRoute( + "alpha", + { ...entry, pendingRouteReservation: true, nativeLocalProviderAttachment: undefined }, + bail, + ), + ).toBe(false); + expect(bail).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts b/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts deleted file mode 100644 index db204bcaa4e..00000000000 --- a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { createRequire } from "node:module"; - -import { describe, expect, it, vi } from "vitest"; -import { - createRebuildFlowHarness, - installRebuildFlowTestHooks, - type RebuildFlowHarness, -} from "../../../../test/helpers/rebuild-flow-generic-harness"; -import { - setupOllamaLocalInference, - setupVllmLocalInference, -} from "../../onboard/inference-providers"; -import { createLocalInferenceRouteApplier } from "../../onboard/local-inference-route"; - -const requireDist = createRequire(import.meta.url); -const openshellRuntime = requireDist("../../adapters/openshell/runtime.js") as { - captureOpenshell( - args: string[], - options?: Record, - ): { status: number | null; output?: string; stdout?: string; stderr?: string }; - runOpenshell( - args: string[], - options?: Record, - ): { status: number | null; stdout?: string; stderr?: string }; -}; -const onboardProviders = requireDist("../../onboard/providers.js") as { - upsertProvider( - name: string, - type: string, - credentialEnv: string, - baseUrl: string | null, - env: NodeJS.ProcessEnv, - runOpenshell: typeof openshellRuntime.runOpenshell, - ): Promise<{ ok: boolean; status?: number; message?: string }>; -}; - -type SetupResult = { done: true; result: unknown } | { done: false }; - -async function upsertLocalProvider( - name: string, - type: string, - credentialEnv: string, - baseUrl: string | null, - env: NodeJS.ProcessEnv = {}, -) { - return await onboardProviders.upsertProvider( - name, - type, - credentialEnv, - baseUrl, - env, - openshellRuntime.runOpenshell, - ); -} - -const unusedCommonInferenceDeps = { - runOpenshell: openshellRuntime.runOpenshell, - verifyInferenceRoute: vi.fn(), - verifyOnboardInferenceSmoke: vi.fn(), - isNonInteractive: () => true, - registry: { updateSandbox: vi.fn() }, - error: vi.fn(), - log: vi.fn(), - exitProcess: (code: number): never => { - throw new Error(`EXIT_CALLED:${code}`); - }, -}; - -const localProviderScenarios = [ - { - provider: "ollama-local", - model: "qwen3.5:9b", - baseUrl: "http://host.openshell.internal:11435/v1", - credentialEnv: "NEMOCLAW_OLLAMA_PROXY_TOKEN", - setup: (applyLocalInferenceRoute: (provider: string, model: string) => Promise) => - setupOllamaLocalInference( - { model: "qwen3.5:9b", provider: "ollama-local", allowToolsIncompatible: false }, - { - upsertProvider: upsertLocalProvider, - validateLocalProvider: () => ({ ok: true }), - getLocalProviderBaseUrl: () => "http://host.openshell.internal:11435/v1", - applyLocalInferenceRoute, - run: () => ({ status: 0 }), - shouldFrontOllamaWithProxy: () => false, - ensureOllamaAuthProxy: vi.fn(), - isProxyHealthy: () => true, - getOllamaProxyToken: () => "unused-proxy-token", - persistAndProbeOllamaProxy: async () => undefined, - localInference: { - validateOllamaModelWithToolsOverride: () => ({ ok: true }), - validateSandboxFacingOllamaModel: () => ({ ok: true }), - runOllamaWarmup: () => {}, - persistResolvedOllamaHost: () => () => {}, - }, - OLLAMA_PROXY_CREDENTIAL_ENV: "NEMOCLAW_OLLAMA_PROXY_TOKEN", - ...unusedCommonInferenceDeps, - }, - ), - }, - { - provider: "vllm-local", - model: "meta-llama/Llama-3.1-8B-Instruct", - baseUrl: "http://host.openshell.internal:8000/v1", - credentialEnv: "NEMOCLAW_VLLM_LOCAL_TOKEN", - setup: (applyLocalInferenceRoute: (provider: string, model: string) => Promise) => - setupVllmLocalInference( - { model: "meta-llama/Llama-3.1-8B-Instruct", provider: "vllm-local" }, - { - upsertProvider: upsertLocalProvider, - validateLocalProvider: () => ({ ok: true }), - getLocalProviderHealthCheck: () => ["true"], - getLocalProviderBaseUrl: () => "http://host.openshell.internal:8000/v1", - applyLocalInferenceRoute, - run: () => ({ status: 0 }), - VLLM_LOCAL_CREDENTIAL_ENV: "NEMOCLAW_VLLM_LOCAL_TOKEN", - getManagedVllmProviderBinding: () => null, - ...unusedCommonInferenceDeps, - }, - ), - }, -] as const; - -function makeRouteApplier() { - const setInferenceRoute = vi.fn(async () => ({ ok: true as const })); - return { - applyLocalInferenceRoute: createLocalInferenceRouteApplier({ - gatewayName: "nemoclaw", - inferenceRouteMutator: { setInferenceRoute }, - isNonInteractive: () => true, - promptValidationRecovery: async () => "selection", - classifyApplyFailure: () => ({ kind: "unknown" }) as never, - localInferenceTimeoutSecs: 30, - error: unusedCommonInferenceDeps.error, - exitProcess: unusedCommonInferenceDeps.exitProcess, - }), - setInferenceRoute, - }; -} - -installRebuildFlowTestHooks({ acceptThirdPartySoftware: true }); - -describe("rebuild local-provider recreation", () => { - it.each(localProviderScenarios)( - "recreates a missing $provider gateway provider through the resumed local setup path", - async ({ provider, model, baseUrl, credentialEnv, setup }) => { - let sourceDeleted = false; - let harness!: RebuildFlowHarness; - let setupResult: SetupResult | undefined; - const routeApplier = makeRouteApplier(); - harness = createRebuildFlowHarness({ - sandboxEntry: { provider, model, credentialEnv: null }, - onboard: async (session) => { - const callsBeforeSetup = harness.runOpenshellSpy.mock.calls.map( - (call) => call[0] as string[], - ); - expect(callsBeforeSetup).not.toContainEqual(["provider", "get", provider]); - expect(session.provider).toBe(provider); - expect(session.model).toBe(model); - expect(session.steps.provider_selection.status).toBe("pending"); - expect(session.steps.inference.status).toBe("pending"); - - setupResult = await setup(routeApplier.applyLocalInferenceRoute); - }, - }); - harness.session.provider = provider; - harness.session.model = model; - harness.runOpenshellSpy.mockImplementation((args: string[]) => { - sourceDeleted ||= args.join(" ") === "sandbox delete -g nemoclaw alpha"; - return args[0] === "sandbox" && args[1] === "get" - ? { - status: 1, - stdout: "", - stderr: "sandbox alpha not found", - } - : { - status: args[0] === "provider" && args[1] === "get" ? 1 : 0, - stdout: "", - stderr: - args[0] === "provider" && args[1] === "get" - ? `provider '${provider}' not found` - : "", - }; - }); - const liveSource = "Name: alpha\nId: sbx-alpha-source\nPhase: Ready\n"; - harness.captureOpenshellSpy.mockImplementation((args: unknown) => { - const argv = Array.isArray(args) ? args.map(String) : []; - return argv.join(" ") === "sandbox get -g nemoclaw alpha" && !sourceDeleted - ? { status: 0, output: liveSource, stdout: liveSource, stderr: "" } - : { status: 1, output: "", stdout: "", stderr: "Error: sandbox alpha not found" }; - }); - - await expect( - harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); - - const calls = harness.runOpenshellSpy.mock.calls.map((call) => call[0] as string[]); - const deleteCall = calls.findIndex( - (args) => args.join(" ") === "sandbox delete -g nemoclaw alpha", - ); - const providerLookup = calls.findIndex( - (args) => args[0] === "provider" && args[1] === "get" && args[2] === provider, - ); - expect(setupResult).toEqual({ done: false }); - expect(harness.onboardSpy).toHaveBeenCalledWith( - expect.objectContaining({ resume: true, nonInteractive: true, recreateSandbox: true }), - ); - expect(deleteCall).toBeGreaterThanOrEqual(0); - expect(providerLookup).toBeGreaterThan(deleteCall); - expect(calls).toContainEqual(["provider", "get", provider]); - expect(calls).toContainEqual([ - "provider", - "create", - "--name", - provider, - "--type", - "openai", - "--credential", - credentialEnv, - "--config", - `OPENAI_BASE_URL=${baseUrl}`, - ]); - expect(routeApplier.setInferenceRoute).toHaveBeenCalledOnce(); - expect(routeApplier.setInferenceRoute).toHaveBeenCalledWith({ - target: { kind: "named", gatewayName: "nemoclaw" }, - route: { provider, model }, - verification: "skip", - verificationTimeoutSeconds: 30, - }); - expect(calls.some((args) => args[0] === "provider" && args[1] === "update")).toBe(false); - expect(harness.restoreSandboxStateSpy).toHaveBeenCalledWith("alpha", harness.backupPath, { - targetAgentType: "openclaw", - }); - }, - ); -}); diff --git a/src/lib/actions/sandbox/rebuild-preflight-phase.ts b/src/lib/actions/sandbox/rebuild-preflight-phase.ts index b5e9e6c62ad..cb2df52d58a 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-phase.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-phase.ts @@ -4,6 +4,7 @@ import path from "node:path"; import type { RebuildSandboxOptions } from "../../domain/lifecycle/options"; +import { hasLegacySharedLocalInferenceRoute } from "../../inference/selection"; import type { SandboxMessagingPlan } from "../../messaging"; import { hydrateCredentialEnv } from "../../onboard/credential-env"; import { DCODE_AUTO_APPROVAL_FEATURE } from "../../onboard/dcode-auto-approval"; @@ -132,6 +133,26 @@ export function runHermesCronRestoreBackupPreflight({ } } +/** Stop before backup or deletion when an old local route cannot be recreated. */ +export function blockRebuildOnLegacySharedLocalRoute( + sandboxName: string, + sandboxEntry: RebuildSandboxEntry, + bail: RebuildBail, +): boolean { + if ( + sandboxEntry.pendingRouteReservation === true || + !hasLegacySharedLocalInferenceRoute(sandboxEntry) + ) + return false; + printRebuildPreflightFailure( + `sandbox '${sandboxName}' uses a legacy shared local inference route without a native provider attachment.`, + "Back up the sandbox, then re-onboard it with --fresh --name --recreate-sandbox before upgrading OpenShell.", + "Legacy shared local inference cannot be rebuilt safely", + bail, + ); + return true; +} + /** * Validate and pin the complete recreate contract while the old sandbox remains * intact. The returned onboard lock stays held across every destructive phase. @@ -154,6 +175,7 @@ export async function runRebuildPreflightPhase( } = createRebuildCommandContext(options, opts); const sandboxEntry = getRebuildSandboxEntryOrBail(sandboxName, bail); if (!sandboxEntry) return null; + if (blockRebuildOnLegacySharedLocalRoute(sandboxName, sandboxEntry, bail)) return null; if (blockRebuildOnRetainedSandboxRecovery(sandboxEntry, bail)) return null; restoreRecordedRebuildGatewayStateDir(sandboxEntry); const confirmedEntrySnapshot = JSON.stringify(sandboxEntry); diff --git a/src/lib/actions/sandbox/rebuild-resume-config.test.ts b/src/lib/actions/sandbox/rebuild-resume-config.test.ts index d616dbeb5ab..8abb3d650cc 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.test.ts @@ -6,6 +6,7 @@ import { hostedNativeProvider, } from "../../inference/native-provider/hosted"; import { createRequire } from "node:module"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -929,6 +930,61 @@ describe("persisted native NVIDIA rebuild authority", () => { ); }); +describe("persisted native local rebuild authority", () => { + const binding = { + provider: "vllm-local", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "alpha", + } as const; + const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "owned", + }; + it.each([null, {}, { ...attachment, providerId: "" }, { ...attachment, schemaVersion: 2 }])( + "rejects malformed local authority before returning a rebuild plan (%j)", + (receipt) => { + vi.spyOn(onboardSession, "loadSession").mockReturnValue(null); + expect(() => + prepareRebuildResumeConfig( + "alpha", + entry({ + provider: binding.provider, + model: "model", + nativeLocalProviderAttachment: receipt, + }), + "langchain-deepagents-code", + noopLog, + throwingBail, + ), + ).toThrow("Malformed native local provider attachment"); + }, + ); + it.each([attachment, undefined])( + "preserves valid native local or absent legacy authority (%j)", + (receipt) => { + vi.spyOn(onboardSession, "loadSession").mockReturnValue(null); + const result = prepareRebuildResumeConfig( + "alpha", + entry({ + provider: binding.provider, + model: "model", + nativeLocalProviderAttachment: receipt, + }), + "langchain-deepagents-code", + noopLog, + throwingBail, + ); + expect(result).not.toBeNull(); + expect(result.nativeLocalProviderAttachment).toEqual(receipt); + }, + ); +}); + describe("fixed hosted rebuild authority", () => { it.each([ ...HOSTED_NATIVE_PROVIDERS, diff --git a/src/lib/actions/sandbox/rebuild-resume-config.ts b/src/lib/actions/sandbox/rebuild-resume-config.ts index 97a78f4f0e8..56a59458aa5 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.ts @@ -9,6 +9,10 @@ // env or global session. Extracted from rebuild.ts so the trust-boundary logic // is auditable on its own (PRA-5). +import { + normalizeNativeLocalProviderAttachment, + type NativeLocalProviderAttachment, +} from "../../inference/native-local/contract"; import { CLI_NAME } from "../../cli/branding"; import { RD as _RD, D, R } from "../../cli/terminal-style"; import { @@ -67,6 +71,7 @@ export interface RebuildResumeConfig { */ readonly pinEndpoint: boolean; readonly endpointUrl: string | null; + readonly nativeLocalProviderAttachment?: NativeLocalProviderAttachment; /** Durable pre-delete route used only for credential-safe provider recovery. */ readonly registryInferenceRoute: RegistryInferenceRoute | null; readonly ambient: AmbientRecreateEnvAssessment; @@ -270,6 +275,13 @@ export function prepareRebuildResumeConfig( } endpointUrl = expectedEndpoint; } + const nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( + sb.nativeLocalProviderAttachment, + ); + if (sb.nativeLocalProviderAttachment !== undefined && !nativeLocalProviderAttachment) { + bail("Malformed native local provider attachment; sandbox is untouched"); + return null; + } const credentialEnv = hostedDefinition?.credentialEnv ?? getRebuildCredentialEnvFromRegistry( @@ -295,6 +307,7 @@ export function prepareRebuildResumeConfig( pinEndpoint: rebuildEndpoint.known || explicitTargetEndpoint !== null, endpointUrl, registryInferenceRoute, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ambient, }; } diff --git a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts index becff08e5b1..139ee654c22 100644 --- a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts @@ -9,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } fr import * as gatewayDrift from "../../adapters/openshell/gateway-drift"; import * as resolve from "../../adapters/openshell/resolve"; +import * as providerCommand from "../../adapters/openshell/provider-command"; import * as openshellRuntime from "../../adapters/openshell/runtime"; import * as agentDefs from "../../agent/defs"; import * as agentRuntime from "../../agent/runtime"; @@ -110,7 +111,7 @@ describe("rebuild resume snapshot repair", () => { session = onboardSession.createSession({ sandboxName: "alpha", - provider: "ollama-local", + provider: "nvidia-router", model: "nvidia/nemotron", lastCompletedStep: "gateway", status: "complete", @@ -216,7 +217,7 @@ describe("rebuild resume snapshot repair", () => { vi.spyOn(onboardSession, "markStepFailed").mockImplementation(() => loadSession()), vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha", - provider: "ollama-local", + provider: "nvidia-router", model: "nvidia/nemotron", agent: null, nimContainer: null, @@ -225,6 +226,24 @@ describe("rebuild resume snapshot repair", () => { gatewayName: "nemoclaw", gatewayPort: 8080, } as never), + vi.spyOn(providerCommand, "runOpenshellProviderCommand").mockImplementation((args) => { + const output = + "Name: nvidia-router\nType: openai\nCredential keys: \nConfig keys: OPENAI_BASE_URL\n"; + const responses = new Map([ + ["provider get nvidia-router", { status: 0, stdout: output, stderr: "" }], + ]); + const response = responses.get(args.slice(0, 3).join(" ")) ?? { + status: 1, + stdout: "", + stderr: "provider not found", + }; + return { + ...response, + pid: 0, + signal: null, + output: [null, response.stdout, response.stderr], + }; + }), vi.spyOn(registry, "updateSandbox").mockReturnValue(true), vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: [] } as never), vi.spyOn(mcpBridgeProvider, "getMcpProviderInspectionRuntimeSelection").mockReturnValue({ @@ -237,7 +256,7 @@ describe("rebuild resume snapshot repair", () => { sandboxName: "alpha", gatewayName: "nemoclaw", route: { - provider: "ollama-local", + provider: "nvidia-router", model: "nvidia/nemotron", endpointUrl: null, preferredInferenceApi: null, diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index ca80987eefd..4a48cee5509 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -18,6 +18,8 @@ import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import * as crossPortRegistryEsm from "../../state/registry/cross-port"; import { type SandboxStartDeps, startSandbox } from "./start"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; +import { buildSandboxInferenceInvocationCommand } from "./inference-invocation-probe"; import { resolveSandboxInferenceInvocationEndpoint } from "./inference-invocation-probe"; import { HOSTED_NATIVE_PROVIDERS, @@ -330,6 +332,53 @@ describe("startSandbox native lifecycle", () => { await expect(startSandbox("my-sandbox", h.deps)).rejects.toThrow("native gateway unavailable"); }); + it.each(["openclaw", "hermes", "langchain-deepagents-code"])( + "checks the recorded native local endpoint after %s restarts (#12558)", + async (agent) => { + const binding = { + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw-19080", + sandboxName: "my-sandbox", + } as const; + const nativeLocalProviderAttachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-local-provider", + }; + const commands: string[] = []; + const probeInferenceInvocation = vi.fn< + NonNullable + >(async (input) => { + commands.push(buildSandboxInferenceInvocationCommand(input)); + return { ok: true }; + }); + const h = harness({ probeInferenceInvocation }); + h.getSandbox.mockReturnValue( + sandbox({ + agent, + stopped: true, + gatewayName: binding.gatewayName, + provider: binding.provider, + model: "local-model", + preferredInferenceApi: "openai-completions", + nativeLocalProviderAttachment, + }), + ); + await expect(startSandbox("my-sandbox", h.deps)).resolves.toEqual({ exitCode: 0 }); + expect(commands).toHaveLength(1); + expect(commands[0]).toContain(`${binding.endpointUrl}/chat/completions`); + expect(commands[0]).not.toContain("openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN"); + expect(commands[0]).toContain( + 'AUTH_HEADER="Authorization: Bearer ${NEMOCLAW_LOCAL_INFERENCE_TOKEN}"', + ); + expect(commands[0]).not.toContain("inference.local"); + }, + ); + it("pins the inference probe to the registered gateway after health", async () => { const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); const h = harness({ probeInferenceInvocation }); diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index ea4eb8becac..b6d9ee863a1 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -178,6 +178,9 @@ async function checkStartedSandboxInference( provider, model, preferredInferenceApi: sandbox.preferredInferenceApi ?? null, + ...(sandbox.nativeLocalProviderAttachment + ? { nativeLocalProviderAttachment: sandbox.nativeLocalProviderAttachment } + : {}), ...(nativeProvider ? { nativeProvider: true } : {}), ...(nativeEndpointUrl ? { nativeEndpointUrl } : {}), }; diff --git a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts index 96e20c3891d..01b935ad25a 100644 --- a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; import type { ProviderHealthStatus } from "../../inference/health"; import type { SandboxEntry } from "../../state/registry"; import type { SandboxInferenceInvocationResult } from "./inference-invocation-probe"; @@ -50,6 +51,112 @@ function snapshotDeps( } describe("collectSandboxStatusSnapshot inference route health", () => { + it.each([true, false])( + "reports native local attachment health without querying the shared route: %s (#12558)", + async (attached) => { + const binding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "alpha", + } as const; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-local-provider", + }; + const options = snapshotDeps( + null, + null, + { ok: true }, + { + provider: binding.provider, + gatewayName: binding.gatewayName, + nativeLocalProviderAttachment: receipt, + }, + ); + const observeInferenceRoute = vi.fn(); + const verifyNativeLocalProviderAttachmentImpl = vi.fn(); + verifyNativeLocalProviderAttachmentImpl.mockImplementation( + attached + ? async () => undefined + : async () => { + throw new Error("attachment missing"); + }, + ); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: true as const })); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + ...options, + deps: { + ...options.deps, + inferenceRouteObserver: { observeInferenceRoute }, + verifyNativeLocalProviderAttachmentImpl, + probeSandboxInferenceInvocationImpl, + }, + }); + expect(snapshot.inferenceHealth).toMatchObject({ + ok: attached, + endpoint: expect.stringContaining(binding.endpointUrl), + }); + expect(observeInferenceRoute).not.toHaveBeenCalled(); + expect(verifyNativeLocalProviderAttachmentImpl).toHaveBeenCalledWith({ + sandboxName: "alpha", + gatewayName: "nemoclaw", + expected: receipt, + }); + expect(probeSandboxInferenceInvocationImpl).toHaveBeenCalledTimes(Number(attached)); + }, + ); + + it("reports bounded redacted native local verification details and recovery (#12558)", async () => { + const binding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "alpha", + } as const; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-local-provider", + }; + const secret = `nvapi-${"a".repeat(40)}`; + const options = snapshotDeps( + null, + null, + { ok: true }, + { + provider: binding.provider, + gatewayName: binding.gatewayName, + nativeLocalProviderAttachment: receipt, + }, + ); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + ...options, + deps: { + ...options.deps, + verifyNativeLocalProviderAttachmentImpl: async () => { + throw new Error( + `profile changed\nAuthorization: Bearer ${secret} ${"detail ".repeat(100)}`, + ); + }, + }, + }); + expect(snapshot.inferenceHealth).toMatchObject({ ok: false, probed: false }); + expect(snapshot.inferenceHealth?.detail).toContain("profile changed"); + expect(snapshot.inferenceHealth?.detail).toContain(receipt.providerName); + expect(snapshot.inferenceHealth?.detail).toContain("Recreate"); + expect(snapshot.inferenceHealth?.detail).not.toContain(secret); + expect(snapshot.inferenceHealth?.detail).not.toMatch(/[\u0000-\u001f\u007f]/u); + expect(snapshot.inferenceHealth?.detail?.length).toBeLessThan(600); + }); + it("restores the guarded agent and host-forward chain before probing a Docker-recovered sandbox", async () => { const order: string[] = []; const gateway: SandboxInferenceRouteHealth = { diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index 1e0f1d85cb6..e8988655971 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -709,7 +709,7 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = probed: false, providerLabel: "Native NVIDIA provider attachment", detail: expect.stringContaining( - "Native NVIDIA provider attachment is unavailable for sandbox 'alpha'", + "Sandbox 'alpha' does not have its native NVIDIA inference provider attached.", ), }); expect(snapshot.inferenceHealth?.detail).toContain( diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 48e8001ddb1..95197f7cd5a 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -20,6 +20,7 @@ import { withStdoutRedirectedToStderr } from "../../cli/stdout-guard"; import { getLlamaCppRouteDetails, normalizeNativeNvidiaProviderAttachment, + normalizeNativeLocalProviderAttachment, type GatewayInference, type LlamaCppRouteDetails, planInferenceRouteReconcile, @@ -60,7 +61,9 @@ import { probeSandboxInferenceGatewayHealth, runSandboxInferenceInvocationProbe, verifyNativeNvidiaStatusAttachment, + verifyNativeLocalStatusAttachment, verifyNativeHostedStatusAttachment, + type VerifyNativeLocalStatusAttachment, type VerifyNativeHostedStatusAttachment, type VerifyNativeNvidiaStatusAttachment, } from "./inference-route-health"; @@ -336,6 +339,7 @@ interface CollectSandboxStatusSnapshotDeps { getGatewayPresets?: GetGatewayPresets; inspectManagedLlamaCppOwnership?: typeof inspectManagedLlamaCppOwnership; verifyNativeNvidiaProviderAttachmentImpl?: VerifyNativeNvidiaStatusAttachment; + verifyNativeLocalProviderAttachmentImpl?: VerifyNativeLocalStatusAttachment; verifyNativeHostedProviderAttachmentImpl?: VerifyNativeHostedStatusAttachment; } @@ -626,7 +630,19 @@ export async function collectSandboxStatusSnapshot( } else { try { const nvidia = normalizeNativeNvidiaProviderAttachment(expected); - if (nvidia) { + const local = + sb.nativeLocalProviderAttachment === undefined + ? undefined + : normalizeNativeLocalProviderAttachment(sb.nativeLocalProviderAttachment); + if (local) { + await ( + opts.deps?.verifyNativeLocalProviderAttachmentImpl ?? verifyNativeLocalStatusAttachment + )({ + gatewayName, + sandboxName, + expected: local, + }); + } else if (nvidia) { await verifyNativeNvidiaStatusAttachment({ gatewayName, sandboxName, @@ -648,7 +664,7 @@ export async function collectSandboxStatusSnapshot( } catch (error) { const detail = sanitizedStatusDetail(error); nativeAttachmentFailure = - `Native ${nativeLabel} provider attachment is unavailable for sandbox '${sandboxName}'` + + `Native ${nativeLabel} provider '${nativeAttachment.providerName}' is unavailable for sandbox '${sandboxName}'` + `${detail ? `: ${detail}` : "."} Recreate the sandbox to restore native ${nativeLabel} inference.`; } } @@ -757,6 +773,9 @@ export async function collectSandboxStatusSnapshot( model: invocationModel, preferredInferenceApi: invocationRoute.preferredInferenceApi, ...(nativeProvider ? { nativeProvider: true } : {}), + ...(sb?.nativeLocalProviderAttachment + ? { nativeLocalProviderAttachment: sb.nativeLocalProviderAttachment } + : {}), ...(nativeAttachment?.endpointUrl ? { nativeEndpointUrl: nativeAttachment.endpointUrl } : {}), @@ -821,6 +840,10 @@ export async function collectSandboxStatusSnapshot( provider: invocationRoute.provider ?? null, nativeProvider, nativeEndpointUrl: nativeAttachment?.endpointUrl, + nativeLocalEndpoint: + sb?.nativeLocalProviderAttachment === undefined + ? undefined + : nativeAttachment?.endpointUrl, model: invocationRoute.model ?? null, preferredInferenceApi: sb?.preferredInferenceApi ?? null, }); @@ -938,7 +961,8 @@ async function buildSandboxStatusReport( const nativeProvider = Boolean( sb && (sb.nativeNvidiaProviderAttachment !== undefined || - sb.nativeHostedProviderAttachment !== undefined), + sb.nativeHostedProviderAttachment !== undefined || + sb.nativeLocalProviderAttachment !== undefined), ); return { schemaVersion: 1, diff --git a/src/lib/adapters/config/live-export-inference-contract.ts b/src/lib/adapters/config/live-export-inference-contract.ts index bca90201e84..78496f8c4b2 100644 --- a/src/lib/adapters/config/live-export-inference-contract.ts +++ b/src/lib/adapters/config/live-export-inference-contract.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; +import { exportNativeInferenceReceipt } from "../../domain/config/export-evidence"; import { fixedNativeProviderForAttachment } from "../../inference/native-provider/fixed"; import { isDeepStrictEqual } from "node:util"; import { VLLM_LOCAL_CREDENTIAL_ENV } from "../../inference/serving/vllm-credential-contract"; @@ -9,7 +10,10 @@ import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "../../inference/ollama/contract"; import type { NativeProviderAttachment } from "../../inference/native-provider/contract"; import type { Provider } from "../openshell/providers"; import type { SandboxEntry } from "../../state/registry/types"; -import { normalizeInferenceSelection } from "../../inference/selection"; +import { + normalizeInferenceSelection, + normalizeNativeLocalProviderAttachment, +} from "../../inference/selection"; export function providerContract(api: string | null | undefined) { if (api?.startsWith("anthropic")) { @@ -37,6 +41,7 @@ function matchesNativeProviderMetadata( routeProvider: string, receipt: NativeInferenceReceipt, ): boolean { + const local = normalizeNativeLocalProviderAttachment(receipt); return isDeepStrictEqual( [ provider.name, @@ -50,7 +55,7 @@ function matchesNativeProviderMetadata( routeProvider, receipt.providerId, receipt.profileId, - [fixedNativeProviderForAttachment(receipt).credentialEnv], + [local?.credentialEnv ?? fixedNativeProviderForAttachment(receipt).credentialEnv], [], receipt.profileId, ], @@ -94,8 +99,14 @@ export function matchesProviderMetadata( } export function resolveExportInferenceSelection(entry: Readonly) { + const local = + entry.nativeLocalProviderAttachment !== undefined + ? exportNativeInferenceReceipt(entry) + : undefined; + if (entry.nativeLocalProviderAttachment !== undefined && !local) + throw new Error("The native local export binding is invalid or unsupported."); return { normalized: normalizeInferenceSelection(entry), - nativeReceipt: recordedNativeProviderAttachment(entry), + nativeReceipt: local ?? recordedNativeProviderAttachment(entry), }; } diff --git a/src/lib/adapters/config/live-export-source-ollama.test.ts b/src/lib/adapters/config/live-export-source-ollama.test.ts index f9e63c554ba..d9150ee8408 100644 --- a/src/lib/adapters/config/live-export-source-ollama.test.ts +++ b/src/lib/adapters/config/live-export-source-ollama.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { attachNativeLocalExportFixture } from "../../../../test/support/native-local-export-fixture"; import { raw, mockSupportedLiveSource, @@ -54,9 +55,13 @@ function ollamaProbe(observed: ObservedOllamaProxy) { }; } -function mockOllamaSource(model: string = "qwen3.5:9b") { +function mockOllamaSource(model: string = "qwen3.5:9b", native = false) { vi.spyOn(os, "platform").mockReturnValue("linux"); - const { source, observed } = ollamaSource(model); + const { source, observed } = ollamaSource( + model, + {}, + native ? "http://host.openshell.internal:11440/v1" : undefined, + ); source.messaging = { schemaVersion: 1, plan: MessagingSetupApplier.emptyPlan(source.name) }; mockSupportedLiveSource(3, 3, source); const effective = configuration(); @@ -105,6 +110,99 @@ function mockOllamaSource(model: string = "qwen3.5:9b") { } describe("attached Ollama export pipeline", () => { + it("exports native Ollama through its existing service without reading credentials or a shared route (#12558)", async () => { + const { source } = mockOllamaSource("qwen2.5:0.5b", true); + const native = attachNativeLocalExportFixture(source); + const exported = await exportLiveSource(); + expect(exported.result).toEqual({ ok: true, completion: { kind: "stdout" } }); + const yaml = exported.writeStdout.mock.calls[0]![0]; + expect(asExportedConfig(YAML.parse(yaml)).spec.inferenceProviders).toEqual([ + { name: "local", provider: "openai", api: "openai-completions", serviceRef: "ollama-auth" }, + ]); + expect(yaml).not.toContain("NEMOCLAW_LOCAL_INFERENCE_TOKEN"); + expect(native.readCredential).not.toHaveBeenCalled(); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + }); + + it("refuses a native profile that changes throughout export observation (#12558)", async () => { + const { source } = mockOllamaSource("qwen2.5:0.5b", true); + const native = attachNativeLocalExportFixture(source); + let revision = 5n; + raw.getProviderProfile.mockImplementation(async () => ({ + profile: { ...native.profile, resourceVersion: ++revision }, + })); + const exported = await exportLiveSource(); + expect(exported.result).toMatchObject({ ok: false }); + expect(exported.writeStdout).not.toHaveBeenCalled(); + expect(native.readCredential).not.toHaveBeenCalled(); + }); + + it.each([ + { + name: "provider ID", + mutate: (f: ReturnType) => { + f.provider.metadata.id = "replacement-id"; + }, + }, + { + name: "profile host", + mutate: (f: ReturnType) => { + f.endpoint.host = "other.internal"; + }, + }, + { + name: "profile permissions", + mutate: (f: ReturnType) => { + f.endpoint.access = "full"; + }, + }, + { + name: "profile IPs", + mutate: (f: ReturnType) => { + f.endpoint.allowedIps = ["0.0.0.0/0"]; + }, + }, + { + name: "credential environment", + mutate: (f: ReturnType) => { + f.profile.credentials = []; + }, + }, + { + name: "profile binding", + mutate: (f: ReturnType) => { + f.provider.profileWorkspace = "other"; + }, + }, + { + name: "profile revision", + mutate: (f: ReturnType) => { + f.profile.resourceVersion = 0n; + }, + }, + { + name: "attachment", + mutate: () => { + raw.getSandbox.mockResolvedValue(inventory()); + }, + }, + { + name: "receipt", + mutate: (f: ReturnType) => { + f.receipt.sandboxName = "other"; + }, + }, + ])("refuses native Ollama export when $name drifts (#12558)", async ({ mutate }) => { + const { source } = mockOllamaSource("qwen2.5:0.5b", true); + const native = attachNativeLocalExportFixture(source); + mutate(native); + const exported = await exportLiveSource(); + expect(exported.result).toMatchObject({ ok: false }); + expect(exported.writeStdout).not.toHaveBeenCalled(); + expect(native.readCredential).not.toHaveBeenCalled(); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + }); + it.each([ { name: "selected non-default model", diff --git a/src/lib/adapters/config/live-export-source-test-fixture.ts b/src/lib/adapters/config/live-export-source-test-fixture.ts index e9913ad9be6..b9d6623f09c 100644 --- a/src/lib/adapters/config/live-export-source-test-fixture.ts +++ b/src/lib/adapters/config/live-export-source-test-fixture.ts @@ -137,12 +137,18 @@ export function configuration(revision = 3) { }; } -export function ollamaSource(model: string = "qwen3.5:9b", environment: NodeJS.ProcessEnv = {}) { +export function ollamaSource( + model: string = "qwen3.5:9b", + environment: NodeJS.ProcessEnv = {}, + nativeEndpointUrl?: string, +) { const route = resolveManagedStartupInferenceRoute( "openclaw", "ollama-local", model, "openai-completions", + true, + nativeEndpointUrl, ); const built = buildManagedStartupProfile({ ...startupInput, diff --git a/src/lib/adapters/config/live-export-source-vllm.test.ts b/src/lib/adapters/config/live-export-source-vllm.test.ts index ed268228930..a040261ffb5 100644 --- a/src/lib/adapters/config/live-export-source-vllm.test.ts +++ b/src/lib/adapters/config/live-export-source-vllm.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { attachNativeLocalExportFixture } from "../../../../test/support/native-local-export-fixture"; import { raw, mockSupportedLiveSource, @@ -47,6 +48,7 @@ function mockManagedVllmSource( environmentOverrides: NodeJS.ProcessEnv = {}, webSearch: ManagedStartupProfileBuilderInput["webSearch"] = null, toolDisclosure: ManagedStartupProfileBuilderInput["toolDisclosure"] = "progressive", + native = false, ) { const catalog = loadServingCatalog(); const provenance = servingProfileProvenance(catalog, EXPORTED_VLLM_PROFILE_ID); @@ -58,6 +60,8 @@ function mockManagedVllmSource( "vllm-local", model, "openai-completions", + true, + native ? "http://host.openshell.internal:18000/v1" : undefined, ); const environment: NodeJS.ProcessEnv = {}; // This is the actual onboarding projection of the fixed server's /v1/models response. @@ -152,6 +156,22 @@ function mockManagedVllmSource( } describe("managed vLLM export pipeline", () => { + it("exports native managed vLLM through its existing service without reading credentials or a shared route (#12558)", async () => { + const { source } = mockManagedVllmSource({}, null, "progressive", true); + const native = attachNativeLocalExportFixture(source); + const exported = await exportLiveSource(); + expect(exported.result).toEqual({ ok: true, completion: { kind: "stdout" } }); + const yaml = exported.writeStdout.mock.calls[0]![0]; + const document = asExportedConfig(YAML.parse(yaml)); + expect(document.spec.inferenceProviders).toEqual([ + expect.objectContaining({ provider: "openai", serviceRef: "vllm" }), + ]); + expect(yaml).not.toContain("host.openshell.internal"); + expect(yaml).not.toContain("NEMOCLAW_LOCAL_INFERENCE_TOKEN"); + expect(native.readCredential).not.toHaveBeenCalled(); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + }); + it.each([ { count: 1, names: ["researcher"] }, { count: 2, names: ["researcher", "reviewer"] }, diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index 99dabd2fc44..334c3e27fea 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import os from "node:os"; +import { normalizeNativeLocalProviderAttachment } from "../../inference/native-local/contract"; import { providerContract, matchesProviderMetadata, @@ -161,7 +162,9 @@ function inferenceTopology( function profileContractFor( routeProvider: string, nativeReceipt: NativeInferenceReceipt | undefined, -): "native-nvidia" | "native-hosted" | "openai" | undefined { +): Parameters["get"]>[0]["profileContract"] { + const local = normalizeNativeLocalProviderAttachment(nativeReceipt); + if (local) return { kind: "native-local", binding: local }; if (nativeReceipt) return nativeReceipt.profileId === "nemoclaw-nvidia-inference-v1" ? "native-nvidia" @@ -194,7 +197,7 @@ async function readProviderEvidence( workspace: "default", name: routeProvider, ...(profileContract ? { profileContract } : {}), - ...(nativeReceipt?.endpointUrl + ...(nativeReceipt?.endpointUrl && !normalizeNativeLocalProviderAttachment(nativeReceipt) ? { nativeHostedEndpoint: nativeReceipt.endpointUrl, nativeHostedAllowedIps: nativeReceipt.allowedIps, diff --git a/src/lib/adapters/openshell/native-hosted-profile-response.ts b/src/lib/adapters/openshell/native-hosted-profile-response.ts index fabd2c28220..8d7b7e7d112 100644 --- a/src/lib/adapters/openshell/native-hosted-profile-response.ts +++ b/src/lib/adapters/openshell/native-hosted-profile-response.ts @@ -10,7 +10,7 @@ import { import { isManagedNativeProfileResponse, type NativeProfileBoundary, -} from "./native-nvidia-profile-response"; +} from "./native-inference-profile-response"; export type HostedNativeProfileId = | (typeof HOSTED_NATIVE_PROVIDERS)[number]["profileId"] diff --git a/src/lib/adapters/openshell/native-nvidia-profile-response.ts b/src/lib/adapters/openshell/native-inference-profile-response.ts similarity index 78% rename from src/lib/adapters/openshell/native-nvidia-profile-response.ts rename to src/lib/adapters/openshell/native-inference-profile-response.ts index 53aab3a1c83..b79d34f0b27 100644 --- a/src/lib/adapters/openshell/native-nvidia-profile-response.ts +++ b/src/lib/adapters/openshell/native-inference-profile-response.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { prepareNativeLocalProfile } from "../../inference/native-local/profile"; + +type NativeLocalBinding = Parameters[0]; + type NativeProfileResponse = Readonly<{ profile: Readonly<{ id: Id; @@ -18,6 +22,7 @@ export type NativeProfileBoundary = Readonly<{ host: string; port?: number; allowedIps?: readonly string[]; + binaries?: readonly string[]; rules: readonly Readonly<{ method: "GET" | "POST"; path: string }>[]; }>; @@ -123,18 +128,21 @@ function nativeEndpoint(value: unknown, expected: NativeProfileBoundary): boolea ); } -function nativeBinaries(value: unknown): boolean { +function nativeBinaries(value: unknown, expected?: readonly string[]): boolean { if (!Array.isArray(value)) return false; const paths = value.map((item) => record(item)?.path); - return stringArrayEquals(paths, [ - "/usr/local/bin/node", - "/usr/bin/node", - "/opt/hermes/.venv/bin/python", - "/opt/hermes/.venv/bin/python3", - "/opt/venv/bin/python3", - "/usr/local/bin/curl", - "/usr/bin/curl", - ]); + return stringArrayEquals( + paths, + expected ?? [ + "/usr/local/bin/node", + "/usr/bin/node", + "/opt/hermes/.venv/bin/python", + "/opt/hermes/.venv/bin/python3", + "/opt/venv/bin/python3", + "/usr/local/bin/curl", + "/usr/bin/curl", + ], + ); } /** Verify the live custom profile at the credential, egress, and binary security boundary. */ @@ -162,7 +170,7 @@ export function isManagedNativeProfileResponse( Array.isArray(endpoints) && endpoints.length === 1 && nativeEndpoint(endpoints[0], expected) && - nativeBinaries(profile.binaries) + nativeBinaries(profile.binaries, expected.binaries) ); } @@ -171,3 +179,27 @@ export function isManagedNativeNvidiaProfileResponse( ): value is NativeProfileResponse { return isManagedNativeProfileResponse(value, nvidiaBoundary); } + +export function isManagedNativeLocalProfileResponse( + value: unknown, + binding: NativeLocalBinding, +): value is NativeProfileResponse { + const expected = prepareNativeLocalProfile(binding); + const endpoint = expected.document.endpoints[0]; + if (!endpoint) return false; + const url = new URL(binding.endpointUrl); + return isManagedNativeProfileResponse(value, { + profileId: expected.profileId, + credentialEnv: binding.credentialEnv, + authStyle: "bearer", + headerName: "authorization", + host: url.hostname, + port: Number(url.port || (url.protocol === "https:" ? 443 : 80)), + allowedIps: endpoint.allowed_ips, + rules: [ + { method: "GET", path: `${url.pathname}/models` }, + { method: "POST", path: `${url.pathname}/chat/completions` }, + ], + binaries: expected.document.binaries, + }); +} diff --git a/src/lib/adapters/openshell/provider-adapter-cli.ts b/src/lib/adapters/openshell/provider-adapter-cli.ts index 12d6f69680b..b3149b7bc7d 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.ts @@ -830,6 +830,17 @@ export function createCliOpenShellProviderAdapter( ); const error = commandError(result); if (error) return failure(error); + if ( + request.expectedProfile && + (request.expectedProfile.profileId !== request.profileType || + !exportedProviderProfileMatchesContract(commandStdout(result), request.expectedProfile)) + ) { + return failure({ + kind: "command", + reason: "profile_incompatible", + message: "The OpenShell provider profile does not match the expected security boundary.", + }); + } const credentialKeys = parseProfileCredentialKeys(commandStdout(result), request.profileType); return credentialKeys ? success({ credentialKeys }) diff --git a/src/lib/adapters/openshell/provider-adapter.ts b/src/lib/adapters/openshell/provider-adapter.ts index 252011d222b..daf7135a79d 100644 --- a/src/lib/adapters/openshell/provider-adapter.ts +++ b/src/lib/adapters/openshell/provider-adapter.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { CheckedInProviderProfileContract } from "./provider-profile"; + import type { OpenShellGatewayTarget } from "./sandbox-observer"; export type OpenShellProviderCommandReason = @@ -119,6 +121,7 @@ export type ImportOpenShellProviderProfileRequest = OpenShellProviderRequest & export type InspectOpenShellProviderProfileRequest = OpenShellProviderRequest & Readonly<{ profileType: string; + expectedProfile?: CheckedInProviderProfileContract; }>; export type DeleteOpenShellProviderRequest = OpenShellProviderRequest & diff --git a/src/lib/adapters/openshell/provider-policy.test-support.ts b/src/lib/adapters/openshell/provider-policy.test-support.ts new file mode 100644 index 00000000000..023473cb772 --- /dev/null +++ b/src/lib/adapters/openshell/provider-policy.test-support.ts @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { vi } from "vitest"; + +export const absentPolicy = { status: 0, stdout: "", stderr: "No global policy history found\n" }; +export function fixture(enabled = "true", policy = absentPolicy) { + const run = vi.fn(async (args: string[]) => { + if (args[0] === "policy") { + if (args[1] === "get" && policy === absentPolicy) + return { + status: 1, + stdout: "", + stderr: 'status: NotFound, message: "no global policy revision found"', + }; + if (args[1] === "list" && policy !== absentPolicy && policy.status === 0) + return { + status: 0, + stdout: "VERSION HASH STATUS CREATED ERROR\n1 fixture Loaded 0\n", + stderr: "", + }; + return policy; + } + if (args[1] === "set") { + enabled = "true"; + return { status: 0, stdout: "", stderr: "" }; + } + return { + status: 0, + stdout: JSON.stringify({ scope: "global", settings: { providers_v2_enabled: enabled } }), + stderr: "", + }; + }); + return run; +} diff --git a/src/lib/adapters/openshell/provider-policy.test.ts b/src/lib/adapters/openshell/provider-policy.test.ts new file mode 100644 index 00000000000..b43fca9471f --- /dev/null +++ b/src/lib/adapters/openshell/provider-policy.test.ts @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { initializeNativeProviderPolicy, requireNativeProviderPolicy } from "./provider-policy"; + +import { fixture } from "./provider-policy.test-support"; + +afterEach(() => vi.unstubAllEnvs()); +describe("native provider policy prerequisites", () => { + it("reads the named existing gateway without changing its settings (#12558)", async () => { + const run = fixture(); + await requireNativeProviderPolicy("selected", run); + expect(run.mock.calls.map(([args]) => args)).toEqual([ + ["settings", "get", "-g", "selected", "--global", "--json"], + ["policy", "list", "-g", "selected", "--global", "--limit", "1"], + ]); + }); + it.each(["false", ""])( + "refuses %s composition without writing (#12558)", + async (value) => { + const run = fixture(value); + await expect(requireNativeProviderPolicy("selected", run)).rejects.toThrow( + /administrator.*enable composition/, + ); + expect(run.mock.calls.every(([args]) => args[1] === "get")).toBe(true); + }, + ); + it("refuses an active global override even when composition is enabled (#12558)", async () => { + const run = fixture("true", { + status: 0, + stdout: JSON.stringify({ scope: "global", status: "loaded" }), + stderr: "", + }); + await expect(requireNativeProviderPolicy("selected", run)).rejects.toThrow( + /global policy override/, + ); + expect(run.mock.calls.map(([args]) => args[1])).toEqual(["get", "list", "get"]); + }); + it("accepts deleted global policy history (#12558)", async () => { + const run = fixture("true", { + status: 0, + stdout: JSON.stringify({ scope: "global", status: "superseded" }), + stderr: "", + }); + await expect(requireNativeProviderPolicy("selected", run)).resolves.toBeUndefined(); + }); + it.each([ + { status: 1, stdout: "", stderr: "No global policy history found" }, + { + status: 1, + stdout: "", + stderr: 'status: NotFound, message: "no global policy revision found"', + }, + { status: 1, stdout: "", stderr: "permission denied" }, + { status: null, stdout: "", stderr: "connection lost" }, + ])( + "stops fresh initialization when policy history cannot be verified (#12558)", + async (response) => { + const run = vi.fn(async () => response); + await expect(initializeNativeProviderPolicy("selected", run)).rejects.toThrow( + /prerequisites/, + ); + expect(run).toHaveBeenCalledExactlyOnceWith([ + "policy", + "list", + "-g", + "selected", + "--global", + "--limit", + "1", + ]); + }, + ); + it("does not accept policy history without a verified current revision (#12558)", async () => { + const run = fixture(); + run.mockResolvedValueOnce({ + status: 0, + stdout: "VERSION HASH STATUS CREATED ERROR\n", + stderr: "", + }); + await expect(initializeNativeProviderPolicy("selected", run)).rejects.toThrow(/prerequisites/); + expect(run.mock.calls.map(([args]) => args[1])).toEqual(["list", "get"]); + }); + it("initializes a fresh gateway once and verifies applied settings (#12558)", async () => { + const run = fixture(""); + await initializeNativeProviderPolicy("selected", run); + expect(run.mock.calls.filter(([args]) => args[1] === "set")).toHaveLength(1); + expect(run.mock.calls.at(-2)?.[0]).toContain("get"); + }); + it("reconciles a lost initialization response without another write (#12558)", async () => { + const original = fixture(); + const run = vi.fn(async (args: string[]) => + args[1] === "set" ? { status: null, error: new Error("connection lost") } : original(args), + ); + await expect(initializeNativeProviderPolicy("selected", run)).resolves.toBeUndefined(); + expect(run.mock.calls.filter(([args]) => args[1] === "set")).toHaveLength(1); + }); + it("observes the setting after an initialization transport exception (#12558)", async () => { + const run = fixture(); + run.mockResolvedValueOnce({ status: 0, stdout: "", stderr: "No global policy history found" }); + run.mockRejectedValueOnce(new Error("connection lost")); + await expect(initializeNativeProviderPolicy("selected", run)).resolves.toBeUndefined(); + expect(run.mock.calls.filter(([args]) => args[1] === "set")).toHaveLength(1); + }); + it.each([ + { status: 1, stdout: "", stderr: "connection lost" }, + { status: 0, stdout: "{broken", stderr: "" }, + { status: 0, stdout: "[]", stderr: "" }, + ])("rejects an unverified gateway response (#12558)", async (response) => { + await expect(requireNativeProviderPolicy("selected", async () => response)).rejects.toThrow(); + }); + it("continues only after verifying disabled composition and sandbox authority (#12558)", async () => { + const original = fixture("false"); + const run = vi.fn(async (args: string[]) => + args[1] === "set" ? { status: 1, stdout: "", stderr: "unavailable" } : original(args), + ); + await expect(initializeNativeProviderPolicy("selected", run)).resolves.toBe("disabled"); + expect(run.mock.calls.map(([args]) => args[1])).toEqual(["list", "set", "get", "list"]); + await expect(requireNativeProviderPolicy("selected", run)).rejects.toThrow( + /enable composition/, + ); + expect(run.mock.calls.filter(([args]) => args[1] === "set")).toHaveLength(1); + }); + it.each(["", "", null, false])( + "rejects indeterminate composition value %s after initialization (#12558)", + async (value) => { + const run = fixture(); + run.mockResolvedValueOnce({ + status: 0, + stdout: "", + stderr: "No global policy history found", + }); + run.mockResolvedValueOnce({ status: 1, stdout: "", stderr: "unavailable" }); + run.mockResolvedValueOnce({ + status: 0, + stdout: JSON.stringify({ scope: "global", settings: { providers_v2_enabled: value } }), + stderr: "", + }); + await expect(initializeNativeProviderPolicy("selected", run)).rejects.toThrow( + /Could not verify/, + ); + expect(run.mock.calls.filter(([args]) => args[1] === "set")).toHaveLength(1); + }, + ); + it("rejects a policy override introduced during disabled initialization (#12558)", async () => { + const run = fixture("false", { + status: 0, + stdout: JSON.stringify({ scope: "global", status: "loaded" }), + stderr: "", + }); + run.mockResolvedValueOnce({ status: 0, stdout: "", stderr: "No global policy history found" }); + run.mockResolvedValueOnce({ status: 1, stdout: "", stderr: "unavailable" }); + await expect(initializeNativeProviderPolicy("selected", run)).rejects.toThrow( + /global policy override/, + ); + expect(run.mock.calls.filter(([args]) => args[1] === "set")).toHaveLength(1); + }); + it("keeps an unreadable post-write state fatal (#12558)", async () => { + const run = fixture(); + run.mockResolvedValueOnce({ status: 0, stdout: "", stderr: "No global policy history found" }); + run.mockRejectedValueOnce(new Error("lost response")); + run.mockResolvedValueOnce({ status: 1, stdout: "", stderr: "unreachable" }); + await expect(initializeNativeProviderPolicy("selected", run)).rejects.toThrow(/prerequisites/); + expect(run.mock.calls.filter(([args]) => args[1] === "set")).toHaveLength(1); + }); + it("rejects an ambient endpoint override before any command (#12558)", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://another.example:443"); + const run = fixture(); + await expect(requireNativeProviderPolicy("selected", run)).rejects.toThrow(); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/adapters/openshell/provider-policy.ts b/src/lib/adapters/openshell/provider-policy.ts new file mode 100644 index 00000000000..f104e06b26b --- /dev/null +++ b/src/lib/adapters/openshell/provider-policy.ts @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isValidName } from "../../../../nemoclaw/dist/shared/sandbox-name.cjs"; +import { + assertNoOpenShellGatewayEndpointOverride, + scopeGatewayOpenshellArgs, +} from "./gateway-scope"; +import { captureSanitizedResolvedOpenshellAsync } from "./sanitized-capture"; + +type PolicyCommandResult = { + status: number | null; + stdout?: string | Buffer | null; + stderr?: string | Buffer | null; + error?: unknown; +}; +type PolicyCommand = (args: string[]) => Promise; + +function commandForGateway(gatewayName: string, run?: PolicyCommand): PolicyCommand { + if (!isValidName(gatewayName)) throw new Error("Invalid native inference gateway name."); + assertNoOpenShellGatewayEndpointOverride(process.env); + return (args) => + ( + run ?? + ((scoped) => + captureSanitizedResolvedOpenshellAsync(scoped, { + ignoreError: true, + includeStreams: true, + includeStderr: true, + timeout: 30_000, + outputLimitBytes: 65_536, + })) + )(scopeGatewayOpenshellArgs(args, gatewayName, 2)); +} + +function requireSuccessfulCommand(result: PolicyCommandResult): void { + if (result.status !== 0 || result.error) + throw new Error( + "Could not inspect OpenShell provider-policy prerequisites. No inference selection was changed.", + ); +} + +function document(result: PolicyCommandResult): Record { + requireSuccessfulCommand(result); + const text = String(result.stdout ?? ""); + if (Buffer.byteLength(text) > 65_536) + throw new Error("OpenShell provider-policy response exceeded its limit."); + try { + const value: unknown = JSON.parse(text); + if (value && typeof value === "object" && !Array.isArray(value)) + return value as Record; + } catch { + /* Reject an incomplete or incompatible response. */ + } + throw new Error("OpenShell returned invalid provider-policy prerequisites."); +} + +async function requireSandboxPolicyAuthority(run: PolicyCommand): Promise { + const result = await run(["policy", "list", "--global", "--limit", "1"]); + requireSuccessfulCommand(result); + // The pinned server returns NotFound for get when no revision exists. + // Only a successful history read proves absence without treating errors as permission. + if ( + !String(result.stdout ?? "").trim() && + String(result.stderr ?? "").trim() === "No global policy history found" + ) + return; + const policy = document(await run(["policy", "get", "--global", "--output", "json"])); + if (policy.scope === "global" && policy.status === "superseded") return; + throw new Error( + "Native local inference requires sandbox-owned policy. This gateway has a global policy override; ask its administrator to prepare the gateway before retrying.", + ); +} + +/** Read-only prerequisite on existing gateways. Never changes sibling policy. */ +export async function requireNativeProviderPolicy( + gatewayName: string, + command?: PolicyCommand, +): Promise { + const run = commandForGateway(gatewayName, command); + const state = document(await run(["settings", "get", "--global", "--json"])); + const settings = state.settings; + if ( + state.scope !== "global" || + !settings || + typeof settings !== "object" || + Array.isArray(settings) || + (settings as Record).providers_v2_enabled !== "true" + ) { + throw new Error( + `Native local inference requires providers_v2_enabled=true on gateway '${gatewayName}'. Ask its administrator to review attached providers and enable composition with 'openshell settings set -g ${gatewayName} --global --key providers_v2_enabled --value true --yes', then retry. NemoClaw does not activate it on existing gateways.`, + ); + } + await requireSandboxPolicyAuthority(run); +} + +/** Called only by the owner immediately after creating a fresh gateway. */ +export async function initializeNativeProviderPolicy( + gatewayName: string, + command?: PolicyCommand, +): Promise<"disabled" | void> { + const run = commandForGateway(gatewayName, command); + await requireSandboxPolicyAuthority(run); + await run([ + "settings", + "set", + "--global", + "--key", + "providers_v2_enabled", + "--value", + "true", + "--yes", + ]).catch(() => undefined); + // Observe even when the mutation response reports failure; never repeat the write. + const state = document(await run(["settings", "get", "--global", "--json"])); + const settings = state.settings; + const enabled = + state.scope === "global" && settings && typeof settings === "object" && !Array.isArray(settings) + ? (settings as Record).providers_v2_enabled + : undefined; + if (enabled !== "true" && enabled !== "false") + throw new Error("Could not verify native provider composition after gateway initialization."); + await requireSandboxPolicyAuthority(run); + if (enabled === "false") return "disabled"; +} diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index c75a188d131..56b299c2b4e 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -24,12 +24,14 @@ import { BuiltinNvidiaProfileResponseSchema, ProviderResponseSchema, } from "./sdk-read-schema"; +import { + isManagedNativeNvidiaProfileResponse, + isManagedNativeLocalProfileResponse, +} from "./native-inference-profile-response"; import { hostedNativeProfile, isManagedNativeHostedProfileResponse, - type HostedNativeProfileId, } from "./native-hosted-profile-response"; -import { isManagedNativeNvidiaProfileResponse } from "./native-nvidia-profile-response"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; import { @@ -46,7 +48,14 @@ const managedProfileSchemas = { "tavily-hermes-v1": ManagedHermesTavilyProfileResponseSchema, }; type ManagedProfileContract = keyof typeof managedProfileSchemas; -type ProfileContract = ManagedProfileContract | "native-nvidia" | "native-hosted"; +type ProfileContract = + | ManagedProfileContract + | "native-nvidia" + | "native-hosted" + | { + kind: "native-local"; + binding: Parameters[1] & { profileId: string }; + }; export type Provider = Readonly< Pick & { @@ -59,7 +68,7 @@ export type Provider = Readonly< profileWorkspace?: string; // null records a successful not-found read at the OpenAI provider's profile binding. managedProfile?: Readonly<{ - id: ManagedProfileContract | typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID | HostedNativeProfileId; + id: string; source: "builtin" | "user"; scope: "" | "platform" | "workspace"; resourceVersion: string; @@ -95,6 +104,11 @@ async function readBuiltinNvidiaEndpoint( return BUILD_ENDPOINT_URL; } +function managedProfileId(contract: ProfileContract): string { + if (typeof contract === "object") return contract.binding.profileId; + return contract === "native-nvidia" ? NVIDIA_HOSTED_NATIVE_PROFILE_ID : contract; +} + async function readManagedProfile( client: OpenShellReadClient, request: Parameters[0], @@ -102,10 +116,10 @@ async function readManagedProfile( providerType: string, profileWorkspace: string | undefined, ): Promise | null> { - let profileId: string | undefined = profileContract; - if (profileContract === "native-nvidia") profileId = NVIDIA_HOSTED_NATIVE_PROFILE_ID; - else if (profileContract === "native-hosted") - profileId = hostedNativeProfile(providerType, request.nativeHostedEndpoint)?.profileId; + const profileId = + profileContract === "native-hosted" + ? hostedNativeProfile(providerType, request.nativeHostedEndpoint)?.profileId + : managedProfileId(profileContract); if ( providerType !== profileId || (profileWorkspace !== "" && profileWorkspace !== request.workspace) @@ -137,11 +151,20 @@ async function readManagedProfile( function validateNativeManagedProfileResponse( response: unknown, profileWorkspace: string, + localBinding?: Parameters[1], ): NonNullable { - if (!isManagedNativeNvidiaProfileResponse(response)) { + if ( + !(localBinding + ? isManagedNativeLocalProfileResponse(response, localBinding) + : isManagedNativeNvidiaProfileResponse(response)) + ) { throw new OpenShellReadError("schema"); } - const profile = response.profile; + const profile = ( + response as { + profile: { id: string; scope: "platform" | "workspace"; resourceVersion: bigint | string }; + } + ).profile; const expectedScope = profileWorkspace === "" ? "platform" : "workspace"; if (profile.scope !== expectedScope) throw new OpenShellReadError("schema"); return { @@ -160,30 +183,28 @@ function validateManagedProfileResponse( nativeHostedEndpoint?: string, nativeHostedAllowedIps?: readonly string[], ): NonNullable { + if (typeof profileContract === "object") + return validateNativeManagedProfileResponse( + response, + profileWorkspace, + profileContract.binding, + ); if (profileContract === "native-nvidia") { return validateNativeManagedProfileResponse(response, profileWorkspace); } if (profileContract === "native-hosted") { - const validated = isManagedNativeHostedProfileResponse( + return validateNativeHostedManagedProfileResponse( response, + profileWorkspace, providerType, nativeHostedEndpoint, nativeHostedAllowedIps, ); - if ( - !validated || - validated.profile.scope !== (profileWorkspace === "" ? "platform" : "workspace") - ) { - throw new OpenShellReadError("schema"); - } - return { - id: validated.profile.id, - source: "user", - scope: validated.profile.scope, - resourceVersion: String(validated.profile.resourceVersion), - }; } - const { profile } = readValue(managedProfileSchemas[profileContract], response); + const { profile } = readValue( + managedProfileSchemas[profileContract as ManagedProfileContract], + response, + ); const builtin = profile.source === "builtin"; const customScope = profileWorkspace === "" ? "platform" : "workspace"; const expectedScope = builtin ? "" : customScope; @@ -202,10 +223,39 @@ function validateManagedProfileResponse( }; } +function validateNativeHostedManagedProfileResponse( + response: unknown, + profileWorkspace: string, + providerType: string, + nativeHostedEndpoint?: string, + nativeHostedAllowedIps?: readonly string[], +): NonNullable { + const validated = isManagedNativeHostedProfileResponse( + response, + providerType, + nativeHostedEndpoint, + nativeHostedAllowedIps, + ); + if ( + !validated || + validated.profile.scope !== (profileWorkspace === "" ? "platform" : "workspace") + ) { + throw new OpenShellReadError("schema"); + } + return { + id: validated.profile.id, + source: "user", + scope: validated.profile.scope, + resourceVersion: String(validated.profile.resourceVersion), + }; +} + function managedInferenceEndpointFor( managedProfile: Provider["managedProfile"], + contract: ProfileContract | undefined, nativeHostedEndpoint?: string, ): string | undefined { + if (typeof contract === "object") return contract.binding.endpointUrl; return managedProfile?.id === NVIDIA_HOSTED_NATIVE_PROFILE_ID ? NVIDIA_HOSTED_NATIVE_ENDPOINT : hostedNativeProfile(managedProfile?.id ?? "", nativeHostedEndpoint)?.endpoint; @@ -245,6 +295,7 @@ async function readProfileEvidence( ); const managedInferenceEndpoint = managedInferenceEndpointFor( managedProfile, + request.profileContract, request.nativeHostedEndpoint, ); return { diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index af60fb598fe..d5dfb8d8c27 100644 --- a/src/lib/domain/config/export-evidence.ts +++ b/src/lib/domain/config/export-evidence.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeLocalProviderAttachment } from "../../inference/native-local/profile"; import type * as TypeBoxModule from "typebox" with { "resolution-mode": "import" }; import { BoundedTextSchema, @@ -74,6 +75,7 @@ export const EXPORT_REGISTRY_EVIDENCE_KEYS = [ "model", "name", "nativeNvidiaProviderAttachment", + "nativeLocalProviderAttachment", "nativeHostedProviderAttachment", "nimContainer", "observabilityEnabled", @@ -94,6 +96,24 @@ type ObservedExportRegistryKey = (typeof EXPORT_REGISTRY_EVIDENCE_KEYS)[number]; export type ObservedExportRegistry = DeepReadonly>; +export function exportNativeInferenceReceipt(entry: ObservedExportRegistry) { + if (entry.nativeLocalProviderAttachment !== undefined) { + const receipt = normalizeNativeLocalProviderAttachment(entry.nativeLocalProviderAttachment); + if ( + !receipt || + !["ollama-local", "vllm-local"].includes(receipt.provider) || + receipt.provider !== entry.provider || + receipt.sandboxName !== entry.name || + receipt.gatewayName !== entry.gatewayName + ) + return null; + return receipt; + } + return entry.provider?.trim() === "nvidia-prod" + ? entry.nativeNvidiaProviderAttachment + : undefined; +} + export function exportWebSearchBinding( entry: Pick, ) { @@ -135,18 +155,7 @@ export interface ObservedExportEndpointEvidence { readonly profileWorkspace?: string; /** null means the OpenAI profile was read at its binding and confirmed absent. */ readonly managedProfile?: { - readonly id: - | "brave" - | "openai" - | "tavily" - | "tavily-hermes-v1" - | "nemoclaw-nvidia-inference-v1" - | "nemoclaw-openai-inference-v1" - | "nemoclaw-anthropic-inference-v1" - | "nemoclaw-gemini-inference-v1" - | "nemoclaw-openrouter-inference-v1" - | "nemoclaw-hermes-inference-v1" - | `nemoclaw-hermes-inference-${string}-v1`; + readonly id: string; readonly source: "builtin" | "user"; readonly scope: "" | "platform" | "workspace"; readonly resourceVersion: string; diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 22c7e06dbe9..b5764c24ad4 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -41,7 +41,11 @@ import { import { fingerprintOpenShellSandboxId } from "../sandbox/openshell-identity"; import { HERMES_PROVIDER_NAME } from "../../onboard/inference-providers/hermes-provider-identity"; import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "../../inference/ollama/contract"; -import { ExportSourceValuesSchema, exportWebSearchBinding } from "./export-evidence"; +import { + ExportSourceValuesSchema, + exportWebSearchBinding, + exportNativeInferenceReceipt, +} from "./export-evidence"; import { inspectAgentInterfaces } from "./verify-agent-interfaces"; import { V1ALPHA1_RUNTIME_DEFAULTS } from "./v1alpha1-runtime-defaults"; import type { @@ -574,6 +578,13 @@ function exportUsesNativeInference(entry: ObservedExportRegistry): boolean { return !hostedNativeProvider(entry.provider) || Boolean(nativeExportReceipt(entry)); } +function exportRouteEndpoint(entry: ObservedExportRegistry): string | undefined { + return ( + entry.nativeLocalProviderAttachment?.endpointUrl ?? + receiptEndpointUrl(nativeExportReceipt(entry)) + ); +} + function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedStartupProfile { if (!isSupportedExportAgent(entry.agent)) { throw new Error("The agent is unsupported."); @@ -593,8 +604,8 @@ function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedSt selected.provider, selected.model, selected.preferredInferenceApi, - exportUsesNativeInference(entry), - nativeExportReceipt(entry)?.endpointUrl, + exportUsesNativeInference(entry) || entry.nativeLocalProviderAttachment !== undefined, + exportRouteEndpoint(entry), ); const projection = EXPORT_AGENT_PROFILE_PROJECTIONS[agent](inference); const search = exportWebSearchBinding(entry); @@ -859,7 +870,46 @@ function classifyManagedStartupProfile( return [...findings, ...classifyProfileEquality(profile, supported)]; } +function nativeLocalEndpointEvidenceMatches(snapshot: QualifiedExportSnapshot): boolean { + const { inference } = snapshot; + const evidence = inference.endpointEvidence; + if (!evidence || evidence.source.kind !== "managed-profile") return false; + const receipt = exportNativeInferenceReceipt(snapshot.registry); + return ( + receipt != null && + "endpointUrl" in receipt && + (receipt.provider === "ollama-local" || receipt.provider === "vllm-local") && + isDeepStrictEqual( + [ + evidence.source.profileId, + evidence.provider.managedProfile?.id, + evidence.provider.name, + evidence.provider.id, + inference.provider, + inference.api, + inference.endpoint, + evidence.endpoint, + snapshot.registry.name, + snapshot.gateway.name, + ], + [ + receipt.profileId, + receipt.profileId, + receipt.providerName, + receipt.providerId, + receipt.provider, + "openai-completions", + receipt.endpointUrl, + receipt.endpointUrl, + receipt.sandboxName, + receipt.gatewayName, + ], + ) + ); +} + function nativeExportReceipt(entry: QualifiedExportSnapshot["registry"]) { + if (entry.nativeLocalProviderAttachment !== undefined) return exportNativeInferenceReceipt(entry); try { return recordedNativeProviderAttachment(entry); } catch { @@ -867,6 +917,12 @@ function nativeExportReceipt(entry: QualifiedExportSnapshot["registry"]) { } } +function receiptEndpointUrl(receipt: ReturnType): string | undefined { + return receipt && "endpointUrl" in receipt && typeof receipt.endpointUrl === "string" + ? receipt.endpointUrl + : undefined; +} + function managedEndpointEvidenceMatchesRoute( snapshot: QualifiedExportSnapshot, evidence: NonNullable & { @@ -877,7 +933,7 @@ function managedEndpointEvidenceMatchesRoute( const receipt = nativeExportReceipt(snapshot.registry); if (!receipt) return false; const definition = fixedNativeProviderForAttachment(receipt); - const hosted = hostedNativeProvider(snapshot.registry.provider, receipt.endpointUrl); + const hosted = hostedNativeProvider(snapshot.registry.provider, receiptEndpointUrl(receipt)); const endpoint = hosted?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT; const api = hosted?.logicalProvider === "openai-api" && inference.api === "openai-responses" @@ -911,6 +967,8 @@ function endpointEvidenceMatchesRoute(snapshot: QualifiedExportSnapshot): boolea const { inference } = snapshot; const evidence = inference.endpointEvidence; if (!evidence) return false; + if (snapshot.registry.nativeLocalProviderAttachment !== undefined) + return nativeLocalEndpointEvidenceMatches(snapshot); if (evidence.source.kind === "managed-profile") return managedEndpointEvidenceMatchesRoute(snapshot, { ...evidence, source: evidence.source }); if (evidence.source.kind === "builtin-profile") { @@ -987,6 +1045,7 @@ function validateSandboxIdentity( function sandboxProviderAttachmentsMatch(snapshot: QualifiedExportSnapshot): boolean { const { registry: entry, sandbox, inference } = snapshot; const nativeReceipt = nativeExportReceipt(entry); + if (nativeReceipt === null) return false; const inferenceAttachment = nativeReceipt?.providerName ?? inference.provider; const additionalProviders = sandbox.providerNames.filter((name) => name !== inferenceAttachment); const webSearch = exportWebSearchBinding(entry); diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index 6655e333787..15ddcb452a9 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -368,6 +368,34 @@ describe("inference selection config", () => { }); describe("getSandboxInferenceConfig", () => { + it.each([ + ["compatible-endpoint", "http://host.openshell.internal:42103/v1", true, INFERENCE_ROUTE_URL], + [ + "compatible-endpoint", + "http://host.openshell.internal:8000/v1", + true, + "http://host.openshell.internal:8000/v1", + ], + ["compatible-endpoint", "http://host.openshell.internal:8000/v1", false, INFERENCE_ROUTE_URL], + ["ollama-local", "http://192.168.65.2:11435/v1", true, "http://192.168.65.2:11435/v1"], + ["ollama-local", "http://192.168.65.2:11435/v1", false, INFERENCE_ROUTE_URL], + ["vllm-local", "http://host.openshell.internal:8000/v1", false, INFERENCE_ROUTE_URL], + ["llama-cpp-local", "http://192.168.65.2:8080/v1", false, INFERENCE_ROUTE_URL], + ] as const)( + "selects %s transport for %s with nativeProvider=%s (#12558)", + (provider, endpoint, nativeProvider, expected) => { + expect( + getSandboxInferenceConfig( + "model-a", + provider, + "openai-completions", + nativeProvider, + endpoint, + ).inferenceBaseUrl, + ).toBe(expected); + }, + ); + it("enables streaming usage for ollama-local behind the managed inference route", () => { expect(getSandboxInferenceConfig("qwen3.6:35b", "ollama-local")).toEqual({ providerKey: MANAGED_PROVIDER_ID, diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index c2b623f13f1..166cf13aeaf 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -6,6 +6,11 @@ * All functions are pure. */ +import { nativeLocalCredentialReference } from "./native-local/agent-config"; +import { + usesNativeLocalInference, + usesNativeLocalInferenceForAgent, +} from "./native-local/contract"; import { isSafeModelId, shouldSkipResponsesProbe } from "../validation"; import { isSafeLlamaCppServedModelAlias, @@ -22,7 +27,15 @@ import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "./ollama/contract"; import { OPENROUTER_CREDENTIAL_ENV, OPENROUTER_PROVIDER_NAME } from "./openrouter"; import { VLLM_LOCAL_CREDENTIAL_ENV } from "./serving/vllm-credential-contract"; -export { isSafeModelId }; +export { + isSafeModelId, + nativeLocalCredentialReference, + usesNativeLocalInference, + usesNativeLocalInferenceForAgent, +}; +export { normalizeNativeLocalProviderAttachment } from "./native-local/contract"; +export { hasLegacySharedLocalInferenceRoute } from "./selection"; +export type { NativeLocalProviderAttachment } from "./native-local/contract"; export { OLLAMA_LOCAL_CREDENTIAL_ENV }; export { managedInferenceApiKey, NVIDIA_INFERENCE_PLACEHOLDER } from "../inference-credential"; export { @@ -415,6 +428,15 @@ export function getSandboxInferenceConfig( break; } + if ( + useNativeProvider && + nativeEndpointUrl && + usesNativeLocalInference(provider, nativeEndpointUrl) && + nativeLocalCredentialReference(provider, nativeEndpointUrl) + ) { + inferenceBaseUrl = nativeEndpointUrl; + inferenceApi = "openai-completions"; + } return { providerKey, primaryModelRef, inferenceBaseUrl, inferenceApi, inferenceCompat }; } diff --git a/src/lib/inference/gateway-route-compatibility.test.ts b/src/lib/inference/gateway-route-compatibility.test.ts index 2939cc2a9f3..5e543bc60ff 100644 --- a/src/lib/inference/gateway-route-compatibility.test.ts +++ b/src/lib/inference/gateway-route-compatibility.test.ts @@ -54,12 +54,14 @@ function check(requested: GatewayInferenceRoute, sandboxes: SandboxEntry[]) { function discover( requested: Omit & { model: string | null }, sandboxes: SandboxEntry[], + nativeLocalSelection = false, ) { return preflightGatewayRouteDiscovery({ gatewayName: "nemoclaw", sandboxName: "target", route: requested, sandboxes, + ...(nativeLocalSelection ? { nativeLocalSelection: true } : {}), }); } @@ -176,6 +178,46 @@ describe("shared gateway inference route compatibility", () => { }); }); + it("allows native local discovery beside a different shared endpoint while rejecting damaged peers (#12975)", () => { + const selected = discoveryRoute("compatible-endpoint", { + endpointUrl: "http://host.openshell.internal:11434/v1", + preferredInferenceApi: "openai-completions", + credentialEnv: "COMPATIBLE_API_KEY", + }); + const peer = sandbox("shared-peer", { + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: "http://host.openshell.internal:19001/v1", + preferredInferenceApi: "openai-completions", + credentialEnv: "COMPATIBLE_API_KEY", + }); + + expect(discover(selected, [peer], true)).toEqual({ + ok: true, + requiredModel: null, + requiredEndpointUrl: null, + requiredInferenceApi: null, + }); + expect(discover(selected, [peer])).toMatchObject({ + ok: false, + result: { conflicts: [{ sandboxName: "shared-peer", reason: "custom-endpoint" }] }, + }); + expect( + discover( + selected, + [sandbox("broken-binding", { gatewayName: "invalid", gatewayPort: null })], + true, + ), + ).toMatchObject({ + ok: false, + result: { conflicts: [{ sandboxName: "broken-binding", reason: "invalid-gateway-binding" }] }, + }); + expect(discover(selected, [{ ...peer, endpointUrl: null }], true)).toMatchObject({ + ok: false, + result: { conflicts: [{ sandboxName: "shared-peer", reason: "incomplete-custom-route" }] }, + }); + }); + it("preserves llama.cpp endpoint and completions API as durable route identity (#8161)", () => { const result = discover( discoveryRoute("llama-cpp-local", { diff --git a/src/lib/inference/gateway-route-compatibility.ts b/src/lib/inference/gateway-route-compatibility.ts index 9505a1764c4..761a3e13141 100644 --- a/src/lib/inference/gateway-route-compatibility.ts +++ b/src/lib/inference/gateway-route-compatibility.ts @@ -71,6 +71,7 @@ export type GatewayRouteDiscoveryResult = export type CurrentGatewayRouteDiscoveryPreflight = ( request: Omit & { route: Omit & { model: string | null }; + nativeLocalSelection?: boolean; }, ) => GatewayRouteDiscoveryResult; @@ -206,8 +207,20 @@ export function preflightGatewayRouteDiscovery( continue; } if (recordedGatewayName !== request.gatewayName) continue; - if (configuredRoute(sandbox)) peers.push(sandbox); - else { + const recorded = configuredRoute(sandbox); + if (recorded) { + peers.push(sandbox); + if ( + request.nativeLocalSelection && + gatewayRouteIdentityConflictReasons(sandbox, sandbox).includes("incomplete-custom-route") + ) { + discoveryConflicts.push({ + sandboxName: sandbox.name, + reason: "incomplete-custom-route", + scope: "registered", + }); + } + } else { discoveryConflicts.push({ sandboxName: sandbox.name, reason: "incomplete-route", @@ -228,6 +241,16 @@ export function preflightGatewayRouteDiscovery( }, }; } + // A native provider does not change the gateway-wide inference route, but + // malformed shared peers must still be rejected before selection. + if (request.nativeLocalSelection) { + return { + ok: true, + requiredModel: null, + requiredEndpointUrl: null, + requiredInferenceApi: null, + }; + } if (peers.length === 0) { return { ok: true, @@ -499,3 +522,5 @@ export function assertGatewayRouteCompatibility(request: GatewayRouteCompatibili const result = checkGatewayRouteCompatibility(request); if (!result.ok) throw new GatewayRouteConflictError(result); } + +export { normalizeNativeLocalProviderAttachment } from "./native-local/contract"; diff --git a/src/lib/inference/gateway/local-endpoint-ports.test.ts b/src/lib/inference/gateway/local-endpoint-ports.test.ts new file mode 100644 index 00000000000..c516e6a0c7d --- /dev/null +++ b/src/lib/inference/gateway/local-endpoint-ports.test.ts @@ -0,0 +1,42 @@ +// 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 { OLLAMA_PROXY_PORT } from "../../core/ollama-proxy-port"; +import { isProtectedLocalInferencePort } from "./local-endpoint-ports"; + +vi.mock("../../state/gateway-registry", () => ({ + resolveHome: () => "/test-home", + listRecordedGatewayPorts: () => [12345], + listRecordedModelRouterPorts: () => [12346], +})); + +describe("local inference endpoint port reservations", () => { + it.each([ + { name: "ordinary backend", port: 11434, options: {}, protected: false }, + { name: "default gateway", port: 8080, options: {}, protected: true }, + { name: "recorded gateway", port: 12345, options: {}, protected: true }, + { name: "retained router", port: 12346, options: {}, protected: true }, + { + name: "router despite proxy authority", + port: 12346, + options: { ownedProxy: true }, + protected: true, + }, + { name: "unowned proxy", port: OLLAMA_PROXY_PORT, options: {}, protected: true }, + { + name: "owned proxy", + port: OLLAMA_PROXY_PORT, + options: { ownedProxy: true }, + protected: false, + }, + { + name: "gateway despite proxy authority", + port: 12345, + options: { ownedProxy: true }, + protected: true, + }, + ])("protects $name at selection time (#12558)", ({ port, options, protected: expected }) => { + expect(isProtectedLocalInferencePort(port, options)).toBe(expected); + }); +}); diff --git a/src/lib/inference/gateway/local-endpoint-ports.ts b/src/lib/inference/gateway/local-endpoint-ports.ts new file mode 100644 index 00000000000..778ee9cef44 --- /dev/null +++ b/src/lib/inference/gateway/local-endpoint-ports.ts @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { OLLAMA_PROXY_PORT } from "../../core/ollama-proxy-port"; +import { isProtectedNemoClawHostPort } from "../../core/protected-host-ports"; +import { + listRecordedGatewayPorts, + listRecordedModelRouterPorts, + resolveHome, +} from "../../state/gateway-registry"; + +/** Apply host control-plane reservations at each local inference mutation boundary. */ +export function isProtectedLocalInferencePort( + port: number, + options: { ownedProxy?: boolean; allowLegacyProxyDefault?: boolean } = {}, +): boolean { + const home = resolveHome(); + return ( + (!(options.ownedProxy === true && port === OLLAMA_PROXY_PORT) && + isProtectedNemoClawHostPort(port, listRecordedModelRouterPorts(home), options)) || + listRecordedGatewayPorts(home).includes(port) + ); +} diff --git a/src/lib/inference/native-local.test.ts b/src/lib/inference/native-local.test.ts new file mode 100644 index 00000000000..e9922b4b167 --- /dev/null +++ b/src/lib/inference/native-local.test.ts @@ -0,0 +1,404 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { buildConfig } from "../../../scripts/generate-openclaw-config.mts"; +import { baseOpenClawGenerationEnv } from "../../../test/helpers/openclaw-env-fixture"; +import { describe, expect, it, vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { + nativeLocalIdentity, + nativeLocalCredentialReference, + normalizeNativeLocalBinding, + normalizeNativeLocalProviderAttachment, + usesNativeLocalInferenceForAgent, + type NativeLocalBinding, + type NativeLocalProviderAttachment, +} from "./native-local/contract"; +import { + ensureNativeLocalProvider, + ensureNativeLocalProviderAttached, + prepareNativeLocalProfile, + verifyNativeLocalProviderAttachment, + retireNativeLocalProvider, +} from "./native-local/profile"; + +vi.mock("../adapters/openshell/provider-policy", () => ({ + requireNativeProviderPolicy: vi.fn(async () => {}), +})); + +const binding: NativeLocalBinding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11435/v1", + credentialEnv: "NEMOCLAW_OLLAMA_PROXY_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "alice", +}; +const identity = nativeLocalIdentity(binding); +const receipt: NativeLocalProviderAttachment = { + ...binding, + ...identity, + schemaVersion: 1, + providerId: "owned-id", +}; + +function fixture(selectedBinding: NativeLocalBinding = binding) { + const binding = selectedBinding; + const identity = nativeLocalIdentity(binding); + let present = false; + let attached = false; + let authority: NativeLocalProviderAttachment | undefined; + const adapter = { + ensureProviderPolicyComposition: vi.fn(() => { + throw new Error("Native local setup must not activate provider composition"); + }), + importProviderProfile: vi.fn(async () => ({ + ok: true, + })), + inspectProviderProfile: vi.fn(async () => ({ + ok: true, + value: { credentialKeys: [binding.credentialEnv] }, + })), + getProvider: vi.fn(async () => + present + ? { + ok: true as const, + value: { + name: identity.providerName, + type: identity.profileId, + credentialKeys: [binding.credentialEnv], + configKeys: [], + revision: { id: "owned-id", resourceVersion: 1 }, + }, + } + : { + ok: false as const, + error: { kind: "command" as const, reason: "not_found" as const, message: "absent" }, + }, + ), + createProvider: vi.fn(async () => { + present = true; + return { ok: true as const }; + }), + updateProvider: vi.fn(async () => ({ ok: true as const })), + deleteProvider: vi.fn(async () => { + present = false; + return { ok: true as const }; + }), + listProviderAttachments: vi.fn(async () => ({ + ok: true as const, + value: { names: attached ? [identity.providerName] : [] }, + })), + attachProvider: vi.fn(async () => { + attached = true; + return { ok: true as const }; + }), + detachProvider: vi.fn(async () => { + attached = false; + return { ok: true as const, value: { changed: true } }; + }), + listProviders: vi.fn(), + configureProviderRefresh: vi.fn(), + getProviderRefreshStatus: vi.fn(), + } satisfies OpenShellProviderAdapter; + return { + adapter, + input: { + adapter, + binding, + credentialValue: "test-only-secret", + readAuthority: () => authority, + writeAuthority: (value: NativeLocalProviderAttachment) => { + authority = value; + }, + }, + }; +} + +describe("native local inference", () => { + it.each([ + "http://host.openshell.internal:11435/v1", + "http://host.docker.internal:11435/v1/", + "http://10.1.2.3:8000/v1", + ])("issues a local credential reference for a qualified endpoint: %s", (endpointUrl) => { + expect(normalizeNativeLocalBinding({ ...binding, endpointUrl })).toBeDefined(); + expect(nativeLocalCredentialReference("ollama-local", endpointUrl)).toBe( + "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + ); + expect(nativeLocalCredentialReference("openai-api", endpointUrl)).toBeNull(); + }); + + it.each([ + "http://host.openshell.internal/v1", + "http://host.openshell.internal:80/v1", + "http://host.openshell.internal:11435/v1?key=hidden", + "http://host.openshell.internal:11435/v1#fragment", + "http://host.openshell.internal:11435/v1/**", + "http://host.openshell.internal:11435/v1%2fadmin", + "http://127.0.0.1:11435/v1", + "http://169.254.169.254:11435/v1", + ])("rejects an unqualified local credential endpoint: %s", (endpointUrl) => { + expect(normalizeNativeLocalBinding({ ...binding, endpointUrl })).toBeUndefined(); + expect(nativeLocalCredentialReference("ollama-local", endpointUrl)).toBeNull(); + }); + + it.each([ + ["openclaw", true], + ["langchain-deepagents-code", true], + ["pi", false], + ["hermes", false], + ])("selects native local routing only for migrated %s", (agent, expected) => { + expect(usesNativeLocalInferenceForAgent(agent, binding.provider, binding.endpointUrl)).toBe( + expected, + ); + }); + + it("restricts the selected bridge to models and chat requests (#12558)", () => { + const profile = prepareNativeLocalProfile(binding); + expect(profile.document.binaries).toContain("/usr/local/bin/openclaw"); + expect(profile.document.binaries).not.toContain("/opt/hermes/.venv/bin/python"); + expect(profile.document.endpoints).toEqual([ + { + host: "host.openshell.internal", + port: 11435, + protocol: "rest", + enforcement: "enforce", + allowed_ips: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], + rules: [ + { allow: { method: "GET", path: "/v1/models" } }, + { allow: { method: "POST", path: "/v1/chat/completions" } }, + ], + }, + ]); + expect(profile.document.binaries.every((path) => !/[?*]/.test(path))).toBe(true); + }); + it("separates authentication modes and sandbox instances without credential-derived names (#12558)", () => { + const sentinel = nativeLocalIdentity({ ...binding, authMode: "sentinel" }); + const otherSandbox = nativeLocalIdentity({ ...binding, sandboxName: "bob" }); + expect(sentinel.profileId).not.toBe(identity.profileId); + expect(otherSandbox.profileId).toBe(identity.profileId); + expect(otherSandbox.providerName).not.toBe(identity.providerName); + }); + it("keeps runtime publication transactions distinct without changing endpoint permissions (#12558)", () => { + const first = nativeLocalIdentity({ ...binding, transactionId: "a".repeat(64) }); + const second = nativeLocalIdentity({ ...binding, transactionId: "b".repeat(64) }); + expect(first.profileId).toBe(second.profileId); + expect(first.providerName).not.toBe(second.providerName); + }); + it.each([ + "http://127.0.0.1:11434/v1", + "http://localhost:11434/v1", + "http://host.openshell.internal:11434/v1?token=private", + "http://user:private@host.openshell.internal:11434/v1", + "http://169.254.169.254:8080/v1", + "http://unqualified.example:11434/v1", + "http://host.openshell.internal:11434/v1/**", + "http://host.openshell.internal:11434/v1%2fadmin", + ])( + "rejects an unqualified endpoint before a provider mutation: %s (#12558)", + async (endpointUrl) => { + const f = fixture(); + await expect( + ensureNativeLocalProvider({ ...f.input, binding: { ...binding, endpointUrl } }), + ).rejects.toThrow("boundary"); + expect(f.adapter.importProviderProfile).not.toHaveBeenCalled(); + expect(f.adapter.createProvider).not.toHaveBeenCalled(); + }, + ); + it("persists only endpoint identity and removes its temporary profile (#12558)", async () => { + const f = fixture(); + let temporaryPath = ""; + f.adapter.importProviderProfile.mockImplementation(async (input) => { + temporaryPath = input.profilePath; + expect(fs.readFileSync(temporaryPath, "utf8")).not.toContain(f.input.credentialValue); + return { ok: true }; + }); + const actual = await ensureNativeLocalProvider(f.input); + expect(actual).toEqual(receipt); + expect(f.input.readAuthority()).toEqual(receipt); + expect(JSON.stringify(actual)).not.toContain(f.input.credentialValue); + expect(fs.existsSync(temporaryPath)).toBe(false); + }); + it("preserves an existing sentinel instead of reading a host OpenAI key (#12558)", async () => { + const f = fixture({ ...binding, authMode: "sentinel" }); + await ensureNativeLocalProvider({ ...f.input, credentialValue: "ollama" }); + expect(f.adapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + credentials: [{ name: binding.credentialEnv, value: "ollama" }], + config: [], + }), + ); + }); + it("refuses a profile collision before changing provider state (#12558)", async () => { + const f = fixture(); + f.adapter.importProviderProfile.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "profile_incompatible", message: "collision" }, + } as never); + await expect(ensureNativeLocalProvider(f.input)).rejects.toThrow("conflicts"); + expect(f.adapter.getProvider).not.toHaveBeenCalled(); + expect(f.adapter.createProvider).not.toHaveBeenCalled(); + }); + it("observes an ambiguous creation before recording ownership (#12558)", async () => { + const f = fixture(); + const create = f.adapter.createProvider.getMockImplementation()!; + f.adapter.createProvider.mockImplementation(async () => { + await create(); + return { ok: false, error: { kind: "timeout", message: "lost response" } } as never; + }); + expect(await ensureNativeLocalProvider(f.input)).toEqual(receipt); + expect(f.adapter.createProvider).toHaveBeenCalledTimes(1); + expect(f.adapter.getProvider).toHaveBeenCalledTimes(2); + }); + it("removes only the new provider when ownership cannot be saved (#12558)", async () => { + const f = fixture(); + await expect( + ensureNativeLocalProvider({ + ...f.input, + writeAuthority: () => { + throw new Error("cannot save"); + }, + }), + ).rejects.toThrow("newly created provider was removed"); + expect(f.adapter.deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: binding.gatewayName }, + providerName: identity.providerName, + }); + }); + it("attaches only to its recorded sandbox and verifies the applied name (#12558)", async () => { + const f = fixture(); + const expected = await ensureNativeLocalProvider(f.input); + await expect( + ensureNativeLocalProviderAttached({ adapter: f.adapter, expected, sandboxName: "bob" }), + ).rejects.toThrow("selected sandbox"); + expect(f.adapter.attachProvider).not.toHaveBeenCalled(); + await expect( + ensureNativeLocalProviderAttached({ adapter: f.adapter, expected, sandboxName: "alice" }), + ).resolves.toEqual({ receipt, changed: true }); + await expect( + verifyNativeLocalProviderAttachment({ adapter: f.adapter, expected, sandboxName: "alice" }), + ).resolves.toEqual(receipt); + }); + it("rejects receipts changed to another endpoint or provider instance (#12558)", () => { + expect( + normalizeNativeLocalProviderAttachment({ + ...receipt, + endpointUrl: "http://host.openshell.internal:8000/v1", + }), + ).toBeUndefined(); + expect( + normalizeNativeLocalProviderAttachment({ ...receipt, sandboxName: "bob" }), + ).toBeUndefined(); + }); + it("refuses another sandbox's attachment before looking up or mutating access (#12558)", async () => { + const f = fixture(); + await expect( + ensureNativeLocalProviderAttached({ + adapter: f.adapter, + sandboxName: "bob", + expected: receipt, + }), + ).rejects.toThrow("selected sandbox"); + expect(f.adapter.getProvider).not.toHaveBeenCalled(); + expect(f.adapter.attachProvider).not.toHaveBeenCalled(); + }); + it("refuses a changed profile before attachment verification (#12558)", async () => { + const f = fixture(); + await ensureNativeLocalProvider(f.input); + f.adapter.inspectProviderProfile.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "profile_incompatible", message: "changed" }, + } as never); + await expect( + ensureNativeLocalProviderAttached({ + adapter: f.adapter, + sandboxName: "alice", + expected: receipt, + }), + ).rejects.toThrow("endpoint boundary"); + expect(f.adapter.attachProvider).not.toHaveBeenCalled(); + }); + it("clears cleanup authority only after exact provider removal is confirmed (#12558)", async () => { + const f = fixture(); + await ensureNativeLocalProvider(f.input); + const clearAuthority = vi.fn(); + await retireNativeLocalProvider({ + adapter: f.adapter, + expected: receipt, + sandboxName: "alice", + gatewayName: "nemoclaw", + clearAuthority, + }); + expect(f.adapter.deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: receipt.providerName, + }); + expect(clearAuthority).toHaveBeenCalledExactlyOnceWith(receipt); + }); + it("retains credentials and cleanup authority when another attachment prevents retirement (#12558)", async () => { + const f = fixture(); + await ensureNativeLocalProvider(f.input); + f.adapter.deleteProvider.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "attached", message: "still attached" }, + } as never); + const clearAuthority = vi.fn(); + await expect( + retireNativeLocalProvider({ + adapter: f.adapter, + expected: receipt, + sandboxName: "alice", + gatewayName: "nemoclaw", + clearAuthority, + }), + ).resolves.toEqual({ status: "attached" }); + expect(clearAuthority).not.toHaveBeenCalled(); + expect(f.adapter.deleteProvider).toHaveBeenCalledOnce(); + }); + it("retains cleanup authority when removal is ambiguous and the provider still exists (#12558)", async () => { + const f = fixture(); + await ensureNativeLocalProvider(f.input); + f.adapter.deleteProvider.mockResolvedValue({ + ok: false, + error: { kind: "transport", reason: "connection_loss", message: "lost" }, + } as never); + const clearAuthority = vi.fn(); + await expect( + retireNativeLocalProvider({ + adapter: f.adapter, + expected: receipt, + sandboxName: "alice", + gatewayName: "nemoclaw", + clearAuthority, + }), + ).rejects.toThrow("not confirmed"); + expect(clearAuthority).not.toHaveBeenCalled(); + expect(f.adapter.deleteProvider).toHaveBeenCalledTimes(1); + }); +}); + +describe("OpenClaw native local inference config", () => { + it.each(["ollama-local", "vllm-local", "llama-cpp-local"])( + "writes the selected native endpoint and opaque credential for %s (#12558)", + (provider) => { + const environment = { + ...baseOpenClawGenerationEnv(), + NEMOCLAW_UPSTREAM_PROVIDER: provider, + NEMOCLAW_PROVIDER_KEY: "inference", + NEMOCLAW_MODEL: "local-model", + NEMOCLAW_INFERENCE_BASE_URL: "http://host.openshell.internal:11434/v1", + NEMOCLAW_INFERENCE_API: "openai-completions", + OPENAI_API_KEY: "ambient-secret-must-not-escape", + }; + const config = buildConfig(environment); + expect(config.models.providers.inference).toMatchObject({ + baseUrl: "http://host.openshell.internal:11434/v1", + apiKey: "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + api: "openai-completions", + models: [expect.objectContaining({ id: "local-model" })], + }); + expect(JSON.stringify(config)).not.toContain("ambient-secret-must-not-escape"); + }, + ); +}); diff --git a/src/lib/inference/native-local/agent-config.ts b/src/lib/inference/native-local/agent-config.ts new file mode 100644 index 00000000000..0534fb23d56 --- /dev/null +++ b/src/lib/inference/native-local/agent-config.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isIP } from "node:net"; +import { unsafeEndpointUrlViolation } from "../../core/endpoint-url-safety.ts"; + +export const NATIVE_LOCAL_CREDENTIAL_ENV = "NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + +/** The endpoint shape shared by local provider registration and agent credentials. */ +export function qualifiedNativeLocalEndpointUrl(endpointUrl: string): string | null { + if (!endpointUrl || unsafeEndpointUrlViolation(endpointUrl)) return null; + try { + const endpoint = new URL(endpointUrl); + const host = endpoint.hostname; + const privateIpv4 = + isIP(host) === 4 && + (host.startsWith("10.") || + host.startsWith("192.168.") || + /^172\.(1[6-9]|2[0-9]|3[01])\./.test(host)); + if ( + endpoint.protocol !== "http:" || + endpoint.username || + endpoint.password || + endpoint.search || + endpoint.hash || + !endpoint.port || + Number(endpoint.port) < 1024 || + (host !== "host.openshell.internal" && host !== "host.docker.internal" && !privateIpv4) || + !/^\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+\/?$/.test(endpoint.pathname) + ) + return null; + return `${endpoint.origin}${endpoint.pathname.replace(/\/$/, "")}`; + } catch { + return null; + } +} + +/** Select the opaque credential reference for a qualified local agent endpoint. */ +export function nativeLocalCredentialReference( + provider: string | null | undefined, + endpointUrl: string, +): string | null { + if ( + !["ollama-local", "vllm-local", "llama-cpp-local", "compatible-endpoint"].includes( + provider ?? "", + ) + ) + return null; + return qualifiedNativeLocalEndpointUrl(endpointUrl) + ? `openshell:resolve:env:${NATIVE_LOCAL_CREDENTIAL_ENV}` + : null; +} + +/** Endpoint-bound credentials require a supervisor-issued revision or stable identity. */ +export const NATIVE_LOCAL_RUNTIME_REFERENCE_PATTERN = + "^openshell:resolve:env:(v[0-9]{1,20}|s[a-f0-9]{64})_NEMOCLAW_LOCAL_INFERENCE_TOKEN$"; + +export const NATIVE_LOCAL_AUTH_HEADER_SCRIPT = [ + 'case "${NEMOCLAW_LOCAL_INFERENCE_TOKEN:-}" in *[!a-zA-Z0-9:_]*) exit 2 ;; esac', + `printf '%s' "\${NEMOCLAW_LOCAL_INFERENCE_TOKEN:-}" | LC_ALL=C grep -Eq '${NATIVE_LOCAL_RUNTIME_REFERENCE_PATTERN}' || exit 2`, + 'AUTH_HEADER="Authorization: Bearer ${NEMOCLAW_LOCAL_INFERENCE_TOKEN}"', +].join("; "); diff --git a/src/lib/inference/native-local/contract.ts b/src/lib/inference/native-local/contract.ts new file mode 100644 index 00000000000..1baf30fe2f2 --- /dev/null +++ b/src/lib/inference/native-local/contract.ts @@ -0,0 +1,167 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +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 { 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 type NativeLocalProvider = + | "ollama-local" + | "vllm-local" + | "llama-cpp-local" + | "compatible-endpoint"; +export type NativeLocalBinding = Readonly<{ + provider: NativeLocalProvider; + endpointUrl: string; + credentialEnv: string; + authMode: "authenticated" | "sentinel"; + gatewayName: string; + sandboxName: string; + /** Existing runtime publication transaction, when that owner requires one. */ + transactionId?: string; +}>; +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; + const input = value as Record; + if ( + (!isLocalInferenceProvider(input.provider as string) && + input.provider !== "compatible-endpoint") || + typeof input.endpointUrl !== "string" || + typeof input.credentialEnv !== "string" || + !/^[A-Z][A-Z0-9_]*$/.test(input.credentialEnv) || + (input.authMode !== "authenticated" && input.authMode !== "sentinel") || + typeof input.gatewayName !== "string" || + !isValidName(input.gatewayName) || + typeof input.sandboxName !== "string" || + !isValidName(input.sandboxName) || + (input.transactionId !== undefined && + (typeof input.transactionId !== "string" || !/^[a-f0-9]{64}$/.test(input.transactionId))) + ) + return undefined; + const endpointUrl = qualifiedNativeLocalEndpointUrl(input.endpointUrl); + if (!endpointUrl) return undefined; + return { + provider: input.provider as NativeLocalProvider, + endpointUrl, + credentialEnv: input.credentialEnv, + authMode: input.authMode, + gatewayName: input.gatewayName, + sandboxName: input.sandboxName, + ...(typeof input.transactionId === "string" ? { transactionId: input.transactionId } : {}), + }; +} + +export function nativeLocalIdentity(binding: NativeLocalBinding) { + const normalized = normalizeNativeLocalBinding(binding); + if (!normalized) throw new Error("Invalid native host-local inference boundary."); + const profileHash = createHash("sha256") + .update( + JSON.stringify([ + normalized.provider, + normalized.endpointUrl, + normalized.credentialEnv, + normalized.authMode, + ]), + ) + .digest("hex") + .slice(0, 24); + const profileId = `nemoclaw-local-${normalized.authMode}-v1-${profileHash}`; + const instanceHash = createHash("sha256") + .update( + JSON.stringify([ + profileId, + normalized.gatewayName, + normalized.sandboxName, + ...(normalized.transactionId ? [normalized.transactionId] : []), + ]), + ) + .digest("hex") + .slice(0, 24); + return { profileId, providerName: `nemoclaw-local-v1-${instanceHash}` }; +} + +export function normalizeNativeLocalProviderAttachment( + value: unknown, +): NativeLocalProviderAttachment | undefined { + const binding = normalizeNativeLocalBinding(value); + if (!binding) return undefined; + const receipt = value as Record; + const identity = nativeLocalIdentity(binding); + if ( + receipt.schemaVersion !== 1 || + receipt.profileId !== identity.profileId || + receipt.providerName !== identity.providerName || + typeof receipt.providerId !== "string" || + !receipt.providerId.trim() + ) + return undefined; + return { ...binding, ...identity, schemaVersion: 1, providerId: receipt.providerId }; +} + +export function normalizeNativeLocalProviderAuthorities( + value: unknown, +): Record | undefined { + if (value === undefined) return undefined; + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error( + "Invalid persisted native local provider authority. Retain the registry for explicit repair.", + ); + const entries = Object.entries(value).map(([name, value]) => { + const receipt = normalizeNativeLocalProviderAttachment(value); + if (!receipt || receipt.providerName !== name) + throw new Error( + "Invalid persisted native local provider authority. Retain the registry for explicit repair.", + ); + return [name, receipt] as const; + }); + return entries.length ? Object.fromEntries(entries) : undefined; +} + +/** Hosted compatible endpoints remain with their hosted migration slice. */ +export function usesNativeLocalInference( + provider: string | null | undefined, + endpointUrl?: string | null, +): boolean { + if (isLocalInferenceProvider(provider)) return true; + if (provider !== "compatible-endpoint" || !endpointUrl) return false; + try { + const endpoint = new URL(endpointUrl); + return ( + endpoint.protocol === "http:" && + [11434, OLLAMA_PROXY_PORT, VLLM_PORT].includes(Number(endpoint.port)) && + [ + "localhost", + "127.0.0.1", + "[::1]", + "host.openshell.internal", + "host.docker.internal", + ].includes(endpoint.hostname) + ); + } catch { + return false; + } +} + +/** Route only the agents whose native local credential consumers are covered by this slice. */ +export function usesNativeLocalInferenceForAgent( + agentName: string | null | undefined, + provider: string | null | undefined, + endpointUrl?: string | null, +): boolean { + return ( + (agentName === "openclaw" || agentName === "langchain-deepagents-code") && + usesNativeLocalInference(provider, endpointUrl) + ); +} diff --git a/src/lib/inference/native-local/profile.ts b/src/lib/inference/native-local/profile.ts new file mode 100644 index 00000000000..0f56bad2bab --- /dev/null +++ b/src/lib/inference/native-local/profile.ts @@ -0,0 +1,190 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { requireNativeProviderPolicy } from "../../adapters/openshell/provider-policy"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { isIP } from "node:net"; +import type { OpenShellProviderAdapter } from "../../adapters/openshell/sandbox-observer"; +import { parseCheckedInProviderProfileContract } from "../../adapters/openshell/provider-profile"; +import { + detachNativeProvider, + retireNativeProvider, + ensureNativeProvider, + ensureNativeProviderAttached, + persistNativeProviderAuthority, + verifyNativeProviderAttachment, +} from "../native-provider/lifecycle"; +import { + nativeLocalIdentity, + normalizeNativeLocalBinding, + normalizeNativeLocalProviderAttachment, + type NativeLocalBinding, + type NativeLocalProviderAttachment, +} from "./contract"; + +export { normalizeNativeLocalProviderAttachment }; + +export function prepareNativeLocalProfile(input: NativeLocalBinding) { + const binding = normalizeNativeLocalBinding(input); + if (!binding) throw new Error("Invalid native host-local inference boundary."); + const identity = nativeLocalIdentity(binding); + const endpoint = new URL(binding.endpointUrl); + return { + ...identity, + credentialEnv: binding.credentialEnv, + document: { + id: identity.profileId, + display_name: "NemoClaw local inference", + description: `Selected ${binding.authMode} host-local inference endpoint`, + category: "inference", + // Existing nonsecret sentinels satisfy the current provider store contract + // for unauthenticated upstreams. They are never replaced with a host API key. + credentials: [ + { + name: "api_key", + env_vars: [binding.credentialEnv], + required: true, + auth_style: "bearer", + header_name: "authorization", + query_param: "", + }, + ], + endpoints: [ + { + host: endpoint.hostname, + port: Number(endpoint.port), + protocol: "rest", + enforcement: "enforce", + // The bridge uses the existing qualified runtime address. These ranges + // admit its private resolution, never another hostname or port. + allowed_ips: isIP(endpoint.hostname) + ? [`${endpoint.hostname}/32`] + : ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], + rules: [ + { allow: { method: "GET", path: `${endpoint.pathname}/models` } }, + { allow: { method: "POST", path: `${endpoint.pathname}/chat/completions` } }, + ], + }, + ], + binaries: [ + "/usr/local/bin/openclaw", + "/usr/local/bin/node", + "/usr/bin/node", + "/usr/bin/python3", + "/opt/venv/bin/python3", + "/usr/local/bin/curl", + "/usr/bin/curl", + ], + inference_capable: true, + }, + }; +} + +export async function ensureNativeLocalProvider(input: { + binding: NativeLocalBinding; + adapter: OpenShellProviderAdapter; + credentialValue: string | null; + policyCommand?: Parameters[1]; + expected?: NativeLocalProviderAttachment; + readAuthority: (providerName: string) => NativeLocalProviderAttachment | undefined; + writeAuthority: (receipt: NativeLocalProviderAttachment) => void; +}): Promise { + const binding = normalizeNativeLocalBinding(input.binding); + if (!binding) throw new Error("Invalid native host-local inference boundary."); + await requireNativeProviderPolicy(binding.gatewayName, input.policyCommand); + const prepared = prepareNativeLocalProfile(binding); + const expected = input.expected && normalizeNativeLocalProviderAttachment(input.expected); + if (input.expected && !expected) + throw new Error("Invalid native local provider ownership receipt."); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-local-profile-")); + try { + const profilePath = path.join(directory, "profile.yaml"); + fs.writeFileSync(profilePath, JSON.stringify(prepared.document), { mode: 0o600 }); + const profile = { ...prepared, profilePath, label: "host-local" }; + const target = { kind: "named" as const, gatewayName: binding.gatewayName }; + const receipt = await ensureNativeProvider({ ...input, profile, target, expected }); + const attachment: NativeLocalProviderAttachment = { ...receipt, ...binding }; + await persistNativeProviderAuthority({ + adapter: input.adapter, + profile, + target, + gatewayName: binding.gatewayName, + receipt: attachment, + existing: expected, + readAuthority: () => input.readAuthority(prepared.providerName), + writeAuthority: () => input.writeAuthority(attachment), + recoveryGuidance: "Inspect native local provider ownership before retrying.", + }); + return attachment; + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +type AttachmentInput = { + adapter: OpenShellProviderAdapter; + sandboxName: string; + expected: NativeLocalProviderAttachment; +}; + +async function checkedAttachment(input: AttachmentInput, requirePolicy = true) { + const expected = normalizeNativeLocalProviderAttachment(input.expected); + if (!expected || expected.sandboxName !== input.sandboxName) + throw new Error("Native local provider ownership does not match the selected sandbox."); + if (requirePolicy) await requireNativeProviderPolicy(expected.gatewayName); + const prepared = prepareNativeLocalProfile(expected); + const contract = parseCheckedInProviderProfileContract(JSON.stringify(prepared.document)); + if (!contract) throw new Error("Invalid native local provider profile."); + const target = { kind: "named" as const, gatewayName: expected.gatewayName }; + const observed = await input.adapter.inspectProviderProfile({ + target, + profileType: expected.profileId, + expectedProfile: contract, + }); + if (!observed.ok) + throw new Error("Native local provider profile does not match its endpoint boundary."); + return { expected, target, profile: { ...prepared, profilePath: "", label: "host-local" } }; +} + +export async function verifyNativeLocalProviderAttachment(input: AttachmentInput) { + const checked = await checkedAttachment(input); + await verifyNativeProviderAttachment({ ...input, ...checked }); + return checked.expected; +} + +export async function ensureNativeLocalProviderAttached(input: AttachmentInput) { + const checked = await checkedAttachment(input); + const result = await ensureNativeProviderAttached({ ...input, ...checked }); + return { receipt: checked.expected, changed: result.changed }; +} + +export async function detachNativeLocalProvider(input: AttachmentInput) { + const checked = await checkedAttachment(input, false); + await detachNativeProvider({ ...input, ...checked }); +} + +/** Retire the exact instance after selection detaches it or its sandbox is confirmed absent. */ +export async function retireNativeLocalProvider(input: { + adapter: OpenShellProviderAdapter; + expected: NativeLocalProviderAttachment; + sandboxName: string; + gatewayName: string; + clearAuthority: (expected: NativeLocalProviderAttachment) => void; +}) { + const expected = normalizeNativeLocalProviderAttachment(input.expected); + if ( + !expected || + expected.sandboxName !== input.sandboxName || + expected.gatewayName !== input.gatewayName + ) + throw new Error("Native local provider cleanup authority changed."); + return retireNativeProvider({ + adapter: input.adapter, + target: { kind: "named", gatewayName: expected.gatewayName }, + expected, + credentialEnv: expected.credentialEnv, + clearAuthority: () => input.clearAuthority(expected), + }); +} diff --git a/src/lib/inference/native-local/selection.ts b/src/lib/inference/native-local/selection.ts new file mode 100644 index 00000000000..8924e6d75ca --- /dev/null +++ b/src/lib/inference/native-local/selection.ts @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { OLLAMA_PROXY_PORT } from "../../core/ollama-proxy-port"; +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; +import { isProtectedLocalInferencePort } from "../gateway/local-endpoint-ports"; +import { + getNativeLocalProviderAuthority, + listNativeLocalProviderAuthorities, + clearNativeLocalProviderAuthority, + setNativeLocalProviderAuthority, +} from "../../state/registry/native-local-provider-authority"; +import { + nativeLocalIdentity, + normalizeNativeLocalProviderAttachment, + NATIVE_LOCAL_CREDENTIAL_ENV, + type NativeLocalBinding, + type NativeLocalProviderAttachment, +} from "./contract"; +import { ensureNativeLocalProvider, retireNativeLocalProvider } from "./profile"; + +/** Register the endpoint selected by the existing local runtime or proxy owner. */ +export async function prepareNativeLocalSelection(input: { + adapter: OpenShellProviderAdapter; + binding: Omit; + credentialValue: string | null; + ownedProxy?: boolean; + readAuthority?: typeof getNativeLocalProviderAuthority; + writeAuthority?: typeof setNativeLocalProviderAuthority; +}) { + const binding = { ...input.binding, credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV }; + const identity = nativeLocalIdentity(binding); + const port = Number(new URL(binding.endpointUrl).port); + const ownedProxy = + input.ownedProxy === true && + port === OLLAMA_PROXY_PORT && + new URL(binding.endpointUrl).hostname === "host.openshell.internal"; + if (isProtectedLocalInferencePort(port, { ownedProxy })) { + throw new Error("The selected local inference endpoint uses a protected host port."); + } + const readAuthority = input.readAuthority ?? getNativeLocalProviderAuthority; + const writeAuthority = input.writeAuthority ?? setNativeLocalProviderAuthority; + return ensureNativeLocalProvider({ + adapter: input.adapter, + binding, + credentialValue: input.credentialValue, + expected: readAuthority(identity.providerName), + readAuthority, + writeAuthority, + }); +} + +/** Caller holds the sandbox mutation lock and has committed its selection or confirmed deletion. */ +export async function retireUnselectedNativeLocalProviders(input: { + adapter: OpenShellProviderAdapter; + sandboxName: string; + gatewayName: string; + selected?: NativeLocalProviderAttachment; + destroyedAttachment?: NativeLocalProviderAttachment; + listAuthorities?: typeof listNativeLocalProviderAuthorities; + clearAuthority?: typeof clearNativeLocalProviderAuthority; +}): Promise { + const receipts = new Map( + (input.listAuthorities ?? listNativeLocalProviderAuthorities)( + input.sandboxName, + input.gatewayName, + ).map((receipt) => [receipt.providerName, receipt]), + ); + const destroyed = input.destroyedAttachment; + if (destroyed) { + const recorded = receipts.get(destroyed.providerName); + if (recorded && recorded.providerId !== destroyed.providerId) + throw new Error("Native local provider cleanup authority changed."); + receipts.set(destroyed.providerName, destroyed); + } + for (const receipt of receipts.values()) { + if (receipt.providerName === input.selected?.providerName) continue; + const result = await retireNativeLocalProvider({ + adapter: input.adapter, + expected: receipt, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + clearAuthority: input.clearAuthority ?? clearNativeLocalProviderAuthority, + }); + if (result.status === "attached") + throw new Error( + "Native inference provider remains attached; recovery authority retained. Inspect its attachments before retrying cleanup.", + ); + } +} + +/** Retire prepared authority only before the caller starts publishing a reservation. */ +export async function retireUnreservedNativeLocalProvider(input: { + adapter: OpenShellProviderAdapter; + expected: NativeLocalProviderAttachment; + sandboxName: string; + gatewayName: string; + getSandbox?: typeof import("../../state/registry").getSandbox; + clearAuthority?: typeof clearNativeLocalProviderAuthority; +}): Promise { + if (!input.getSandbox) throw new Error("Sandbox ownership observation is unavailable."); + const entry = input.getSandbox(input.sandboxName); + const recorded = normalizeNativeLocalProviderAttachment(entry?.nativeLocalProviderAttachment); + if (entry?.nativeLocalProviderAttachment !== undefined && !recorded) + throw new Error( + "Sandbox provider ownership could not be verified; cleanup authority retained.", + ); + if ( + recorded?.providerName === input.expected.providerName && + recorded.providerId === input.expected.providerId + ) + return; + const retired = await retireNativeLocalProvider({ + ...input, + clearAuthority: input.clearAuthority ?? clearNativeLocalProviderAuthority, + }); + if (retired.status === "attached") + throw new Error("Provider remains attached; cleanup authority retained."); +} diff --git a/src/lib/inference/native-provider-policy-separation.test.ts b/src/lib/inference/native-provider-policy-separation.test.ts new file mode 100644 index 00000000000..d6b6f676eda --- /dev/null +++ b/src/lib/inference/native-provider-policy-separation.test.ts @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import type { + OpenShellProviderAdapter, + OpenShellProviderMetadata, +} from "../adapters/openshell/provider-adapter"; +import { + NVIDIA_HOSTED_NATIVE_PROVIDER, + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + NVIDIA_HOSTED_CREDENTIAL_ENV, + ensureNativeNvidiaProvider, + nativeNvidiaProviderAttachmentFromMetadata, +} from "./native-nvidia"; +import { ensureNativeLocalProvider } from "./native-local/profile"; + +const target = { kind: "named", gatewayName: "selected" } as const; +const metadata: OpenShellProviderMetadata = { + name: NVIDIA_HOSTED_NATIVE_PROVIDER, + type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, + credentialKeys: [NVIDIA_HOSTED_CREDENTIAL_ENV], + configKeys: [], + revision: { id: "owned", resourceVersion: 1 }, +}; +function fixture(existing = false) { + let provider: OpenShellProviderMetadata | undefined = existing ? metadata : undefined; + const adapter = { + importProviderProfile: vi.fn(async () => ({ ok: true as const })), + getProvider: vi.fn(async () => + provider + ? { ok: true as const, value: provider } + : { + ok: false as const, + error: { kind: "command" as const, reason: "not_found" as const, message: "absent" }, + }, + ), + ensureProviderPolicyComposition: vi.fn< + OpenShellProviderAdapter["ensureProviderPolicyComposition"] + >(async () => ({ ok: true, value: undefined })), + createProvider: vi.fn(async (request) => { + provider = { + ...metadata, + name: request.name, + type: request.type, + credentialKeys: request.credentials.map((c) => c.name), + }; + return { ok: true }; + }), + updateProvider: vi.fn(async () => ({ ok: true as const })), + }; + return { adapter, transport: adapter as unknown as OpenShellProviderAdapter }; +} +function localFixture(enabled: "true" | "false") { + const f = fixture(); + const policyCommand = vi.fn(async (args: string[]) => ({ + status: 0, + stdout: + args[0] === "settings" + ? JSON.stringify({ scope: "global", settings: { providers_v2_enabled: enabled } }) + : "", + stderr: args[0] === "settings" ? "" : "No global policy history found", + })); + const action = ensureNativeLocalProvider({ + adapter: f.transport, + binding: { + provider: "vllm-local", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "selected", + sandboxName: "alice", + }, + credentialValue: "test-key", + policyCommand, + readAuthority: () => undefined, + writeAuthority: vi.fn(), + }); + return { f, policyCommand, action }; +} +describe("native provider policy ownership", () => { + it("activates NVIDIA composition before creating the validated provider (#12558)", async () => { + const f = fixture(); + await ensureNativeNvidiaProvider({ adapter: f.transport, target, credentialValue: "test-key" }); + expect(f.adapter.ensureProviderPolicyComposition).toHaveBeenCalledExactlyOnceWith({ target }); + expect(f.adapter.getProvider.mock.invocationCallOrder[0]).toBeLessThan( + f.adapter.ensureProviderPolicyComposition.mock.invocationCallOrder[0]!, + ); + expect(f.adapter.ensureProviderPolicyComposition.mock.invocationCallOrder[0]).toBeLessThan( + f.adapter.createProvider.mock.invocationCallOrder[0]!, + ); + }); + it("activates NVIDIA composition when reusing owned credentials (#12558)", async () => { + const f = fixture(true); + const expected = nativeNvidiaProviderAttachmentFromMetadata(metadata); + await expect( + ensureNativeNvidiaProvider({ adapter: f.transport, target, expected, credentialValue: null }), + ).resolves.toEqual(expected); + expect(f.adapter.ensureProviderPolicyComposition).toHaveBeenCalledOnce(); + expect(f.adapter.updateProvider).not.toHaveBeenCalled(); + }); + it("rejects unowned NVIDIA providers without activating composition (#12558)", async () => { + const f = fixture(true); + await expect( + ensureNativeNvidiaProvider({ adapter: f.transport, target, credentialValue: "test-key" }), + ).rejects.toThrow("ownership receipt"); + expect(f.adapter.ensureProviderPolicyComposition).not.toHaveBeenCalled(); + }); + it("rejects missing NVIDIA credentials without activating composition (#12558)", async () => { + const f = fixture(); + await expect( + ensureNativeNvidiaProvider({ adapter: f.transport, target, credentialValue: null }), + ).rejects.toThrow("host credential"); + expect(f.adapter.ensureProviderPolicyComposition).not.toHaveBeenCalled(); + }); + it("stops NVIDIA creation when composition activation fails (#12558)", async () => { + const f = fixture(); + f.adapter.ensureProviderPolicyComposition.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "failed", message: "denied" }, + }); + await expect( + ensureNativeNvidiaProvider({ adapter: f.transport, target, credentialValue: "test-key" }), + ).rejects.toThrow("activate native NVIDIA provider policy"); + expect(f.adapter.createProvider).not.toHaveBeenCalled(); + }); + it("keeps enabled native-local composition read-only (#12558)", async () => { + const { f, policyCommand, action } = localFixture("true"); + await expect(action).resolves.toMatchObject({ sandboxName: "alice" }); + expect(f.adapter.ensureProviderPolicyComposition).not.toHaveBeenCalled(); + expect(policyCommand.mock.calls.some(([args]) => args.includes("set"))).toBe(false); + }); + it("rejects disabled native-local composition without activating it (#12558)", async () => { + const { f, policyCommand, action } = localFixture("false"); + await expect(action).rejects.toThrow("administrator"); + expect(f.adapter.ensureProviderPolicyComposition).not.toHaveBeenCalled(); + expect(policyCommand.mock.calls.some(([args]) => args.includes("set"))).toBe(false); + }); +}); diff --git a/src/lib/inference/native-provider/lifecycle.ts b/src/lib/inference/native-provider/lifecycle.ts new file mode 100644 index 00000000000..9831e0f3dde --- /dev/null +++ b/src/lib/inference/native-provider/lifecycle.ts @@ -0,0 +1,489 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { + OpenShellGatewayTarget, + OpenShellProviderAdapter, + OpenShellProviderError, + OpenShellProviderMetadata, +} from "../../adapters/openshell/sandbox-observer"; + +export type NativeProviderAttachment = Readonly<{ + schemaVersion: 1; + profileId: string; + providerName: string; + providerId: string; +}>; +export type NativeProviderProfile = Readonly<{ + profileId: string; + providerName: string; + credentialEnv: string; + label: string; + profilePath: string; +}>; +export class NativeProviderError extends Error { + constructor(message: string) { + super(message); + this.name = "NativeProviderError"; + } +} + +function assertExpectedProfile( + profile: NativeProviderProfile, + expected?: NativeProviderAttachment, +): void { + if ( + expected && + (expected.profileId !== profile.profileId || expected.providerName !== profile.providerName) + ) { + throw new NativeProviderError( + "Recorded native provider identity does not match the selected profile. No provider was changed.", + ); + } +} + +function providerErrorDetail(error: OpenShellProviderError): string { + return error.message.trim() || "OpenShell did not provide a diagnostic."; +} + +function exactNativeProvider( + metadata: OpenShellProviderMetadata, + profile: Pick, +): boolean { + return ( + metadata.name === profile.providerName && + metadata.type === profile.profileId && + metadata.configKeys.length === 0 && + metadata.credentialKeys.length === 1 && + metadata.credentialKeys[0] === profile.credentialEnv && + Boolean(metadata.revision?.id) + ); +} + +export function nativeProviderAttachmentFromMetadata( + metadata: OpenShellProviderMetadata, + profile: NativeProviderProfile, +): NativeProviderAttachment { + if (!exactNativeProvider(metadata, profile) || !metadata.revision) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' does not match the NemoClaw-owned ${profile.label} inference boundary. No provider was changed.`, + ); + } + return { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: metadata.revision.id, + }; +} + +async function inspectNativeProvider( + adapter: OpenShellProviderAdapter, + target: OpenShellGatewayTarget, + profile: NativeProviderProfile, +): Promise { + const observed = await adapter.getProvider({ + target, + providerName: profile.providerName, + }); + if (observed.ok) return observed.value; + if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; + throw new NativeProviderError( + `Could not inspect OpenShell provider '${profile.providerName}': ${providerErrorDetail(observed.error)}`, + ); +} + +function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { + return ( + error.kind === "timeout" || + (error.kind === "transport" && + (error.reason === "connection_loss" || error.reason === "unreachable")) || + (error.kind === "command" && error.reason === "uncertain") + ); +} + +async function removeNewNativeProvider(input: { + profile: NativeProviderProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + expected: NativeProviderAttachment; +}): Promise { + const provider = await inspectNativeProvider(input.adapter, input.target, input.profile); + if (!provider) return; + const current = nativeProviderAttachmentFromMetadata(provider, input.profile); + if (current.providerId !== input.expected.providerId) { + throw new NativeProviderError( + `Refusing to remove OpenShell provider '${input.profile.providerName}' because its identity changed.`, + ); + } + const removed = await input.adapter.deleteProvider({ + target: input.target, + providerName: input.profile.providerName, + }); + if (!removed.ok && !mutationOutcomeMayBeAmbiguous(removed.error)) { + throw new NativeProviderError( + `Could not remove OpenShell provider '${input.profile.providerName}': ${providerErrorDetail(removed.error)}`, + ); + } + const after = await inspectNativeProvider(input.adapter, input.target, input.profile); + if (after) { + const observed = nativeProviderAttachmentFromMetadata(after, input.profile); + const identity = + observed.providerId === input.expected.providerId ? "still exists" : "changed identity"; + throw new NativeProviderError( + `OpenShell provider '${input.profile.providerName}' ${identity} after cleanup.`, + ); + } +} + +/** Record provider authority or remove only the new, unreferenced provider. */ +export async function persistNativeProviderAuthority(input: { + profile: NativeProviderProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + gatewayName: string; + recoveryGuidance: string; + receipt: NativeProviderAttachment; + existing?: NativeProviderAttachment; + readAuthority: (gatewayName: string) => NativeProviderAttachment | undefined; + writeAuthority: (gatewayName: string, receipt: NativeProviderAttachment) => void; +}): Promise { + assertExpectedProfile(input.profile, input.receipt); + assertExpectedProfile(input.profile, input.existing); + try { + input.writeAuthority(input.gatewayName, input.receipt); + return; + } catch (writeError) { + const writeDetail = writeError instanceof Error ? writeError.message : String(writeError); + let observed: NativeProviderAttachment | undefined; + try { + observed = input.readAuthority(input.gatewayName); + } catch (readError) { + const readDetail = readError instanceof Error ? readError.message : String(readError); + throw new NativeProviderError( + `NemoClaw could not record or confirm ownership of OpenShell provider '${input.profile.providerName}' for gateway '${input.gatewayName}'. The provider was retained. ${input.recoveryGuidance}\n Write failure: ${writeDetail}\n Read failure: ${readDetail}`, + ); + } + if (observed?.providerId === input.receipt.providerId) return; + if (input.existing || observed) { + throw new NativeProviderError( + `NemoClaw could not record ownership of OpenShell provider '${input.profile.providerName}' for gateway '${input.gatewayName}'. The provider was retained because this operation cannot prove that it is unreferenced. ${input.recoveryGuidance}\n ${writeDetail}`, + ); + } + try { + await removeNewNativeProvider({ + adapter: input.adapter, + target: input.target, + expected: input.receipt, + profile: input.profile, + }); + } catch (cleanupError) { + const cleanupDetail = + cleanupError instanceof Error ? cleanupError.message : String(cleanupError); + throw new NativeProviderError( + `NemoClaw could not record ownership of OpenShell provider '${input.profile.providerName}' for gateway '${input.gatewayName}', and cleanup did not complete. ${input.recoveryGuidance}\n Write failure: ${writeDetail}\n Cleanup failure: ${cleanupDetail}`, + ); + } + throw new NativeProviderError( + `NemoClaw could not record ownership of OpenShell provider '${input.profile.providerName}' for gateway '${input.gatewayName}'. The newly created provider was removed. Retry the command.\n ${writeDetail}`, + ); + } +} + +/** Ensure the least-privilege hosted profile and provider without retrying an ambiguous mutation. */ +export async function ensureNativeProvider(input: { + profile: NativeProviderProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + credentialValue: string | null; + reuseExistingCredential?: boolean; + /** Provider-owned policy preparation after identity and credential checks. */ + prepareProviderPolicy?: () => Promise; + expected?: NativeProviderAttachment; + profilePath?: string; +}): Promise { + const { adapter, target, profile } = input; + assertExpectedProfile(profile, input.expected); + const imported = await adapter.importProviderProfile({ + target, + profilePath: input.profilePath ?? profile.profilePath, + }); + if (!imported.ok) { + const collision = + imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; + throw new NativeProviderError( + collision + ? `OpenShell provider profile '${profile.profileId}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` + : `Could not prepare OpenShell provider profile '${profile.profileId}': ${providerErrorDetail(imported.error)}`, + ); + } + + const before = await inspectNativeProvider(adapter, target, profile); + if (before) { + const receipt = nativeProviderAttachmentFromMetadata(before, profile); + if (!input.expected) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' already exists without a matching NemoClaw ownership receipt. No provider was changed.`, + ); + } + if (input.expected && input.expected.providerId !== receipt.providerId) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' changed identity. Recreate the sandbox before using native ${profile.label} inference. No provider was changed.`, + ); + } + await input.prepareProviderPolicy?.(); + if (!input.credentialValue) return receipt; + const updated = await adapter.updateProvider({ + target, + providerName: profile.providerName, + credentials: [{ name: profile.credentialEnv, value: input.credentialValue }], + config: [], + }); + if (!updated.ok && mutationOutcomeMayBeAmbiguous(updated.error)) { + throw new NativeProviderError( + `OpenShell did not confirm whether provider '${profile.providerName}' accepted its credential update. No provider receipt was recorded.`, + ); + } + if (!updated.ok) { + throw new NativeProviderError( + `Could not update OpenShell provider '${profile.providerName}': ${providerErrorDetail(updated.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target, profile); + if (!observed) { + throw new NativeProviderError( + `OpenShell did not confirm provider '${profile.providerName}' after its credential update.`, + ); + } + const confirmed = nativeProviderAttachmentFromMetadata(observed, profile); + if (confirmed.providerId !== receipt.providerId) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' changed identity during its credential update. No provider receipt was recorded.`, + ); + } + return confirmed; + } + + if (input.expected) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' is missing. Recreate the sandbox before using native ${profile.label} inference. No provider was changed.`, + ); + } + + if (!input.credentialValue && !input.reuseExistingCredential) { + throw new NativeProviderError( + `A host credential is required to create OpenShell provider '${profile.providerName}'.`, + ); + } + await input.prepareProviderPolicy?.(); + const created = await adapter.createProvider({ + target, + name: profile.providerName, + type: profile.profileId, + credentials: input.credentialValue + ? [{ name: profile.credentialEnv, value: input.credentialValue }] + : [], + config: [], + fromExisting: !input.credentialValue, + }); + if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { + throw new NativeProviderError( + `Could not create OpenShell provider '${profile.providerName}': ${providerErrorDetail(created.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target, profile); + if (!observed) { + throw new NativeProviderError( + `OpenShell did not confirm provider '${profile.providerName}' after creation.`, + ); + } + return nativeProviderAttachmentFromMetadata(observed, profile); +} + +/** Prove that the exact NemoClaw-owned hosted provider is attached to one sandbox. */ +export async function verifyNativeProviderAttachment(input: { + profile: NativeProviderProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected?: NativeProviderAttachment; +}): Promise { + const profile = input.profile; + if (!profile) + throw new NativeProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if (!provider) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' is missing. Recreate the sandbox to restore native ${profile.label} inference.`, + ); + } + const receipt = nativeProviderAttachmentFromMetadata(provider, profile); + if (input.expected && input.expected.providerId !== receipt.providerId) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' changed identity. Recreate the sandbox before using native ${profile.label} inference.`, + ); + } + const attachments = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!attachments.ok) { + throw new NativeProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, + ); + } + if (!attachments.value.names.includes(profile.providerName)) { + throw new NativeProviderError( + `Sandbox '${input.sandboxName}' does not have its native ${profile.label} inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, + ); + } + return receipt; +} + +/** Attach native hosted access and reconcile an ambiguous command through observation. */ +export async function ensureNativeProviderAttached(input: { + profile: NativeProviderProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeProviderAttachment; +}): Promise<{ receipt: NativeProviderAttachment; changed: boolean }> { + const profile = input.profile; + if (!profile) + throw new NativeProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if ( + !provider || + nativeProviderAttachmentFromMetadata(provider, profile).providerId !== input.expected.providerId + ) { + throw new NativeProviderError( + `OpenShell provider '${profile.providerName}' changed identity before attachment. Recreate the sandbox; no provider was attached.`, + ); + } + const before = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!before.ok) { + throw new NativeProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, + ); + } + if (before.value.names.includes(profile.providerName)) { + return { + receipt: await verifyNativeProviderAttachment({ ...input, profile }), + changed: false, + }; + } + const attached = await input.adapter.attachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: profile.providerName, + }); + if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { + throw new NativeProviderError( + `Could not attach native ${profile.label} provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, + ); + } + try { + return { + receipt: await verifyNativeProviderAttachment({ ...input, profile }), + changed: true, + }; + } catch (error) { + try { + await detachNativeProvider({ ...input, profile }); + } catch (detachError) { + const detail = error instanceof Error ? error.message : String(error); + const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); + throw new NativeProviderError(`${detail}\n ${detachDetail}`); + } + throw error; + } +} + +/** Detach only the recorded native hosted provider identity and prove absence. */ +export async function detachNativeProvider(input: { + profile: NativeProviderProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeProviderAttachment; +}): Promise { + const profile = input.profile; + if (!profile) + throw new NativeProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if (!provider) return; + const current = nativeProviderAttachmentFromMetadata(provider, profile); + if (current.providerId !== input.expected.providerId) { + throw new NativeProviderError( + `Refusing to detach OpenShell provider '${profile.providerName}' because its identity changed.`, + ); + } + const detached = await input.adapter.detachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: profile.providerName, + }); + if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { + throw new NativeProviderError( + `Could not detach native ${profile.label} provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, + ); + } + const after = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!after.ok || after.value.names.includes(profile.providerName)) { + throw new NativeProviderError( + `OpenShell did not confirm removal of native ${profile.label} access from sandbox '${input.sandboxName}'.`, + ); + } +} + +export type NativeProviderRetirement = { status: "retired" | "attached" }; + +/** Observe exact provider absence before releasing its recovery authority. */ +export async function retireNativeProvider(input: { + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + expected: NativeProviderAttachment; + credentialEnv: string; + clearAuthority: () => void; +}): Promise { + const { expected } = input; + const request = { target: input.target, providerName: expected.providerName }; + const before = await input.adapter.getProvider(request); + if (!before.ok) { + if (before.error.kind === "command" && before.error.reason === "not_found") { + input.clearAuthority(); + return { status: "retired" }; + } + throw new NativeProviderError( + `Provider '${expected.providerName}' retirement could not verify ownership; recovery authority retained.`, + ); + } + if ( + !exactNativeProvider(before.value, { ...expected, credentialEnv: input.credentialEnv }) || + before.value.revision?.id !== expected.providerId + ) { + throw new NativeProviderError( + `Provider '${expected.providerName}' identity changed; no provider was removed.`, + ); + } + const removed = await input.adapter.deleteProvider(request); + if (!removed.ok && removed.error.kind === "command" && removed.error.reason === "attached") + return { status: "attached" }; + const after = await input.adapter.getProvider(request); + if (!after.ok && after.error.kind === "command" && after.error.reason === "not_found") { + input.clearAuthority(); + return { status: "retired" }; + } + throw new NativeProviderError( + `Provider '${expected.providerName}' removal was not confirmed; recovery authority retained.`, + ); +} diff --git a/src/lib/inference/selection.ts b/src/lib/inference/selection.ts index 52866ac18bd..e05de053c2a 100644 --- a/src/lib/inference/selection.ts +++ b/src/lib/inference/selection.ts @@ -6,6 +6,26 @@ import { readModelSelectionProvenance, type ModelSelectionProvenance, } from "../domain/telemetry/provenance"; +import { usesNativeLocalInferenceForAgent } from "./native-local/contract"; + +export { normalizeNativeLocalProviderAttachment } from "./native-local/contract"; + +/** Identify an existing local selection that predates sandbox-attached providers. */ +export function hasLegacySharedLocalInferenceRoute(recorded: { + agent?: string | null; + provider?: string | null; + endpointUrl?: string | null; + nativeLocalProviderAttachment?: unknown; +}): boolean { + return ( + recorded.nativeLocalProviderAttachment === undefined && + usesNativeLocalInferenceForAgent( + recorded.agent ?? "openclaw", + recorded.provider, + recorded.endpointUrl, + ) + ); +} export { type ReasoningEffortRequest, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index a0bd185746a..71c89d81899 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -62,7 +62,7 @@ const { ensureOllamaLoopbackSystemdOverride, }: typeof import("./onboard/ollama-systemd") = require("./onboard/ollama-systemd"); const { - createCompatibleEndpointSmoke, + createCompatibleEndpointSmoke: createSmoke, buildCompatibleEndpointSandboxSmokeCommand, buildCompatibleEndpointSandboxSmokeScript, verifyCompatibleEndpointSandboxSmoke, @@ -673,7 +673,7 @@ const { }); const sandboxExec = sandboxCommandCli.createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); -const compatibleSmoke = createCompatibleEndpointSmoke(runOpenshell, sandboxExec, redact); +const compatibleSmoke = createSmoke(runOpenshell, sandboxExec, redact, registry.getSandbox); const { isSandboxReady, parseSandboxStatus, getSandboxStateFromOutputs } = gatewayState; const waitForSandboxReady = sandboxReadinessTracing.createCliSandboxReadyWaiter({ @@ -3206,8 +3206,14 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { getChatUiUrl: () => process.env.CHAT_UI_URL || `http://127.0.0.1:${DASHBOARD_PORT}`, buildVerifyChain: (chatUiUrl, name) => buildAgentVerifyChain(chatUiUrl, name, agent), verifyDeployment: async (name, chain) => { - const recordedSandbox = registry.getSandbox(name); const verifyDeploymentModule: typeof import("./verify-deployment") = require("./verify-deployment"); + const inference = verifyDeploymentModule.onboardInferenceVerificationContext( + name, + GATEWAY_NAME, + agent?.name ?? "openclaw", + liveFinalFlowContext, + registry.getSandbox(name), + ); return verifyDeploymentModule.verifyDeployment( name, chain, @@ -3219,13 +3225,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { providerExistsInGateway: (providerName: string) => providerExistsInGateway(providerName), probeInferenceInvocation: () => - verifyDeploymentModule.probeOnboardInferenceInvocation({ - ...recordedSandbox, - ...liveFinalFlowContext, - sandboxName: name, - gatewayName: GATEWAY_NAME, - agentName: agent?.name, - }), + verifyDeploymentModule.probeOnboardInferenceInvocation(inference.invocation), }, { diagnoseCustomOpenClawRuntime: @@ -3233,7 +3233,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { liveFinalFlowContext.fromDockerfile, agent?.name, ), - inferenceRouteContext: recordedSandbox ?? liveFinalFlowContext, + inferenceRouteContext: inference.route, }, ); }, diff --git a/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts b/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts index f8e392841da..583cfabcd12 100644 --- a/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts +++ b/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import { buildProviderNeutralInferenceSandboxSmokeScript } from "../compatible-endpoint-smoke"; import fs from "node:fs"; import path from "node:path"; @@ -125,3 +126,178 @@ export function runSmokeScript(script: string, tmpDir: string, binDir: string) { }, }); } + +type ProviderNeutralAuthority = NonNullable< + Parameters[1] +>; + +export function providerNeutralResponses( + model: string, + includeToolCall = true, + toolArguments: unknown = "{}", +): unknown[] { + return [ + { model, choices: [{ message: { content: "PONG" } }] }, + { + model, + choices: [ + { + message: { + tool_calls: includeToolCall + ? [ + { + function: { + name: "nemoclaw_route_probe", + arguments: toolArguments, + }, + }, + ] + : [], + }, + }, + ], + }, + ]; +} + +export function runProviderNeutralScript(options: { + authority: ProviderNeutralAuthority; + model?: string; + script?: string; + responses?: unknown[]; + denial?: unknown; + denialBytes?: readonly number[]; + denialOversized?: boolean; + directError?: "connection-refused" | "dns" | "timeout"; + managedProxyResponses?: unknown[]; + inferenceUrl?: string; + expectedAuthorization?: string; + runtimeEnvironment?: NodeJS.ProcessEnv; +}) { + const model = options.model ?? "qwen3.5-9b"; + const directAuthority = `host.openshell.internal:${String(options.authority.directHostPort)}`; + const responses = options.responses ?? providerNeutralResponses(model); + const denial = + options.denial ?? + ({ + error: "policy_denied", + detail: `POST ${directAuthority}/v1/chat/completions not permitted by policy`, + } satisfies Record); + const denialBytes = + options.denialBytes ?? Array.from(Buffer.from(JSON.stringify(denial), "utf8")); + const denialBody = options.denialOversized + ? 'b"x" * 1048577' + : `bytes(${JSON.stringify(denialBytes)})`; + const prelude = ` +import atexit +import errno +import io +import json +import socket +import time +import urllib.error +import urllib.request + +responses = json.loads(${JSON.stringify(JSON.stringify(responses))}) +managed_proxy_responses = json.loads(${JSON.stringify( + JSON.stringify(options.managedProxyResponses ?? []), + )}) +managed_proxy_enabled = ${options.managedProxyResponses === undefined ? "False" : "True"} +denial_bytes = ${denialBody} +inference_request_tokens = [] +direct_request_count = [] +direct_request_urls = [] +managed_proxy_request_count = [] +managed_proxy_request_urls = [] +sleep_delays = [] +direct_error = ${options.directError === undefined ? "None" : JSON.stringify(options.directError)} + +def emit_request_evidence(): + print("INFERENCE_REQUEST_TOKENS=" + ",".join(str(value) for value in inference_request_tokens)) + print("DIRECT_REQUEST_COUNT=" + str(len(direct_request_count))) + print("DIRECT_REQUEST_URLS=" + ",".join(direct_request_urls)) + print("MANAGED_PROXY_REQUEST_COUNT=" + str(len(managed_proxy_request_count))) + print("MANAGED_PROXY_REQUEST_URLS=" + ",".join(managed_proxy_request_urls)) + print("SLEEP_DELAYS=" + ",".join(str(value) for value in sleep_delays)) + +atexit.register(emit_request_evidence) + +class FakeResponse: + def __init__(self, status, payload): + self.status = status + self.payload_source = payload + self.payload = json.dumps(payload).encode("utf-8") + def __enter__(self): + return self + def __exit__(self, exc_type, exc, traceback): + return False + def read(self, size=-1): + if isinstance(self.payload_source, dict) and self.payload_source.get("__oversized__") is True: + return b"x" * (size if size >= 0 else 1048577) + return self.payload if size < 0 else self.payload[:size] + +class FakeOpener: + def open(self, request, timeout): + if request.full_url == ${JSON.stringify(options.inferenceUrl ?? "https://inference.local/v1/chat/completions")}: + assert request.get_header("Authorization") == ${options.expectedAuthorization ? JSON.stringify(options.expectedAuthorization) : "None"} + if not responses: + raise RuntimeError("test response queue exhausted") + request_data = json.loads(request.data.decode("utf-8")) + inference_request_tokens.append( + request_data.get("max_tokens", request_data.get("max_completion_tokens")) + ) + return FakeResponse(200, responses.pop(0)) + direct_request_count.append(1) + direct_request_urls.append(request.full_url) + if direct_error == "connection-refused": + raise urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) + if direct_error == "dns": + raise urllib.error.URLError(socket.gaierror(socket.EAI_NONAME, "not known")) + if direct_error == "timeout": + raise urllib.error.URLError(TimeoutError("timed out")) + raise urllib.error.HTTPError( + request.full_url, + 403, + "Forbidden", + {}, + io.BytesIO(denial_bytes), + ) + +class ManagedProxyOpener: + def open(self, request, timeout): + managed_proxy_request_count.append(1) + managed_proxy_request_urls.append(request.full_url) + if not managed_proxy_responses: + raise urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) + request_data = json.loads(request.data.decode("utf-8")) + inference_request_tokens.append( + request_data.get("max_tokens", request_data.get("max_completion_tokens")) + ) + return FakeResponse(200, managed_proxy_responses.pop(0)) + +def build_test_opener(*handlers): + proxy_disabled = any( + isinstance(handler, urllib.request.ProxyHandler) and handler.proxies == {} + for handler in handlers + ) + if managed_proxy_enabled and not proxy_disabled: + return ManagedProxyOpener() + return FakeOpener() + +urllib.request.build_opener = build_test_opener +time.sleep = lambda seconds: sleep_delays.append(seconds) +`; + const script = + options.script ?? buildProviderNeutralInferenceSandboxSmokeScript(model, options.authority); + return spawnSync("python3", ["-c", `${prelude}\n${script}`], { + encoding: "utf8", + env: + options.managedProxyResponses === undefined + ? { ...process.env, ...options.runtimeEnvironment } + : { + ...process.env, + HTTPS_PROXY: "http://openshell-runtime-proxy.invalid:8080", + NO_PROXY: "", + }, + }); +} diff --git a/src/lib/onboard/compatible-endpoint-smoke-native-selection.test.ts b/src/lib/onboard/compatible-endpoint-smoke-native-selection.test.ts new file mode 100644 index 00000000000..83abda507d2 --- /dev/null +++ b/src/lib/onboard/compatible-endpoint-smoke-native-selection.test.ts @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { nativeLocalIdentity, type NativeLocalBinding } from "../inference/native-local/contract"; +import * as profile from "../inference/native-local/profile"; +import { + createCompatibleEndpointSmoke, + verifyCompatibleEndpointSandboxSmoke, +} from "./compatible-endpoint-smoke"; + +const binding: NativeLocalBinding = { + provider: "vllm-local", + endpointUrl: "http://host.openshell.internal:8000/v1", + gatewayName: "selected", + sandboxName: "alice", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", +}; +const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned", +}; +afterEach(() => vi.restoreAllMocks()); + +function fixture() { + const verification = vi + .spyOn(profile, "verifyNativeLocalProviderAttachment") + .mockRejectedValue(new Error("attachment proof attempted")); + vi.spyOn(console, "log").mockImplementation(() => {}); + const runOpenshell = vi.fn(); + const executor = { runBuffered: vi.fn() }; + const smoke = createCompatibleEndpointSmoke( + runOpenshell, + executor, + (value) => value, + () => ({ name: "alice", provider: "vllm-local", nativeLocalProviderAttachment: receipt }), + ); + return { smoke, verification, runOpenshell, executor }; +} + +describe("native-local smoke selection", () => { + it.each(["onboard", "rebuild"])( + "rejects a mismatched provider during %s before verification", + async (flow) => { + const { smoke, verification, runOpenshell, executor } = fixture(); + const selection = { sandboxName: "alice", provider: "llama-cpp-local", model: "model-a" }; + await expect(async () => + flow === "onboard" + ? smoke.verify(selection) + : smoke.verifyRebuilt({ ...selection, environment: {} }), + ).rejects.toThrow("does not match the selected provider"); + expect(verification).not.toHaveBeenCalled(); + expect(runOpenshell).not.toHaveBeenCalled(); + expect(executor.runBuffered).not.toHaveBeenCalled(); + }, + ); + + it("rejects a mismatched provider for direct smoke callers before verification", async () => { + const { verification, runOpenshell, executor } = fixture(); + await expect( + verifyCompatibleEndpointSandboxSmoke({ + sandboxName: "alice", + provider: "llama-cpp-local", + model: "model-a", + nativeLocalProviderAttachment: receipt, + runOpenshell, + sandboxCommandExecutor: executor, + redact: (value) => value, + }), + ).rejects.toThrow("does not match the selected provider"); + expect(verification).not.toHaveBeenCalled(); + expect(runOpenshell).not.toHaveBeenCalled(); + expect(executor.runBuffered).not.toHaveBeenCalled(); + }); + + it("requires attachment verification for a matching provider", async () => { + const { smoke, verification } = fixture(); + await expect( + smoke.verify({ sandboxName: "alice", provider: "vllm-local", model: "model-a" }), + ).rejects.toThrow("attachment proof attempted"); + expect(verification).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ expected: receipt }), + ); + }); +}); diff --git a/src/lib/onboard/compatible-endpoint-smoke.test.ts b/src/lib/onboard/compatible-endpoint-smoke.test.ts index 39bdc196a24..494df87af8a 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.test.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.test.ts @@ -1,20 +1,28 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; +import { + nativeLocalIdentity, + NATIVE_LOCAL_CREDENTIAL_ENV, + type NativeLocalBinding, +} from "../inference/native-local/contract"; +import * as nativeProfile from "../inference/native-local/profile"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import type { OpenShellSandboxBufferedCommandRequest } from "../adapters/openshell/sandbox-command"; import { + runProviderNeutralScript, + providerNeutralResponses, runSmokeScript, writeFakeCurl, writeFakeSleep, writeSmokeConfig, } from "./__test-helpers__/compatible-endpoint-smoke-helpers"; -vi.mock("../inference/config", () => ({ +vi.mock("../inference/config", async (importOriginal) => ({ + ...(await importOriginal()), INFERENCE_ROUTE_URL: "https://inference.local/v1", MANAGED_PROVIDER_ID: "inference", })); @@ -123,173 +131,6 @@ const allAgentProofAuthorities = [ }, ] as const satisfies readonly { agentName: string; authority: ProviderNeutralAuthority }[]; -function providerNeutralResponses( - model: string, - includeToolCall = true, - toolArguments: unknown = "{}", -): unknown[] { - return [ - { model, choices: [{ message: { content: "PONG" } }] }, - { - model, - choices: [ - { - message: { - tool_calls: includeToolCall - ? [ - { - function: { - name: "nemoclaw_route_probe", - arguments: toolArguments, - }, - }, - ] - : [], - }, - }, - ], - }, - ]; -} - -function runProviderNeutralScript(options: { - authority: ProviderNeutralAuthority; - model?: string; - script?: string; - responses?: unknown[]; - denial?: unknown; - denialBytes?: readonly number[]; - denialOversized?: boolean; - directError?: "connection-refused" | "dns" | "timeout"; - managedProxyResponses?: unknown[]; -}) { - const model = options.model ?? "qwen3.5-9b"; - const directAuthority = `host.openshell.internal:${String(options.authority.directHostPort)}`; - const responses = options.responses ?? providerNeutralResponses(model); - const denial = - options.denial ?? - ({ - error: "policy_denied", - detail: `POST ${directAuthority}/v1/chat/completions not permitted by policy`, - } satisfies Record); - const denialBytes = - options.denialBytes ?? Array.from(Buffer.from(JSON.stringify(denial), "utf8")); - const denialBody = options.denialOversized - ? 'b"x" * 1048577' - : `bytes(${JSON.stringify(denialBytes)})`; - const prelude = ` -import atexit -import errno -import io -import json -import socket -import time -import urllib.error -import urllib.request - -responses = json.loads(${JSON.stringify(JSON.stringify(responses))}) -managed_proxy_responses = json.loads(${JSON.stringify( - JSON.stringify(options.managedProxyResponses ?? []), - )}) -managed_proxy_enabled = ${options.managedProxyResponses === undefined ? "False" : "True"} -denial_bytes = ${denialBody} -inference_request_tokens = [] -direct_request_count = [] -direct_request_urls = [] -managed_proxy_request_count = [] -managed_proxy_request_urls = [] -sleep_delays = [] -direct_error = ${options.directError === undefined ? "None" : JSON.stringify(options.directError)} - -def emit_request_evidence(): - print("INFERENCE_REQUEST_TOKENS=" + ",".join(str(value) for value in inference_request_tokens)) - print("DIRECT_REQUEST_COUNT=" + str(len(direct_request_count))) - print("DIRECT_REQUEST_URLS=" + ",".join(direct_request_urls)) - print("MANAGED_PROXY_REQUEST_COUNT=" + str(len(managed_proxy_request_count))) - print("MANAGED_PROXY_REQUEST_URLS=" + ",".join(managed_proxy_request_urls)) - print("SLEEP_DELAYS=" + ",".join(str(value) for value in sleep_delays)) - -atexit.register(emit_request_evidence) - -class FakeResponse: - def __init__(self, status, payload): - self.status = status - self.payload_source = payload - self.payload = json.dumps(payload).encode("utf-8") - def __enter__(self): - return self - def __exit__(self, exc_type, exc, traceback): - return False - def read(self, size=-1): - if isinstance(self.payload_source, dict) and self.payload_source.get("__oversized__") is True: - return b"x" * (size if size >= 0 else 1048577) - return self.payload if size < 0 else self.payload[:size] - -class FakeOpener: - def open(self, request, timeout): - if request.full_url.startswith("https://inference.local/"): - if not responses: - raise RuntimeError("test response queue exhausted") - request_data = json.loads(request.data.decode("utf-8")) - inference_request_tokens.append( - request_data.get("max_tokens", request_data.get("max_completion_tokens")) - ) - return FakeResponse(200, responses.pop(0)) - direct_request_count.append(1) - direct_request_urls.append(request.full_url) - if direct_error == "connection-refused": - raise urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) - if direct_error == "dns": - raise urllib.error.URLError(socket.gaierror(socket.EAI_NONAME, "not known")) - if direct_error == "timeout": - raise urllib.error.URLError(TimeoutError("timed out")) - raise urllib.error.HTTPError( - request.full_url, - 403, - "Forbidden", - {}, - io.BytesIO(denial_bytes), - ) - -class ManagedProxyOpener: - def open(self, request, timeout): - managed_proxy_request_count.append(1) - managed_proxy_request_urls.append(request.full_url) - if not managed_proxy_responses: - raise urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) - request_data = json.loads(request.data.decode("utf-8")) - inference_request_tokens.append( - request_data.get("max_tokens", request_data.get("max_completion_tokens")) - ) - return FakeResponse(200, managed_proxy_responses.pop(0)) - -def build_test_opener(*handlers): - proxy_disabled = any( - isinstance(handler, urllib.request.ProxyHandler) and handler.proxies == {} - for handler in handlers - ) - if managed_proxy_enabled and not proxy_disabled: - return ManagedProxyOpener() - return FakeOpener() - -urllib.request.build_opener = build_test_opener -time.sleep = lambda seconds: sleep_delays.append(seconds) -`; - const script = - options.script ?? buildProviderNeutralInferenceSandboxSmokeScript(model, options.authority); - return spawnSync("python3", ["-c", `${prelude}\n${script}`], { - encoding: "utf8", - env: - options.managedProxyResponses === undefined - ? process.env - : { - ...process.env, - HTTPS_PROXY: "http://openshell-runtime-proxy.invalid:8080", - NO_PROXY: "", - }, - }); -} - describe("compatible endpoint sandbox smoke helpers", () => { const providerMetadata = (name: string): string => [ @@ -314,7 +155,12 @@ describe("compatible endpoint sandbox smoke helpers", () => { stderr: "", })), }; - const smoke = createCompatibleEndpointSmoke(defaultRun, executor, (value) => value); + const smoke = createCompatibleEndpointSmoke( + defaultRun, + executor, + (value) => value, + () => null, + ); await smoke.verify( { sandboxName: "smoke-sandbox", provider: "compatible-endpoint", model: "baseline" }, scopedRun, @@ -346,6 +192,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { () => ({ status: testCase.status, stdout: providerMetadata("compatible-endpoint") }), executor, (value) => value, + () => null, ); try { await expect( @@ -769,6 +616,46 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(script).not.toContain("curl"); }); + it.each(["v42", `s${"a".repeat(64)}`])( + "preserves issued native credential identity %s in content and tool requests (#12558)", + (identity) => { + const binding: NativeLocalBinding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV, + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "native", + }; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned", + }; + const authority = allAgentProofAuthorities[0].authority; + const result = runProviderNeutralScript({ + authority, + script: buildProviderNeutralInferenceSandboxSmokeScript("qwen3.5-9b", authority, receipt), + inferenceUrl: `${binding.endpointUrl}/chat/completions`, + expectedAuthorization: `Bearer openshell:resolve:env:${identity}_${NATIVE_LOCAL_CREDENTIAL_ENV}`, + runtimeEnvironment: { + [NATIVE_LOCAL_CREDENTIAL_ENV]: `openshell:resolve:env:${identity}_${NATIVE_LOCAL_CREDENTIAL_ENV}`, + }, + denial: { + error: "policy_denied", + detail: "POST host.openshell.internal:11434/v1/nemoclaw-denied not permitted by policy", + }, + }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain("INFERENCE_SMOKE_OK PONG"); + expect(result.stdout).toContain("INFERENCE_REQUEST_TOKENS=512,512"); + expect(result.stdout).toContain( + "DIRECT_REQUEST_URLS=http://host.openshell.internal:11434/v1/nemoclaw-denied", + ); + }, + ); + it.each(allAgentProofAuthorities)( "executes exact model, required tool, and policy-deny proof for $agentName", ({ authority }) => { @@ -1456,3 +1343,85 @@ JSON expect(command).not.toContain("base64.b64decode"); }); }); + +it("reports the native provider identity when a verified lookup subsequently fails (#12558)", async () => { + const binding = { + provider: "vllm-local", + sandboxName: "native", + gatewayName: "nemoclaw", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV, + authMode: "authenticated", + } as const; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-provider-id", + }; + const verification = vi + .spyOn(nativeProfile, "verifyNativeLocalProviderAttachment") + .mockResolvedValue(receipt); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + const runOpenshell = vi.fn().mockReturnValue({ status: 1, stderr: "provider query failed" }); + try { + await expect( + verifyCompatibleEndpointSandboxSmoke({ + sandboxName: "native", + provider: "vllm-local", + model: "model-a", + nativeLocalProviderAttachment: receipt, + runOpenshell, + sandboxCommandExecutor: bufferedExecutorThrough(runOpenshell), + redact: (value) => value, + onFailure: () => { + throw new Error("verification failed"); + }, + }), + ).rejects.toThrow("verification failed"); + const diagnostics = error.mock.calls.flat().join("\n"); + expect(diagnostics).toContain(receipt.providerName); + expect(diagnostics).toContain("Native sandbox inference"); + expect(diagnostics).not.toContain("inference.local"); + expect(diagnostics).not.toContain("Compatible endpoint provider"); + } finally { + verification.mockRestore(); + error.mockRestore(); + log.mockRestore(); + } +}); + +it.each([ + "", + "short", + "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + "openshell:resolve:env:v42_OTHER_KEY", + "openshell:resolve:env:v42_NEMOCLAW_LOCAL_INFERENCE_TOKEN\n", +])("refuses invalid native smoke reference %# without a request", (reference) => { + const binding: NativeLocalBinding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV, + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "native", + }; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned", + }; + const authority = allAgentProofAuthorities[0].authority; + const result = runProviderNeutralScript({ + authority, + script: buildProviderNeutralInferenceSandboxSmokeScript("qwen3.5-9b", authority, receipt), + runtimeEnvironment: { [NATIVE_LOCAL_CREDENTIAL_ENV]: reference }, + }); + expect(result.status).toBe(2); + expect(result.stderr.trim()).toBe( + "Native local inference requires an issued credential reference", + ); + expect(result.stdout).not.toContain("INFERENCE_SMOKE_OK"); +}); diff --git a/src/lib/onboard/compatible-endpoint-smoke.ts b/src/lib/onboard/compatible-endpoint-smoke.ts index e61a4143376..2ae851bfdf5 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -1,12 +1,19 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_LOCAL_RUNTIME_REFERENCE_PATTERN } from "../inference/native-local/agent-config"; +import { verifyNativeLocalProviderAttachment } from "../inference/native-local/profile"; import type { StdioOptions } from "node:child_process"; import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; import { shellQuote } from "../core/shell-quote"; import { compactText } from "../core/url-utils"; -import { INFERENCE_ROUTE_URL, MANAGED_PROVIDER_ID } from "../inference/config"; +import { + INFERENCE_ROUTE_URL, + MANAGED_PROVIDER_ID, + normalizeNativeLocalProviderAttachment, + type NativeLocalProviderAttachment, +} from "../inference/config"; import { resolveMaxTokensField } from "../inference/max-tokens-field"; import type { HostLocalInferenceSandboxProofAuthority } from "./runtime-provider/host-local-inference-routing"; import { @@ -113,6 +120,7 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { agent?: CompatibleEndpointSmokeAgent; /** Force the provider-neutral inference.local proof for any supported agent. */ forceCanonicalRoute?: boolean; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; hostLocalInferenceProofAuthority?: HostLocalInferenceSandboxProofAuthority; /** Recheck sandbox identity after the sandbox proof and before success output. */ beforeSuccess?: () => void; @@ -121,20 +129,32 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { }): Promise { const fail: (exitCode: number) => never = options.onFailure ?? process.exit; const agentName = options.agent?.name || "openclaw"; + const local = normalizeNativeLocalProviderAttachment(options.nativeLocalProviderAttachment); + if (options.nativeLocalProviderAttachment && !local) + throw new Error("Invalid native local inference ownership receipt."); + if (local && local.provider !== options.provider) + throw new Error("Native local inference attachment does not match the selected provider."); if ( + !local && options.forceCanonicalRoute !== true && (agentName !== "openclaw" || options.provider !== "compatible-endpoint") ) { return; } + const forceCanonicalRoute = options.forceCanonicalRoute === true || Boolean(local); + const providerName = local?.providerName ?? options.provider; console.log( - options.forceCanonicalRoute - ? " Verifying provider-neutral inference through the sandbox runtime..." - : " Verifying compatible endpoint through the sandbox runtime...", + local + ? " Verifying native local inference through the sandbox runtime..." + : forceCanonicalRoute + ? " Verifying provider-neutral inference through the sandbox runtime..." + : " Verifying compatible endpoint through the sandbox runtime...", ); - const target = { kind: "selected" } as const; + const target = local + ? { kind: "named" as const, gatewayName: local.gatewayName } + : { kind: "selected" as const }; const adapter = createCliOpenShellProviderAdapter({ run: (command, runOptions) => { const result = options.runOpenshell(command, runOptions); @@ -151,22 +171,33 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { }; }, }); + if (local) + await verifyNativeLocalProviderAttachment({ + adapter, + sandboxName: options.sandboxName, + expected: local, + }); const providerResult = await adapter.getProvider({ target, - providerName: options.provider, + providerName: local?.providerName ?? options.provider, }); if (!providerResult.ok) { console.error( - options.forceCanonicalRoute - ? ` Provider-neutral inference provider '${options.provider}' is missing or unreachable in the OpenShell gateway.` + forceCanonicalRoute + ? ` Provider-neutral inference provider '${providerName}' is missing or unreachable in the OpenShell gateway.` : ` Compatible endpoint provider '${options.provider}' is missing from the OpenShell gateway.`, ); - console.error(" The sandbox inference.local route cannot reach the selected model provider."); + console.error( + local + ? " Native sandbox inference cannot reach the selected model provider." + : " The sandbox inference.local route cannot reach the selected model provider.", + ); console.error(` ${compactText(options.redact(providerResult.error.message)).slice(0, 800)}`); fail(1); } if ( + !local && options.credentialEnv && !providerResult.value.credentialKeys.includes(options.credentialEnv) ) { @@ -175,11 +206,11 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { ); } - const forceCanonicalRoute = options.forceCanonicalRoute === true; const script = forceCanonicalRoute ? buildProviderNeutralInferenceSandboxSmokeScript( options.model, options.hostLocalInferenceProofAuthority, + local, ) : buildCompatibleEndpointSandboxSmokeCommand(options.model); const smokeResult = await options.sandboxCommandExecutor.runBuffered({ @@ -195,11 +226,11 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { if (smokeStatus !== 0 || !/INFERENCE_SMOKE_OK/.test(smokeOutput)) { console.error( - options.forceCanonicalRoute + forceCanonicalRoute ? " Provider-neutral sandbox inference smoke check failed." : " Compatible endpoint sandbox smoke check failed.", ); - if (!options.forceCanonicalRoute) { + if (!forceCanonicalRoute) { console.error( " Messaging setup is not the root cause; the sandbox inference.local route failed.", ); @@ -210,9 +241,11 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { options.beforeSuccess?.(); console.log( - options.forceCanonicalRoute - ? " \u2713 Provider responds through inference.local inside the sandbox" - : " \u2713 Compatible endpoint responds through inference.local inside the sandbox", + local + ? " \u2713 Native local inference responds inside the sandbox" + : options.forceCanonicalRoute + ? " \u2713 Provider responds through inference.local inside the sandbox" + : " \u2713 Compatible endpoint responds through inference.local inside the sandbox", ); } @@ -224,8 +257,21 @@ export function createCompatibleEndpointSmoke( ) => ReturnType, sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor, redact: (value: string) => string, + getSandbox: typeof import("../state/registry").getSandbox, ) { type SmokeOptions = Parameters[0]; + const nativeSelection = ( + options: Pick, + ) => { + const recorded = getSandbox(options.sandboxName)?.nativeLocalProviderAttachment; + if (recorded === undefined) return {}; + const receipt = normalizeNativeLocalProviderAttachment(recorded); + if (!receipt) + throw new Error( + "Native local inference requires its recorded provider attachment. Recreate this beta sandbox.", + ); + return { nativeLocalProviderAttachment: receipt }; + }; return { verify( options: Omit, @@ -233,6 +279,7 @@ export function createCompatibleEndpointSmoke( ): Promise { return verifyCompatibleEndpointSandboxSmoke({ ...options, + ...nativeSelection(options), runOpenshell: run, sandboxCommandExecutor, redact, @@ -250,6 +297,7 @@ export function createCompatibleEndpointSmoke( const { environment, gatewayName, ...selection } = options; return verifyCompatibleEndpointSandboxSmoke({ ...selection, + ...nativeSelection(selection), onFailure: (exitCode) => { throw new Error(`Compatible endpoint verification failed (exit ${exitCode}).`); }, @@ -502,12 +550,12 @@ export function buildCompatibleEndpointSandboxSmokeCommand(model: string): strin /** * Runs a Python standard-library request inside the sandbox, proving a real - * chat response through inference.local and explicit policy denial for the - * selected direct host-native inference port that would bypass the gateway. + * chat response through the selected endpoint and explicit denial outside its policy. */ export function buildProviderNeutralInferenceSandboxSmokeScript( model: string, authority: HostLocalInferenceSandboxProofAuthority | undefined, + local?: NativeLocalProviderAttachment, ): string { const expectedHealthPath = authority?.service === "ollama" @@ -518,37 +566,52 @@ export function buildProviderNeutralInferenceSandboxSmokeScript( ? "/health" : null; if ( - !authority || - !Number.isSafeInteger(authority.directHostPort) || - authority.directHostPort < 1 || - authority.directHostPort > 65_535 || - authority.directHealthPath !== expectedHealthPath + !local && + (!authority || + !Number.isSafeInteger(authority.directHostPort) || + authority.directHostPort < 1 || + authority.directHostPort > 65_535 || + authority.directHealthPath !== expectedHealthPath) ) { throw new Error("Provider-neutral sandbox smoke requires exact provider health authority."); } - const inferenceUrl = JSON.stringify(`${INFERENCE_ROUTE_URL}/chat/completions`); + const endpointLabel = local ? "Native local inference" : "inference.local"; + const inferenceUrl = JSON.stringify( + `${local?.endpointUrl ?? INFERENCE_ROUTE_URL}/chat/completions`, + ); const maxTokensField = JSON.stringify(resolveMaxTokensField(model)); const modelValue = JSON.stringify(model); - const toolCallingRequired = authority.toolCallingRequired ? "True" : "False"; - const directAuthority = `${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.host}:${String( - authority.directHostPort, - )}`; - const directUrl = JSON.stringify( - `http://${directAuthority}${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.path}`, - ); + const toolCallingRequired = authority?.toolCallingRequired ? "True" : "False"; + const directAuthority = local + ? new URL(local.endpointUrl).host + : `${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.host}:${String(authority!.directHostPort)}`; + const deniedPath = local + ? `${new URL(local.endpointUrl).pathname}/nemoclaw-denied` + : OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.path; + const directUrl = JSON.stringify(`http://${directAuthority}${deniedPath}`); const directMethod = JSON.stringify(OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.method); const directDenialError = JSON.stringify(OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.error); const directDenialDetail = JSON.stringify( - `${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.method} ${directAuthority}${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.path} ${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.detailSuffix}`, + `${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.method} ${directAuthority}${deniedPath} ${OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.detailSuffix}`, ); + const authSetup = local + ? `credential = os.environ.get("NEMOCLAW_LOCAL_INFERENCE_TOKEN", "") +if not re.fullmatch(${JSON.stringify(NATIVE_LOCAL_RUNTIME_REFERENCE_PATTERN)}, credential): + print("Native local inference requires an issued credential reference", file=sys.stderr) + sys.exit(2) +auth_headers = {"Authorization": "Bearer " + credential}` + : "auth_headers = {}"; return ` import errno import json +import os +import re import sys import time import urllib.error import urllib.request +${authSetup} inference_url = ${inferenceUrl} model = ${modelValue} max_tokens_field = ${maxTokensField} @@ -561,7 +624,7 @@ def post_inference(payload, label): request = urllib.request.Request( inference_url, data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json"}, + headers={"Content-Type": "application/json", **auth_headers}, method="POST", ) response_data = None @@ -569,31 +632,31 @@ def post_inference(payload, label): try: with inference_opener.open(request, timeout=60) as response: if response.status < 200 or response.status > 299: - raise RuntimeError("inference.local returned HTTP %s" % response.status) + raise RuntimeError("${endpointLabel} returned HTTP %s" % response.status) response_bytes = response.read(max_response_bytes + 1) if len(response_bytes) > max_response_bytes: - print("inference.local %s proof response exceeded byte limit" % label, file=sys.stderr) + print("${endpointLabel} %s proof response exceeded byte limit" % label, file=sys.stderr) sys.exit(1) try: response_data = json.loads(response_bytes.decode("utf-8", errors="strict")) except (UnicodeDecodeError, json.JSONDecodeError): - print("inference.local %s proof returned invalid JSON" % label, file=sys.stderr) + print("${endpointLabel} %s proof returned invalid JSON" % label, file=sys.stderr) sys.exit(1) break except urllib.error.HTTPError as error: if 500 <= error.code <= 599 and attempt < 2: time.sleep(5 * (attempt + 1)) continue - print("inference.local %s proof returned terminal HTTP %s" % (label, error.code), file=sys.stderr) + print("${endpointLabel} %s proof returned terminal HTTP %s" % (label, error.code), file=sys.stderr) sys.exit(1) except urllib.error.URLError: if attempt < 2: time.sleep(5 * (attempt + 1)) continue - print("inference.local %s proof transport failed after bounded retries" % label, file=sys.stderr) + print("${endpointLabel} %s proof transport failed after bounded retries" % label, file=sys.stderr) sys.exit(1) if not isinstance(response_data, dict) or response_data.get("model") != model: - print("inference.local %s proof returned a different model identity" % label, file=sys.stderr) + print("${endpointLabel} %s proof returned a different model identity" % label, file=sys.stderr) sys.exit(1) return response_data @@ -629,7 +692,7 @@ def classify_content_shape(data): content_shape, content, retry_reasoning = classify_content_shape(response_data) if retry_reasoning: print( - "inference.local content proof returned REASONING_ONLY at the initial token limit; retrying once with a larger content budget", + "${endpointLabel} content proof returned REASONING_ONLY at the initial token limit; retrying once with a larger content budget", file=sys.stderr, ) response_data = post_inference({ @@ -639,7 +702,7 @@ if retry_reasoning: }, "content") content_shape, content, _ = classify_content_shape(response_data) if not isinstance(content, str) or not content.strip(): - print("inference.local content proof failed: %s" % content_shape, file=sys.stderr) + print("${endpointLabel} content proof failed: %s" % content_shape, file=sys.stderr) sys.exit(1) if tool_calling_required: @@ -664,7 +727,7 @@ if tool_calling_required: tool_calls = tool_message.get("tool_calls") matching_call = next((call for call in tool_calls if isinstance(call, dict) and isinstance(call.get("function"), dict) and call["function"].get("name") == tool_name), None) if isinstance(tool_calls, list) else None if matching_call is None: - print("inference.local tool proof did not return the required tool call", file=sys.stderr) + print("${endpointLabel} tool proof did not return the required tool call", file=sys.stderr) sys.exit(1) arguments = matching_call["function"].get("arguments") try: @@ -672,7 +735,7 @@ if tool_calling_required: except json.JSONDecodeError: decoded_arguments = None if not isinstance(decoded_arguments, dict) or decoded_arguments: - print("inference.local tool proof returned invalid tool arguments", file=sys.stderr) + print("${endpointLabel} tool proof returned invalid tool arguments", file=sys.stderr) sys.exit(1) direct_url = ${directUrl} diff --git a/src/lib/onboard/created-sandbox-completion-selection.test.ts b/src/lib/onboard/created-sandbox-completion-selection.test.ts new file mode 100644 index 00000000000..4393d5c0e32 --- /dev/null +++ b/src/lib/onboard/created-sandbox-completion-selection.test.ts @@ -0,0 +1,255 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { nativeLocalIdentity } from "../inference/native-local/contract"; +import { createOnboardCreatedSandboxCompletion } from "./created-sandbox-finalization"; +import type { SandboxGpuCreateFlowResult } from "./sandbox-gpu-create-flow"; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("created sandbox completion inference selection", () => { + it.each([ + { + label: "mismatched hosted identity", + provider: "compatible-endpoint", + endpointUrl: "https://openrouter.ai/api/v1", + attached: false, + liveEndpoint: "https://inference.local/v1", + reachesRegistration: false, + }, + { + label: "authenticated local receipt", + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + attached: true, + liveEndpoint: "http://host.openshell.internal:8000/v1", + reachesRegistration: true, + }, + { + label: "credentialless local receipt", + provider: "vllm-local", + endpointUrl: null, + attached: true, + liveEndpoint: "http://host.openshell.internal:8000/v1", + reachesRegistration: true, + }, + { + label: "local receipt over a stale endpoint", + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:11436/v1", + attached: true, + liveEndpoint: "http://host.openshell.internal:8000/v1", + reachesRegistration: true, + }, + { + label: "shared route without a local receipt", + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + attached: false, + liveEndpoint: "https://inference.local/v1", + reachesRegistration: true, + }, + { + label: "direct route without a local receipt", + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + attached: false, + liveEndpoint: "http://host.openshell.internal:8000/v1", + reachesRegistration: false, + }, + { + label: "shared route with a local receipt", + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + attached: true, + liveEndpoint: "https://inference.local/v1", + reachesRegistration: false, + }, + ])( + "validates $label through the production completion constructor (#12975)", + async ({ provider, endpointUrl, attached, liveEndpoint, reachesRegistration }) => { + const model = "nvidia/nemotron-3-ultra-550b-a55b"; + const verifiedCreateBoundary = { + sandboxName: "dcode", + gatewayName: "nemoclaw", + gatewayPort: 8080, + lifecycleGeneration: "generation-1", + lifecycleLiveIdentityFingerprint: "a".repeat(64), + route: "native" as const, + }; + const getVerifiedCreateRegistrationAuthority = vi.fn(() => { + // Stop at the publication boundary after the real identity reader accepts the route. + throw new Error("registration reached"); + }); + const localBinding = { + provider: provider as "compatible-endpoint" | "vllm-local", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: provider === "vllm-local" ? ("sentinel" as const) : ("authenticated" as const), + gatewayName: "nemoclaw", + sandboxName: "dcode", + }; + const nativeLocalProviderAttachment = attached + ? { + ...localBinding, + ...nativeLocalIdentity(localBinding), + schemaVersion: 1 as const, + providerId: "selected-provider-id", + } + : undefined; + const runCaptureOpenshell = vi.fn(() => + [ + "Sandbox: dcode", + "Route: inference", + `Provider: ${provider}`, + `Model: openai:${model}`, + `Endpoint: ${liveEndpoint}`, + "Runtime: Deep Agents Code (terminal)", + ].join("\n"), + ); + const runBuffered = vi.fn(async () => ({ + outcome: { kind: "completed" as const, exitCode: 0 }, + stdout: runCaptureOpenshell(), + stderr: "", + })); + vi.spyOn(process, "exit").mockImplementation((code): never => { + throw new Error(`exit ${code}`); + }); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + const completionArgs = [ + "dcode", + null, + null, + null, + null, + { customOpenClawImage: false, isManagedDcodeAgent: true }, + { + provider, + model, + preferredInferenceApi: "openai-completions", + endpointUrl, + }, + { + createIntent: { + endpointUrl, + endpointSource: null, + observabilityEnabled: false, + }, + resolvedCreateIntent: { + policy: { options: {} }, + hostMounts: undefined, + nativeLocalProviderAttachment, + }, + }, + { + gpuEnabled: false, + hostGpuDetected: false, + sandboxGpuEnabled: false, + sandboxGpuMode: "none", + sandboxGpuDevice: null, + sandboxGpuProof: null, + openshellDriver: "docker", + openshellVersion: "0.0.101", + }, + false, + { toolDisclosure: undefined, dcodeAutoApprovalMode: "disabled" }, + { webSearchConfig: null, hermesAuthMethod: null }, + { + plannedMessagingState: undefined, + preservedMcpState: undefined, + hermesToolGateways: [], + }, + null, + { gatewayName: "nemoclaw", gatewayPort: 8080 }, + { + initialSandboxPolicy: { + appliedPresets: ["personal-open-internet"], + policyPath: "/private/initial-policy.yaml", + }, + compatibilityPolicyPath: null, + dashboardRemoteBindPrepared: false, + getVerifiedCreateBoundary: () => verifiedCreateBoundary, + getVerifiedCreateRegistrationAuthority, + revalidateSandboxIdentity: vi.fn(), + }, + null, + "build-1", + { + mode: "none", + hostGpuDetected: false, + hostGpuPlatform: "linux", + sandboxGpuEnabled: false, + sandboxGpuDevice: null, + errors: [], + }, + false, + vi.fn(), + runCaptureOpenshell, + "http://127.0.0.1:8643", + { config: null, enabled: false }, + vi.fn(), + vi.fn(), + vi.fn(), + { + runtimeProvider: null, + ensurePreparedWorkload: vi.fn(), + ensurePreparedProfile: vi.fn(), + }, + { + source: { + kind: "legacy-dockerfile", + dockerfilePath: "/workspace/Dockerfile", + reason: "agent-not-managed", + }, + release: null, + fallbackDiagnostic: null, + }, + vi.fn(), + { runBuffered }, + ] as unknown as Parameters; + const completion = createOnboardCreatedSandboxCompletion(...completionArgs); + const created = { + createResult: { status: 0, output: "", sawProgress: true }, + route: "native", + firstCreateOutput: "", + registryImageRef: null, + lifecycleRegistrationFields: { lifecycleGeneration: "generation-1" }, + } as SandboxGpuCreateFlowResult; + const lifecycleLiveIdentityFingerprint = "a".repeat(64); + const lifecycle = { + generation: "generation-1", + recordExactIdentity: () => ({ + lifecycleGeneration: "generation-1", + lifecycleLiveIdentityFingerprint, + }), + capture: () => ({ + lifecycleGeneration: "generation-1", + lifecycleLiveIdentityFingerprint, + }), + revalidate: (registration: { + lifecycleGeneration: string; + lifecycleLiveIdentityFingerprint: string; + }) => registration, + }; + + await expect( + completion.complete( + created, + null, + "disabled", + false, + () => ({ lifecycleGeneration: "generation-1" }), + lifecycle, + ), + ).rejects.toThrow(reachesRegistration ? "registration reached" : "exit 1"); + expect(getVerifiedCreateRegistrationAuthority).toHaveBeenCalledTimes( + reachesRegistration ? 1 : 0, + ); + expect(runBuffered).toHaveBeenCalledOnce(); + }, + ); +}); diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index bb53dd96623..9e9810f851d 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -10,6 +10,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as restoreWindow from "../actions/sandbox/runtime/openclaw-lifecycle"; +import { nativeLocalIdentity } from "../inference/native-local/contract"; import type { SandboxEntry } from "../state/registry"; import type { QualifiedSandboxInferenceRouteReservation } from "../state/registry/route-reservation"; import * as sandboxState from "../state/sandbox"; @@ -474,169 +475,6 @@ describe("created DCode sandbox finalization", () => { }, ); - it("passes the fresh create endpoint through the production completion constructor (#9555)", async () => { - const endpointUrl = "https://openrouter.ai/api/v1"; - const model = "nvidia/nemotron-3-ultra-550b-a55b"; - const verifiedCreateBoundary = { - sandboxName: "dcode", - gatewayName: "nemoclaw", - gatewayPort: 8080, - lifecycleGeneration: "generation-1", - lifecycleLiveIdentityFingerprint: "a".repeat(64), - route: "native" as const, - }; - const verifiedCreate = { - reservation: {} as never, - checkpoint: pendingSandboxCreateIdentityForBoundary(verifiedCreateBoundary), - } as NonNullable; - const runCaptureOpenshell = vi.fn(() => - [ - "Sandbox: dcode", - "Route: inference", - "Provider: compatible-endpoint", - `Model: openai:${model}`, - "Endpoint: https://inference.local/v1", - "Runtime: Deep Agents Code (terminal)", - ].join("\n"), - ); - const runBuffered = vi.fn(async () => ({ - outcome: { kind: "completed" as const, exitCode: 0 }, - stdout: runCaptureOpenshell(), - stderr: "", - })); - vi.spyOn(process, "exit").mockImplementation((code): never => { - throw new Error(`exit ${code}`); - }); - vi.spyOn(console, "error").mockImplementation(() => undefined); - - const completionArgs = [ - "dcode", - null, - null, - null, - null, - { customOpenClawImage: false, isManagedDcodeAgent: true }, - { - provider: "compatible-endpoint", - model, - preferredInferenceApi: "openai-completions", - endpointUrl, - }, - { - createIntent: { - endpointUrl, - endpointSource: null, - observabilityEnabled: false, - }, - resolvedCreateIntent: { - policy: { options: {} }, - hostMounts: undefined, - }, - }, - { - gpuEnabled: false, - hostGpuDetected: false, - sandboxGpuEnabled: false, - sandboxGpuMode: "none", - sandboxGpuDevice: null, - sandboxGpuProof: null, - openshellDriver: "docker", - openshellVersion: "0.0.101", - }, - false, - { toolDisclosure: undefined, dcodeAutoApprovalMode: "disabled" }, - { webSearchConfig: null, hermesAuthMethod: null }, - { - plannedMessagingState: undefined, - preservedMcpState: undefined, - hermesToolGateways: [], - }, - null, - { gatewayName: "nemoclaw", gatewayPort: 8080 }, - { - initialSandboxPolicy: { - appliedPresets: ["personal-open-internet"], - policyPath: "/private/initial-policy.yaml", - }, - compatibilityPolicyPath: null, - dashboardRemoteBindPrepared: false, - getVerifiedCreateBoundary: () => verifiedCreateBoundary, - getVerifiedCreateRegistrationAuthority: () => verifiedCreate, - revalidateSandboxIdentity: vi.fn(), - }, - null, - "build-1", - { - mode: "none", - hostGpuDetected: false, - hostGpuPlatform: "linux", - sandboxGpuEnabled: false, - sandboxGpuDevice: null, - errors: [], - }, - false, - vi.fn(), - runCaptureOpenshell, - "http://127.0.0.1:8643", - { config: null, enabled: false }, - vi.fn(), - vi.fn(), - vi.fn(), - { - runtimeProvider: null, - ensurePreparedWorkload: vi.fn(), - ensurePreparedProfile: vi.fn(), - }, - { - source: { - kind: "legacy-dockerfile", - dockerfilePath: "/workspace/Dockerfile", - reason: "agent-not-managed", - }, - release: null, - fallbackDiagnostic: null, - }, - vi.fn(), - { runBuffered }, - ] as unknown as Parameters; - const completion = createOnboardCreatedSandboxCompletion(...completionArgs); - const created = { - createResult: { status: 0, output: "", sawProgress: true }, - route: "native", - firstCreateOutput: "", - registryImageRef: null, - lifecycleRegistrationFields: { lifecycleGeneration: "generation-1" }, - } as SandboxGpuCreateFlowResult; - const lifecycleLiveIdentityFingerprint = "a".repeat(64); - const lifecycle = { - generation: "generation-1", - recordExactIdentity: () => ({ - lifecycleGeneration: "generation-1", - lifecycleLiveIdentityFingerprint, - }), - capture: () => ({ - lifecycleGeneration: "generation-1", - lifecycleLiveIdentityFingerprint, - }), - revalidate: (registration: { - lifecycleGeneration: string; - lifecycleLiveIdentityFingerprint: string; - }) => registration, - }; - - await expect( - completion.complete( - created, - null, - "disabled", - false, - () => ({ lifecycleGeneration: "generation-1" }), - lifecycle, - ), - ).rejects.toThrow("exit 1"); - expect(runBuffered).toHaveBeenCalledOnce(); - }); - it("does not publish registry metadata when live validation fails (#6311)", async () => { const register = vi.fn(); const error = vi.fn(); @@ -1141,9 +979,26 @@ describe("created sandbox completion actions", () => { sandboxGpuDevice: null, errors: [], }; + const binding = { + provider: "ollama-local" as const, + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated" as const, + gatewayName: "nemoclaw", + sandboxName: "hermes", + }; + const nativeLocalProviderAttachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "selected-provider-id", + }; + const retireNativeLocalProviders = vi.fn(async () => { + order.push("retire-providers"); + }); const registerCreatedSandbox = vi.fn((input: CreatedSandboxRegistrationInput) => { order.push("registry"); - return input as unknown as SandboxEntry; + return { ...input, nativeLocalProviderAttachment } as unknown as SandboxEntry; }); const initialOpenShellGpuDiagnostics = { collect: vi.fn(() => []) }; const receiptOpenShellGpuDiagnostics = { collect: vi.fn(() => []) }; @@ -1293,6 +1148,7 @@ describe("created sandbox completion actions", () => { throw new Error(`unexpected exit ${code}`); }, registerCreatedSandbox, + retireNativeLocalProviders, }, ); const created = { @@ -1349,7 +1205,15 @@ describe("created sandbox completion actions", () => { ...(schema5 ? [] : ["workload"]), "lifecycle-revalidate", "registry", + "retire-providers", ]); + expect(retireNativeLocalProviders).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + sandboxName: "hermes", + gatewayName: "nemoclaw", + selected: nativeLocalProviderAttachment, + }), + ); expect(gpuConfig.sandboxGpuProof).toEqual(gpuProof); expect(verifyHermesGpu).toHaveBeenCalledWith( gpuConfig, @@ -1378,6 +1242,7 @@ describe("created sandbox completion actions", () => { const proofFailure = new Error("Hermes GPU proof failed"); verifyHermesGpu.mockRejectedValueOnce(proofFailure); registerCreatedSandbox.mockClear(); + retireNativeLocalProviders.mockClear(); await expect( completion.complete( schema5 ? null : created, @@ -1390,111 +1255,41 @@ describe("created sandbox completion actions", () => { ), ).rejects.toBe(proofFailure); expect(registerCreatedSandbox).not.toHaveBeenCalled(); - }, - ); -}); - -describe("restored OpenClaw selection reconciliation", () => { - const options = { - sandboxName: "openclaw", - gatewayName: "nemoclaw-9090", - restoreBackupPath: "/tmp/managed-openclaw-backup", - preUpgradeBackup: false, - targetAgentType: "openclaw", - validateManagedDcode: false, - provider: "compatible-endpoint", - model: "changed-model", - preferredInferenceApi: null, - reconcileOpenClawInference: true, - }; - - function deps(order: string[]) { - return { - ...preparedRestoreAuthority("openclaw"), - restoreRecreatedSandboxState: async () => { - order.push("restore"); - return { - success: true, - restoredDirs: ["."], - restoredFiles: [], - failedDirs: [], - failedFiles: [], - }; - }, - writeRestoredOpenclawInferenceRoute: vi.fn(async () => { - order.push("selection"); - }), - getDcodeSelectionDrift: vi.fn(), - register: vi.fn(() => { - order.push("register"); - }), - note: vi.fn(), - error: vi.fn(), - exitProcess: (code: number): never => { - throw new Error(`unexpected exit ${code}`); - }, - }; - } + expect(retireNativeLocalProviders).not.toHaveBeenCalled(); - it("applies the selected model after restore and before restart and publication (#12667)", async () => { - const order: string[] = []; - const dependencies = deps(order); - vi.mocked(restoreWindow.finishUnregisteredOpenClawPostRestoreDoctor).mockImplementation( - async () => { - order.push("restart"); - return { ok: true }; - }, - ); - await finalizeCreatedSandbox(options, dependencies); - expect(order).toEqual(["restore", "selection", "restart", "register"]); - expect(dependencies.writeRestoredOpenclawInferenceRoute).toHaveBeenCalledExactlyOnceWith( - "openclaw", - "changed-model", - "compatible-endpoint", - null, - "nemoclaw-9090", - undefined, - { endpointUrl: undefined, nativeProvider: false }, - ); - }); + const cleanupFailure = new Error("Provider absence was not confirmed; authority retained"); + retireNativeLocalProviders.mockRejectedValueOnce(cleanupFailure); + await expect( + completion.complete( + schema5 ? null : created, + configuredReceipt, + "hermes", + manageDashboard, + () => ({ lifecycleGeneration: "generation-1" }), + lifecycle, + schema5 ? inferenceRouteReservation : undefined, + ), + ).rejects.toBe(cleanupFailure); + expect(registerCreatedSandbox).toHaveBeenCalledOnce(); + expect(retireNativeLocalProviders).toHaveBeenCalledOnce(); - it.each([ - { - label: "ordinary rebuild", - patch: { reconcileOpenClawInference: false, preUpgradeBackup: true }, + const registrationFailure = new Error("Registry publication outcome is uncertain"); + registerCreatedSandbox.mockImplementationOnce(() => { + throw registrationFailure; + }); + retireNativeLocalProviders.mockClear(); + await expect( + completion.complete( + schema5 ? null : created, + configuredReceipt, + "hermes", + manageDashboard, + () => ({ lifecycleGeneration: "generation-1" }), + lifecycle, + schema5 ? inferenceRouteReservation : undefined, + ), + ).rejects.toBe(registrationFailure); + expect(retireNativeLocalProviders).not.toHaveBeenCalled(); }, - { label: "custom image", patch: { customImage: true } }, - { label: "fresh creation", patch: { restoreBackupPath: null } }, - ])("preserves $label native configuration (#12667)", async ({ patch }) => { - const dependencies = deps([]); - await finalizeCreatedSandbox({ ...options, ...patch }, dependencies); - expect(dependencies.writeRestoredOpenclawInferenceRoute).not.toHaveBeenCalled(); - expect(dependencies.register).toHaveBeenCalledOnce(); - }); - - it("refuses reconciliation when the prepared runtime identity changes (#12667)", async () => { - const dependencies = deps([]); - dependencies.revalidatePreparedRegistration = () => { - throw new Error("runtime identity changed"); - }; - await expect(finalizeCreatedSandbox(options, dependencies)).rejects.toThrow( - "runtime identity changed", - ); - expect(dependencies.writeRestoredOpenclawInferenceRoute).not.toHaveBeenCalled(); - expect(dependencies.register).not.toHaveBeenCalled(); - expect(restoreWindow.abortUnregisteredOpenClawPostRestoreDoctor).toHaveBeenCalledOnce(); - }); - - it("aborts the offline window without publishing when reconciliation fails (#12667)", async () => { - const dependencies = deps([]); - dependencies.writeRestoredOpenclawInferenceRoute.mockRejectedValue( - new Error("native write failed"), - ); - await expect(finalizeCreatedSandbox(options, dependencies)).rejects.toThrow( - "native write failed", - ); - expect(dependencies.register).not.toHaveBeenCalled(); - expect(restoreWindow.finishUnregisteredOpenClawPostRestoreDoctor).not.toHaveBeenCalled(); - expect(restoreWindow.abortUnregisteredOpenClawPostRestoreDoctor).toHaveBeenCalledOnce(); - }); + ); }); diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index 37ba5316739..461af5beaec 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -4,6 +4,8 @@ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; +import type { retireUnselectedNativeLocalProviders } from "../inference/native-local/selection"; + import { restoreRecreatedSandboxStateWithManagedAuthority } from "../actions/sandbox/snapshot/restore-authority"; import { hermesDashboardStateMigrationRecoveryGuidance, @@ -28,6 +30,7 @@ import { type RestoreResult, } from "../state/sandbox"; import { cliName } from "./branding"; +import { retireUnselectedCreatedSandboxProviders } from "./sandbox-create/provider-retirement"; import { writeRestoredOpenclawInferenceRoute } from "./openclaw/initial-inference-route"; import { createDcodeSelectionDriftReader } from "./dcode-selection-drift"; import { restoreDefaultAfterRecreate } from "./default-preservation"; @@ -174,6 +177,7 @@ export interface CreatedSandboxCompletionDeps extends Omit< CreatedSandboxFinalizationDeps, "prepareRegistration" | "register" | "revalidatePreparedRegistration" > { + readonly retireNativeLocalProviders?: typeof retireUnselectedNativeLocalProviders; readonly prepareCreatedSandboxRegistration?: typeof prepareCreatedSandboxRegistration; readonly registerCreatedSandbox?: typeof registerCreatedSandbox; readonly registerPreparedCreatedSandbox?: typeof registerPreparedCreatedSandbox; @@ -553,12 +557,23 @@ export function createCreatedSandboxCompletionActions( )(await registrationInput(true), prepared), register: async (prepared) => { const input = await registrationInput(prepared !== undefined); - return prepared + const registered = prepared ? (deps.registerPreparedCreatedSandbox ?? registerPreparedCreatedSandbox)( input, prepared, ) : (deps.registerCreatedSandbox ?? registerCreatedSandbox)(input); + // Reservation is too early: the former sandbox may still need its provider. + // Retirement failure retains the committed selection and cleanup authority. + await retireUnselectedCreatedSandboxProviders( + { + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + selected: registered.nativeLocalProviderAttachment, + }, + deps.retireNativeLocalProviders, + ); + return registered; }, }, ); @@ -605,6 +620,7 @@ type OnboardCreateIntent = { readonly observabilityEnabled?: boolean; } | null; type OnboardResolvedCreateIntent = { + readonly nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; readonly nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; readonly nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; readonly policy: { @@ -759,8 +775,9 @@ export function createOnboardCreatedSandboxCompletion( provider, model, preferredInferenceApi, - endpointUrl, + endpointUrl: resolvedCreateIntent.nativeLocalProviderAttachment?.endpointUrl ?? endpointUrl, nativeProvider: Boolean( + resolvedCreateIntent.nativeLocalProviderAttachment || resolvedCreateIntent.nativeHostedProviderAttachment || resolvedCreateIntent.nativeNvidiaProviderAttachment, ), diff --git a/src/lib/onboard/created-sandbox-restored-openclaw-selection.test.ts b/src/lib/onboard/created-sandbox-restored-openclaw-selection.test.ts new file mode 100644 index 00000000000..91a9505f381 --- /dev/null +++ b/src/lib/onboard/created-sandbox-restored-openclaw-selection.test.ts @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import * as restoreWindow from "../actions/sandbox/runtime/openclaw-lifecycle"; +import type { SandboxEntry } from "../state/registry"; +import { finalizeCreatedSandbox } from "./created-sandbox-finalization"; + +beforeEach(() => { + vi.spyOn(restoreWindow, "beginUnregisteredOpenClawBackupQuiesce").mockResolvedValue({ + ok: true, + window: { sandboxName: "spark-box", kind: "backup" }, + }); + vi.spyOn(restoreWindow, "finishUnregisteredOpenClawPostRestoreDoctor").mockResolvedValue({ + ok: true, + }); + vi.spyOn(restoreWindow, "abortUnregisteredOpenClawPostRestoreDoctor").mockResolvedValue({ + ok: true, + }); +}); + +afterEach(() => vi.restoreAllMocks()); + +function preparedRestoreAuthority(sandboxName: string) { + const prepared = { name: sandboxName } as SandboxEntry; + return { + prepareRegistration: () => prepared, + revalidatePreparedRegistration: (target: SandboxEntry) => target, + }; +} + +describe("restored OpenClaw selection reconciliation", () => { + const options = { + sandboxName: "openclaw", + gatewayName: "nemoclaw-9090", + restoreBackupPath: "/tmp/managed-openclaw-backup", + preUpgradeBackup: false, + targetAgentType: "openclaw", + validateManagedDcode: false, + provider: "compatible-endpoint", + model: "changed-model", + preferredInferenceApi: null, + reconcileOpenClawInference: true, + }; + + function deps(order: string[]) { + return { + ...preparedRestoreAuthority("openclaw"), + restoreRecreatedSandboxState: async () => { + order.push("restore"); + return { + success: true, + restoredDirs: ["."], + restoredFiles: [], + failedDirs: [], + failedFiles: [], + }; + }, + writeRestoredOpenclawInferenceRoute: vi.fn(async () => { + order.push("selection"); + }), + getDcodeSelectionDrift: vi.fn(), + register: vi.fn(() => { + order.push("register"); + }), + note: vi.fn(), + error: vi.fn(), + exitProcess: (code: number): never => { + throw new Error(`unexpected exit ${code}`); + }, + }; + } + + it("applies the selected model after restore and before restart and publication (#12667)", async () => { + const order: string[] = []; + const dependencies = deps(order); + vi.mocked(restoreWindow.finishUnregisteredOpenClawPostRestoreDoctor).mockImplementation( + async () => { + order.push("restart"); + return { ok: true }; + }, + ); + await finalizeCreatedSandbox(options, dependencies); + expect(order).toEqual(["restore", "selection", "restart", "register"]); + expect(dependencies.writeRestoredOpenclawInferenceRoute).toHaveBeenCalledExactlyOnceWith( + "openclaw", + "changed-model", + "compatible-endpoint", + null, + "nemoclaw-9090", + undefined, + { endpointUrl: undefined, nativeProvider: false }, + ); + }); + + it.each([ + { + label: "ordinary rebuild", + patch: { reconcileOpenClawInference: false, preUpgradeBackup: true }, + }, + { label: "custom image", patch: { customImage: true } }, + { label: "fresh creation", patch: { restoreBackupPath: null } }, + ])("preserves $label native configuration (#12667)", async ({ patch }) => { + const dependencies = deps([]); + await finalizeCreatedSandbox({ ...options, ...patch }, dependencies); + expect(dependencies.writeRestoredOpenclawInferenceRoute).not.toHaveBeenCalled(); + expect(dependencies.register).toHaveBeenCalledOnce(); + }); + + it("refuses reconciliation when the prepared runtime identity changes (#12667)", async () => { + const dependencies = deps([]); + dependencies.revalidatePreparedRegistration = () => { + throw new Error("runtime identity changed"); + }; + await expect(finalizeCreatedSandbox(options, dependencies)).rejects.toThrow( + "runtime identity changed", + ); + expect(dependencies.writeRestoredOpenclawInferenceRoute).not.toHaveBeenCalled(); + expect(dependencies.register).not.toHaveBeenCalled(); + expect(restoreWindow.abortUnregisteredOpenClawPostRestoreDoctor).toHaveBeenCalledOnce(); + }); + + it("aborts the offline window without publishing when reconciliation fails (#12667)", async () => { + const dependencies = deps([]); + dependencies.writeRestoredOpenclawInferenceRoute.mockRejectedValue( + new Error("native write failed"), + ); + await expect(finalizeCreatedSandbox(options, dependencies)).rejects.toThrow( + "native write failed", + ); + expect(dependencies.register).not.toHaveBeenCalled(); + expect(restoreWindow.finishUnregisteredOpenClawPostRestoreDoctor).not.toHaveBeenCalled(); + expect(restoreWindow.abortUnregisteredOpenClawPostRestoreDoctor).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/lib/onboard/created-sandbox-selection-reconciliation.test.ts b/src/lib/onboard/created-sandbox-selection-reconciliation.test.ts new file mode 100644 index 00000000000..effaae22e63 --- /dev/null +++ b/src/lib/onboard/created-sandbox-selection-reconciliation.test.ts @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as restoreWindow from "../actions/sandbox/runtime/openclaw-lifecycle"; +import type { SandboxEntry } from "../state/registry"; +import { finalizeCreatedSandbox } from "./created-sandbox-finalization"; + +beforeEach(() => { + vi.spyOn(restoreWindow, "beginUnregisteredOpenClawBackupQuiesce").mockResolvedValue({ + ok: true, + window: { sandboxName: "spark-box", kind: "backup" }, + }); + vi.spyOn(restoreWindow, "finishUnregisteredOpenClawPostRestoreDoctor").mockResolvedValue({ + ok: true, + }); + vi.spyOn(restoreWindow, "abortUnregisteredOpenClawPostRestoreDoctor").mockResolvedValue({ + ok: true, + }); +}); + +function preparedRestoreAuthority(sandboxName: string) { + const prepared = { name: sandboxName } as SandboxEntry; + return { + prepareRegistration: () => prepared, + revalidatePreparedRegistration: (target: SandboxEntry) => target, + }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("restored OpenClaw selection reconciliation", () => { + const options = { + sandboxName: "openclaw", + gatewayName: "nemoclaw-9090", + restoreBackupPath: "/tmp/managed-openclaw-backup", + preUpgradeBackup: false, + targetAgentType: "openclaw", + validateManagedDcode: false, + provider: "compatible-endpoint", + model: "changed-model", + preferredInferenceApi: null, + reconcileOpenClawInference: true, + }; + + function deps(order: string[]) { + return { + ...preparedRestoreAuthority("openclaw"), + restoreRecreatedSandboxState: async () => { + order.push("restore"); + return { + success: true, + restoredDirs: ["."], + restoredFiles: [], + failedDirs: [], + failedFiles: [], + }; + }, + writeRestoredOpenclawInferenceRoute: vi.fn(async () => { + order.push("selection"); + }), + getDcodeSelectionDrift: vi.fn(), + register: vi.fn(() => { + order.push("register"); + }), + note: vi.fn(), + error: vi.fn(), + exitProcess: (code: number): never => { + throw new Error(`unexpected exit ${code}`); + }, + }; + } + + it("applies the selected model after restore and before restart and publication (#12667)", async () => { + const order: string[] = []; + const dependencies = deps(order); + vi.mocked(restoreWindow.finishUnregisteredOpenClawPostRestoreDoctor).mockImplementation( + async () => { + order.push("restart"); + return { ok: true }; + }, + ); + await finalizeCreatedSandbox(options, dependencies); + expect(order).toEqual(["restore", "selection", "restart", "register"]); + expect(dependencies.writeRestoredOpenclawInferenceRoute).toHaveBeenCalledExactlyOnceWith( + "openclaw", + "changed-model", + "compatible-endpoint", + null, + "nemoclaw-9090", + undefined, + { endpointUrl: undefined, nativeProvider: false }, + ); + }); + + it.each([ + { + label: "ordinary rebuild", + patch: { reconcileOpenClawInference: false, preUpgradeBackup: true }, + }, + { label: "custom image", patch: { customImage: true } }, + { label: "fresh creation", patch: { restoreBackupPath: null } }, + ])("preserves $label native configuration (#12667)", async ({ patch }) => { + const dependencies = deps([]); + await finalizeCreatedSandbox({ ...options, ...patch }, dependencies); + expect(dependencies.writeRestoredOpenclawInferenceRoute).not.toHaveBeenCalled(); + expect(dependencies.register).toHaveBeenCalledOnce(); + }); + + it("refuses reconciliation when the prepared runtime identity changes (#12667)", async () => { + const dependencies = deps([]); + dependencies.revalidatePreparedRegistration = () => { + throw new Error("runtime identity changed"); + }; + await expect(finalizeCreatedSandbox(options, dependencies)).rejects.toThrow( + "runtime identity changed", + ); + expect(dependencies.writeRestoredOpenclawInferenceRoute).not.toHaveBeenCalled(); + expect(dependencies.register).not.toHaveBeenCalled(); + expect(restoreWindow.abortUnregisteredOpenClawPostRestoreDoctor).toHaveBeenCalledOnce(); + }); + + it("aborts the offline window without publishing when reconciliation fails (#12667)", async () => { + const dependencies = deps([]); + dependencies.writeRestoredOpenclawInferenceRoute.mockRejectedValue( + new Error("native write failed"), + ); + await expect(finalizeCreatedSandbox(options, dependencies)).rejects.toThrow( + "native write failed", + ); + expect(dependencies.register).not.toHaveBeenCalled(); + expect(restoreWindow.finishUnregisteredOpenClawPostRestoreDoctor).not.toHaveBeenCalled(); + expect(restoreWindow.abortUnregisteredOpenClawPostRestoreDoctor).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/lib/onboard/dcode-selection-drift.test.ts b/src/lib/onboard/dcode-selection-drift.test.ts index af1dc9ce793..6a8e2fe9f44 100644 --- a/src/lib/onboard/dcode-selection-drift.test.ts +++ b/src/lib/onboard/dcode-selection-drift.test.ts @@ -71,6 +71,31 @@ function identity( } describe("live DCode selection drift", () => { + it.each([ + ["http://host.openshell.internal:42103/v1", "https://inference.local/v1"], + ["http://host.openshell.internal:8000/v1", "http://host.openshell.internal:8000/v1"], + ])("accepts the selected compatible transport for %s (#12558)", async (endpoint, expected) => { + const output = identity({ + Provider: "compatible-endpoint", + Model: "openai:model-a", + Endpoint: expected, + }); + expect( + await getDcodeSelectionDrift( + "alpha", + "compatible-endpoint", + "model-a", + "openai-completions", + driftDeps(() => output, endpoint), + ), + ).toMatchObject({ + changed: false, + providerChanged: false, + modelChanged: false, + unknown: false, + }); + }); + it.each([ [ "openai-api", diff --git a/src/lib/onboard/docker-driver-gateway-config.ts b/src/lib/onboard/docker-driver-gateway-config.ts index ebf8e87d053..e7824c18d45 100644 --- a/src/lib/onboard/docker-driver-gateway-config.ts +++ b/src/lib/onboard/docker-driver-gateway-config.ts @@ -10,6 +10,7 @@ import { verify, } from "node:crypto"; import fs from "node:fs"; +import { prepareNativeGatewayCreation } from "./gateway/native-creation"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { parse as parseToml } from "smol-toml"; @@ -1143,6 +1144,21 @@ export function prepareDockerDriverGatewayConfigEnv( gatewayRuntime?: RuntimeProviderGatewayHostRuntime; externalComponent?: ExternalComponentGatewayConfiguration | null; } = {}, +): Record { + return prepareNativeGatewayCreation(stateDir, gatewayEnv.OPENSHELL_GRPC_ENDPOINT ?? "", () => + prepareGatewayConfig(gatewayEnv, stateDir, sandboxBin, options), + ); +} + +function prepareGatewayConfig( + gatewayEnv: Record, + stateDir: string, + sandboxBin: string | null | undefined, + options: { + allowOpenShell0044PreAuthDatabase?: boolean; + gatewayRuntime?: RuntimeProviderGatewayHostRuntime; + externalComponent?: ExternalComponentGatewayConfiguration | null; + }, ): Record { const runtime = resolveGatewayRuntimeProjection(gatewayEnv, options.gatewayRuntime); const identity = resolveDockerDriverGatewayIdentity( diff --git a/src/lib/onboard/dockerfile-patch-native-hosted.test.ts b/src/lib/onboard/dockerfile-patch-native-hosted.test.ts index 559668e0afe..ea654509aa3 100644 --- a/src/lib/onboard/dockerfile-patch-native-hosted.test.ts +++ b/src/lib/onboard/dockerfile-patch-native-hosted.test.ts @@ -18,28 +18,44 @@ function dockerfileWith(content: string): string { describe("Hermes Dockerfile route selection", () => { it.each([ { + provider: "hermes-provider", nativeProvider: false, upstreamEndpointUrl: "https://custom.example/v1", expected: "https://inference.local/v1", }, { + provider: "hermes-provider", nativeProvider: undefined, upstreamEndpointUrl: "https://custom.example/v1", expected: "https://inference.local/v1", }, { + provider: "hermes-provider", nativeProvider: true, upstreamEndpointUrl: "https://authenticated.example/v1", expected: "https://authenticated.example/v1", }, { + provider: "hermes-provider", nativeProvider: true, upstreamEndpointUrl: "https://inference-api.nousresearch.com/v1", expected: "https://inference-api.nousresearch.com/v1", }, + { + provider: "vllm-local", + nativeProvider: false, + upstreamEndpointUrl: "http://host.openshell.internal:8000/v1", + expected: "https://inference.local/v1", + }, + { + provider: "compatible-endpoint", + nativeProvider: false, + upstreamEndpointUrl: "http://host.openshell.internal:8000/v1", + expected: "https://inference.local/v1", + }, ])( "renders $upstreamEndpointUrl with nativeProvider=$nativeProvider", - ({ expected, ...options }) => { + ({ expected, provider, ...options }) => { const file = dockerfileWith( "FROM example/base\nARG NEMOCLAW_INFERENCE_BASE_URL=old\nARG NEMOCLAW_UPSTREAM_ENDPOINT_URL=old\n", ); @@ -48,7 +64,7 @@ describe("Hermes Dockerfile route selection", () => { "fixture-model", "", "build", - "hermes-provider", + provider, null, null, null, diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index cd744ea7c50..2cb450a8835 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -62,6 +62,7 @@ function sanitizeDockerArg(value: unknown): string { } export interface HermesPortableDockerfileBuildSettings { + readonly nativeEndpointUrl?: string; readonly baseImageRef?: string; readonly model: string; readonly provider: string | null; @@ -128,6 +129,8 @@ export function renderHermesPortableDockerfileBuildSettings( input.model, input.provider, input.preferredInferenceApi, + true, + input.nativeEndpointUrl, ); const replacements = [ ["NEMOCLAW_MODEL", input.model], diff --git a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts index 27299fde9ab..17c41fc545a 100644 --- a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts +++ b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts @@ -125,6 +125,9 @@ const CANONICAL_POST_GENERATOR_INSTRUCTION_SHA256 = new Set([ // Main-image chmod for NemoClaw startup helpers, source, preloads, policy, // and plugin payloads; it does not write OpenClaw configuration. "4baee14013357ee190f418985d6b58457ab7a0c414f7ae3d8d308704da1696cf", + // The reviewed instruction adds native-local source permissions and leaves + // the generated OpenClaw configuration untouched. + "23dbd2c2f3225b0a671073f46900fddf232fc1c773ab5a583a103776ee221f61", // NEMOCLAW_DARWIN_VM_COMPAT chmod for the OpenClaw and NemoClaw state trees; // it changes modes only and preserves the generated dashboard binding. "295282a4f06106c93df72b4e035f980a2fc0e8a7dcbf6d270e102d7c75be27fb", diff --git a/src/lib/onboard/gateway/docker-driver-start.ts b/src/lib/onboard/gateway/docker-driver-start.ts index 28e6508f8fc..1669453c7e4 100644 --- a/src/lib/onboard/gateway/docker-driver-start.ts +++ b/src/lib/onboard/gateway/docker-driver-start.ts @@ -1,6 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { consumeNativeGatewayCreation } from "./native-creation"; +import { initializeNativeProviderPolicy } from "../../adapters/openshell/provider-policy"; +import { captureSanitizedResolvedOpenshellAsync } from "../../adapters/openshell/sanitized-capture"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -46,6 +49,7 @@ type DynamicGatewayHelpers = ReturnType< >; export interface DockerDriverGatewayStartDeps { + initializeNativeProviderPolicy?: typeof initializeNativeProviderPolicy; observer: import("../../adapters/openshell/gateway-reuse").OpenShellGatewayReuseObserver; SUPPORTED_OPENSHELL_FALLBACK_VERSION: string; checkGatewayPortAvailable(): Promise; @@ -208,7 +212,7 @@ export function createDockerDriverGatewayStart( const runtimeOptions = selectedRuntimeEnv ? { env: selectedRuntimeEnv, - replaceEnv: true, + replaceEnv: true as const, } : {}; const runCaptureOpenshell: DockerDriverGatewayStartDeps["runCaptureOpenshell"] = ( @@ -232,6 +236,8 @@ export function createDockerDriverGatewayStart( home: os.homedir(), port: deps.gatewayPort(), }); + const creationGatewayName = deps.gatewayName(); + const creationGatewayPort = deps.gatewayPort(); const configuredStateDir = binding.stateDir?.trim(); const stateLifecycleLock = configuredStateDir ? gatewayStateLifecycleLock.acquireManagedGatewayStateLifecycleLock(stateDir) @@ -298,7 +304,43 @@ export function createDockerDriverGatewayStart( ); const driftGatewayEnv = runtimeIdentity?.desiredEnv ?? gatewayEnv; const identityGatewayBin = runtimeIdentity?.identityGatewayBin ?? gatewayBin; + const creation = consumeNativeGatewayCreation( + stateDir, + gatewayEnv.OPENSHELL_GRPC_ENDPOINT ?? "", + ); const initialPortCheck = await deps.checkGatewayPortAvailable(); + const initializeFreshGateway = async () => { + if (!creation || !initialPortCheck.ok || initialPortCheck.warning) return; + if ( + deps.gatewayName() !== creationGatewayName || + deps.gatewayPort() !== creationGatewayPort || + !creation() + ) + throw new Error("Fresh gateway configuration changed before policy initialization."); + const policy = await ( + deps.initializeNativeProviderPolicy ?? initializeNativeProviderPolicy + )(creationGatewayName, (args) => + captureSanitizedResolvedOpenshellAsync(args, { + ...runtimeOptions, + ignoreError: true, + includeStreams: true, + includeStderr: true, + timeout: 30_000, + outputLimitBytes: 65_536, + }), + ); + if (policy === "disabled") { + if ( + deps.gatewayName() !== creationGatewayName || + deps.gatewayPort() !== creationGatewayPort || + !creation() + ) + throw new Error("Fresh gateway configuration changed during policy initialization."); + (output?.warn ?? console.warn)( + "Native local inference is unavailable because provider composition remains disabled. Hosted provider onboarding can continue.", + ); + } + }; const servicePortOwnership = deps.createGatewayServicePortOwnership(initialPortCheck, { exitOnFailure, gatewayBin: identityGatewayBin, @@ -416,6 +458,7 @@ export function createDockerDriverGatewayStart( ), ); if (cutover !== "launch") { + if (cutover === "managed") await initializeFreshGateway(); rememberBinding(); return; } @@ -475,6 +518,7 @@ export function createDockerDriverGatewayStart( sleepSeconds: deps.sleepSeconds, }); if (startup === "healthy") { + await initializeFreshGateway(); rememberBinding(); (output?.log ?? console.log)(" ✓ Docker-driver gateway is healthy"); return; diff --git a/src/lib/onboard/gateway/native-creation.test.ts b/src/lib/onboard/gateway/native-creation.test.ts new file mode 100644 index 00000000000..efa8f6582ba --- /dev/null +++ b/src/lib/onboard/gateway/native-creation.test.ts @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { consumeNativeGatewayCreation, prepareNativeGatewayCreation } from "./native-creation"; + +const endpoint = "http://127.0.0.1:8080"; +const roots: string[] = []; +function fixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "gateway-creation-")); + roots.push(root); + const write = () => { + fs.mkdirSync(path.join(root, "jwt"), { recursive: true, mode: 0o700 }); + for (const file of ["openshell-gateway.toml", "jwt/signing.pem", "jwt/public.pem", "jwt/kid"]) + fs.writeFileSync(path.join(root, file), `fixture ${file}`, { mode: 0o600 }); + return "prepared"; + }; + return { root, write, prepare: () => prepareNativeGatewayCreation(root, endpoint, write) }; +} +afterEach(() => { + for (const root of roots.splice(0)) { + consumeNativeGatewayCreation(root, endpoint); + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +describe("current-invocation native gateway creation authority", () => { + it("survives its own repeated preparation and is consumed once (#12558)", () => { + const f = fixture(); + expect(f.prepare()).toBe("prepared"); + f.prepare(); + const proof = consumeNativeGatewayCreation(f.root, endpoint); + expect(proof?.()).toBe(true); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + f.prepare(); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + }); + it.each(["openshell.db", "runtime.json", "openshell-gateway.toml"])( + "does not activate preexisting %s state (#12558)", + (name) => { + const f = fixture(); + fs.writeFileSync(path.join(f.root, name), "existing"); + f.prepare(); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + }, + ); + it("does not activate a preexisting JWT directory (#12558)", () => { + const f = fixture(); + fs.mkdirSync(path.join(f.root, "jwt")); + f.prepare(); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + }); + it.each(["openshell.db", "runtime.json", "openshell-gateway.toml", "jwt/kid"])( + "rejects intervening %s writes even through another preparation (#12558)", + (name) => { + const f = fixture(); + f.prepare(); + fs.writeFileSync(path.join(f.root, name), "changed"); + f.prepare(); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + }, + ); + it("does not retain authority after a preparation throws (#12558)", () => { + const f = fixture(); + f.prepare(); + expect(() => + prepareNativeGatewayCreation(f.root, endpoint, () => { + f.write(); + throw new Error("partial preparation"); + }), + ).toThrow("partial preparation"); + f.prepare(); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + }); + it("cannot transfer authority between endpoints or state directories (#12558)", () => { + const a = fixture(); + const b = fixture(); + a.prepare(); + expect(consumeNativeGatewayCreation(b.root, endpoint)).toBeUndefined(); + expect(consumeNativeGatewayCreation(a.root, "http://127.0.0.1:8081")).toBeUndefined(); + expect(consumeNativeGatewayCreation(a.root, endpoint)).toBeUndefined(); + }); + it("rejects a replacement file even with identical contents (#12558)", () => { + const f = fixture(); + f.prepare(); + const file = path.join(f.root, "jwt/kid"); + fs.writeFileSync(`${file}.new`, fs.readFileSync(file), { mode: 0o600 }); + fs.renameSync(`${file}.new`, file); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + }); + it("does not follow a replaced JWT file symlink (#12558)", () => { + const f = fixture(); + f.prepare(); + const file = path.join(f.root, "jwt/kid"); + fs.renameSync(file, `${file}.saved`); + fs.symlinkSync(`${file}.saved`, file); + expect(consumeNativeGatewayCreation(f.root, endpoint)).toBeUndefined(); + }); + it("allows runtime creation after consumption but rejects generated config drift (#12558)", () => { + const f = fixture(); + f.prepare(); + const proof = consumeNativeGatewayCreation(f.root, endpoint); + fs.writeFileSync(path.join(f.root, "openshell.db"), "new runtime"); + fs.writeFileSync(path.join(f.root, "runtime.json"), "new runtime marker"); + expect(proof?.()).toBe(true); + fs.appendFileSync(path.join(f.root, "openshell-gateway.toml"), "changed"); + expect(proof?.()).toBe(false); + }); +}); diff --git a/src/lib/onboard/gateway/native-creation.ts b/src/lib/onboard/gateway/native-creation.ts new file mode 100644 index 00000000000..1131fce41aa --- /dev/null +++ b/src/lib/onboard/gateway/native-creation.ts @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { openRegularFileNoFollow } from "../../adapters/fs/regular-file"; + +const generatedFiles = ["openshell-gateway.toml", "jwt/signing.pem", "jwt/public.pem", "jwt/kid"]; +const runtimeFiles = ["openshell.db", "runtime.json"]; +const preparations = new Map(); + +function stateEntries(stateDir: string): string[] { + try { + return fs.readdirSync(stateDir); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } +} + +function hasNoRuntime(stateDir: string): boolean { + const entries = stateEntries(stateDir); + return runtimeFiles.every((file) => !entries.includes(file)); +} + +function fingerprint(stateDir: string): string | null { + try { + const digest = createHash("sha256"); + for (const directory of [stateDir, path.join(stateDir, "jwt")]) { + const stat = fs.lstatSync(directory); + if (!stat.isDirectory()) return null; + digest.update(JSON.stringify([stat.dev, stat.ino, stat.uid, stat.mode])); + } + if ( + fs.readdirSync(path.join(stateDir, "jwt")).sort().join(",") !== "kid,public.pem,signing.pem" + ) + return null; + for (const file of generatedFiles) { + const filePath = path.join(stateDir, file); + const opened = openRegularFileNoFollow(filePath); + try { + const stat = opened.stat(); + digest.update(JSON.stringify([file, stat.dev, stat.ino, stat.uid, stat.mode, stat.size])); + digest.update(opened.readBytes(65_536)); + } finally { + opened.close(); + } + } + return digest.digest("hex"); + } catch { + return null; + } +} + +/** Keep creation authority across this process's own config preparation, never across invocations. */ +export function prepareNativeGatewayCreation( + stateDir: string, + endpoint: string, + prepare: () => T, +): T { + const root = path.resolve(stateDir); + const prior = preparations.get(root); + preparations.delete(root); + const fresh = prior + ? prior.endpoint === endpoint && prior.fingerprint === fingerprint(root) && hasNoRuntime(root) + : !stateEntries(root).some((file) => + [...runtimeFiles, "openshell-gateway.toml", "jwt"].includes(file), + ); + // A thrown preparation leaves no authority, including after a partial write. + const result = prepare(); + const prepared = fresh && endpoint && hasNoRuntime(root) ? fingerprint(root) : null; + if (prepared) preparations.set(root, { endpoint, fingerprint: prepared }); + return result; +} + +/** Consume only the exact prepared state; the returned check remains valid after runtime startup. */ +export function consumeNativeGatewayCreation( + stateDir: string, + endpoint: string, +): (() => boolean) | undefined { + const root = path.resolve(stateDir); + const prepared = preparations.get(root); + preparations.delete(root); + if ( + !prepared || + prepared.endpoint !== endpoint || + !hasNoRuntime(root) || + prepared.fingerprint !== fingerprint(root) + ) + return undefined; + return () => prepared.fingerprint === fingerprint(root); +} diff --git a/src/lib/onboard/gateway/native-provider-bootstrap.test.ts b/src/lib/onboard/gateway/native-provider-bootstrap.test.ts new file mode 100644 index 00000000000..a842d55272d --- /dev/null +++ b/src/lib/onboard/gateway/native-provider-bootstrap.test.ts @@ -0,0 +1,158 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + createDockerDriverGatewayStart, + type DockerDriverGatewayStartDeps, +} from "./docker-driver-start"; +import { buildDockerDriverGatewayEnv } from "../docker-driver-gateway-env"; +import { flowDeps } from "../external-component/onboarding"; +import * as cutover from "../docker-driver-gateway-cutover"; + +const roots: string[] = []; +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +function fixture() { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "native-gateway-")); + roots.push(stateDir); + vi.stubEnv("NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR", ""); + const initialize = vi.fn<() => Promise<"disabled" | void>>(async () => {}); + const port = vi.fn(async () => ({ ok: true })); + const managed = vi + .spyOn(cutover, "runDockerDriverGatewayManagedFallback") + .mockResolvedValue("managed"); + // The cutover owner is mocked; unexpected use of a live dependency fails the test. + const buildEnv = () => + buildDockerDriverGatewayEnv({ + platform: "linux", + gatewayPort: 8080, + stateDir, + getDockerSupervisorImage: () => "ghcr.io/nvidia/openshell/supervisor:test", + resolveSandboxBin: () => null, + }); + const getEnv = vi.fn(buildEnv); + const gatewayName = vi.fn(() => "selected"); + const deps = { + initializeNativeProviderPolicy: initialize, + gatewayName, + gatewayPort: () => 8080, + gatewayBinding: { resolveGatewayStateDirForPort: () => stateDir }, + getDockerDriverGatewayStateDir: () => stateDir, + resolveOpenShellGatewayBinary: () => null, + getDockerDriverGatewayEnv: getEnv, + runCaptureOpenshell: () => "", + checkGatewayPortAvailable: port, + createGatewayServicePortOwnership: () => ({}), + runner: {}, + } as unknown as DockerDriverGatewayStartDeps; + return { + stateDir, + getEnv, + gatewayName, + prepare: () => + flowDeps({ collectGatewayReadiness: async () => undefined }, buildEnv, (() => { + throw new Error("unexpected sandbox inspection"); + }) as never).configureExternalComponentGateway(null), + initialize, + port, + managed, + start: createDockerDriverGatewayStart(deps).startDockerDriverGateway, + }; +} + +describe("native policy initialization ownership", () => { + it("initializes composition after the fresh gateway owner reports healthy (#12558)", async () => { + const f = fixture(); + await f.start(); + expect(f.initialize).toHaveBeenCalledExactlyOnceWith("selected", expect.any(Function)); + expect(f.managed.mock.invocationCallOrder[0]).toBeLessThan( + f.initialize.mock.invocationCallOrder[0], + ); + }); + it("keeps creation authority through the real onboarding preparation (#12558)", async () => { + const f = fixture(); + await f.prepare(); + expect(fs.existsSync(path.join(f.stateDir, "openshell-gateway.toml"))).toBe(true); + await f.start(); + expect(f.initialize).toHaveBeenCalledExactlyOnceWith("selected", expect.any(Function)); + }); + it("does not reuse creation authority for a second startup (#12558)", async () => { + const f = fixture(); + await f.prepare(); + await f.start(); + await f.start(); + expect(f.initialize).toHaveBeenCalledTimes(1); + }); + it("fails startup if prepared configuration changes during launch (#12558)", async () => { + const f = fixture(); + f.managed.mockImplementation(async () => { + fs.appendFileSync(path.join(f.stateDir, "openshell-gateway.toml"), "\n# changed"); + return "managed"; + }); + await expect(f.start()).rejects.toThrow("configuration changed"); + expect(f.initialize).not.toHaveBeenCalled(); + }); + it("does not activate another gateway selected during startup (#12558)", async () => { + const f = fixture(); + f.managed.mockImplementation(async () => { + f.gatewayName.mockReturnValue("sibling"); + return "managed"; + }); + await expect(f.start()).rejects.toThrow("configuration changed"); + expect(f.initialize).not.toHaveBeenCalled(); + }); + it.each(["openshell.db", "openshell-gateway.toml", "runtime.json", "jwt"])( + "does not activate composition when existing state contains %s (#12558)", + async (file) => { + const f = fixture(); + fs.writeFileSync(path.join(f.stateDir, file), "existing"); + f.getEnv.mockImplementation(() => ({ OPENSHELL_GRPC_ENDPOINT: "http://127.0.0.1:8080" })); + await f.start(); + expect(f.initialize).not.toHaveBeenCalled(); + }, + ); + it("does not activate a gateway reused from an occupied port (#12558)", async () => { + const f = fixture(); + f.port.mockResolvedValue({ ok: false }); + await f.start(); + expect(f.initialize).not.toHaveBeenCalled(); + }); + it("does not activate composition on the reused cutover path (#12558)", async () => { + const f = fixture(); + f.managed.mockResolvedValue("reused"); + await f.start(); + expect(f.initialize).not.toHaveBeenCalled(); + }); + it("allows healthy startup with a warning when composition is verified disabled (#12558)", async () => { + const f = fixture(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + f.initialize.mockResolvedValue("disabled"); + await expect(f.start()).resolves.toBeUndefined(); + expect(warn).toHaveBeenCalledOnce(); + expect(f.initialize).toHaveBeenCalledTimes(1); + }); + it("rejects changed creation authority before allowing disabled composition (#12558)", async () => { + const f = fixture(); + await f.prepare(); + f.initialize.mockImplementation(async () => { + fs.appendFileSync(path.join(f.stateDir, "openshell-gateway.toml"), "\n# changed"); + return "disabled"; + }); + await expect(f.start()).rejects.toThrow("configuration changed"); + expect(f.initialize).toHaveBeenCalledTimes(1); + }); + it("does not return startup success when initialization cannot be verified (#12558)", async () => { + const f = fixture(); + f.initialize.mockRejectedValue(new Error("settings unavailable")); + await expect(f.start()).rejects.toThrow("settings unavailable"); + expect(f.initialize).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts index caecd52d308..2d520a3ce3f 100644 --- a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts +++ b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts @@ -1,17 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { isProtectedNemoClawHostPort } from "../../core/protected-host-ports"; +import { isProtectedLocalInferencePort } from "../../inference/gateway/local-endpoint-ports"; import { DEFAULT_OLLAMA_PROXY_PORT, OLLAMA_PROXY_PORT } from "../../core/ollama-proxy-port"; import { VLLM_PORT } from "../../core/vllm-port"; import { unsafeEndpointUrlViolation } from "../../core/endpoint-url-safety"; import { LLAMA_CPP_PORT } from "../../inference/llama-cpp/contract"; import { isLoopbackHostname } from "../../private-networks"; -import { - listRecordedGatewayPorts, - listRecordedModelRouterPorts, - resolveHome, -} from "../../state/gateway-registry"; import type { RunOpenshell, UpsertProvider, UpsertProviderResult } from "./types"; // Keep this list aligned with the materialized host.openshell.internal endpoints @@ -71,12 +66,10 @@ export function isLoopbackNoAuthCompatibleEndpointUrl( endpointUrl: string | null | undefined, ): boolean { const port = loopbackNoAuthCompatibleEndpointPort(provider, endpointUrl); - const home = resolveHome(); return ( port !== null && COMPATIBLE_ENDPOINT_GATEWAY_PORT_SET.has(port) && - !isProtectedNemoClawHostPort(port, listRecordedModelRouterPorts(home)) && - !listRecordedGatewayPorts(home).includes(port) + !isProtectedLocalInferencePort(port) ); } @@ -102,14 +95,10 @@ export function isLegacyRecordedLoopbackNoAuthCompatibleEndpointUrl( provider: string, endpointUrl: string | null | undefined, ): boolean { - const home = resolveHome(); return ( OLLAMA_PROXY_PORT !== DEFAULT_OLLAMA_PROXY_PORT && loopbackNoAuthCompatibleEndpointPort(provider, endpointUrl) === DEFAULT_OLLAMA_PROXY_PORT && - !isProtectedNemoClawHostPort(DEFAULT_OLLAMA_PROXY_PORT, listRecordedModelRouterPorts(home), { - allowLegacyProxyDefault: true, - }) && - !listRecordedGatewayPorts(home).includes(DEFAULT_OLLAMA_PROXY_PORT) + !isProtectedLocalInferencePort(DEFAULT_OLLAMA_PROXY_PORT, { allowLegacyProxyDefault: true }) ); } diff --git a/src/lib/onboard/inference-providers/index.ts b/src/lib/onboard/inference-providers/index.ts index 350feae0b5d..e3a1a5a8ded 100644 --- a/src/lib/onboard/inference-providers/index.ts +++ b/src/lib/onboard/inference-providers/index.ts @@ -25,3 +25,15 @@ export type { SetupInferenceResult, VllmDeps, } from "./types"; + +export { requireNativeProviderPolicy } from "../../adapters/openshell/provider-policy"; +export { + normalizeNativeLocalProviderAttachment, + usesNativeLocalInference, + usesNativeLocalInferenceForAgent, +} from "../../inference/native-local/contract"; +export { + prepareNativeLocalSelection, + retireUnreservedNativeLocalProvider, +} from "../../inference/native-local/selection"; +export { gatewayReachableCompatibleEndpointUrl } from "./compatible-endpoint-gateway-route"; diff --git a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts index 3cdf2c5ca70..9f2ddbd2009 100644 --- a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts +++ b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts @@ -387,6 +387,38 @@ describe("custom Anthropic provider replacement on the OpenAI surface", () => { }); describe("OpenAI-compatible no-auth provider registration", () => { + it("reports retained native proxy ownership when reservation throws (#12558)", async () => { + const harness = createHarness(); + const persist = vi.fn(); + const restore = vi.fn(); + vi.mocked(noAuthProxy).mockReturnValue({ + baseUrl: "http://host.openshell.internal:11435/v1", + credentialValue: "proxy-token", + persist, + restore, + }); + harness.deps.reserveSandboxInferenceRoute.mockImplementation(() => { + throw new Error("registry readback secret unavailable"); + }); + harness.deps.redact.mockImplementation((value: string) => + value.replaceAll("secret", "[redacted]"), + ); + + await expect( + setupRemoteProviderInference( + { + ...makeArgs(SANDBOX), + provider: "compatible-endpoint", + credentialEnv: NO_AUTH_ENV, + }, + { ...harness.deps, nativeLocalInference: true }, + ), + ).rejects.toThrow( + "Native local inference could not publish its proxy owner: registry readback [redacted] unavailable. The proxy was retained.", + ); + expect(persist).toHaveBeenCalledOnce(); + expect(restore).not.toHaveBeenCalled(); + }); it.each(["compatible-endpoint", "compatible-anthropic-endpoint"])( "publishes the pending %s owner before a waiting destroy checks the proxy", async (provider) => { diff --git a/src/lib/onboard/inference-providers/remote.ts b/src/lib/onboard/inference-providers/remote.ts index 36c2772d3ee..55e3552f84b 100644 --- a/src/lib/onboard/inference-providers/remote.ts +++ b/src/lib/onboard/inference-providers/remote.ts @@ -292,7 +292,15 @@ export async function setupRemoteProviderInference( const gatewayEndpointUrl = proxy?.baseUrl ?? gatewayReachableCompatibleEndpointUrl(provider, resolvedEndpointUrl); let providerResult; - if (reuseGatewayCredentialWithoutLocalKey) { + if (deps.nativeLocalInference && reuseGatewayCredentialWithoutLocalKey) { + providerResult = await upsertProvider( + provider, + config.providerType, + resolvedCredentialEnv, + gatewayEndpointUrl, + {}, + ); + } else if (reuseGatewayCredentialWithoutLocalKey) { providerResult = await reuseRegisteredProviderWithGatewayEndpoint({ provider, providerType: config.providerType, @@ -403,6 +411,34 @@ export async function setupRemoteProviderInference( restoreUncommittedProxy(); return exitProcess(providerResult.status || 1); } + if (deps.nativeLocalInference) { + if (proxy && sandboxName) { + // Preserve the proxy owner before releasing its lifecycle lock. + // A failed registry write may already have committed, so retain it. + proxy.persist(); + proxySettled = true; + let reservationFailure: string | null = null; + try { + if (!reserveSandboxInferenceRoute(sandboxName, { model, provider })) { + reservationFailure = "reservation returned false"; + } + } catch (reservationError) { + reservationFailure = compactText( + redact( + reservationError instanceof Error + ? reservationError.message + : String(reservationError), + ), + ); + } + if (reservationFailure) { + throw new Error( + `Native local inference could not publish its proxy owner: ${reservationFailure}. The proxy was retained.`, + ); + } + } + break; + } const applyResult = await inferenceRouteMutator.setInferenceRoute({ target: { kind: "named", gatewayName }, route: { provider, model }, diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 093560c24c7..b38d65c12a7 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -98,6 +98,7 @@ export type Registry = { }; export type CommonDeps = { + nativeLocalInference?: boolean; runOpenshell: RunOpenshell; upsertProvider: UpsertProvider; verifyInferenceRoute: VerifyInferenceRoute; diff --git a/src/lib/onboard/machine/core-flow-phases.ts b/src/lib/onboard/machine/core-flow-phases.ts index 5ebe3484f38..896d236533f 100644 --- a/src/lib/onboard/machine/core-flow-phases.ts +++ b/src/lib/onboard/machine/core-flow-phases.ts @@ -42,11 +42,9 @@ export interface EndpointProvenanceOptions { endpointSource?: InferenceEndpointSource | null; endpointSourceProvider?: string | null; endpointSourceEndpointUrl?: string | null; - getSandboxRegistryEntry: (name: string) => { - provider?: unknown; - endpointUrl?: unknown; - endpointSource?: unknown; - } | null; + getSandboxRegistryEntry: ( + name: string, + ) => Partial | null; } export interface ProviderInferenceOnboardFlowPhaseOptions< @@ -281,7 +279,10 @@ export function createProviderInferenceOnboardFlowPhase< selectedMessagingChannels: context.selectedMessagingChannels, env: options.env, constants: options.constants, - deps: options.deps, + deps: { + ...options.deps, + getSandboxRegistryEntry: options.endpointProvenance.getSandboxRegistryEntry, + }, }); return { diff --git a/src/lib/onboard/machine/finalization-deps-terminal-inference.test.ts b/src/lib/onboard/machine/finalization-deps-terminal-inference.test.ts index ff920880fa8..ce92eb54c44 100644 --- a/src/lib/onboard/machine/finalization-deps-terminal-inference.test.ts +++ b/src/lib/onboard/machine/finalization-deps-terminal-inference.test.ts @@ -4,6 +4,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { finalizationHandlerDeps, finalizationHandlerRuntime } from "./finalization-deps"; +import { onboardInferenceVerificationContext } from "../../verify-deployment"; +import { + nativeLocalIdentity, + NATIVE_LOCAL_CREDENTIAL_ENV, +} from "../../inference/native-local/contract"; const input = { sandboxName: "deep-code", @@ -12,6 +17,20 @@ const input = { model: "moonshotai/kimi-k2.6", preferredInferenceApi: "openai-completions", }; +const localBinding = { + provider: "ollama-local" as const, + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV, + authMode: "sentinel" as const, + gatewayName: "nemoclaw-19090", + sandboxName: "deep-code", +}; +const localAttachment = { + ...localBinding, + ...nativeLocalIdentity(localBinding), + schemaVersion: 1 as const, + providerId: "provider-1", +}; describe("terminal inference finalization dependency", () => { afterEach(() => vi.restoreAllMocks()); @@ -22,6 +41,7 @@ describe("terminal inference finalization dependency", () => { } as never); const probeOnboardInferenceInvocation = vi.fn(async () => ({ ok: true })); vi.spyOn(finalizationHandlerRuntime, "loadVerifyDeployment").mockReturnValue({ + onboardInferenceVerificationContext, probeOnboardInferenceInvocation, } as never); @@ -31,6 +51,42 @@ describe("terminal inference finalization dependency", () => { expect(probeOnboardInferenceInvocation).toHaveBeenCalledExactlyOnceWith({ ...input, gatewayName: "nemoclaw-19090", + endpointUrl: null, + nativeLocalExpected: false, + nativeLocalProviderAttachment: undefined, + nativeHostedProviderAttachment: undefined, + }); + }); + + it("passes the selected native local receipt to DCode's terminal agent probe", async () => { + vi.spyOn(finalizationHandlerRuntime, "loadRegistryPersistence").mockReturnValue({ + load: () => ({ + sandboxes: { + "deep-code": { + gatewayName: "nemoclaw-19090", + endpointUrl: localBinding.endpointUrl, + nativeLocalProviderAttachment: localAttachment, + }, + }, + }), + } as never); + const probeOnboardInferenceInvocation = vi.fn(async () => ({ ok: true })); + vi.spyOn(finalizationHandlerRuntime, "loadVerifyDeployment").mockReturnValue({ + onboardInferenceVerificationContext, + probeOnboardInferenceInvocation, + } as never); + + await expect( + finalizationHandlerDeps.probeTerminalInference({ ...input, provider: "ollama-local" }), + ).resolves.toEqual({ ok: true }); + expect(probeOnboardInferenceInvocation).toHaveBeenCalledExactlyOnceWith({ + ...input, + provider: "ollama-local", + gatewayName: "nemoclaw-19090", + endpointUrl: localBinding.endpointUrl, + nativeLocalExpected: true, + nativeLocalProviderAttachment: localAttachment, + nativeHostedProviderAttachment: undefined, }); }); @@ -43,12 +99,16 @@ describe("terminal inference finalization dependency", () => { } as never); const probeOnboardInferenceInvocation = vi.fn(async () => ({ ok: true })); vi.spyOn(finalizationHandlerRuntime, "loadVerifyDeployment").mockReturnValue({ + onboardInferenceVerificationContext, probeOnboardInferenceInvocation, } as never); await finalizationHandlerDeps.probeTerminalInference(input); expect(probeOnboardInferenceInvocation).toHaveBeenCalledExactlyOnceWith({ ...input, gatewayName: "nemoclaw", + endpointUrl: null, + nativeLocalExpected: false, + nativeLocalProviderAttachment: undefined, nativeHostedProviderAttachment, }); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index c9a65b30c76..831d48ec420 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -423,11 +423,15 @@ export const finalizationHandlerDeps = { if (typeof gatewayName !== "string" || !gatewayName) { return { ok: false, detail: "the sandbox gateway identity is unavailable" }; } - return finalizationHandlerRuntime.loadVerifyDeployment().probeOnboardInferenceInvocation({ - ...entry, - ...input, + const verification = finalizationHandlerRuntime.loadVerifyDeployment(); + const context = verification.onboardInferenceVerificationContext( + input.sandboxName, gatewayName, - }); + input.agentName, + { ...input, endpointUrl: entry.endpointUrl }, + entry, + ); + return verification.probeOnboardInferenceInvocation(context.invocation); }, async waitForSandboxControlPlaneReady(name: string): Promise { return finalizationHandlerRuntime diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index aa2af7993db..c7d351368ed 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -1,6 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeLocalProviderAttachment, + usesNativeLocalInferenceForAgent, + type NativeLocalProviderAttachment, +} from "../../../inference/native-local/contract"; import type { SandboxMessagingPlan } from "../../../messaging/manifest"; import type { Session, SessionUpdates } from "../../../state/onboard-session"; import { normalizeAgentNameForResumeState } from "../../agent-resume-state"; @@ -19,6 +24,7 @@ export interface PolicyPresetEntry { } export interface ActiveSandboxPolicyState { + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; messaging?: { plan: SandboxMessagingPlan } | null; } @@ -68,6 +74,7 @@ export interface PoliciesStateOptions { credentialEnv: string | null; messagingChannels: string[]; agent: Agent; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; forceCanonicalRoute?: boolean; hostLocalInferenceProofAuthority?: HostLocalInferenceSandboxProofAuthority; beforeSuccess?: () => void; @@ -151,6 +158,20 @@ export async function handlePoliciesState({ const observabilityEnabled = latestSession?.observabilityEnabled === true; const recordedMessagingChannels = getActiveChannelsFromPlan(latestSession?.messagingPlan); const activeSandbox = deps.getActiveSandbox(sandboxName); + const recordedNativeLocal = normalizeNativeLocalProviderAttachment( + activeSandbox?.nativeLocalProviderAttachment, + ); + const nativeLocalSelected = usesNativeLocalInferenceForAgent( + normalizeAgentNameForResumeState((agent as { name?: string } | null)?.name), + provider, + endpointUrl, + ); + const nativeLocal = nativeLocalSelected ? recordedNativeLocal : undefined; + if (nativeLocalSelected && !nativeLocal) + throw new Error( + "Native local inference requires its recorded provider attachment before policy application.", + ); + const excludeLocalPreset = hostLocalInferenceRouteOnly || Boolean(nativeLocal); const activePlan = activeSandbox?.messaging?.plan; const activeMessagingChannels = getActiveChannelsFromPlan(activePlan); const planDisabledChannels = getDisabledChannelsFromPlan(activePlan); @@ -188,6 +209,7 @@ export async function handlePoliciesState({ credentialEnv, messagingChannels: policyMessagingChannels, agent, + ...(nativeLocal ? { nativeLocalProviderAttachment: nativeLocal } : {}), ...(hostLocalInferenceRouteOnly ? { forceCanonicalRoute: true } : {}), ...(hostLocalInferenceRouteOnly ? { hostLocalInferenceProofAuthority: hostLocalInferenceSandboxProofAuthority ?? undefined } @@ -225,7 +247,7 @@ export async function handlePoliciesState({ }), }; } - if (!hostLocalInferenceRouteOnly) await verifySandboxInferenceRoute(); + if (!excludeLocalPreset) await verifySandboxInferenceRoute(); const policyResumeSelection = await deps.preparePolicyPresetResumeSelection(sandboxName, { disabledChannels, @@ -240,8 +262,7 @@ export async function handlePoliciesState({ }); const livePolicyPresetsForSupport = policyResumeSelection.policyPresets; const staleLocalInferencePolicy = - hostLocalInferenceRouteOnly && - (await deps.arePolicyPresetsApplied(sandboxName, ["local-inference"])); + excludeLocalPreset && (await deps.arePolicyPresetsApplied(sandboxName, ["local-inference"])); const resumePolicies = resume && !staleLocalInferencePolicy && @@ -253,7 +274,7 @@ export async function handlePoliciesState({ let appliedPolicyPresets = livePolicyPresetsForSupport; let session: Session | null; if (resumePolicies) { - if (hostLocalInferenceRouteOnly) await verifySandboxInferenceRoute(); + if (excludeLocalPreset) await verifySandboxInferenceRoute(); deps.skippedStepMessage("policies", livePolicyPresetsForSupport.join(", ")); await deps.recordStateSkipped("policies", { reason: "resume", @@ -277,8 +298,8 @@ export async function handlePoliciesState({ enabledChannels: policyMessagingChannels, disabledChannels, webSearchConfig, - provider: hostLocalInferenceRouteOnly ? null : provider, - ...(hostLocalInferenceRouteOnly ? { excludedPresets: ["local-inference"] } : {}), + provider: excludeLocalPreset ? null : provider, + ...(excludeLocalPreset ? { excludedPresets: ["local-inference"] } : {}), // selectOnboardAgent returns null for the default OpenClaw path (no // --agent flag, no recorded agent). Normalise null/blank/whitespace // to "openclaw" so the auto-suggest gate still fires; explicit @@ -290,7 +311,7 @@ export async function handlePoliciesState({ hermesToolGateways, onSelection: () => undefined, }); - if (hostLocalInferenceRouteOnly) await verifySandboxInferenceRoute(); + if (excludeLocalPreset) await verifySandboxInferenceRoute(); session = await deps.recordStepComplete( "policies", deps.toSessionUpdates({ diff --git a/src/lib/onboard/machine/handlers/provider-inference-legacy-local-route.test.ts b/src/lib/onboard/machine/handlers/provider-inference-legacy-local-route.test.ts new file mode 100644 index 00000000000..8a5fe59aeb6 --- /dev/null +++ b/src/lib/onboard/machine/handlers/provider-inference-legacy-local-route.test.ts @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +// The reservation helper must not inspect the operator's real registry. +vi.mock("../../../state/registry", async (importOriginal) => ({ + ...(await importOriginal()), + getSandbox: vi.fn(() => null), +})); + +import { parseSandboxRegistryEntries } from "../../../state/registry-normalization"; +import { createSession } from "../../../state/onboard-session"; +import type { SandboxEntry } from "../../../state/registry"; +import { handleProviderInferenceState } from "./provider-inference"; +import { baseOptions, createDeps } from "./provider-inference.test-support"; + +describe("legacy local inference resume", () => { + it.each([ + ["openclaw", true, "2026-09-01T00:00:00Z"], + ["openclaw", true, undefined], + ["langchain-deepagents-code", true, "2026-09-01T00:00:00Z"], + ["langchain-deepagents-code", true, undefined], + ["langchain-deepagents-code", false, "2026-09-01T00:00:00Z"], + ])( + "stops %s before provider mutations with completed selection %s", + async (selectedAgent, complete, recordedAt) => { + const session = createSession({ + agent: selectedAgent, + sandboxName: "my-assistant", + provider: "ollama-local", + model: "qwen3:8b", + endpointUrl: "http://host.openshell.internal:11435/v1", + credentialEnv: "NEMOCLAW_OLLAMA_PROXY_TOKEN", + preferredInferenceApi: "openai-completions", + }); + session.steps.provider_selection.status = complete + ? "complete" + : session.steps.provider_selection.status; + const recorded = { + name: "my-assistant", + agent: selectedAgent, + gatewayName: "nemoclaw", + ...(recordedAt ? { createdAt: recordedAt } : {}), + provider: session.provider, + model: session.model, + endpointUrl: session.endpointUrl, + credentialEnv: session.credentialEnv, + preferredInferenceApi: session.preferredInferenceApi, + } as SandboxEntry; + const [, persisted] = parseSandboxRegistryEntries( + JSON.parse(JSON.stringify({ "my-assistant": recorded })), + )[0]!; + const { deps, calls } = createDeps({ getSandboxRegistryEntry: () => persisted }); + + await expect( + handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + agent: { name: selectedAgent }, + sandboxName: "my-assistant", + }), + ).rejects.toThrow("Resume is unavailable for this route"); + expect(calls.setupInference).not.toHaveBeenCalled(); + expect(calls.setupNim).not.toHaveBeenCalled(); + }, + ); +}); 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 3ef3730e6cc..ac518119873 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 @@ -15,7 +15,7 @@ import { } from "./provider-inference"; import { guardProviderInferenceRouteSelection } from "./provider-inference-route-containment"; -type Options = ProviderInferenceStateOptions; +type Options = ProviderInferenceStateOptions; const fallbackSelection: ProviderSelectionResult = { model: "nvidia/test", @@ -202,6 +202,78 @@ function reportDifferentRoute( }); } +function localEndpointGuard() { + const { calls } = createDeps(); + const containmentDeps = { + checkGatewayRouteCompatibility: calls.checkGatewayRouteCompatibility, + preflightGatewayRouteDiscovery: calls.preflightGatewayRouteDiscovery, + error: calls.error, + exitProcess: calls.exit, + }; + calls.checkGatewayRouteCompatibility.mockReturnValue({ + ok: false, + gatewayName: "nemoclaw-9090", + sandboxName: "target-sandbox", + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "shared-peer", reason: "custom-endpoint" }], + }); + const select = ( + nativeLocalSelection: boolean, + endpointUrl = "http://host.openshell.internal:11434/v1", + ) => + guardProviderInferenceRouteSelection( + containmentDeps, + "nemoclaw-9090", + "target-sandbox", + nativeLocalSelection, + { + provider: "compatible-endpoint", + model: "test-model", + endpointUrl, + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }, + ); + return { calls, select }; +} + +function freshLocalSelection(agentName: string) { + const { calls, deps } = createDeps(); + const selected = { + ...fallbackSelection, + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }; + calls.setupNim.mockImplementation( + async (_gpu, _sandbox, _agent, _recover, _gateway, guard, canProbeRoute) => { + calls.canProbeResult(canProbeRoute?.("ollama-local")); + calls.routeConstraints(guard?.(selected)); + return selected; + }, + ); + calls.checkGatewayRouteCompatibility.mockReturnValue({ + ok: false, + gatewayName: "nemoclaw-9090", + sandboxName: "target-sandbox", + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "shared-peer", reason: "custom-endpoint" }], + }); + const options = resumeOptions(deps, createSession()); + return { + calls, + run: () => + handleProviderInferenceState({ + ...options, + resume: false, + sandboxName: "target-sandbox", + agent: { name: agentName }, + }), + }; +} + describe("provider route containment", () => { it("defers exact endpoint comparison until llama.cpp route discovery is complete (#8161)", () => { const { calls } = createDeps(); @@ -213,13 +285,19 @@ describe("provider route containment", () => { }; expect( - guardProviderInferenceRouteSelection(containmentDeps, "nemoclaw-9090", "target-sandbox", { - provider: "llama-cpp-local", - model: "team/model-alias", - endpointUrl: null, - credentialEnv: "NEMOCLAW_LLAMACPP_LOCAL_TOKEN", - preferredInferenceApi: null, - }), + guardProviderInferenceRouteSelection( + containmentDeps, + "nemoclaw-9090", + "target-sandbox", + true, + { + provider: "llama-cpp-local", + model: "team/model-alias", + endpointUrl: null, + credentialEnv: "NEMOCLAW_LLAMACPP_LOCAL_TOKEN", + preferredInferenceApi: null, + }, + ), ).toEqual({ requiredModel: null, requiredEndpointUrl: null, @@ -229,6 +307,168 @@ describe("provider route containment", () => { expect(calls.checkGatewayRouteCompatibility).not.toHaveBeenCalled(); }); + it("allows native local selection beside a shared route (#12975)", () => { + const { calls, select } = localEndpointGuard(); + expect(select(true)).toEqual({ + requiredModel: null, + requiredEndpointUrl: null, + requiredInferenceApi: null, + }); + expect(calls.preflightGatewayRouteDiscovery).toHaveBeenCalledWith( + expect.objectContaining({ nativeLocalSelection: true }), + ); + expect(calls.checkGatewayRouteCompatibility).not.toHaveBeenCalled(); + }); + + it("keeps non-native selection on the shared route (#12975)", () => { + const { calls, select } = localEndpointGuard(); + expect(() => select(false)).toThrow("exit 1"); + expect(calls.preflightGatewayRouteDiscovery.mock.calls[0]?.[0]).not.toHaveProperty( + "nativeLocalSelection", + ); + expect(calls.checkGatewayRouteCompatibility).toHaveBeenCalledOnce(); + }); + + it("keeps a hosted compatible endpoint on the shared route (#12975)", () => { + const { calls, select } = localEndpointGuard(); + expect(() => select(false, "https://example.test/v1")).toThrow("exit 1"); + expect(calls.preflightGatewayRouteDiscovery.mock.calls[0]?.[0]).not.toHaveProperty( + "nativeLocalSelection", + ); + expect(calls.checkGatewayRouteCompatibility).toHaveBeenCalledOnce(); + }); + + it.each(["openclaw", "langchain-deepagents-code"])( + "carries %s native local selection through the early route guard (#12975)", + async (agent) => { + const { calls, run } = freshLocalSelection(agent); + await expect(run()).resolves.toMatchObject({ + provider: "compatible-endpoint", + model: "test-model", + }); + expect(calls.preflightGatewayRouteDiscovery).toHaveBeenCalledWith( + expect.objectContaining({ nativeLocalSelection: true }), + ); + expect(calls.checkGatewayRouteCompatibility).not.toHaveBeenCalled(); + expect(calls.setupInference).toHaveBeenCalledOnce(); + }, + ); + + it("rejects malformed shared peers while resuming native local inference (#12975)", async () => { + const session = createSession({ + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }); + session.steps.provider_selection.status = "complete"; + const { calls, deps } = createDeps(); + calls.preflightGatewayRouteDiscovery.mockReturnValue({ + ok: false, + result: { + ok: false, + gatewayName: "nemoclaw-9090", + sandboxName: "target-sandbox", + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "broken-peer", reason: "incomplete-custom-route" }], + }, + }); + + await expect( + handleProviderInferenceState({ + ...resumeOptions(deps, session), + agent: { name: "openclaw" }, + }), + ).rejects.toThrow("exit 1"); + + expect(calls.error).toHaveBeenCalledWith(expect.stringContaining("broken-peer")); + expect(calls.setupInference).not.toHaveBeenCalled(); + expect(calls.checkGatewayRouteCompatibility).not.toHaveBeenCalled(); + }); + + it.each(["pi", "hermes"])( + "keeps %s shared route conflicts in the early guard (#12975)", + async (agent) => { + const { calls, run } = freshLocalSelection(agent); + await expect(run()).rejects.toThrow("exit 1"); + expect(calls.preflightGatewayRouteDiscovery.mock.calls.at(-1)?.[0]).not.toHaveProperty( + "nativeLocalSelection", + ); + expect(calls.checkGatewayRouteCompatibility).toHaveBeenCalledOnce(); + expect(calls.setupInference).not.toHaveBeenCalled(); + }, + ); + + it.each(["openclaw", "langchain-deepagents-code"])( + "resumes %s native local inference beside a shared route (#12975)", + async (agent) => { + const session = createSession({ + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }); + session.steps.provider_selection.status = "complete"; + session.steps.sandbox.status = "complete"; + const { calls, deps } = createDeps(); + calls.checkGatewayRouteCompatibility.mockReturnValue({ + ok: false, + gatewayName: "nemoclaw-9090", + sandboxName: "target-sandbox", + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "shared-peer", reason: "custom-endpoint" }], + }); + + await expect( + handleProviderInferenceState({ ...resumeOptions(deps, session), agent: { name: agent } }), + ).resolves.toMatchObject({ provider: "compatible-endpoint", model: "test-model" }); + + expect(calls.preflightGatewayRouteDiscovery).toHaveBeenCalledWith( + expect.objectContaining({ nativeLocalSelection: true }), + ); + expect(calls.checkGatewayRouteCompatibility).not.toHaveBeenCalled(); + }, + ); + + it("rejects malformed shared peer state before native local selection (#12975)", () => { + const { calls } = createDeps(); + calls.preflightGatewayRouteDiscovery.mockReturnValue({ + ok: false, + result: { + ok: false, + gatewayName: "nemoclaw-9090", + sandboxName: "target-sandbox", + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "broken-peer", reason: "invalid-gateway-binding" }], + }, + }); + + expect(() => + guardProviderInferenceRouteSelection( + { + checkGatewayRouteCompatibility: calls.checkGatewayRouteCompatibility, + preflightGatewayRouteDiscovery: calls.preflightGatewayRouteDiscovery, + error: calls.error, + exitProcess: calls.exit, + }, + "nemoclaw-9090", + "target-sandbox", + true, + { + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + }, + ), + ).toThrow("exit 1"); + expect(calls.error).toHaveBeenCalledWith(expect.stringContaining("broken-peer")); + expect(calls.checkGatewayRouteCompatibility).not.toHaveBeenCalled(); + }); + it("allows fresh selection to continue so setup can issue the mutation warning (#6315)", async () => { const { calls, deps } = createDeps(); reportDifferentRoute(calls, "nvidia-prod", "nvidia/test"); diff --git a/src/lib/onboard/machine/handlers/provider-inference-route-containment.ts b/src/lib/onboard/machine/handlers/provider-inference-route-containment.ts index 9a765d7cdb2..0c29b6b91fb 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-route-containment.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-route-containment.ts @@ -34,7 +34,19 @@ export function assertProviderInferenceRouteCompatible( gatewayName: string, sandboxName: string | null, route: GatewayInferenceRoute, + nativeLocalSelection = false, ): void { + if (nativeLocalSelection) { + const preflight = deps.preflightGatewayRouteDiscovery({ + gatewayName, + sandboxName, + route: { ...route, model: route.model ?? null }, + nativeLocalSelection: true, + }); + if (preflight.ok) return; + deps.error(` Error: ${formatGatewayRouteConflict(preflight.result)}`); + deps.exitProcess(1); + } const compatibility = deps.checkGatewayRouteCompatibility({ gatewayName, sandboxName, route }); if (!compatibility.ok) { if (isAdvisoryGatewayRouteConflict(compatibility)) return; @@ -48,6 +60,7 @@ export function guardProviderInferenceRouteSelection( deps: ProviderInferenceRouteContainmentDeps, gatewayName: string, sandboxName: string | null, + nativeLocalSelection: boolean, route: ProviderInferenceProbeRoute, ): GatewayRouteDiscoveryConstraints { const model = typeof route.model === "string" && route.model.trim() ? route.model : null; @@ -55,6 +68,7 @@ export function guardProviderInferenceRouteSelection( gatewayName, sandboxName, route: { ...route, model }, + ...(nativeLocalSelection ? { nativeLocalSelection: true } : {}), }); if (!preflight.ok) { if (isAdvisoryGatewayRouteConflict(preflight.result)) { @@ -63,6 +77,7 @@ export function guardProviderInferenceRouteSelection( deps.error(` Error: ${formatGatewayRouteConflict(preflight.result)}`); deps.exitProcess(1); } + if (nativeLocalSelection) return unconstrainedGatewayRouteDiscovery(); const provider = typeof route.provider === "string" ? route.provider.trim() : ""; const completeCustomRoute = !["compatible-endpoint", "compatible-anthropic-endpoint", "llama-cpp-local"].includes( diff --git a/src/lib/onboard/machine/handlers/provider-inference-selected-agent.test.ts b/src/lib/onboard/machine/handlers/provider-inference-selected-agent.test.ts new file mode 100644 index 00000000000..efc1235b131 --- /dev/null +++ b/src/lib/onboard/machine/handlers/provider-inference-selected-agent.test.ts @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { expect, it, vi } from "vitest"; + +import { createSession } from "../../../state/onboard-session"; +import { createSetupInference, type SetupInferenceDeps } from "../../setup-inference"; +import { handleProviderInferenceState } from "./provider-inference"; +import { baseOptions, baseSelection, createDeps } from "./provider-inference.test-support"; + +it.each(["openclaw", "langchain-deepagents-code"])( + "admits selected %s local inference when the prior registration was Hermes", + async (name) => { + const { deps, calls } = createDeps(); + const session = createSession(); + calls.setupNim.mockResolvedValue({ + ...baseSelection, + provider: "ollama-local", + model: "local-model", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: null, + }); + await handleProviderInferenceState({ + ...baseOptions(deps, session), + sandboxName: "same-sandbox", + agent: { name }, + }); + + // Stop at the next real boundary after agent admission, before provider mutation. + const policyFailure = new Error("fixture policy unavailable"); + const requireNativeProviderPolicy = vi.fn(async () => { + throw policyFailure; + }); + const setup = createSetupInference({ + getGatewayName: () => "nemoclaw", + getSandbox: () => ({ agent: "hermes" }), + requireNativeProviderPolicy, + } as unknown as SetupInferenceDeps); + expect(calls.setupInference).toHaveBeenCalledOnce(); + await expect(setup(...calls.setupInference.mock.calls[0]!)).rejects.toBe(policyFailure); + expect(requireNativeProviderPolicy).toHaveBeenCalledWith("nemoclaw"); + }, +); + +it.each(["pi", "hermes"])( + "keeps selected %s local inference on the existing shared route", + async (name) => { + const { deps, calls } = createDeps(); + const session = createSession(); + calls.setupNim.mockResolvedValue({ + ...baseSelection, + provider: name === "pi" ? "compatible-endpoint" : "ollama-local", + model: "local-model", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: null, + }); + + await handleProviderInferenceState({ + ...baseOptions(deps, session), + sandboxName: "same-sandbox", + agent: { name }, + }); + + expect(calls.setupInference).toHaveBeenCalledOnce(); + expect(calls.setupInference.mock.calls[0]?.[7]).toEqual( + expect.objectContaining({ agentName: name }), + ); + }, +); diff --git a/src/lib/onboard/machine/handlers/provider-inference.test.ts b/src/lib/onboard/machine/handlers/provider-inference.test.ts index 419687d02da..31782e1b8dd 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test.ts @@ -1468,6 +1468,7 @@ describe("handleProviderInferenceState", () => { null, [], setupOptions(session, { + agentName: "openclaw", allowToolsIncompatible: true, preferredInferenceApi: "openai-responses", deferPublishedRouteReservation: true, diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 8b76dec3ce9..d066f8e59b3 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -3,7 +3,12 @@ import type { ModelSelectionProvenance } from "../../../domain/telemetry/provenance"; import { clearAutoDetectedCompatibleContextWindow } from "../../../inference/compatible-endpoint-context"; -import { resolveAgentProviderInferenceApi } from "../../../inference/config"; +import { + hasLegacySharedLocalInferenceRoute, + resolveAgentProviderInferenceApi, + usesNativeLocalInference, + usesNativeLocalInferenceForAgent, +} from "../../../inference/config"; import type { TrustedPrivateEndpointCapability } from "../../../inference/endpoint-ssrf-preflight"; import { type CurrentGatewayRouteCompatibilityCheck, @@ -18,6 +23,7 @@ import { OPENROUTER_PROVIDER_NAME } from "../../../inference/openrouter"; import type { InferenceEndpointSource } from "../../../inference/selection"; import type { ServingProfileProvenance } from "../../../inference/serving/types"; import type { WebSearchConfig } from "../../../inference/web-search"; +import type { SandboxEntry } from "../../../state/registry"; import type { HermesAuthMethod, Session, SessionUpdates } from "../../../state/onboard-session"; import { LLAMA_CPP_PORT } from "../../../inference/llama-cpp/contract"; import { @@ -83,6 +89,7 @@ function selectedNativeInference( } export interface ProviderInferenceSetupOptions { + agentName?: string; gatewayName?: string; allowToolsIncompatible?: boolean; skipHostInferenceSmoke?: boolean; @@ -308,6 +315,7 @@ export interface ProviderInferenceStateOptions { getOpenshellBinary(): string; needsBedrockRuntimeAdapter(provider: string, endpointUrl: string | null): boolean; isInferenceRouteReady(gatewayName: string, provider: string, model: string): boolean; + getSandboxRegistryEntry?(sandboxName: string): Partial | null; isRoutedInferenceProvider(provider: string): boolean; reconcileModelRouter(): Promise; reupsertRoutedProvider( @@ -1259,6 +1267,31 @@ async function resolveSelectionSandboxName( return deps.promptValidatedSandboxName(agent); } +function nativeLocalAgentOptions(agent: unknown, provider: string, endpointUrl: string | null) { + return usesNativeLocalInference(provider, endpointUrl) ? { agentName: agentName(agent) } : {}; +} + +function assertNoLegacySharedLocalResume( + deps: Pick< + ProviderInferenceStateOptions["deps"], + "getSandboxRegistryEntry" + >, + effectiveResume: boolean, + sandboxName: string | null, +): void { + const recorded = + effectiveResume && sandboxName ? deps.getSandboxRegistryEntry?.(sandboxName) : null; + if ( + recorded && + recorded.pendingRouteReservation !== true && + hasLegacySharedLocalInferenceRoute(recorded) + ) { + throw new Error( + `Sandbox ${sandboxName} uses a legacy shared local inference route. Resume is unavailable for this route. Back up the sandbox, then re-onboard it with --fresh --name ${sandboxName} --recreate-sandbox to attach a native provider before upgrading OpenShell.`, + ); + } +} + export async function handleProviderInferenceState({ gatewayName, resume, @@ -1476,15 +1509,16 @@ export async function handleProviderInferenceState({ forceInferenceSetup ||= completeRecoveredReviewSelectionAfterInference || reviewRecoveredInteractively; let managedLlamaCppRecovered = false; + assertNoLegacySharedLocalResume(deps, effectiveResume, sandboxName); if (resumeProviderSelection) { assertOnboardReasoningEffortRoute(reasoningEffortRequest, provider, preferredInferenceApi); - assertProviderInferenceRouteCompatible(deps, gatewayName, sandboxName, { - provider, - model, - endpointUrl, - credentialEnv, - preferredInferenceApi, - }); + assertProviderInferenceRouteCompatible( + deps, + gatewayName, + sandboxName, + { provider, model, endpointUrl, credentialEnv, preferredInferenceApi }, + usesNativeLocalInferenceForAgent(agentName(agent), provider, endpointUrl), + ); // A completed provider-selection checkpoint is not proof that a managed // host runtime survived a process or gateway restart. Recover the exact // gateway-owned llama.cpp lifecycle before the selection shortcut can @@ -1612,11 +1646,25 @@ export async function handleProviderInferenceState({ agent, recoverRecordedProvider, gatewayName, - (route) => guardProviderInferenceRouteSelection(deps, gatewayName, sandboxName, route), + (route) => + guardProviderInferenceRouteSelection( + deps, + gatewayName, + sandboxName, + usesNativeLocalInferenceForAgent( + agentName(agent), + route.provider, + route.endpointUrl, + ), + route, + ), (provider) => { const preflight = deps.preflightGatewayRouteDiscovery({ gatewayName, sandboxName, + ...(usesNativeLocalInferenceForAgent(agentName(agent), provider) + ? { nativeLocalSelection: true } + : {}), route: { provider, model: null, @@ -1704,13 +1752,13 @@ export async function handleProviderInferenceState({ ); if (!resumeProviderSelection) { assertOnboardReasoningEffortRoute(reasoningEffortRequest, provider, preferredInferenceApi); - assertProviderInferenceRouteCompatible(deps, gatewayName, sandboxName, { - provider, - model, - endpointUrl, - credentialEnv, - preferredInferenceApi, - }); + assertProviderInferenceRouteCompatible( + deps, + gatewayName, + sandboxName, + { provider, model, endpointUrl, credentialEnv, preferredInferenceApi }, + usesNativeLocalInferenceForAgent(agentName(agent), provider, endpointUrl), + ); } if ( shouldRecordProviderSelection && @@ -1831,6 +1879,7 @@ export async function handleProviderInferenceState({ if (!sandboxName) sandboxName = await deps.promptValidatedSandboxName(agent); const confirmedSandboxName = sandboxName; const inferenceOptions = { + ...nativeLocalAgentOptions(agent, selectedProvider, endpointUrl), gatewayName, allowToolsIncompatible, ...(skipHostInferenceSmoke ? { skipHostInferenceSmoke } : {}), @@ -1922,13 +1971,19 @@ export async function handleProviderInferenceState({ const getRouterPort = deps.getModelRouterPort ?? resolveModelRouterPort; const routedRepair = await deps.withGatewayRouteMutationLock(gatewayName, () => withRouterPortLifecycleLock(getRouterPort(), async () => { - assertProviderInferenceRouteCompatible(deps, gatewayName, sandboxName, { - provider: selectedProvider, - model: selectedModel, - endpointUrl, - credentialEnv, - preferredInferenceApi, - }); + assertProviderInferenceRouteCompatible( + deps, + gatewayName, + sandboxName, + { + provider: selectedProvider, + model: selectedModel, + endpointUrl, + credentialEnv, + preferredInferenceApi, + }, + usesNativeLocalInferenceForAgent(agentName(agent), selectedProvider, endpointUrl), + ); try { await deps.reconcileModelRouter(); } catch (err) { @@ -1985,13 +2040,19 @@ export async function handleProviderInferenceState({ } if (resumeReservationName && !routedInferenceProvider) { const reserved = await deps.withGatewayRouteMutationLock(gatewayName, () => { - assertProviderInferenceRouteCompatible(deps, gatewayName, resumeReservationName, { - provider: selectedProvider, - model: selectedModel, - endpointUrl, - credentialEnv, - preferredInferenceApi, - }); + assertProviderInferenceRouteCompatible( + deps, + gatewayName, + resumeReservationName, + { + provider: selectedProvider, + model: selectedModel, + endpointUrl, + credentialEnv, + preferredInferenceApi, + }, + usesNativeLocalInferenceForAgent(agentName(agent), selectedProvider, endpointUrl), + ); return reserveRecoveredSandboxInferenceRoute( deps.reserveSandboxInferenceRoute, resumeReservationName, @@ -2136,6 +2197,7 @@ export async function handleProviderInferenceState({ deps.prepareLocalProviderForInference, ); const inferenceOptions = { + ...nativeLocalAgentOptions(agent, selectedProvider, endpointUrl), gatewayName, allowToolsIncompatible, ...legacyRecordedNoAuthEndpointSetupOptions({ diff --git a/src/lib/onboard/machine/handlers/sandbox-dcode-resume.ts b/src/lib/onboard/machine/handlers/sandbox-dcode-resume.ts index 0668f68b372..c1145c78950 100644 --- a/src/lib/onboard/machine/handlers/sandbox-dcode-resume.ts +++ b/src/lib/onboard/machine/handlers/sandbox-dcode-resume.ts @@ -119,9 +119,11 @@ export async function resolveSignals( options.provider, options.model, options.preferredInferenceApi, - options.endpointUrl, + registryEntry.nativeLocalProviderAttachment?.endpointUrl ?? options.endpointUrl, Boolean( - registryEntry.nativeHostedProviderAttachment || registryEntry.nativeNvidiaProviderAttachment, + registryEntry.nativeLocalProviderAttachment || + registryEntry.nativeHostedProviderAttachment || + registryEntry.nativeNvidiaProviderAttachment, ), ); return { diff --git a/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts b/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts index eb189959d5a..62d49c5a5e0 100644 --- a/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts @@ -9,10 +9,39 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { testTimeoutOptions } from "../../../../../test/helpers/timeouts"; +import { nativeLocalIdentity } from "../../../inference/native-local/contract"; +import * as registry from "../../../state/registry"; import { handleSandboxState } from "./sandbox"; import { baseOptions, createDeps } from "./sandbox-test-fixtures"; describe("sandbox registration route transaction", () => { + const nativeEndpoint = "http://host.openshell.internal:11434/v1"; + const nativeBinding = { + provider: "compatible-endpoint", + endpointUrl: nativeEndpoint, + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "my-assistant", + } as const; + const nativeAttachment = { + ...nativeBinding, + ...nativeLocalIdentity(nativeBinding), + schemaVersion: 1 as const, + providerId: "native-provider-id", + }; + const nativeEntry = { + name: "my-assistant", + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: nativeEndpoint, + endpointSource: "onboard" as const, + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + gatewayName: "nemoclaw", + nativeLocalProviderAttachment: nativeAttachment, + }; + beforeEach(() => { vi.stubEnv("HOME", fs.mkdtempSync(path.join(os.tmpdir() ?? "/tmp", "nemoclaw-sandbox-route-"))); }); @@ -20,6 +49,7 @@ describe("sandbox registration route transaction", () => { afterEach(() => { fs.rmSync(process.env.HOME!, { force: true, recursive: true }); vi.unstubAllEnvs(); + vi.restoreAllMocks(); }); it("allows valid peer-route drift after waiting for the gateway lock", async () => { @@ -65,6 +95,156 @@ describe("sandbox registration route transaction", () => { expect(calls.error).not.toHaveBeenCalled(); }); + it.each(["openclaw", "langchain-deepagents-code"])( + "accepts %s exact native local reservation before sandbox creation (#12975)", + async (agentName) => { + const startRecordedStep = vi.fn(async () => { + throw new Error("past-native-route-guard"); + }); + const checkGatewayRouteCompatibility = vi.fn(() => ({ + ok: false as const, + gatewayName: "nemoclaw", + sandboxName: null, + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "shared-peer", reason: "custom-endpoint" as const }], + })); + const { calls, deps } = createDeps({ + checkGatewayRouteCompatibility, + getSandboxRegistryEntry: () => ({ ...nativeEntry }), + startRecordedStep, + }); + + await expect( + handleSandboxState({ + ...baseOptions(deps), + agent: { name: agentName }, + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: nativeEndpoint, + endpointSource: "onboard", + credentialEnv: "COMPATIBLE_API_KEY", + }), + ).rejects.toThrow("past-native-route-guard"); + + expect(checkGatewayRouteCompatibility).not.toHaveBeenCalled(); + expect(startRecordedStep).toHaveBeenCalledOnce(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + expect(calls.error).not.toHaveBeenCalled(); + }, + ); + + it("rejects a changed native local reservation before sandbox creation (#12975)", async () => { + const { calls, deps } = createDeps({ + getSandboxRegistryEntry: () => ({ + ...nativeEntry, + endpointUrl: "http://host.openshell.internal:8000/v1", + }), + }); + + await expect( + handleSandboxState({ + ...baseOptions(deps), + agent: { name: "openclaw" }, + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: nativeEndpoint, + endpointSource: "onboard", + credentialEnv: "COMPATIBLE_API_KEY", + }), + ).rejects.toThrow("exit 1"); + + expect(calls.error).toHaveBeenCalledWith(expect.stringContaining("reservation")); + expect(calls.createSandbox).not.toHaveBeenCalled(); + }); + + it("does not bypass shared route conflicts without a native local attachment (#12975)", async () => { + const { nativeLocalProviderAttachment: _attachment, ...legacyEntry } = nativeEntry; + const checkGatewayRouteCompatibility = vi.fn(() => ({ + ok: false as const, + gatewayName: "nemoclaw", + sandboxName: null, + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "my-assistant", reason: "custom-endpoint" as const }], + })); + const { calls, deps } = createDeps({ + checkGatewayRouteCompatibility, + getSandboxRegistryEntry: () => legacyEntry, + }); + + await expect( + handleSandboxState({ + ...baseOptions(deps), + agent: { name: "openclaw" }, + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: nativeEndpoint, + endpointSource: "onboard", + credentialEnv: "COMPATIBLE_API_KEY", + }), + ).rejects.toThrow("exit 1"); + + expect(checkGatewayRouteCompatibility).toHaveBeenCalledOnce(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + }); + + it.each([ + ["pi", nativeEndpoint], + ["hermes", nativeEndpoint], + ["openclaw", "https://hosted.example.test/v1"], + ])("keeps %s at %s on the shared route guard (#12975)", async (agentName, endpointUrl) => { + const checkGatewayRouteCompatibility = vi.fn(() => ({ + ok: false as const, + gatewayName: "nemoclaw", + sandboxName: null, + route: { provider: "compatible-endpoint", model: "test-model" }, + conflicts: [{ sandboxName: "shared-peer", reason: "custom-endpoint" as const }], + })); + const { calls, deps } = createDeps({ + checkGatewayRouteCompatibility, + getSandboxRegistryEntry: () => ({ ...nativeEntry }), + }); + + await expect( + handleSandboxState({ + ...baseOptions(deps), + agent: { name: agentName }, + provider: "compatible-endpoint", + model: "test-model", + endpointUrl, + endpointSource: "onboard", + credentialEnv: "COMPATIBLE_API_KEY", + }), + ).rejects.toThrow("exit 1"); + + expect(checkGatewayRouteCompatibility).toHaveBeenCalledOnce(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + }); + + it.each(["pi", "hermes"])( + "does not carry OpenClaw's native local provider into %s sandbox creation (#12975)", + async (agentName) => { + vi.spyOn(registry, "getSandbox").mockReturnValue(null); + const { calls, deps } = createDeps({ + getSandboxRegistryEntry: () => ({ ...nativeEntry }), + }); + + await handleSandboxState({ + ...baseOptions(deps), + agent: { name: agentName }, + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: nativeEndpoint, + endpointSource: "onboard", + credentialEnv: "COMPATIBLE_API_KEY", + }); + + const createIntent = calls.resolveCreateIntent.mock.calls[0]?.[0]; + expect(createIntent?.inferenceProvider).toBe("compatible-endpoint"); + expect(createIntent).not.toHaveProperty("nativeLocalProviderAttachment"); + expect(createIntent).toMatchObject({ hostLocalInferenceRouteOnly: false }); + }, + ); + it("stages credentials, then holds sandbox, host dashboard, and gateway locks through creation", async () => { const events: string[] = []; let releaseProviderPlan!: () => void; 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 2655b50ec44..5f7977333b9 100644 --- a/src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts @@ -1,7 +1,8 @@ // 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 fs from "node:fs"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { createSession } from "../../../state/onboard-session"; import type { SandboxEntry } from "../../../state/registry"; @@ -13,6 +14,24 @@ vi.mock("../../messaging-channel-setup", () => ({ detectUnconfiguredMessagingChannels: vi.fn(() => []), })); +const testHome = await vi.hoisted(async () => { + const fs = await import("node:fs"); + const os = await import("node:os"); + const path = await import("node:path"); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "sandbox-route-publication-")); + vi.stubEnv("HOME", directory); + return directory; +}); + +beforeEach((context) => { + vi.stubEnv("HOME", testHome); + fs.mkdirSync(testHome, { recursive: true }); + context.onTestFinished(() => { + vi.unstubAllEnvs(); + fs.rmSync(testHome, { recursive: true, force: true }); + }); +}); + describe("sandbox route publication", () => { it("reuses an already-published route without finalizing a stale session reservation", async () => { const session = createSession({ sandboxName: "saved" }); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 1390010cba4..b3f0b04e76e 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -99,6 +99,7 @@ import { } from "../../sandbox-recreate-transaction"; import { nativeInferenceCreateIntentFields, + nativeLocalReservationStatus, sandboxCreateInferenceSelection, withSandboxImageRegistrationFence, } from "../../sandbox-registration"; @@ -357,6 +358,7 @@ export interface SandboxStateOptions< resolveSandboxCreateIntent(input: { sandboxName: string; inferenceProvider?: string | null; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; hostLocalInferenceRouteOnly?: boolean; @@ -1229,6 +1231,7 @@ class SandboxStateFlow< ` Error: sandbox '${sandboxName}' changed OpenShell gateways while onboarding was in progress. Retry onboarding.`, ); } + if (this.acceptsNativeLocalReservation(targetEntry, sandboxName)) return; const compatibility = this.deps.checkGatewayRouteCompatibility({ gatewayName: this.options.gatewayName, // A deferred route still belongs to the published source until backup @@ -1252,6 +1255,33 @@ class SandboxStateFlow< this.failGatewayRouteCheck(` Error: ${formatGatewayRouteConflict(compatibility)}`); } + private acceptsNativeLocalReservation(targetEntry: SandboxEntry, sandboxName: string): boolean { + if (!targetEntry.nativeLocalProviderAttachment) return false; + const agentName = (this.options.agent as { name?: string } | null)?.name ?? "openclaw"; + let mismatchFields: readonly string[] = []; + const nativeLocalReservation = nativeLocalReservationStatus({ + entry: targetEntry, + agentName, + sandboxName, + gatewayName: this.options.gatewayName, + provider: this.options.provider, + model: this.options.model, + endpointUrl: this.options.endpointUrl, + endpointSource: this.options.endpointSource ?? null, + credentialEnv: this.options.credentialEnv ?? null, + preferredInferenceApi: this.options.preferredInferenceApi ?? null, + onMismatch: (fields) => { + mismatchFields = fields; + }, + }); + if (nativeLocalReservation === "changed") { + this.failGatewayRouteCheck( + ` Error: native local inference reservation for sandbox '${sandboxName}' changed while onboarding was in progress (${mismatchFields.join(", ")}). Retry onboarding.`, + ); + } + return nativeLocalReservation === "exact"; + } + private publishedRecreateSourceForRouteCheck( sandboxName: string, targetEntry: SandboxEntry, @@ -1919,7 +1949,13 @@ class SandboxStateFlow< const registeredEntry = this.deps.getSandboxRegistryEntry(sandboxName); const resolved = await this.deps.resolveSandboxCreateIntent({ sandboxName, - ...nativeInferenceCreateIntentFields(this.options.provider, registeredEntry), + ...nativeInferenceCreateIntentFields({ + agentName: (this.options.agent as { name?: string } | null)?.name ?? "openclaw", + provider: this.options.provider, + endpointUrl: this.options.endpointUrl, + gatewayName: this.options.gatewayName, + entry: registeredEntry, + }), hostLocalInferenceRouteOnly: this.options.hostLocalInferenceRouteOnly === true, enabledChannels: state.selectedMessagingChannels, webSearchConfig: state.webSearchConfig, @@ -1932,6 +1968,8 @@ class SandboxStateFlow< hostMounts: this.options.hostMounts, ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), }); + const endpointUrl = + resolved.nativeLocalProviderAttachment?.endpointUrl ?? this.options.endpointUrl; const recreate = requiresSandboxRecreation(decision, this.options.recreateSandbox(false)); return { resolved, @@ -1954,7 +1992,7 @@ class SandboxStateFlow< }) ?? toolDisclosureOrDefault(state.session?.toolDisclosure), observabilityEnabled: state.session?.observabilityEnabled === true, ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true as const } : {}), - ...(this.options.endpointUrl ? { endpointUrl: this.options.endpointUrl } : {}), + ...(endpointUrl ? { endpointUrl } : {}), ...compatibleEndpointReasoningForCreateIntent(this.options.compatibleEndpointReasoning), endpointSource: this.options.endpointSource ?? null, ...(this.options.deferredN1xManagedVllmPreviewIntent === true diff --git a/src/lib/onboard/managed-workload-clone-handoff.test.ts b/src/lib/onboard/managed-workload-clone-handoff.test.ts index 80a1e2a0f97..e62c11508ad 100644 --- a/src/lib/onboard/managed-workload-clone-handoff.test.ts +++ b/src/lib/onboard/managed-workload-clone-handoff.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeLocalIdentity } from "../inference/native-local/contract"; import { createHash } from "node:crypto"; import { describe, expect, it, vi } from "vitest"; @@ -36,6 +37,21 @@ const PORTABLE_PROFILE = { legacyDockerfileBuilds: false, } as const satisfies RuntimeProviderWorkloadProfile; +const localBinding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "alpha", +} as const; +const localReceipt = { + ...localBinding, + ...nativeLocalIdentity(localBinding), + schemaVersion: 1 as const, + providerId: "owned-local-provider", +}; + function provider(providerId: "docker" | "mxc"): RuntimeProviderBundle { return providerId === "docker" ? CURRENT_RUNTIME_PROVIDER_BUNDLES.docker! @@ -179,6 +195,12 @@ function prepare( } describe("prepareManagedWorkloadCloneHandoff", () => { + it("refuses to copy a native local provider attachment to another sandbox (#12558)", () => { + const entry = source("openclaw", "docker"); + entry.nativeLocalProviderAttachment = localReceipt; + expect(() => prepare(entry, provider("docker"))).toThrow(/cannot be cloned/); + }); + it.each([ ["docker", "openclaw"], ["docker", "hermes"], 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 new file mode 100644 index 00000000000..488a7f62d8a --- /dev/null +++ b/src/lib/onboard/managed-workload/native-local-startup-route.test.ts @@ -0,0 +1,97 @@ +// 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 { nativeLocalIdentity } from "../../inference/native-local/contract"; +import { getSandboxInferenceConfig, resolveAgentInferenceApi } from "../../inference/config"; +import { createManagedWorkloadOnboardRuntime } from "./onboard-orchestration"; + +const nativeBinding = { + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "alpha", +} as const; +const nativeAttachment = { + ...nativeBinding, + ...nativeLocalIdentity(nativeBinding), + schemaVersion: 1 as const, + providerId: "fixture-provider", +}; +const routes = [ + { + name: "resolved native attachment", + endpointUrl: null, + attachment: nativeAttachment, + expected: nativeBinding.endpointUrl, + }, + { + name: "legacy ephemeral endpoint", + endpointUrl: "http://host.openshell.internal:42103/v1", + expected: "https://inference.local/v1", + }, + { + name: "unattached native endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + expected: "https://inference.local/v1", + }, +] as const; + +describe.each(["openclaw", "hermes", "langchain-deepagents-code"] as const)( + "%s managed startup inference", + (agentName) => { + it.each(routes)("keeps $name on its selected transport (#12558)", (route) => { + const { endpointUrl } = route; + const expected = agentName === "hermes" ? "https://inference.local/v1" : route.expected; + const runtime = createManagedWorkloadOnboardRuntime( + { + computePlan: { driverName: "docker", gatewayLauncher: "nemoclaw" }, + managedWorkloadRebuild: null, + tempManagedRuntime: false, + stockManagedRuntime: true, + tempManagedRuntimeCatalog: null, + agentName, + legacyDockerfilePath: "Dockerfile", + customDockerfilePath: null, + rootDir: process.cwd(), + model: "fixture-model", + provider: "compatible-endpoint", + preferredInferenceApi: "openai-completions", + endpointUrl, + ...("attachment" in route ? { nativeLocalProviderAttachment: route.attachment } : {}), + startupProfile: { + chatUiUrl: "http://localhost:18789", + effectiveDashboardPort: 18789, + dashboardBindAddress: undefined, + manageDashboard: agentName !== "langchain-deepagents-code", + wslExposure: false, + hermesDashboardState: { + config: { enabled: false, port: 19189, internalPort: 29189, tuiEnabled: false }, + enabled: false, + }, + webSearch: null, + toolDisclosure: "progressive", + hermesToolGateways: [], + messagingPlan: null, + dcodeAutoApprovalMode: "disabled", + observabilityEnabled: false, + environment: {}, + }, + note: vi.fn(), + fallbackBuildEstimate: () => null, + }, + { getSandboxInferenceConfig, resolveAgentInferenceApi }, + ); + const prepared = runtime.ensurePreparedProfile({ + source: { kind: "managed-image" }, + } as never); + expect(prepared?.profile.inference).toMatchObject({ + model: "fixture-model", + upstreamProvider: "compatible-endpoint", + routedBaseUrl: expected, + }); + }); + }, +); diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index 1c64f25b63b..62788989cb2 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -4,6 +4,7 @@ import { isCandidateAgent, readCandidateQualificationReceipt } from "../../agent/candidate"; import type { AgentDefinition } from "../../agent/defs"; import { getVersion } from "../../core/version"; +import { usesNativeLocalInference } from "../../inference/config"; import type { SandboxMessagingPlan } from "../../messaging/manifest"; import type { SandboxEntry, SandboxWorkloadReceipt } from "../../state/registry/types"; import type { ToolDisclosure } from "../../tool-disclosure"; @@ -197,6 +198,7 @@ export interface CreateManagedWorkloadOnboardRuntimeInput { readonly provider: string | null; readonly preferredInferenceApi: string | null; readonly endpointUrl: string | null; + readonly nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; readonly nativeProvider?: boolean; readonly startupProfile: ManagedProfileInput; readonly note: (message: string) => void; @@ -395,8 +397,15 @@ export function createManagedWorkloadOnboardRuntime( return input.managedWorkloadRebuild.replacementProfile; } if (preparedProfile) return preparedProfile; + const nativeLocalProviderAttachment = + input.agentName === "openclaw" || input.agentName === "langchain-deepagents-code" + ? input.nativeLocalProviderAttachment + : undefined; const selectedModel = input.model?.trim() || ""; const selectedProvider = input.provider?.trim() || null; + const endpointUrl = + nativeLocalProviderAttachment?.endpointUrl ?? + (usesNativeLocalInference(selectedProvider, input.endpointUrl) ? null : input.endpointUrl); const inferenceApi = input.agentName === "langchain-deepagents-code" ? "openai-completions" @@ -410,12 +419,12 @@ export function createManagedWorkloadOnboardRuntime( selectedProvider, inferenceApi, input.nativeProvider ?? true, - input.endpointUrl, + endpointUrl, ); preparedProfile = buildManagedStartupOnboardProfile({ agentName: input.agentName, inference: - !selectedModel && !selectedProvider && !input.preferredInferenceApi && !input.endpointUrl + !selectedModel && !selectedProvider && !input.preferredInferenceApi && !endpointUrl ? null : { routeProvider: inference.providerKey, @@ -423,7 +432,7 @@ export function createManagedWorkloadOnboardRuntime( model: selectedModel, routedBaseUrl: inference.inferenceBaseUrl, upstreamEndpointUrl: - input.agentName === "langchain-deepagents-code" ? input.endpointUrl : null, + input.agentName === "langchain-deepagents-code" ? endpointUrl : null, api: inference.inferenceApi as | "openai-completions" | "openai-responses" diff --git a/src/lib/onboard/openclaw-setup.test.ts b/src/lib/onboard/openclaw-setup.test.ts index f2023c05ea4..e2286eeac1a 100644 --- a/src/lib/onboard/openclaw-setup.test.ts +++ b/src/lib/onboard/openclaw-setup.test.ts @@ -457,26 +457,41 @@ describe("restored native OpenClaw inference fields", () => { }); }); -describe("initial Hermes provider selection", () => { +describe("initial native or shared provider selection", () => { it.each([ { + provider: "hermes-provider", nativeProvider: false, endpointUrl: "https://custom.example/v1", expected: "https://inference.local/v1", }, { + provider: "hermes-provider", nativeProvider: true, endpointUrl: "https://authenticated.example/v1", expected: "https://authenticated.example/v1", }, { + provider: "hermes-provider", nativeProvider: true, endpointUrl: "https://inference-api.nousresearch.com/v1", expected: "https://inference-api.nousresearch.com/v1", }, + { + provider: "vllm-local", + nativeProvider: false, + endpointUrl: "http://host.openshell.internal:8000/v1", + expected: "https://inference.local/v1", + }, + { + provider: "vllm-local", + nativeProvider: true, + endpointUrl: "http://host.openshell.internal:8000/v1", + expected: "http://host.openshell.internal:8000/v1", + }, ])( "preserves $endpointUrl with nativeProvider=$nativeProvider", - async ({ expected, ...selection }) => { + async ({ expected, provider, ...selection }) => { const config = {}; const writeConfig = vi.fn(); const readInferenceSelection = vi.fn(() => selection); @@ -486,11 +501,11 @@ describe("initial Hermes provider selection", () => { patchOpenclawInferenceConfig: patchOpenClawInferenceConfig, writeOpenclawInferenceConfigNatively: writeConfig, }); - await write("alpha", "fixture-model", "hermes-provider", null, "selected-gateway"); + await write("alpha", "fixture-model", provider, null, "selected-gateway"); expect(readInferenceSelection).toHaveBeenCalledExactlyOnceWith( "alpha", "selected-gateway", - "hermes-provider", + provider, ); expect(writeConfig).toHaveBeenCalledWith( "alpha", @@ -502,7 +517,7 @@ describe("initial Hermes provider selection", () => { await write( "alpha", "fixture-model", - "hermes-provider", + provider, null, "selected-gateway", undefined, diff --git a/src/lib/onboard/openclaw/initial-inference-route.ts b/src/lib/onboard/openclaw/initial-inference-route.ts index f1c984b6955..4d1592fb639 100644 --- a/src/lib/onboard/openclaw/initial-inference-route.ts +++ b/src/lib/onboard/openclaw/initial-inference-route.ts @@ -142,9 +142,11 @@ const nativeInferenceRouteDeps: InitialOpenclawInferenceRouteDeps = { throw new Error("Initial OpenClaw inference route does not match its registered selection."); } return { - endpointUrl: entry.endpointUrl, + endpointUrl: entry.nativeLocalProviderAttachment?.endpointUrl ?? entry.endpointUrl, nativeProvider: Boolean( - entry.nativeHostedProviderAttachment || entry.nativeNvidiaProviderAttachment, + entry.nativeLocalProviderAttachment || + entry.nativeHostedProviderAttachment || + entry.nativeNvidiaProviderAttachment, ), }; }, diff --git a/src/lib/onboard/runtime-provider/host-local-inference-routing.ts b/src/lib/onboard/runtime-provider/host-local-inference-routing.ts index 231586916bc..555644d6157 100644 --- a/src/lib/onboard/runtime-provider/host-local-inference-routing.ts +++ b/src/lib/onboard/runtime-provider/host-local-inference-routing.ts @@ -56,6 +56,10 @@ export interface HostLocalInferenceGatewayMutationInput { * owner captures the prior provider and inference selection before returning. */ export interface HostLocalInferenceGatewayMutation { + /** Register native inference through the runtime owner's existing publication journal. */ + registerNativeProvider?: () => Promise< + import("../../inference/native-local/contract").NativeLocalProviderAttachment + >; /** Exact provider mutation owned by a product transaction when supplied. */ upsertProvider?: ( name: string, diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index 90decdbd683..f2f48a8e784 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { NativeLocalProviderAttachment } from "../inference/native-local/contract"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; import type { WebSearchConfig } from "../inference/web-search"; @@ -29,6 +30,7 @@ import { export type CompleteSandboxCreateIntentInput = { sandboxName: string; inferenceProvider?: string | null; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; nativeHostedProviderAttachment?: NativeProviderAttachment; hostLocalInferenceRouteOnly?: boolean; @@ -149,6 +151,7 @@ export function createSandboxCreateIntentResolver< basePolicyPath: deps.getAgentPolicyPath(input.agent) || deps.defaultPolicyPath, sandboxName: input.sandboxName, inferenceProvider: input.inferenceProvider, + nativeLocalProviderAttachment: input.nativeLocalProviderAttachment, nativeNvidiaProviderAttachment: input.nativeNvidiaProviderAttachment, nativeHostedProviderAttachment: input.nativeHostedProviderAttachment, hostLocalInferenceRouteOnly: input.hostLocalInferenceRouteOnly === true, diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index f1ff81d2787..54aec18f9af 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { NativeLocalProviderAttachment } from "../inference/native-local/contract"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; import type { SandboxHostMount } from "../state/registry/types"; @@ -50,6 +51,7 @@ export type SandboxCreatePolicyRequest = { export type SandboxCreateIntent = { readonly sandboxName: string; readonly inferenceProvider: string | null; + readonly nativeLocalProviderAttachment?: NativeLocalProviderAttachment; readonly nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; readonly nativeHostedProviderAttachment?: NativeProviderAttachment; readonly activeMessagingChannels: readonly string[]; @@ -73,6 +75,7 @@ export type ResolveSandboxCreateIntentInput = { basePolicyPath: string; sandboxName: string; inferenceProvider?: string | null; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; nativeHostedProviderAttachment?: NativeProviderAttachment; hostLocalInferenceRouteOnly?: boolean; diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index fd108488f03..7868a5530a1 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -140,6 +140,7 @@ export function resolveSandboxCreateIntent({ basePolicyPath, sandboxName, inferenceProvider, + nativeLocalProviderAttachment, nativeNvidiaProviderAttachment, nativeHostedProviderAttachment, hostLocalInferenceRouteOnly = false, @@ -189,6 +190,7 @@ export function resolveSandboxCreateIntent({ return { sandboxName, inferenceProvider: normalizedInferenceProvider, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), activeMessagingChannels, @@ -206,7 +208,9 @@ export function resolveSandboxCreateIntent({ ? { hostGpuAvailable: sandboxGpuConfig.hostGpuDetected } : {}), additionalPresets: [...hermesToolGateways], - ...(hostLocalInferenceRouteOnly ? { hostLocalInferenceRouteOnly: true as const } : {}), + ...(hostLocalInferenceRouteOnly || nativeLocalProviderAttachment + ? { hostLocalInferenceRouteOnly: true as const } + : {}), ...(agentName !== undefined ? { agentName } : {}), policyTier, }, diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 89eb64bad98..c838639c73c 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -96,6 +96,7 @@ import { validateAttachedHermesToolGatewayProfileBeforeSandboxCreation, verifyNativeHostedAttachmentAfterCreate, validateAttachedMessagingProvidersBeforeSandboxCreation, + verifyNativeLocalAttachmentAfterCreate, verifyNativeNvidiaAttachmentAfterCreate, } from "./provider-publication"; import { @@ -1439,6 +1440,7 @@ export function createProviderEffectBoundary(input: { readonly resumingVerifiedCreate?: boolean; readonly sandboxName: string; readonly gatewayName: string; + readonly expectedNativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; readonly expectedNativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; readonly expectedNativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; readonly preparationInput: ProviderPreparationInput; @@ -1499,6 +1501,18 @@ export function createProviderEffectBoundary(input: { const attachAndVerifyNativeInferenceProvider = async ( context: VerifiedSandboxCreateEffectsContext, ) => { + if (input.expectedNativeLocalProviderAttachment) { + context.revalidateSandboxIdentity( + `attaching native local provider for sandbox '${input.sandboxName}'`, + ); + await verifyNativeLocalAttachmentAfterCreate({ + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + expected: input.expectedNativeLocalProviderAttachment, + deps, + }); + return; + } if ( !usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) && !usesNativeHostedProvider(input.preparationInput.inferenceProvider) @@ -2114,7 +2128,9 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche provider, preferredInferenceApi, endpointUrl: createIntent?.endpointUrl ?? null, + nativeLocalProviderAttachment: resolvedCreateIntent.nativeLocalProviderAttachment, nativeProvider: Boolean( + resolvedCreateIntent.nativeLocalProviderAttachment || resolvedCreateIntent.nativeHostedProviderAttachment || resolvedCreateIntent.nativeNvidiaProviderAttachment, ), @@ -2472,6 +2488,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche preferredInferenceApi, createIntent, nativeProvider: Boolean( + existingSandboxEntry?.nativeLocalProviderAttachment || existingSandboxEntry?.nativeHostedProviderAttachment || existingSandboxEntry?.nativeNvidiaProviderAttachment, ), @@ -2832,8 +2849,12 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche model, chatUiUrl, provider, - endpointUrl: createIntent?.endpointUrl ?? null, + endpointUrl: + resolvedCreateIntent.nativeLocalProviderAttachment?.endpointUrl ?? + createIntent?.endpointUrl ?? + null, nativeProvider: Boolean( + resolvedCreateIntent.nativeLocalProviderAttachment || resolvedCreateIntent.nativeHostedProviderAttachment || resolvedCreateIntent.nativeNvidiaProviderAttachment, ), @@ -3742,6 +3763,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche resumingVerifiedCreate: Boolean(resumeVerifiedCreateInput), sandboxName, gatewayName: GATEWAY_NAME, + expectedNativeLocalProviderAttachment: resolvedCreateIntent.nativeLocalProviderAttachment, expectedNativeNvidiaProviderAttachment: resolvedCreateIntent.nativeNvidiaProviderAttachment, expectedNativeHostedProviderAttachment: resolvedCreateIntent.nativeHostedProviderAttachment, preparationInput: providerPreparationInput, @@ -3850,6 +3872,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche }), sourceRoot: ROOT, buildContextSettings: { + nativeEndpointUrl: resolvedCreateIntent.nativeLocalProviderAttachment?.endpointUrl, model, provider, preferredInferenceApi, diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index efc3a68cc5e..5705a0efe7d 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -3,6 +3,7 @@ import path from "node:path"; +import { ensureNativeLocalProviderAttached } from "../../inference/native-local/profile"; import { isNativeHostedProviderName } from "../../inference/native-provider/hosted-attachment"; import { hostedNativeProviderForAttachment } from "../../inference/native-provider/hosted-attachment"; import { nativeProviderLifecycle } from "../../inference/native-provider"; @@ -253,6 +254,21 @@ export async function verifyNativeNvidiaAttachmentAfterCreate(input: { }); } +export async function verifyNativeLocalAttachmentAfterCreate(input: { + readonly sandboxName: string; + readonly gatewayName: string; + readonly expected: NonNullable; + readonly deps: ProviderPreparationDeps; +}): Promise { + if (input.expected.gatewayName !== input.gatewayName) + throw new Error("Native local provider gateway authority changed."); + await ensureNativeLocalProviderAttached({ + adapter: resolveProviderAdapter(input.deps), + sandboxName: input.sandboxName, + expected: input.expected, + }); +} + export function usesNativeHostedProvider(inferenceProvider: string | null): boolean { return isNativeHostedProviderName(inferenceProvider); } diff --git a/src/lib/onboard/sandbox-create/provider-retirement.ts b/src/lib/onboard/sandbox-create/provider-retirement.ts new file mode 100644 index 00000000000..c4d0b0a9f80 --- /dev/null +++ b/src/lib/onboard/sandbox-create/provider-retirement.ts @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createManagedProviderAdapter } from "../../adapters/openshell/managed-provider-adapter"; +import { retireUnselectedNativeLocalProviders } from "../../inference/native-local/selection"; + +/** Retire former providers only after the caller commits sandbox registration. */ +export async function retireUnselectedCreatedSandboxProviders( + input: Omit[0], "adapter">, + retire: typeof retireUnselectedNativeLocalProviders = retireUnselectedNativeLocalProviders, +): Promise { + await retire({ ...input, adapter: createManagedProviderAdapter() }); +} diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index 48a5a9ff304..3cffc315c97 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -6,6 +6,7 @@ import { createRequire } from "node:module"; import { afterEach, describe, expect, it, vi } from "vitest"; import { managedStartupE2eProfile } from "../../../scripts/checks/generate-managed-startup-profile-fixture.mts"; +import type { AgentDefinition } from "../agent/defs"; import { serializedHostLocalInferenceReceipt, serializedLlamaCppHostLocalInferenceReceipt, @@ -24,6 +25,8 @@ const requireDist = createRequire(import.meta.url); const onboardSession = requireDist("../state/onboard-session.js"); const { buildCreatedSandboxRegistryEntry, + nativeInferenceCreateIntentFields, + nativeLocalReservationStatus, prepareCreatedSandboxRegistration, registerCreatedSandbox, registerPreparedCreatedSandbox, @@ -31,6 +34,10 @@ const { selection, } = requireDist("./sandbox-registration.ts") as typeof import("./sandbox-registration"); +afterEach(() => { + vi.restoreAllMocks(); +}); + const runtimeFields = { gpuEnabled: true, hostGpuDetected: true, @@ -93,6 +100,254 @@ function createdRegistryEntryInput( } describe("buildCreatedSandboxRegistryEntry", () => { + it("retains the managed llama.cpp attachment for its published application route", () => { + const { nativeLocalIdentity } = requireDist( + "../inference/native-local/contract.ts", + ) as typeof import("../inference/native-local/contract"); + const binding = { + provider: "llama-cpp-local" as const, + endpointUrl: "http://host.openshell.internal:8081/v1", + credentialEnv: "NEMOCLAW_LLAMACPP_LOCAL_TOKEN", + authMode: "authenticated" as const, + gatewayName: "nemoclaw", + sandboxName: "demo", + }; + const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "provider-1", + }; + const hostLocalInferenceReceipt = serializedLlamaCppHostLocalInferenceReceipt("docker"); + const base = createdRegistryEntryInput(); + const input = { + ...base, + agent: { name: "openclaw" } as AgentDefinition, + hostLocalInferenceReceipt, + nativeLocalProviderAttachment: attachment, + inferenceSelection: { + ...base.inferenceSelection, + provider: "llama-cpp-local", + endpointUrl: "https://inference.local/v1", + }, + }; + expect(buildCreatedSandboxRegistryEntry(input).nativeLocalProviderAttachment).toEqual( + attachment, + ); + const staleBinding = { ...binding, endpointUrl: "http://host.openshell.internal:8082/v1" }; + expect( + buildCreatedSandboxRegistryEntry({ + ...input, + nativeLocalProviderAttachment: { + ...staleBinding, + ...nativeLocalIdentity(staleBinding), + schemaVersion: 1, + providerId: "stale-provider", + }, + }).nativeLocalProviderAttachment, + ).toBeUndefined(); + expect( + nativeInferenceCreateIntentFields({ + agentName: "openclaw", + provider: "llama-cpp-local", + endpointUrl: "https://inference.local/v1", + gatewayName: "nemoclaw", + entry: buildCreatedSandboxRegistryEntry(input), + }).nativeLocalProviderAttachment, + ).toEqual(attachment); + expect( + nativeLocalReservationStatus({ + entry: buildCreatedSandboxRegistryEntry(input), + agentName: "openclaw", + sandboxName: "demo", + gatewayName: "nemoclaw", + provider: "llama-cpp-local", + model: "llama", + endpointUrl: "https://inference.local/v1", + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + }), + ).toBe("exact"); + const hostSelection = { + entry: buildCreatedSandboxRegistryEntry(input), + agentName: "openclaw", + sandboxName: "demo", + gatewayName: "nemoclaw", + provider: "llama-cpp-local", + model: "llama", + endpointUrl: "http://127.0.0.1:8081/v1", + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + } as const; + expect(nativeLocalReservationStatus(hostSelection)).toBe("exact"); + const onMismatch = vi.fn(); + expect( + nativeLocalReservationStatus({ + ...hostSelection, + endpointUrl: "http://127.0.0.1:8082/v1", + onMismatch, + }), + ).toBe("changed"); + expect(onMismatch).toHaveBeenCalledWith(expect.arrayContaining(["endpointUrl"])); + }); + + it("does not inherit a native attachment from a different published route (#12558)", () => { + const registry = requireDist("../state/registry.js") as typeof import("../state/registry"); + const { nativeLocalIdentity } = requireDist( + "../inference/native-local/contract.ts", + ) as typeof import("../inference/native-local/contract"); + const binding = { + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "demo", + } as const; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "previous-id", + }; + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "demo", + gatewayName: "nemoclaw", + provider: "compatible-endpoint", + endpointUrl: "http://localhost:8000/v1", + nativeLocalProviderAttachment: receipt, + }); + const base = createdRegistryEntryInput(); + const entry = prepareCreatedSandboxRegistration({ + ...base, + inferenceSelection: { + ...base.inferenceSelection, + provider: "compatible-endpoint", + endpointUrl: "https://models.example.com/v1", + }, + }); + expect(entry.nativeLocalProviderAttachment).toBeUndefined(); + }); + + it.each(["pi", "hermes", "openclaw", "langchain-deepagents-code"])( + "keeps a native local attachment only for a supported %s target and exact route (#12975)", + (agentName) => { + const registry = requireDist("../state/registry.js") as typeof import("../state/registry"); + const { nativeLocalIdentity } = requireDist( + "../inference/native-local/contract.ts", + ) as typeof import("../inference/native-local/contract"); + const endpointUrl = "http://host.openshell.internal:11434/v1"; + const binding = { + provider: "compatible-endpoint", + endpointUrl, + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "demo", + } as const; + const attachment = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "previous-id", + }; + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "demo", + gatewayName: "nemoclaw", + provider: "compatible-endpoint", + endpointUrl, + nativeLocalProviderAttachment: attachment, + }); + const base = createdRegistryEntryInput(); + const input = { + ...base, + agent: { name: agentName } as AgentDefinition, + inferenceSelection: { + ...base.inferenceSelection, + provider: "compatible-endpoint", + endpointUrl, + }, + }; + const expectedAttachment = + agentName === "openclaw" || agentName === "langchain-deepagents-code" + ? attachment + : undefined; + const createIntent = nativeInferenceCreateIntentFields({ + agentName, + provider: "compatible-endpoint", + endpointUrl, + gatewayName: "nemoclaw", + entry: registry.getSandbox("demo"), + }); + expect(createIntent.inferenceProvider).toBe( + expectedAttachment?.providerName ?? "compatible-endpoint", + ); + expect(createIntent.nativeLocalProviderAttachment).toEqual(expectedAttachment); + + expect(prepareCreatedSandboxRegistration(input).nativeLocalProviderAttachment).toEqual( + expectedAttachment, + ); + expect( + prepareCreatedSandboxRegistration({ + ...input, + nativeLocalProviderAttachment: attachment, + }).nativeLocalProviderAttachment, + ).toEqual(expectedAttachment); + + const staleBinding = { + ...binding, + endpointUrl: "http://host.openshell.internal:8000/v1", + }; + const staleAttachment = { + ...staleBinding, + ...nativeLocalIdentity(staleBinding), + schemaVersion: 1 as const, + providerId: "previous-id", + }; + const staleEntry = { + ...registry.getSandbox("demo")!, + nativeLocalProviderAttachment: staleAttachment, + }; + expect( + nativeInferenceCreateIntentFields({ + agentName, + provider: "compatible-endpoint", + endpointUrl, + gatewayName: "nemoclaw", + entry: staleEntry, + }).nativeLocalProviderAttachment, + ).toBeUndefined(); + expect( + prepareCreatedSandboxRegistration({ + ...input, + nativeLocalProviderAttachment: staleAttachment, + }).nativeLocalProviderAttachment, + ).toBeUndefined(); + expect( + nativeLocalReservationStatus({ + entry: { + ...staleEntry, + model: "llama", + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + }, + agentName, + sandboxName: "demo", + gatewayName: "nemoclaw", + provider: "compatible-endpoint", + model: "llama", + endpointUrl, + endpointSource: null, + credentialEnv: null, + preferredInferenceApi: null, + }), + ).toBe(expectedAttachment ? "changed" : "shared"); + }, + ); + it("records only an exact native NVIDIA provider identity", () => { const attachment = { schemaVersion: 1 as const, diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index f7edd8c7d93..caab2777559 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeLocalProviderAttachment, + usesNativeLocalInferenceForAgent, +} from "../inference/native-local/contract"; import { requireHostedProviderAttachment } from "../inference/native-provider/hosted-attachment"; import { isDeepStrictEqual } from "node:util"; @@ -28,10 +32,15 @@ import { withCurrentPortableHostFenceTry } from "../state/portable-uninstall-ret import { cloneSandboxHostLocalInferenceProvenance, cloneSandboxHostLocalInferenceReceipt, + nativeLocalAttachmentMatchesHostLocalReceipt, + nativeLocalHostSelectionMatchesHostLocalReceipt, requireSandboxHostLocalInferenceProvenance, } from "../state/registry/host-local-inference"; import { cloneSandboxHostMounts } from "../state/registry/host-mount"; -import type { QualifiedSandboxInferenceRouteReservation } from "../state/registry/route-reservation"; +import { + retainedNativeLocalProviderAttachment, + type QualifiedSandboxInferenceRouteReservation, +} from "../state/registry/route-reservation"; import { cloneSandboxWorkloadReceipt } from "../state/registry/workload"; import { DEFAULT_TOOL_DISCLOSURE, type ToolDisclosure } from "../tool-disclosure"; import type { DcodeAutoApprovalMode } from "./dcode-auto-approval"; @@ -85,6 +94,7 @@ export interface CreatedSandboxRegistryEntryInput { workload?: SandboxEntry["workload"]; hostLocalInferenceReceipt?: SandboxEntry["hostLocalInferenceReceipt"]; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; deferredN1xManagedVllmPreviewIntent?: true; @@ -196,6 +206,37 @@ export function sandboxCreateInferenceSelection( return normalizeInferenceSelection(input); } +function nativeLocalAttachmentMatchesSelection( + attachment: NonNullable, + selection: { + agentName: string; + sandboxName: string; + gatewayName: string; + provider: string | null | undefined; + endpointUrl: string | null; + hostLocalInferenceReceipt?: string | null; + }, +): boolean { + const endpointMatches = + attachment.endpointUrl === selection.endpointUrl || + nativeLocalAttachmentMatchesHostLocalReceipt( + selection.endpointUrl, + attachment.endpointUrl, + selection.hostLocalInferenceReceipt, + ); + return ( + usesNativeLocalInferenceForAgent( + selection.agentName, + selection.provider, + selection.endpointUrl, + ) && + attachment.sandboxName === selection.sandboxName && + attachment.gatewayName === selection.gatewayName && + attachment.provider === selection.provider && + endpointMatches + ); +} + export function buildCreatedSandboxRegistryEntry( input: CreatedSandboxRegistryEntryInput, ): SandboxEntry { @@ -242,6 +283,11 @@ export function buildCreatedSandboxRegistryEntry( const hostLocalInferenceProvenance = cloneSandboxHostLocalInferenceProvenance( input.hostLocalInferenceProvenance, ); + const nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( + input.nativeLocalProviderAttachment, + ); + if (input.nativeLocalProviderAttachment !== undefined && !nativeLocalProviderAttachment) + throw new Error("Invalid native local provider attachment."); const nativeHostedProviderAttachment = requireHostedProviderAttachment( input.nativeHostedProviderAttachment, input.inferenceSelection.provider, @@ -303,6 +349,17 @@ export function buildCreatedSandboxRegistryEntry( workload, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeLocalProviderAttachment && + nativeLocalAttachmentMatchesSelection(nativeLocalProviderAttachment, { + agentName: requestedAgent, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + provider: input.inferenceSelection.provider, + endpointUrl: input.inferenceSelection.endpointUrl, + hostLocalInferenceReceipt, + }) + ? { nativeLocalProviderAttachment } + : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(deferredN1xManagedVllmAccepted ? { deferredN1xManagedVllmAccepted: true as const } : {}), @@ -380,6 +437,16 @@ export function prepareCreatedSandboxRegistration( input.hostLocalInferenceProvenance !== undefined ? input.hostLocalInferenceProvenance : pending?.hostLocalInferenceProvenance; + const effectiveSelection = pendingRoute + ? { ...input.inferenceSelection, ...pendingRoute } + : input.inferenceSelection; + const pendingNativeLocalProviderAttachment = + input.nativeLocalProviderAttachment ?? + retainedNativeLocalProviderAttachment(pending ?? undefined, { + provider: effectiveSelection.provider, + endpointUrl: effectiveSelection.endpointUrl, + gatewayName: input.gatewayName, + }); const pendingNativeNvidiaProviderAttachment = input.nativeNvidiaProviderAttachment !== undefined ? input.nativeNvidiaProviderAttachment @@ -391,13 +458,16 @@ export function prepareCreatedSandboxRegistration( nativeHostedProviderAttachment: pendingNativeHostedProviderAttachment, inferenceSelection: pendingRoute ? { ...input.inferenceSelection, ...pendingRoute } - : input.inferenceSelection, + : effectiveSelection, ...(pendingHostLocalInferenceReceipt === undefined ? {} : { hostLocalInferenceReceipt: pendingHostLocalInferenceReceipt }), ...(pendingHostLocalInferenceProvenance === undefined ? {} : { hostLocalInferenceProvenance: pendingHostLocalInferenceProvenance }), + ...(pendingNativeLocalProviderAttachment + ? { nativeLocalProviderAttachment: pendingNativeLocalProviderAttachment } + : {}), ...(pendingNativeNvidiaProviderAttachment === undefined ? {} : { nativeNvidiaProviderAttachment: pendingNativeNvidiaProviderAttachment }), @@ -482,24 +552,107 @@ export function registerCreatedSandbox(input: CreatedSandboxRegistrationInput): return publishCreatedSandboxRegistration(input, prepareCreatedSandboxRegistration(input)); } -export function nativeInferenceCreateIntentFields( - provider: string | null | undefined, - entry: SandboxEntry | null, -): { +/** The sandbox phase may bypass a shared route only for its exact native local reservation. */ +export function nativeLocalReservationStatus(input: { + entry: SandboxEntry; + agentName: string; + sandboxName: string; + gatewayName: string; + provider: string; + model: string; + endpointUrl: string | null; + endpointSource: InferenceEndpointSource | null; + credentialEnv: string | null; + preferredInferenceApi: string | null; + onMismatch?: (fields: readonly string[]) => void; +}): "shared" | "exact" | "changed" { + if (!usesNativeLocalInferenceForAgent(input.agentName, input.provider, input.endpointUrl)) { + return "shared"; + } + const attachment = normalizeNativeLocalProviderAttachment( + input.entry.nativeLocalProviderAttachment, + ); + const selectedEndpointUrl = nativeLocalHostSelectionMatchesHostLocalReceipt( + input.entry.endpointUrl, + input.endpointUrl, + input.entry.hostLocalInferenceReceipt, + ) + ? (input.entry.endpointUrl ?? null) + : input.endpointUrl; + const matches = { + attachment: Boolean( + attachment && + nativeLocalAttachmentMatchesSelection(attachment, { + agentName: input.agentName, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + provider: input.provider, + endpointUrl: selectedEndpointUrl, + hostLocalInferenceReceipt: input.entry.hostLocalInferenceReceipt, + }), + ), + provider: input.entry.provider === input.provider, + model: input.entry.model === input.model, + endpointUrl: input.entry.endpointUrl === selectedEndpointUrl, + endpointSource: (input.entry.endpointSource ?? null) === input.endpointSource, + credentialEnv: (input.entry.credentialEnv ?? null) === input.credentialEnv, + preferredInferenceApi: + (input.entry.preferredInferenceApi ?? null) === input.preferredInferenceApi, + }; + const mismatches = Object.entries(matches) + .filter(([, matches]) => !matches) + .map(([field]) => field); + if (mismatches.length) input.onMismatch?.(mismatches); + return mismatches.length ? "changed" : "exact"; +} + +export function nativeInferenceCreateIntentFields(input: { + agentName: string; + provider: string | null | undefined; + endpointUrl: string | null; + gatewayName: string; + entry: SandboxEntry | null; +}): { inferenceProvider: string | null; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; } { + const retainedAttachment = input.entry + ? normalizeNativeLocalProviderAttachment( + retainedNativeLocalProviderAttachment(input.entry, { + provider: input.provider ?? null, + endpointUrl: input.endpointUrl, + gatewayName: input.gatewayName, + }), + ) + : undefined; + const nativeLocalProviderAttachment = + retainedAttachment && + input.entry && + nativeLocalAttachmentMatchesSelection(retainedAttachment, { + agentName: input.agentName, + sandboxName: input.entry.name, + gatewayName: input.gatewayName, + provider: input.provider, + endpointUrl: input.endpointUrl, + hostLocalInferenceReceipt: input.entry?.hostLocalInferenceReceipt, + }) + ? retainedAttachment + : undefined; const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - entry?.nativeNvidiaProviderAttachment, + input.entry?.nativeNvidiaProviderAttachment, ); const hostedAttachment = requireHostedProviderAttachment( - entry?.nativeHostedProviderAttachment, - provider, + input.entry?.nativeHostedProviderAttachment, + input.provider, ); return { inferenceProvider: - hostedAttachment?.providerName ?? nativeInferenceProviderForSandbox(provider), + nativeLocalProviderAttachment?.providerName ?? + hostedAttachment?.providerName ?? + nativeInferenceProviderForSandbox(input.provider), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), nativeHostedProviderAttachment: hostedAttachment, ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), }; diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 249cdc0048c..19bef32fd47 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -1,6 +1,19 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { + NativeLocalProvider, + NativeLocalProviderAttachment, +} from "../inference/native-local/contract"; +import { + requireNativeProviderPolicy, + normalizeNativeLocalProviderAttachment, + usesNativeLocalInference, + usesNativeLocalInferenceForAgent, + prepareNativeLocalSelection, + retireUnreservedNativeLocalProvider, + gatewayReachableCompatibleEndpointUrl, +} from "./inference-providers"; import { hostedNativeProvider, usesNativeHermesEndpoint, @@ -8,7 +21,6 @@ import { import { requireHostedProviderAttachment } from "../inference/native-provider/hosted-attachment"; import { prepareHostedNativeProvider } from "../inference/native-provider/setup"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; - import type { OpenShellGatewayLifecycle } from "../adapters/openshell/gateway-lifecycle"; import { canonicalEndpoint } from "../core/url-utils"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; @@ -215,6 +227,7 @@ type ProviderBranchDeps = Pick< Pick; export type SetupInferenceDeps = ProviderBranchDeps & { + requireNativeProviderPolicy?: typeof requireNativeProviderPolicy; /** Injectable resolver for resumed custom-endpoint SSRF preflight tests. */ resolveEndpointHost?: EndpointDnsLookupFn; /** Exact private endpoint hosts trusted by the operator (tests may inject this). */ @@ -246,6 +259,9 @@ export type SetupInferenceDeps = ProviderBranchDeps & { // by hand, so every read below must stay optional-chained. getSandbox?: typeof import("../state/registry").getSandbox; listSandboxes?: typeof import("../state/registry").listSandboxes; + getNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").getNativeLocalProviderAuthority; + setNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").setNativeLocalProviderAuthority; + clearNativeLocalProviderAuthority?: typeof import("../state/registry/native-local-provider-authority").clearNativeLocalProviderAuthority; getNativeHostedProviderAuthority?: typeof import("../state/registry").getNativeHostedProviderAuthority; setNativeHostedProviderAuthority?: typeof import("../state/registry").setNativeHostedProviderAuthority; getNativeNvidiaProviderAuthority?: typeof import("../state/registry").getNativeNvidiaProviderAuthority; @@ -646,6 +662,157 @@ function releaseSupersededOllamaModel( if (authorityRefusal) throw authorityRefusal; } +async function rejectNativeLocalSetupFailure(input: { + error: unknown; + attachment?: NativeLocalProviderAttachment; + reservationEntered: boolean; + sandboxName: string | null; + gatewayName: string; + deps: SetupInferenceDeps; +}): Promise { + if ( + input.attachment && + !input.reservationEntered && + input.deps.providerAdapter && + input.sandboxName + ) { + try { + await retireUnreservedNativeLocalProvider({ + adapter: input.deps.providerAdapter, + expected: input.attachment, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + getSandbox: input.deps.getSandbox, + clearAuthority: input.deps.clearNativeLocalProviderAuthority, + }); + } catch (cleanupError) { + throw new Error( + `${hostLocalInferenceFailureDetail(input.error, input.deps)}\n Native local provider cleanup was not confirmed: ${hostLocalInferenceFailureDetail(cleanupError, input.deps)}`, + { cause: input.error }, + ); + } + } + if (input.error instanceof HostLocalInferenceBranchExit) + return input.deps.exitProcess(input.error.code); + throw input.error; +} + +function resolveHostedSelection(input: { + provider: string; + endpointUrl: string | null; + sandboxName: string | null; + gatewayName: string; + deps: SetupInferenceDeps; +}) { + const { provider, endpointUrl, sandboxName, gatewayName, deps } = input; + const recordedSandbox = + provider === "hermes-provider" && sandboxName ? deps.getSandbox?.(sandboxName) : null; + const authority = + provider === "hermes-provider" + ? ((recordedSandbox?.provider === provider + ? requireHostedProviderAttachment( + recordedSandbox.nativeHostedProviderAttachment, + provider, + ) + : undefined) ?? + deps.getNativeHostedProviderAuthority?.(gatewayName, provider, endpointUrl || undefined)) + : undefined; + return { + authority, + selected: + Boolean(hostedNativeProvider(provider)) && + (provider !== "hermes-provider" || usesNativeHermesEndpoint(endpointUrl, authority)), + }; +} + +async function prepareSelectedHostedProvider(input: { + provider: string; + gatewayName: string; + sandboxName: string | null; + credentialEnv: string | null; + reuseExistingCredential: boolean; + deps: SetupInferenceDeps; +}): Promise<{ attachment: NativeProviderAttachment; retainedCredential: boolean }> { + const { provider, gatewayName, sandboxName, credentialEnv, reuseExistingCredential, deps } = + input; + if ( + !deps.providerAdapter || + !deps.getNativeHostedProviderAuthority || + !deps.setNativeHostedProviderAuthority + ) { + throw new Error("Native hosted setup is missing its provider adapter or ownership store."); + } + const hosted = hostedNativeProvider(provider); + if (!hosted) throw new Error("Native hosted provider is unsupported."); + const credentialValue = deps.hydrateCredentialEnv(credentialEnv || hosted.credentialEnv) || null; + const attachment = await prepareHostedNativeProvider({ + provider, + adapter: deps.providerAdapter, + gatewayName, + credentialValue, + reuseExistingCredential, + recordedSandbox: sandboxName ? deps.getSandbox?.(sandboxName) : null, + readAuthority: deps.getNativeHostedProviderAuthority, + writeAuthority: deps.setNativeHostedProviderAuthority, + }); + return { attachment, retainedCredential: !credentialValue }; +} + +async function gatewayRouteCompatible(input: { + provider: string; + model: string; + endpointUrl: string | null; + credentialEnv: string | null; + gatewayName: string; + sandboxName: string | null; + preferredInferenceApi: ProviderInferenceSetupOptions["preferredInferenceApi"]; + nativeHostedSelection: boolean; + selectingNativeLocal: boolean; + deps: SetupInferenceDeps; +}): Promise { + const { + provider, + model, + endpointUrl, + credentialEnv, + gatewayName, + sandboxName, + preferredInferenceApi, + nativeHostedSelection, + selectingNativeLocal, + deps, + } = input; + if (isNativeNvidiaProvider(provider) || nativeHostedSelection || selectingNativeLocal) + return true; + const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ + target: { kind: "named", gatewayName }, + }); + if (!observedRoute.ok) { + deps.error( + ` Cannot reconcile the current OpenShell inference selection on gateway '${gatewayName}' before onboarding mutation: ${observedRoute.error.message}`, + ); + return false; + } + const compatibility = deps.checkGatewayRouteCompatibility({ + gatewayName, + sandboxName, + route: { + provider, + model, + endpointUrl, + credentialEnv, + preferredInferenceApi: preferredInferenceApi ?? null, + }, + }); + if (compatibility.ok) return true; + if (!isAdvisoryGatewayRouteConflict(compatibility)) { + deps.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); + return false; + } + deps.error(` ${formatGatewayRouteImpactWarning(compatibility)}`); + return true; +} + function shouldStageGatewayRouteAfterBackup( provider: string, source: SandboxEntry | null | undefined, @@ -665,6 +832,7 @@ function shouldStageGatewayRouteAfterBackup( function createGatewayRouteStager(input: { deps: SetupInferenceDeps; + selectingNativeLocal: boolean; provider: string; sandboxName: string | null; gatewayName: string; @@ -680,7 +848,9 @@ function createGatewayRouteStager(input: { > = []; const publishedSourceForStaging = (): SandboxEntry | null => { const source = - input.sandboxName && input.options.deferPublishedRouteReservation + !input.selectingNativeLocal && + input.sandboxName && + input.options.deferPublishedRouteReservation ? input.deps.getSandbox?.(input.sandboxName) : null; return shouldStageGatewayRouteAfterBackup( @@ -854,6 +1024,15 @@ export function createSetupInference( const gatewayName = options.gatewayName ?? deps.getGatewayName(); const endpointSource = options.endpointSource === undefined ? "onboard" : options.endpointSource; + const selectingNativeLocal = usesNativeLocalInferenceForAgent( + options.agentName ?? + options.hostLocalInference?.request.application ?? + (sandboxName ? deps.getSandbox?.(sandboxName)?.agent : undefined), + provider, + endpointUrl, + ); + if (selectingNativeLocal) + await (deps.requireNativeProviderPolicy ?? requireNativeProviderPolicy)(gatewayName); const routedProvider = deps.isRoutedInferenceProvider?.(provider) === true; const usesBedrockRuntimeAdapter = provider === "compatible-anthropic-endpoint" && isBedrockRuntimeEndpoint(endpointUrl); @@ -875,55 +1054,23 @@ export function createSetupInference( ); return deps.exitProcess(1); } - const recordedSandbox = - provider === "hermes-provider" && sandboxName ? deps.getSandbox?.(sandboxName) : null; - const hermesAuthority = - provider === "hermes-provider" - ? ((recordedSandbox?.provider === provider - ? requireHostedProviderAttachment( - recordedSandbox.nativeHostedProviderAttachment, - provider, - ) - : undefined) ?? - deps.getNativeHostedProviderAuthority?.( - gatewayName, - provider, - endpointUrl || undefined, - )) - : undefined; - const nativeHostedSelection = - hostedNativeProvider(provider) && - (provider !== "hermes-provider" || - usesNativeHermesEndpoint(endpointUrl, hermesAuthority)); - if (!isNativeNvidiaProvider(provider) && !nativeHostedSelection) { - const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ - target: { kind: "named", gatewayName }, - }); - if (!observedRoute.ok) { - deps.error( - ` Cannot reconcile the current OpenShell inference selection on gateway '${gatewayName}' before onboarding mutation: ${observedRoute.error.message}`, - ); - return deps.exitProcess(1); - } - const compatibility = deps.checkGatewayRouteCompatibility({ + const { authority: hermesAuthority, selected: nativeHostedSelection } = + resolveHostedSelection({ provider, endpointUrl, sandboxName, gatewayName, deps }); + if ( + !(await gatewayRouteCompatible({ + provider, + model, + endpointUrl, + credentialEnv, gatewayName, sandboxName, - route: { - provider, - model, - endpointUrl, - credentialEnv, - preferredInferenceApi: options.preferredInferenceApi ?? null, - }, - }); - if (!compatibility.ok) { - if (!isAdvisoryGatewayRouteConflict(compatibility)) { - deps.error(` Error: ${formatGatewayRouteConflict(compatibility)}`); - return deps.exitProcess(1); - } - deps.error(` ${formatGatewayRouteImpactWarning(compatibility)}`); - } - } + preferredInferenceApi: options.preferredInferenceApi, + nativeHostedSelection, + selectingNativeLocal, + deps, + })) + ) + return deps.exitProcess(1); deps.step(4, 8, "Setting up inference provider"); let endpointPinnedAddresses = options.endpointPinnedAddresses; let endpointTrustedPrivateCapability = options.endpointTrustedPrivateCapability; @@ -974,6 +1121,7 @@ export function createSetupInference( const hostLocalSelection = options.hostLocalInference; const routeStager = createGatewayRouteStager({ deps, + selectingNativeLocal, provider, sandboxName, gatewayName, @@ -990,12 +1138,14 @@ export function createSetupInference( let hostLocalRegistryPublicationEntered = false; const hostLocalProviderErrors: string[] = []; let routeReserved = false; + let nativeLocalReservationEntered = false; let hostLocalInferenceReceipt: string | null = null; let hostLocalInferenceProvenance: | import("../state/registry/types").SandboxEntry["hostLocalInferenceProvenance"] | undefined; let hostLocalInferenceGatewayPortAuthority: number | undefined; let hostLocalInferenceRuntimeProviderId: string | undefined; + let nativeLocalProviderAttachment: NativeLocalProviderAttachment | undefined; let nativeHostedEndpoint: string | undefined; let nativeHostedCredentialEnv: string | undefined; let nativeHostedProviderAttachment: NativeProviderAttachment | undefined; @@ -1009,6 +1159,7 @@ export function createSetupInference( ? deps.getSandbox?.(name) : null; if ( + !selectingNativeLocal && options.deferPublishedRouteReservation && shouldStageGatewayRouteAfterBackup( provider, @@ -1039,6 +1190,7 @@ export function createSetupInference( reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(hostLocalInferenceProvenance && hostLocalInferenceGatewayPortAuthority !== undefined @@ -1051,6 +1203,8 @@ export function createSetupInference( if (releaseAbandonedRouteReservation(name, route)) { deps.log(` Released an abandoned inference route reservation for sandbox '${name}'.`); } + // A failed response can follow a durable registry write. Retain authority once publication starts. + nativeLocalReservationEntered = true; const reserved = deps.updateSandbox(name, route); routeReserved = reserved; return reserved; @@ -1061,11 +1215,12 @@ export function createSetupInference( gatewayName, revalidateSandboxIdentity, ); - const providerExitProcess: CommonDeps["exitProcess"] = hostLocalSelection - ? (code: number): never => { - throw new HostLocalInferenceBranchExit(code); - } - : deps.exitProcess; + const providerExitProcess: CommonDeps["exitProcess"] = + hostLocalSelection || selectingNativeLocal + ? (code: number): never => { + throw new HostLocalInferenceBranchExit(code); + } + : deps.exitProcess; const ambiguousRouteExitProcess: CommonDeps["exitProcess"] = hostLocalSelection ? (code: number): never => { throw new HostLocalInferenceBranchExit(code, true); @@ -1078,6 +1233,54 @@ export function createSetupInference( : deps.error; const selectedUpsertProvider: CommonDeps["upsertProvider"] = async (...args) => { revalidateSandboxIdentity?.("register the inference provider"); + if (selectingNativeLocal) { + if (!sandboxName) throw new Error("Native local inference requires a sandbox."); + if (hostLocalGatewayMutation?.registerNativeProvider) { + nativeLocalProviderAttachment = + await hostLocalGatewayMutation.registerNativeProvider(); + return { ok: true }; + } + if (!deps.providerAdapter) + throw new Error("Native local inference requires a provider adapter."); + const [name, , sourceCredentialEnv, selectedEndpoint, env] = args; + const recorded = deps.getSandbox?.(sandboxName); + if ( + recorded && + recorded.pendingRouteReservation !== true && + usesNativeLocalInference(recorded.provider, recorded.endpointUrl) && + !normalizeNativeLocalProviderAttachment(recorded.nativeLocalProviderAttachment) + ) { + throw new Error("Recreate this beta sandbox before using native local inference."); + } + const value = env?.[sourceCredentialEnv] ?? null; + const hostReachableEndpoint = + hostLocalRoute?.gatewayProviderBaseUrl ?? + gatewayReachableCompatibleEndpointUrl(name, selectedEndpoint); + if (typeof hostReachableEndpoint !== "string") + throw new Error("Native local inference endpoint is missing."); + nativeLocalProviderAttachment = await prepareNativeLocalSelection({ + adapter: deps.providerAdapter, + binding: { + provider: name as NativeLocalProvider, + endpointUrl: hostReachableEndpoint, + authMode: + (name === "ollama-local" && value === "ollama") || + (name === "vllm-local" && value === "dummy") + ? "sentinel" + : "authenticated", + gatewayName, + sandboxName, + }, + credentialValue: value, + ownedProxy: + (name === "ollama-local" && !hostLocalRoute && deps.shouldFrontOllamaWithProxy()) || + (name === "compatible-endpoint" && + sourceCredentialEnv === deps.ollamaProxyCredentialEnv), + readAuthority: deps.getNativeLocalProviderAuthority, + writeAuthority: deps.setNativeLocalProviderAuthority, + }); + return { ok: true }; + } const reused = routeStager.reusePublishedProvider(args[0]); if (reused) return reused; const upsertProvider = hostLocalGatewayMutation?.upsertProvider ?? defaultUpsertProvider; @@ -1088,6 +1291,7 @@ export function createSetupInference( const commonDeps = { runOpenshell: runGatewayOpenshell, inferenceRouteMutator: revalidatingInferenceRouteMutator, + nativeLocalInference: selectingNativeLocal, gatewayName, upsertProvider: selectedUpsertProvider, verifyInferenceRoute: (selectedProvider: string, selectedModel: string) => { @@ -1186,28 +1390,16 @@ export function createSetupInference( const setupSelectedProvider = async (): Promise => { const hosted = hostedNativeProvider(provider); if (hosted && provider !== deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { - if ( - !deps.providerAdapter || - !deps.getNativeHostedProviderAuthority || - !deps.setNativeHostedProviderAuthority - ) { - throw new Error( - "Native hosted setup is missing its provider adapter or ownership store.", - ); - } - const credentialValue = - deps.hydrateCredentialEnv(credentialEnv || hosted.credentialEnv) || null; - nativeHostedProviderAttachment = await prepareHostedNativeProvider({ + const prepared = await prepareSelectedHostedProvider({ provider, - adapter: deps.providerAdapter, gatewayName, - credentialValue, + sandboxName, + credentialEnv, reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, - recordedSandbox: sandboxName ? deps.getSandbox?.(sandboxName) : null, - readAuthority: deps.getNativeHostedProviderAuthority, - writeAuthority: deps.setNativeHostedProviderAuthority, + deps, }); - retainedNativeHostedCredential = !credentialValue; + nativeHostedProviderAttachment = prepared.attachment; + retainedNativeHostedCredential = prepared.retainedCredential; return null; } @@ -1369,19 +1561,25 @@ export function createSetupInference( getLocalProviderBaseUrl: hostLocalRoute ? () => hostLocalRoute.gatewayProviderBaseUrl : deps.getLocalProviderBaseUrl, - applyLocalInferenceRoute: resolveLocalInferenceRouteApplier( - hostLocalRoute - ? { - ...deps, - exitProcess: commonDeps.exitProcess, - error: commonDeps.error, - } - : deps, - revalidatingInferenceRouteMutator, - gatewayName, - revalidateSandboxIdentity, - ambiguousRouteExitProcess, - ), + applyLocalInferenceRoute: selectingNativeLocal + ? async () => { + if (!nativeLocalProviderAttachment) + throw new Error("Native local provider registration was not confirmed."); + return false; + } + : resolveLocalInferenceRouteApplier( + hostLocalRoute + ? { + ...deps, + exitProcess: commonDeps.exitProcess, + error: commonDeps.error, + } + : deps, + revalidatingInferenceRouteMutator, + gatewayName, + revalidateSandboxIdentity, + ambiguousRouteExitProcess, + ), run: deps.run, VLLM_LOCAL_CREDENTIAL_ENV: deps.vllmLocalCredentialEnv, getManagedVllmProviderBinding: hostLocalRoute @@ -1427,19 +1625,25 @@ export function createSetupInference( getLocalProviderBaseUrl: hostLocalRoute ? () => hostLocalRoute.gatewayProviderBaseUrl : deps.getLocalProviderBaseUrl, - applyLocalInferenceRoute: resolveLocalInferenceRouteApplier( - hostLocalRoute - ? { - ...deps, - exitProcess: commonDeps.exitProcess, - error: commonDeps.error, - } - : deps, - revalidatingInferenceRouteMutator, - gatewayName, - revalidateSandboxIdentity, - ambiguousRouteExitProcess, - ), + applyLocalInferenceRoute: selectingNativeLocal + ? async () => { + if (!nativeLocalProviderAttachment) + throw new Error("Native local provider registration was not confirmed."); + return false; + } + : resolveLocalInferenceRouteApplier( + hostLocalRoute + ? { + ...deps, + exitProcess: commonDeps.exitProcess, + error: commonDeps.error, + } + : deps, + revalidatingInferenceRouteMutator, + gatewayName, + revalidateSandboxIdentity, + ambiguousRouteExitProcess, + ), run: deps.run, shouldFrontOllamaWithProxy: hostLocalRoute ? () => false @@ -1494,7 +1698,13 @@ export function createSetupInference( try { const providerResult = await setupSelectedProvider(); if (providerResult) return providerResult; - if (!nativeNvidiaProviderAttachment && !nativeHostedProviderAttachment) + if (selectingNativeLocal && !nativeLocalProviderAttachment) + throw new Error("Native local provider registration was not confirmed."); + if ( + !nativeNvidiaProviderAttachment && + !nativeHostedProviderAttachment && + !nativeLocalProviderAttachment + ) commonDeps.verifyInferenceRoute(provider, model); if (hostLocalRoute) { deps.log( @@ -1584,7 +1794,16 @@ export function createSetupInference( shouldLogSuccessfulRoute = true; return routeStager.successResult(); } catch (error) { - if (!hostLocalRoute || !hostLocalSelection) throw error; + if (!hostLocalRoute || !hostLocalSelection) { + return rejectNativeLocalSetupFailure({ + error, + attachment: nativeLocalProviderAttachment, + reservationEntered: nativeLocalReservationEntered, + sandboxName, + gatewayName, + deps, + }); + } emitHostLocalInferenceFailure( hostLocalSelection.runtimeProviderId, error instanceof HostLocalInferenceBranchExit diff --git a/src/lib/onboard/workload/clone.ts b/src/lib/onboard/workload/clone.ts index f0f1f85ba28..2db89611d6b 100644 --- a/src/lib/onboard/workload/clone.ts +++ b/src/lib/onboard/workload/clone.ts @@ -291,6 +291,11 @@ function reboundMessaging( export function prepareManagedWorkloadCloneHandoff( input: PrepareManagedWorkloadCloneHandoffInput, ): PreparedManagedWorkloadCloneHandoff { + if (input.source.nativeLocalProviderAttachment !== undefined) { + fail( + "Native local provider attachments cannot be cloned. Onboard the destination with its own provider.", + ); + } const sourceSandboxName = requireSandboxName(input.source.name, "source"); const snapshotSandboxName = requireSandboxName(input.snapshot.sandboxName, "snapshot source"); const destinationSandboxName = requireSandboxName(input.destinationSandboxName, "destination"); diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 872c2921354..fdce95c0b1b 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -132,6 +132,8 @@ function stageManagedStartupRuntimeSources(rootDir: string, buildCtx: string): v "inference-credential.ts", path.join("core", "json-types.ts"), path.join("core", "ports.ts"), + path.join("core", "endpoint-url-safety.ts"), + path.join("inference", "native-local", "agent-config.ts"), path.join("security", "credential-hash.ts"), path.join("state", "paths.ts"), path.join("state", "state-root.ts"), diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index d2e480016ab..593dc7453ca 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -540,6 +540,66 @@ describe("composeSandboxConfigBody", () => { } }); + it("pins a native local OpenClaw handle before the gateway restarts", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-local-config-")); + const endpoint = "http://host.openshell.internal:8000/v1"; + const reference = "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + const handle = "openshell:resolve:env:v42_NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + try { + fs.writeFileSync(path.join(directory, "openclaw"), '#!/bin/sh\ncat "$4"\n', { + mode: 0o700, + }); + const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.inference", + value: { baseUrl: endpoint, apiKey: reference, api: "openai-completions" }, + }, + ]); + const command = invocation.args.slice(invocation.args.indexOf("--") + 1); + const run = (value: string | undefined) => + spawnSync(command[0]!, command.slice(1), { + input: invocation.input, + encoding: "utf8", + timeout: 5_000, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH ?? ""}`, + NEMOCLAW_LOCAL_INFERENCE_TOKEN: value, + }, + }); + + const success = run(handle); + expect(success.status, success.stderr).toBe(0); + const batch = JSON.parse(success.stdout) as Array<{ value: { apiKey: string } }>; + expect(batch[0]?.value.apiKey).toBe(handle); + expect(invocation.input).toContain(reference); + expect(invocation.input).not.toContain(handle); + expect(invocation.args.join(" ")).not.toContain(handle); + expect(run(undefined).status).toBe(75); + expect(run(reference).status).toBe(1); + expect(run("raw-secret").status).toBe(1); + expect(run("openshell:resolve:env:v42_OPENAI_API_KEY").status).toBe(1); + expect(() => + buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.openai", + value: { baseUrl: endpoint, apiKey: reference }, + }, + ]), + ).toThrow("config path does not match its identity"); + expect(() => + buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.inference", + value: { baseUrl: "https://untrusted.example/v1", apiKey: reference }, + }, + ]), + ).toThrow("qualified private endpoint"); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + it("retries only a missing newly attached handle before OpenClaw mutates config", () => { const pending = { status: 75, stderr: "NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\n" }; const succeeded = { status: 0, stderr: "" }; diff --git a/src/lib/sandbox/openclaw-native-config.ts b/src/lib/sandbox/openclaw-native-config.ts index 6accfc9424f..583c3a8d828 100644 --- a/src/lib/sandbox/openclaw-native-config.ts +++ b/src/lib/sandbox/openclaw-native-config.ts @@ -20,6 +20,10 @@ const { NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_ENDPOINT, }: typeof import("../inference/native-nvidia/contract") = require("../inference/native-nvidia/contract"); +const { + NATIVE_LOCAL_CREDENTIAL_ENV, + nativeLocalCredentialReference, +}: typeof import("../inference/native-local/agent-config") = require("../inference/native-local/agent-config"); const { nativeHostedAgentConfig, }: typeof import("../inference/native-provider/agent-config") = require("../inference/native-provider/agent-config"); @@ -123,9 +127,11 @@ const materializeNativeProviderHandle = [ ].join("\n"); function nativeProviderHandleUpdate(updates: readonly OpenClawConfigUpdate[]) { + const localReference = `openshell:resolve:env:${NATIVE_LOCAL_CREDENTIAL_ENV}`; const matching = updates.filter(({ dotpath, value }) => { if (!dotpath.startsWith("models.providers.") || !isConfigObject(value)) return false; - if (value.apiKey === NVIDIA_INFERENCE_PLACEHOLDER) return true; + if (value.apiKey === NVIDIA_INFERENCE_PLACEHOLDER || value.apiKey === localReference) + return true; if ( typeof value.apiKey !== "string" || !/^openshell:resolve:env:[A-Z][A-Z0-9_]*$/u.test(value.apiKey) @@ -139,6 +145,24 @@ function nativeProviderHandleUpdate(updates: readonly OpenClawConfigUpdate[]) { if (matching.length !== 1) throw new Error("Expected one native provider config update"); const value = matching[0]!.value; if (!isConfigObject(value)) throw new Error("Invalid native provider config update"); + if (value.apiKey === localReference) { + if ( + typeof value.baseUrl !== "string" || + nativeLocalCredentialReference("compatible-endpoint", value.baseUrl) !== localReference + ) { + throw new Error("Native local OpenClaw credential requires a qualified private endpoint."); + } + const providerPath = "models.providers.inference"; + if (matching[0]!.dotpath !== providerPath) { + throw new Error("Native provider config path does not match its identity"); + } + return { + credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV, + endpoint: value.baseUrl, + placeholder: localReference, + providerPath, + }; + } const headers = isConfigObject(value.headers) ? value.headers : {}; const provider = headers["X-NemoClaw-Upstream-Provider"]; const native = diff --git a/src/lib/security/credential-filter.test.ts b/src/lib/security/credential-filter.test.ts index 315cb99c1e1..8baf451eb89 100644 --- a/src/lib/security/credential-filter.test.ts +++ b/src/lib/security/credential-filter.test.ts @@ -289,6 +289,33 @@ describe("textContainsHighConfidenceCredential", () => { }); }); +describe.each([ + ["raw text", textContainsCredential], + ["high-confidence text", textContainsHighConfidenceCredential], +] as const)("native local placeholder in %s", (_name, scan) => { + const sentinel = "sk-OPENSHELL-RESOLVE-ENV-NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + + it.each([ + ["literal", sentinel], + ["bundled source", `const accepted = new Set(["${sentinel}"]);`], + ["configuration", JSON.stringify({ apiKey: sentinel })], + ["authorization", `Authorization: Bearer ${sentinel}`], + ])("preserves the exact non-secret reference in %s", (_context, text) => { + expect(scan(text)).toBe(false); + }); + + it.each([ + `${sentinel}-secret`, + `${sentinel}_SECRET`, + sentinel.replace("INFERENCE_TOKEN", "OTHER_TOKEN"), + sentinel.toLowerCase(), + `_${sentinel}`, + `${sentinel} sk-proj-0123456789abcdefghij`, + ])("still rejects credential material or altered references: %s", (text) => { + expect(scan(text)).toBe(true); + }); +}); + describe("textContainsCredential", () => { it.each([ "request failed: Authorization: Bearer opaqueCredentialPayloadZ1234567890", diff --git a/src/lib/security/credential-filter.ts b/src/lib/security/credential-filter.ts index c899ab3ce65..5b76f239ce9 100644 --- a/src/lib/security/credential-filter.ts +++ b/src/lib/security/credential-filter.ts @@ -109,6 +109,10 @@ function textWithoutSafeCredentialFixtures(value: string): string { // prefix from malformed placeholder-shaped credential values. .replace(/(?:xox[bx]|xapp)-OPENSHELL-RESOLVE-ENV-\[A-Za-z0-9_\]\+/gu, "unused") .replace(/(? { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-local-attachment-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + const authority = await import("./registry/native-local-provider-authority"); + const { nativeLocalIdentity } = await import("../inference/native-local/contract"); + const binding = { + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "alpha", + } as const; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "original-provider", + }; + authority.setNativeLocalProviderAuthority(receipt); + registry.registerSandbox({ + name: "alpha", + provider: binding.provider, + model: "model-a", + endpointUrl: "http://127.0.0.1:11434/v1", + gatewayName: binding.gatewayName, + nativeLocalProviderAttachment: receipt, + }); + const nextBinding = { + ...binding, + endpointUrl: endpointUrl.replace("127.0.0.1", "host.openshell.internal"), + gatewayName, + }; + const nextReceipt = replacement + ? { + ...nextBinding, + ...nativeLocalIdentity(nextBinding), + schemaVersion: 1 as const, + providerId: "replacement-provider", + } + : undefined; + registry.reserveSandboxInferenceRoute("alpha", { + provider: binding.provider, + model: "model-b", + credentialEnv: null, + preferredInferenceApi: "openai-completions", + endpointUrl, + gatewayName, + ...(nextReceipt ? { nativeLocalProviderAttachment: nextReceipt } : {}), + }); + const entry = registry.getSandbox("alpha")!; + expect(entry.nativeLocalProviderAttachment).toEqual( + retained ? (nextReceipt ?? receipt) : undefined, + ); + expect(authority.getNativeLocalProviderAuthority(receipt.providerName)).toEqual(receipt); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } + }, +); + +it("enumerates cleanup authority only for the exact sandbox and gateway (#12558)", async () => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-native-cleanup-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const authority = await import("./registry/native-local-provider-authority"); + const { nativeLocalIdentity } = await import("../inference/native-local/contract"); + const binding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "selected", + sandboxName: "alpha", + } as const; + const own = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "own", + }; + const siblingBinding = { ...binding, sandboxName: "beta" }; + const sibling = { + ...siblingBinding, + ...nativeLocalIdentity(siblingBinding), + schemaVersion: 1 as const, + providerId: "sibling", + }; + const otherBinding = { ...binding, gatewayName: "other" }; + const other = { + ...otherBinding, + ...nativeLocalIdentity(otherBinding), + schemaVersion: 1 as const, + providerId: "other", + }; + authority.setNativeLocalProviderAuthority(own); + authority.setNativeLocalProviderAuthority(sibling); + authority.setNativeLocalProviderAuthority(other); + expect(authority.listNativeLocalProviderAuthorities("alpha", "selected")).toEqual([own]); + expect(authority.getNativeLocalProviderAuthority(sibling.providerName)).toEqual(sibling); + expect(authority.getNativeLocalProviderAuthority(other.providerName)).toEqual(other); + } finally { + vi.unstubAllEnvs(); + vi.resetModules(); + await fs.rm(home, { recursive: true, force: true }); + } +}); + +const wrongAuthorityKeyBinding = { + provider: "vllm-local", + endpointUrl: "http://host.openshell.internal:8000/v1", + sandboxName: "alpha", + gatewayName: "nemoclaw", + authMode: "sentinel", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", +} as const; + +it.each([ + ["invalid map", []], + [ + "wrong map key", + { + "different-key": { + ...wrongAuthorityKeyBinding, + ...nativeLocalIdentity(wrongAuthorityKeyBinding), + schemaVersion: 1, + providerId: "retained-id", + }, + }, + ], + ["invalid receipt", { "owned-provider": { providerId: "retained-id" } }], +])( + "preserves %s authority evidence when an unrelated registry write is attempted (#12558)", + async (_label, invalid) => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-native-invalid-authority-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + const { REGISTRY_FILE, save } = await import("./registry/persistence"); + await fs.mkdir(path.dirname(REGISTRY_FILE), { recursive: true }); + const original = JSON.stringify({ + sandboxes: {}, + defaultSandbox: null, + nativeLocalProviderAuthorities: invalid, + }); + await fs.writeFile(REGISTRY_FILE, original); + expect(() => + registry.registerSandbox({ name: "unrelated", gatewayName: "nemoclaw" }), + ).toThrow(/native local provider authority/i); + expect(await fs.readFile(REGISTRY_FILE, "utf8")).toBe(original); + expect(() => save({ sandboxes: {}, defaultSandbox: null })).toThrow( + /native local provider authority/i, + ); + expect(await fs.readFile(REGISTRY_FILE, "utf8")).toBe(original); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } + }, +); + +it.each(["malformed receipt", "different sandbox", "different gateway", "different provider"])( + "rejects a %s in a persisted sandbox without changing the registry (#12975)", + async (scenario) => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-invalid-local-attachment-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + const { load, REGISTRY_FILE, save } = await import("./registry/persistence"); + const binding = { + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: "alpha", + } as const; + const changedBinding = { + ...binding, + ...(scenario === "different sandbox" ? { sandboxName: "beta" } : {}), + ...(scenario === "different gateway" ? { gatewayName: "other" } : {}), + ...(scenario === "different provider" ? { provider: "compatible-endpoint" as const } : {}), + }; + const attachment = { + ...changedBinding, + ...nativeLocalIdentity(changedBinding), + schemaVersion: 1, + providerId: scenario === "malformed receipt" ? "" : "provider-id", + }; + const entry = { + name: "alpha", + provider: binding.provider, + gatewayName: binding.gatewayName, + nativeLocalProviderAttachment: attachment, + }; + const original = JSON.stringify({ sandboxes: { alpha: entry }, defaultSandbox: null }); + await fs.mkdir(path.dirname(REGISTRY_FILE), { recursive: true }); + await fs.writeFile(REGISTRY_FILE, original); + + expect(() => load()).toThrow(/sandbox "alpha".*native local provider attachment/i); + expect(() => + registry.registerSandbox({ name: "unrelated", gatewayName: "nemoclaw" }), + ).toThrow(/sandbox "alpha".*native local provider attachment/i); + expect(() => save({ sandboxes: {}, defaultSandbox: null })).toThrow( + /sandbox "alpha".*native local provider attachment/i, + ); + expect(await fs.readFile(REGISTRY_FILE, "utf8")).toBe(original); + + const clean = JSON.stringify({ sandboxes: {}, defaultSandbox: null }); + await fs.writeFile(REGISTRY_FILE, clean); + expect(() => + save({ sandboxes: { alpha: entry }, defaultSandbox: null } as Parameters[0]), + ).toThrow(/sandbox "alpha".*native local provider attachment/i); + expect(await fs.readFile(REGISTRY_FILE, "utf8")).toBe(clean); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } + }, +); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index d4ff65b247a..7e0033cdde0 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -27,6 +27,8 @@ import { import { withLock } from "./registry/lock"; import { load, save } from "./registry/persistence"; import { + normalizeNativeLocalProviderAttachment, + retainedNativeLocalProviderAttachment, nativeHostedReservationAttachment, isCurrentSandboxInferenceRouteReservation, isCurrentPendingSandboxCreateReservation, @@ -491,6 +493,18 @@ export function registerSandbox( ); } } + const nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( + entry.nativeLocalProviderAttachment, + ); + if ( + entry.nativeLocalProviderAttachment !== undefined && + (!nativeLocalProviderAttachment || + nativeLocalProviderAttachment.sandboxName !== entry.name || + nativeLocalProviderAttachment.gatewayName !== entry.gatewayName || + nativeLocalProviderAttachment.provider !== entry.provider) + ) { + throw new Error("Cannot publish an invalid native local provider attachment."); + } const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( entry.nativeNvidiaProviderAttachment, ); @@ -560,6 +574,7 @@ export function registerSandbox( : undefined, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), lifecycleGeneration: entry.lifecycleGeneration, @@ -612,6 +627,7 @@ type SandboxInferenceRouteReservation = Pick< reservationSessionId?: string; hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; }; @@ -655,6 +671,18 @@ export function reserveSandboxInferenceRoute( ) return false; const normalized = normalizeInferenceSelection(route); + const nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( + route.nativeLocalProviderAttachment, + ); + if ( + route.nativeLocalProviderAttachment !== undefined && + (!nativeLocalProviderAttachment || + nativeLocalProviderAttachment.sandboxName !== name || + nativeLocalProviderAttachment.gatewayName !== route.gatewayName || + nativeLocalProviderAttachment.provider !== route.provider) + ) { + throw new Error("Cannot publish an invalid native local provider attachment."); + } const nativeHostedProviderAttachment = nativeHostedReservationAttachment( route.nativeHostedProviderAttachment, normalized.provider, @@ -722,6 +750,10 @@ export function reserveSandboxInferenceRoute( existing.hostLocalInferenceProvenance, route.hostLocalInferenceProvenance ?? existing.hostLocalInferenceProvenance, ) && + isDeepStrictEqual( + existing.nativeLocalProviderAttachment, + nativeLocalProviderAttachment ?? existing.nativeLocalProviderAttachment, + ) && isDeepStrictEqual( existing.nativeHostedProviderAttachment, nativeHostedProviderAttachment ?? existing.nativeHostedProviderAttachment, @@ -766,6 +798,13 @@ export function reserveSandboxInferenceRoute( endpointSource: normalized.endpointSource, credentialEnv: normalized.credentialEnv, preferredInferenceApi: normalized.preferredInferenceApi, + nativeLocalProviderAttachment: + nativeLocalProviderAttachment ?? + retainedNativeLocalProviderAttachment(existing, { + provider: normalized.provider, + endpointUrl: normalized.endpointUrl, + gatewayName: route.gatewayName, + }), nativeHostedProviderAttachment: nativeHostedReservationAttachment( nativeHostedProviderAttachment, normalized.provider, diff --git a/src/lib/state/registry/host-local-inference.ts b/src/lib/state/registry/host-local-inference.ts index 529c4dfb510..d2bdd6fe3ac 100644 --- a/src/lib/state/registry/host-local-inference.ts +++ b/src/lib/state/registry/host-local-inference.ts @@ -8,11 +8,47 @@ import { parseHostLocalInferenceReceipt, serializeHostLocalInferenceReceipt, } from "../../onboard/runtime-provider/host-local-inference"; +import { HOST_LOCAL_INFERENCE_APPLICATION_BASE_URL } from "../../onboard/runtime-provider/host-local-inference-routing"; import type { SandboxHostLocalInferenceProvenance } from "./types"; const SHA256 = /^[a-f0-9]{64}$/u; const SAFE_SANDBOX_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u; +/** Bind a published application route to the exact host endpoint in its receipt. */ +export function nativeLocalAttachmentMatchesHostLocalReceipt( + applicationEndpointUrl: string | null | undefined, + attachmentEndpointUrl: string, + serializedReceipt: string | null | undefined, +): boolean { + if (applicationEndpointUrl !== HOST_LOCAL_INFERENCE_APPLICATION_BASE_URL || !serializedReceipt) + return false; + try { + const receipt = parseHostLocalInferenceReceipt(serializedReceipt); + return ( + attachmentEndpointUrl === + `http://${receipt.endpoint.host}:${String(receipt.endpoint.port)}/v1` + ); + } catch { + return false; + } +} + +/** Match the managed host listener selected before the application route is published. */ +export function nativeLocalHostSelectionMatchesHostLocalReceipt( + applicationEndpointUrl: string | null | undefined, + selectedEndpointUrl: string | null | undefined, + serializedReceipt: string | null | undefined, +): boolean { + if (applicationEndpointUrl !== HOST_LOCAL_INFERENCE_APPLICATION_BASE_URL || !serializedReceipt) + return false; + try { + const receipt = parseHostLocalInferenceReceipt(serializedReceipt); + return selectedEndpointUrl === `http://127.0.0.1:${String(receipt.endpoint.port)}/v1`; + } catch { + return false; + } +} + function receiptTransactionId(receipt: HostLocalInferenceReceipt): string | null { if (receipt.schemaVersion === 2) return receipt.publication?.transactionId ?? null; return receipt.runtime.kind === "container" ? (receipt.runtime.model?.generation ?? null) : null; diff --git a/src/lib/state/registry/native-local-provider-authority.ts b/src/lib/state/registry/native-local-provider-authority.ts new file mode 100644 index 00000000000..6b7b3b8ebf7 --- /dev/null +++ b/src/lib/state/registry/native-local-provider-authority.ts @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + normalizeNativeLocalProviderAttachment, + type NativeLocalProviderAttachment, +} from "../../inference/native-local/contract"; +import { withLock } from "./lock"; +import { load, save } from "./persistence"; + +export function getNativeLocalProviderAuthority( + providerName: string, +): NativeLocalProviderAttachment | undefined { + return normalizeNativeLocalProviderAttachment( + load().nativeLocalProviderAuthorities?.[providerName], + ); +} + +export function setNativeLocalProviderAuthority(receipt: NativeLocalProviderAttachment): void { + const normalized = normalizeNativeLocalProviderAttachment(receipt); + if (!normalized) throw new Error("Cannot record invalid native local provider authority."); + withLock(() => { + const data = load(); + const previous = data.nativeLocalProviderAuthorities?.[normalized.providerName]; + if (previous?.providerId === normalized.providerId) return; + if (previous) throw new Error("Native local provider ownership changed before publication."); + data.nativeLocalProviderAuthorities = { + ...data.nativeLocalProviderAuthorities, + [normalized.providerName]: normalized, + }; + save(data); + }); +} + +export function clearNativeLocalProviderAuthority(expected: NativeLocalProviderAttachment): void { + withLock(() => { + const data = load(); + const previous = data.nativeLocalProviderAuthorities?.[expected.providerName]; + if (!previous) return; + if (previous.providerId !== expected.providerId) + throw new Error("Native local provider ownership changed before cleanup."); + delete data.nativeLocalProviderAuthorities![expected.providerName]; + save(data); + }); +} + +/** Return only validated cleanup authority belonging to one sandbox and gateway. */ +export function listNativeLocalProviderAuthorities( + sandboxName: string, + gatewayName: string, +): NativeLocalProviderAttachment[] { + return Object.values(load().nativeLocalProviderAuthorities ?? {}).filter( + (receipt) => receipt.sandboxName === sandboxName && receipt.gatewayName === gatewayName, + ); +} diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index 930f5fc2e6f..a2ccbccadbf 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -1,6 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeLocalProviderAttachment, + normalizeNativeLocalProviderAuthorities, +} from "../../inference/native-local/contract"; + import path from "node:path"; import { requireHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; import { normalizeNativeHostedProviderAuthorities } from "./native-provider-authority-state"; @@ -97,6 +102,25 @@ function normalizeDeferredN1xManagedVllmAcceptance( return value; } +function requireNativeLocalProviderAttachment( + entry: SandboxEntry, + operation: "load" | "save", +): SandboxEntry["nativeLocalProviderAttachment"] { + if (entry.nativeLocalProviderAttachment === undefined) return undefined; + const attachment = normalizeNativeLocalProviderAttachment(entry.nativeLocalProviderAttachment); + if ( + !attachment || + attachment.sandboxName !== entry.name || + attachment.gatewayName !== entry.gatewayName || + attachment.provider !== entry.provider + ) { + throw new Error( + `Cannot ${operation} sandbox ${JSON.stringify(entry.name)}: invalid native local provider attachment in sandboxes.json. Inspect and repair nativeLocalProviderAttachment before retrying.`, + ); + } + return attachment; +} + export const REGISTRY_FILE = path.join( nemoclawStateRoot(process.env.HOME || "/tmp", GATEWAY_PORT), "sandboxes.json", @@ -110,6 +134,12 @@ export function load(): SandboxRegistry { export function save(data: SandboxRegistry): void { const serialized = serializeRegistryForDisk(data); const previous = readConfigFile(REGISTRY_FILE, {}); + if (isObjectRecord(previous)) { + normalizeNativeLocalProviderAuthorities(previous.nativeLocalProviderAuthorities); + for (const [, entry] of parseSandboxRegistryEntries(previous.sandboxes)) { + requireNativeLocalProviderAttachment(entry, "save"); + } + } // Legacy MCP ownership is disk-only compatibility evidence, not runtime // authority. Ordinary writes must retain it until an explicit migration or // verified removal retires it. Never accept a caller-supplied replacement. @@ -127,6 +157,9 @@ export function save(data: SandboxRegistry): void { function normalizeRegistry(value: unknown): SandboxRegistry { const data = isObjectRecord(value) ? value : {}; const extraProviders = normalizeExtraProviders(data.extraProviders); + const nativeLocalProviderAuthorities = normalizeNativeLocalProviderAuthorities( + data.nativeLocalProviderAuthorities, + ); const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( data.nativeNvidiaProviderAuthorities, ); @@ -146,6 +179,8 @@ function normalizeRegistry(value: unknown): SandboxRegistry { sandboxes, }; if (extraProviders) base.extraProviders = extraProviders; + if (nativeLocalProviderAuthorities) + base.nativeLocalProviderAuthorities = nativeLocalProviderAuthorities; const nativeHostedProviderAuthorities = normalizeNativeHostedProviderAuthorities( data.nativeHostedProviderAuthorities, ); @@ -159,6 +194,9 @@ function normalizeRegistry(value: unknown): SandboxRegistry { function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { const extraProviders = normalizeExtraProviders(data.extraProviders); + const nativeLocalProviderAuthorities = normalizeNativeLocalProviderAuthorities( + data.nativeLocalProviderAuthorities, + ); const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( data.nativeNvidiaProviderAuthorities, ); @@ -181,6 +219,8 @@ function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { sandboxes, }; if (extraProviders) base.extraProviders = extraProviders; + if (nativeLocalProviderAuthorities) + base.nativeLocalProviderAuthorities = nativeLocalProviderAuthorities; const nativeHostedProviderAuthorities = normalizeNativeHostedProviderAuthorities( data.nativeHostedProviderAuthorities, ); @@ -210,6 +250,7 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { ); const deferredN1xManagedVllmAccepted = normalizeDeferredN1xManagedVllmAcceptance(entry, "load"); const policyEntry = normalizeSandboxPolicyAttribution(entry); + const nativeLocalProviderAttachment = requireNativeLocalProviderAttachment(policyEntry, "load"); const { cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, @@ -218,6 +259,7 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, deferredN1xManagedVllmAccepted: _deferredN1xManagedVllmAccepted, + nativeLocalProviderAttachment: _nativeLocalProviderAttachment, nativeHostedProviderAttachment: hostedAttachment, nativeNvidiaProviderAuthority: _legacyNativeNvidiaProviderAuthority, mcp: _legacyMcp, @@ -233,6 +275,7 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { ); return { ...rest, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(workload ? { workload } : {}), ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), @@ -280,6 +323,7 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { ); const deferredN1xManagedVllmAccepted = normalizeDeferredN1xManagedVllmAcceptance(durable, "save"); const policyEntry = normalizeSandboxPolicyAttribution(durable); + const nativeLocalProviderAttachment = requireNativeLocalProviderAttachment(policyEntry, "save"); const { cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, @@ -288,6 +332,7 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, deferredN1xManagedVllmAccepted: _deferredN1xManagedVllmAccepted, + nativeLocalProviderAttachment: _nativeLocalProviderAttachment, nativeHostedProviderAttachment: hostedAttachment, nativeNvidiaProviderAuthority: _legacyNativeNvidiaProviderAuthority, mcp: _legacyMcp, @@ -303,6 +348,7 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { ); return { ...rest, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(rest.dashboardPort === 0 ? { dashboardPort: null } : {}), ...(workload ? { workload } : {}), diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index db83d35af79..99de661d7aa 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -1,6 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + normalizeNativeLocalProviderAttachment, + usesNativeLocalInference, +} from "../../inference/native-local/contract"; + import { isDeepStrictEqual } from "node:util"; import { normalizeInferenceSelection, type InferenceSelection } from "../../inference/selection"; @@ -24,6 +29,7 @@ const ROUTE_RESERVATION_KEYS = new Set([ "lifecycleLiveIdentityFingerprint", "model", "name", + "nativeLocalProviderAttachment", "nativeNvidiaProviderAttachment", "nativeHostedProviderAttachment", "openshellDriver", @@ -91,6 +97,11 @@ function validCarriedRouteMetadata(entry: SandboxEntry): boolean { if (entry.webSearchEnabled !== undefined && typeof entry.webSearchEnabled !== "boolean") { return false; } + if ( + entry.nativeLocalProviderAttachment !== undefined && + !normalizeNativeLocalProviderAttachment(entry.nativeLocalProviderAttachment) + ) + return false; if ( entry.nativeNvidiaProviderAttachment !== undefined && !normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) @@ -197,11 +208,13 @@ export function isPublishedSandboxRegistration(entry: { pendingRouteReservation? /** True when an entry participates in the inference route shared by its gateway. */ export function isSharedGatewayRouteParticipant(entry: { + nativeLocalProviderAttachment?: unknown; pendingRouteReservation?: true; createdAt?: string; provider?: string | null; model?: string | null; }): boolean { + if (normalizeNativeLocalProviderAttachment(entry.nativeLocalProviderAttachment)) return false; if (isPublishedSandboxRegistration(entry)) return true; return ( isRouteOnlySandboxReservation(entry) && @@ -358,6 +371,22 @@ export function sandboxRegistrationMatchesInferenceRouteReservation( ); } +export { normalizeNativeLocalProviderAttachment }; + +/** Keep a native attachment only when reusing its recorded route and gateway. */ +export function retainedNativeLocalProviderAttachment( + existing: SandboxEntry | undefined, + selection: Pick & { gatewayName: string }, +): SandboxEntry["nativeLocalProviderAttachment"] { + return existing && + usesNativeLocalInference(selection.provider, selection.endpointUrl) && + selection.provider === existing.provider && + selection.endpointUrl === existing.endpointUrl && + selection.gatewayName === existing.gatewayName + ? existing.nativeLocalProviderAttachment + : undefined; +} + /** Preserve only the selected hosted provider's validated registration/reservation identity. */ export function nativeHostedReservationAttachment( value: unknown, diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 20d77a53045..61fa6f0735a 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { NativeLocalProviderAttachment } from "../../inference/native-local/contract"; import type { NativeProviderAttachment } from "../../inference/native-provider/contract"; import type { NativeHostedProviderAuthorities } from "./native-provider-authority-state"; import type { InferenceSelection } from "../../inference/selection"; @@ -147,6 +148,8 @@ export interface SandboxEntry extends Partial { managedStartupProtocol?: "identity-bound" | "legacy-unbound"; /** Canonical provider-neutral receipt for an out-of-sandbox inference runtime. */ hostLocalInferenceReceipt?: string | null; + /** Exact host-local provider identity attached to this sandbox. */ + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; /** Exact OpenShell provider identity attached for native NVIDIA hosted inference. */ nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; /** Exact selected fixed hosted provider identity; separate from gateway ownership. */ @@ -250,6 +253,8 @@ export interface SandboxRegistry { defaultSandbox: string | null; defaultSelectionRevision?: number; extraProviders?: string[]; + /** NemoClaw-owned host-local provider identities keyed by provider name. */ + nativeLocalProviderAuthorities?: Record; /** Exact NemoClaw-owned native NVIDIA provider identity for each OpenShell gateway. */ nativeNvidiaProviderAuthorities?: Record; nativeHostedProviderAuthorities?: NativeHostedProviderAuthorities; diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index bbc4f4cde97..e8b6c3d0c3a 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -2,11 +2,34 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import { serializedLlamaCppHostLocalInferenceReceipt } from "../../test/helpers/host-local-inference-receipt"; import { buildChain } from "./dashboard/contract.js"; -import { probeOnboardInferenceInvocation, verifyDeployment } from "./verify-deployment.js"; +import { + nativeLocalIdentity, + NATIVE_LOCAL_CREDENTIAL_ENV, +} from "./inference/native-local/contract.js"; +import { + onboardInferenceVerificationContext, + probeOnboardInferenceInvocation, + verifyDeployment, +} from "./verify-deployment.js"; const NO_RETRY = { retryDelaysMs: [], sleep: async (_ms: number) => {} }; const DCODE_AGENT = "langchain-deepagents-code"; +const localBinding = { + provider: "ollama-local" as const, + endpointUrl: "http://host.openshell.internal:11434/v1", + credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV, + authMode: "sentinel" as const, + gatewayName: "my-gateway", + sandboxName: "my-sandbox", +}; +const localAttachment = { + ...localBinding, + ...nativeLocalIdentity(localBinding), + schemaVersion: 1 as const, + providerId: "provider-1", +}; function makeDeps(overrides: Record = {}) { return { @@ -35,6 +58,237 @@ function makeModelsRouteDeps(code: string, overrides: Record = } describe("verifyDeployment inference route model-catalog validation", () => { + it.each([ + ["openclaw", true], + [DCODE_AGENT, true], + ["pi", false], + ["hermes", false], + ])("selects the same onboarding verification route for %s", (agentName, expected) => { + const context = onboardInferenceVerificationContext("my-sandbox", "my-gateway", agentName, { + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: "http://host.openshell.internal:8000/v1", + preferredInferenceApi: "openai-completions", + }); + + expect(context.route.nativeLocalExpected).toBe(expected); + expect(context.invocation.nativeLocalExpected).toBe(expected); + }); + + it("uses the recorded native local attachment instead of the shared models route", async () => { + const scripts: string[] = []; + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); + const result = await verifyDeployment( + "my-sandbox", + buildChain(), + makeDeps({ + executeSandboxCommand: async (_name: string, script: string) => { + scripts.push(script); + return { status: 0, stdout: "200", stderr: "" }; + }, + probeInferenceInvocation, + }), + { + ...NO_RETRY, + inferenceRouteContext: { + provider: "ollama-local", + gatewayName: "my-gateway", + nativeLocalExpected: true, + nativeLocalProviderAttachment: localAttachment, + }, + }, + ); + + expect(result.verification.inferenceRouteWorking).toBe(true); + expect(probeInferenceInvocation).toHaveBeenCalledOnce(); + expect(scripts.join("\n")).not.toContain("inference.local"); + }); + + it("fails closed when a selected native local route has no attachment", async () => { + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); + const result = await verifyDeployment( + "my-sandbox", + buildChain(), + makeModelsRouteDeps("200", { probeInferenceInvocation }), + { + ...NO_RETRY, + inferenceRouteContext: { provider: "ollama-local", nativeLocalExpected: true }, + }, + ); + + expect(result.verification.inferenceRouteWorking).toBe(false); + expect(result.diagnostics.find((entry) => entry.link === "inference")?.detail).toContain( + "attachment is missing or invalid", + ); + expect(probeInferenceInvocation).not.toHaveBeenCalled(); + }); + + it("rejects a native local attachment from another gateway before probing inference", async () => { + const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); + const result = await verifyDeployment( + "my-sandbox", + buildChain(), + makeModelsRouteDeps("200", { probeInferenceInvocation }), + { + ...NO_RETRY, + inferenceRouteContext: { + provider: "ollama-local", + gatewayName: "other-gateway", + nativeLocalExpected: true, + nativeLocalProviderAttachment: localAttachment, + }, + }, + ); + + expect(result.verification.inferenceRouteWorking).toBe(false); + expect(result.diagnostics.find((entry) => entry.link === "inference")?.detail).toContain( + "attachment is missing or invalid", + ); + expect(probeInferenceInvocation).not.toHaveBeenCalled(); + }); + + it.each(["openclaw", 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("uses the published managed route when the provider phase still holds the host URL", async () => { + 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", + "openclaw", + { + provider: "llama-cpp-local", + model: "test-model", + endpointUrl: "http://127.0.0.1:8081/v1", + preferredInferenceApi: "openai-completions", + }, + { + provider: "llama-cpp-local", + model: "test-model", + endpointUrl: "https://inference.local/v1", + hostLocalInferenceReceipt: serializedLlamaCppHostLocalInferenceReceipt(), + nativeLocalProviderAttachment: attachment, + }, + ); + expect(context.route.endpointUrl).toBe("https://inference.local/v1"); + expect(context.invocation.endpointUrl).toBe("https://inference.local/v1"); + const probe = vi.fn(async () => ({ ok: true }) as const); + expect(await probeOnboardInferenceInvocation(context.invocation, probe)).toEqual({ ok: true }); + expect(probe).toHaveBeenCalledOnce(); + }); + + it("rejects a native local attachment for a different selected endpoint in both probes", async () => { + const context = onboardInferenceVerificationContext( + "my-sandbox", + "my-gateway", + DCODE_AGENT, + { + provider: "ollama-local", + model: "test-model", + endpointUrl: "http://host.openshell.internal:11435/v1", + preferredInferenceApi: "openai-completions", + }, + { nativeLocalProviderAttachment: localAttachment }, + ); + 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(false); + expect(routeProbe).not.toHaveBeenCalled(); + + const invocationProbe = vi.fn(async () => ({ ok: true }) as const); + expect( + await probeOnboardInferenceInvocation(context.invocation, invocationProbe), + ).toMatchObject({ + ok: false, + }); + expect(invocationProbe).not.toHaveBeenCalled(); + }); + + it("accepts a normalized spelling of the selected native local endpoint", async () => { + const context = onboardInferenceVerificationContext( + "my-sandbox", + "my-gateway", + DCODE_AGENT, + { + provider: "ollama-local", + model: "test-model", + endpointUrl: `${localBinding.endpointUrl}/`, + preferredInferenceApi: "openai-completions", + }, + { nativeLocalProviderAttachment: localAttachment }, + ); + const probe = vi.fn(async () => ({ ok: true }) as const); + expect(await probeOnboardInferenceInvocation(context.invocation, probe)).toEqual({ ok: true }); + expect(probe).toHaveBeenCalledOnce(); + 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(); + }); + it("uses the native NVIDIA invocation instead of probing inference.local", async () => { const scripts: string[] = []; const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); @@ -300,6 +554,52 @@ describe("verifyDeployment inference route model-catalog validation", () => { }); }); + it("passes the native local receipt to the bounded agent request", async () => { + const probe = vi.fn(async () => ({ ok: true }) as const); + const result = await probeOnboardInferenceInvocation( + { + sandboxName: "my-sandbox", + gatewayName: "my-gateway", + agentName: DCODE_AGENT, + model: "test-model", + provider: "ollama-local", + preferredInferenceApi: "openai-completions", + nativeLocalExpected: true, + nativeLocalProviderAttachment: localAttachment, + }, + probe, + ); + + expect(result).toEqual({ ok: true }); + expect(probe).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + gatewayName: "my-gateway", + provider: "ollama-local", + model: "test-model", + nativeLocalProviderAttachment: localAttachment, + }), + ); + }); + + it("does not request inference without the selected native local receipt", async () => { + const probe = vi.fn(async () => ({ ok: true }) as const); + const result = await probeOnboardInferenceInvocation( + { + sandboxName: "my-sandbox", + gatewayName: "my-gateway", + agentName: DCODE_AGENT, + model: "test-model", + provider: "ollama-local", + preferredInferenceApi: "openai-completions", + nativeLocalExpected: true, + }, + probe, + ); + + expect(result).toMatchObject({ ok: false }); + expect(probe).not.toHaveBeenCalled(); + }); + it("fails closed when a model was recorded without its provider (#10543)", async () => { const result = await probeOnboardInferenceInvocation({ sandboxName: "my-sandbox", diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 4aed793ae3c..ad81cdceb0d 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -33,6 +33,12 @@ import { listMessagingChannelsWithoutCredentials } from "./messaging/channels"; import { retryUntilAsync } from "./core/retry"; import { isNativeNvidiaProvider } from "./inference/native-nvidia"; import { requireHostedProviderAttachment } from "./inference/native-provider/hosted-attachment"; +import { + normalizeNativeLocalBinding, + normalizeNativeLocalProviderAttachment, + usesNativeLocalInferenceForAgent, + type NativeLocalProviderAttachment, +} from "./inference/native-local/contract"; import { buildCustomOpenClawRuntimeFailureHints, classifyOpenClawRuntimeFailure, @@ -40,6 +46,8 @@ import { } from "./onboard/custom-openclaw-runtime-diagnosis"; import { GATEWAY_PORT, resolveGatewayLogPathForPort } from "./onboard/gateway/state-dir"; import { getMessagingProviderNamesForChannel } from "./onboard/messaging-reuse"; +import { HOST_LOCAL_INFERENCE_APPLICATION_BASE_URL } from "./onboard/runtime-provider/host-local-inference-routing"; +import { nativeLocalAttachmentMatchesHostLocalReceipt } from "./state/registry/host-local-inference"; export { shouldDiagnoseCustomOpenClawRuntime } from "./onboard/custom-openclaw-runtime-diagnosis"; @@ -114,8 +122,8 @@ export interface VerifyDeploymentDeps { /** * Send one bounded inference request over the sandbox's configured route. - * This request is authoritative for native NVIDIA, which has no shared - * `inference.local` route. It also validates OpenRouter runtime adapters, + * This request is authoritative for attached native providers, which have + * no shared `inference.local` route. It also validates OpenRouter runtime adapters, * whose models route returns HTTP 404 (#12621). When this dependency is * absent, both exceptional paths fail closed because no request validated * the selected model (#10543). @@ -269,6 +277,10 @@ type InferenceRouteStatus = "ok" | "unreachable" | "unhealthy"; */ export type InferenceRouteContext = { provider?: string | null; + endpointUrl?: string | null; + gatewayName?: string; + nativeLocalExpected?: boolean; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeHostedProviderAttachment?: unknown; }; @@ -391,6 +403,28 @@ async function resolveExpectedModelsRoute404( }; } +function matchesNativeLocalVerificationRoute( + context: InferenceRouteContext, + sandboxName: string, +): boolean { + const attachment = normalizeNativeLocalProviderAttachment(context.nativeLocalProviderAttachment); + if ( + !attachment || + attachment.sandboxName !== sandboxName || + attachment.gatewayName !== context.gatewayName || + attachment.provider !== context.provider + ) + return false; + if (context.endpointUrl === undefined) return true; + if ( + context.nativeLocalExpected && + context.endpointUrl === HOST_LOCAL_INFERENCE_APPLICATION_BASE_URL + ) + return true; + const selected = normalizeNativeLocalBinding({ ...attachment, endpointUrl: context.endpointUrl }); + return selected?.endpointUrl === attachment.endpointUrl; +} + async function verifyInferenceRoute( sandboxName: string, deps: VerifyDeploymentDeps, @@ -398,6 +432,8 @@ async function verifyInferenceRoute( sleep: (ms: number) => Promise, context: InferenceRouteContext, ): Promise { + const nativeLocal = + context.nativeLocalExpected || context.nativeLocalProviderAttachment !== undefined; let hostedAttachment; try { hostedAttachment = requireHostedProviderAttachment( @@ -412,8 +448,20 @@ async function verifyInferenceRoute( hint: "Restore the recorded provider ownership before retrying onboarding.", }; } - if (isNativeNvidiaProvider(context.provider) || hostedAttachment) { - const label = hostedAttachment ? (context.provider?.trim() ?? "hosted") : "NVIDIA"; + if (nativeLocal && !matchesNativeLocalVerificationRoute(context, sandboxName)) { + return { + status: "unhealthy", + detail: "native local provider attachment is missing or invalid", + httpCode: 0, + hint: "Reconcile the recorded native local provider before retrying onboarding.", + }; + } + if (isNativeNvidiaProvider(context.provider) || hostedAttachment || nativeLocal) { + const label = nativeLocal + ? "local" + : hostedAttachment + ? (context.provider?.trim() ?? "hosted") + : "NVIDIA"; const invocation = await retryUntilAsync( async () => (await deps.probeInferenceInvocation?.()) ?? null, { @@ -918,8 +966,76 @@ export type InferenceInvocationContext = InferenceRouteContext & { model: string | null; provider: string | null; preferredInferenceApi: string | null; + nativeLocalExpected?: boolean; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; }; +/** Keep onboarding route verification and its request on the same selected route. */ +export function onboardInferenceVerificationContext( + sandboxName: string, + gatewayName: string, + agentName: string, + flow: Pick & { + endpointUrl?: string | null; + }, + attachment?: + | (Pick< + InferenceRouteContext, + "nativeLocalProviderAttachment" | "nativeHostedProviderAttachment" + > & + Partial> & { + hostLocalInferenceReceipt?: string | null; + }) + | null, +): { route: InferenceRouteContext; invocation: InferenceInvocationContext } { + const nativeLocalExpected = usesNativeLocalInferenceForAgent( + agentName, + flow.provider, + flow.endpointUrl, + ); + const nativeLocalProviderAttachment = attachment?.nativeLocalProviderAttachment; + const nativeHostedProviderAttachment = attachment?.nativeHostedProviderAttachment; + const recordedHostLocalRouteMatchesAttachment = + nativeLocalProviderAttachment && + nativeLocalAttachmentMatchesHostLocalReceipt( + attachment?.endpointUrl, + nativeLocalProviderAttachment.endpointUrl, + attachment?.hostLocalInferenceReceipt, + ); + // The provider phase can still hold the host listener URL after publishing a + // managed local route. Verify the exact recorded application route instead. + const endpointUrl = + nativeLocalExpected && + nativeLocalProviderAttachment && + attachment?.provider === flow.provider && + attachment?.model === flow.model && + recordedHostLocalRouteMatchesAttachment + ? attachment.endpointUrl + : (flow.endpointUrl ?? null); + return { + route: { + provider: flow.provider, + endpointUrl, + gatewayName, + nativeLocalExpected, + nativeLocalProviderAttachment, + nativeHostedProviderAttachment, + }, + invocation: { + sandboxName, + gatewayName, + agentName, + model: flow.model, + provider: flow.provider, + endpointUrl, + preferredInferenceApi: flow.preferredInferenceApi, + nativeLocalExpected, + nativeLocalProviderAttachment, + nativeHostedProviderAttachment, + }, + }; +} + /** * The standard `probeInferenceInvocation` dependency: send one bounded * inference request over the recorded native or retained shared route, using @@ -929,11 +1045,18 @@ export type InferenceInvocationContext = InferenceRouteContext & { */ export async function probeOnboardInferenceInvocation( context: InferenceInvocationContext, + probe: typeof runSandboxInferenceInvocationProbe = runSandboxInferenceInvocationProbe, ): Promise<{ ok: boolean; detail?: string }> { const { model, provider } = context; if (!model || !provider) { return { ok: false, detail: "no provider and model were recorded for this sandbox" }; } + if ( + (context.nativeLocalExpected || context.nativeLocalProviderAttachment !== undefined) && + !matchesNativeLocalVerificationRoute(context, context.sandboxName) + ) { + return { ok: false, detail: "native local provider attachment is missing or invalid" }; + } let hostedAttachment; try { hostedAttachment = requireHostedProviderAttachment( @@ -952,14 +1075,21 @@ export async function probeOnboardInferenceInvocation( detail: "the recorded native hosted provider attachment could not be verified", }; } - const result = await runSandboxInferenceInvocationProbe({ + const result = await probe({ sandboxName: context.sandboxName, gatewayName: context.gatewayName, agentName: context.agentName ?? null, provider, model, preferredInferenceApi: context.preferredInferenceApi, - ...(isNativeNvidiaProvider(provider) || hostedAttachment ? { nativeProvider: true } : {}), + ...(context.nativeLocalProviderAttachment + ? { nativeLocalProviderAttachment: context.nativeLocalProviderAttachment } + : {}), + ...(isNativeNvidiaProvider(provider) || + hostedAttachment || + context.nativeLocalProviderAttachment + ? { nativeProvider: true } + : {}), ...(hostedAttachment?.endpointUrl ? { nativeEndpointUrl: hostedAttachment.endpointUrl } : {}), }); return result.ok ? { ok: true } : { ok: false, detail: result.detail }; diff --git a/test/agents/deepagents/dcode-start-keepalive.test.ts b/test/agents/deepagents/dcode-start-keepalive.test.ts index d5bd74a2509..a2b0c79109d 100644 --- a/test/agents/deepagents/dcode-start-keepalive.test.ts +++ b/test/agents/deepagents/dcode-start-keepalive.test.ts @@ -186,3 +186,41 @@ describe("Deep Agents Code sandbox entrypoint keep-alive (#5717)", () => { ); }); }); + +it.each(["v42", `s${"a".repeat(64)}`])( + "preserves native credential identity %s through startup and a later shell", + (identity) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-start-native-")); + tempDirs.push(dir); + const fixture = makeStartScriptFixture(dir); + const reference = `openshell:resolve:env:${identity}_NEMOCLAW_LOCAL_INFERENCE_TOKEN`; + const result = spawnSync( + fixture.scriptPath, + ["sh", "-c", 'printf "NATIVE_REF=%s\\n" "$NEMOCLAW_LOCAL_INFERENCE_TOKEN"'], + { + env: { ...process.env, NEMOCLAW_LOCAL_INFERENCE_TOKEN: reference }, + encoding: "utf8", + timeout: 5000, + }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain(`NATIVE_REF=${reference}`); + const laterReference = "openshell:resolve:env:v43_NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + const shell = spawnSync( + "bash", + [ + "-c", + 'source "$1"; printf "%s" "$NEMOCLAW_LOCAL_INFERENCE_TOKEN"', + "fixture", + fixture.envFile, + ], + { + env: { ...process.env, NEMOCLAW_LOCAL_INFERENCE_TOKEN: laterReference }, + encoding: "utf8", + timeout: 5000, + }, + ); + expect(shell.status, shell.stderr).toBe(0); + expect(shell.stdout).toBe(laterReference); + }, +); diff --git a/test/agents/deepagents/langchain-deepagents-code-config.test.ts b/test/agents/deepagents/langchain-deepagents-code-config.test.ts index 75db76a72fb..65dda40752d 100644 --- a/test/agents/deepagents/langchain-deepagents-code-config.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-config.test.ts @@ -69,6 +69,21 @@ function runGenerator(env: Record): string { } describe("LangChain Deep Agents Code config generator", () => { + it.each(["ollama-local", "vllm-local", "llama-cpp-local"])( + "writes the selected native endpoint and credential reference for %s (#12558)", + (provider) => { + const config = runGenerator({ + NEMOCLAW_UPSTREAM_PROVIDER: provider, + NEMOCLAW_MODEL: "local-model", + NEMOCLAW_INFERENCE_BASE_URL: "http://host.openshell.internal:11434/v1", + OPENAI_API_KEY: "ambient-secret-must-not-escape", + }); + expect(config).toContain('base_url = "http://host.openshell.internal:11434/v1"'); + expect(config).toContain('api_key_env = "NEMOCLAW_LOCAL_INFERENCE_TOKEN"'); + expect(config).toContain('default = "openai:local-model"'); + expect(config).not.toContain("ambient-secret-must-not-escape"); + }, + ); it.each( HOSTED_NATIVE_PROVIDERS.filter( (provider) => diff --git a/test/agents/deepagents/langchain-deepagents-code-image-credentials.test.ts b/test/agents/deepagents/langchain-deepagents-code-image-credentials.test.ts index c563749bdbb..efe5b71e37f 100644 --- a/test/agents/deepagents/langchain-deepagents-code-image-credentials.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-image-credentials.test.ts @@ -869,3 +869,51 @@ describe("LangChain Deep Agents Code image credential boundary", () => { }, ); }); + +it.each(["v42", `s${"a".repeat(64)}`])( + "passes the issued native local identity %s to DCode unchanged", + (identity) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-identity-")); + try { + const fixture = makeWrapperFixture(dir); + fs.writeFileSync( + fixture.wrapperPath, + fs + .readFileSync(fixture.wrapperPath, "utf8") + .replace("echo dcode-stub-ran", 'printf "%s\\n" "$NEMOCLAW_LOCAL_INFERENCE_TOKEN"'), + ); + const reference = `openshell:resolve:env:${identity}_NEMOCLAW_LOCAL_INFERENCE_TOKEN`; + const result = runWrapper(fixture.wrapperPath, ["-n", "hi"], { + NEMOCLAW_LOCAL_INFERENCE_TOKEN: reference, + }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe(reference); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }, +); + +it.each([ + "", + "short", + "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + "openshell:resolve:env:v42_OTHER_KEY", + "opaque-host-secret-must-not-leak", +])("refuses invalid native local credential candidate %# before DCode launch", (reference) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-denial-")); + try { + const fixture = makeWrapperFixture(dir); + const result = runWrapper(fixture.wrapperPath, ["-n", "hi"], { + NEMOCLAW_LOCAL_INFERENCE_TOKEN: reference, + }); + expect(result.status).toBe(2); + expect(fs.existsSync(fixture.ranMarker)).toBe(false); + expect(result.stdout).toBe(""); + expect(result.stderr).toBe( + "dcode: refusing to start — runtime environment variable contains an invalid OpenShell credential placeholder in NEMOCLAW_LOCAL_INFERENCE_TOKEN.\n Use only the exact placeholder for that same environment variable.\n", + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/test/agents/deepagents/langchain-deepagents-code-image.test.ts b/test/agents/deepagents/langchain-deepagents-code-image.test.ts index 6ae64ac7535..0f504b7165f 100644 --- a/test/agents/deepagents/langchain-deepagents-code-image.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-image.test.ts @@ -224,8 +224,7 @@ describe("LangChain Deep Agents Code image contracts", () => { "USER root", ].join("\n"); const managedRuntimeDirectory = "&& install -d -o root -g root -m 0755 /run/nemoclaw"; - const runtimeModeReplay = - "RUN chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts"; + const runtimeModeReplay = "RUN chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts"; expect(dockerfile).toContain("ARG BASE_IMAGE\n"); expect(dockerfile).toContain("ARG NEMOCLAW_MODEL=nvidia/nemotron-3-ultra-550b-a55b"); diff --git a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts index b64106f7fd1..e4a1811956a 100644 --- a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts @@ -9,6 +9,7 @@ import { cleanupPackageFixtures, createPackageFixture, patchFixture, + managedUpstreamProviderPath, } from "../../helpers/langchain-deepagents-code-patch-fixture"; afterEach(cleanupPackageFixtures); @@ -91,6 +92,63 @@ print("managed-ultra-template-argument-ok") expect(output).toContain("managed-ultra-template-argument-ok"); }); + it("passes the issued native-local reference to the actual model constructor (#12558)", () => { + const tempDir = createPackageFixture(); + patchFixture(tempDir); + const routeFile = path.join(tempDir, "managed-inference-base-url"); + const providerFile = managedUpstreamProviderPath(tempDir); + const validation = ` +import os +from pathlib import Path +from deepagents_code import config + +def write_owned(file, value): + path = Path(file) + path.chmod(0o644) + path.write_text(value + "\\n") + path.chmod(0o444) + +name = "NEMOCLAW_LOCAL_INFERENCE_TOKEN" +for upstream in ("ollama-local", "vllm-local", "llama-cpp-local", "compatible-endpoint"): + write_owned(${JSON.stringify(providerFile)}, upstream) + for endpoint in ("http://host.openshell.internal:8000/v1", "http://host.docker.internal:11434/v1", "http://10.2.3.4:8000/v1", "http://172.16.2.3:8000/v1", "http://192.168.2.3:8000/v1"): + write_owned(${JSON.stringify(routeFile)}, endpoint) + for identity in ("v42", "s" + "a" * 64): + reference = "openshell:resolve:env:" + identity + "_" + name + os.environ[name] = reference + for adapter in ("openai", "openrouter"): + resolved = config._get_provider_kwargs(adapter, model_name="local-model") + assert resolved["api_key"] == reference + assert resolved["base_url"] == endpoint + for invalid in (None, "", "raw-secret", "openshell:resolve:env:" + name, "openshell:resolve:env:v42_OTHER_KEY", "openshell:resolve:env:v42_" + name + "\\n"): + if invalid is None: + os.environ.pop(name, None) + else: + os.environ[name] = invalid + try: + config._get_provider_kwargs("openai") + except RuntimeError as error: + assert not invalid or invalid not in str(error) + else: + raise AssertionError("invalid native-local reference accepted") + +# Ambient local credentials cannot replace the managed hosted-route token. +os.environ[name] = "openshell:resolve:env:v42_" + name +for endpoint in ("https://inference.local/v1", "https://host.openshell.internal:8000/v1", "http://172.32.2.3:8000/v1"): + write_owned(${JSON.stringify(routeFile)}, endpoint) + assert config._get_provider_kwargs("openai")["api_key"] == "nemoclaw-managed-inference" +write_owned(${JSON.stringify(routeFile)}, "http://host.openshell.internal:8000/v1") +write_owned(${JSON.stringify(providerFile)}, "nvidia-prod") +assert config._get_provider_kwargs("openai")["api_key"] == "nemoclaw-managed-inference" +print("native-local-constructor-reference-ok") +`; + const output = execFileSync("python3", ["-c", validation], { + env: { PATH: process.env.PATH, PYTHONPATH: tempDir }, + encoding: "utf8", + }); + expect(output).toContain("native-local-constructor-reference-ok"); + }); + it("passes only the matching OpenShell placeholder to the native NVIDIA constructor (#11847)", () => { const tempDir = createPackageFixture(); patchFixture(tempDir); diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts index 451a6dd9781..c63ea895114 100644 --- a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts @@ -381,6 +381,77 @@ os.fsync = sync_or_fail` ); }); + it.each([ + { rootMode: false, endpoint: "http://host.openshell.internal:11436/v1" }, + { rootMode: true, endpoint: "http://host.openshell.internal:11436/v1" }, + { rootMode: false, endpoint: "http://10.2.3.4:11436/v1" }, + ])( + "refreshes a persisted native local handle after sandbox rebuild (root=$rootMode, endpoint=$endpoint)", + async ({ rootMode, endpoint }) => { + const oldHandle = "openshell:resolve:env:v42_NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + const currentHandle = "openshell:resolve:env:v43_NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + const run = await runRefresh( + { + models: { + providers: { + inference: { + baseUrl: endpoint, + apiKey: oldHandle, + }, + }, + }, + channels: { telegram: { botToken: oldHandle } }, + }, + { NEMOCLAW_LOCAL_INFERENCE_TOKEN: currentHandle }, + rootMode, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers.inference.apiKey).toBe(currentHandle); + expect(run.config.channels.telegram.botToken).toBe(oldHandle); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: NEMOCLAW_LOCAL_INFERENCE_TOKEN", + ); + }, + ); + + it.each([ + { + reason: "raw credential", + endpoint: "http://host.openshell.internal:11436/v1", + runtime: "raw-secret", + }, + { + reason: "public endpoint", + endpoint: "https://example.com/v1", + runtime: "openshell:resolve:env:v43_NEMOCLAW_LOCAL_INFERENCE_TOKEN", + }, + { + reason: "loopback endpoint", + endpoint: "http://127.0.0.1:11436/v1", + runtime: "openshell:resolve:env:v43_NEMOCLAW_LOCAL_INFERENCE_TOKEN", + }, + { + reason: "missing runtime handle", + endpoint: "http://host.openshell.internal:11436/v1", + runtime: "", + }, + ])( + "keeps a persisted native local handle when refresh has $reason", + async ({ endpoint, runtime }) => { + const saved = "openshell:resolve:env:v42_NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + const run = await runRefresh( + { models: { providers: { inference: { baseUrl: endpoint, apiKey: saved } } } }, + runtime ? { NEMOCLAW_LOCAL_INFERENCE_TOKEN: runtime } : {}, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers.inference.apiKey).toBe(saved); + expect(JSON.stringify(run.config)).not.toContain("raw-secret"); + expect(run.result.stderr).not.toContain("raw-secret"); + }, + ); + it.each([ { reason: "raw credential in root environment", diff --git a/test/e2e/README.md b/test/e2e/README.md index 9a07a75dd1c..971f4964b12 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -2383,6 +2383,16 @@ test, and makes `full-e2e` the source of truth for the hard cold-path contract. The explicit `dgx-station-express` target runs the local Station Express installer with cached Ultra weights, checks routed sandbox inference, and uninstalls the job runtime. See [Station dispatch](docs/dgx-station-dispatch.md) for prerequisites, workflow selection, and evidence boundaries. +### Native host-local inference + +`managed-image-activation` owns real OpenClaw and DCode agent turns before and after restart. Its authenticated compatible-server fixture listens on native-local port 8000, so those turns exercise sandbox-attached providers and the server's selected-model request ledger. A second DCode sandbox uses the existing credentialless vLLM selection against a separate fixture port. Its real agent turns before and after restart must reach that endpoint and model, and its recorded attachment must declare `authMode: sentinel`. Each case keeps separate artifacts and verifies sandbox removal. Hermes uses its shared route. `double-onboard` owns two real OpenShell sandboxes; its sibling uses a native provider on port 11434, and the first sandbox must receive a policy denial when it requests that endpoint. Existing GPU qualification owns Ollama, vLLM, llama.cpp, startup, and cleanup. + +Profile rules, ownership collisions, credential custody, mutation reconciliation, gateway prerequisites, and generated request behavior belong to the native-local, provider-policy, gateway bootstrap, and compatible-endpoint-smoke source tests. Sibling denial remains live because a source test cannot prove OpenShell composes provider policy per sandbox. No assertion about terminal formatting is added. + +`gpu-e2e` and `gpu-double-onboard` retain their existing live chat assertions against the qualified Ollama proxy endpoint with the attached provider placeholder. They protect native routing after GPU startup and recreation. Request construction and credential reference selection remain in source and generator tests; these live assertions prove the real OpenShell proxy boundary. Their assertion counts are unchanged. + +Native Ollama and managed vLLM export reuse the existing GPU export cases. SDK metadata, exact native profile permissions, attachment identity, stable observation, credential custody, and unchanged service serialization are covered by the live-export-source Ollama/vLLM pipeline tests in the CLI lane. Export adds no live assertions. + ## Fixed hosted provider qualification `live/inference-routing-provider-smoke.test.ts` owns credential-backed native inference smoke tests. @@ -2429,9 +2439,7 @@ sandbox isolation, restart, and failed-operation recovery. Each selected case requires its matching approved model variable, listed below. The smoke does not select a default model. The Hermes smoke uses `NOUS_API_KEY`. It does not prove interactive OAuth login or token refresh. Credentials remain in the test host environment and OpenShell provider store; artifacts redact them. -The cleanup helper destroys each test sandbox. The Deep Agents Code case checks sandbox absence even if onboarding fails. -Other hosted cases check absence after successful onboarding; failed onboarding uses best-effort cleanup. -Neither path proves removal of credentials from the OpenShell provider store. +The cleanup helper destroys each test sandbox. After successful onboarding, strict cleanup checks sandbox absence and requires public `nemoclaw destroy` to succeed so provider retirement cannot be silently skipped. The Deep Agents Code case also checks sandbox absence if onboarding fails; other hosted cases use best-effort cleanup after failed onboarding. Neither path proves removal of credentials from the OpenShell provider store. Discard the approved disposable gateway after each run, including failed onboarding. Use a fresh gateway for a retry. Select one explicit target with `targets=hosted-inference-openai`, `hosted-inference-anthropic`, diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index 0e3dcb2e3f7..194e5e34787 100644 --- a/test/e2e/fixtures/hermes-config-export-live.ts +++ b/test/e2e/fixtures/hermes-config-export-live.ts @@ -98,6 +98,14 @@ const CREDENTIAL_HTTP_REFUSAL = const PODMAN_REFUSAL = "V1alpha1 export currently supports the Docker runtime; Podman compatibility is deferred."; const MESSAGING_REFUSAL = "V1 export does not support messaging."; +const POLICY_REFUSAL = + "Verified effective policy is malformed, unknown, or cannot be represented losslessly."; +// The exporter reports these v1 compatibility limits alongside excluded messaging. +const MESSAGING_ADDITIONAL_REFUSALS = [ + "The sandbox provider attachments do not match its supported configuration.", + "The managed startup profile is not the canonical profile supported by v1 export.", + POLICY_REFUSAL, +]; function normalizeCommandDiagnostics(stdout: string, stderr: string): string { return [stdout, stderr] @@ -355,10 +363,23 @@ export async function verifyHermesConfigExportLive( const refusalDiagnosticMatches = [nemoclawDiagnostics, nemohermesDiagnostics].every( (diagnostic) => { if (!expectsMessagingRefusal) return diagnostic === expectedDiagnostic; - const lines = diagnostic.split("\n"); + const [header, ...findings] = diagnostic.split("\n"); + const categories = /^Config export failed \(([^)]+)\)\.$/u + .exec(header ?? "")?.[1] + ?.split(", "); + const expectedCategories = [ + "unsupported", + ...(findings.includes(POLICY_REFUSAL) ? ["policy-not-representable"] : []), + ]; return ( - lines[0] === "Config export failed (unsupported)." && - expectedRefusals.every((refusal) => lines.includes(refusal)) + categories?.length === expectedCategories.length && + expectedCategories.every((category) => categories.includes(category)) && + expectedRefusals.every((refusal) => findings.includes(refusal)) && + findings.every( + (finding) => + expectedRefusals.includes(finding) || + MESSAGING_ADDITIONAL_REFUSALS.includes(finding), + ) ); }, ); diff --git a/test/e2e/fixtures/phases/lifecycle.ts b/test/e2e/fixtures/phases/lifecycle.ts index 122a7bb447c..7c435ba341b 100644 --- a/test/e2e/fixtures/phases/lifecycle.ts +++ b/test/e2e/fixtures/phases/lifecycle.ts @@ -126,6 +126,11 @@ export function buildOpenShellGatewayUserServiceStopScript( " exit 1", "fi", 'source "$installer"', + 'if [ "$(uname -s)" = Linux ] && command -v systemctl >/dev/null 2>&1; then', + ' runtime_dir="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"', + ' export XDG_RUNTIME_DIR="$runtime_dir"', + ' export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$runtime_dir/bus}"', + "fi", ...(options.permanent ? [ 'if [ "$(uname -s)" = Linux ] && command -v systemctl >/dev/null 2>&1; then', diff --git a/test/e2e/live/double-onboard.test.ts b/test/e2e/live/double-onboard.test.ts index 0ea7afab584..6b9981c5390 100644 --- a/test/e2e/live/double-onboard.test.ts +++ b/test/e2e/live/double-onboard.test.ts @@ -5,6 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { parseOpenShellSandboxId } from "../../../src/lib/adapters/openshell/sandbox-identity.ts"; +import { NATIVE_LOCAL_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-local/agent-config.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText } from "../fixtures/clients/command.ts"; @@ -268,6 +269,12 @@ test( "re-onboard same sandbox on existing gateway", "recreate OpenClaw sandbox after a model change", "onboard sibling sandbox with isolated dashboard", + ...(process.env.NEMOCLAW_AGENT === "hermes" + ? [] + : [ + "verify sibling native endpoint remains isolated", + "verify sibling native endpoint accepts authenticated requests", + ]), "stop sibling sandbox without disturbing the first forward", "replace sandbox after stale registry refusal", "remove double-onboard resources", @@ -315,6 +322,24 @@ test( await artifacts.writeJson("fake-openai-requests.json", fake.requests()); await fake.close(); }); + const siblingInference = + process.env.NEMOCLAW_AGENT === "hermes" + ? null + : await startFakeOpenAiCompatibleServer({ + apiKey: "dummy", + host: "0.0.0.0", + model: "test-model", + port: 11434, + progress, + publicHost: "host.openshell.internal", + requireAuth: true, + requireAuthModels: true, + }); + siblingInference && + cleanup.trackDisposable("close sibling OpenAI-compatible endpoint", async () => { + await artifacts.writeJson("sibling-openai-requests.json", siblingInference.requests()); + await siblingInference.close(); + }); cleanup.trackGateway(host, "nemoclaw", { artifactName: "cleanup-openshell-gateway-destroy-nemoclaw", env: commandEnv(), @@ -373,6 +398,9 @@ test( "changed-model OpenClaw onboarding replaces the sandbox and updates agent and registry selection", ]), "a sibling sandbox keeps a separate owned dashboard forward", + ...(process.env.NEMOCLAW_AGENT === "hermes" + ? [] + : ["a sibling native provider does not grant the first sandbox access to its endpoint"]), "stopping the sibling releases only its dashboard forward", "status and connect preserve a stale local registration", "explicit removal permits a clean replacement and complete cleanup", @@ -487,9 +515,60 @@ test( } progress.phase("onboard sibling sandbox with isolated dashboard"); - const sibling = await runOnboard(host, SANDBOX_B, fake.baseUrl, "phase-4-sibling-onboard"); + const sibling = await runOnboard( + host, + SANDBOX_B, + siblingInference?.baseUrl ?? fake.baseUrl, + "phase-4-sibling-onboard", + ); expect(sibling.exitCode, resultText(sibling)).toBe(0); + siblingInference && progress.phase("verify sibling native endpoint remains isolated"); + const denied = siblingInference + ? await sandbox.exec( + SANDBOX_A, + ["curl", "-sS", "--max-time", "15", "http://host.openshell.internal:11434/v1/models"], + { + artifactName: "phase-4-sibling-native-endpoint-denial", + env: commandEnv(), + timeoutMs: 30_000, + }, + ) + : null; + denied && expect(JSON.parse(denied.stdout)).toMatchObject({ error: "policy_denied" }); + + siblingInference && + progress.phase("verify sibling native endpoint accepts authenticated requests"); + const previousRequests = siblingInference?.requests().length ?? 0; + const accepted = siblingInference + ? await sandbox.exec( + SANDBOX_B, + [ + "sh", + "-lc", + `${NATIVE_LOCAL_AUTH_HEADER_SCRIPT}; curl -fsS --max-time 15 http://host.openshell.internal:11434/v1/chat/completions -H "$AUTH_HEADER" -H 'Content-Type: application/json' --data '{"model":"test-model","messages":[{"role":"user","content":"ping"}]}'`, + ], + { + artifactName: "phase-4-sibling-native-endpoint-authenticated-post", + env: commandEnv(), + timeoutMs: 30_000, + }, + ) + : null; + accepted && expect(accepted.exitCode, resultText(accepted)).toBe(0); + siblingInference && + expect( + siblingInference + .requests() + .slice(previousRequests) + .some( + (request) => + request.auth === "ok" && + request.method === "POST" && + request.path === "/v1/chat/completions", + ), + ).toBe(true); + const dashboardABeforeStop = await waitForDashboardReachability( host, DASHBOARD_PORT_A, diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index 03777ab4a0e..afb328949e0 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -4,6 +4,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { NATIVE_LOCAL_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-local/agent-config.ts"; import { containsAnswer } from "../../helpers/e2e-answer-assertions.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; @@ -145,7 +146,7 @@ async function expectSandboxInference42( [ "sh", "-lc", - `curl -fsS --max-time 120 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data '${chatRequest(model)}' | ${parseReplyCommand()}`, + `${NATIVE_LOCAL_AUTH_HEADER_SCRIPT}; curl -fsS --max-time 120 http://host.openshell.internal:${PROXY_PORT}/v1/chat/completions -H "$AUTH_HEADER" -H 'Content-Type: application/json' --data '${chatRequest(model)}' | ${parseReplyCommand()}`, ], { artifactName, @@ -192,7 +193,7 @@ test( "the persisted Ollama auth-proxy token works after first onboard", "nemoclaw onboard --non-interactive --yes recreates the sandbox", "the running proxy accepts the persisted token after re-onboard and rejects unauthenticated/wrong-token requests", - "sandbox inference.local reaches Ollama after re-onboard", + "sandbox native endpoint reaches Ollama after re-onboard", ], }); diff --git a/test/e2e/live/gpu-e2e-helpers.ts b/test/e2e/live/gpu-e2e-helpers.ts index 63c668c11e1..3feda02f2a5 100644 --- a/test/e2e/live/gpu-e2e-helpers.ts +++ b/test/e2e/live/gpu-e2e-helpers.ts @@ -2,10 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; import { ownChildProcess } from "../../helpers/child-process-lifecycle.ts"; +import { getSandboxAcrossGatewayRoots } from "../../../src/lib/state/registry/cross-port.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import type { ArtifactSink } from "../fixtures/artifacts.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import { resultText } from "../fixtures/clients/index.ts"; import { type SandboxClient, validateSandboxName } from "../fixtures/clients/sandbox.ts"; @@ -218,19 +221,47 @@ export function assertAgentExecutionSucceeded( ); } +/** Retain the serving process result even when the following agent assertion fails. */ +export async function captureManagedRuntimeLogArtifact( + artifacts: Pick, + phase: "setup" | "pre-approval-agent" | "post-agent", + providerId: string, + runtimeId: string, + capture: () => { + status: number | null; + error?: { message: string } | null; + stdout: string; + stderr: string; + }, +): Promise { + const runtimeLogs = capture(); + await artifacts.writeJson(`managed-runtime-logs-${phase}.json`, { + providerId, + runtimeId, + status: runtimeLogs.status, + error: runtimeLogs.error?.message ?? null, + stdout: runtimeLogs.stdout, + stderr: runtimeLogs.stderr, + }); +} + export async function cleanupGpu( host: HostCliClient, lifecycle: LifecyclePhaseFixture, sandbox: SandboxClient, environment: NodeJS.ProcessEnv = env(), ): Promise { - await preCleanBestEffort("destroy GPU sandbox", () => - host.command("node", [CLI, SANDBOX_NAME, "destroy", "--yes"], { - artifactName: "cleanup-destroy-gpu", - env: environment, - timeoutMs: 120_000, - }), - ); + // Destroying an absent sandbox starts a gateway, which can leave port 8080 occupied + // before the next scenario creates its own private HOME. + if (getSandboxAcrossGatewayRoots(SANDBOX_NAME, environment.HOME ?? os.homedir())) { + await preCleanBestEffort("destroy GPU sandbox", () => + host.command("node", [CLI, SANDBOX_NAME, "destroy", "--yes"], { + artifactName: "cleanup-destroy-gpu", + env: environment, + timeoutMs: 120_000, + }), + ); + } await preCleanBestEffort("delete OpenShell sandbox", () => sandbox.cleanupSandbox(SANDBOX_NAME, { artifactName: "cleanup-delete-gpu", diff --git a/test/e2e/live/gpu-e2e.test.ts b/test/e2e/live/gpu-e2e.test.ts index 0c0b895599d..293cb47584b 100644 --- a/test/e2e/live/gpu-e2e.test.ts +++ b/test/e2e/live/gpu-e2e.test.ts @@ -8,6 +8,7 @@ import { EXPORTED_VLLM_PROFILE_ID } from "../../../src/lib/config/model.ts"; import type { V1Alpha1OllamaProxyService } from "../../../src/lib/config/v1alpha1-export.ts"; import { cleanupLocalModelRuntimes } from "../../../src/lib/inference/local-model-profile/cleanup.ts"; import { HOST_LOCAL_VLLM_CONTAINER_NAME } from "../../../src/lib/inference/serving/vllm-host-local-lifecycle.ts"; +import { NATIVE_LOCAL_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-local/agent-config.ts"; import { loadManagedVllmApiKey } from "../../../src/lib/inference/vllm-api-key.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; @@ -84,7 +85,7 @@ test( "install Ollama and GPU sandbox", "validate GPU runtime status", "validate Ollama proxy credential boundary", - "run sandbox inference.local chat", + "run sandbox native local chat", "restart Ollama and recover agent inference", ], }, @@ -93,7 +94,7 @@ test( await artifacts.target.declare({ id: "gpu-e2e", boundary: - "GPU host + install.sh Ollama provider + OpenShell sandbox + auth proxy + inference.local", + "GPU host + install.sh Ollama provider + OpenShell sandbox + auth proxy + native provider", credentialBoundary: "The proxy token remains host/OpenShell-owned and is absent from sandbox env.", remoteInstallerBoundary: @@ -191,13 +192,6 @@ test( expect(retainedSandboxContainer.State).toBe("running"); expect(retainedSandboxContainer.Status).toMatch(/\(healthy\)/i); - const route = await sandbox.openshell(["inference", "get"], { - artifactName: "openshell-inference-route", - env: env(), - timeoutMs: 30_000, - }); - expect(resultText(route)).toMatch(/ollama/i); - progress.phase("validate Ollama proxy credential boundary"); const tokenRecord = readTokenFileChecked(ollamaProxyTokenFile()); expect(tokenRecord.mode).toBe("600"); @@ -238,12 +232,12 @@ test( "OpenShell owns proxy authentication; the host proxy token must not enter sandbox env", ).toBe(""); - progress.phase("run sandbox inference.local chat"); + progress.phase("run sandbox native local chat"); const model = await detectOllamaModel(host); const chat = await sandbox.execShell( SANDBOX_NAME, trustedSandboxShellScript( - `curl -sS --max-time 120 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data '${JSON.stringify( + `${NATIVE_LOCAL_AUTH_HEADER_SCRIPT}; curl -sS --max-time 120 http://host.openshell.internal:${PROXY_PORT}/v1/chat/completions -H "$AUTH_HEADER" -H 'Content-Type: application/json' --data '${JSON.stringify( { model, messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], @@ -255,8 +249,9 @@ test( }, )}'`, ), - { artifactName: "sandbox-inference-local-chat", env: env(), timeoutMs: 150_000 }, + { artifactName: "sandbox-native-local-chat", env: env(), timeoutMs: 150_000 }, ); + expect(chat.exitCode, resultText(chat)).toBe(0); expect(chatContent(chat.stdout)).toMatch(/pong/i); const readySandbox = await sandbox.openshell(["sandbox", "get", SANDBOX_NAME], { @@ -432,6 +427,18 @@ test( credentialBoundary: "The existing proxy owner authenticates observation; exported inference providers omit credentials and internal endpoints.", }); + await host.command("lsof", ["-nP", "-iTCP:8080", "-sTCP:LISTEN"], { + artifactName: "export-gateway-listener-before-preclean", + env: env(), + timeoutMs: 10_000, + }); + // Pre-clean may start a gateway; do it before creating the fresh private HOME. + await cleanupGpu(host, lifecycle, sandbox, env()); + await host.command("lsof", ["-nP", "-iTCP:8080", "-sTCP:LISTEN"], { + artifactName: "export-gateway-listener-after-preclean", + env: env(), + timeoutMs: 10_000, + }); // The SDK rejects gateway state below a world-writable ancestor such as /tmp. const directory = createGpuPrivateHome(os.homedir()); const exportEnv = env({ @@ -454,7 +461,6 @@ test( expect(result.exitCode, resultText(result)).toBe(0); }); cleanup.trackDisposable("stop the fixture-owned Ollama daemon", () => daemonOwner?.terminate()); - await cleanupGpu(host, lifecycle, sandbox, exportEnv); await runtimeProvider.requireAvailable({ artifactName: "export-runtime-info", scenarioLabel: "attached Ollama export", diff --git a/test/e2e/live/inference-routing-helpers.ts b/test/e2e/live/inference-routing-helpers.ts index 59b42308b89..e46ccfec8c6 100644 --- a/test/e2e/live/inference-routing-helpers.ts +++ b/test/e2e/live/inference-routing-helpers.ts @@ -205,27 +205,10 @@ async function cleanupSandbox( const cleanupEvidence: string[] = []; let deletionConfirmedAbsent = false; - try { - const destroy = await host.command( - process.execPath, - [CLI_ENTRYPOINT, sandboxName, "destroy", "--yes"], - { - artifactName: `cleanup-nemoclaw-destroy-${sandboxName}`, - env: buildAvailabilityProbeEnv(), - timeoutMs: 120_000, - }, - ); - cleanupEvidence.push(probeSummary("nemoclaw destroy", destroy)); - } catch (error) { - cleanupEvidence.push( - `nemoclaw destroy threw: ${error instanceof Error ? error.message : String(error)}`, - ); - } - try { const deletion = await sandbox.openshell(["sandbox", "delete", sandboxName], { artifactName: `cleanup-openshell-sandbox-delete-${sandboxName}`, - env: buildAvailabilityProbeEnv(), + env: rawOpenShellEnv(), timeoutMs: 60_000, }); cleanupEvidence.push(probeSummary("openshell sandbox delete", deletion)); @@ -238,18 +221,61 @@ async function cleanupSandbox( ); } - clearOnboardState(); - if (deletionConfirmedAbsent) return; + // A failed Deep Agents Code onboarding may never create the sandbox. Its + // explicit not-found result is sufficient absence evidence; otherwise retain + // the public destroy proof that retires provider ownership after success. + if (deletionConfirmedAbsent) { + clearOnboardState(); + return; + } - const inventory = await sandbox.list({ - artifactName: `cleanup-openshell-sandbox-list-${sandboxName}`, - env: buildAvailabilityProbeEnv(), - timeoutMs: 30_000, - }); - cleanupEvidence.push(probeSummary("openshell sandbox list", inventory)); - if (inventory.exitCode !== 0 || outputContainsSandbox(inventory, sandboxName)) { + // Observe absence while the gateway is still running. Public destroy may + // stop the last gateway after reconciling its registry and provider ownership. + let absenceVerified = false; + try { + const listing = await sandbox.list({ + artifactName: `cleanup-openshell-sandbox-list-${sandboxName}`, + env: rawOpenShellEnv(), + timeoutMs: 30_000, + }); + cleanupEvidence.push(probeSummary("openshell sandbox list", listing)); + absenceVerified = + listing.exitCode === 0 && + !listing.timedOut && + listing.signal === null && + !outputContainsSandbox(listing, sandboxName); + } catch (error) { + cleanupEvidence.push( + `openshell sandbox list threw: ${error instanceof Error ? error.message : String(error)}`, + ); + } + + let destroySucceeded = false; + try { + const destroy = await host.command( + process.execPath, + [CLI_ENTRYPOINT, sandboxName, "destroy", "--yes"], + { + artifactName: `cleanup-nemoclaw-destroy-${sandboxName}`, + env: rawOpenShellEnv(), + timeoutMs: 120_000, + }, + ); + cleanupEvidence.push(probeSummary("nemoclaw destroy", destroy)); + destroySucceeded = destroy.exitCode === 0 && !destroy.timedOut && destroy.signal === null; + if (destroy.timedOut) cleanupEvidence.push("nemoclaw destroy timed out"); + if (destroy.signal !== null) cleanupEvidence.push(`nemoclaw destroy signal=${destroy.signal}`); + } catch (error) { + cleanupEvidence.push( + `nemoclaw destroy threw: ${error instanceof Error ? error.message : String(error)}`, + ); + } finally { + clearOnboardState(); + } + if (!absenceVerified || !destroySucceeded) { + const reason = absenceVerified ? "public destroy was not verified" : "absence was not verified"; throw new Error( - `sandbox '${sandboxName}' absence is unverified after strict cleanup\n${cleanupEvidence.join("\n")}`, + `sandbox '${sandboxName}' ${reason} after strict cleanup\n${cleanupEvidence.join("\n")}`, ); } } @@ -503,3 +529,17 @@ export { skipLive, TRANSPORT_CLASSIFICATION_PATTERN, }; + +export function providerPolicyRestoreArgs(value: unknown): string[] | undefined { + return new Map([ + ["", ["settings", "delete", "--global", "--key", "providers_v2_enabled", "--yes"]], + [ + "false", + ["settings", "set", "--global", "--key", "providers_v2_enabled", "--value", "false", "--yes"], + ], + [ + "true", + ["settings", "set", "--global", "--key", "providers_v2_enabled", "--value", "true", "--yes"], + ], + ]).get(typeof value === "string" ? value : value === undefined ? "" : ""); +} diff --git a/test/e2e/live/inference-routing.test.ts b/test/e2e/live/inference-routing.test.ts index 381a9969810..547f751685c 100644 --- a/test/e2e/live/inference-routing.test.ts +++ b/test/e2e/live/inference-routing.test.ts @@ -35,6 +35,7 @@ import { hasRawNodeStackTrace, inferenceSandboxName, onboardSandbox, + providerPolicyRestoreArgs, redactedResultText, requireLivePrerequisites, runNemoclawCli, @@ -271,16 +272,11 @@ async function runRuntimeIdentityE2EScenario( cleanupSandbox(host, sandbox, sandboxName, { strict: true }), ); await cleanupSandbox(host, sandbox, sandboxName); - const inference = await startFakeOpenAiCompatibleServer({ + const cloudflaredBin = await resolveVerifiedCloudflaredBinary(cleanup, host); + const inference = await startFakeHttpsCompatibleServer({ apiKey: inferenceKey, chatContent: "PONG", - host: "0.0.0.0", model, - port: 8000, - progress, - publicHost: "localhost", - requireAuth: true, - requireAuthModels: true, }); cleanup.add("close runtime identity inference prerequisite", async () => { try { @@ -289,13 +285,24 @@ async function runRuntimeIdentityE2EScenario( await inference.close(); } }); + // Arbitrary loopback ports are intentionally not rewritten by onboarding. + // Use a public prerequisite route while preserving the shared inference path. + const inferenceTunnel = await startPublicMcpHttpsTunnel({ + cloudflaredBin, + cleanup, + label: "runtime identity inference prerequisite", + progress, + readinessPath: "/v1/models", + readinessStatus: 401, + server: inference, + }); progress.phase("onboard a real OpenShell sandbox"); const onboard = await onboardSandbox( artifacts, sandboxName, { COMPATIBLE_API_KEY: inferenceKey, - NEMOCLAW_ENDPOINT_URL: inference.baseUrl, + NEMOCLAW_ENDPOINT_URL: `${inferenceTunnel.origin}/v1`, NEMOCLAW_MODEL: model, NEMOCLAW_PREFERRED_API: "openai-completions", NEMOCLAW_PROVIDER: "custom", @@ -328,17 +335,7 @@ async function runRuntimeIdentityE2EScenario( settings?: Record; }; const priorProvidersV2Setting = settingsDocument.settings?.providers_v2_enabled; - const restoreSettingArgs = new Map([ - ["", ["settings", "delete", "--global", "--key", "providers_v2_enabled", "--yes"]], - [ - "false", - ["settings", "set", "--global", "--key", "providers_v2_enabled", "--value", "false", "--yes"], - ], - [ - "true", - ["settings", "set", "--global", "--key", "providers_v2_enabled", "--value", "true", "--yes"], - ], - ]).get(priorProvidersV2Setting ?? ""); + const restoreSettingArgs = providerPolicyRestoreArgs(priorProvidersV2Setting); expect(restoreSettingArgs).toBeDefined(); cleanup.add("restore OpenShell provider-derived policy setting", async () => { const restored = await sandbox.openshell(restoreSettingArgs!, { @@ -379,7 +376,6 @@ async function runRuntimeIdentityE2EScenario( await oauth.close(); } }); - const cloudflaredBin = await resolveVerifiedCloudflaredBinary(cleanup, host); const tunnel = await startPublicMcpHttpsTunnel({ cloudflaredBin, cleanup, @@ -717,100 +713,6 @@ test }, ); -test( - "TC-INF-09 local compatible endpoint routes through inference.local (#5744)", - { - timeout: ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS, - meta: { - e2ePhases: [ - "confirm compatible-endpoint prerequisites", - "start the local compatible endpoint", - "onboard to the compatible endpoint", - "request sandbox chat through inference.local", - ], - }, - }, - async ({ artifacts, cleanup, host, progress, runtimeProvider, sandbox }) => { - const model = "nemoclaw-e2e-compatible"; - const apiKey = "sk-compatible-TEST-NOT-A-REAL-VALUE"; - await requireLivePrerequisites(host, runtimeProvider); - const sandboxName = inferenceSandboxName("e2e-compat"); - cleanup.add( - `best-effort inference-routing compatible-endpoint cleanup for ${sandboxName}`, - () => cleanupSandbox(host, sandbox, sandboxName), - ); - cleanup.add(`strict inference-routing compatible-endpoint cleanup for ${sandboxName}`, () => - cleanupSandbox(host, sandbox, sandboxName, { strict: true }), - ); - await cleanupSandbox(host, sandbox, sandboxName); - progress.phase("start the local compatible endpoint"); - const fake = await startFakeOpenAiCompatibleServer({ - apiKey, - chatContent: "PONG", - host: "0.0.0.0", - model, - port: 8000, - progress, - publicHost: "localhost", - requireAuth: true, - requireAuthModels: true, - }); - cleanup.add("close inference-routing compatible endpoint", async () => { - try { - await artifacts.writeJson("tc-inf-09-compatible-endpoint-requests.json", fake.requests()); - } finally { - await fake.close(); - } - }); - await artifacts.target.declare({ - id: "inference-routing-compatible-endpoint", - contract: [ - "a custom OpenAI-compatible endpoint onboards", - "sandbox inference.local routes chat to compatible endpoint", - ], - endpointUrl: fake.baseUrl, - model, - }); - progress.phase("onboard to the compatible endpoint"); - const onboard = await onboardSandbox( - artifacts, - sandboxName, - { - COMPATIBLE_API_KEY: apiKey, - NEMOCLAW_ENDPOINT_URL: fake.baseUrl, - NEMOCLAW_MODEL: model, - NEMOCLAW_PREFERRED_API: "openai-completions", - NEMOCLAW_PROVIDER: "custom", - }, - [apiKey], - "tc-inf-09-onboard-compatible-endpoint", - progress, - ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS, - ); - expectOnboardSuccess(onboard, "TC-INF-09 compatible-endpoint onboard"); - progress.phase("request sandbox chat through inference.local"); - const sandboxRequestOffset = fake.requests().length; - await expectOpenAiChatThroughSandbox( - sandbox, - sandboxName, - model, - [apiKey], - "compatible-endpoint-inference-local-chat", - ); - expect( - fake - .requests() - .slice(sandboxRequestOffset) - .some( - (request) => - request.auth === "ok" && - request.method === "POST" && - request.path === "/v1/chat/completions", - ), - ).toBe(true); - }, -); - test( "TC-INF-11 DNS-backed HTTPS custom endpoint routes through the local pinning adapter (#6141)", { @@ -880,24 +782,30 @@ test( endpointUrl, model, }); - // Onboarding's own SSRF preflight (assertEndpointResolvesPublic) only - // rejects private/internal addresses; it does not fail closed on - // DNS-backed HTTPS the way the HTTPS Pin Runtime adapter's call site does, - // and onboarding never wires that adapter itself (only - // inference-set-route-containment.ts's normalizeCustomEndpointUrl does, on - // the `inference set --endpoint-url` path). Onboard with a disposable - // plain-HTTP placeholder endpoint first -- the same shape TC-INF-09 already - // onboards successfully with -- then switch to the DNS-backed HTTPS - // endpoint through `inference set --endpoint-url`, the actual #6141 call - // site this test exercises. - // Advertise localhost so onboarding exercises its host-bridge rewrite, but - // listen beyond host loopback so the resulting sandbox route can reach it. + // A distinct public onboarding endpoint keeps inference set on the pinning + // path: reusing the exact onboarded URL intentionally bypasses that adapter. + const onboarding = await startFakeHttpsCompatibleServer({ + apiKey, + chatContent: "placeholder", + model, + }); + cleanup.add("close https-pin onboarding endpoint", () => onboarding.close()); + const onboardingTunnel = await startPublicMcpHttpsTunnel({ + cloudflaredBin, + cleanup, + label: "https-pin onboarding prerequisite", + progress, + readinessPath: "/v1/models", + readinessStatus: 401, + server: onboarding, + }); + // Keep a separate private target to witness that redirects are never followed. const placeholder = await startFakeOpenAiCompatibleServer({ apiKey, chatContent: "placeholder", host: "0.0.0.0", model, - port: 8000, + port: 0, progress, publicHost: "localhost", requireAuth: true, @@ -910,7 +818,7 @@ test( sandboxName, { COMPATIBLE_API_KEY: apiKey, - NEMOCLAW_ENDPOINT_URL: placeholder.baseUrl, + NEMOCLAW_ENDPOINT_URL: `${onboardingTunnel.origin}/v1`, NEMOCLAW_MODEL: model, NEMOCLAW_PREFERRED_API: "openai-completions", NEMOCLAW_PROVIDER: "custom", diff --git a/test/e2e/live/llama-cpp-generic-gpu.test.ts b/test/e2e/live/llama-cpp-generic-gpu.test.ts index 51980d766e1..9d7dad83678 100644 --- a/test/e2e/live/llama-cpp-generic-gpu.test.ts +++ b/test/e2e/live/llama-cpp-generic-gpu.test.ts @@ -22,7 +22,11 @@ import { resultText } from "../fixtures/clients/index.ts"; import { trustedSandboxShellScript, validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; -import { assertAgentExecutionSucceeded, hasExactReadyPhase } from "./gpu-e2e-helpers.ts"; +import { + assertAgentExecutionSucceeded, + captureManagedRuntimeLogArtifact, + hasExactReadyPhase, +} from "./gpu-e2e-helpers.ts"; import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; const TIMEOUT_MS = 110 * 60_000; @@ -172,20 +176,13 @@ test( const runtimeId = receipt.runtime.runtimeId; const runtimeOperation = runtimeProvider.hostLocalInference.createOperation({ env: env() }); runtimeOperation.assertAuthority(); - const captureManagedRuntimeLogs = async (phase: "setup" | "post-agent") => { - const runtimeLogs = runtimeOperation.engine.capture( - ["container", "logs", "--tail", "20000", runtimeId], - 30_000, + const captureManagedRuntimeLogs = (phase: "setup" | "pre-approval-agent" | "post-agent") => + captureManagedRuntimeLogArtifact(artifacts, phase, receipt.providerId, runtimeId, () => + runtimeOperation.engine.capture( + ["container", "logs", "--tail", "20000", runtimeId], + 30_000, + ), ); - await artifacts.writeJson(`managed-runtime-logs-${phase}.json`, { - providerId: receipt.providerId, - runtimeId, - status: runtimeLogs.status, - error: runtimeLogs.error?.message ?? null, - stdout: runtimeLogs.stdout, - stderr: runtimeLogs.stderr, - }); - }; await captureManagedRuntimeLogs("setup"); const runtimeInspection = runtimeOperation.engine.capture( ["container", "inspect", receipt.runtime.runtimeId], @@ -345,6 +342,7 @@ NODE`), env: env(), timeoutMs: 12 * 60_000, }); + await captureManagedRuntimeLogs("pre-approval-agent"); expect(preApprovalAgent.exitCode, resultText(preApprovalAgent)).toBe(0); assertAgentExecutionSucceeded( preApprovalAgent.stdout, diff --git a/test/e2e/live/managed-image-activation-e2e-helpers.ts b/test/e2e/live/managed-image-activation-e2e-helpers.ts index 19071e0fae9..a8405d57270 100644 --- a/test/e2e/live/managed-image-activation-e2e-helpers.ts +++ b/test/e2e/live/managed-image-activation-e2e-helpers.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { resolveSandboxHealthProbeUrl } from "../../../src/lib/actions/sandbox/forward-recovery.ts"; import { shellQuote } from "../../../src/lib/core/shell-quote.ts"; +import { normalizeNativeLocalProviderAttachment } from "../../../src/lib/inference/native-local/contract.ts"; import { resolveGatewayLogPathForPort } from "../../../src/lib/onboard/gateway/state-dir.ts"; import { type ManagedImagePlatform, @@ -40,7 +41,10 @@ import { countLocalImageBuildCommands, createContainerBuildGuard, } from "../fixtures/docker-build-guard.ts"; -import { startFakeOpenAiCompatibleServer } from "../fixtures/fake-openai-compatible.ts"; +import { + startFakeOpenAiCompatibleServer, + type FakeOpenAiCompatibleRequest, +} from "../fixtures/fake-openai-compatible.ts"; import { captureIssue4462FailureDiagnostics } from "../fixtures/issue-4462-diagnostics.ts"; import { initializeGatewayForCleanup } from "../fixtures/gateway-runtime-start.ts"; import type { LifecyclePhaseFixture } from "../fixtures/phases/lifecycle.ts"; @@ -199,25 +203,33 @@ function exactCatalog( return contracts; } -function commandEnv( - guard: ContainerBuildGuard, +export function managedActivationCommandEnv( + guard: Pick, catalogPath: string, endpointUrl: string, + credentialless = false, ): NodeJS.ProcessEnv { const gatewayRuntime = process.env.NEMOCLAW_GATEWAY_RUNTIME === "podman" ? "podman" : "docker"; return { ...guard.env, - COMPATIBLE_API_KEY: API_KEY, + COMPATIBLE_API_KEY: credentialless ? undefined : API_KEY, NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", NEMOCLAW_COMPAT_MODEL: MODEL, - NEMOCLAW_ENDPOINT_URL: endpointUrl, + NEMOCLAW_ENDPOINT_URL: credentialless ? undefined : endpointUrl, NEMOCLAW_IGNORE_RUNTIME_RESOURCES: "1", NEMOCLAW_GATEWAY_RUNTIME: gatewayRuntime, NEMOCLAW_MANAGED_ACTIVATION_CATALOG: catalogPath, NEMOCLAW_MODEL: MODEL, NEMOCLAW_NON_INTERACTIVE: "1", NEMOCLAW_PREFERRED_API: "openai-completions", - NEMOCLAW_PROVIDER: "custom", + NEMOCLAW_PROVIDER: credentialless ? "vllm" : "custom", + ...(credentialless + ? { + NEMOCLAW_VLLM_PORT: new URL(endpointUrl).port, + NEMOCLAW_LOCAL_INFERENCE_SANDBOX_HOST_URL: undefined, + NEMOCLAW_VLLM_LOCAL_TOKEN: undefined, + } + : {}), NEMOCLAW_RECREATE_SANDBOX: "1", OPENSHELL_DRIVERS: gatewayRuntime, OPENSHELL_GATEWAY: GATEWAY, @@ -279,7 +291,11 @@ exec ${command.map((argument) => shellQuote(argument)).join(" ")} interface ExternalImageRegistryDocument { sandboxes?: Record< string, - { toolDisclosure?: "progressive" | "direct"; workload?: Record } + { + toolDisclosure?: "progressive" | "direct"; + workload?: Record; + nativeLocalProviderAttachment?: unknown; + } >; } @@ -395,13 +411,16 @@ export function externalImageActivationMatches(input: { ); } -async function runAgentTurn( +export async function runManagedActivationAgentTurn( sandbox: SandboxClient, agent: ShippedManagedImageAgent, sandboxName: string, phase: "before" | "boundary" | "after", env: NodeJS.ProcessEnv, + artifactPrefix: string = agent, + observeRequests?: () => readonly FakeOpenAiCompatibleRequest[], ): Promise { + const requestStart = observeRequests?.().length ?? 0; const command = agentTurnCommand(agent, `managed-${agent}-${phase}-${Date.now()}`); const postRestartScript = managedActivationPostRestartAgentTurnScript( agent, @@ -412,7 +431,7 @@ async function runAgentTurn( : undefined, ); const options = { - artifactName: `${agent}-agent-turn-${phase}-restart`, + artifactName: `${artifactPrefix}-agent-turn-${phase}-restart`, env, redactionValues: [API_KEY], timeoutMs: @@ -425,6 +444,18 @@ async function runAgentTurn( expect(result.exitCode === 0 && /\bPONG\b/iu.test(resultText(result)), resultText(result)).toBe( true, ); + observeRequests && + expect( + observeRequests() + .slice(requestStart) + .some( + (request) => + request.method === "POST" && + request.path === "/v1/chat/completions" && + request.model === MODEL, + ), + `${artifactPrefix} ${phase} restart must send a new completion to its selected endpoint and model`, + ).toBe(true); } export function managedOpenClawSubagentCommand(sessionId: string): string[] { @@ -561,7 +592,7 @@ async function proveHermesRestartSecretBoundary( !output.includes(HERMES_BOUNDARY_SENTINEL), output, ).toBe(true); - await runAgentTurn(sandbox, "hermes", sandboxName, "boundary", env); + await runManagedActivationAgentTurn(sandbox, "hermes", sandboxName, "boundary", env); } export async function preclean( @@ -699,7 +730,11 @@ async function verifyExactCleanup( expect(containers.stdout.trim(), resultText(containers)).toBe(""); } -function enterOnboardPhase(progress: TestProgress, agent: ShippedManagedImageAgent): void { +function enterOnboardPhase( + progress: TestProgress, + agent: ShippedManagedImageAgent, + credentialless = false, +): void { switch (agent) { case "openclaw": progress.phase("onboard and exercise OpenClaw"); @@ -708,7 +743,11 @@ function enterOnboardPhase(progress: TestProgress, agent: ShippedManagedImageAge progress.phase("onboard and exercise Hermes"); return; case "langchain-deepagents-code": - progress.phase("onboard and exercise Deep Agents Code"); + if (credentialless) { + progress.phase("qualify credentialless Deep Agents Code lifecycle"); + } else { + progress.phase("qualify authenticated Deep Agents Code lifecycle"); + } return; } } @@ -722,7 +761,7 @@ function enterPublicLifecyclePhase(progress: TestProgress, agent: ShippedManaged progress.phase("stop and start Hermes through public NemoClaw lifecycle"); return; case "langchain-deepagents-code": - progress.phase("stop and start Deep Agents Code through public NemoClaw lifecycle"); + progress.event("stop and start Deep Agents Code through public NemoClaw lifecycle"); return; } } @@ -736,7 +775,7 @@ function enterCleanupPhase(progress: TestProgress, agent: ShippedManagedImageAge progress.phase("destroy and verify Hermes cleanup"); return; case "langchain-deepagents-code": - progress.phase("destroy and verify Deep Agents Code cleanup"); + progress.event("destroy and verify Deep Agents Code cleanup"); return; } } @@ -869,21 +908,24 @@ export async function qualifyAgent( endpointUrl: string, agent: ShippedManagedImageAgent, contract: ManagedImageContractV1, + credentialless = false, + observeRequests?: () => readonly FakeOpenAiCompatibleRequest[], ): Promise { const { artifacts, cleanup, host, lifecycle, progress, sandbox } = fixtures; - const sandboxName = SANDBOX_NAMES[agent]; - const env = commandEnv(guard, catalogPath, endpointUrl); + const sandboxName = `${SANDBOX_NAMES[agent]}${credentialless ? "-noauth" : ""}`; + const artifactPrefix = `${agent}${credentialless ? "-credentialless" : ""}`; + const env = managedActivationCommandEnv(guard, catalogPath, endpointUrl, credentialless); cleanup.trackDisposable(`delete OpenShell sandbox ${sandboxName}`, () => sandbox.cleanupSandbox(sandboxName, { env, timeoutMs: 60_000 }), ); cleanup.trackSandbox(host, sandboxName, { env, timeoutMs: 3 * 60_000 }); await preclean(host, lifecycle, sandbox, sandboxName, env); - enterOnboardPhase(progress, agent); + enterOnboardPhase(progress, agent, credentialless); const onboard = await host.nemoclaw( managedActivationOnboardArgs(catalogPath, agent, sandboxName), { - artifactName: `managed-activation-onboard-${agent}`, + artifactName: `managed-activation-onboard-${artifactPrefix}`, env, redactionValues: [API_KEY], timeoutMs: ONBOARD_TIMEOUT_MS, @@ -897,13 +939,21 @@ export async function qualifyAgent( if (agent === "openclaw") { await approveOpenClawAdminScope(host, sandbox, sandboxName, env, [API_KEY]); } - await runAgentTurn(sandbox, agent, sandboxName, "before", env); + await runManagedActivationAgentTurn( + sandbox, + agent, + sandboxName, + "before", + env, + artifactPrefix, + observeRequests, + ); if (agent === "openclaw") await runOpenClawSubagentTurn(sandbox, sandboxName, env); if (agent === "hermes") { progress.phase("prove Hermes secret-boundary refusal before native restart"); await proveHermesRestartSecretBoundary(host, sandbox, sandboxName, env); } - const marker = `managed-activation-${agent}-${Date.now()}`; + const marker = `managed-activation-${artifactPrefix}-${Date.now()}`; await sandbox.execShell( sandboxName, trustedSandboxShellScript( @@ -916,7 +966,7 @@ export async function qualifyAgent( .join("\n"), ), { - artifactName: `${agent}-write-durable-marker`, + artifactName: `${artifactPrefix}-write-durable-marker`, env, timeoutMs: 30_000, }, @@ -924,7 +974,7 @@ export async function qualifyAgent( enterPublicLifecyclePhase(progress, agent); const stop = await host.nemoclaw([sandboxName, "stop"], { - artifactName: `${agent}-public-stop`, + artifactName: `${artifactPrefix}-public-stop`, env, redactionValues: [API_KEY], timeoutMs: 120_000, @@ -933,7 +983,7 @@ export async function qualifyAgent( await collectOnboardFailureRuntimeDiagnostics(artifacts, host, agent, sandboxName, env); } const start = await host.nemoclaw([sandboxName, "start"], { - artifactName: `${agent}-public-start`, + artifactName: `${artifactPrefix}-public-start`, env, redactionValues: [API_KEY], timeoutMs: 10 * 60_000, @@ -946,7 +996,7 @@ export async function qualifyAgent( `${resultText(stop)}\n${resultText(start)}`, ).toBe(true); await lifecycle.waitForSandboxReadyAfterGatewayRestart(sandboxName, { - artifactNamePrefix: `${agent}-post-public-start-ready`, + artifactNamePrefix: `${artifactPrefix}-post-public-start-ready`, env, }); expectManagedReceipt(sandboxName, contract); @@ -963,7 +1013,7 @@ export async function qualifyAgent( .join("\n"), ), { - artifactName: `${agent}-read-durable-marker-after-public-lifecycle`, + artifactName: `${artifactPrefix}-read-durable-marker-after-public-lifecycle`, env, timeoutMs: 30_000, }, @@ -972,11 +1022,41 @@ export async function qualifyAgent( readMarker.exitCode === 0 && readMarker.stdout.trim() === marker, resultText(readMarker), ).toBe(true); - await runAgentTurn(sandbox, agent, sandboxName, "after", env); + await runManagedActivationAgentTurn( + sandbox, + agent, + sandboxName, + "after", + env, + artifactPrefix, + observeRequests, + ); + if (agent === "openclaw" || agent === "langchain-deepagents-code") { + const receipt = normalizeNativeLocalProviderAttachment( + registryDocument().sandboxes?.[sandboxName]?.nativeLocalProviderAttachment, + ); + const attachments = await sandbox.openshell( + ["sandbox", "provider", "list", "-g", GATEWAY, sandboxName], + { + artifactName: `managed-activation-native-provider-attachment-${artifactPrefix}`, + env, + timeoutMs: 60_000, + }, + ); + expect( + receipt?.gatewayName === GATEWAY && + receipt.sandboxName === sandboxName && + receipt.endpointUrl === endpointUrl && + receipt.authMode === (credentialless ? "sentinel" : "authenticated") && + attachments.exitCode === 0 && + attachments.stdout.split(/\s+/u).includes(receipt.providerName), + `receipt=${JSON.stringify(receipt)} attachments=${resultText(attachments)}`, + ).toBe(true); + } enterCleanupPhase(progress, agent); await sandbox.cleanupSandbox(sandboxName, { - artifactName: `managed-activation-openshell-delete-${agent}`, + artifactName: `managed-activation-openshell-delete-${artifactPrefix}`, env, timeoutMs: 120_000, }); @@ -1003,7 +1083,7 @@ async function qualifyExternalImage( }> { const { artifacts, cleanup, host, lifecycle, sandbox } = fixtures; const sandboxName = EXTERNAL_IMAGE_SANDBOX_NAMES[agent]; - const env = commandEnv(guard, catalogPath, endpointUrl); + const env = managedActivationCommandEnv(guard, catalogPath, endpointUrl); cleanup.trackDisposable(`delete external-image sandbox ${sandboxName}`, () => sandbox.cleanupSandbox(sandboxName, { env, timeoutMs: 60_000 }), ); @@ -1030,7 +1110,7 @@ async function qualifyExternalImage( artifactNamePrefix: `external-image-${agent}-ready`, env, }); - await runAgentTurn(sandbox, agent, sandboxName, "before", env); + await runManagedActivationAgentTurn(sandbox, agent, sandboxName, "before", env); const beforeInspection = await inspectRuntimeImageId( host, @@ -1106,7 +1186,7 @@ async function qualifyExternalImage( // before exercising the same privileged CLI boundary again. await approveOpenClawAdminScope(host, sandbox, sandboxName, env, [API_KEY]); } - await runAgentTurn(sandbox, agent, sandboxName, "after", env); + await runManagedActivationAgentTurn(sandbox, agent, sandboxName, "after", env); rebuilt = true; } registryEntry = registryDocument().sandboxes?.[sandboxName]; @@ -1168,17 +1248,12 @@ export async function qualifyManagedImageActivation(fixtures: RuntimeFixtures): guard.dispose, ); cleanup.trackGateway(host, GATEWAY, { env: guard.env, timeoutMs: 60_000 }); - const runtimeInfo = await host.command(containerEngine, ["info"], { - artifactName: `managed-activation-${containerEngine}-info`, - env: guard.env, - timeoutMs: 30_000, - }); - expect(runtimeInfo.exitCode, resultText(runtimeInfo)).toBe(0); const inference = await startFakeOpenAiCompatibleServer({ apiKey: API_KEY, chatContent: "PONG", host: "0.0.0.0", model: MODEL, + port: 8000, progress, publicHost: "host.openshell.internal", requireAuth: true, @@ -1206,9 +1281,40 @@ export async function qualifyManagedImageActivation(fixtures: RuntimeFixtures): inference.baseUrl, agent, contracts.get(agent)!, + false, + inference.requests, ); } + // Exercise the existing bearerless vLLM selection through DCode's real client. + // An ephemeral port keeps this fixture separate from the authenticated backend. + const credentiallessInference = await startFakeOpenAiCompatibleServer({ + chatContent: "PONG", + host: "0.0.0.0", + model: MODEL, + progress, + publicHost: "host.openshell.internal", + requireAuth: false, + requireAuthModels: false, + }); + cleanup.trackDisposable("close credentialless DCode inference responder", async () => { + await artifacts.writeJson( + "dcode-credentialless-inference-requests.json", + credentiallessInference.requests(), + ); + await credentiallessInference.close(); + }); + await qualifyAgent( + fixtures, + guard, + catalogPath, + credentiallessInference.baseUrl, + "langchain-deepagents-code", + contracts.get("langchain-deepagents-code")!, + true, + credentiallessInference.requests, + ); + progress.phase( "prove buildless external-image onboarding, drift rejection, rebuild, and retention", ); @@ -1239,8 +1345,7 @@ export async function qualifyManagedImageActivation(fixtures: RuntimeFixtures): .requests() .filter((request) => request.method === "POST" && request.path === "/v1/chat/completions"); expect( - chatRequests.length >= SHIPPED_MANAGED_IMAGE_AGENTS.length * 2 && - chatRequests.every((request) => request.auth === "ok" && request.model === MODEL) && + chatRequests.every((request) => request.auth === "ok" && request.model === MODEL) && chatRequests.some((request) => request.requestCanaryPresent === true) && chatRequests.some((request) => request.toolResultPresent === true) && externalImages.every((image) => image.verified), diff --git a/test/e2e/live/managed-image-activation-e2e.test.ts b/test/e2e/live/managed-image-activation-e2e.test.ts index d7189b54547..877c7053a7b 100644 --- a/test/e2e/live/managed-image-activation-e2e.test.ts +++ b/test/e2e/live/managed-image-activation-e2e.test.ts @@ -20,9 +20,8 @@ test( "prove Hermes secret-boundary refusal before native restart", "stop and start Hermes through public NemoClaw lifecycle", "destroy and verify Hermes cleanup", - "onboard and exercise Deep Agents Code", - "stop and start Deep Agents Code through public NemoClaw lifecycle", - "destroy and verify Deep Agents Code cleanup", + "qualify authenticated Deep Agents Code lifecycle", + "qualify credentialless Deep Agents Code lifecycle", "prove buildless external-image onboarding, drift rejection, rebuild, and retention", ], }, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 21256f07a43..f8703caddf2 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -102,6 +102,8 @@ "test/e2e/live/openclaw-admin-scope.ts" ], "fast": [ + "src/lib/inference/native-local.test.ts", + "src/lib/onboard/managed-workload/native-local-startup-route.test.ts", "src/lib/onboard/command.test.ts", "src/lib/onboard/sandbox-workload-preparation.test.ts", "test/e2e/support/managed-image-activation-diagnostics.test.ts", @@ -197,6 +199,7 @@ "test/e2e/support/onboard-timeout-contract.test.ts", "test/onboarding/onboard-inference-gateway-scope.test.ts", "test/e2e/support/managed-image-activation-diagnostics.test.ts", + "test/e2e/support/inference-routing-cleanup.test.ts", "test/e2e/support/hosted-provider-smoke-selection.test.ts" ] }, @@ -576,6 +579,7 @@ { "live": "test/e2e/live/double-onboard.test.ts", "fast": [ + "src/lib/inference/native-local.test.ts", "test/cli/sandbox-status-text.test.ts", "src/lib/onboard/created-sandbox-finalization.test.ts", "src/lib/onboard/gateway-reuse.test.ts", @@ -591,6 +595,7 @@ { "live": "test/e2e/live/gpu-double-onboard.test.ts", "fast": [ + "src/lib/inference/native-local.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", "test/helpers/e2e-answer-assertions.test.ts" diff --git a/test/e2e/support/gpu-e2e-helpers.test.ts b/test/e2e/support/gpu-e2e-helpers.test.ts index 3eca30364b1..ecf429a00b0 100644 --- a/test/e2e/support/gpu-e2e-helpers.test.ts +++ b/test/e2e/support/gpu-e2e-helpers.test.ts @@ -17,6 +17,7 @@ import { CleanupRegistry } from "../fixtures/cleanup.ts"; import type { LifecyclePhaseFixture } from "../fixtures/phases/lifecycle.ts"; import { assertAgentExecutionSucceeded, + captureManagedRuntimeLogArtifact, cleanupGpu, createGpuPrivateHome, env, @@ -25,6 +26,7 @@ import { ollamaProxyTokenFile, openClawModelConfigProjectionScript, REPO_ROOT, + SANDBOX_NAME, startAttachedOllama, trackGpuGatewayCleanup, waitForAttachedOllama, @@ -170,6 +172,35 @@ const invalidExecutionProofs: Array<{ ]; describe("GPU E2E helpers", () => { + it("retains a failed managed runtime log capture for agent failure diagnosis", async () => { + const writeJson = vi.fn().mockResolvedValue("artifact"); + const capture = vi.fn(() => ({ + status: 125, + error: { message: "container unavailable" }, + stdout: "", + stderr: "runtime log capture failed", + })); + await captureManagedRuntimeLogArtifact( + { writeJson }, + "pre-approval-agent", + "docker", + "managed-runtime", + capture, + ); + expect(capture).toHaveBeenCalledOnce(); + expect(writeJson).toHaveBeenCalledExactlyOnceWith( + "managed-runtime-logs-pre-approval-agent.json", + { + providerId: "docker", + runtimeId: "managed-runtime", + status: 125, + error: "container unavailable", + stdout: "", + stderr: "runtime log capture failed", + }, + ); + }); + it.each([ { name: "waits through refused connections and curl timeouts", codes: [7, 28, 0], attempts: 3 }, { name: "stops after 20 curl timeouts", codes: [28], attempts: 20, reason: "exhausted" }, @@ -670,6 +701,61 @@ describe("GPU E2E helpers", () => { expect(openshell).not.toHaveBeenCalled(); }); + it("does not start a gateway by destroying an unregistered sandbox during pre-clean", async () => { + const home = mkdtempSync(path.join(tmpdir(), "nemoclaw-gpu-clean-")); + try { + const success = { exitCode: 0, stderr: "", stdout: "" }; + const host = { + command: vi.fn(async () => success), + cleanupGatewayRegistration: vi.fn(async () => success), + } as unknown as HostCliClient; + const sandbox = { cleanupSandbox: vi.fn(async () => success) } as unknown as SandboxClient; + const lifecycle = { + stopGatewayRuntime: vi.fn(async () => null), + } as unknown as LifecyclePhaseFixture; + + await cleanupGpu(host, lifecycle, sandbox, { HOME: home }); + expect(host.command).not.toHaveBeenCalledWith("node", expect.anything(), expect.anything()); + expect(sandbox.cleanupSandbox).toHaveBeenCalledOnce(); + expect(lifecycle.stopGatewayRuntime).toHaveBeenCalledOnce(); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + it("still destroys a sandbox recorded in the gateway registry", async () => { + const home = mkdtempSync(path.join(tmpdir(), "nemoclaw-gpu-registered-clean-")); + try { + const registryDir = path.join(home, ".nemoclaw"); + mkdirSync(registryDir); + writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + defaultSandbox: null, + sandboxes: { [SANDBOX_NAME]: { name: SANDBOX_NAME, agent: "openclaw" } }, + }), + ); + const success = { exitCode: 0, stderr: "", stdout: "" }; + const host = { + command: vi.fn(async () => success), + cleanupGatewayRegistration: vi.fn(async () => success), + } as unknown as HostCliClient; + const sandbox = { cleanupSandbox: vi.fn(async () => success) } as unknown as SandboxClient; + const lifecycle = { + stopGatewayRuntime: vi.fn(async () => null), + } as unknown as LifecyclePhaseFixture; + + await cleanupGpu(host, lifecycle, sandbox, { HOME: home }); + expect(host.command).toHaveBeenCalledWith( + "node", + expect.arrayContaining(["destroy", "--yes"]), + expect.objectContaining({ artifactName: "cleanup-destroy-gpu" }), + ); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + it("stops terminal GPU gateway runtime before registration and private-state cleanup", async () => { const cleanup = new CleanupRegistry(); const cleanupOrder: string[] = []; diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 9941407dd28..e2b381383ee 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -410,7 +410,7 @@ describe("Hermes config export live evidence", () => { ); it.each(["https", "http"])( - "accepts the exact messaging and %s export refusals from both aliases", + "accepts messaging refusal from both aliases with %s endpoint", async (scheme) => { mocks.load.mockReturnValue({ sandboxes: { @@ -452,7 +452,11 @@ describe("Hermes config export live evidence", () => { }, ); - it("accepts messaging refusal alongside other unsupported export findings", async () => { + it.each([ + "unsupported", + "unsupported, policy-not-representable", + "policy-not-representable, unsupported", + ])("accepts messaging refusal alongside categories %s", async (categories) => { mocks.load.mockReturnValue({ sandboxes: { hermes: { @@ -468,10 +472,15 @@ describe("Hermes config export live evidence", () => { exitCode: 2, stdout: "", stderr: [ - "Config export failed (unsupported).", + `Config export failed (${categories}).`, "V1 export does not support messaging.", "The sandbox provider attachments do not match its supported configuration.", "The managed startup profile is not the canonical profile supported by v1 export.", + ...(categories.includes("policy-not-representable") + ? [ + "Verified effective policy is malformed, unknown, or cannot be represented losslessly.", + ] + : []), ].join("\n"), }); @@ -485,6 +494,106 @@ describe("Hermes config export live evidence", () => { ); }); + it.each([ + { + name: "unrelated messaging failure", + scheme: "https", + driver: "docker", + diagnostics: "messaging export crashed", + }, + { + name: "missing refusal category", + scheme: "https", + driver: "docker", + diagnostics: "Config export failed (drifted).\nV1 export does not support messaging.", + }, + { + name: "vague messaging detail", + scheme: "https", + driver: "docker", + diagnostics: "Config export failed (unsupported).\nUnexpected messaging failure.", + }, + { + name: "missing HTTP credential refusal", + scheme: "http", + driver: "docker", + diagnostics: "Config export failed (unsupported).\nV1 export does not support messaging.", + }, + { + name: "unexpected identity drift alongside messaging refusal", + scheme: "https", + driver: "docker", + diagnostics: [ + "Config export failed (unsupported, drifted).", + "V1 export does not support messaging.", + "Registry and live gateway bindings differ.", + ].join("\n"), + }, + { + name: "undocumented finding in the unsupported category", + scheme: "https", + driver: "docker", + diagnostics: [ + "Config export failed (unsupported).", + "V1 export does not support messaging.", + "Unexpected export observation failure.", + ].join("\n"), + }, + { + name: "unrelated category with only expected findings", + scheme: "https", + driver: "docker", + diagnostics: + "Config export failed (unsupported, drifted).\nV1 export does not support messaging.", + }, + { + name: "policy category without its finding", + scheme: "https", + driver: "docker", + diagnostics: + "Config export failed (unsupported, policy-not-representable).\nV1 export does not support messaging.", + }, + { + name: "policy finding without its category", + scheme: "https", + driver: "docker", + diagnostics: [ + "Config export failed (unsupported).", + "V1 export does not support messaging.", + "Verified effective policy is malformed, unknown, or cannot be represented losslessly.", + ].join("\n"), + }, + { + name: "missing Podman refusal", + scheme: "https", + driver: "podman", + diagnostics: "Config export failed (unsupported).\nV1 export does not support messaging.", + }, + ])( + "rejects $name as expected messaging refusal evidence", + async ({ scheme, driver, diagnostics }) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: `${scheme}://host.openshell.internal:35271/v1`, + gatewayName: "nemoclaw", + openshellDriver: driver, + messaging: { schemaVersion: 1, plan: { channels: [] } }, + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, + }, + }); + mocks.command.mockResolvedValue({ exitCode: 2, stdout: "", stderr: diagnostics }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: false }); + expect(mocks.writeJson).toHaveBeenCalledWith( + "hermes-config-export-live-evidence.json", + expect.objectContaining({ refusalCategory: null, refusalDiagnosticMatches: false }), + ); + expect(mocks.save).not.toHaveBeenCalled(); + }, + ); + it("rejects other unsupported findings without the messaging refusal", async () => { mocks.load.mockReturnValue({ sandboxes: { diff --git a/test/e2e/support/inference-routing-cleanup.test.ts b/test/e2e/support/inference-routing-cleanup.test.ts new file mode 100644 index 00000000000..abfe0d0ae00 --- /dev/null +++ b/test/e2e/support/inference-routing-cleanup.test.ts @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { afterAll, describe, expect, it, vi } from "vitest"; +import { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { cleanupSandbox, providerPolicyRestoreArgs } from "../live/inference-routing-helpers.ts"; + +const home = vi.hoisted(() => `/tmp/nemoclaw-inference-cleanup-test-${process.pid}`); +vi.mock("node:os", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, default: { ...actual, homedir: () => home }, homedir: () => home }; +}); +afterAll(() => fs.rmSync(home, { recursive: true, force: true })); + +function result(stdout = "", exitCode = 0): ShellProbeResult { + return { + command: [], + stdout, + stderr: "", + exitCode, + signal: null, + timedOut: false, + artifacts: { stdout: "", stderr: "", result: "" }, + }; +} +function fixture(listing: ShellProbeResult | Error, destroy: ShellProbeResult | Error = result()) { + fs.mkdirSync(path.join(home, ".nemoclaw"), { recursive: true }); + const calls: string[] = []; + const sandbox = new SandboxClient({ + run: async (command) => { + calls.push(command.args.join(" ")); + const response = new Map([ + ["sandbox list", listing], + ["sandbox delete fixture", result()], + ]).get(command.args.join(" ")); + expect(response, `unsupported command: ${command.args.join(" ")}`).toBeDefined(); + return response instanceof Error ? Promise.reject(response) : response!; + }, + }); + const host = { + command: vi.fn(async () => { + calls.push("public destroy"); + return destroy instanceof Error ? Promise.reject(destroy) : destroy; + }), + }; + return { + calls, + host, + run: () => + cleanupSandbox(host as unknown as HostCliClient, sandbox, "fixture", { strict: true }), + }; +} + +describe("inference routing strict cleanup", () => { + it("confirms absence before public destroy can stop the gateway (#12558)", async () => { + const f = fixture(result("No sandboxes found.\n")); + await f.run(); + expect(f.calls).toEqual(["sandbox delete fixture", "sandbox list", "public destroy"]); + }); + it.each([ + ["sandbox still present", result("fixture Ready\n")], + ["unsupported command", result("unrecognized subcommand", 2)], + ["gateway unreachable", result("connection refused", 1)], + ["timeout", { ...result("", 0), timedOut: true }], + ["terminated probe", { ...result("", 0), signal: "SIGTERM" as const }], + ])("does not claim absence for %s (#12558)", async (_name, response) => { + const f = fixture(response); + await expect(f.run()).rejects.toThrow("absence was not verified"); + expect(f.calls).toEqual(["sandbox delete fixture", "sandbox list", "public destroy"]); + }); + it("attempts public destroy and clears state when sandbox listing throws (#12558)", async () => { + const f = fixture(new Error("gateway read unavailable")); + fs.writeFileSync(path.join(home, ".nemoclaw", "onboard-session.json"), "fixture"); + await expect(f.run()).rejects.toThrow( + /absence was not verified[\s\S]*gateway read unavailable/, + ); + expect(f.calls).toEqual(["sandbox delete fixture", "sandbox list", "public destroy"]); + expect(fs.existsSync(path.join(home, ".nemoclaw", "onboard-session.json"))).toBe(false); + }); + it("reports both failures and clears state when listing and public destroy throw (#12558)", async () => { + const f = fixture( + new Error("gateway read unavailable"), + new Error("provider retirement unavailable"), + ); + fs.writeFileSync(path.join(home, ".nemoclaw", "onboard-session.json"), "fixture"); + await expect(f.run()).rejects.toThrow( + /absence was not verified[\s\S]*gateway read unavailable[\s\S]*provider retirement unavailable/, + ); + expect(f.calls).toEqual(["sandbox delete fixture", "sandbox list", "public destroy"]); + expect(fs.existsSync(path.join(home, ".nemoclaw", "onboard-session.json"))).toBe(false); + }); + it("does not mistake a sibling's name for the target (#12558)", async () => { + const f = fixture(result("fixture-sibling Ready\n")); + await f.run(); + expect(f.host.command).toHaveBeenCalledOnce(); + }); + it.each([ + ["nonzero exit", result("provider retirement failed", 1)], + ["timeout", { ...result(), timedOut: true }], + ["signal", { ...result(), signal: "SIGTERM" as const }], + ["throw", new Error("provider retirement unavailable")], + ])("rejects %s from public destroy after sandbox absence (#12558)", async (_name, destroy) => { + const f = fixture(result("No sandboxes found.\n"), destroy); + fs.writeFileSync(path.join(home, ".nemoclaw", "onboard-session.json"), "fixture"); + fs.writeFileSync(path.join(home, ".nemoclaw", "onboard.lock"), "fixture"); + await expect(f.run()).rejects.toThrow("public destroy was not verified"); + expect(f.calls).toEqual(["sandbox delete fixture", "sandbox list", "public destroy"]); + expect(fs.existsSync(path.join(home, ".nemoclaw", "onboard-session.json"))).toBe(false); + expect(fs.existsSync(path.join(home, ".nemoclaw", "onboard.lock"))).toBe(false); + }); +}); + +describe("runtime identity settings restoration", () => { + it("deletes a setting absent from the pinned CLI JSON (#12558)", () => { + expect(providerPolicyRestoreArgs(undefined)).toEqual([ + "settings", + "delete", + "--global", + "--key", + "providers_v2_enabled", + "--yes", + ]); + }); + it.each(["true", "false"])("restores an explicit %s setting (#12558)", (value) => { + expect(providerPolicyRestoreArgs(value)).toEqual([ + "settings", + "set", + "--global", + "--key", + "providers_v2_enabled", + "--value", + value, + "--yes", + ]); + }); + it.each([null, true, false, "", "invalid"])("rejects malformed value %s (#12558)", (value) => { + expect(providerPolicyRestoreArgs(value)).toBeUndefined(); + }); +}); diff --git a/test/e2e/support/lifecycle-user-service.test.ts b/test/e2e/support/lifecycle-user-service.test.ts index d44bb8e49a4..d6cf1ede869 100644 --- a/test/e2e/support/lifecycle-user-service.test.ts +++ b/test/e2e/support/lifecycle-user-service.test.ts @@ -509,6 +509,7 @@ describe("managed OpenShell gateway user-service stop", () => { [ "#!/bin/sh", `printf "%s\\n" "$*" >> ${JSON.stringify(log)}`, + 'if [ "$XDG_RUNTIME_DIR" != "/run/user/$(id -u)" ] || [ "$DBUS_SESSION_BUS_ADDRESS" != "unix:path=$XDG_RUNTIME_DIR/bus" ]; then exit 96; fi', `if [ "$*" = ${JSON.stringify(upstreamServiceShow)} ]; then exit 1; fi`, 'if [ "$*" = "--user show-environment" ]; then exit 0; fi', `if [ "$*" = "--user show nemoclaw-openshell-gateway.service --property=FragmentPath --value" ]; then printf '%s\\n' ${JSON.stringify(unit)}; exit 0; fi`, diff --git a/test/e2e/support/managed-image-activation-diagnostics.test.ts b/test/e2e/support/managed-image-activation-diagnostics.test.ts index 66035991632..a3986cf4c6b 100644 --- a/test/e2e/support/managed-image-activation-diagnostics.test.ts +++ b/test/e2e/support/managed-image-activation-diagnostics.test.ts @@ -3,6 +3,7 @@ import fs, { existsSync, readFileSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; +import { execFileSync } from "node:child_process"; import os from "node:os"; import path, { join } from "node:path"; @@ -22,6 +23,7 @@ import { ADMIN_APPROVAL_TEST_OPENSHELL_SH, } from "../../support/admin-approval-connect-fixture.ts"; import { ArtifactSink } from "../fixtures/artifacts.ts"; +import { captureManagedRuntimeLogArtifact } from "../live/gpu-e2e-helpers.ts"; import { captureManagedImageOnboardPairingDiagnostics, collectOnboardFailureRuntimeDiagnostics, @@ -29,6 +31,8 @@ import { externalImageActivationMatches, externalImageActivationOnboardArgs, managedActivationPostRestartAgentTurnScript, + managedActivationCommandEnv, + runManagedActivationAgentTurn, managedActivationOpenClawPluginScript, managedHermesBoundaryPoisonCommand, managedOpenClawSubagentCommand, @@ -41,6 +45,7 @@ import { waitForManagedActivationSandboxAbsence, } from "../live/managed-image-activation-e2e-helpers.ts"; import { pendingAdminRequestId } from "../fixtures/issue-4462-admin-approval-evidence.ts"; +import { validateSandboxName } from "../fixtures/clients/sandbox.ts"; const MANAGED_ADMIN_PUBLIC_KEY_BYTES = Buffer.from( Array.from({ length: 32 }, (_value, index) => index), @@ -189,7 +194,159 @@ printf '%s\n' "$@" >"$MANAGED_ACTIVATION_FIXTURE/openclaw-args" } } +describe("managed image activation inference selection", () => { + it.each([false, true])( + "passes the selected credentialless=%s boundary to the CLI process", + (credentialless) => { + const environment = managedActivationCommandEnv( + { + env: { + COMPATIBLE_API_KEY: "unrelated-compatible-key", + NEMOCLAW_LOCAL_INFERENCE_SANDBOX_HOST_URL: "http://127.0.0.1", + NEMOCLAW_VLLM_LOCAL_TOKEN: "unrelated-local-token", + }, + }, + "/exact-catalog.json", + "http://host.openshell.internal:18321/v1", + credentialless, + ); + const child = JSON.parse( + execFileSync( + process.execPath, + [ + "-e", + ` + const e=process.env; + console.log(JSON.stringify({ + provider:e.NEMOCLAW_PROVIDER, + port:e.NEMOCLAW_VLLM_PORT ?? null, + endpoint:e.NEMOCLAW_ENDPOINT_URL ?? null, + compatibleCredentialPresent:Boolean(e.COMPATIBLE_API_KEY), + localCredentialPresent:Boolean(e.NEMOCLAW_VLLM_LOCAL_TOKEN), + loopbackOverridePresent:Boolean(e.NEMOCLAW_LOCAL_INFERENCE_SANDBOX_HOST_URL), + catalog:e.NEMOCLAW_MANAGED_ACTIVATION_CATALOG, + })); + `, + ], + { env: environment, encoding: "utf8" }, + ), + ); + expect(child).toEqual( + credentialless + ? { + provider: "vllm", + port: "18321", + endpoint: null, + compatibleCredentialPresent: false, + localCredentialPresent: false, + loopbackOverridePresent: false, + catalog: "/exact-catalog.json", + } + : { + provider: "custom", + port: null, + endpoint: "http://host.openshell.internal:18321/v1", + compatibleCredentialPresent: true, + localCredentialPresent: true, + loopbackOverridePresent: true, + catalog: "/exact-catalog.json", + }, + ); + }, + ); +}); + +describe("managed image activation agent request evidence", () => { + it.each([ + { label: "stale onboarding request", newRequests: [], accepted: false }, + { + label: "wrong model", + newRequests: [ + { method: "POST", path: "/v1/chat/completions", bodyBytes: 1, model: "other-model" }, + ], + accepted: false, + }, + { + label: "model discovery only", + newRequests: [{ method: "GET", path: "/v1/models", bodyBytes: 0 }], + accepted: false, + }, + { + label: "new selected-model completion", + newRequests: [ + { + method: "POST", + path: "/v1/chat/completions", + bodyBytes: 1, + model: "nemoclaw-managed-activation-model", + }, + ], + accepted: true, + }, + ])("accepts only new agent completion evidence: $label", async ({ newRequests, accepted }) => { + const requests: import("../fixtures/fake-openai-compatible.ts").FakeOpenAiCompatibleRequest[] = + [ + { + method: "POST", + path: "/v1/chat/completions", + bodyBytes: 1, + model: "nemoclaw-managed-activation-model", + }, + ]; + const exec = vi.fn(async () => { + requests.push(...newRequests); + return { exitCode: 0, stdout: "PONG", stderr: "", timedOut: false }; + }); + const outcome = await runManagedActivationAgentTurn( + { exec } as never, + "langchain-deepagents-code", + "credentialless-fixture", + "after", + {}, + "dcode-credentialless", + () => requests, + ).then( + () => true, + () => false, + ); + expect(outcome).toBe(accepted); + expect(exec).toHaveBeenCalledWith( + "credentialless-fixture", + ["dcode", "-n", "Reply with exactly one word: PONG", "--json"], + expect.objectContaining({ artifactName: "dcode-credentialless-agent-turn-after-restart" }), + ); + }); +}); + describe("managed image activation failure diagnostics", () => { + it("retains redacted llama.cpp logs before a failed agent assertion", async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-llama-agent-logs-")); + const secret = "fixture-runtime-secret"; + try { + const artifacts = new ArtifactSink(directory, [secret]); + await captureManagedRuntimeLogArtifact( + artifacts, + "pre-approval-agent", + "docker", + "fixture-runtime", + () => ({ + status: 0, + error: null, + stdout: "", + stderr: `agent request failed with ${secret}`, + }), + ); + const recorded = fs.readFileSync( + path.join(directory, "managed-runtime-logs-pre-approval-agent.json"), + "utf8", + ); + expect(recorded).toContain('"status": 0'); + expect(recorded).toContain("[REDACTED]"); + expect(recorded).not.toContain(secret); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); it.each<{ diagnostic: string; expectedRequestId?: string; @@ -924,10 +1081,19 @@ ${adminApprovalConnectScript("nemoclaw", "fixture-sandbox", "managed-cron", outp expectedLogs: [], readyCalls: 1, error: "reached readiness", + credentialless: true, }, ])( "retains diagnostics before reporting stop=$stop/start=$start", - async ({ stop, start, expectedEvents, expectedLogs, readyCalls, error }) => { + async ({ + stop, + start, + expectedEvents, + expectedLogs, + readyCalls, + error, + credentialless = false, + }) => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-restart-diagnostics-")); const events: string[] = []; const ok = { exitCode: 0, stdout: "PONG", stderr: "" }; @@ -976,7 +1142,10 @@ ${adminApprovalConnectScript("nemoclaw", "fixture-sandbox", "managed-cron", outp const ready = vi.fn(async () => { throw new Error("reached readiness"); }); - const cleanupSandbox = vi.fn(async () => ok); + const cleanupSandbox = vi.fn(async (name: string) => { + validateSandboxName(name); + return ok; + }); try { await expect( qualifyAgent( @@ -993,7 +1162,7 @@ ${adminApprovalConnectScript("nemoclaw", "fixture-sandbox", "managed-cron", outp stopGatewayRuntime: vi.fn(), waitForSandboxReadyAfterGatewayRestart: ready, }, - progress: { phase: vi.fn() }, + progress: { phase: vi.fn(), event: vi.fn() }, sandbox: { cleanupSandbox, exec: vi.fn(async () => ok), @@ -1005,6 +1174,7 @@ ${adminApprovalConnectScript("nemoclaw", "fixture-sandbox", "managed-cron", outp "http://inference.invalid/v1", "langchain-deepagents-code", {} as never, + credentialless, ), ).rejects.toThrow(error); expect(events).toEqual(expectedEvents); diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index 4730451ac16..d6a928f8292 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -33,6 +33,7 @@ export type DestroyHarness = { errorSpy: MockInstance; events: string[]; executeSandboxDestroySpy: MockInstance; + retireNativeLocalProviderSpy: MockInstance; enforceRemovedImmutabilityMigrationBoundarySpy: MockInstance; finalGatewaySleepSpy: MockInstance; finalizeMcpBridgesAfterSandboxDeleteSpy: MockInstance; @@ -54,6 +55,7 @@ export type DestroyHarness = { cleanupManagedLlamaCppRuntimeForSandboxSpy: MockInstance; preparePortableDestroyAuthoritySpy: MockInstance; promptSpy: MockInstance; + nativeLocalProviderAuthority: typeof import("../../src/lib/state/registry/native-local-provider-authority"); registry: Pick; removeManagedAgentStateVolumesSpy: MockInstance; removeSandboxSpy: MockInstance; @@ -273,6 +275,9 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr "../../state/mcp-lifecycle-lock.js", ) as typeof import("../../src/lib/state/mcp-lifecycle-lock"); const registry = requireSource("../../state/registry.js"); + const nativeLocalProviderAuthority = requireSource( + "../../state/registry/native-local-provider-authority.js", + ); const removedImmutabilityMigration = requireSource( "../../state/migrations/removed-immutability.js", ); @@ -316,6 +321,9 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr } }, ); + const retireNativeLocalProviderSpy = vi + .spyOn(destroyExecution, "retireDestroyedSandboxNativeLocalProvider") + .mockResolvedValue(undefined); const executeSandboxDestroySpy = vi.spyOn(destroyExecution, "executeSandboxDestroy"); if (options.executeSandboxDestroyResult) { executeSandboxDestroySpy.mockResolvedValue(options.executeSandboxDestroyResult); @@ -779,6 +787,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr errorSpy, events, executeSandboxDestroySpy, + retireNativeLocalProviderSpy, runSandboxProviderPreDeleteCleanupSpy, enforceRemovedImmutabilityMigrationBoundarySpy, finalGatewaySleepSpy, @@ -803,6 +812,7 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr portableDestroyVerifyAbsentSpy, promptSpy, registry, + nativeLocalProviderAuthority, removeManagedAgentStateVolumesSpy, removeSandboxSpy, reconstructRetainedSandboxRecoverySpy, diff --git a/test/helpers/inference-set.ts b/test/helpers/inference-set.ts index 161827eedb9..0bd7f33a3e0 100644 --- a/test/helpers/inference-set.ts +++ b/test/helpers/inference-set.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + nativeLocalIdentity, + type NativeLocalBinding, +} from "../../src/lib/inference/native-local/contract"; import { vi } from "vitest"; import type { CaptureOpenshellOptions, @@ -260,6 +264,26 @@ export type CaptureOpenshell = ( options?: CaptureOpenshellOptions, ) => CaptureOpenshellResult; +export function nativeLocalTestReceipt( + provider: NativeLocalBinding["provider"] = "ollama-local", + endpointUrl = "http://host.openshell.internal:11435/v1", +) { + const binding: NativeLocalBinding = { + provider, + endpointUrl, + sandboxName: "alpha", + gatewayName: "nemoclaw", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + }; + return { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "local-provider-id", + }; +} + export function createDeps(options: { config: ConfigObject; entry?: SandboxEntry | null; @@ -439,6 +463,28 @@ export function createDeps(options: { { redactDiagnostic: redactInferenceSetRouteDiagnostic }, ); return { + requireNativeProviderPolicy: async () => {}, + prepareNativeLocalSwitch: async (input) => { + const binding: NativeLocalBinding = { + provider: input.provider as NativeLocalBinding["provider"], + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + endpointUrl: input.binding?.baseUrl ?? "http://host.openshell.internal:11435/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + }; + return { + changed: false, + previousDetached: false, + receipt: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "local-provider-id", + }, + }; + }, + listNativeLocalProviderAuthorities: () => [], getDefaultSandbox: () => defaultSandbox, getSandbox: (name: string) => sandboxes[name] ?? null, listSandboxes: () => ({ sandboxes: entries, defaultSandbox }), @@ -500,3 +546,55 @@ export function createDeps(options: { getSession: () => session, }; } + +/** Stateful local-to-NVIDIA fixture with a failed restoration after detach. */ +export function createFailingNativeLocalRestoreAdapter( + base: OpenShellProviderAdapter, + previous: ReturnType, +) { + let localAttached = true; + const detachProvider = vi.fn(async (request: Parameters[0]) => { + if (request.providerName !== previous.providerName) return base.detachProvider(request); + localAttached = false; + return { ok: true as const, value: { changed: true } }; + }); + const adapter = { + ...base, + detachProvider, + inspectProviderProfile: async () => ({ + ok: true as const, + value: { credentialKeys: [previous.credentialEnv] }, + }), + getProvider: async (request: Parameters[0]) => + request.providerName !== previous.providerName + ? base.getProvider(request) + : { + ok: true as const, + value: { + name: previous.providerName, + type: previous.profileId, + credentialKeys: [previous.credentialEnv], + configKeys: [], + revision: { id: previous.providerId, resourceVersion: 1 }, + }, + }, + listProviderAttachments: async ( + request: Parameters[0], + ) => { + const result = await base.listProviderAttachments(request); + return result.ok + ? { + ok: true as const, + value: { + names: [...result.value.names, ...(localAttached ? [previous.providerName] : [])], + }, + } + : result; + }, + attachProvider: async (request: Parameters[0]) => { + if (request.providerName !== previous.providerName) return base.attachProvider(request); + throw new Error("local restoration unavailable"); + }, + }; + return { adapter, detachProvider }; +} diff --git a/test/helpers/rebuild-flow-generic-harness.ts b/test/helpers/rebuild-flow-generic-harness.ts index 95ddd77e202..e85a6ef0473 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: "nvidia-router", model: "nvidia/nemotron", policies: ["npm"], agent: null, diff --git a/test/helpers/rebuild-flow-test-support.ts b/test/helpers/rebuild-flow-test-support.ts index 0dabdfd0c01..dee5b057c55 100644 --- a/test/helpers/rebuild-flow-test-support.ts +++ b/test/helpers/rebuild-flow-test-support.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { type MockInstance, vi } from "vitest"; +import { + nativeLocalIdentity, + type NativeLocalProviderAttachment, +} from "../../src/lib/inference/native-local/contract"; import type { GatewayRestartResult } from "../../src/lib/actions/sandbox/gateway-restart"; import type { SandboxGatewayState } from "../../src/lib/actions/sandbox/gateway-state"; import type { OpenShellSandboxInventory } from "../../src/lib/adapters/openshell/sandbox-observer"; @@ -239,7 +243,7 @@ export function createRebuildFlowSession(machineSnapshotVersion: number): Rebuil updatedAt: "2026-06-01T00:00:00.000Z", sandboxName: "alpha", agent: null, - provider: "ollama-local", + provider: "nvidia-router", model: "nvidia/nemotron", credentialEnv: null, checkpoint: null, @@ -301,3 +305,23 @@ export function installTerminalStepFailureMock( return session; }); } + +/** A normalized local source receipt for tests that exercise later rebuild boundaries. */ +export function nativeLocalRebuildAttachment( + provider: "ollama-local" | "vllm-local", +): NativeLocalProviderAttachment { + const binding = { + provider, + endpointUrl: `http://host.openshell.internal:${provider === "vllm-local" ? "8000" : "11434"}/v1`, + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "sentinel" as const, + gatewayName: "nemoclaw", + sandboxName: "alpha", + }; + return { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "11111111-2222-4333-8444-555555555555", + }; +} diff --git a/test/onboarding/onboard-gateway-prelaunch-cutover.test.ts b/test/onboarding/onboard-gateway-prelaunch-cutover.test.ts index 1d0477b8865..dca881271dc 100644 --- a/test/onboarding/onboard-gateway-prelaunch-cutover.test.ts +++ b/test/onboarding/onboard-gateway-prelaunch-cutover.test.ts @@ -162,6 +162,9 @@ const observedListenerPids = []; Module._load = function(request, parent, isMain) { const actual = () => originalLoad.call(this, request, parent, isMain); + if (request.endsWith("/adapters/openshell/provider-policy")) { + return { ...actual(), initializeNativeProviderPolicy: async () => {} }; + } if (request.endsWith("/preflight")) { return { ...actual(), checkPortAvailable: async () => ({ ok: true, pid: ++probe }) }; } diff --git a/test/onboarding/onboard-host-local-inference-routing.test.ts b/test/onboarding/onboard-host-local-inference-routing.test.ts index 6f11016a5d4..4a176d77c08 100644 --- a/test/onboarding/onboard-host-local-inference-routing.test.ts +++ b/test/onboarding/onboard-host-local-inference-routing.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"; -import { createCliOpenShellInferenceRouteMutator } from "../../src/lib/adapters/openshell/inference-route-cli.js"; +import { nativeLocalSetupReceipt } from "../support/native-local-setup-harness"; import type { HostLocalInferenceOperation, HostLocalInferencePreparedStartup, @@ -39,6 +39,7 @@ 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 NATIVE_APPLICATIONS = ["openclaw", "langchain-deepagents-code"] as const; const PUBLISHED_RESUME_ROLLBACK_CASES = APPLICATIONS.flatMap((application) => (["running", "stopped"] as const).map((stateAtEntry) => ({ application, stateAtEntry })), ); @@ -243,6 +244,9 @@ function fixture( options: Parameters[2] & { gatewayCommitError?: Error; gatewayRollbackError?: Error; + registerNativeProvider?: NonNullable< + HostLocalInferenceGatewayMutation["registerNativeProvider"] + >; gatewayUpsertProvider?: NonNullable; recover?: boolean; resume?: boolean; @@ -281,6 +285,9 @@ function fixture( const prepareGatewayMutation = vi.fn(() => { events.push("gateway-snapshot"); return { + ...(options.registerNativeProvider + ? { registerNativeProvider: options.registerNativeProvider } + : {}), ...(options.gatewayUpsertProvider ? { upsertProvider: options.gatewayUpsertProvider } : {}), commit: gatewayCommit, rollback: gatewayRollback, @@ -466,8 +473,8 @@ describe("onboard host-local inference routing", () => { ); }); - it.each(APPLICATIONS)( - "routes %s through inference.local without legacy host probes", + it.each(NATIVE_APPLICATIONS)( + "prepares native local inference for %s without a shared gateway route or legacy host probes", async (application) => { const route = fixture(application, "ollama"); const legacyRun = vi.fn(); @@ -549,18 +556,22 @@ describe("onboard host-local inference routing", () => { kind: "host", acceleration: "nvidia-gpu", }); - expect(harness.commands.map(({ command }) => command)).toEqual([ - "provider get -g nemoclaw ollama-local", - "provider create -g nemoclaw --name ollama-local --type openai --credential NEMOCLAW_OLLAMA_PROXY_TOKEN --config OPENAI_BASE_URL=http://host.openshell.internal:11434/v1", - `inference set -g nemoclaw --no-verify --provider ollama-local --model ${MODEL} --timeout 180`, - ]); - expect(harness.commands.map(({ command }) => command).join(" ")).not.toContain( - "mxc-provider-native.internal", + expect(harness.commands).toEqual([]); + expect(harness.native.adapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + target: { kind: "named", gatewayName: "nemoclaw" }, + type: expect.stringMatching(/^nemoclaw-local-sentinel-v1-/), + credentials: [{ name: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", value: "ollama" }], + config: [], + }), ); + expect(harness.native.profiles[0]).toMatchObject({ + endpoints: [{ host: "host.openshell.internal", port: 11434 }], + }); + expect(verify).not.toHaveBeenCalled(); expect(route.events).toEqual([ "provider-ready-proof", "gateway-snapshot", - "gateway-route-verify", "runtime-precommit-validation", "gateway-commit", "runtime-precommit-validation", @@ -585,10 +596,17 @@ describe("onboard host-local inference routing", () => { ); it("uses a transaction-owned provider create instead of the generic gateway upsert", async () => { - const exactProviderCreate = vi.fn(() => ({ ok: true })); + const attachment = nativeLocalSetupReceipt({ + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11434/v1", + authMode: "sentinel", + gatewayName: "nemoclaw", + sandboxName: SANDBOX, + }); + const exactProviderCreate = vi.fn(async () => attachment); const genericUpsertProvider = vi.fn(async () => ({ ok: true })); - const route = fixture("hermes", "ollama", { - gatewayUpsertProvider: exactProviderCreate, + const route = fixture("openclaw", "ollama", { + registerNativeProvider: exactProviderCreate, }); const harness = createHarness({ overrides: { @@ -604,16 +622,35 @@ describe("onboard host-local inference routing", () => { }), ).resolves.toEqual({ ok: true }); - expect(exactProviderCreate).toHaveBeenCalledWith( - "ollama-local", - "openai", - "NEMOCLAW_OLLAMA_PROXY_TOKEN", - "http://host.openshell.internal:11434/v1", - { NEMOCLAW_OLLAMA_PROXY_TOKEN: "ollama" }, + expect(exactProviderCreate).toHaveBeenCalledExactlyOnceWith(); + expect(harness.native.adapter.createProvider).not.toHaveBeenCalled(); + expect(harness.updateSandbox).toHaveBeenCalledWith( + SANDBOX, + expect.objectContaining({ nativeLocalProviderAttachment: attachment }), ); expect(genericUpsertProvider).not.toHaveBeenCalled(); }); + it("keeps Hermes host-local setup on its transaction-owned shared route", async () => { + const sharedUpsert = vi.fn(() => ({ ok: true })); + const route = fixture("hermes", "ollama", { gatewayUpsertProvider: sharedUpsert }); + const harness = createHarness({ overrides: { applyLocalInferenceRoute: undefined } }); + + await expect( + harness.setupInference(SANDBOX, MODEL, "ollama-local", null, null, null, [], { + gatewayName: "nemoclaw", + hostLocalInference: route.selection, + }), + ).resolves.toEqual({ ok: true }); + + expect(sharedUpsert).toHaveBeenCalledOnce(); + expect(harness.native.adapter.createProvider).not.toHaveBeenCalled(); + expect(harness.updateSandbox).not.toHaveBeenCalledWith( + SANDBOX, + expect.objectContaining({ nativeLocalProviderAttachment: expect.anything() }), + ); + }); + it.each(APPLICATIONS)( "registers explicitly selected llama.cpp for %s with exact private provenance", async (application) => { @@ -740,9 +777,10 @@ describe("onboard host-local inference routing", () => { }), ).resolves.toEqual({ ok: true }); - expect(harness.commands.some(({ command }) => command.includes(`:${String(port)}/v1`))).toBe( - true, - ); + expect(harness.native.profiles[0]).toMatchObject({ + endpoints: [{ host: "host.openshell.internal", port }], + }); + expect(harness.commands).toEqual([]); expect(legacyRun).not.toHaveBeenCalled(); expect(legacyValidate).not.toHaveBeenCalled(); expect(route.gatewayCommit).toHaveBeenCalledOnce(); @@ -803,16 +841,22 @@ describe("onboard host-local inference routing", () => { // it is not rollback authority for an already-published runtime. priorState: "absent", resumeStateAtEntry: stateAtEntry, + registerNativeProvider: async () => { + throw new Error("provider creation denied"); + }, }); const harness = createHarness({ overrides: { applyLocalInferenceRoute: vi.fn(async () => true) }, }); - await expect( - harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { - hostLocalInference: route.selection, - }), - ).resolves.toEqual({ retry: "selection" }); + const setup = harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { + hostLocalInference: route.selection, + }); + const outcome = await setup.then( + (value) => value, + (error: Error) => error.message, + ); + expect(outcome).toEqual(application === "hermes" ? { retry: "selection" } : "EXIT_CALLED:1"); const preparedStartup = route.preparedStartups[0]; expect(route.providerRuntime.resumeManaged).toHaveBeenCalledOnce(); @@ -832,7 +876,12 @@ describe("onboard host-local inference routing", () => { it.each(APPLICATIONS)( "rolls back %s gateway denial and exact prior runtime state", async (application) => { - const route = fixture(application, "vllm", { priorState: "stopped" }); + const route = fixture(application, "vllm", { + priorState: "stopped", + registerNativeProvider: async () => { + throw new Error("provider creation denied"); + }, + }); const error = vi.fn(() => route.events.push("redacted-evidence")); const harness = createHarness({ overrides: { @@ -841,11 +890,14 @@ describe("onboard host-local inference routing", () => { }, }); - await expect( - harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { - hostLocalInference: route.selection, - }), - ).resolves.toEqual({ retry: "selection" }); + const setup = harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { + hostLocalInference: route.selection, + }); + const outcome = await setup.then( + (value) => value, + (error: Error) => error.message, + ); + expect(outcome).toEqual(application === "hermes" ? { retry: "selection" } : "EXIT_CALLED:1"); expect(route.events.slice(-3)).toEqual([ "redacted-evidence", @@ -863,21 +915,15 @@ describe("onboard host-local inference routing", () => { { provider: "ollama-local", service: "ollama" }, { provider: "vllm-local", service: "vllm" }, ] as const)( - "retains the $service gateway and runtime after an ambiguous route mutation", + "retains the $service gateway and runtime when native provider creation and cleanup cannot be reconciled", async ({ provider, service }) => { - const route = fixture("openclaw", service); - const harness = createHarness({ - overrides: { - applyLocalInferenceRoute: undefined, - inferenceRouteMutator: createCliOpenShellInferenceRouteMutator(async () => ({ - status: 0, - signal: null, - output: "Error: authentication failed", - stdout: "", - stderr: "Error: authentication failed", - })), + const route = fixture("openclaw", service, { + registerNativeProvider: async () => { + throw new Error("provider creation result is unknown"); }, + gatewayRollbackError: new Error("provider identity cannot be reconciled"), }); + const harness = createHarness(); await expect( harness.setupInference(SANDBOX, MODEL, provider, null, null, null, [], { @@ -885,10 +931,10 @@ describe("onboard host-local inference routing", () => { }), ).rejects.toThrow("EXIT_CALLED:1"); - expect(route.gatewayRollback).not.toHaveBeenCalled(); + expect(route.gatewayRollback).toHaveBeenCalledOnce(); expect(route.preparedStartups[0]?.rollback).not.toHaveBeenCalled(); expect(route.events).not.toContain("runtime-rollback"); - expect(harness.errors.join(" ")).toContain("route update result is unknown"); + expect(harness.errors.join(" ")).toContain("provider creation result is unknown"); }, ); @@ -897,6 +943,9 @@ describe("onboard host-local inference routing", () => { async (application) => { const route = fixture(application, "vllm", { gatewayRollbackError: new Error("indeterminate gateway cleanup"), + registerNativeProvider: async () => { + throw new Error("provider creation denied"); + }, }); const harness = createHarness({ overrides: { applyLocalInferenceRoute: vi.fn(async () => true) }, @@ -945,19 +994,14 @@ describe("onboard host-local inference routing", () => { }); it("never emits a raw secret-bearing gateway provider failure", async () => { - const route = fixture("openclaw", "vllm"); - const providerFailures = { - "provider get": { status: 1 }, - "provider create": { - status: 1, - stderr: + const route = fixture("openclaw", "vllm", { + registerNativeProvider: async () => { + throw new Error( "https://gateway-user:gateway-password@gateway.example/v1?token=gateway-query OPENAI_API_KEY=gateway-env-secret", + ); }, - } as const; - const harness = createHarness({ - runOpenshell: (args) => - providerFailures[args.slice(0, 2).join(" ") as keyof typeof providerFailures], }); + const harness = createHarness(); await expect( harness.setupInference(SANDBOX, MODEL, "vllm-local", null, null, null, [], { diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 007ac2f0cf7..fb7f125e4b7 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeLocalSetupReceipt } from "../support/native-local-setup-harness"; import fs from "node:fs"; import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; @@ -64,7 +65,7 @@ describe("onboarding inference gateway scope", () => { runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { status: 1 } : undefined, }); - const endpointUrl = "http://localhost:8000/v1?tenant=local#models"; + const endpointUrl = "http://localhost:8000/v1"; const model = "deepseek-ai/DeepSeek-V4-Flash"; await expect( @@ -76,15 +77,28 @@ describe("onboarding inference gateway scope", () => { "COMPATIBLE_API_KEY", null, [], - { gatewayName: GATEWAY }, + { gatewayName: GATEWAY, agentName: "langchain-deepagents-code" }, ), ).resolves.toEqual({ ok: true }); - expect(harness.commands.map(({ command }) => command)).toEqual([ - `provider get -g ${GATEWAY} compatible-endpoint`, - `provider create -g ${GATEWAY} --name compatible-endpoint --type openai --credential COMPATIBLE_API_KEY --config OPENAI_BASE_URL=http://host.openshell.internal:8000/v1?tenant=local#models`, - `inference set -g ${GATEWAY} --no-verify --provider compatible-endpoint --model ${model} --timeout 180`, - ]); + expect(harness.commands).toEqual([]); + expect(harness.native.adapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + target: { kind: "named", gatewayName: GATEWAY }, + type: expect.stringMatching(/^nemoclaw-local-authenticated-v1-/), + credentials: [ + { + name: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + value: "sk-compatible-TEST-NOT-A-REAL-VALUE", + }, + ], + config: [], + }), + ); + expect(harness.native.profiles[0]).toMatchObject({ + endpoints: [{ host: "host.openshell.internal", port: 8000 }], + }); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); expect(harness.verifyOnboardInferenceSmoke).toHaveBeenCalledWith({ provider: "compatible-endpoint", model, @@ -104,6 +118,10 @@ describe("onboarding inference gateway scope", () => { gatewayName: GATEWAY, reservationSessionId: undefined, hostLocalInferenceReceipt: null, + nativeLocalProviderAttachment: expect.objectContaining({ + gatewayName: GATEWAY, + sandboxName: "dcode-vllm-local", + }), }); expectCommandsTargetOnly(harness.commands); }, @@ -122,6 +140,14 @@ describe("onboarding inference gateway scope", () => { } : undefined, }); + const receipt = nativeLocalSetupReceipt({ + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + authMode: "authenticated", + gatewayName: GATEWAY, + sandboxName: "dcode-vllm-local", + }); + harness.native.seed(receipt); const model = "deepseek-ai/DeepSeek-V4-Flash"; await expect( @@ -135,29 +161,22 @@ describe("onboarding inference gateway scope", () => { [], { gatewayName: GATEWAY, + agentName: "langchain-deepagents-code", reuseGatewayCredentialWithoutLocalKey: true, skipHostInferenceSmoke: true, }, ), ).resolves.toEqual({ ok: true }); - expect(harness.commands.map(({ command }) => command)).toEqual([ - `provider get -g ${GATEWAY} compatible-endpoint`, - `provider get -g ${GATEWAY} compatible-endpoint`, - `provider update -g ${GATEWAY} compatible-endpoint --config OPENAI_BASE_URL=http://host.openshell.internal:8000/v1`, - `inference set -g ${GATEWAY} --no-verify --provider compatible-endpoint --model ${model} --timeout 180`, - ]); - const providerUpdate = harness.commands.find(({ command }) => - command.startsWith("provider update "), - ); - expect(providerUpdate?.env).toBeUndefined(); - expect(harness.commands.every(({ env }) => env?.COMPATIBLE_API_KEY === undefined)).toBe(true); + expect(harness.commands).toEqual([]); + expect(harness.native.adapter.getProvider).toHaveBeenCalledWith({ + target: { kind: "named", gatewayName: GATEWAY }, + providerName: receipt.providerName, + }); + expect(harness.native.adapter.createProvider).not.toHaveBeenCalled(); + expect(harness.native.adapter.updateProvider).not.toHaveBeenCalled(); expect(harness.verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); - expect(harness.verifyInferenceRoute).toHaveBeenCalledWith( - GATEWAY, - "compatible-endpoint", - model, - ); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); expectCommandsTargetOnly(harness.commands); }); }); diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index a4dc57230d2..2b37bdcfdf7 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeLocalSetupReceipt } from "../support/native-local-setup-harness"; +import type { NativeLocalProviderAttachment } from "../../src/lib/inference/native-local/contract"; import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import fs from "node:fs"; @@ -657,14 +659,17 @@ const { onboard } = require(${onboardPath}); : undefined, overrides: { applyLocalInferenceRoute }, }); - await harness.setupInference("test-box", "meta-llama", "vllm-local"); - const providerCommand = harness.commands.find((entry) => - entry.command.includes("provider create"), - ); - assert.ok(providerCommand, "expected local vLLM provider create command"); - assert.match(providerCommand.command, /--credential NEMOCLAW_VLLM_LOCAL_TOKEN/); - assert.doesNotMatch(providerCommand.command, /--credential OPENAI_API_KEY/); - assert.equal(providerCommand.env?.NEMOCLAW_VLLM_LOCAL_TOKEN, "dummy"); + await harness.setupInference("test-box", "meta-llama", "vllm-local", null, null, null, [], { + agentName: "langchain-deepagents-code", + }); + const providerRequest = harness.native.adapter.createProvider.mock.calls[0]?.[0]; + assert.ok(providerRequest, "expected native local vLLM provider creation"); + assert.deepEqual(providerRequest.credentials, [ + { name: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", value: "dummy" }, + ]); + assert.ok(!providerRequest.credentials.some(({ name }) => name === "OPENAI_API_KEY")); + assert.deepEqual(providerRequest.config, []); + assert.deepEqual(harness.commands, []); assert.equal(credentials.getCredential("OPENAI_API_KEY"), "sk-existing"); }); } finally { @@ -699,27 +704,27 @@ const { onboard } = require(${onboardPath}); }); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { - await harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"); + await harness.setupInference("test-box", "qwen3.5:9b", "ollama-local", null, null, null, [], { + agentName: "openclaw", + }); } finally { warn.mockRestore(); } assert.deepEqual(proxyCalls, ["ensure", "healthy", "persist:proxy-token"]); - const providerCommand = harness.commands.find( - (entry) => - entry.command.includes("provider create") && entry.command.includes("ollama-local"), - ); - assert.ok(providerCommand, "expected ollama-local provider create command"); - assert.match(providerCommand.command, /--credential NEMOCLAW_OLLAMA_PROXY_TOKEN/); - assert.equal(providerCommand.env?.NEMOCLAW_OLLAMA_PROXY_TOKEN, "proxy-token"); - assert.doesNotMatch(providerCommand.command, /proxy-token/); - assert.ok( - harness.commands.some((entry) => - entry.command.includes("inference set -g nemoclaw --no-verify --provider ollama-local"), - ), - "expected ollama-local inference route to be selected", - ); + const providerRequest = harness.native.adapter.createProvider.mock.calls[0]?.[0]; + assert.ok(providerRequest, "expected native Ollama provider creation"); + assert.deepEqual(providerRequest.credentials, [ + { name: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", value: "proxy-token" }, + ]); + assert.deepEqual(providerRequest.config, []); + expect(harness.native.profiles[0]).toMatchObject({ + endpoints: [{ host: "host.openshell.internal", port: 11435 }], + }); + assert.ok(!JSON.stringify(harness.native.profiles).includes("proxy-token")); + assert.deepEqual(harness.commands, []); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); }); - it("surfaces a contextual error and exits when ollama-local inference set fails after the proxy-ready warning (#4257)", async () => { + it("rejects ollama-local native registration failure before sandbox reservation (#4257)", async () => { const error = vi.fn(); const exitProcess = vi.fn((code: number): never => { throw Object.assign(new Error(`EXIT_CALLED:${code}`), { __exit: true }); @@ -755,31 +760,31 @@ const { onboard } = require(${onboardPath}); exitProcess, }, }); + harness.native.adapter.createProvider.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "failed", message: "native provider registration denied" }, + }); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { await assert.rejects( - harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"), - (error: Error & { __exit?: boolean }) => error.__exit === true, + harness.setupInference("test-box", "qwen3.5:9b", "ollama-local", null, null, null, [], { + agentName: "openclaw", + }), + /native provider registration denied/, ); } finally { warn.mockRestore(); } - const setCmd = harness.commands.find((entry) => - entry.command.includes("inference set -g nemoclaw --no-verify --provider ollama-local"), - ); - assert.ok(setCmd, "expected ollama-local inference set command to be issued"); - assert.equal( - setCmd.ignoreError, - true, - "ollama-local inference set must use ignoreError so onboard can recover", - ); - const combinedErr = error.mock.calls.flat().join("\n"); - assert.equal(exitProcess.mock.calls.length, 1); - assert.equal(exitProcess.mock.calls[0]?.[0], 7); - assert.match(combinedErr, /No sandbox was created/); - assert.match(combinedErr, /nemoclaw onboard --resume/); + expect(harness.native.adapter.createProvider).toHaveBeenCalledOnce(); + expect(harness.native.authorities.size).toBe(0); + expect(harness.updateSandbox).not.toHaveBeenCalled(); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); + expect(harness.verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); + expect(exitProcess).not.toHaveBeenCalled(); + expect(commandRouter.callCount("ollama-inference-set")).toBe(0); + // Shared-route exit status and resume guidance remain covered by local-inference-route.test.ts. }); - it("surfaces a contextual error and exits when vllm-local inference set fails (#4257)", async () => { + it("rejects vllm-local native registration failure before sandbox reservation (#4257)", async () => { const exitProcess = vi.fn((code: number): never => { throw Object.assign(new Error(`EXIT_CALLED:${code}`), { __exit: true }); }); @@ -804,25 +809,25 @@ const { onboard } = require(${onboardPath}); }, }); + harness.native.adapter.createProvider.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "failed", message: "native provider registration denied" }, + }); await assert.rejects( - harness.setupInference("test-box", "meta-llama", "vllm-local"), - (error: Error & { __exit?: boolean }) => error.__exit === true, + harness.setupInference("test-box", "meta-llama", "vllm-local", null, null, null, [], { + agentName: "openclaw", + }), + /native provider registration denied/, ); - const setCmd = harness.commands.find((entry) => - entry.command.includes("inference set -g nemoclaw --no-verify --provider vllm-local"), - ); - assert.ok(setCmd, "expected vllm-local inference set command to be issued"); - assert.equal( - setCmd.ignoreError, - true, - "vllm-local inference set must use ignoreError so onboard can recover", - ); - const combinedErr = harness.errors.join("\n"); - assert.equal(exitProcess.mock.calls.length, 1); - assert.equal(exitProcess.mock.calls[0]?.[0], 13); - assert.match(combinedErr, /No sandbox was created/); - assert.match(combinedErr, /nemoclaw onboard --resume/); + expect(harness.native.adapter.createProvider).toHaveBeenCalledOnce(); + expect(harness.native.authorities.size).toBe(0); + expect(harness.updateSandbox).not.toHaveBeenCalled(); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); + expect(harness.verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); + expect(exitProcess).not.toHaveBeenCalled(); + expect(commandRouter.callCount("vllm-inference-set")).toBe(0); + // Shared-route exit status and resume guidance remain covered by local-inference-route.test.ts. }); it("detects when the live inference route already matches the requested provider and model", () => { const repoRoot = path.join(import.meta.dirname, "../.."); @@ -1074,11 +1079,20 @@ describe("re-onboard Ollama GPU release (#9110)", () => { provider: string; model: string; endpointUrl?: string | null; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; }; + const priorAttachment = nativeLocalSetupReceipt({ + provider: "ollama-local", + endpointUrl: "http://host.openshell.internal:11435/v1", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: "test-box", + }); const priorEntry: ReleaseEntry = { name: "test-box", provider: "ollama-local", model: "llama3", + nativeLocalProviderAttachment: priorAttachment, }; function releaseHarness(options: { @@ -1095,7 +1109,7 @@ describe("re-onboard Ollama GPU release (#9110)", () => { releasedModels?: readonly string[], ) => void; }) { - return createDirectSetupInferenceHarness({ + const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { status: 1, stdout: "", stderr: "" } @@ -1127,6 +1141,8 @@ describe("re-onboard Ollama GPU release (#9110)", () => { }, }, }); + harness.native.seed(priorAttachment); + return harness; } it("releases the superseded model after a re-onboard onto a different model (#9110)", async () => { @@ -1418,6 +1434,7 @@ describe("re-onboard Ollama GPU release (#9110)", () => { }, }, }); + harness.native.seed(priorAttachment); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { await harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"); @@ -1427,6 +1444,7 @@ describe("re-onboard Ollama GPU release (#9110)", () => { // A serialized re-onboard can neither replace the row under the read nor // select the captured model before this cleanup runs. expect(events).toEqual([ + "read-prior-route", // Agent support admission; cleanup reads the route again under the lock. "lock-enter", "read-prior-route", "ownership-lock-enter", @@ -1437,22 +1455,28 @@ describe("re-onboard Ollama GPU release (#9110)", () => { ]); }); - it("skips the release when the route returns to selection (#9110)", async () => { + it("skips the release when endpoint rejection returns to selection (#9110)", async () => { const unloadOllamaModels = vi.fn<(onlyModels: readonly string[]) => void>(); const harness = releaseHarness({ getSandbox: () => priorEntry, sandboxes: [priorEntry], unloadOllamaModels, - applyLocalInferenceRoute: async () => true, }); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); let result: Awaited>; try { - result = await harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"); + result = await harness.setupInference( + "test-box", + "new-model", + "compatible-endpoint", + "http://169.254.169.254/v1", + ); } finally { warn.mockRestore(); } assert.deepEqual(result, { retry: "selection" }); expect(unloadOllamaModels).not.toHaveBeenCalled(); + expect(harness.updateSandbox).not.toHaveBeenCalled(); + expect(harness.commands).toEqual([]); }); }); diff --git a/test/onboarding/onboard-native-provider-reservation.test.ts b/test/onboarding/onboard-native-provider-reservation.test.ts new file mode 100644 index 00000000000..e78d8287106 --- /dev/null +++ b/test/onboarding/onboard-native-provider-reservation.test.ts @@ -0,0 +1,182 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { nativeLocalSetupReceipt } from "../support/native-local-setup-harness"; +import { createDirectSetupInferenceHarness } from "../helpers/onboard-split-context"; + +const testHome = await vi.hoisted(async () => { + const fs = await import("node:fs"); + const os = await import("node:os"); + const path = await import("node:path"); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "native-reservation-")); + vi.stubEnv("HOME", directory); + return directory; +}); + +beforeEach((context) => { + vi.stubEnv("HOME", testHome); + fs.mkdirSync(testHome, { recursive: true }); + context.onTestFinished(() => { + vi.unstubAllEnvs(); + fs.rmSync(testHome, { recursive: true, force: true }); + }); +}); + +describe("native provider ownership before route reservation", () => { + it("retires an unreserved provider after host smoke fails (#12558)", async () => { + const harness = createDirectSetupInferenceHarness({ + overrides: { + isNonInteractive: () => true, + applyLocalInferenceRoute: undefined, + verifyOnboardInferenceSmoke: async () => { + throw new Error("host smoke refused"); + }, + }, + }); + await expect( + harness.setupInference("test-box", "meta-llama", "vllm-local", null, null, null, [], { + agentName: "openclaw", + }), + ).rejects.toThrow("host smoke refused"); + expect(harness.native.adapter.createProvider).toHaveBeenCalledOnce(); + expect(harness.updateSandbox).not.toHaveBeenCalled(); + expect(harness.native.providers.size).toBe(0); + expect(harness.native.authorities.size).toBe(0); + }); +}); + +describe("native provider cleanup uncertainty", () => { + it("retains authority when deletion cannot be confirmed (#12558)", async () => { + const harness = createDirectSetupInferenceHarness({ + overrides: { + isNonInteractive: () => true, + applyLocalInferenceRoute: undefined, + verifyOnboardInferenceSmoke: async () => { + throw new Error("host smoke refused"); + }, + }, + }); + harness.native.adapter.deleteProvider.mockResolvedValue({ + ok: false, + error: { kind: "transport", reason: "connection_loss", message: "delete outcome unknown" }, + }); + await expect( + harness.setupInference("test-box", "meta-llama", "vllm-local", null, null, null, [], { + agentName: "openclaw", + }), + ).rejects.toThrow(/host smoke refused[\s\S]*cleanup was not confirmed/); + expect(harness.native.providers.size).toBe(1); + expect(harness.native.authorities.size).toBe(1); + }); + + it("retains authority after a failed reservation response (#12558)", async () => { + const harness = createDirectSetupInferenceHarness({ + overrides: { + isNonInteractive: () => true, + applyLocalInferenceRoute: undefined, + updateSandbox: () => { + throw new Error("reservation response lost"); + }, + }, + }); + await expect( + harness.setupInference("test-box", "meta-llama", "vllm-local", null, null, null, [], { + agentName: "openclaw", + }), + ).rejects.toThrow("reservation response lost"); + expect(harness.native.adapter.deleteProvider).not.toHaveBeenCalled(); + expect(harness.native.providers.size).toBe(1); + expect(harness.native.authorities.size).toBe(1); + }); + + it("keeps an existing selected provider after a pre-reservation failure (#12558)", async () => { + const existing = nativeLocalSetupReceipt({ + provider: "vllm-local", + sandboxName: "test-box", + gatewayName: "nemoclaw", + endpointUrl: "http://host.openshell.internal:8000/v1", + authMode: "sentinel", + }); + const harness = createDirectSetupInferenceHarness({ + overrides: { + isNonInteractive: () => true, + applyLocalInferenceRoute: undefined, + getSandbox: () => ({ + name: "test-box", + provider: "vllm-local", + nativeLocalProviderAttachment: existing, + }), + verifyOnboardInferenceSmoke: async () => { + throw new Error("host smoke refused"); + }, + }, + }); + harness.native.seed(existing); + await expect( + harness.setupInference("test-box", "meta-llama", "vllm-local", null, null, null, [], { + agentName: "openclaw", + }), + ).rejects.toThrow("host smoke refused"); + expect(harness.native.adapter.deleteProvider).not.toHaveBeenCalled(); + expect(harness.native.providers.size).toBe(1); + expect(harness.native.authorities.size).toBe(1); + }); +}); + +describe("native selection with published shared-route staging enabled", () => { + it.each([ + ["openclaw", "llama-cpp-local"], + ["openclaw", "compatible-endpoint"], + ["langchain-deepagents-code", "llama-cpp-local"], + ["langchain-deepagents-code", "compatible-endpoint"], + ])( + "reserves %s native %s ownership without changing the shared route (#12977)", + async (agentName, provider) => { + const port = provider === "llama-cpp-local" ? 8081 : 8000; + const endpointUrl = `http://127.0.0.1:${port}/v1`; + const harness = createDirectSetupInferenceHarness({ + overrides: { + isNonInteractive: () => true, + hydrateCredentialEnv: () => "fixture-local-key", + getSandbox: () => ({ + name: "test-box", + agent: agentName, + provider: "nvidia-prod", + model: "old-model", + gatewayName: "nemoclaw", + }), + }, + }); + const result = await harness.setupInference( + "test-box", + "new-model", + provider, + endpointUrl, + "LOCAL_KEY", + null, + [], + { agentName, deferPublishedRouteReservation: true, onboardEndpointUrl: endpointUrl }, + ); + expect(result).toEqual({ ok: true }); + expect(harness.updateSandbox).toHaveBeenCalledExactlyOnceWith( + "test-box", + expect.objectContaining({ + provider, + model: "new-model", + nativeLocalProviderAttachment: expect.objectContaining({ + provider, + endpointUrl: `http://host.openshell.internal:${port}/v1`, + gatewayName: "nemoclaw", + sandboxName: "test-box", + }), + }), + ); + expect(harness.native.providers.size).toBe(1); + expect(harness.commands.filter(({ command }) => command.startsWith("inference set"))).toEqual( + [], + ); + }, + ); +}); diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index d3755dcfd8a..84bbbf7ba89 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -152,7 +152,7 @@ function writeSiblingRegistry( sandboxes: { alpha: { name: "alpha", - provider: "ollama-local", + provider: "nvidia-router", model: "nvidia/nemotron", agent: "openclaw", dashboardPort: 18_789, diff --git a/test/repository/cli-coverage-sequencer.test.ts b/test/repository/cli-coverage-sequencer.test.ts index 18fc771cb6f..a3c7ab2f5d3 100644 --- a/test/repository/cli-coverage-sequencer.test.ts +++ b/test/repository/cli-coverage-sequencer.test.ts @@ -132,7 +132,7 @@ describe("stable CLI coverage sharding", () => { const weights = shards.map((shard) => shard.totalWeightMs); const averageWeight = weights.reduce((total, weight) => total + weight, 0) / weights.length; - expect(Math.max(...weights)).toBeLessThanOrEqual(averageWeight * 1.055); + expect(Math.max(...weights)).toBeLessThanOrEqual(averageWeight * 1.059); }); it("balances the serialized integration lane across the twelve CI shards (#6237)", () => { diff --git a/test/runtime/sandbox/sandbox-build-context.test.ts b/test/runtime/sandbox/sandbox-build-context.test.ts index 303e3414321..3fe3d5a57d0 100644 --- a/test/runtime/sandbox/sandbox-build-context.test.ts +++ b/test/runtime/sandbox/sandbox-build-context.test.ts @@ -271,6 +271,8 @@ describe("sandbox build context staging", () => { "inference-credential.ts", path.join("core", "json-types.ts"), path.join("core", "ports.ts"), + path.join("core", "endpoint-url-safety.ts"), + path.join("inference", "native-local", "agent-config.ts"), path.join("onboard", "managed-startup", "image-runtime.ts"), path.join("security", "credential-hash.ts"), path.join("state", "paths.ts"), @@ -520,6 +522,8 @@ describe("sandbox build context staging", () => { path.join("src", "lib", "inference-credential.ts"), path.join("src", "lib", "core", "json-types.ts"), path.join("src", "lib", "core", "ports.ts"), + path.join("src", "lib", "core", "endpoint-url-safety.ts"), + path.join("src", "lib", "inference", "native-local", "agent-config.ts"), path.join("src", "lib", "onboard", "managed-startup", "image-runtime.ts"), path.join("src", "lib", "security", "credential-hash.ts"), path.join("src", "lib", "state", "paths.ts"), diff --git a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts index 157d4b6a612..461e0ff314f 100644 --- a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts +++ b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts @@ -5,7 +5,11 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; -import { dockerRunCommandBetween, runLoggedDockerShell } from "../../helpers/dockerfile-run-shell"; +import { + dockerRunCommandBetween, + runLoggedDockerShell, + shellCommandSegmentBetween, +} from "../../helpers/dockerfile-run-shell"; const ROOT = path.resolve(import.meta.dirname, "../../.."); const DOCKERFILE = path.join(ROOT, "Dockerfile"); @@ -100,6 +104,8 @@ describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () toolDisclosurePath, applierPath, messagingHookPath, + path.join(localSrc, "lib/core/endpoint-url-safety.ts"), + path.join(localSrc, "lib/inference/native-local/agent-config.ts"), pluginFile, nestedPluginFile, ]; @@ -112,6 +118,7 @@ describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () fs.mkdirSync(path.dirname(applierPath), { recursive: true }); fs.mkdirSync(path.dirname(messagingHookPath), { recursive: true }); files.forEach((file) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, "# fixture\n", { mode: 0o600 }); fs.chmodSync(file, 0o600); }); @@ -169,3 +176,60 @@ describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () } }); }); + +it.each([ + { + agent: "OpenClaw cached install", + marker: "COPY --from=openclaw-runtime-payload /scripts/ /scripts/", + dockerfile: "Dockerfile", + start: "chmod 444 /src/lib/*.ts /src/lib/inference/native-local/agent-config.ts", + file: "/src/lib/inference/native-local/agent-config.ts", + }, + { + agent: "OpenClaw runtime", + marker: "# Copy startup script and shared sandbox initialisation library", + dockerfile: "Dockerfile", + start: "chmod 444 /src/lib/*.ts", + file: "/src/lib/inference/native-local/agent-config.ts", + }, + { + agent: "DCode", + marker: "# Copy the managed-startup entrypoint", + dockerfile: "agents/langchain-deepagents-code/Dockerfile", + start: "chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts", + file: "/opt/nemoclaw-deepagents-code/src/lib/inference/native-local/agent-config.ts", + }, + { + agent: "DCode helper", + marker: "# Copy the managed-startup entrypoint", + dockerfile: "agents/langchain-deepagents-code/Dockerfile", + start: "chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts", + file: "/opt/nemoclaw-deepagents-code/src/lib/core/endpoint-url-safety.ts", + }, +])( + "makes the native config dependency read-only for $agent from private checkout modes (#12558)", + ({ dockerfile, marker, start, file }) => { + const source = fs.readFileSync(path.join(ROOT, dockerfile), "utf8"); + const command = shellCommandSegmentBetween( + source.slice(source.indexOf(marker)).replaceAll(/\\\n\s*/gu, " "), + start, + "&&", + ); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "native-config-mode-")); + try { + const operands = command + .split(/\s+/u) + .slice(2) + .map((operand) => operand.replace("*.ts", "fixture.ts")); + const files = [...operands, file].map((operand) => path.join(tmp, operand)); + const directories = files.map((operand) => path.dirname(operand)); + const setup = `mkdir -p ${directories.join(" ")} && touch ${files.join(" ")} && chmod 600 ${files.join(" ")}`; + const rewritten = command.replaceAll(/ \/(?=opt|src|scripts|usr|etc|ci)/gu, ` ${tmp}/`); + const { result } = runLoggedDockerShell(`${setup} && ${rewritten}`, tmp); + expect(result.status, result.stderr).toBe(0); + expect(fs.statSync(path.join(tmp, file)).mode & 0o777).toBe(0o444); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }, +); diff --git a/test/support/native-local-export-fixture.ts b/test/support/native-local-export-fixture.ts new file mode 100644 index 00000000000..e9095cd4bc0 --- /dev/null +++ b/test/support/native-local-export-fixture.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { vi } from "vitest"; +import { raw } from "./config-export-harness"; +import { + nativeNvidiaProfile, + inventory, + readFailureCanary, +} from "../../src/lib/adapters/config/live-export-source-test-fixture"; +import { + nativeLocalIdentity, + NATIVE_LOCAL_CREDENTIAL_ENV, + type NativeLocalBinding, +} from "../../src/lib/inference/native-local/contract"; +import { prepareNativeLocalProfile } from "../../src/lib/inference/native-local/profile"; +import type { SandboxEntry } from "../../src/lib/state/registry/types"; + +/** Replace the existing local source's live provider with its native attachment. */ +export function attachNativeLocalExportFixture(source: SandboxEntry) { + const binding: NativeLocalBinding = { + provider: source.provider as "ollama-local" | "vllm-local", + endpointUrl: source.endpointUrl!, + credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV, + authMode: "authenticated", + gatewayName: source.gatewayName!, + sandboxName: source.name, + }; + const receipt = { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "native-local-id", + }; + source.nativeLocalProviderAttachment = receipt; + const readCredential = vi.fn(() => { + throw new Error(readFailureCanary); + }); + const provider = { + metadata: { + id: receipt.providerId, + name: receipt.providerName, + workspace: "default", + resourceVersion: 8n, + }, + type: receipt.profileId, + profileWorkspace: "default", + credentials: Object.defineProperty({}, NATIVE_LOCAL_CREDENTIAL_ENV, { + enumerable: true, + get: readCredential, + }), + config: {}, + }; + const profile = nativeNvidiaProfile(); + profile.id = receipt.profileId; + profile.credentials = [ + { + name: "api_key", + envVars: [NATIVE_LOCAL_CREDENTIAL_ENV], + required: true, + authStyle: "bearer", + headerName: "authorization", + queryParam: "", + pathTemplate: "", + }, + ]; + const endpoint = (profile.endpoints as Record[])[0]!; + const url = new URL(binding.endpointUrl); + Object.assign(endpoint, { + host: url.hostname, + port: Number(url.port), + allowedIps: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], + }); + profile.binaries = prepareNativeLocalProfile(binding).document.binaries.map((path) => ({ path })); + const sandbox = inventory(); + Object.assign(sandbox.sandbox.spec, { providers: [receipt.providerName] }); + raw.getSandbox.mockResolvedValue(sandbox); + raw.getProvider.mockResolvedValue({ provider }); + raw.getProviderProfile.mockResolvedValue({ profile }); + return { receipt, provider, profile, endpoint, readCredential }; +} diff --git a/test/support/native-local-setup-harness.ts b/test/support/native-local-setup-harness.ts new file mode 100644 index 00000000000..4303b4e15fb --- /dev/null +++ b/test/support/native-local-setup-harness.ts @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { vi } from "vitest"; +import type { + OpenShellProviderAdapter, + OpenShellProviderMetadata, +} from "../../src/lib/adapters/openshell/provider-adapter"; +import { + nativeLocalIdentity, + NATIVE_LOCAL_CREDENTIAL_ENV, + type NativeLocalBinding, + type NativeLocalProviderAttachment, +} from "../../src/lib/inference/native-local/contract"; + +export function nativeLocalSetupReceipt( + binding: Omit, +): NativeLocalProviderAttachment { + const selected = { ...binding, credentialEnv: NATIVE_LOCAL_CREDENTIAL_ENV }; + const identity = nativeLocalIdentity(selected); + return { + ...selected, + ...identity, + schemaVersion: 1, + providerId: `fixture-${identity.providerName}`, + }; +} + +/** Stateful provider boundary; production selection and ownership checks still execute. */ +export function createNativeLocalSetupHarness() { + const providers = new Map(); + const authorities = new Map(); + const profiles: Record[] = []; + const unsupported = () => { + throw new Error("Unexpected native setup adapter operation"); + }; + const adapter = { + ensureProviderPolicyComposition: vi.fn(unsupported), + importProviderProfile: vi.fn( + async ({ profilePath }) => { + profiles.push(JSON.parse(fs.readFileSync(profilePath, "utf8"))); + return { ok: true }; + }, + ), + getProvider: vi.fn( + async ({ target, providerName }) => { + const value = providers.get(JSON.stringify([target, providerName])); + return value + ? { ok: true, value } + : { ok: false, error: { kind: "command", reason: "not_found", message: "absent" } }; + }, + ), + createProvider: vi.fn(async (request) => { + providers.set(JSON.stringify([request.target, request.name]), { + name: request.name, + type: request.type, + credentialKeys: request.credentials.map(({ name }) => name), + configKeys: request.config.map(({ key }) => key), + revision: { id: `fixture-${request.name}`, resourceVersion: 1 }, + }); + return { ok: true }; + }), + updateProvider: vi.fn(async (request) => { + const key = JSON.stringify([request.target, request.providerName]); + const previous = providers.get(key); + if (!previous) + return { ok: false, error: { kind: "command", reason: "not_found", message: "absent" } }; + providers.set(key, { + ...previous, + credentialKeys: request.credentials.map(({ name }) => name), + revision: { + id: previous.revision!.id, + resourceVersion: previous.revision!.resourceVersion + 1, + }, + }); + return { ok: true }; + }), + deleteProvider: vi.fn( + async ({ target, providerName }) => { + providers.delete(JSON.stringify([target, providerName])); + return { ok: true }; + }, + ), + inspectProviderProfile: vi.fn(unsupported), + listProviders: vi.fn(unsupported), + listProviderAttachments: vi.fn(unsupported), + attachProvider: vi.fn(unsupported), + detachProvider: vi.fn(unsupported), + configureProviderRefresh: vi.fn(unsupported), + getProviderRefreshStatus: vi.fn(unsupported), + } satisfies OpenShellProviderAdapter; + return { + seed(receipt: NativeLocalProviderAttachment) { + authorities.set(receipt.providerName, receipt); + providers.set( + JSON.stringify([{ kind: "named", gatewayName: receipt.gatewayName }, receipt.providerName]), + { + name: receipt.providerName, + type: receipt.profileId, + credentialKeys: [receipt.credentialEnv], + configKeys: [], + revision: { id: receipt.providerId, resourceVersion: 1 }, + }, + ); + }, + adapter, + providers, + authorities, + profiles, + getNativeLocalProviderAuthority: (name: string) => authorities.get(name), + clearNativeLocalProviderAuthority: (receipt: NativeLocalProviderAttachment) => { + const current = authorities.get(receipt.providerName); + if (current?.providerId !== receipt.providerId) throw new Error("Fixture authority changed"); + authorities.delete(receipt.providerName); + }, + setNativeLocalProviderAuthority: (receipt: NativeLocalProviderAttachment) => { + authorities.set(receipt.providerName, receipt); + }, + }; +} + +/** Exercise the real policy parser without contacting a developer gateway. */ +export async function withNativePolicyFixture(operation: () => Promise): Promise { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-setup-policy-")); + const executable = path.join(directory, "openshell"); + const previous = process.env.NEMOCLAW_OPENSHELL_BIN; + fs.writeFileSync( + executable, + `#!/bin/sh +set -eu +if [ "$#" = 6 ] && [ "$1" = settings ] && [ "$2" = get ] && [ "$3" = -g ] && [ "$5" = --global ] && [ "$6" = --json ]; then + printf '%s\\n' '{"scope":"global","settings":{"providers_v2_enabled":"true"}}' +elif [ "$#" = 7 ] && [ "$1" = policy ] && [ "$2" = list ] && [ "$3" = -g ] && [ "$5" = --global ] && [ "$6" = --limit ] && [ "$7" = 1 ]; then + printf '%s\\n' 'No global policy history found' >&2 +else + echo 'Unexpected policy fixture command' >&2 + exit 1 +fi +`, + { mode: 0o700 }, + ); + process.env.NEMOCLAW_OPENSHELL_BIN = executable; + try { + return await operation(); + } finally { + if (previous === undefined) delete process.env.NEMOCLAW_OPENSHELL_BIN; + else process.env.NEMOCLAW_OPENSHELL_BIN = previous; + fs.rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 39dca3365cd..fa4a61eb342 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -13,6 +13,11 @@ import { type SetupInference, type SetupInferenceDeps, } from "../../src/lib/onboard/setup-inference.js"; +import { usesNativeLocalInference } from "../../src/lib/inference/native-local/contract"; +import { + createNativeLocalSetupHarness, + withNativePolicyFixture, +} from "./native-local-setup-harness"; import { redact } from "../../src/lib/security/redact.js"; const onboardProviderHelpers = require("../../src/lib/onboard/providers") as { @@ -421,7 +426,7 @@ export function createDirectSetupInferenceHarnessFactory( } return directRunResult(); }; - const setupInferenceWithoutPolicyAuthority = createSetupInference({ + const harnessDeps: Partial = { checkGatewayRouteCompatibility: () => ({ ok: true }), withGatewayRouteMutationLock: async ( _gatewayName: string, @@ -544,6 +549,16 @@ export function createDirectSetupInferenceHarnessFactory( unloadOllamaModels, withOllamaModelOwnershipLock: (operation) => operation(), ...options.overrides, + }; + const setupInferenceWithoutPolicyAuthority = createSetupInference(harnessDeps); + const native = createNativeLocalSetupHarness(); + const setupNativeInference = createSetupInference({ + ...harnessDeps, + providerAdapter: native.adapter, + getNativeLocalProviderAuthority: native.getNativeLocalProviderAuthority, + setNativeLocalProviderAuthority: native.setNativeLocalProviderAuthority, + clearNativeLocalProviderAuthority: native.clearNativeLocalProviderAuthority, + ...options.overrides, }); const revalidateSandboxIdentity = vi.fn(); const setupInference: SetupInference = ( @@ -555,22 +570,27 @@ export function createDirectSetupInferenceHarnessFactory( hermesAuthMethod, hermesToolGateways, inferenceOptions = {}, - ) => - setupInferenceWithoutPolicyAuthority( - sandboxName, - model, - provider, - endpointUrl, - credentialEnv, - hermesAuthMethod, - hermesToolGateways, - { - ...inferenceOptions, - revalidateSandboxIdentity: - inferenceOptions.revalidateSandboxIdentity ?? revalidateSandboxIdentity, - }, - ); + ) => { + const nativeLocal = usesNativeLocalInference(provider, endpointUrl); + const operation = () => + (nativeLocal ? setupNativeInference : setupInferenceWithoutPolicyAuthority)( + sandboxName, + model, + provider, + endpointUrl, + credentialEnv, + hermesAuthMethod, + hermesToolGateways, + { + ...inferenceOptions, + revalidateSandboxIdentity: + inferenceOptions.revalidateSandboxIdentity ?? revalidateSandboxIdentity, + }, + ); + return nativeLocal ? withNativePolicyFixture(operation) : operation(); + }; return { + native, commands, errors, logs,