From 57fd4ef15638ea03de8a6158a5e5c2d74d475b58 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:05:46 -0700 Subject: [PATCH 01/45] feat(inference): attach native local providers for OpenClaw and DCode Refs #12975 Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- Dockerfile | 19 +- agents/langchain-deepagents-code/Dockerfile | 3 +- .../dcode-wrapper.sh | 9 +- .../generate-config.ts | 19 +- .../managed-dcode-runtime.py | 20 + .../src/shared/credential-filter-boundary.cts | 1 + .../shared/credential-filter-boundary.test.ts | 13 + scripts/generate-openclaw-config.mts | 6 +- .../inference-set-context-window.test.ts | 8 +- .../inference-set-degraded-state.test.ts | 2 +- .../inference-set-live-rollback.test.ts | 184 ++++++- .../inference-set-local-provider.test.ts | 45 +- ...erence-set-native-local-retirement.test.ts | 162 ++++++ .../inference-set-native-local.test.ts | 270 ++++++++++ .../inference-set-no-auth-compatible.test.ts | 442 +++------------- .../inference-set-provider-diagnostics.ts | 30 ++ src/lib/actions/inference-set-provider.ts | 50 ++ src/lib/actions/inference-set.test-support.ts | 95 ++++ src/lib/actions/inference-set.ts | 264 +++++++--- src/lib/actions/inference/native-local.ts | 231 ++++++++ .../managed-workload-rebuild-profile.ts | 1 + src/lib/actions/sandbox/connect.ts | 7 +- src/lib/actions/sandbox/destroy-execution.ts | 23 +- .../sandbox/destroy-native-local.test.ts | 106 ++++ src/lib/actions/sandbox/destroy.ts | 7 + .../actions/sandbox/doctor-inference.test.ts | 56 ++ src/lib/actions/sandbox/doctor-inference.ts | 93 +++- .../doctor-observation-failure.test.ts | 62 ++- src/lib/actions/sandbox/doctor.ts | 12 +- .../inference-invocation-probe.test.ts | 146 +++++- .../sandbox/inference-invocation-probe.ts | 27 +- .../actions/sandbox/inference-route-health.ts | 41 ++ src/lib/actions/sandbox/launch-readiness.ts | 4 +- .../sandbox/launch-readiness/health.ts | 33 +- .../sandbox/rebuild-dcode-target.test.ts | 49 ++ .../actions/sandbox/rebuild-dcode-target.ts | 13 + .../sandbox/rebuild-resume-config.test.ts | 56 ++ .../actions/sandbox/rebuild-resume-config.ts | 13 + src/lib/actions/sandbox/start.test.ts | 49 ++ src/lib/actions/sandbox/start.ts | 3 + .../status-snapshot-inference-health.test.ts | 107 ++++ src/lib/actions/sandbox/status-snapshot.ts | 96 +++- .../config/live-export-source-ollama.test.ts | 102 +++- .../config/live-export-source-test-fixture.ts | 7 +- .../config/live-export-source-vllm.test.ts | 19 + src/lib/adapters/config/live-export-source.ts | 32 +- ...s => native-inference-profile-response.ts} | 97 +++- .../openshell/provider-adapter-cli.ts | 11 + .../adapters/openshell/provider-adapter.ts | 3 + .../openshell/provider-policy.test-support.ts | 35 ++ .../openshell/provider-policy.test.ts | 173 ++++++ src/lib/adapters/openshell/provider-policy.ts | 125 +++++ src/lib/adapters/openshell/providers.ts | 49 +- src/lib/domain/config/export-evidence.ts | 29 +- src/lib/domain/config/verify-export-source.ts | 121 +++-- src/lib/inference/config.test.ts | 15 + src/lib/inference/config.ts | 22 +- .../inference/gateway-route-compatibility.ts | 2 + .../gateway/local-endpoint-ports.test.ts | 42 ++ .../inference/gateway/local-endpoint-ports.ts | 23 + src/lib/inference/gateway/route-contract.ts | 3 +- src/lib/inference/native-local.test.ts | 375 +++++++++++++ .../inference/native-local/agent-config.ts | 45 ++ src/lib/inference/native-local/contract.ts | 192 +++++++ src/lib/inference/native-local/profile.ts | 189 +++++++ src/lib/inference/native-local/selection.ts | 119 +++++ src/lib/inference/native-nvidia/index.ts | 493 ++++-------------- .../native-provider-policy-separation.test.ts | 139 +++++ .../inference/native-provider/lifecycle.ts | 489 +++++++++++++++++ src/lib/onboard.ts | 4 +- .../compatible-endpoint-smoke-helpers.ts | 176 +++++++ .../onboard/compatible-endpoint-smoke.test.ts | 306 +++++------ src/lib/onboard/compatible-endpoint-smoke.ts | 142 +++-- .../created-sandbox-finalization.test.ts | 167 +++--- .../onboard/created-sandbox-finalization.ts | 17 +- ...d-sandbox-selection-reconciliation.test.ts | 136 +++++ src/lib/onboard/dcode-selection-drift.test.ts | 25 + src/lib/onboard/dcode-selection-drift.ts | 7 +- .../onboard/docker-driver-gateway-config.ts | 16 + src/lib/onboard/dockerfile-patch.ts | 2 + ...ckerfile-remote-dashboard-bind-contract.ts | 4 + .../onboard/gateway/docker-driver-start.ts | 46 +- .../onboard/gateway/native-creation.test.ts | 112 ++++ src/lib/onboard/gateway/native-creation.ts | 93 ++++ .../gateway/native-provider-bootstrap.test.ts | 158 ++++++ .../compatible-endpoint-gateway-route.ts | 17 +- src/lib/onboard/inference-providers/index.ts | 12 + src/lib/onboard/inference-providers/remote.ts | 24 +- src/lib/onboard/inference-providers/types.ts | 1 + src/lib/onboard/machine/handlers/policies.ts | 35 +- .../provider-inference-selected-agent.test.ts | 69 +++ .../handlers/provider-inference.test.ts | 1 + .../machine/handlers/provider-inference.ts | 12 +- .../machine/handlers/sandbox-dcode-resume.ts | 2 +- src/lib/onboard/machine/handlers/sandbox.ts | 19 +- .../managed-workload-clone-handoff.test.ts | 22 + .../native-local-startup-route.test.ts | 97 ++++ .../managed-workload/onboard-orchestration.ts | 11 +- .../host-local-inference-routing.ts | 4 + .../sandbox-create-intent-resolution.ts | 4 + .../onboard/sandbox-create-intent-types.ts | 4 + src/lib/onboard/sandbox-create-intent.ts | 6 +- .../onboard/sandbox-create/orchestration.ts | 25 +- .../sandbox-create/provider-publication.ts | 17 + .../sandbox-create/provider-retirement.ts | 13 + src/lib/onboard/sandbox-registration.test.ts | 38 ++ src/lib/onboard/sandbox-registration.ts | 31 +- src/lib/onboard/setup-inference.ts | 208 ++++++-- src/lib/onboard/workload/clone.ts | 5 + src/lib/sandbox/build-context.ts | 1 + src/lib/security/credential-filter.test.ts | 27 + src/lib/security/credential-filter.ts | 4 + ...egistry-native-provider-attachment.test.ts | 176 +++++++ src/lib/state/registry.ts | 39 ++ .../native-local-provider-authority.ts | 55 ++ src/lib/state/registry/persistence.ts | 14 + src/lib/state/registry/route-reservation.ts | 29 ++ src/lib/state/registry/types.ts | 6 + .../deepagents/dcode-start-keepalive.test.ts | 38 ++ .../langchain-deepagents-code-config.test.ts | 16 + ...-deepagents-code-image-credentials.test.ts | 48 ++ .../langchain-deepagents-code-image.test.ts | 2 +- ...epagents-code-managed-model-params.test.ts | 58 +++ test/helpers/destroy-flow-test-harness.ts | 10 + .../onboard-gateway-prelaunch-cutover.test.ts | 3 + ...board-host-local-inference-routing.test.ts | 160 +++--- .../onboard-inference-gateway-scope.test.ts | 62 ++- .../onboard-inference-reconciliation.test.ts | 131 +++-- ...nboard-native-provider-reservation.test.ts | 107 ++++ .../sandbox/sandbox-build-context.test.ts | 2 + ...ox-provisioning-helper-permissions.test.ts | 65 ++- test/support/native-local-export-fixture.ts | 81 +++ test/support/native-local-setup-harness.ts | 153 ++++++ test/support/setup-inference-test-harness.ts | 52 +- 134 files changed, 7693 insertions(+), 1562 deletions(-) create mode 100644 src/lib/actions/inference-set-native-local-retirement.test.ts create mode 100644 src/lib/actions/inference-set-native-local.test.ts create mode 100644 src/lib/actions/inference/native-local.ts create mode 100644 src/lib/actions/sandbox/destroy-native-local.test.ts rename src/lib/adapters/openshell/{native-nvidia-profile-response.ts => native-inference-profile-response.ts} (59%) create mode 100644 src/lib/adapters/openshell/provider-policy.test-support.ts create mode 100644 src/lib/adapters/openshell/provider-policy.test.ts create mode 100644 src/lib/adapters/openshell/provider-policy.ts create mode 100644 src/lib/inference/gateway/local-endpoint-ports.test.ts create mode 100644 src/lib/inference/gateway/local-endpoint-ports.ts create mode 100644 src/lib/inference/native-local.test.ts create mode 100644 src/lib/inference/native-local/agent-config.ts create mode 100644 src/lib/inference/native-local/contract.ts create mode 100644 src/lib/inference/native-local/profile.ts create mode 100644 src/lib/inference/native-local/selection.ts create mode 100644 src/lib/inference/native-provider-policy-separation.test.ts create mode 100644 src/lib/inference/native-provider/lifecycle.ts create mode 100644 src/lib/onboard/created-sandbox-selection-reconciliation.test.ts create mode 100644 src/lib/onboard/gateway/native-creation.test.ts create mode 100644 src/lib/onboard/gateway/native-creation.ts create mode 100644 src/lib/onboard/gateway/native-provider-bootstrap.test.ts create mode 100644 src/lib/onboard/machine/handlers/provider-inference-selected-agent.test.ts create mode 100644 src/lib/onboard/managed-workload/native-local-startup-route.test.ts create mode 100644 src/lib/onboard/sandbox-create/provider-retirement.ts create mode 100644 src/lib/state/registry/native-local-provider-authority.ts create mode 100644 test/onboarding/onboard-native-provider-reservation.test.ts create mode 100644 test/support/native-local-export-fixture.ts create mode 100644 test/support/native-local-setup-harness.ts diff --git a/Dockerfile b/Dockerfile index 35e5f333941..83e68001b06 100644 --- a/Dockerfile +++ b/Dockerfile @@ -696,10 +696,10 @@ COPY scripts/managed-startup-hold.sh /usr/local/bin/nemoclaw-managed-startup-hol COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/ COPY --from=runtime-preload-builder /opt/nemoclaw-root/dist/lib/messaging/channels/ /usr/local/lib/nemoclaw/preloads-compiled-channels/ COPY scripts/codex-acp-wrapper.sh /usr/local/bin/nemoclaw-codex-acp -COPY scripts/generate-openclaw-config.mts /scripts/ -COPY scripts/validate-openclaw-tool-search.mts /scripts/ +COPY scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ COPY --from=managed-startup-runtime-builder /out/managed-startup-image-runtime.cjs /usr/local/lib/nemoclaw/managed-startup-image-runtime.cjs COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts src/lib/inference-credential.ts /src/lib/ +COPY src/lib/inference/native-local/agent-config.ts /src/lib/inference/native-local/ 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/ @@ -1544,15 +1544,15 @@ RUN node /usr/local/lib/nemoclaw/patch-openclaw-shared-state-permissions.mts \ RUN mkdir -p /sandbox/.nemoclaw/blueprints/0.1.0 \ && cp -r /opt/nemoclaw-blueprint/* /sandbox/.nemoclaw/blueprints/0.1.0/ -# Copy configuration inputs before the cached non-messaging plugin install. -COPY scripts/generate-openclaw-config.mts /scripts/ -COPY scripts/validate-openclaw-tool-search.mts /scripts/ +# Config inputs precede the cached plugin install. +COPY scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts src/lib/inference-credential.ts /src/lib/ +COPY src/lib/inference/native-local/agent-config.ts /src/lib/inference/native-local/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ RUN chmod 755 /scripts/generate-openclaw-config.mts \ /scripts/validate-openclaw-tool-search.mts /src /src/lib \ - && chmod 444 /src/lib/*.ts \ + && 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 {} + \ @@ -1562,9 +1562,7 @@ RUN chmod 755 /scripts/generate-openclaw-config.mts \ # 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 @@ -1951,8 +1949,7 @@ RUN chmod 755 /usr/local/bin/nemoclaw-start /usr/local/bin/nemoclaw-codex-acp \ /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 \ + && 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 017bd503d66..93b2f416d43 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -156,6 +156,7 @@ 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/inference/native-local/agent-config.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-local/agent-config.ts COPY agents/langchain-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py COPY agents/langchain-deepagents-code/patch-managed-deepagents-code.py /opt/nemoclaw-deepagents-code/patch-managed-deepagents-code.py COPY agents/langchain-deepagents-code/patch-managed-quickjs.py /opt/nemoclaw-deepagents-code/patch-managed-quickjs.py @@ -189,7 +190,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/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 ac4fd25cab3..3faa91ca920 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 129744b2dbd..21d99521af2 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -6,6 +6,11 @@ // 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 { chmodSync, mkdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -161,9 +166,11 @@ function providerConfigLines( model: string, baseUrl: string, reasoningEffort: ReasoningEffort | null, + upstreamProvider: string, ): string[] { - 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 : MANAGED_INFERENCE_API_KEY_ENV; return [ @@ -198,7 +205,13 @@ function buildConfig(settings: Settings): ManagedDeepAgentsConfig { "[models]", `default = ${tomlString(defaultModel)}`, "", - ...providerConfigLines(provider, model, settings.baseUrl, settings.reasoningEffort), + ...providerConfigLines( + provider, + model, + settings.baseUrl, + settings.reasoningEffort, + settings.upstreamProvider, + ), "", "[update]", "check = false", diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index 38e2c0ef640..d331262d161 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -1080,6 +1080,26 @@ 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: + pass + if parsed.scheme == "http" and local_host and _managed_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": return "nemoclaw-managed-inference" name = "NVIDIA_INFERENCE_API_KEY" diff --git a/nemoclaw/src/shared/credential-filter-boundary.cts b/nemoclaw/src/shared/credential-filter-boundary.cts index 8089159e80c..41e53ff0e5c 100644 --- a/nemoclaw/src/shared/credential-filter-boundary.cts +++ b/nemoclaw/src/shared/credential-filter-boundary.cts @@ -132,6 +132,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 382d7dd61d6..b490edd232e 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("preserves a value that has no secret shape (#8291)", () => { expect(valueLooksLikeSecret("keep-me")).toBe(false); expect(stripCredentials({ model: "unused" })).toEqual({ model: "unused" }); diff --git a/scripts/generate-openclaw-config.mts b/scripts/generate-openclaw-config.mts index 81748bef221..d08b66108f5 100755 --- a/scripts/generate-openclaw-config.mts +++ b/scripts/generate-openclaw-config.mts @@ -27,6 +27,8 @@ // 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 { hasProviderlessInferenceEnvironment } from "../src/lib/providerless-inference.ts"; import { managedInferenceApiKey } from "../src/lib/inference-credential.ts"; @@ -974,7 +976,9 @@ export function buildConfig(env: Env = process.env): JsonObject { const providers = { [providerKey]: { baseUrl: inferenceBaseUrl, - apiKey: managedInferenceApiKey(inferenceBaseUrl, "unused"), + apiKey: + nativeLocalCredentialReference(env.NEMOCLAW_UPSTREAM_PROVIDER, inferenceBaseUrl) ?? + managedInferenceApiKey(inferenceBaseUrl, "unused"), api: inferenceApi, timeoutSeconds: agentTimeout, models: providerModels, diff --git a/src/lib/actions/inference-set-context-window.test.ts b/src/lib/actions/inference-set-context-window.test.ts index 5706278dd77..e4c1a6da49b 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 "./inference-set.test-support"; 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 bdd0aabc4a0..a776e319a86 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 500d28bebd7..d9a96244534 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 "./inference-set.test-support"; +import { + createCompatibleProviderCapture, + createDeps, + nativeLocalTestReceipt, + createFailingNativeLocalRestoreAdapter, +} from "./inference-set.test-support"; 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 e82d02b0272..987945a9efc 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 force --no-verify for 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..01b5da8231b --- /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 "./inference-set.test-support"; +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..067321af0e9 --- /dev/null +++ b/src/lib/actions/inference-set-native-local.test.ts @@ -0,0 +1,270 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +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("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("restore unavailable"); + }); +}); 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 c46126ccbf9..60e00841f23 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 "./inference-set.test-support"; -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,404 +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", - }); - expect( - deps.calls.updateSandbox.mock.calls - .filter(([, fields]) => fields.provider !== undefined) - .at(-1), - ).toEqual([ - "alpha", - expect.objectContaining({ - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - credentialEnv: NO_AUTH_CREDENTIAL_ENV, - preferredInferenceApi: "openai-completions", - }), - ]); - }); - - it("skips host-side verification when no endpoint options are passed", async () => { - const captureOpenshell = noAuthProviderCapture(); - const deps = createDeps({ - config: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - }); - - 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 })]); - }); - - it("keeps a recorded legacy no-auth route after the proxy port moves", async () => { - vi.stubEnv("NEMOCLAW_OLLAMA_PROXY_PORT", "12435"); - vi.resetModules(); - try { - const [{ runInferenceSet: runWithMovedProxy }, support] = await Promise.all([ - import("./inference-set"), - import("./inference-set.test-support"), - ]); - const endpointUrl = "http://127.0.0.1:11435/v1"; - const entry = { - ...noAuthEntry(), - endpointUrl, - } as SandboxEntry; - const session = support.baseSession({ - provider: "compatible-endpoint", - model: "model-a", - endpointUrl, - credentialEnv: NO_AUTH_CREDENTIAL_ENV, - preferredInferenceApi: "openai-completions", - }); - const captureOpenshell = support.createCompatibleProviderCapture({ - name: "compatible-endpoint", - type: "openai", - credentialEnv: NO_AUTH_CREDENTIAL_ENV, - configKey: "OPENAI_BASE_URL", - initiallyPresent: true, - }); - const deps = support.createDeps({ - config: { - agents: { defaults: { model: { primary: "inference/model-a" } } }, - models: { providers: { inference: { api: "openai-completions", models: [] } } }, - }, - entry, - session, - captureOpenshell, - }); - - await runWithMovedProxy({ provider: "compatible-endpoint", model: "model-b" }, deps); - - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - 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", - }); - expect( - deps.calls.updateSandbox.mock.calls - .filter(([, fields]) => fields.provider !== undefined) - .at(-1), - ).toEqual([ - "alpha", - 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([]); + ).rejects.toThrow("Recreate this beta sandbox"); + expect(deps.calls.captureOpenshell).not.toHaveBeenCalled(); 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 }); + 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: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, - probeSandboxRoute, + config: structuredClone(CONFIG), + entry, + session: baseSession(entry), }); - - await runInferenceSet( - { - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - }, - deps, + 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(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(resolve).not.toHaveBeenCalled(); + expect(deps.calls.captureOpenshell.mock.calls.some(([args]) => args[0] === "inference")).toBe( + false, ); - 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(deps.calls.probeSandboxRoute).toHaveBeenCalledWith( + expect.objectContaining({ + model: "model-b", + nativeLocalProviderAttachment: expect.objectContaining({ providerId: receipt.providerId }), + }), ); - - 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" }); + 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 expect( - runInferenceSet( - { - provider: "compatible-endpoint", - model: "model-b", - endpointUrl: NO_AUTH_ENDPOINT_URL, - }, - deps, - ), - ).rejects.toThrow(/malformed, foreign/); - - expect(providerMutationArgs(captureOpenshell)).toEqual([]); + 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("refuses to recreate a provider whose no-auth binding only onboarding can rebuild", async () => { - const captureOpenshell = noAuthProviderCapture({ initiallyPresent: false }); + 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: CONFIG, - entry: noAuthEntry(), - session: noAuthSession(), - captureOpenshell, + 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(/Rerun onboarding to restore the provider/); - - expect(providerMutationArgs(captureOpenshell)).toEqual([]); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + ).rejects.toThrow(/credential/); + expect(prepare).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-provider-diagnostics.ts b/src/lib/actions/inference-set-provider-diagnostics.ts index cfb83edbb52..f4b1b37bc94 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,32 @@ 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.`, + ); + } + const restoreFailure = await input.restorePreviousSelection(); + 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 0874fe03874..ab5c0e1a623 100644 --- a/src/lib/actions/inference-set-provider.ts +++ b/src/lib/actions/inference-set-provider.ts @@ -593,3 +593,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.test-support.ts b/src/lib/actions/inference-set.test-support.ts index d4300f4748b..d3b5ce2438b 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeLocalIdentity, type NativeLocalBinding } from "../inference/native-local/contract"; import { vi } from "vitest"; import type { CaptureOpenshellOptions, CaptureOpenshellResult } from "../adapters/openshell/client"; import type { @@ -251,6 +252,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; @@ -423,6 +444,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 }), @@ -478,3 +521,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/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index be1e879e8b3..9aa8b909d4a 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -1,6 +1,22 @@ // 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 } from "../inference/native-local/contract"; +import { + nativeLocalCredentialReference, + 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, @@ -34,7 +50,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, @@ -181,12 +203,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; getNativeNvidiaProviderAuthority?: typeof registry.getNativeNvidiaProviderAuthority; setNativeNvidiaProviderAuthority: typeof registry.setNativeNvidiaProviderAuthority; updateSandbox: (name: string, updates: Partial) => boolean; @@ -698,14 +726,17 @@ function buildProviderConfig( const providerConfig: ConfigObject = { ...existing, baseUrl: route.inferenceBaseUrl, - apiKey: managedInferenceApiKey( - route.inferenceBaseUrl, - typeof existing.apiKey === "string" && - existing.apiKey && - existing.apiKey !== NVIDIA_INFERENCE_PLACEHOLDER - ? existing.apiKey - : "unused", - ), + apiKey: + nativeLocalCredentialReference(provider, route.inferenceBaseUrl) ?? + managedInferenceApiKey( + route.inferenceBaseUrl, + typeof existing.apiKey === "string" && + existing.apiKey && + existing.apiKey !== NVIDIA_INFERENCE_PLACEHOLDER && + existing.apiKey !== "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN" + ? existing.apiKey + : "unused", + ), api: route.inferenceApi, models: selectedIndex < 0 @@ -726,9 +757,15 @@ export function patchOpenClawInferenceConfig( upstreamProviderMarker?: string, reasoningEffort: ReasoningEffortRequest = { effort: null, explicit: false }, inheritPrimaryReplyBudget = true, + nativeEndpointUrl: string | null = null, ): { changed: boolean; route: SandboxInferenceConfig } { const before = JSON.stringify(config); - const route = getSandboxInferenceConfig(model, provider, preferredInferenceApi); + const route = getSandboxInferenceConfig( + model, + provider, + preferredInferenceApi, + nativeEndpointUrl, + ); const inheritedMaxTokens = inheritPrimaryReplyBudget ? readOpenClawPrimaryReplyBudget(config) : undefined; @@ -828,9 +865,15 @@ export function patchHermesInferenceConfig( model: string, preferredInferenceApi: string | null = null, contextWindow?: number, + nativeEndpointUrl: string | null = null, ): { changed: boolean; route: SandboxInferenceConfig } { const before = JSON.stringify(config); - const route = getSandboxInferenceConfig(model, provider, preferredInferenceApi); + const route = getSandboxInferenceConfig( + model, + provider, + preferredInferenceApi, + nativeEndpointUrl, + ); applyHermesManagedRoute(config, { model, baseUrl: route.inferenceBaseUrl, @@ -1094,7 +1137,7 @@ async function applyInferenceRouteSelection(input: { deps: InferenceSetDeps; }): Promise { if (input.nativeNvidia) { - input.deps.log(` Using attached native NVIDIA provider: ${input.provider} / ${input.model}`); + input.deps.log(` Using attached native provider: ${input.provider} / ${input.model}`); return false; } input.deps.log(` Setting OpenShell inference route: ${input.provider} / ${input.model}`); @@ -1140,7 +1183,7 @@ function providerBackedRouteLacksRollbackTarget(input: { httpsPinProviderBinding: boolean; probeDirectSandboxBridge: boolean; rollbackRoute: boolean; - previousNativeNvidiaAttachment: boolean; + previousNativeAttachment: boolean; }): boolean { return ( !input.nativeNvidia && @@ -1148,7 +1191,7 @@ function providerBackedRouteLacksRollbackTarget(input: { input.httpsPinProviderBinding || input.probeDirectSandboxBridge) && !input.rollbackRoute && - !input.previousNativeNvidiaAttachment + !input.previousNativeAttachment ); } @@ -1376,6 +1419,18 @@ async function runInferenceSetWithoutHostLock( // stopped legacy Hermes row that still records the Anthropic frontend will // depend on that route when restarted and must not be normalized away. const selectingNativeNvidia = isNativeNvidiaProvider(provider); + const selectingNativeLocal = usesNativeLocalInferenceForAgent( + agentName, + provider, + options.endpointUrl ?? (entry.provider === provider ? entry.endpointUrl : null), + ); + const selectingNative = selectingNativeNvidia || selectingNativeLocal; + const previousNativeLocalAttachment = await prepareNativeLocalSelectionBoundary({ + entry, + selectingNativeLocal, + gatewayName: expectedGatewayName, + requirePolicy: deps.requireNativeProviderPolicy, + }); const routeSandboxes = deps.listSandboxes().sandboxes; const preparedRoute = prepareInferenceSetRoute({ entry: routeEntry, @@ -1384,7 +1439,7 @@ async function runInferenceSetWithoutHostLock( model, customRoute, session: routeSession, - sandboxes: selectingNativeNvidia ? [] : routeSandboxes, + sandboxes: selectingNative ? [] : routeSandboxes, }); if (preparedRoute.gatewayName !== expectedGatewayName) { throw new InferenceSetError( @@ -1394,7 +1449,7 @@ async function runInferenceSetWithoutHostLock( ); } const preMutationRoute = await observeInferenceRouteForSelection({ - nativeNvidia: selectingNativeNvidia, + nativeNvidia: selectingNative, gatewayName: preparedRoute.gatewayName, deps, }); @@ -1460,7 +1515,7 @@ async function runInferenceSetWithoutHostLock( // OpenRouter onboarding registers a sandbox-facing adapter without a custom // provider binding. Verify its model switches through the sandbox route too. const probeSandboxRoute = - selectingNativeNvidia || + selectingNative || provider === "openrouter-api" || isSandboxBridgeProviderBinding(directProviderBinding) || loopbackNoAuthProxyRoute; @@ -1572,12 +1627,14 @@ async function runInferenceSetWithoutHostLock( ].some(([previous, next]) => previous !== next)); if ( providerBackedRouteLacksRollbackTarget({ - nativeNvidia: selectingNativeNvidia, + nativeNvidia: selectingNative, directProviderBinding: Boolean(directProviderBinding), httpsPinProviderBinding: Boolean(httpsPinProviderBinding), probeDirectSandboxBridge: probeSandboxRoute, rollbackRoute: Boolean(rollbackRoute), - previousNativeNvidiaAttachment: Boolean(previousNativeNvidiaAttachment), + previousNativeAttachment: Boolean( + previousNativeNvidiaAttachment || previousNativeLocalAttachment, + ), }) ) { throw new InferenceSetError( @@ -1595,40 +1652,27 @@ 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 nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; let nativeNvidiaAttachmentChanged = false; let nativeNvidiaRegistryCommitted = false; let previousNativeNvidiaDetached = false; let previousNativeNvidiaDetachCommitted = false; const restorePreviousInferenceSelection = async (): Promise => { - if (selectingNativeNvidia || previousNativeNvidiaAttachment) { - 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 nativeNvidiaSelection = await prepareNativeNvidiaSelection({ @@ -1641,7 +1685,27 @@ async function runInferenceSetWithoutHostLock( nativeNvidiaProviderAttachment = nativeNvidiaSelection.attachment; nativeNvidiaAttachmentChanged = nativeNvidiaSelection.attachmentChanged; 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, @@ -1698,7 +1762,7 @@ async function runInferenceSetWithoutHostLock( await assertProviderCurrentBeforeSelection?.(); if (routeImpactWarning) deps.log(` ${routeImpactWarning}`); appliedInferenceSelection = await applyInferenceRouteSelection({ - nativeNvidia: selectingNativeNvidia, + nativeNvidia: selectingNative, provider, model, gatewayName: preparedRoute.gatewayName, @@ -1738,6 +1802,7 @@ async function runInferenceSetWithoutHostLock( model, preferredInferenceApi: preMutationInferenceApi, ...(selectingNativeNvidia ? { nativeProvider: true } : {}), + nativeLocalProviderAttachment, }, previousProvider, previousModel, @@ -1773,18 +1838,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.`, - ); - } - throw new InferenceSetError( - `Sandbox-side verification rejected provider '${provider}' / '${model}': ${probe.detail}. ` + - `The previous OpenShell inference selection was restored to '${rollbackRoute?.provider ?? previousProvider}' / '${rollbackRoute?.model ?? previousModel}'.`, - ); + await rejectInferenceSelectionProbe({ + nativeLocal: selectingNativeLocal, + sandboxName, + provider, + model, + detail: probe.detail, + previousProvider: rollbackRoute?.provider ?? previousProvider, + previousModel: rollbackRoute?.model ?? previousModel, + restorePreviousSelection: restorePreviousInferenceSelection, + }); } } @@ -1799,6 +1862,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) => ({ @@ -1824,6 +1895,10 @@ async function runInferenceSetWithoutHostLock( nimContainer: registryMetadata.nimContainer ?? null, }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), + ...nativeLocalSelectionRegistryFields( + nativeLocalProviderAttachment, + previousNativeLocalDetached, + ), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...nativeNvidiaDepartureRegistryFields(previousNativeNvidiaDetached), }); @@ -1843,6 +1918,8 @@ async function runInferenceSetWithoutHostLock( `Failed to update NemoClaw registry for sandbox '${sandboxName}'.`, ); } + nativeLocalRegistryCommitted = Boolean(nativeLocalProviderAttachment); + previousNativeLocalDetachCommitted = previousNativeLocalDetached; nativeNvidiaRegistryCommitted = Boolean(nativeNvidiaProviderAttachment); previousNativeNvidiaDetachCommitted = previousNativeNvidiaDetached; @@ -1902,6 +1979,7 @@ async function runInferenceSetWithoutHostLock( model, preferredInferenceApi, contextWindow, + nativeLocalProviderAttachment?.endpointUrl ?? null, ); } else { // Recompute the context window for the model being switched to, so it does @@ -1923,6 +2001,8 @@ async function runInferenceSetWithoutHostLock( contextWindow, provider, reasoningEffortRequest, + true, + nativeLocalProviderAttachment?.endpointUrl ?? null, ); } @@ -2046,29 +2126,58 @@ async function runInferenceSetWithoutHostLock( expectedGatewayName, ); if (error instanceof OpenClawInferenceConfigSyncError) throw error; - await restorePreviousNativeNvidiaAfterFailedPublish({ + 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 restorePreviousNativeNvidiaAfterFailedPublish({ detached: previousNativeNvidiaDetached, committed: previousNativeNvidiaDetachCommitted, previousAttachment: previousNativeNvidiaAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, - error, + error: failure, deps, - }); - await rollbackNativeNvidiaSelection({ + }).then( + () => failure, + (rollbackError: unknown) => rollbackError, + ); + failure = await rollbackNativeNvidiaSelection({ attachmentChanged: nativeNvidiaAttachmentChanged, registryCommitted: nativeNvidiaRegistryCommitted, attachment: nativeNvidiaProviderAttachment, 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 { @@ -2167,6 +2276,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/native-local.ts b/src/lib/actions/inference/native-local.ts new file mode 100644 index 00000000000..2788161cf64 --- /dev/null +++ b/src/lib/actions/inference/native-local.ts @@ -0,0 +1,231 @@ +// 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) + await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous!, + }); + 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) { + await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous, + }); + throw error; + } + return true; +} + +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 04ded0c93af..c246969c691 100644 --- a/src/lib/actions/sandbox/agents/managed-workload-rebuild-profile.ts +++ b/src/lib/actions/sandbox/agents/managed-workload-rebuild-profile.ts @@ -93,6 +93,7 @@ export function prepareManagedRebuildProfileHandoff(input: { resumeConfig.provider, resumeConfig.model, resumeConfig.preferredInferenceApi, + resumeConfig.nativeLocalProviderAttachment?.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 b14fb93c2ef..f7ddbf8631b 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 nativeNvidiaAttachment = getNativeNvidiaProviderAttachment(sb); - if (nativeNvidiaAttachment) { + if (nativeNvidiaAttachment || sb.nativeLocalProviderAttachment !== undefined) { await requireNativeNvidiaInferenceHealth({ 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 (getNativeNvidiaProviderAttachment(snapshot)) { + if ( + getNativeNvidiaProviderAttachment(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 9b8f7ad8174..cff5e3aad2d 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"; @@ -895,6 +897,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. @@ -960,6 +965,7 @@ export async function executeSandboxDestroy({ force && !hasMcpOwnership && !hasHostLocalInferenceOwnership && + !hasNativeLocalAuthority && portableContainerAuthority === undefined; if (deleteFailed && !forcedLocalCleanup) { @@ -973,7 +979,7 @@ export async function executeSandboxDestroy({ gatewayUnreachable, ...(timedOut ? { timedOut: true as const } : {}), hostLocalInferenceOwnershipRequiresGateway: - gatewayUnreachable && hasHostLocalInferenceOwnership, + gatewayUnreachable && (hasHostLocalInferenceOwnership || hasNativeLocalAuthority), mcpOwnershipRequiresGateway: gatewayUnreachable && hasMcpOwnership, mcpRecoveryFailure, portableLifecycleOwnershipRequiresGateway: @@ -1121,3 +1127,16 @@ 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, +): Promise { + await retireUnselectedNativeLocalProviders({ + adapter: createManagedProviderAdapter(), + 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..f44da773aa3 --- /dev/null +++ b/src/lib/actions/sandbox/destroy-native-local.test.ts @@ -0,0 +1,106 @@ +// 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 { + nativeLocalIdentity, + type NativeLocalBinding, +} from "../../inference/native-local/contract"; + +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(harness.removeSandboxSpy).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index f00bf4d2183..45970531d68 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, @@ -1118,6 +1119,12 @@ async function destroySandboxUnlocked( if (!deleteSucceededOrAlreadyGone) { preparedManagedLlamaCppCleanup?.abort(); } + if (deleteSucceededOrAlreadyGone && sandbox) { + await retireDestroyedSandboxNativeLocalProvider(sandbox, cleanupGatewayName).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 0544d8b9ec1..488790ea87d 100644 --- a/src/lib/actions/sandbox/doctor-inference.test.ts +++ b/src/lib/actions/sandbox/doctor-inference.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import { nativeLocalTestReceipt } from "../inference-set.test-support"; import type { ProviderHealthStatus } from "../../inference/health"; import { collectInferenceChecks, collectManagedLlamaCppDoctorChecks } from "./doctor-inference"; @@ -427,3 +428,58 @@ describe("doctor inference checks", () => { }); }); }); + +describe("native local doctor reachability", () => { + it("skips route verification while the sandbox is unreachable (#12558)", async () => { + const verify = vi.fn(); + const probe = vi.fn(); + const shared = vi.fn(); + const checks = await collectInferenceChecks( + "alpha", + { + provider: "ollama-local", + model: "model", + nativeLocalProviderAttachment: nativeLocalTestReceipt(), + }, + false, + { + gatewayName: "nemoclaw", + verifyNativeLocalStatusAttachmentImpl: verify, + nativeLocalInvocationProbe: probe, + probeSandboxInferenceGatewayHealthImpl: shared, + probeProviderHealthImpl: () => null, + includeServingProcessCheck: false, + }, + ); + expect(checks).toContainEqual( + expect.objectContaining({ label: "Inference route (native local)", status: "info" }), + ); + expect(verify).not.toHaveBeenCalled(); + expect(probe).not.toHaveBeenCalled(); + expect(shared).not.toHaveBeenCalled(); + }); + it("still fails reachable native routes with missing gateway authority (#12558)", 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 168670e5905..8c210f5181f 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 { CLI_NAME } from "../../cli/branding"; import { type ProviderHealthStatus, probeProviderHealth } from "../../inference/health"; import { inspectManagedLlamaCppStatus } from "../../inference/llama-cpp/managed-status"; @@ -31,6 +40,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; }; @@ -82,11 +92,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, @@ -315,16 +383,23 @@ export async function collectInferenceChecks( const effortCheck = reasoningEffortCheck(route); if (effortCheck) checks.push(effortCheck); const nativeNvidia = isNativeNvidiaProvider(route.provider); - const routeProbe = nativeNvidia - ? await collectNativeNvidiaRouteProbe(sandboxName, route, sandboxReachable, deps) - : await collectInferenceRouteProbe( - sandboxName, - sandboxReachable, - deps.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth, - deps.gatewayName, - ); + const nativeLocal = route.nativeLocalProviderAttachment !== undefined; + const routeProbe = nativeLocal + ? await collectNativeLocalRouteProbe(sandboxName, route, sandboxReachable, deps) + : nativeNvidia + ? await collectNativeNvidiaRouteProbe(sandboxName, route, sandboxReachable, deps) + : await collectInferenceRouteProbe( + sandboxName, + sandboxReachable, + deps.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth, + deps.gatewayName, + ); pushInferenceHealthCheck(checks, routeProbe, { - label: nativeNvidia ? "Inference route (native NVIDIA)" : "Inference route (gateway)", + label: nativeLocal + ? "Inference route (native local)" + : 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 2f51a29964a..a9921407461 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -389,8 +389,15 @@ 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 && openshellBin && openshellConnected && gatewayName) { + if ( + !recordedNativeNvidia && + !recordedNativeLocal && + openshellBin && + openshellConnected && + gatewayName + ) { const result = await createSynchronousCliOpenShellInferenceRouteObserver( captureOpenshell, ).observeInferenceRoute({ @@ -405,6 +412,9 @@ async function resolveInferenceRoute( effectiveReasoningEffort: resolveDoctorReasoningEffort(sb), recordedEndpointUrl: sb?.endpointUrl, agentName: sb?.agent, + ...(recordedNativeLocal + ? { nativeLocalProviderAttachment: sb?.nativeLocalProviderAttachment } + : {}), ...(recordedNativeNvidia ? { nativeNvidiaProviderAttachment: normalizeNativeNvidiaProviderAttachment( diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 52a09c8603e..c16fb344426 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.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 { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; import { spawnSync } from "node:child_process"; import { getChatCompletionsProbePayload } from "../../inference/openai-probe-models"; @@ -61,7 +62,7 @@ function runProbeCommandWithBody( parentDirectory: string = tmpdir(), probeInput: SandboxInferenceInvocationInput = input, probeEnvironment: NodeJS.ProcessEnv = {}, -): { stdout: string; argv: string[] } { +): { stdout: string; stderr: string; status: number | null; argv: string[] } { const dir = mkdtempSync(path.join(parentDirectory, "nemoclaw-probe-parity-")); try { const bin = path.join(dir, "bin"); @@ -85,7 +86,11 @@ function runProbeCommandWithBody( }); return { stdout: run.stdout || "", - argv: readFileSync(path.join(dir, "argv.txt"), "utf8").trimEnd().split("\n"), + stderr: run.stderr || "", + status: run.status, + argv: existsSync(path.join(dir, "argv.txt")) + ? readFileSync(path.join(dir, "argv.txt"), "utf8").trimEnd().split("\n") + : [], }; } finally { rmSync(dir, { recursive: true, force: true }); @@ -99,6 +104,74 @@ const NVCF_BODY_VARIANTS = [ ] as const; describe("sandbox inference invocation probe", () => { + it("validates native compatible replies using the API sent to the endpoint (#12558)", async () => { + const binding = { + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: input.sandboxName, + } as const; + const execute = vi.fn(async () => ({ + status: 0, + stdout: '200\n{"choices":[{"message":{"content":"PONG"}}]}', + stderr: "", + })); + const result = await probeSandboxInferenceInvocation( + { + ...input, + provider: binding.provider, + gatewayName: binding.gatewayName, + preferredInferenceApi: "openai-responses", + nativeLocalProviderAttachment: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "owned-local-provider", + }, + }, + { execute }, + ); + expect(result).toEqual({ ok: true }); + expect((execute.mock.calls[0] as unknown as [string, string])[1]).toContain( + "/v1/chat/completions", + ); + }); + + it("probes the recorded native endpoint with its opaque credential (#12558)", async () => { + 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 nativeInput = { + ...input, + provider: binding.provider, + gatewayName: binding.gatewayName, + nativeLocalProviderAttachment: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "owned-local-provider", + }, + }; + const execute = vi.fn(async () => ({ status: 1, stdout: "403\n", stderr: "" })); + const result = await probeSandboxInferenceInvocation(nativeInput, { execute }); + expect(result).toMatchObject({ + ok: false, + httpStatus: 403, + endpoint: "http://host.openshell.internal:11434/v1/chat/completions", + }); + expect(execute).toHaveBeenCalledOnce(); + const command = execute.mock.calls[0] as unknown as [string, string]; + expect(command[1]).toContain("NEMOCLAW_LOCAL_INFERENCE_TOKEN"); + expect(command[1]).not.toContain("inference.local"); + }); + it("ignores personal curl configuration when an inference request fails (#11520)", () => { const dir = mkdtempSync(path.join(tmpdir(), "nemoclaw-curl-config-")); try { @@ -753,3 +826,72 @@ it("gives native Ultra readiness the same reasoning budget as host onboarding", expect(payload.max_tokens).toBe(256); expect(command).toContain('"max_tokens":256'); }); + +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([ + "", + "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN", + "openshell:resolve:env:v42_OTHER_KEY", + "short", + "opaque-host-secret-must-not-leak", + "openshell:resolve:env:v42_NEMOCLAW_LOCAL_INFERENCE_TOKEN\n", +])("refuses invalid native 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 result = runProbeCommandWithBody( + "200", + "{}", + tmpdir(), + { + ...input, + provider: binding.provider, + nativeLocalProviderAttachment: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1, + providerId: "owned", + }, + }, + { [binding.credentialEnv]: reference }, + ); + expect(result.status).toBe(2); + expect(result.argv).toEqual([]); + expect(result.stdout + result.stderr).toBe(""); +}); diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index d897e32408e..d69872ae28c 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -1,6 +1,12 @@ // 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 { NATIVE_LOCAL_AUTH_HEADER_SCRIPT } from "../../inference/native-local/agent-config"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; import { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; import type { @@ -49,6 +55,7 @@ export type SandboxInferenceInvocationInput = { model: string; preferredInferenceApi: string | null; nativeProvider?: boolean; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; }; export type SandboxInferenceInvocationResult = @@ -82,10 +89,20 @@ 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, + local?.endpointUrl ?? null, ); const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); const baseUrl = ( @@ -95,7 +112,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { ? "https://inference.local/v1" : config.inferenceBaseUrl ).replace(/\/+$/u, ""); - const apiBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`; + const apiBaseUrl = local || baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`; if (config.inferenceApi === "anthropic-messages") { return { endpoint: `${apiBaseUrl}/messages`, @@ -142,15 +159,19 @@ export function buildSandboxInferenceInvocationCommand( ): string { const request = buildProbeRequest(input); const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); + const useNativeLocal = Boolean( + normalizeNativeLocalProviderAttachment(input.nativeLocalProviderAttachment), + ); const headerArgs = ["Content-Type: application/json", ...request.headers] .map((header) => `-H ${shellQuote(header)}`) - .join(" ") + (useNativeNvidia ? ' -H "$AUTH_HEADER"' : ""); + .join(" ") + (useNativeNvidia || useNativeLocal ? ' -H "$AUTH_HEADER"' : ""); const payload = shellQuote(JSON.stringify(request.payload)); const endpoint = shellQuote(request.endpoint); return [ "umask 077", ...(useNativeNvidia ? [NATIVE_NVIDIA_AUTH_HEADER_SCRIPT] : []), + ...(useNativeLocal ? [NATIVE_LOCAL_AUTH_HEADER_SCRIPT] : []), "body=$(mktemp /tmp/nemoclaw-inference-invocation.XXXXXX) || exit 1", "trap 'rm -f \"$body\"' EXIT HUP INT TERM", `code=$(curl -q -sS --connect-timeout 5 --max-time ${INFERENCE_INVOCATION_REQUEST_TIMEOUT_SECONDS} --max-filesize ${INFERENCE_INVOCATION_MAX_RESPONSE_BYTES} -o "$body" -w '%{http_code}' ${headerArgs} --data-binary ${payload} ${endpoint}) || { rc=$?; printf 'curl-error:%s\\n' "$rc"; exit "$rc"; }`, @@ -261,6 +282,8 @@ export async function probeSandboxInferenceInvocation( input.model, input.provider, input.preferredInferenceApi, + 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 46b4ff718a1..9382badf23d 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -1,6 +1,9 @@ // 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 { verifyNativeLocalProviderAttachment } from "../../inference/native-local/profile"; + import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; import { buildSandboxCommandEnvironment } from "../../adapters/sandbox/command-transport"; import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; @@ -61,6 +64,24 @@ 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 SandboxInferenceRouteHealth = { ok: boolean; endpoint: string; @@ -335,6 +356,7 @@ function buildInvokedRouteHealth( export type SandboxInferenceRouteHealthContext = { provider: string | null; nativeNvidia?: boolean; + nativeLocalEndpoint?: string; }; // A models route that answers but is credential-gated (401/403) stays @@ -367,6 +389,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), + }; + } if (context.nativeNvidia && isNativeNvidiaProvider(context.provider)) { const endpoint = invocation && !invocation.ok && invocation.endpoint diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 5289c9c06a6..afd9cbe89d4 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -826,7 +826,9 @@ async function captureLaunchIdentity( } const inferenceSelection = normalizeInferenceSelection(entry); const inference = registry.getSandboxEntryInference(entry); - const nativeNvidia = Boolean(getNativeNvidiaProviderAttachment(entry)); + const nativeNvidia = + Boolean(getNativeNvidiaProviderAttachment(entry)) || + entry.nativeLocalProviderAttachment !== undefined; let liveInference: { provider: string; model: string } | null = null; if (!nativeNvidia) { const inferenceGetStartedAt = performance.now(); diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index d06401f587f..108fd048aad 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"; @@ -77,6 +80,7 @@ export interface LaunchReadinessHealthDeps { gatewayName: string, ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; + verifyNativeLocalAttachment?: typeof verifyNativeLocalStatusAttachment; verifyNativeNvidiaAttachment?: (input: { sandboxName: string; gatewayName: string; @@ -218,6 +222,30 @@ export async function requireNativeNvidiaInferenceHealth(input: { entry: SandboxEntry; deps: LaunchReadinessHealthDeps; }): Promise { + if (input.entry.nativeLocalProviderAttachment !== undefined) { + const expected = normalizeNativeLocalProviderAttachment( + input.entry.nativeLocalProviderAttachment, + ); + if (!expected || !input.entry.model) 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 = getNativeNvidiaProviderAttachment(input.entry); if (!expected) return false; const provider = normalizedString(input.entry.provider); @@ -349,7 +377,10 @@ export async function requireLaunchSemanticHealth( } if (inferenceConfigured) { const inferenceStartedAt = performance.now(); - if (getNativeNvidiaProviderAttachment(entry)) { + if ( + getNativeNvidiaProviderAttachment(entry) || + entry.nativeLocalProviderAttachment !== undefined + ) { try { await requireNativeNvidiaInferenceHealth({ 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 2a30c700746..be06ec0fdbc 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 { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import { @@ -15,6 +19,7 @@ export type DcodeRebuildRegistryEntry = SandboxGatewayBinding & { agent?: string | null; dashboardPort?: number | null; nativeNvidiaProviderAttachment?: unknown; + nativeLocalProviderAttachment?: unknown; }; export type DcodeRebuildResumeConfig = { @@ -25,6 +30,7 @@ export type DcodeRebuildResumeConfig = { }; export type ResolvedDcodeRebuildTarget = { + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeProvider?: boolean; agent: typeof DCODE_AGENT_NAME; gatewayName: string; @@ -64,6 +70,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"); + } return { agent: DCODE_AGENT_NAME, gatewayName, @@ -71,6 +83,7 @@ export function resolveDcodeRebuildTarget( provider: requiredString(resumeConfig.provider, "inference provider"), model: requiredString(resumeConfig.model, "inference model"), preferredInferenceApi: resumeConfig.preferredInferenceApi, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) ? { nativeProvider: true } : {}), diff --git a/src/lib/actions/sandbox/rebuild-resume-config.test.ts b/src/lib/actions/sandbox/rebuild-resume-config.test.ts index 9ac27fde367..c30d2f1d987 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { createRequire } from "node:module"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -924,3 +925,58 @@ 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); + }, + ); +}); diff --git a/src/lib/actions/sandbox/rebuild-resume-config.ts b/src/lib/actions/sandbox/rebuild-resume-config.ts index 3c7f8e4b0a6..46b791a38c9 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 { @@ -63,6 +67,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; @@ -249,6 +254,13 @@ export function prepareRebuildResumeConfig( bail("Malformed native NVIDIA provider attachment; sandbox is untouched"); return null; } + const nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( + sb.nativeLocalProviderAttachment, + ); + if (sb.nativeLocalProviderAttachment !== undefined && !nativeLocalProviderAttachment) { + bail("Malformed native local provider attachment; sandbox is untouched"); + return null; + } return { ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), agent: rebuildAgent, @@ -265,6 +277,7 @@ export function prepareRebuildResumeConfig( pinEndpoint: rebuildEndpoint.known || explicitTargetEndpoint !== null, endpointUrl, registryInferenceRoute, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ambient, }; } diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index 640616ae51c..f1d325a95f6 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -17,6 +17,8 @@ import { createRuntimeProviderBundleRegistry } from "../../onboard/runtime-provi import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { type SandboxStartDeps, startSandbox } from "./start"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; +import { buildSandboxInferenceInvocationCommand } from "./inference-invocation-probe"; afterEach(() => { vi.restoreAllMocks(); @@ -314,6 +316,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 301d559feb7..7b168277136 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -164,6 +164,9 @@ async function checkStartedSandboxInference( provider, model, preferredInferenceApi: sandbox.preferredInferenceApi ?? null, + ...(sandbox.nativeLocalProviderAttachment + ? { nativeLocalProviderAttachment: sandbox.nativeLocalProviderAttachment } + : {}), }; const probe = () => (deps.probeInferenceInvocation ?? probeSandboxInferenceInvocation)( 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.ts b/src/lib/actions/sandbox/status-snapshot.ts index 53c41e2036b..71a91d2b3b5 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -1,6 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeLocalProviderAttachment } from "../../inference/config"; +import { + verifyNativeLocalStatusAttachment, + type VerifyNativeLocalStatusAttachment, +} from "./inference-route-health"; + import { setTimeout as sleep } from "node:timers/promises"; import type { OpenShellStateRpcIssue } from "../../adapters/openshell/gateway-drift"; @@ -333,6 +339,7 @@ interface CollectSandboxStatusSnapshotDeps { getSandboxStatusPreflightImpl?: typeof getSandboxStatusPreflight; getGatewayPresets?: GetGatewayPresets; inspectManagedLlamaCppOwnership?: typeof inspectManagedLlamaCppOwnership; + verifyNativeLocalProviderAttachmentImpl?: VerifyNativeLocalStatusAttachment; verifyNativeNvidiaProviderAttachmentImpl?: VerifyNativeNvidiaStatusAttachment; } @@ -562,13 +569,17 @@ export async function collectSandboxStatusSnapshot( const nativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( sb?.nativeNvidiaProviderAttachment, ); - const nativeNvidia = Boolean(nativeNvidiaAttachment); + const nativeLocalAttachment = normalizeNativeLocalProviderAttachment( + sb?.nativeLocalProviderAttachment, + ); + const nativeLocal = sb?.nativeLocalProviderAttachment !== undefined; + const nativeInference = Boolean(nativeNvidiaAttachment) || nativeLocal; let liveResult: OpenShellInferenceRouteResult | null = null; let gatewayName: string | null = null; if (lookup.state === "present") { try { gatewayName = resolveSandboxGatewayName(sb); - if (!nativeNvidia) { + if (!nativeInference) { const observer = opts.deps?.inferenceRouteObserver ?? createCliOpenShellInferenceRouteObserver(captureOpenshellForStatus); @@ -614,11 +625,17 @@ export async function collectSandboxStatusSnapshot( // as drift instead of being mislabeled as this sandbox's configuration. const currentModel = sb ? sb.model || "unknown" : (live && live.model) || "unknown"; const currentProvider = sb ? sb.provider || "unknown" : (live && live.provider) || "unknown"; - let nativeNvidiaAttachmentFailure: string | null = null; - if (!suppressInferenceProbe && lookup.state === "present" && nativeNvidia && sb) { + let nativeAttachmentFailure: string | null = null; + if ( + !suppressInferenceProbe && + lookup.state === "present" && + nativeInference && + !nativeLocal && + sb + ) { const expected = nativeNvidiaAttachment; if (!gatewayName || !expected) { - nativeNvidiaAttachmentFailure = + nativeAttachmentFailure = `Native NVIDIA provider attachment is unavailable for sandbox '${sandboxName}'. ` + "Recreate the sandbox to restore native NVIDIA inference."; } else { @@ -633,14 +650,32 @@ export async function collectSandboxStatusSnapshot( }); } catch (error) { const detail = sanitizedStatusDetail(error); - nativeNvidiaAttachmentFailure = + nativeAttachmentFailure = `Native NVIDIA provider attachment is unavailable for sandbox '${sandboxName}'` + `${detail ? `: ${detail}` : "."} Recreate the sandbox to restore native NVIDIA inference.`; } } } + if (!suppressInferenceProbe && lookup.state === "present" && nativeLocal) { + if (!nativeLocalAttachment || !gatewayName) { + nativeAttachmentFailure = + "Native local provider authority is missing. Recreate this beta sandbox."; + } else { + try { + await ( + opts.deps?.verifyNativeLocalProviderAttachmentImpl ?? verifyNativeLocalStatusAttachment + )({ sandboxName, gatewayName, expected: nativeLocalAttachment }); + nativeAttachmentFailure = null; + } catch (error) { + const detail = sanitizedStatusDetail(error); + nativeAttachmentFailure = + `Native local provider '${nativeLocalAttachment.providerName}' is unavailable for sandbox '${sandboxName}'` + + `${detail ? `: ${detail}` : "."} Recreate the sandbox to restore native local inference.`; + } + } + } const routeDriftPlan = - !nativeNvidia && sb && sb.provider && sb.model + !nativeInference && sb && sb.provider && sb.model ? planInferenceRouteReconcile(live, { provider: sb.provider, model: sb.model }) : null; const routeDrift = @@ -671,13 +706,13 @@ export async function collectSandboxStatusSnapshot( // value to null afterwards. let providerHealth: ProviderHealthStatus | null = null; try { - providerHealth = nativeNvidiaAttachmentFailure + providerHealth = nativeAttachmentFailure ? null : maybeGetSandboxStatusInferenceHealth( suppressInferenceProbe, lookup.state === "present", - nativeNvidia ? currentProvider : (live && live.provider) || currentProvider, - nativeNvidia ? currentModel : (live && live.model) || currentModel, + nativeInference ? currentProvider : (live && live.provider) || currentProvider, + nativeInference ? currentModel : (live && live.model) || currentModel, opts.deps?.probeProviderHealthImpl, sb?.endpointUrl, ); @@ -700,7 +735,7 @@ export async function collectSandboxStatusSnapshot( // a live model with a recorded provider and request a route neither one // describes. const invocationRoute = - !nativeNvidia && live?.provider && live.model + !nativeInference && live?.provider && live.model ? { provider: live.provider, model: live.model, @@ -727,15 +762,13 @@ export async function collectSandboxStatusSnapshot( opts.deps?.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth; await retryUntilAsync( async () => { - gatewayChain = nativeNvidia + gatewayChain = nativeInference ? null : gatewayName ? await probe(sandboxName, { gatewayName }) : null; invocation = - !nativeNvidiaAttachmentFailure && - (nativeNvidia || gatewayChain?.ok) && - canProbeInvocation + !nativeAttachmentFailure && (nativeInference || gatewayChain?.ok) && canProbeInvocation ? await runSandboxInferenceInvocationProbe( { sandboxName, @@ -744,7 +777,10 @@ export async function collectSandboxStatusSnapshot( provider: invocationProvider, model: invocationModel, preferredInferenceApi: invocationRoute.preferredInferenceApi, - ...(nativeNvidia ? { nativeProvider: true } : {}), + ...(nativeNvidiaAttachment ? { nativeProvider: true } : {}), + ...(nativeLocalAttachment + ? { nativeLocalProviderAttachment: nativeLocalAttachment } + : {}), }, opts.deps?.probeSandboxInferenceInvocationImpl, (error) => @@ -758,7 +794,7 @@ export async function collectSandboxStatusSnapshot( }, { accept: ({ gatewayChain: chain, invocation: result }) => { - if (nativeNvidia) { + if (nativeInference) { return result?.ok === true || !isTransientInferenceInvocationFailure(result); } if (chain?.ok && (!canProbeInvocation || result?.ok)) return true; @@ -792,26 +828,31 @@ export async function collectSandboxStatusSnapshot( gatewayChain = null; invocation = null; } - inferenceHealth = nativeNvidiaAttachmentFailure + inferenceHealth = nativeAttachmentFailure ? { ok: false, probed: false, - providerLabel: "Native NVIDIA provider attachment", - endpoint: NVIDIA_HOSTED_NATIVE_ENDPOINT, - detail: nativeNvidiaAttachmentFailure, + providerLabel: nativeLocal + ? "Native local provider attachment" + : "Native NVIDIA provider attachment", + endpoint: nativeLocal + ? (nativeLocalAttachment?.endpointUrl ?? "") + : NVIDIA_HOSTED_NATIVE_ENDPOINT, + detail: nativeAttachmentFailure, failureLabel: "unreachable", probeLabel: "provider attachment", } : buildSandboxInferenceRouteHealth(gatewayChain, providerHealth, invocation, { provider: invocationRoute.provider ?? null, - nativeNvidia, + nativeNvidia: Boolean(nativeNvidiaAttachment), + nativeLocalEndpoint: nativeLocalAttachment?.endpointUrl, }); } // Classify once per snapshot so every renderer observes the same receipt state. // A complete matching live route is required because the shared gateway route // may belong to another sandbox or provider entirely (#10256). const llamaCpp = - routeDriftPlan?.kind === "aligned" + routeDriftPlan?.kind === "aligned" || nativeLocalAttachment ? getLlamaCppRouteDetails( sb, opts.deps?.inspectManagedLlamaCppOwnership ?? inspectManagedLlamaCppOwnership, @@ -917,8 +958,9 @@ async function buildSandboxStatusReport( const livePolicies = sb && deps.getGatewayPresets ? await deps.getGatewayPresets(sandboxName, undefined, sb) : []; const agent = resolveSandboxStatusAgent(sb?.agent || "openclaw"); - const nativeNvidia = Boolean( - normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment), + const nativeInference = Boolean( + normalizeNativeNvidiaProviderAttachment(sb?.nativeNvidiaProviderAttachment) || + sb?.nativeLocalProviderAttachment !== undefined, ); return { schemaVersion: 1, @@ -932,8 +974,8 @@ async function buildSandboxStatusReport( // Native NVIDIA inference is sandbox-attached and independent of the // gateway-global route. Other schema-v1 consumers keep the established // live-first fields, with explicit route fields separating both views. - model: nativeNvidia ? currentModel : (liveRoute?.model ?? currentModel), - provider: nativeNvidia ? currentProvider : (liveRoute?.provider ?? currentProvider), + model: nativeInference ? currentModel : (liveRoute?.model ?? currentModel), + provider: nativeInference ? currentProvider : (liveRoute?.provider ?? currentProvider), servingProfileProvenance: sb?.servingProfileProvenance ?? null, llamaCpp, recordedRoute, 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 85bd30c5411..49ae29b6313 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, @@ -53,9 +54,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, + ); mockSupportedLiveSource(3, 3, source); const effective = configuration(); effective.policy.network_policies.api.endpoints = [ @@ -103,6 +108,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..f3be350f07d 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,17 @@ 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", + 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 d8b1e6df1f5..98c67e24a9a 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, @@ -46,6 +47,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); @@ -57,6 +59,7 @@ function mockManagedVllmSource( "vllm-local", model, "openai-completions", + 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. @@ -150,6 +153,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 1595c828cc6..a35d018aed6 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -15,6 +15,7 @@ import { namedOpenShellGateway } from "../openshell/sandbox-observer"; import { EXPORT_REGISTRY_EVIDENCE_KEYS, exportWebSearchBinding, + exportNativeInferenceReceipt, } from "../../domain/config/export-evidence"; import type { ExportSnapshotReadStage, @@ -173,13 +174,13 @@ function inferenceTopology( : "hosted"; } -type NativeNvidiaReceipt = NonNullable; +type NativeInferenceReceipt = NonNullable>; function matchesNativeProviderMetadata( provider: Provider, normalized: ReturnType, routeProvider: string, - receipt: NativeNvidiaReceipt, + receipt: NativeInferenceReceipt, ): boolean { return isDeepStrictEqual( [ @@ -194,7 +195,9 @@ function matchesNativeProviderMetadata( routeProvider, receipt.providerId, receipt.profileId, - expectedCredentialKeys(normalized.credentialEnv, routeProvider), + "endpointUrl" in receipt + ? [receipt.credentialEnv] + : expectedCredentialKeys(normalized.credentialEnv, routeProvider), [], receipt.profileId, ], @@ -206,7 +209,7 @@ function matchesProviderMetadata( normalized: ReturnType, routeProvider: string, managed: boolean, - nativeReceipt?: NativeNvidiaReceipt, + nativeReceipt?: NativeInferenceReceipt, ): boolean { if (nativeReceipt !== undefined) { return matchesNativeProviderMetadata(provider, normalized, routeProvider, nativeReceipt); @@ -239,14 +242,16 @@ function matchesProviderMetadata( function profileContractFor( routeProvider: string, - nativeReceipt: NativeNvidiaReceipt | undefined, -): "native-nvidia" | "openai" | undefined { + nativeReceipt: NativeInferenceReceipt | undefined, +): Parameters["get"]>[0]["profileContract"] { + if (nativeReceipt && "endpointUrl" in nativeReceipt) + return { kind: "native-local", binding: nativeReceipt }; if (nativeReceipt) return "native-nvidia"; return routeProvider === "ollama-local" ? "openai" : undefined; } function endpointSourceFor( - nativeReceipt: NativeNvidiaReceipt | undefined, + nativeReceipt: NativeInferenceReceipt | undefined, builtin: boolean, configKey: "ANTHROPIC_BASE_URL" | "OPENAI_BASE_URL", ): ObservedExportEndpointEvidence["source"] { @@ -261,7 +266,7 @@ async function readProviderEvidence( gatewayName: string, signal: AbortSignal, managedServing?: ObservedManagedVllmRuntime, - nativeReceipt?: NativeNvidiaReceipt, + nativeReceipt?: NativeInferenceReceipt, ): Promise { const { configKey } = providerContract(normalized.preferredInferenceApi); const profileContract = profileContractFor(routeProvider, nativeReceipt); @@ -294,7 +299,7 @@ async function readProviderEvidence( async function resolveLiveInference( entry: Readonly, gatewayName: string, - nativeReceipt: NativeNvidiaReceipt | undefined, + nativeReceipt: NativeInferenceReceipt | undefined, ): Promise> { if (!nativeReceipt) { const live = await readInferenceRoute(entry, gatewayName); @@ -302,7 +307,7 @@ async function resolveLiveInference( } const selected = getSandboxEntryInference(entry); if (selected.kind !== "configured") { - throw new Error("The native NVIDIA inference selection is incomplete."); + throw new Error("The native inference selection is incomplete."); } return { provider: nativeReceipt.providerName, @@ -320,10 +325,11 @@ async function inferenceFor( ): Promise { const normalized = normalizeInferenceSelection(entry); const gateway = resolveGatewayBinding(entry); - const nativeReceipt = - entry.provider?.trim() === "nvidia-prod" ? entry.nativeNvidiaProviderAttachment : undefined; + const nativeReceipt = exportNativeInferenceReceipt(entry); + if (nativeReceipt === null) + throw new Error("The native local export binding is invalid or unsupported."); if (nativeReceipt && !sandbox.providerNames.includes(nativeReceipt.providerName)) { - throw new Error("The native NVIDIA provider is not attached to the sandbox."); + throw new Error("The native inference provider is not attached to the sandbox."); } const live = await resolveLiveInference(entry, gateway.name, nativeReceipt); beforeRead("provider-metadata"); diff --git a/src/lib/adapters/openshell/native-nvidia-profile-response.ts b/src/lib/adapters/openshell/native-inference-profile-response.ts similarity index 59% rename from src/lib/adapters/openshell/native-nvidia-profile-response.ts rename to src/lib/adapters/openshell/native-inference-profile-response.ts index 0b4b6d7d7da..ea389b6bae1 100644 --- a/src/lib/adapters/openshell/native-nvidia-profile-response.ts +++ b/src/lib/adapters/openshell/native-inference-profile-response.ts @@ -1,9 +1,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -type NativeNvidiaProfileResponse = Readonly<{ +import { prepareNativeLocalProfile } from "../../inference/native-local/profile"; +type NativeLocalBinding = Parameters[0]; + +type NativeBoundary = { + id: string; + credentialEnv: string; + endpointUrl: string; + allowedIps: readonly string[]; + binaries: readonly string[]; +}; + +type NativeProfileResponse = Readonly<{ profile: Readonly<{ - id: "nemoclaw-nvidia-inference-v1"; + id: string; source: "user"; scope: "platform" | "workspace"; resourceVersion: bigint | string; @@ -33,12 +44,12 @@ function stringArrayEquals(value: unknown, expected: readonly string[]): boolean ); } -function nativeCredential(value: unknown): boolean { +function nativeCredential(value: unknown, credentialEnv: string): boolean { const credential = record(value); return ( credential !== null && credential.name === "api_key" && - stringArrayEquals(credential.envVars, ["NVIDIA_INFERENCE_API_KEY"]) && + stringArrayEquals(credential.envVars, [credentialEnv]) && credential.required === true && credential.authStyle === "bearer" && credential.headerName === "authorization" && @@ -66,13 +77,14 @@ function nativeRule(value: unknown, method: "GET" | "POST", path: string): boole ); } -function nativeEndpoint(value: unknown): boolean { +function nativeEndpoint(value: unknown, expected: NativeBoundary): boolean { + const url = new URL(expected.endpointUrl); const endpoint = record(value); const rules = endpoint?.rules; return ( endpoint !== null && - endpoint.host === "integrate.api.nvidia.com" && - endpoint.port === 443 && + endpoint.host === url.hostname && + endpoint.port === Number(url.port || (url.protocol === "https:" ? 443 : 80)) && emptyArray(endpoint.ports) && endpoint.protocol === "rest" && endpoint.tls === "" && @@ -80,9 +92,9 @@ function nativeEndpoint(value: unknown): boolean { endpoint.access === "" && Array.isArray(rules) && rules.length === 2 && - nativeRule(rules[0], "GET", "/v1/models") && - nativeRule(rules[1], "POST", "/v1/chat/completions") && - emptyArray(endpoint.allowedIps) && + nativeRule(rules[0], "GET", `${url.pathname}/models`) && + nativeRule(rules[1], "POST", `${url.pathname}/chat/completions`) && + stringArrayEquals(endpoint.allowedIps, expected.allowedIps) && emptyArray(endpoint.denyRules) && endpoint.allowEncodedSlash === false && endpoint.persistedQueries === "" && @@ -101,24 +113,19 @@ function nativeEndpoint(value: unknown): boolean { ); } -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( + value.map((item) => record(item)?.path), + expected, + ); } /** Verify the live custom profile at the credential, egress, and binary security boundary. */ -export function isManagedNativeNvidiaProfileResponse( +function isManagedNativeProfileResponse( value: unknown, -): value is NativeNvidiaProfileResponse { + expected: NativeBoundary, +): value is NativeProfileResponse { const response = record(value); const profile = record(response?.profile); const revision = profile?.resourceVersion; @@ -126,7 +133,7 @@ export function isManagedNativeNvidiaProfileResponse( const endpoints = profile?.endpoints; return ( profile !== null && - profile.id === "nemoclaw-nvidia-inference-v1" && + profile.id === expected.id && profile.source === "user" && (profile.scope === "platform" || profile.scope === "workspace") && (typeof revision === "bigint" || typeof revision === "string") && @@ -135,10 +142,46 @@ export function isManagedNativeNvidiaProfileResponse( profile.discovery === undefined && Array.isArray(credentials) && credentials.length === 1 && - nativeCredential(credentials[0]) && + nativeCredential(credentials[0], expected.credentialEnv) && Array.isArray(endpoints) && endpoints.length === 1 && - nativeEndpoint(endpoints[0]) && - nativeBinaries(profile.binaries) + nativeEndpoint(endpoints[0], expected) && + nativeBinaries(profile.binaries, expected.binaries) ); } + +export function isManagedNativeNvidiaProfileResponse( + value: unknown, +): value is NativeProfileResponse { + return isManagedNativeProfileResponse(value, { + id: "nemoclaw-nvidia-inference-v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + allowedIps: [], + binaries: [ + "/usr/local/bin/node", + "/usr/bin/node", + "/opt/hermes/.venv/bin/python", + "/opt/hermes/.venv/bin/python3", + "/opt/venv/bin/python3", + "/usr/local/bin/curl", + "/usr/bin/curl", + ], + }); +} + +export function isManagedNativeLocalProfileResponse( + value: unknown, + binding: NativeLocalBinding, +): value is NativeProfileResponse { + const expected = prepareNativeLocalProfile(binding); + const endpoint = expected.document.endpoints[0]; + if (!endpoint) return false; + return isManagedNativeProfileResponse(value, { + id: expected.profileId, + credentialEnv: binding.credentialEnv, + endpointUrl: binding.endpointUrl, + allowedIps: endpoint.allowed_ips, + 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 6fb13b4f17d..0e050cd9edd 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.ts @@ -756,6 +756,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 ec4e0c43d91..19eb89da6c4 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -24,7 +24,10 @@ import { BuiltinNvidiaProfileResponseSchema, ProviderResponseSchema, } from "./sdk-read-schema"; -import { isManagedNativeNvidiaProfileResponse } from "./native-nvidia-profile-response"; +import { + isManagedNativeNvidiaProfileResponse, + isManagedNativeLocalProfileResponse, +} from "./native-inference-profile-response"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; import { @@ -41,7 +44,13 @@ const managedProfileSchemas = { "tavily-hermes-v1": ManagedHermesTavilyProfileResponseSchema, }; type ManagedProfileContract = keyof typeof managedProfileSchemas; -type ProfileContract = ManagedProfileContract | "native-nvidia"; +type ProfileContract = + | ManagedProfileContract + | "native-nvidia" + | { + kind: "native-local"; + binding: Parameters[1] & { profileId: string }; + }; export type Provider = Readonly< Pick & { @@ -54,7 +63,7 @@ export type Provider = Readonly< profileWorkspace?: string; // null records a successful not-found read at the OpenAI provider's profile binding. managedProfile?: Readonly<{ - id: ManagedProfileContract | typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; + id: string; source: "builtin" | "user"; scope: "" | "platform" | "workspace"; resourceVersion: string; @@ -88,6 +97,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: ReadRequest, @@ -95,8 +109,7 @@ async function readManagedProfile( providerType: string, profileWorkspace: string | undefined, ): Promise | null> { - const profileId = - profileContract === "native-nvidia" ? NVIDIA_HOSTED_NATIVE_PROFILE_ID : profileContract; + const profileId = managedProfileId(profileContract); if ( providerType !== profileId || (profileWorkspace !== "" && profileWorkspace !== request.workspace) @@ -121,11 +134,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 { @@ -141,6 +163,12 @@ function validateManagedProfileResponse( profileContract: ProfileContract, profileWorkspace: string, ): NonNullable { + if (typeof profileContract === "object") + return validateNativeManagedProfileResponse( + response, + profileWorkspace, + profileContract.binding, + ); if (profileContract === "native-nvidia") { return validateNativeManagedProfileResponse(response, profileWorkspace); } @@ -165,7 +193,9 @@ function validateManagedProfileResponse( function managedInferenceEndpointFor( managedProfile: Provider["managedProfile"], + contract: ProfileContract | undefined, ): string | undefined { + if (typeof contract === "object") return contract.binding.endpointUrl; return managedProfile?.id === NVIDIA_HOSTED_NATIVE_PROFILE_ID ? NVIDIA_HOSTED_NATIVE_ENDPOINT : undefined; @@ -203,7 +233,10 @@ async function readProfileEvidence( provider.type, provider.profileWorkspace, ); - const managedInferenceEndpoint = managedInferenceEndpointFor(managedProfile); + const managedInferenceEndpoint = managedInferenceEndpointFor( + managedProfile, + request.profileContract, + ); return { ...(builtinInferenceEndpoint === undefined ? {} : { builtinInferenceEndpoint }), ...(provider.profileWorkspace === undefined diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index eae6be1a39e..7799991f6b5 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", "nimContainer", "observabilityEnabled", "openshellDriver", @@ -93,6 +95,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, ) { @@ -134,12 +154,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"; + readonly id: string; readonly source: "builtin" | "user"; readonly scope: "" | "platform" | "workspace"; readonly resourceVersion: string; @@ -154,7 +169,7 @@ export interface ObservedExportEndpointEvidence { | { readonly kind: "builtin-profile"; readonly profileId: "nvidia" } | { readonly kind: "managed-profile"; - readonly profileId: "nemoclaw-nvidia-inference-v1"; + readonly profileId: string; }; } diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 3359b06659b..f85bc3d9e00 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -43,7 +43,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 { @@ -545,6 +549,7 @@ function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedSt selected.provider, selected.model, selected.preferredInferenceApi, + entry.nativeLocalProviderAttachment?.endpointUrl, ); const projection = EXPORT_AGENT_PROFILE_PROJECTIONS[agent](inference); const search = exportWebSearchBinding(entry); @@ -809,40 +814,86 @@ function classifyManagedStartupProfile( return [...findings, ...classifyProfileEquality(profile, supported)]; } +function nativeNvidiaEndpointEvidenceMatches(snapshot: QualifiedExportSnapshot): boolean { + const { inference } = snapshot; + const evidence = inference.endpointEvidence; + if (!evidence || evidence.source.kind !== "managed-profile") return false; + const receipt = normalizeNativeNvidiaProviderAttachment( + snapshot.registry.nativeNvidiaProviderAttachment, + ); + return ( + receipt !== undefined && + isDeepStrictEqual( + [ + evidence.source.profileId, + evidence.provider.name, + evidence.provider.id, + inference.provider, + inference.api, + inference.endpoint, + evidence.endpoint, + inference.credentialEnv, + ], + [ + NVIDIA_HOSTED_NATIVE_PROFILE_ID, + receipt.providerName, + receipt.providerId, + NVIDIA_HOSTED_LOGICAL_PROVIDER, + "openai-completions", + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_NATIVE_ENDPOINT, + NVIDIA_HOSTED_CREDENTIAL_ENV, + ], + ) + ); +} + +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 endpointEvidenceMatchesRoute(snapshot: QualifiedExportSnapshot): boolean { const { inference } = snapshot; const evidence = inference.endpointEvidence; if (!evidence) return false; - if (evidence.source.kind === "managed-profile") { - const receipt = normalizeNativeNvidiaProviderAttachment( - snapshot.registry.nativeNvidiaProviderAttachment, - ); - return ( - receipt !== undefined && - isDeepStrictEqual( - [ - evidence.source.profileId, - evidence.provider.name, - evidence.provider.id, - inference.provider, - inference.api, - inference.endpoint, - evidence.endpoint, - inference.credentialEnv, - ], - [ - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - receipt.providerName, - receipt.providerId, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - "openai-completions", - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_CREDENTIAL_ENV, - ], - ) - ); - } + if (snapshot.registry.nativeLocalProviderAttachment !== undefined) + return nativeLocalEndpointEvidenceMatches(snapshot); + if (evidence.source.kind === "managed-profile") + return nativeNvidiaEndpointEvidenceMatches(snapshot); if (evidence.source.kind === "builtin-profile") { return ( inference.credentialEnv !== null && @@ -916,9 +967,8 @@ function validateSandboxIdentity( function sandboxProviderAttachmentsMatch(snapshot: QualifiedExportSnapshot): boolean { const { registry: entry, sandbox, inference } = snapshot; - const nativeReceipt = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAttachment, - ); + const nativeReceipt = exportNativeInferenceReceipt(entry); + if (nativeReceipt === null) return false; const inferenceAttachment = nativeReceipt?.providerName ?? inference.provider; const additionalProviders = sandbox.providerNames.filter((name) => name !== inferenceAttachment); const webSearch = exportWebSearchBinding(entry); @@ -1238,8 +1288,7 @@ function validateInferenceRepresentation(snapshot: QualifiedExportSnapshot): Exp function expectedEndpointProviderName(snapshot: QualifiedExportSnapshot): string { return ( - normalizeNativeNvidiaProviderAttachment(snapshot.registry.nativeNvidiaProviderAttachment) - ?.providerName ?? snapshot.inference.provider + exportNativeInferenceReceipt(snapshot.registry)?.providerName ?? snapshot.inference.provider ); } diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index f5b376f741f..fb3f0a27460 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -368,6 +368,21 @@ describe("inference selection config", () => { }); describe("getSandboxInferenceConfig", () => { + it.each([ + ["compatible-endpoint", "http://host.openshell.internal:42103/v1", INFERENCE_ROUTE_URL], + [ + "compatible-endpoint", + "http://host.openshell.internal:8000/v1", + "http://host.openshell.internal:8000/v1", + ], + ["ollama-local", "http://192.168.65.2:11435/v1", "http://192.168.65.2:11435/v1"], + ])("selects %s transport for %s (#12558)", (provider, endpoint, expected) => { + expect( + getSandboxInferenceConfig("model-a", provider, "openai-completions", 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 b34a207a0e9..81b0b87fc9d 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, @@ -20,7 +25,13 @@ 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 { OLLAMA_LOCAL_CREDENTIAL_ENV }; export { managedInferenceApiKey, NVIDIA_INFERENCE_PLACEHOLDER } from "../inference-credential"; export { @@ -321,6 +332,7 @@ export function getSandboxInferenceConfig( model: string, provider: string | null = null, preferredInferenceApi: string | null = null, + nativeEndpointUrl: string | null = null, ): SandboxInferenceConfig { let providerKey: string; let primaryModelRef: string; @@ -408,6 +420,14 @@ export function getSandboxInferenceConfig( break; } + if ( + 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.ts b/src/lib/inference/gateway-route-compatibility.ts index 9505a1764c4..a45a74ce223 100644 --- a/src/lib/inference/gateway-route-compatibility.ts +++ b/src/lib/inference/gateway-route-compatibility.ts @@ -499,3 +499,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/gateway/route-contract.ts b/src/lib/inference/gateway/route-contract.ts index 4638ea13c0a..e046641acd2 100644 --- a/src/lib/inference/gateway/route-contract.ts +++ b/src/lib/inference/gateway/route-contract.ts @@ -9,10 +9,11 @@ export function resolveManagedStartupInferenceRoute( provider: string, model: string, preferredInferenceApi: string | null, + nativeEndpointUrl?: string, ) { const api = agentName === "langchain-deepagents-code" ? "openai-completions" : resolveAgentInferenceApi(agentName, provider, preferredInferenceApi); - return getSandboxInferenceConfig(model, provider, api); + return getSandboxInferenceConfig(model, provider, api, nativeEndpointUrl); } diff --git a/src/lib/inference/native-local.test.ts b/src/lib/inference/native-local.test.ts new file mode 100644 index 00000000000..9d4f6a853ab --- /dev/null +++ b/src/lib/inference/native-local.test.ts @@ -0,0 +1,375 @@ +// 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, + 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([ + ["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).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..8c6ba5f74a8 --- /dev/null +++ b/src/lib/inference/native-local/agent-config.ts @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const NATIVE_LOCAL_CREDENTIAL_ENV = "NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + +/** 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; + try { + const endpoint = new URL(endpointUrl); + const host = endpoint.hostname; + const privateIpv4 = + /^10\.\d+\.\d+\.\d+$/.test(host) || + /^192\.168\.\d+\.\d+$/.test(host) || + /^172\.(1[6-9]|2[0-9]|3[01])\.\d+\.\d+$/.test(host); + if ( + endpoint.protocol !== "http:" || + endpoint.username || + endpoint.password || + (!privateIpv4 && host !== "host.openshell.internal" && host !== "host.docker.internal") + ) + return null; + return `openshell:resolve:env:${NATIVE_LOCAL_CREDENTIAL_ENV}`; + } catch { + return 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..313d9a59ee7 --- /dev/null +++ b/src/lib/inference/native-local/contract.ts @@ -0,0 +1,192 @@ +// 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 { isIP } from "node:net"; +import { unsafeEndpointUrlViolation } from "../../core/endpoint-url-safety"; +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" || + unsafeEndpointUrlViolation(input.endpointUrl) || + 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; + try { + const endpoint = new URL(input.endpointUrl); + const host = endpoint.hostname; + // Loopback always identifies the sandbox itself. Public or arbitrary DNS + // names belong to hosted endpoint validation, not the host-local bridge. + 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 undefined; + return { + provider: input.provider as NativeLocalProvider, + endpointUrl: `${endpoint.origin}${endpoint.pathname.replace(/\/$/, "")}`, + credentialEnv: input.credentialEnv, + authMode: input.authMode, + gatewayName: input.gatewayName, + sandboxName: input.sandboxName, + ...(typeof input.transactionId === "string" ? { transactionId: input.transactionId } : {}), + }; + } catch { + return undefined; + } +} + +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..6a486c853e3 --- /dev/null +++ b/src/lib/inference/native-local/profile.ts @@ -0,0 +1,189 @@ +// 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/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-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts index e449c06b9f6..80699e5649e 100644 --- a/src/lib/inference/native-nvidia/index.ts +++ b/src/lib/inference/native-nvidia/index.ts @@ -2,19 +2,25 @@ // SPDX-License-Identifier: Apache-2.0 import path from "node:path"; +import type { OpenShellProviderMetadata } from "../../adapters/openshell/provider-adapter"; +import { + NativeProviderError as NativeNvidiaProviderError, + ensureNativeProvider, + nativeProviderAttachmentFromMetadata, + persistNativeProviderAuthority, + verifyNativeProviderAttachment, + ensureNativeProviderAttached, + detachNativeProvider, + type NativeProviderAttachment, +} from "../native-provider/lifecycle"; -import type { - OpenShellGatewayTarget, - OpenShellProviderAdapter, - OpenShellProviderError, - OpenShellProviderMetadata, -} from "../../adapters/openshell/sandbox-observer"; import { REPOSITORY_ROOT } from "../../core/repository-root"; import { NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, + normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, } from "./contract"; @@ -28,12 +34,7 @@ export { type NativeNvidiaProviderAttachment, } from "./contract"; -export class NativeNvidiaProviderError extends Error { - constructor(message: string) { - super(message); - this.name = "NativeNvidiaProviderError"; - } -} +export { NativeProviderError as NativeNvidiaProviderError } from "../native-provider/lifecycle"; export function nativeNvidiaProviderProfilePath(root = REPOSITORY_ROOT): string { return path.join( @@ -72,401 +73,111 @@ export function nativeInferenceProviderForSandbox( return isNativeNvidiaProvider(normalized) ? NVIDIA_HOSTED_NATIVE_PROVIDER : normalized; } -function providerErrorDetail(error: OpenShellProviderError): string { - return error.message.trim() || "OpenShell did not provide a diagnostic."; -} - async function requireNativeNvidiaProviderProfileBoundary( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, - profilePath = nativeNvidiaProviderProfilePath(), + input: Parameters[0], ): Promise { - const imported = await adapter.importProviderProfile({ target, profilePath }); - if (imported.ok) return; - const collision = - imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; + const result = await input.adapter.importProviderProfile({ + target: input.target, + profilePath: nativeNvidiaProviderProfilePath(), + }); + if (result.ok) return; throw new NativeNvidiaProviderError( - collision + result.error.kind === "command" && result.error.reason === "profile_incompatible" ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` - : `Could not verify OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, + : `Could not verify OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${result.error.message}`, ); } -function exactNativeProvider(metadata: OpenShellProviderMetadata): boolean { - return ( - metadata.name === NVIDIA_HOSTED_NATIVE_PROVIDER && - metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID && - metadata.configKeys.length === 0 && - metadata.credentialKeys.length === 1 && - metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && - Boolean(metadata.revision?.id) - ); -} - -export function nativeNvidiaProviderAttachmentFromMetadata( - metadata: OpenShellProviderMetadata, -): NativeNvidiaProviderAttachment { - if (!exactNativeProvider(metadata) || !metadata.revision) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' does not match the NemoClaw-owned NVIDIA inference boundary. No provider was changed.`, - ); - } +function nativeProfile(profilePath = nativeNvidiaProviderProfilePath()) { return { - schemaVersion: 1, profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: metadata.revision.id, + credentialEnv: NVIDIA_HOSTED_CREDENTIAL_ENV, + label: "NVIDIA", + profilePath, }; } - -async function inspectNativeProvider( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, -): Promise { - const observed = await adapter.getProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (observed.ok) return observed.value; - if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; - throw new NativeNvidiaProviderError( - `Could not inspect OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(observed.error)}`, - ); +function nvidiaReceipt(receipt: NativeProviderAttachment): NativeNvidiaProviderAttachment { + const normalized = normalizeNativeNvidiaProviderAttachment(receipt); + if (!normalized) + throw new NativeNvidiaProviderError("OpenShell returned an invalid NVIDIA provider identity."); + return normalized; } - -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") +export function nativeNvidiaProviderAttachmentFromMetadata( + metadata: OpenShellProviderMetadata, +): NativeNvidiaProviderAttachment { + return nvidiaReceipt(nativeProviderAttachmentFromMetadata(metadata, nativeProfile())); +} + +export async function ensureNativeNvidiaProvider( + input: Omit< + Parameters[0], + "profile" | "expected" | "prepareProviderPolicy" + > & { + expected?: NativeNvidiaProviderAttachment; + }, +): Promise { + return nvidiaReceipt( + await ensureNativeProvider({ + ...input, + profile: nativeProfile(input.profilePath), + prepareProviderPolicy: async () => { + const result = await input.adapter.ensureProviderPolicyComposition({ + target: input.target, + }); + if (!result.ok) { + throw new NativeNvidiaProviderError( + `Could not activate native NVIDIA provider policy: ${result.error.message.trim() || "OpenShell did not provide a diagnostic."}`, + ); + } + }, + }), ); } - -function authorityPersistenceRecovery(gatewayName: string): string { - return `Run 'nemoclaw credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER} --yes' against gateway '${gatewayName}', then retry.`; -} - -async function removeNewNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const removed = await input.adapter.deleteProvider({ - target: input.target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!removed.ok && !mutationOutcomeMayBeAmbiguous(removed.error)) { - throw new NativeNvidiaProviderError( - `Could not remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(removed.error)}`, - ); - } - const after = await inspectNativeProvider(input.adapter, input.target); - if (after) { - const observed = nativeNvidiaProviderAttachmentFromMetadata(after); - const identity = - observed.providerId === input.expected.providerId ? "still exists" : "changed identity"; - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' ${identity} after cleanup.`, - ); - } -} - -/** Record provider authority or remove only the new, unreferenced provider. */ -export async function persistNativeNvidiaProviderAuthority(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - gatewayName: string; - receipt: NativeNvidiaProviderAttachment; - existing?: NativeNvidiaProviderAttachment; - readAuthority: (gatewayName: string) => NativeNvidiaProviderAttachment | undefined; - writeAuthority: (gatewayName: string, receipt: NativeNvidiaProviderAttachment) => void; -}): Promise { - try { - input.writeAuthority(input.gatewayName, input.receipt); - return; - } catch (writeError) { - const writeDetail = writeError instanceof Error ? writeError.message : String(writeError); - let observed: NativeNvidiaProviderAttachment | undefined; - try { - observed = input.readAuthority(input.gatewayName); - } catch (readError) { - const readDetail = readError instanceof Error ? readError.message : String(readError); - throw new NativeNvidiaProviderError( - `NemoClaw could not record or confirm ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Read failure: ${readDetail}`, - ); - } - if (observed?.providerId === input.receipt.providerId) return; - if (input.existing || observed) { - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained because this operation cannot prove that it is unreferenced. ${authorityPersistenceRecovery(input.gatewayName)}\n ${writeDetail}`, - ); - } - try { - await removeNewNativeNvidiaProvider({ - adapter: input.adapter, - target: input.target, - expected: input.receipt, - }); - } catch (cleanupError) { - const cleanupDetail = - cleanupError instanceof Error ? cleanupError.message : String(cleanupError); - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}', and cleanup did not complete. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Cleanup failure: ${cleanupDetail}`, - ); - } - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The newly created provider was removed. Retry the command.\n ${writeDetail}`, - ); - } -} - -/** Ensure the least-privilege NVIDIA profile and provider without retrying an ambiguous mutation. */ -export async function ensureNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - credentialValue: string | null; - reuseExistingCredential?: boolean; - expected?: NativeNvidiaProviderAttachment; - profilePath?: string; -}): Promise { - const { adapter, target } = input; - await requireNativeNvidiaProviderProfileBoundary( - adapter, - target, - input.profilePath ?? nativeNvidiaProviderProfilePath(), +export async function verifyNativeNvidiaProviderAttachment( + input: Omit[0], "profile" | "expected"> & { + expected?: NativeNvidiaProviderAttachment; + }, +): Promise { + await requireNativeNvidiaProviderProfileBoundary({ ...input, profile: nativeProfile() }); + return nvidiaReceipt( + await verifyNativeProviderAttachment({ ...input, profile: nativeProfile() }), ); - - const activatePolicy = async () => { - const policy = await adapter.ensureProviderPolicyComposition({ target }); - if (!policy.ok) { - throw new NativeNvidiaProviderError( - `Could not activate native NVIDIA provider policy: ${providerErrorDetail(policy.error)}`, - ); - } - }; - - const before = await inspectNativeProvider(adapter, target); - if (before) { - const receipt = nativeNvidiaProviderAttachmentFromMetadata(before); - if (!input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' already exists without a matching NemoClaw ownership receipt. No provider was changed.`, - ); - } - if (input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - await activatePolicy(); - if (!input.credentialValue) return receipt; - const updated = await adapter.updateProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], - config: [], - }); - if (!updated.ok && mutationOutcomeMayBeAmbiguous(updated.error)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm whether provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' accepted its credential update. No provider receipt was recorded.`, - ); - } - if (!updated.ok) { - throw new NativeNvidiaProviderError( - `Could not update OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(updated.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after its credential update.`, - ); - } - const observedReceipt = nativeNvidiaProviderAttachmentFromMetadata(observed); - if (observedReceipt.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity during its credential update. No provider receipt was recorded.`, - ); - } - return observedReceipt; - } - - if (input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - - if (!input.credentialValue && !input.reuseExistingCredential) { - throw new NativeNvidiaProviderError( - `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, - ); - } - await activatePolicy(); - const created = await adapter.createProvider({ - target, - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: input.credentialValue - ? [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }] - : [], - config: [], - fromExisting: !input.credentialValue, - }); - if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { - throw new NativeNvidiaProviderError( - `Could not create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(created.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after creation.`, - ); - } - return nativeNvidiaProviderAttachmentFromMetadata(observed); -} - -/** Prove that the exact NemoClaw-owned NVIDIA provider is attached to one sandbox. */ -export async function verifyNativeNvidiaProviderAttachment(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected?: NativeNvidiaProviderAttachment; -}): Promise { - await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (input.expected && input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const attachments = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!attachments.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, - ); - } - if (!attachments.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `Sandbox '${input.sandboxName}' does not have its native NVIDIA inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, - ); - } - return receipt; -} - -/** Attach native NVIDIA access and reconcile an ambiguous command through observation. */ -export async function ensureNativeNvidiaProviderAttached(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { - await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (receipt.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const before = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!before.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, - ); - } - if (before.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: false, - }; - } - const attached = await input.adapter.attachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { - throw new NativeNvidiaProviderError( - `Could not attach native NVIDIA provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, - ); - } - try { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: true, - }; - } catch (error) { - try { - await detachNativeNvidiaProvider(input); - } catch (detachError) { - const detail = error instanceof Error ? error.message : String(error); - const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); - throw new NativeNvidiaProviderError(`${detail}\n ${detachDetail}`); - } - throw error; - } } - -/** Detach only the recorded native NVIDIA provider identity and prove absence. */ -export async function detachNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to detach OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const detached = await input.adapter.detachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { - throw new NativeNvidiaProviderError( - `Could not detach native NVIDIA provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, - ); - } - const after = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, +export async function ensureNativeNvidiaProviderAttached( + input: Omit[0], "profile" | "expected"> & { + expected: NativeNvidiaProviderAttachment; + }, +): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { + await requireNativeNvidiaProviderProfileBoundary({ ...input, profile: nativeProfile() }); + const result = await ensureNativeProviderAttached({ ...input, profile: nativeProfile() }); + return { ...result, receipt: nvidiaReceipt(result.receipt) }; +} +export async function detachNativeNvidiaProvider( + input: Omit[0], "profile" | "expected"> & { + expected: NativeNvidiaProviderAttachment; + }, +): Promise { + return detachNativeProvider({ ...input, profile: nativeProfile() }); +} + +/** Persist before attaching; failed writes must not strand an unowned provider. */ +export async function persistNativeNvidiaProviderAuthority( + input: Omit< + Parameters[0], + "profile" | "recoveryGuidance" | "receipt" | "existing" | "readAuthority" | "writeAuthority" + > & { + receipt: NativeNvidiaProviderAttachment; + existing?: NativeNvidiaProviderAttachment; + readAuthority: (gatewayName: string) => NativeNvidiaProviderAttachment | undefined; + writeAuthority: (gatewayName: string, receipt: NativeNvidiaProviderAttachment) => void; + }, +): Promise { + return persistNativeProviderAuthority({ + ...input, + profile: nativeProfile(), + recoveryGuidance: `Run 'nemoclaw credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER} --yes' against gateway '${input.gatewayName}', then retry.`, + writeAuthority: (gatewayName, receipt) => + input.writeAuthority(gatewayName, nvidiaReceipt(receipt)), }); - if (!after.ok || after.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm removal of native NVIDIA access from sandbox '${input.sandboxName}'.`, - ); - } } diff --git a/src/lib/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/onboard.ts b/src/lib/onboard.ts index 17cd5e0d654..58fa483c8ae 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({ 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.test.ts b/src/lib/onboard/compatible-endpoint-smoke.test.ts index 39bdc196a24..e14b2521fcc 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.test.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.test.ts @@ -1,13 +1,20 @@ // 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, @@ -123,173 +130,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 +154,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 +191,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { () => ({ status: testCase.status, stdout: providerMetadata("compatible-endpoint") }), executor, (value) => value, + () => null, ); try { await expect( @@ -769,6 +615,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 +1342,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..1e1f8077d1f 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -1,6 +1,12 @@ // 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 { 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"; @@ -113,6 +119,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 +128,30 @@ 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 && 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 +168,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 +203,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 +223,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 +238,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 +254,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 +276,7 @@ export function createCompatibleEndpointSmoke( ): Promise { return verifyCompatibleEndpointSandboxSmoke({ ...options, + ...nativeSelection(options), runOpenshell: run, sandboxCommandExecutor, redact, @@ -250,6 +294,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 +547,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 +563,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 +621,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 +629,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 +689,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 +699,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 +724,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 +732,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-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index 4bb0fdf494f..7cd5e043d2b 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"; @@ -1136,9 +1137,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(() => []) }; @@ -1288,6 +1306,7 @@ describe("created sandbox completion actions", () => { throw new Error(`unexpected exit ${code}`); }, registerCreatedSandbox, + retireNativeLocalProviders, }, ); const created = { @@ -1344,7 +1363,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, @@ -1373,6 +1400,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, @@ -1385,110 +1413,41 @@ describe("created sandbox completion actions", () => { ), ).rejects.toBe(proofFailure); expect(registerCreatedSandbox).not.toHaveBeenCalled(); - }, - ); -}); + expect(retireNativeLocalProviders).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}`); - }, - }; - } - - 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, - ); - }); + 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 69b869b0ea5..74d378886e6 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"; @@ -172,6 +175,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; @@ -551,12 +555,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; }, }, ); 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..9714346def4 --- /dev/null +++ b/src/lib/onboard/created-sandbox-selection-reconciliation.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, + }); +}); + +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, + ); + }); + + 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 c005e94c845..25935dc2fda 100644 --- a/src/lib/onboard/dcode-selection-drift.test.ts +++ b/src/lib/onboard/dcode-selection-drift.test.ts @@ -70,6 +70,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("limits the managed identity contract to stock DCode images (#6311)", () => { expect(usesManagedDcodeIdentity("langchain-deepagents-code", null)).toBe(true); expect(usesManagedDcodeIdentity("langchain-deepagents-code", "/tmp/Dockerfile")).toBe(false); diff --git a/src/lib/onboard/dcode-selection-drift.ts b/src/lib/onboard/dcode-selection-drift.ts index f0afce7a5d2..9ffcd03d373 100644 --- a/src/lib/onboard/dcode-selection-drift.ts +++ b/src/lib/onboard/dcode-selection-drift.ts @@ -92,7 +92,12 @@ export function getExpectedDcodeInferenceIdentity( ): DcodeInferenceIdentity | null { if (requestedModel === null) return null; - const route = getSandboxInferenceConfig(requestedModel, requestedProvider, preferredInferenceApi); + const route = getSandboxInferenceConfig( + requestedModel, + requestedProvider, + preferredInferenceApi, + requestedEndpointUrl, + ); const managedIdentity = resolveManagedDcodeIdentity( requestedProvider, requestedModel, 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.ts b/src/lib/onboard/dockerfile-patch.ts index 2a704758346..86c1699b399 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,7 @@ export function renderHermesPortableDockerfileBuildSettings( input.model, input.provider, input.preferredInferenceApi, + 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..6f8b785ec12 100644 --- a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts +++ b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts @@ -125,6 +125,10 @@ 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 same metadata-only instruction includes the native-local config input. + "aa67a56299fedea5c7130da731ef3ee58a9800a69e7f92e5f13e64a54faab6ab", + // The same instruction after removing a duplicate wrapper chmod operand. + "d70666fe15aa35161e49de378e90a3b7994814bca11efa9ca96b2581fac63b0f", // 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.ts b/src/lib/onboard/inference-providers/remote.ts index 36c2772d3ee..5ed7e22ce22 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,20 @@ 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; + if (!reserveSandboxInferenceRoute(sandboxName, { model, provider })) { + throw new Error( + "Native local inference could not publish its proxy owner. 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 66c4e39d75b..5a6d44df4f8 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -89,6 +89,7 @@ export type Registry = { }; export type CommonDeps = { + nativeLocalInference?: boolean; runOpenshell: RunOpenshell; upsertProvider: UpsertProvider; verifyInferenceRoute: VerifyInferenceRoute; 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-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 49a7518110e..7ec8435f8e5 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test.ts @@ -1465,6 +1465,7 @@ describe("handleProviderInferenceState", () => { null, [], setupOptions(session, { + agentName: "openclaw", allowToolsIncompatible: true, preferredInferenceApi: "openai-responses", }), diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index d3b84deb23d..c73e4a6d0e0 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -3,7 +3,10 @@ import type { ModelSelectionProvenance } from "../../../domain/telemetry/provenance"; import { clearAutoDetectedCompatibleContextWindow } from "../../../inference/compatible-endpoint-context"; -import { resolveAgentProviderInferenceApi } from "../../../inference/config"; +import { + resolveAgentProviderInferenceApi, + usesNativeLocalInference, +} from "../../../inference/config"; import type { TrustedPrivateEndpointCapability } from "../../../inference/endpoint-ssrf-preflight"; import { type CurrentGatewayRouteCompatibilityCheck, @@ -75,6 +78,7 @@ import { export type ProviderInferenceRetry = { retry: "selection" } | { ok: true; retry?: undefined }; export interface ProviderInferenceSetupOptions { + agentName?: string; gatewayName?: string; allowToolsIncompatible?: boolean; skipHostInferenceSmoke?: boolean; @@ -1240,6 +1244,10 @@ async function resolveSelectionSandboxName( return deps.promptValidatedSandboxName(agent); } +function nativeLocalAgentOptions(agent: unknown, provider: string, endpointUrl: string | null) { + return usesNativeLocalInference(provider, endpointUrl) ? { agentName: agentName(agent) } : {}; +} + export async function handleProviderInferenceState({ gatewayName, resume, @@ -1811,6 +1819,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 } : {}), @@ -2104,6 +2113,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 ab5b76f563b..9ea8e89a0e2 100644 --- a/src/lib/onboard/machine/handlers/sandbox-dcode-resume.ts +++ b/src/lib/onboard/machine/handlers/sandbox-dcode-resume.ts @@ -118,7 +118,7 @@ export async function resolveSignals( options.provider, options.model, options.preferredInferenceApi, - options.endpointUrl, + registryEntry.nativeLocalProviderAttachment?.endpointUrl ?? options.endpointUrl, ); return { inferenceSelectionChanged: Boolean(drift.changed || drift.unknown), diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index e67d1c3f884..565ab9ddc07 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeLocalProviderAttachment } from "../../../inference/gateway-route-compatibility"; + import { type CurrentGatewayRouteCompatibilityCheck, formatGatewayRouteConflict, @@ -135,18 +137,24 @@ type SandboxRecreateWorkloadSkipReason = Extract< { readonly status: "skipped" } >["reason"]; -function nativeNvidiaCreateIntentFields( +function nativeInferenceCreateIntentFields( provider: string | null | undefined, entry: SandboxEntry | null, ): { inferenceProvider: string | null; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; } { + const nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( + entry?.nativeLocalProviderAttachment, + ); const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( entry?.nativeNvidiaProviderAttachment, ); return { - inferenceProvider: nativeInferenceProviderForSandbox(provider), + inferenceProvider: + nativeLocalProviderAttachment?.providerName ?? nativeInferenceProviderForSandbox(provider), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), }; } @@ -373,6 +381,7 @@ export interface SandboxStateOptions< resolveSandboxCreateIntent(input: { sandboxName: string; inferenceProvider?: string | null; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[]; @@ -1884,7 +1893,7 @@ class SandboxStateFlow< const registeredEntry = this.deps.getSandboxRegistryEntry(sandboxName); const resolved = await this.deps.resolveSandboxCreateIntent({ sandboxName, - ...nativeNvidiaCreateIntentFields(this.options.provider, registeredEntry), + ...nativeInferenceCreateIntentFields(this.options.provider, registeredEntry), hostLocalInferenceRouteOnly: this.options.hostLocalInferenceRouteOnly === true, enabledChannels: state.selectedMessagingChannels, webSearchConfig: state.webSearchConfig, @@ -1897,6 +1906,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, @@ -1917,7 +1928,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 67b239b0929..b8c82bb6f07 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"; @@ -35,6 +36,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! @@ -178,6 +194,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 b5f7a09a559..7d065d13bf5 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -198,6 +198,7 @@ export interface CreateManagedWorkloadOnboardRuntimeInput { readonly provider: string | null; readonly preferredInferenceApi: string | null; readonly endpointUrl: string | null; + readonly nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; readonly startupProfile: ManagedProfileInput; readonly note: (message: string) => void; readonly fallbackBuildEstimate: () => string | null; @@ -395,6 +396,11 @@ 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 endpointUrl = nativeLocalProviderAttachment?.endpointUrl ?? input.endpointUrl; const selectedModel = input.model?.trim() || ""; const selectedProvider = input.provider?.trim() || null; const inferenceApi = @@ -409,11 +415,12 @@ export function createManagedWorkloadOnboardRuntime( selectedModel, selectedProvider, inferenceApi, + nativeLocalProviderAttachment?.endpointUrl ?? null, ); preparedProfile = buildManagedStartupOnboardProfile({ agentName: input.agentName, inference: - !selectedModel && !selectedProvider && !input.preferredInferenceApi && !input.endpointUrl + !selectedModel && !selectedProvider && !input.preferredInferenceApi && !endpointUrl ? null : { routeProvider: inference.providerKey, @@ -421,7 +428,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/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 a258271e590..eba02f5c676 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -1,6 +1,8 @@ // 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 { WebSearchConfig } from "../inference/web-search"; import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; @@ -27,6 +29,7 @@ import { export type CompleteSandboxCreateIntentInput = { sandboxName: string; inferenceProvider?: string | null; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[] | null; @@ -146,6 +149,7 @@ export function createSandboxCreateIntentResolver< basePolicyPath: deps.getAgentPolicyPath(input.agent) || deps.defaultPolicyPath, sandboxName: input.sandboxName, inferenceProvider: input.inferenceProvider, + nativeLocalProviderAttachment: input.nativeLocalProviderAttachment, nativeNvidiaProviderAttachment: input.nativeNvidiaProviderAttachment, hostLocalInferenceRouteOnly: input.hostLocalInferenceRouteOnly === true, channels: deps.channels, diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index d12c693881f..9467bd4856e 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -1,6 +1,8 @@ // 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 { SandboxHostMount } from "../state/registry/types"; import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; import type { MessagingChannelConfig } from "../messaging-channel-config"; @@ -48,6 +50,7 @@ export type SandboxCreatePolicyRequest = { export type SandboxCreateIntent = { readonly sandboxName: string; readonly inferenceProvider: string | null; + readonly nativeLocalProviderAttachment?: NativeLocalProviderAttachment; readonly nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; readonly activeMessagingChannels: readonly string[]; readonly messagingProviderRequests: readonly SandboxCreateMessagingProviderRequest[]; @@ -70,6 +73,7 @@ export type ResolveSandboxCreateIntentInput = { basePolicyPath: string; sandboxName: string; inferenceProvider?: string | null; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; hostLocalInferenceRouteOnly?: boolean; channels: readonly MessagingChannel[]; diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index a039c03849a..c3d31e97ae4 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, hostLocalInferenceRouteOnly = false, channels, @@ -188,6 +189,7 @@ export function resolveSandboxCreateIntent({ return { sandboxName, inferenceProvider: normalizedInferenceProvider, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), activeMessagingChannels, messagingProviderRequests: messagingProviderRequests.map((request) => ({ ...request })), @@ -204,7 +206,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 c1c3c18a539..d034b44b3aa 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -89,6 +89,7 @@ import { publishAttachedProvidersBeforeDockerSandboxCreation, usesNativeNvidiaProvider, validateAttachedMessagingProvidersBeforeSandboxCreation, + verifyNativeLocalAttachmentAfterCreate, verifyNativeNvidiaAttachmentAfterCreate, } from "./provider-publication"; import { @@ -1425,6 +1426,7 @@ export function createProviderEffectBoundary(input: { readonly deferred: boolean; readonly sandboxName: string; readonly gatewayName: string; + readonly expectedNativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; readonly expectedNativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; readonly preparationInput: ProviderPreparationInput; readonly preparationDeps: ProviderPreparationDeps; @@ -1447,6 +1449,18 @@ export function createProviderEffectBoundary(input: { const attachAndVerifyNativeNvidiaProvider = 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: input.preparationDeps, + }); + return; + } if (!usesNativeNvidiaProvider(input.preparationInput.inferenceProvider)) return; context.revalidateSandboxIdentity( `attaching and verifying native NVIDIA provider for sandbox '${input.sandboxName}'`, @@ -1466,9 +1480,11 @@ export function createProviderEffectBoundary(input: { input.revalidateSandboxIdentityBeforeCreate(); await publish(); }, - runAfterVerifiedCreate: usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) - ? attachAndVerifyNativeNvidiaProvider - : undefined, + runAfterVerifiedCreate: + input.expectedNativeLocalProviderAttachment || + usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) + ? attachAndVerifyNativeNvidiaProvider + : undefined, }; } return { @@ -2021,6 +2037,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche provider, preferredInferenceApi, endpointUrl: createIntent?.endpointUrl ?? null, + nativeLocalProviderAttachment: resolvedCreateIntent.nativeLocalProviderAttachment, startupProfile: { chatUiUrl, effectiveDashboardPort: effectivePort, @@ -3560,6 +3577,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche deferred: createIntent?.deferSandboxEffectsUntilIdentityVerification === true, sandboxName, gatewayName: GATEWAY_NAME, + expectedNativeLocalProviderAttachment: resolvedCreateIntent.nativeLocalProviderAttachment, expectedNativeNvidiaProviderAttachment: resolvedCreateIntent.nativeNvidiaProviderAttachment, preparationInput: providerPreparationInput, preparationDeps: providerPreparationDeps, @@ -3667,6 +3685,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 ba011e54ea6..08cf5c5552f 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { ensureNativeLocalProviderAttached } from "../../inference/native-local/profile"; + import type { SandboxCreateOrchestrationRuntime } from "../../onboard"; import type { OpenShellProviderAdapter, @@ -89,6 +91,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, + }); +} + type ExpectedMessagingBindingInspection = | Readonly<{ kind: "exact" | "mismatch" }> | Readonly<{ kind: "failed"; error: OpenShellProviderError }>; 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..97f446943be 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -93,6 +93,44 @@ function createdRegistryEntryInput( } describe("buildCreatedSandboxRegistryEntry", () => { + 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("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 6b5aac4c802..9415b231d3b 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -1,6 +1,8 @@ // 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 { isDeepStrictEqual } from "node:util"; import type { AgentDefinition } from "../agent/defs"; import { isDeferredN1xManagedVllmAcceptanceRoute } from "../domain/sandbox/n1x-managed-vllm-rebuild"; @@ -26,7 +28,10 @@ import { 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"; @@ -80,6 +85,7 @@ export interface CreatedSandboxRegistryEntryInput { workload?: SandboxEntry["workload"]; hostLocalInferenceReceipt?: SandboxEntry["hostLocalInferenceReceipt"]; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; deferredN1xManagedVllmPreviewIntent?: true; toolDisclosure?: ToolDisclosure; @@ -236,6 +242,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 nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( input.nativeNvidiaProviderAttachment, ); @@ -293,6 +304,7 @@ export function buildCreatedSandboxRegistryEntry( workload, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(deferredN1xManagedVllmAccepted ? { deferredN1xManagedVllmAccepted: true as const } : {}), toolDisclosure: input.toolDisclosure ?? DEFAULT_TOOL_DISCLOSURE, @@ -369,21 +381,32 @@ 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 : pending?.nativeNvidiaProviderAttachment; const entry = buildCreatedSandboxRegistryEntry({ ...input, - inferenceSelection: pendingRoute - ? { ...input.inferenceSelection, ...pendingRoute } - : input.inferenceSelection, + inferenceSelection: effectiveSelection, ...(pendingHostLocalInferenceReceipt === undefined ? {} : { hostLocalInferenceReceipt: pendingHostLocalInferenceReceipt }), ...(pendingHostLocalInferenceProvenance === undefined ? {} : { hostLocalInferenceProvenance: pendingHostLocalInferenceProvenance }), + ...(pendingNativeLocalProviderAttachment + ? { nativeLocalProviderAttachment: pendingNativeLocalProviderAttachment } + : {}), ...(pendingNativeNvidiaProviderAttachment === undefined ? {} : { nativeNvidiaProviderAttachment: pendingNativeNvidiaProviderAttachment }), diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index bc6d98c1bad..a424a238b86 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 type { OpenShellGatewayLifecycle } from "../adapters/openshell/gateway-lifecycle"; import { canonicalEndpoint } from "../core/url-utils"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; @@ -206,6 +219,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). */ @@ -237,6 +251,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; getNativeNvidiaProviderAuthority?: typeof import("../state/registry").getNativeNvidiaProviderAuthority; setNativeNvidiaProviderAuthority?: typeof import("../state/registry").setNativeNvidiaProviderAuthority; unloadOllamaModels?: (onlyModels: readonly string[]) => OllamaUnloadResult | void; @@ -635,6 +652,41 @@ 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; +} + export function createSetupInference( defaults: SetupInferenceDeps, overrides: Partial = {}, @@ -656,6 +708,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); @@ -681,7 +742,7 @@ export function createSetupInference( ); return deps.exitProcess(1); } - if (!isNativeNvidiaProvider(provider)) { + if (!isNativeNvidiaProvider(provider) && !selectingNativeLocal) { const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ target: { kind: "named", gatewayName }, }); @@ -770,12 +831,14 @@ export function createSetupInference( const hostLocalProviderErrors: string[] = []; const hostLocalSelection = options.hostLocalInference; 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 nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; const reserveRoute = (name: string, selectedProvider: string, selectedModel: string) => { if (routeReserved) return true; @@ -795,6 +858,7 @@ export function createSetupInference( reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(hostLocalInferenceProvenance && hostLocalInferenceGatewayPortAuthority !== undefined ? { gatewayPort: hostLocalInferenceGatewayPortAuthority } @@ -806,6 +870,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; @@ -816,11 +882,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); @@ -833,12 +900,61 @@ 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 upsertProvider = hostLocalGatewayMutation?.upsertProvider ?? defaultUpsertProvider; return await upsertProvider(...args); }; const commonDeps = { runOpenshell: runGatewayOpenshell, inferenceRouteMutator: revalidatingInferenceRouteMutator, + nativeLocalInference: selectingNativeLocal, gatewayName, upsertProvider: selectedUpsertProvider, verifyInferenceRoute: (selectedProvider: string, selectedModel: string) => { @@ -1065,19 +1181,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 @@ -1123,19 +1245,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 @@ -1190,7 +1318,10 @@ export function createSetupInference( try { const providerResult = await setupSelectedProvider(); if (providerResult) return providerResult; - if (!nativeNvidiaProviderAttachment) commonDeps.verifyInferenceRoute(provider, model); + if (selectingNativeLocal && !nativeLocalProviderAttachment) + throw new Error("Native local provider registration was not confirmed."); + if (!nativeNvidiaProviderAttachment && !nativeLocalProviderAttachment) + commonDeps.verifyInferenceRoute(provider, model); if (hostLocalRoute) { deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", @@ -1275,7 +1406,16 @@ export function createSetupInference( shouldLogSuccessfulRoute = true; return { ok: true as const }; } 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 e346625b20e..d1ae99fc6ed 100644 --- a/src/lib/onboard/workload/clone.ts +++ b/src/lib/onboard/workload/clone.ts @@ -277,6 +277,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 9a87edd73e6..3804d7bd688 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -132,6 +132,7 @@ function stageManagedStartupRuntimeSources(rootDir: string, buildCtx: string): v "inference-credential.ts", path.join("core", "json-types.ts"), path.join("core", "ports.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/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(); + } + }, +); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 9b310ef3100..4101da4b140 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -22,6 +22,8 @@ import { import { withLock } from "./registry/lock"; import { load, save } from "./registry/persistence"; import { + normalizeNativeLocalProviderAttachment, + retainedNativeLocalProviderAttachment, isCurrentSandboxInferenceRouteReservation, isCurrentPendingSandboxCreateReservation, normalizeSandboxInferenceRouteSelection, @@ -485,6 +487,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, ); @@ -550,6 +564,7 @@ export function registerSandbox( : undefined, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), lifecycleGeneration: entry.lifecycleGeneration, lifecycleLiveIdentityFingerprint: entry.lifecycleLiveIdentityFingerprint, @@ -601,6 +616,7 @@ type SandboxInferenceRouteReservation = Pick< reservationSessionId?: string; hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; + nativeLocalProviderAttachment?: SandboxEntry["nativeLocalProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; }; @@ -643,6 +659,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 nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( route.nativeNvidiaProviderAttachment, ); @@ -706,6 +734,10 @@ export function reserveSandboxInferenceRoute( existing.hostLocalInferenceProvenance, route.hostLocalInferenceProvenance ?? existing.hostLocalInferenceProvenance, ) && + isDeepStrictEqual( + existing.nativeLocalProviderAttachment, + nativeLocalProviderAttachment ?? existing.nativeLocalProviderAttachment, + ) && isDeepStrictEqual( existing.nativeNvidiaProviderAttachment, nativeNvidiaProviderAttachment ?? existing.nativeNvidiaProviderAttachment, @@ -746,6 +778,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, + }), nativeNvidiaProviderAttachment: isNativeNvidiaProvider(normalized.provider) ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) : undefined, 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 57358f362dc..a75a17a3860 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeLocalProviderAuthorities } from "../../inference/native-local/contract"; + import path from "node:path"; import { isObjectRecord } from "../../core/json-types"; import { GATEWAY_PORT } from "../../core/ports"; @@ -108,6 +110,8 @@ 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); // 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. @@ -125,6 +129,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, ); @@ -144,6 +151,8 @@ function normalizeRegistry(value: unknown): SandboxRegistry { sandboxes, }; if (extraProviders) base.extraProviders = extraProviders; + if (nativeLocalProviderAuthorities) + base.nativeLocalProviderAuthorities = nativeLocalProviderAuthorities; if (nativeNvidiaProviderAuthorities) { base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; } @@ -152,6 +161,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, ); @@ -174,6 +186,8 @@ function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { sandboxes, }; if (extraProviders) base.extraProviders = extraProviders; + if (nativeLocalProviderAuthorities) + base.nativeLocalProviderAuthorities = nativeLocalProviderAuthorities; if (nativeNvidiaProviderAuthorities) { base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; } diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 4ac16f5351b..ea8072965e3 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"; @@ -22,6 +27,7 @@ const ROUTE_RESERVATION_KEYS = new Set([ "lifecycleLiveIdentityFingerprint", "model", "name", + "nativeLocalProviderAttachment", "nativeNvidiaProviderAttachment", "openshellDriver", "pendingRouteReservation", @@ -82,6 +88,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) @@ -188,11 +199,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) && @@ -348,3 +361,19 @@ 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; +} diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index f351c290b2c..7675b397e28 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -1,6 +1,8 @@ // 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 { InferenceSelection } from "../../inference/selection"; import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import type { @@ -145,6 +147,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; /** Explicit hidden-lifecycle provenance; absence keeps llama.cpp on its legacy path. */ @@ -246,6 +250,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; } 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 62e24d8cb30..f376f72e260 100644 --- a/test/agents/deepagents/langchain-deepagents-code-config.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-config.test.ts @@ -68,6 +68,22 @@ 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("routes managed inference through OpenAI-compatible chat completions", () => { const config = runGenerator({}); 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 0022c0bb8aa..a806b30aa64 100644 --- a/test/agents/deepagents/langchain-deepagents-code-image.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-image.test.ts @@ -225,7 +225,7 @@ describe("LangChain Deep Agents Code image contracts", () => { ].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"; + "RUN chmod 444 /opt/nemoclaw-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-local/agent-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-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 9d636f91f7a..85252eb0df5 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/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/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 4e4c4bf15b0..edbb5c77114 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"; @@ -76,7 +77,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( @@ -92,11 +93,24 @@ describe("onboarding inference gateway scope", () => { ), ).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, @@ -116,6 +130,10 @@ describe("onboarding inference gateway scope", () => { gatewayName: GATEWAY, reservationSessionId: undefined, hostLocalInferenceReceipt: null, + nativeLocalProviderAttachment: expect.objectContaining({ + gatewayName: GATEWAY, + sandboxName: "dcode-vllm-local", + }), }); expectCommandsTargetOnly(harness.commands); }, @@ -134,6 +152,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( @@ -153,23 +179,15 @@ describe("onboarding inference gateway scope", () => { ), ).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 1ca897f922f..fcb46ca25bc 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"; @@ -649,13 +651,14 @@ const { onboard } = require(${onboardPath}); 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"); + 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 { @@ -695,22 +698,20 @@ const { onboard } = require(${onboardPath}); 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 }); @@ -746,31 +747,29 @@ 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, + /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 }); }); @@ -795,25 +794,23 @@ 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, + /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, "../.."); @@ -1077,11 +1074,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: { @@ -1098,7 +1104,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: "" } @@ -1130,6 +1136,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 () => { @@ -1421,6 +1429,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"); @@ -1430,8 +1439,10 @@ 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", + "read-prior-route", "ownership-lock-enter", "peer-scan", "unload", @@ -1440,22 +1451,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..619264ddec9 --- /dev/null +++ b/test/onboarding/onboard-native-provider-reservation.test.ts @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { nativeLocalSetupReceipt } from "../support/native-local-setup-harness"; +import { createDirectSetupInferenceHarness } from "../helpers/onboard-split-context"; + +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); + }); +}); diff --git a/test/runtime/sandbox/sandbox-build-context.test.ts b/test/runtime/sandbox/sandbox-build-context.test.ts index dec16f51321..478a8c208b4 100644 --- a/test/runtime/sandbox/sandbox-build-context.test.ts +++ b/test/runtime/sandbox/sandbox-build-context.test.ts @@ -268,6 +268,7 @@ describe("sandbox build context staging", () => { "inference-credential.ts", path.join("core", "json-types.ts"), path.join("core", "ports.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"), @@ -517,6 +518,7 @@ 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", "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..16e365e346e 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,7 @@ describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () toolDisclosurePath, applierPath, messagingHookPath, + path.join(localSrc, "lib/inference/native-local/agent-config.ts"), pluginFile, nestedPluginFile, ]; @@ -112,6 +117,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 +175,60 @@ describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () } }); }); + +it.each([ + { + agent: "OpenClaw cached install", + marker: "# Config inputs precede the cached plugin install.", + dockerfile: "Dockerfile", + start: "chmod 444 /src/lib/*.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: "Hermes", + marker: "# Keep the config generator", + dockerfile: "agents/hermes/Dockerfile", + start: "chmod 444 /src/lib/hermes-managed-route.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", + }, +])( + "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 35cf3b6e2a0..1b3d08cabd1 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -11,6 +11,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 { @@ -369,7 +374,7 @@ export function createDirectSetupInferenceHarnessFactory( } return directRunResult(); }; - const setupInferenceWithoutPolicyAuthority = createSetupInference({ + const harnessDeps: Partial = { checkGatewayRouteCompatibility: () => ({ ok: true }), withGatewayRouteMutationLock: async ( _gatewayName: string, @@ -492,6 +497,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 = ( @@ -503,22 +518,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, From f7fd304be5247be5de67218aeeabe851faece060 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:58:44 -0700 Subject: [PATCH 02/45] test(inference): identify native-local agents in reconciliation fixtures --- .../onboard-inference-gateway-scope.test.ts | 3 ++- .../onboard-inference-reconciliation.test.ts | 17 ++++++++++++----- ...dbox-provisioning-helper-permissions.test.ts | 7 ------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index edbb5c77114..a3c6bfce6d3 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -89,7 +89,7 @@ describe("onboarding inference gateway scope", () => { "COMPATIBLE_API_KEY", null, [], - { gatewayName: GATEWAY }, + { gatewayName: GATEWAY, agentName: "langchain-deepagents-code" }, ), ).resolves.toEqual({ ok: true }); @@ -173,6 +173,7 @@ describe("onboarding inference gateway scope", () => { [], { gatewayName: GATEWAY, + agentName: "langchain-deepagents-code", reuseGatewayCredentialWithoutLocalKey: true, skipHostInferenceSmoke: true, }, diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index fcb46ca25bc..65fa5661cfd 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -650,7 +650,9 @@ const { onboard } = require(${onboardPath}); : undefined, overrides: { applyLocalInferenceRoute }, }); - await harness.setupInference("test-box", "meta-llama", "vllm-local"); + 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, [ @@ -693,7 +695,9 @@ 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(); } @@ -754,7 +758,9 @@ const { onboard } = require(${onboardPath}); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { await assert.rejects( - harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"), + harness.setupInference("test-box", "qwen3.5:9b", "ollama-local", null, null, null, [], { + agentName: "openclaw", + }), /native provider registration denied/, ); } finally { @@ -799,7 +805,9 @@ const { onboard } = require(${onboardPath}); error: { kind: "command", reason: "failed", message: "native provider registration denied" }, }); await assert.rejects( - harness.setupInference("test-box", "meta-llama", "vllm-local"), + harness.setupInference("test-box", "meta-llama", "vllm-local", null, null, null, [], { + agentName: "openclaw", + }), /native provider registration denied/, ); @@ -1442,7 +1450,6 @@ describe("re-onboard Ollama GPU release (#9110)", () => { "read-prior-route", // Agent support admission; cleanup reads the route again under the lock. "lock-enter", "read-prior-route", - "read-prior-route", "ownership-lock-enter", "peer-scan", "unload", diff --git a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts index 16e365e346e..215bfb06164 100644 --- a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts +++ b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts @@ -191,13 +191,6 @@ it.each([ start: "chmod 444 /src/lib/*.ts", file: "/src/lib/inference/native-local/agent-config.ts", }, - { - agent: "Hermes", - marker: "# Keep the config generator", - dockerfile: "agents/hermes/Dockerfile", - start: "chmod 444 /src/lib/hermes-managed-route.ts", - file: "/src/lib/inference/native-local/agent-config.ts", - }, { agent: "DCode", marker: "# Copy the managed-startup entrypoint", From 77f983515e9b27959dd3b8ee8d6826020ce28215 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:19:11 -0700 Subject: [PATCH 03/45] test(e2e): qualify native local inference in existing targets --- ci/e2e-assertion-budget.json | 12 +- ci/e2e-assertion-growth-exceptions.json | 6 +- test/e2e/README.md | 12 ++ test/e2e/live/double-onboard.test.ts | 45 ++++- test/e2e/live/gpu-double-onboard.test.ts | 4 +- test/e2e/live/gpu-e2e.test.ts | 10 +- test/e2e/live/inference-routing-helpers.ts | 75 +++++--- test/e2e/live/inference-routing.test.ts | 169 ++++-------------- .../managed-image-activation-e2e-helpers.ts | 1 + test/e2e/mock-parity.json | 5 + .../support/inference-routing-cleanup.test.ts | 108 +++++++++++ tools/e2e/onboard-timeout-contract.mts | 2 + 12 files changed, 277 insertions(+), 172 deletions(-) create mode 100644 test/e2e/support/inference-routing-cleanup.test.ts diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 47f902732ce..4c5697faef0 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -18,11 +18,11 @@ "expectCalls": 1250, "matcherAssertions": 1229, "nodeAssertions": 104, - "namedAssertionHelpers": 421, + "namedAssertionHelpers": 419, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 168, - "assertionPoints": 1972, + "assertionPoints": 1970, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, @@ -30,11 +30,11 @@ "expectCalls": 1673, "matcherAssertions": 1647, "nodeAssertions": 127, - "namedAssertionHelpers": 666, + "namedAssertionHelpers": 664, "failCalls": 1, "throwGuards": 528, "objectFieldAssertions": 245, - "assertionPoints": 3214, + "assertionPoints": 3212, "generatedProbeBlocks": 209, "generatedProbeConditions": 721 }, @@ -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": [43,48,43,48,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": [18,22,29,41,2], - "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], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 04f4efbeb86..a442076dfae 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 #12767 shares restoration validation through one command builder in the scanned live source set. Every restoration predicate remains counted. This transition preserves the seven-assertion concurrent-gateway reduction from #12608. Exact revised transition approval: https://github.com/NVIDIA/NemoClaw/pull/12767#issuecomment-6061291322. This prerequisite must merge before the repaired #12767 candidate uses the exception. A changed base or candidate budget invalidates this entry. Remove after #12767 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 #12767 shares restoration validation through one command builder in the scanned live source set. Every restoration predicate remains counted. This transition preserves the seven-assertion concurrent-gateway reduction from #12608. Exact revised transition approval: https://github.com/NVIDIA/NemoClaw/pull/12767#issuecomment-6061291322. This prerequisite must merge before the repaired #12767 candidate uses the exception. A changed base or candidate budget invalidates this entry. Remove after #12767 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 moves native-local agent and sibling-policy coverage into existing live targets without increasing total direct expectations. It raises the double-onboard per-file budget by one while retiring the curl-only inference-routing case. The earlier approval was superseded by the #12924 baseline merge. Refreshed exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6104551185. This candidate entry supports local validation; independent CI verifies the PR-specific approval on GitHub. Remove after #12977 merges.", "schemaVersion": 1, "exceptions": [ { @@ -39,6 +39,10 @@ { "pullRequest": 12958, "changeSha256": "96e09e5e48df3a94e93f7122758571ed078440f6330467c98d45f0a71b11d91c" + }, + { + "pullRequest": 12977, + "changeSha256": "3f500dd6d4f5c57029d448a5c5fd68acba5f35dc95d8859371649abcdd0ba4a4" } ] } diff --git a/test/e2e/README.md b/test/e2e/README.md index d18bfa0617c..2793916335c 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -2148,6 +2148,18 @@ 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 + +The first slice of #12975 supports the DCode/OpenClaw contract below. Pi and Hermes continue to use their existing shared local routes. Native-local provider attachment for those agents belongs to later slices. + +`managed-image-activation` owns real OpenClaw and DCode agent turns before and after restart. Its existing 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. Hermes remains on 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. The former TC-INF-09 managed-route curl probe is retired because these existing targets now own the native agent and local endpoint outcomes. The `inference-routing` target retains its other cases and 75-minute limit. 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. diff --git a/test/e2e/live/double-onboard.test.ts b/test/e2e/live/double-onboard.test.ts index 0ea7afab584..03d344cd113 100644 --- a/test/e2e/live/double-onboard.test.ts +++ b/test/e2e/live/double-onboard.test.ts @@ -268,6 +268,9 @@ 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"]), "stop sibling sandbox without disturbing the first forward", "replace sandbox after stale registry refusal", "remove double-onboard resources", @@ -315,6 +318,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 +394,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 +511,28 @@ 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" }); + 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..f59ba6fb8de 100644 --- a/test/e2e/live/gpu-double-onboard.test.ts +++ b/test/e2e/live/gpu-double-onboard.test.ts @@ -145,7 +145,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()}`, + `curl -fsS --max-time 120 http://host.openshell.internal:${PROXY_PORT}/v1/chat/completions -H 'Authorization: Bearer openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN' -H 'Content-Type: application/json' --data '${chatRequest(model)}' | ${parseReplyCommand()}`, ], { artifactName, @@ -192,7 +192,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.test.ts b/test/e2e/live/gpu-e2e.test.ts index 0c0b895599d..cfad0e24ba7 100644 --- a/test/e2e/live/gpu-e2e.test.ts +++ b/test/e2e/live/gpu-e2e.test.ts @@ -84,7 +84,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 +93,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: @@ -238,12 +238,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( + `curl -sS --max-time 120 http://host.openshell.internal:${PROXY_PORT}/v1/chat/completions -H 'Authorization: Bearer openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN' -H 'Content-Type: application/json' --data '${JSON.stringify( { model, messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], @@ -255,7 +255,7 @@ test( }, )}'`, ), - { artifactName: "sandbox-inference-local-chat", env: env(), timeoutMs: 150_000 }, + { artifactName: "sandbox-native-local-chat", env: env(), timeoutMs: 150_000 }, ); expect(chatContent(chat.stdout)).toMatch(/pong/i); diff --git a/test/e2e/live/inference-routing-helpers.ts b/test/e2e/live/inference-routing-helpers.ts index a959b5d7272..78b90e36017 100644 --- a/test/e2e/live/inference-routing-helpers.ts +++ b/test/e2e/live/inference-routing-helpers.ts @@ -6,7 +6,7 @@ import os from "node:os"; import path from "node:path"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; -import { resultText } from "../fixtures/clients/command.ts"; +import { outputContainsSandbox, resultText } from "../fixtures/clients/command.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { validateSandboxName } from "../fixtures/clients/sandbox.ts"; @@ -204,27 +204,10 @@ async function cleanupSandbox( } const cleanupEvidence: string[] = []; - 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)); @@ -234,19 +217,43 @@ async function cleanupSandbox( ); } - clearOnboardState(); - - const status = await sandbox.status(sandboxName, { - artifactName: `cleanup-openshell-sandbox-status-${sandboxName}`, - env: buildAvailabilityProbeEnv(), + // Observe absence while the gateway is still running. Public destroy may + // stop the last gateway after reconciling its registry and provider ownership. + const listing = await sandbox.list({ + artifactName: `cleanup-openshell-sandbox-list-${sandboxName}`, + env: rawOpenShellEnv(), timeoutMs: 30_000, }); - cleanupEvidence.push(probeSummary("openshell sandbox status", status)); - if (status.exitCode === 0) { + cleanupEvidence.push(probeSummary("openshell sandbox list", listing)); + if ( + listing.exitCode !== 0 || + listing.timedOut || + listing.signal !== null || + outputContainsSandbox(listing, sandboxName) + ) { throw new Error( - `sandbox '${sandboxName}' still exists after strict cleanup\n${cleanupEvidence.join("\n")}`, + `sandbox '${sandboxName}' absence was not verified after strict cleanup\n${cleanupEvidence.join("\n")}`, ); } + + 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)); + } catch (error) { + cleanupEvidence.push( + `nemoclaw destroy threw: ${error instanceof Error ? error.message : String(error)}`, + ); + } + + clearOnboardState(); } async function expectNoActiveSandbox(host: HostCliClient, sandboxName: string): Promise { @@ -498,3 +505,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..0fabac9422a 100644 --- a/test/e2e/live/inference-routing.test.ts +++ b/test/e2e/live/inference-routing.test.ts @@ -9,6 +9,7 @@ import path from "node:path"; import { ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS, ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS, + INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS, } from "../../../tools/e2e/onboard-timeout-contract.mts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText } from "../fixtures/clients/command.ts"; @@ -35,6 +36,7 @@ import { hasRawNodeStackTrace, inferenceSandboxName, onboardSandbox, + providerPolicyRestoreArgs, redactedResultText, requireLivePrerequisites, runNemoclawCli, @@ -51,7 +53,7 @@ process.env.NEMOCLAW_CLI_BIN ??= CLI_ENTRYPOINT; test( "TC-INF-06 invalid API key fails with credential classification and cleanup", { - timeout: 5 * 60_000, + timeout: INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS, meta: { e2ePhases: [ "confirm live inference prerequisites", @@ -103,7 +105,7 @@ test( test( "TC-INF-07 unreachable endpoint fails with transport classification and cleanup", { - timeout: 5 * 60_000, + timeout: INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS, meta: { e2ePhases: [ "confirm live inference prerequisites", @@ -271,16 +273,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 +286,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 +336,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 +377,6 @@ async function runRuntimeIdentityE2EScenario( await oauth.close(); } }); - const cloudflaredBin = await resolveVerifiedCloudflaredBinary(cleanup, host); const tunnel = await startPublicMcpHttpsTunnel({ cloudflaredBin, cleanup, @@ -717,100 +714,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 +783,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 +819,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/managed-image-activation-e2e-helpers.ts b/test/e2e/live/managed-image-activation-e2e-helpers.ts index dcbe3e4ca5a..3b26058c69b 100644 --- a/test/e2e/live/managed-image-activation-e2e-helpers.ts +++ b/test/e2e/live/managed-image-activation-e2e-helpers.ts @@ -1173,6 +1173,7 @@ export async function qualifyManagedImageActivation(fixtures: RuntimeFixtures): chatContent: "PONG", host: "0.0.0.0", model: MODEL, + port: 8000, progress, publicHost: "host.openshell.internal", requireAuth: true, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 3eb3246c381..7697f9e52bd 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -100,6 +100,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", @@ -195,6 +197,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" ] }, @@ -565,6 +568,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", @@ -580,6 +584,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/inference-routing-cleanup.test.ts b/test/e2e/support/inference-routing-cleanup.test.ts new file mode 100644 index 00000000000..ed55458beb7 --- /dev/null +++ b/test/e2e/support/inference-routing-cleanup.test.ts @@ -0,0 +1,108 @@ +// 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) { + 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!; + }, + }); + const host = { + command: vi.fn(async () => { + calls.push("public destroy"); + return result(); + }), + }; + 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.host.command).not.toHaveBeenCalled(); + }); + 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(); + }); +}); + +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/tools/e2e/onboard-timeout-contract.mts b/tools/e2e/onboard-timeout-contract.mts index a67e19357c4..7adeb6c3226 100644 --- a/tools/e2e/onboard-timeout-contract.mts +++ b/tools/e2e/onboard-timeout-contract.mts @@ -31,6 +31,8 @@ export const ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS = ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS + ONBOARD_TEST_HEADROOM_MS; export const ONBOARD_SINGLE_FINAL_HANDOFF_TARGET_TIMEOUT_MINUTES = 75; +export const INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS = 5 * MINUTE_MS; + // The typed DCode target runs onboarding, its invalid-credential lifecycle, // state validation, and the ordered cloud checks. Those checks can consume 96 // minutes of command deadlines before automatic config export; retain the same From a140b27dd932371c79482876d689482b89761b23 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:22:37 -0700 Subject: [PATCH 04/45] test(e2e): retain existing negative-case timeout contract --- test/e2e/live/inference-routing.test.ts | 5 ++--- tools/e2e/onboard-timeout-contract.mts | 2 -- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/test/e2e/live/inference-routing.test.ts b/test/e2e/live/inference-routing.test.ts index 0fabac9422a..547f751685c 100644 --- a/test/e2e/live/inference-routing.test.ts +++ b/test/e2e/live/inference-routing.test.ts @@ -9,7 +9,6 @@ import path from "node:path"; import { ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS, ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS, - INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS, } from "../../../tools/e2e/onboard-timeout-contract.mts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText } from "../fixtures/clients/command.ts"; @@ -53,7 +52,7 @@ process.env.NEMOCLAW_CLI_BIN ??= CLI_ENTRYPOINT; test( "TC-INF-06 invalid API key fails with credential classification and cleanup", { - timeout: INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS, + timeout: 5 * 60_000, meta: { e2ePhases: [ "confirm live inference prerequisites", @@ -105,7 +104,7 @@ test( test( "TC-INF-07 unreachable endpoint fails with transport classification and cleanup", { - timeout: INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS, + timeout: 5 * 60_000, meta: { e2ePhases: [ "confirm live inference prerequisites", diff --git a/tools/e2e/onboard-timeout-contract.mts b/tools/e2e/onboard-timeout-contract.mts index 7adeb6c3226..a67e19357c4 100644 --- a/tools/e2e/onboard-timeout-contract.mts +++ b/tools/e2e/onboard-timeout-contract.mts @@ -31,8 +31,6 @@ export const ONBOARD_SINGLE_FINAL_HANDOFF_TEST_TIMEOUT_MS = ONBOARD_FINAL_HANDOFF_COMMAND_TIMEOUT_MS + ONBOARD_TEST_HEADROOM_MS; export const ONBOARD_SINGLE_FINAL_HANDOFF_TARGET_TIMEOUT_MINUTES = 75; -export const INFERENCE_ROUTING_NEGATIVE_TEST_TIMEOUT_MS = 5 * MINUTE_MS; - // The typed DCode target runs onboarding, its invalid-credential lifecycle, // state validation, and the ordered cloud checks. Those checks can consume 96 // minutes of command deadlines before automatic config export; retain the same From edde9b99c84470fa3bbd18a953dbae6835239c26 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sat, 10 Oct 2026 20:13:14 -0700 Subject: [PATCH 05/45] fix(inference): verify attached native local onboarding route Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../managed-dcode-runtime.py | 1 + src/lib/onboard.ts | 18 +-- ...nalization-deps-terminal-inference.test.ts | 52 +++++++ src/lib/onboard/machine/finalization-deps.ts | 28 ++-- .../verify-deployment-inference-route.test.ts | 134 +++++++++++++++++- src/lib/verify-deployment.ts | 95 +++++++++++-- 6 files changed, 297 insertions(+), 31 deletions(-) diff --git a/agents/langchain-deepagents-code/managed-dcode-runtime.py b/agents/langchain-deepagents-code/managed-dcode-runtime.py index d331262d161..cb32bb0aaab 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -1089,6 +1089,7 @@ def managed_inference_api_key(base_url: str) -> str: "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 if parsed.scheme == "http" and local_host and _managed_upstream_provider() in { "ollama-local", "vllm-local", "llama-cpp-local", "compatible-endpoint" diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 58fa483c8ae..e4ce9344953 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -3207,6 +3207,13 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { buildVerifyChain: (chatUiUrl, name) => buildAgentVerifyChain(chatUiUrl, name, agent), verifyDeployment: async (name, chain) => { const verifyDeploymentModule: typeof import("./verify-deployment") = require("./verify-deployment"); + const inference = verifyDeploymentModule.onboardInferenceVerificationContext( + name, + GATEWAY_NAME, + agent?.name ?? "openclaw", + liveFinalFlowContext, + registry.getSandbox(name)?.nativeLocalProviderAttachment, + ); return verifyDeploymentModule.verifyDeployment( name, chain, @@ -3218,12 +3225,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { providerExistsInGateway: (providerName: string) => providerExistsInGateway(providerName), probeInferenceInvocation: () => - verifyDeploymentModule.probeOnboardInferenceInvocation({ - ...liveFinalFlowContext, - sandboxName: name, - gatewayName: GATEWAY_NAME, - agentName: agent?.name, - }), + verifyDeploymentModule.probeOnboardInferenceInvocation(inference.invocation), }, { diagnoseCustomOpenClawRuntime: @@ -3231,9 +3233,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { liveFinalFlowContext.fromDockerfile, agent?.name, ), - inferenceRouteContext: { - provider: liveFinalFlowContext.provider, - }, + inferenceRouteContext: inference.route, }, ); }, 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 3a004548c13..930a9e35ca6 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,38 @@ describe("terminal inference finalization dependency", () => { expect(probeOnboardInferenceInvocation).toHaveBeenCalledExactlyOnceWith({ ...input, gatewayName: "nemoclaw-19090", + nativeLocalExpected: false, + nativeLocalProviderAttachment: 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", + nativeLocalExpected: true, + nativeLocalProviderAttachment: localAttachment, }); }); diff --git a/src/lib/onboard/machine/finalization-deps.ts b/src/lib/onboard/machine/finalization-deps.ts index c0e7709b963..e67f9108ba1 100644 --- a/src/lib/onboard/machine/finalization-deps.ts +++ b/src/lib/onboard/machine/finalization-deps.ts @@ -15,6 +15,7 @@ import type { import { WATCHER_STATUS_TIMEOUT_MS } from "../../actions/sandbox/auto-pair-warmup"; import { sanitizeWedgeLogLine } from "../../actions/sandbox/gateway-wedge-diagnostics"; import { OPENSHELL_DEFAULT_WORKSPACE } from "../../adapters/openshell/sandbox-ssh-host"; +import type { SandboxEntry } from "../../state/registry/types"; export { OPENCLAW_ONBOARDING_PAIRING_FINAL_OBSERVATION_TIMEOUT_MS, @@ -377,12 +378,12 @@ export function ordinaryOpenClawPairingIncompleteMessage( return `OpenClaw onboarding for '${name}' is incomplete because ${cause}. Resume or rerun onboarding.`; } -function readRegistryGatewayName(name: string): string | null { +function readRegistryInferenceRoute(name: string): (SandboxEntry & { gatewayName: string }) | null { try { - const gatewayName = finalizationHandlerRuntime.loadRegistryPersistence().load().sandboxes[ - name - ]?.gatewayName; - return typeof gatewayName === "string" && gatewayName ? gatewayName : null; + const entry = finalizationHandlerRuntime.loadRegistryPersistence().load().sandboxes[name]; + return typeof entry?.gatewayName === "string" && entry.gatewayName + ? { ...entry, gatewayName: entry.gatewayName } + : null; } catch { return null; } @@ -396,14 +397,19 @@ export const finalizationHandlerDeps = { model: string; preferredInferenceApi: string | null; }): Promise<{ ok: boolean; detail?: string }> { - const gatewayName = readRegistryGatewayName(input.sandboxName); - if (!gatewayName) { + const route = readRegistryInferenceRoute(input.sandboxName); + if (!route) { return { ok: false, detail: "the sandbox gateway identity is unavailable" }; } - return finalizationHandlerRuntime.loadVerifyDeployment().probeOnboardInferenceInvocation({ - ...input, - gatewayName, - }); + const verification = finalizationHandlerRuntime.loadVerifyDeployment(); + const context = verification.onboardInferenceVerificationContext( + input.sandboxName, + route.gatewayName, + input.agentName, + { ...input, endpointUrl: route.endpointUrl }, + route.nativeLocalProviderAttachment, + ); + return verification.probeOnboardInferenceInvocation(context.invocation); }, async waitForSandboxControlPlaneReady(name: string): Promise { return finalizationHandlerRuntime diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index bbc4f4cde97..8b9fdb00d3b 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -3,10 +3,32 @@ import { describe, expect, it, vi } from "vitest"; 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 +57,70 @@ 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", + 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("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 +386,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 8f7ae84b1c7..9c5fa996a5f 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -10,7 +10,7 @@ * 1. Gateway reachable (HTTP /health returns 200 or 401) * 2. Gateway version retrieval * 3. Dashboard port reachable from the host (port forward working) - * 4. Inference route working (sandbox can reach inference.local) + * 4. Selected inference route serves a sandbox request * 5. Messaging bridges healthy (if configured) * * Fixes #2342 — users no longer see "AGENT IS LIVE" followed by @@ -31,6 +31,11 @@ import { listMessagingChannelsWithoutCredentials } from "./messaging/channels"; import { retryUntilAsync } from "./core/retry"; import { isNativeNvidiaProvider } from "./inference/native-nvidia"; +import { + normalizeNativeLocalProviderAttachment, + usesNativeLocalInferenceForAgent, + type NativeLocalProviderAttachment, +} from "./inference/native-local/contract"; import { buildCustomOpenClawRuntimeFailureHints, classifyOpenClawRuntimeFailure, @@ -112,8 +117,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). @@ -267,6 +272,8 @@ type InferenceRouteStatus = "ok" | "unreachable" | "unhealthy"; */ export type InferenceRouteContext = { provider?: string | null; + nativeLocalExpected?: boolean; + nativeLocalProviderAttachment?: NativeLocalProviderAttachment; }; function toRouteHealthContext(context: InferenceRouteContext): SandboxInferenceRouteHealthContext { @@ -395,7 +402,24 @@ async function verifyInferenceRoute( sleep: (ms: number) => Promise, context: InferenceRouteContext, ): Promise { - if (isNativeNvidiaProvider(context.provider)) { + const nativeLocal = + context.nativeLocalExpected || context.nativeLocalProviderAttachment !== undefined; + if (isNativeNvidiaProvider(context.provider) || nativeLocal) { + if ( + nativeLocal && + (!normalizeNativeLocalProviderAttachment(context.nativeLocalProviderAttachment) || + context.nativeLocalProviderAttachment?.sandboxName !== sandboxName || + context.nativeLocalProviderAttachment?.provider !== context.provider) + ) { + return { + status: "unhealthy", + detail: "native local provider attachment is missing or invalid", + httpCode: 0, + hint: + "The selected sandbox has no valid native local provider attachment. " + + "Reconcile its recorded provider before retrying onboarding.", + }; + } const invocation = await retryUntilAsync( async () => (await deps.probeInferenceInvocation?.()) ?? null, { @@ -407,18 +431,24 @@ async function verifyInferenceRoute( if (invocation?.ok) { return { status: "ok", - detail: "native NVIDIA inference served an agent request", + detail: nativeLocal + ? "native local inference served a sandbox request" + : "native NVIDIA inference served an agent request", httpCode: 200, }; } const reason = invocation?.detail ?? "no inference request confirmed the selected model"; return { status: "unhealthy", - detail: `native NVIDIA inference did not serve an agent request: ${reason}`, + detail: nativeLocal + ? `native local inference did not serve a sandbox request: ${reason}` + : `native NVIDIA inference did not serve an agent request: ${reason}`, httpCode: 0, - hint: - "The sandbox-attached NVIDIA provider could not serve the selected model. Confirm the " + - "NVIDIA credential and model, then re-run: nemoclaw status.", + hint: nativeLocal + ? "The sandbox-attached local provider could not serve the selected model. Confirm its " + + "endpoint and credential, then re-run: nemoclaw status." + : "The sandbox-attached NVIDIA provider could not serve the selected model. Confirm the " + + "NVIDIA credential and model, then re-run: nemoclaw status.", }; } const routeContext = toRouteHealthContext(context); @@ -900,8 +930,40 @@ export type InferenceInvocationContext = { 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; + }, + nativeLocalProviderAttachment?: NativeLocalProviderAttachment, +): { route: InferenceRouteContext; invocation: InferenceInvocationContext } { + const nativeLocalExpected = usesNativeLocalInferenceForAgent( + agentName, + flow.provider, + flow.endpointUrl, + ); + return { + route: { provider: flow.provider, nativeLocalExpected, nativeLocalProviderAttachment }, + invocation: { + sandboxName, + gatewayName, + agentName, + model: flow.model, + provider: flow.provider, + preferredInferenceApi: flow.preferredInferenceApi, + nativeLocalExpected, + nativeLocalProviderAttachment, + }, + }; +} + /** * The standard `probeInferenceInvocation` dependency: send one bounded * inference request over the gateway route, using the same probe `status` @@ -911,18 +973,31 @@ export type InferenceInvocationContext = { */ 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" }; } - const result = await runSandboxInferenceInvocationProbe({ + if ( + (context.nativeLocalExpected || context.nativeLocalProviderAttachment !== undefined) && + (!normalizeNativeLocalProviderAttachment(context.nativeLocalProviderAttachment) || + context.nativeLocalProviderAttachment?.sandboxName !== context.sandboxName || + context.nativeLocalProviderAttachment?.gatewayName !== context.gatewayName || + context.nativeLocalProviderAttachment?.provider !== provider) + ) { + return { ok: false, detail: "native local provider attachment is missing or invalid" }; + } + const result = await probe({ sandboxName: context.sandboxName, gatewayName: context.gatewayName, agentName: context.agentName ?? null, provider, model, preferredInferenceApi: context.preferredInferenceApi, + ...(context.nativeLocalProviderAttachment + ? { nativeLocalProviderAttachment: context.nativeLocalProviderAttachment } + : {}), ...(isNativeNvidiaProvider(provider) ? { nativeProvider: true } : {}), }); return result.ok ? { ok: true } : { ok: false, detail: result.detail }; From f3a1ea7f111110c8cc18ea29bc726818b1aed745 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:57:49 -0700 Subject: [PATCH 06/45] fix(inference): retain recovery evidence and capture GPU agent failure Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../inference-set-native-local.test.ts | 13 +++++- src/lib/actions/inference/native-local.ts | 41 ++++++++++++++----- .../remote-openai-surface.test.ts | 32 +++++++++++++++ src/lib/onboard/inference-providers/remote.ts | 18 +++++++- test/e2e/README.md | 2 +- test/e2e/live/inference-routing-helpers.ts | 29 +++++++------ test/e2e/live/llama-cpp-generic-gpu.test.ts | 5 ++- .../support/inference-routing-cleanup.test.ts | 20 +++++++-- 8 files changed, 129 insertions(+), 31 deletions(-) diff --git a/src/lib/actions/inference-set-native-local.test.ts b/src/lib/actions/inference-set-native-local.test.ts index 067321af0e9..6abf9c28d62 100644 --- a/src/lib/actions/inference-set-native-local.test.ts +++ b/src/lib/actions/inference-set-native-local.test.ts @@ -121,6 +121,15 @@ describe("native local inference replacement", () => { 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({ @@ -265,6 +274,8 @@ describe.each([ vi.mocked(ensureNativeLocalProviderAttached).mockRejectedValueOnce( new Error("restore unavailable"), ); - await expect(execute(input)).rejects.toThrow("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, + ); }); }); diff --git a/src/lib/actions/inference/native-local.ts b/src/lib/actions/inference/native-local.ts index 2788161cf64..9670ea511b8 100644 --- a/src/lib/actions/inference/native-local.ts +++ b/src/lib/actions/inference/native-local.ts @@ -111,12 +111,17 @@ export async function prepareNativeLocalSwitch(input: { "Native attachment failure could not be reconciled. Provider ownership was retained; inspect sandbox attachments before retrying.", { cause: error }, ); - if (previousDetached) - await ensureNativeLocalProviderAttached({ - adapter: input.adapter, - sandboxName: input.sandboxName, - expected: input.previous!, - }); + if (previousDetached) { + try { + await ensureNativeLocalProviderAttached({ + adapter: input.adapter, + sandboxName: input.sandboxName, + expected: input.previous!, + }); + } catch (restoreError) { + throw nativeLocalRestorationFailure(error, restoreError); + } + } throw error; } } @@ -212,16 +217,30 @@ export async function detachPreviousNativeLocalBeforePublish(input: { expected: input.previous, }); } catch (error) { - await ensureNativeLocalProviderAttached({ - adapter: input.adapter, - sandboxName: input.sandboxName, - expected: input.previous, - }); + 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, 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 5ed7e22ce22..55e3552f84b 100644 --- a/src/lib/onboard/inference-providers/remote.ts +++ b/src/lib/onboard/inference-providers/remote.ts @@ -417,9 +417,23 @@ export async function setupRemoteProviderInference( // A failed registry write may already have committed, so retain it. proxy.persist(); proxySettled = true; - if (!reserveSandboxInferenceRoute(sandboxName, { model, provider })) { + 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. The proxy was retained.", + `Native local inference could not publish its proxy owner: ${reservationFailure}. The proxy was retained.`, ); } } diff --git a/test/e2e/README.md b/test/e2e/README.md index 2793916335c..f8e146f2bc3 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -2185,7 +2185,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 existing cleanup helper destroys each test sandbox. After successful onboarding, strict cleanup checks sandbox absence only. +The existing 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. Failed onboarding uses best-effort cleanup. 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. diff --git a/test/e2e/live/inference-routing-helpers.ts b/test/e2e/live/inference-routing-helpers.ts index 78b90e36017..cc4d10f8fdb 100644 --- a/test/e2e/live/inference-routing-helpers.ts +++ b/test/e2e/live/inference-routing-helpers.ts @@ -225,17 +225,13 @@ async function cleanupSandbox( timeoutMs: 30_000, }); cleanupEvidence.push(probeSummary("openshell sandbox list", listing)); - if ( - listing.exitCode !== 0 || - listing.timedOut || - listing.signal !== null || - outputContainsSandbox(listing, sandboxName) - ) { - throw new Error( - `sandbox '${sandboxName}' absence was not verified after strict cleanup\n${cleanupEvidence.join("\n")}`, - ); - } + const absenceVerified = + listing.exitCode === 0 && + !listing.timedOut && + listing.signal === null && + !outputContainsSandbox(listing, sandboxName); + let destroySucceeded = false; try { const destroy = await host.command( process.execPath, @@ -247,13 +243,22 @@ async function cleanupSandbox( }, ); 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}' ${reason} after strict cleanup\n${cleanupEvidence.join("\n")}`, + ); } - - clearOnboardState(); } async function expectNoActiveSandbox(host: HostCliClient, sandboxName: string): Promise { diff --git a/test/e2e/live/llama-cpp-generic-gpu.test.ts b/test/e2e/live/llama-cpp-generic-gpu.test.ts index 51980d766e1..3a584789d09 100644 --- a/test/e2e/live/llama-cpp-generic-gpu.test.ts +++ b/test/e2e/live/llama-cpp-generic-gpu.test.ts @@ -172,7 +172,9 @@ test( const runtimeId = receipt.runtime.runtimeId; const runtimeOperation = runtimeProvider.hostLocalInference.createOperation({ env: env() }); runtimeOperation.assertAuthority(); - const captureManagedRuntimeLogs = async (phase: "setup" | "post-agent") => { + const captureManagedRuntimeLogs = async ( + phase: "setup" | "pre-approval-agent" | "post-agent", + ) => { const runtimeLogs = runtimeOperation.engine.capture( ["container", "logs", "--tail", "20000", runtimeId], 30_000, @@ -345,6 +347,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/support/inference-routing-cleanup.test.ts b/test/e2e/support/inference-routing-cleanup.test.ts index ed55458beb7..a218e25fbc0 100644 --- a/test/e2e/support/inference-routing-cleanup.test.ts +++ b/test/e2e/support/inference-routing-cleanup.test.ts @@ -27,7 +27,7 @@ function result(stdout = "", exitCode = 0): ShellProbeResult { artifacts: { stdout: "", stderr: "", result: "" }, }; } -function fixture(listing: ShellProbeResult) { +function fixture(listing: ShellProbeResult, destroy: ShellProbeResult | Error = result()) { fs.mkdirSync(path.join(home, ".nemoclaw"), { recursive: true }); const calls: string[] = []; const sandbox = new SandboxClient({ @@ -44,7 +44,7 @@ function fixture(listing: ShellProbeResult) { const host = { command: vi.fn(async () => { calls.push("public destroy"); - return result(); + return destroy instanceof Error ? Promise.reject(destroy) : destroy; }), }; return { @@ -70,13 +70,27 @@ describe("inference routing strict cleanup", () => { ])("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.host.command).not.toHaveBeenCalled(); + expect(f.calls).toEqual(["sandbox delete fixture", "sandbox list", "public destroy"]); }); 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", () => { From 5f03d73fbcf9c8adceda6275df10adcd6c3bbaa5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:09:16 -0700 Subject: [PATCH 07/45] fix(inference): admit OpenClaw native provider requests Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/inference/native-local.test.ts | 1 + src/lib/inference/native-local/profile.ts | 1 + test/e2e/live/gpu-e2e-helpers.ts | 25 ++++++++++++++++ test/e2e/live/inference-routing-helpers.ts | 29 ++++++++++++------- test/e2e/live/llama-cpp-generic-gpu.test.ts | 27 +++++++---------- .../support/inference-routing-cleanup.test.ts | 25 ++++++++++++++-- ...naged-image-activation-diagnostics.test.ts | 29 +++++++++++++++++++ 7 files changed, 108 insertions(+), 29 deletions(-) diff --git a/src/lib/inference/native-local.test.ts b/src/lib/inference/native-local.test.ts index 9d4f6a853ab..7de8247de5c 100644 --- a/src/lib/inference/native-local.test.ts +++ b/src/lib/inference/native-local.test.ts @@ -128,6 +128,7 @@ describe("native local inference", () => { 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([ { diff --git a/src/lib/inference/native-local/profile.ts b/src/lib/inference/native-local/profile.ts index 6a486c853e3..0f56bad2bab 100644 --- a/src/lib/inference/native-local/profile.ts +++ b/src/lib/inference/native-local/profile.ts @@ -69,6 +69,7 @@ export function prepareNativeLocalProfile(input: NativeLocalBinding) { }, ], binaries: [ + "/usr/local/bin/openclaw", "/usr/local/bin/node", "/usr/bin/node", "/usr/bin/python3", diff --git a/test/e2e/live/gpu-e2e-helpers.ts b/test/e2e/live/gpu-e2e-helpers.ts index 63c668c11e1..3f41aea37cf 100644 --- a/test/e2e/live/gpu-e2e-helpers.ts +++ b/test/e2e/live/gpu-e2e-helpers.ts @@ -6,6 +6,7 @@ import path from "node:path"; import { ownChildProcess } from "../../helpers/child-process-lifecycle.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,6 +219,30 @@ 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, diff --git a/test/e2e/live/inference-routing-helpers.ts b/test/e2e/live/inference-routing-helpers.ts index cc4d10f8fdb..ba6876e5a0e 100644 --- a/test/e2e/live/inference-routing-helpers.ts +++ b/test/e2e/live/inference-routing-helpers.ts @@ -219,17 +219,24 @@ async function cleanupSandbox( // Observe absence while the gateway is still running. Public destroy may // stop the last gateway after reconciling its registry and provider ownership. - const listing = await sandbox.list({ - artifactName: `cleanup-openshell-sandbox-list-${sandboxName}`, - env: rawOpenShellEnv(), - timeoutMs: 30_000, - }); - cleanupEvidence.push(probeSummary("openshell sandbox list", listing)); - const absenceVerified = - listing.exitCode === 0 && - !listing.timedOut && - listing.signal === null && - !outputContainsSandbox(listing, sandboxName); + 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 { diff --git a/test/e2e/live/llama-cpp-generic-gpu.test.ts b/test/e2e/live/llama-cpp-generic-gpu.test.ts index 3a584789d09..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,22 +176,13 @@ test( const runtimeId = receipt.runtime.runtimeId; const runtimeOperation = runtimeProvider.hostLocalInference.createOperation({ env: env() }); runtimeOperation.assertAuthority(); - const captureManagedRuntimeLogs = async ( - phase: "setup" | "pre-approval-agent" | "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], diff --git a/test/e2e/support/inference-routing-cleanup.test.ts b/test/e2e/support/inference-routing-cleanup.test.ts index a218e25fbc0..abfe0d0ae00 100644 --- a/test/e2e/support/inference-routing-cleanup.test.ts +++ b/test/e2e/support/inference-routing-cleanup.test.ts @@ -27,7 +27,7 @@ function result(stdout = "", exitCode = 0): ShellProbeResult { artifacts: { stdout: "", stderr: "", result: "" }, }; } -function fixture(listing: ShellProbeResult, destroy: ShellProbeResult | Error = 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({ @@ -38,7 +38,7 @@ function fixture(listing: ShellProbeResult, destroy: ShellProbeResult | Error = ["sandbox delete fixture", result()], ]).get(command.args.join(" ")); expect(response, `unsupported command: ${command.args.join(" ")}`).toBeDefined(); - return response!; + return response instanceof Error ? Promise.reject(response) : response!; }, }); const host = { @@ -72,6 +72,27 @@ describe("inference routing strict cleanup", () => { 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(); diff --git a/test/e2e/support/managed-image-activation-diagnostics.test.ts b/test/e2e/support/managed-image-activation-diagnostics.test.ts index a6d535c93ee..56def468d5f 100644 --- a/test/e2e/support/managed-image-activation-diagnostics.test.ts +++ b/test/e2e/support/managed-image-activation-diagnostics.test.ts @@ -22,6 +22,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, @@ -189,6 +190,34 @@ printf '%s\n' "$@" >"$MANAGED_ACTIVATION_FIXTURE/openclaw-args" } 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; From 75eec899dde24082b91576aa93dead3ef32875b0 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:12:37 -0700 Subject: [PATCH 08/45] test(e2e): cover failed GPU runtime log capture Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/support/gpu-e2e-helpers.test.ts | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/e2e/support/gpu-e2e-helpers.test.ts b/test/e2e/support/gpu-e2e-helpers.test.ts index 3eca30364b1..8b33b96e4cc 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, @@ -170,6 +171,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" }, From c64c90351e3f11b16f0cc8912481d13f3def6a0a Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:06:38 -0700 Subject: [PATCH 09/45] test: split restored OpenClaw selection coverage --- .../created-sandbox-finalization.test.ts | 105 -------------- ...andbox-restored-openclaw-selection.test.ts | 136 ++++++++++++++++++ 2 files changed, 136 insertions(+), 105 deletions(-) create mode 100644 src/lib/onboard/created-sandbox-restored-openclaw-selection.test.ts diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index 8338c916edb..9fd349f136b 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -1456,108 +1456,3 @@ describe("created sandbox completion actions", () => { }, ); }); - -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-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(); + }); +}); From 51d52313756b7ae9be4f32d838a6ac804de140af Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:10:28 -0700 Subject: [PATCH 10/45] fix(inference): allow native local selection beside shared routes Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../gateway-route-compatibility.test.ts | 42 +++ .../inference/gateway-route-compatibility.ts | 27 +- ...ovider-inference-route-containment.test.ts | 256 +++++++++++++++++- .../provider-inference-route-containment.ts | 15 + .../machine/handlers/provider-inference.ts | 85 ++++-- 5 files changed, 386 insertions(+), 39 deletions(-) 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 a45a74ce223..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, 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.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index cf3ebbf4f1d..64945f0809f 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -6,6 +6,7 @@ import { clearAutoDetectedCompatibleContextWindow } from "../../../inference/com import { resolveAgentProviderInferenceApi, usesNativeLocalInference, + usesNativeLocalInferenceForAgent, } from "../../../inference/config"; import type { TrustedPrivateEndpointCapability } from "../../../inference/endpoint-ssrf-preflight"; import { @@ -1474,13 +1475,13 @@ export async function handleProviderInferenceState({ let managedLlamaCppRecovered = false; 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 @@ -1608,11 +1609,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, @@ -1700,13 +1715,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 && @@ -1914,13 +1929,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) { @@ -1977,13 +1998,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, From 0bde68df4e0da67c335db2351eef31f53f9a5a19 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:35:02 -0700 Subject: [PATCH 11/45] fix(onboard): honor native local reservation at sandbox guard Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox-route-mutation-lock.test.ts | 123 ++++++++++++++++++ src/lib/onboard/machine/handlers/sandbox.ts | 24 ++++ src/lib/onboard/sandbox-registration.ts | 38 +++++- 3 files changed, 184 insertions(+), 1 deletion(-) 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..029bd0ff23e 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,38 @@ 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 { 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-"))); }); @@ -65,6 +93,101 @@ 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.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("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.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 706c365070c..ee97f5d4ed0 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"; @@ -1226,6 +1227,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, sandboxName: null, @@ -1243,6 +1245,28 @@ class SandboxStateFlow< this.failGatewayRouteCheck(` Error: ${formatGatewayRouteConflict(compatibility)}`); } + private acceptsNativeLocalReservation(targetEntry: SandboxEntry, sandboxName: string): boolean { + const agentName = (this.options.agent as { name?: string } | null)?.name ?? "openclaw"; + 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, + }); + if (nativeLocalReservation === "changed") { + this.failGatewayRouteCheck( + ` Error: native local inference reservation for sandbox '${sandboxName}' changed while onboarding was in progress. Retry onboarding.`, + ); + } + return nativeLocalReservation === "exact"; + } + private failGatewayRouteCheck(message: string): never { this.deps.error(message); this.deps.exitProcess(1); diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index 42fadbf1d4d..8f035078ea8 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -1,7 +1,10 @@ // 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 { + normalizeNativeLocalProviderAttachment, + usesNativeLocalInferenceForAgent, +} from "../inference/native-local/contract"; import { requireHostedProviderAttachment } from "../inference/native-provider/hosted-attachment"; import { isDeepStrictEqual } from "node:util"; @@ -506,6 +509,39 @@ export function registerCreatedSandbox(input: CreatedSandboxRegistrationInput): return publishCreatedSandboxRegistration(input, prepareCreatedSandboxRegistration(input)); } +/** 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; +}): "shared" | "exact" | "changed" { + if (!usesNativeLocalInferenceForAgent(input.agentName, input.provider, input.endpointUrl)) { + return "shared"; + } + const attachment = normalizeNativeLocalProviderAttachment( + input.entry.nativeLocalProviderAttachment, + ); + return attachment && + attachment.sandboxName === input.sandboxName && + attachment.gatewayName === input.gatewayName && + attachment.provider === input.provider && + input.entry.provider === input.provider && + input.entry.model === input.model && + input.entry.endpointUrl === input.endpointUrl && + (input.entry.endpointSource ?? null) === input.endpointSource && + (input.entry.credentialEnv ?? null) === input.credentialEnv && + (input.entry.preferredInferenceApi ?? null) === input.preferredInferenceApi + ? "exact" + : "changed"; +} + export function nativeInferenceCreateIntentFields( provider: string | null | undefined, entry: SandboxEntry | null, From 32364354452d3fc89116eb99cfc85371269cfe26 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:52:39 -0700 Subject: [PATCH 12/45] fix(ci): align approved E2E growth digest with main Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-growth-exceptions.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index e732c199353..633c8319951 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 #12767 shares restoration validation through one command builder in the scanned live source set. Every restoration predicate remains counted. This transition preserves the seven-assertion concurrent-gateway reduction from #12608. Exact revised transition approval: https://github.com/NVIDIA/NemoClaw/pull/12767#issuecomment-6061291322. This prerequisite must merge before the repaired #12767 candidate uses the exception. A changed base or candidate budget invalidates this entry. Remove after #12767 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 moves native-local agent and sibling-policy coverage into existing live targets without increasing total direct expectations. It raises the double-onboard per-file budget by one while retiring the curl-only inference-routing case. The earlier approval was superseded by the latest main merge. Refreshed exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6114994953. This candidate entry supports local validation; independent CI verifies the PR-specific approval on GitHub. Remove after #12977 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 #12767 shares restoration validation through one command builder in the scanned live source set. Every restoration predicate remains counted. This transition preserves the seven-assertion concurrent-gateway reduction from #12608. Exact revised transition approval: https://github.com/NVIDIA/NemoClaw/pull/12767#issuecomment-6061291322. This prerequisite must merge before the repaired #12767 candidate uses the exception. A changed base or candidate budget invalidates this entry. Remove after #12767 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 moves native-local agent and sibling-policy coverage into existing live targets without increasing total direct expectations. It raises the double-onboard per-file budget by one while retiring the curl-only inference-routing case. Exact maintainer approval for the current main-to-head budget change: https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6104551185. This candidate entry supports local validation; independent CI verifies the PR-specific approval on GitHub. Remove after #12977 merges.", "schemaVersion": 1, "exceptions": [ { @@ -42,7 +42,7 @@ }, { "pullRequest": 12977, - "changeSha256": "35f7a11122bf9136b9d1bbfe279ed1972c3d2b58f07581327fb50680eecf9633" + "changeSha256": "3f500dd6d4f5c57029d448a5c5fd68acba5f35dc95d8859371649abcdd0ba4a4" } ] } From 3e0b2ddddc44f4afe82dcc784e575b71430f3a97 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:51:22 -0700 Subject: [PATCH 13/45] fix: scope native OpenClaw inference handles during config sync --- .../actions/inference-set-openrouter.test.ts | 6 +- .../status-snapshot-route-drift.test.ts | 2 +- .../native-inference-profile-response.ts | 4 +- ...d-sandbox-selection-reconciliation.test.ts | 1 + .../sandbox-route-mutation-lock.test.ts | 30 ++++++++++ src/lib/onboard/machine/handlers/sandbox.ts | 1 + .../compose-sandbox-config-body.test.ts | 59 ++++++++++++++++-- src/lib/sandbox/openclaw-native-config.ts | 60 ++++++++++++++----- .../verify-deployment-inference-route.test.ts | 25 ++++++++ src/lib/verify-deployment.ts | 3 + .../managed-image-activation-e2e-helpers.ts | 1 + .../repository/cli-coverage-sequencer.test.ts | 2 +- ...ox-provisioning-helper-permissions.test.ts | 4 +- 13 files changed, 170 insertions(+), 28 deletions(-) diff --git a/src/lib/actions/inference-set-openrouter.test.ts b/src/lib/actions/inference-set-openrouter.test.ts index e81ebf15522..0f53c1ff316 100644 --- a/src/lib/actions/inference-set-openrouter.test.ts +++ b/src/lib/actions/inference-set-openrouter.test.ts @@ -177,7 +177,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([]); @@ -196,7 +196,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([]); @@ -209,7 +209,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/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/adapters/openshell/native-inference-profile-response.ts b/src/lib/adapters/openshell/native-inference-profile-response.ts index 745a1848ae8..b79d34f0b27 100644 --- a/src/lib/adapters/openshell/native-inference-profile-response.ts +++ b/src/lib/adapters/openshell/native-inference-profile-response.ts @@ -68,8 +68,8 @@ function nativeCredential(value: unknown, expected: NativeProfileBoundary): bool credential.name === "api_key" && stringArrayEquals(credential.envVars, [expected.credentialEnv]) && credential.required === true && - credential.authStyle === "bearer" && - credential.headerName === "authorization" && + credential.authStyle === expected.authStyle && + credential.headerName === expected.headerName && credential.queryParam === "" && credential.pathTemplate === "" && credential.refresh === undefined && diff --git a/src/lib/onboard/created-sandbox-selection-reconciliation.test.ts b/src/lib/onboard/created-sandbox-selection-reconciliation.test.ts index 9714346def4..effaae22e63 100644 --- a/src/lib/onboard/created-sandbox-selection-reconciliation.test.ts +++ b/src/lib/onboard/created-sandbox-selection-reconciliation.test.ts @@ -91,6 +91,7 @@ describe("restored OpenClaw selection reconciliation", () => { null, "nemoclaw-9090", undefined, + { endpointUrl: undefined, nativeProvider: false }, ); }); 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 029bd0ff23e..a167fbd5de1 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 @@ -155,6 +155,36 @@ describe("sandbox registration route transaction", () => { 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], diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index ee97f5d4ed0..13cf1fde9fb 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -1246,6 +1246,7 @@ class SandboxStateFlow< } private acceptsNativeLocalReservation(targetEntry: SandboxEntry, sandboxName: string): boolean { + if (!targetEntry.nativeLocalProviderAttachment) return false; const agentName = (this.options.agent as { name?: string } | null)?.name ?? "openclaw"; const nativeLocalReservation = nativeLocalReservationStatus({ entry: targetEntry, diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index fa843358c3f..b4a6fce457d 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -42,7 +42,7 @@ const { ) => string; hermesConfigAllowsPrivateUrls: (config: Record) => boolean; runOpenClawNativeConfigBatchUntilHandleReady: ( - nativeNvidiaUpdate: boolean, + nativeHandleKind: "NVIDIA" | "local" | null, run: () => { status: number; stderr: string; error?: Error; signal?: string }, wait?: (ms: number) => void, warn?: (message: string) => void, @@ -275,6 +275,57 @@ 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(() => + 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: "" }; @@ -282,7 +333,7 @@ describe("composeSandboxConfigBody", () => { const wait = vi.fn(); const warn = vi.fn(); - runOpenClawNativeConfigBatchUntilHandleReady(true, run, wait, warn); + runOpenClawNativeConfigBatchUntilHandleReady("NVIDIA", run, wait, warn); expect(run).toHaveBeenCalledTimes(2); expect(wait).toHaveBeenCalledExactlyOnceWith(2_000); expect(warn).toHaveBeenCalledExactlyOnceWith( @@ -292,7 +343,7 @@ describe("composeSandboxConfigBody", () => { const exhaustedRun = vi.fn().mockReturnValue(pending); const exhaustedWait = vi.fn(); expect(() => - runOpenClawNativeConfigBatchUntilHandleReady(true, exhaustedRun, exhaustedWait, vi.fn()), + runOpenClawNativeConfigBatchUntilHandleReady("NVIDIA", exhaustedRun, exhaustedWait, vi.fn()), ).toThrow("Native OpenClaw config command failed after 10 attempt(s)"); expect(exhaustedRun).toHaveBeenCalledTimes(10); expect(exhaustedWait).toHaveBeenCalledTimes(9); @@ -306,7 +357,7 @@ describe("composeSandboxConfigBody", () => { const failedRun = vi.fn().mockReturnValue(result); const wait = vi.fn(); expect(() => - runOpenClawNativeConfigBatchUntilHandleReady(true, failedRun, wait, vi.fn()), + runOpenClawNativeConfigBatchUntilHandleReady("NVIDIA", failedRun, wait, vi.fn()), ).toThrow("Native OpenClaw config command failed after 1 attempt(s)"); expect(failedRun).toHaveBeenCalledOnce(); expect(wait).not.toHaveBeenCalled(); diff --git a/src/lib/sandbox/openclaw-native-config.ts b/src/lib/sandbox/openclaw-native-config.ts index a72da9a2cd1..247fb2888a8 100644 --- a/src/lib/sandbox/openclaw-native-config.ts +++ b/src/lib/sandbox/openclaw-native-config.ts @@ -19,6 +19,10 @@ const { const { 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 { isConfigObject, }: typeof import("../security/credential-filter") = require("../security/credential-filter"); @@ -83,14 +87,15 @@ export interface OpenClawConfigUpdate { // gateway restart replaces that process image with its old environment. Pin // the supervisor-issued handle in the native config batch before restarting; // the actual credential remains outside the sandbox and endpoint-bound. -const materializeNativeNvidiaHandle = [ +const materializeNativeProviderHandle = [ "import json, os, re, sys", - 'handle = os.environ.get("NVIDIA_INFERENCE_API_KEY", "")', + "env_key, endpoint, reference = sys.argv[2:]", + "handle = os.environ.get(env_key, '')", "if not handle:", ' sys.stderr.write("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\\n")', " raise SystemExit(75)", - 'if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY", handle):', - ' raise SystemExit("Native NVIDIA provider handle is unavailable or invalid")', + 'if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_" + re.escape(env_key), handle):', + ' raise SystemExit("Native provider handle is unavailable or invalid")', 'with open(sys.argv[1], "r+", encoding="utf-8") as stream:', " updates = json.load(stream)", " if not isinstance(updates, list):", @@ -100,14 +105,14 @@ const materializeNativeNvidiaHandle = [ ' if not isinstance(update, dict) or update.get("path") != "models.providers.inference":', " continue", ' provider = update.get("value")', - ' if not isinstance(provider, dict) or provider.get("apiKey") != sys.argv[3]:', + ' if not isinstance(provider, dict) or provider.get("apiKey") != reference:', " continue", - ' if provider.get("baseUrl") != sys.argv[2]:', - ' raise SystemExit("Native NVIDIA provider endpoint does not match")', + ' if provider.get("baseUrl") != endpoint:', + ' raise SystemExit("Native provider endpoint does not match")', ' provider["apiKey"] = handle', " matched += 1", " if matched != 1:", - ' raise SystemExit("Expected one native NVIDIA provider config update")', + ' raise SystemExit("Expected one native provider config update")', " stream.seek(0)", ' json.dump(updates, stream, separators=(",", ":"))', " stream.truncate()", @@ -123,11 +128,34 @@ export function buildOpenClawNativeConfigBatchInvocation( isConfigObject(value) && value.apiKey === NVIDIA_INFERENCE_PLACEHOLDER, ); - const materializeCommand = nativeNvidiaUpdate - ? `python3 -c ${shellQuote(materializeNativeNvidiaHandle)} "$file" ${shellQuote(NVIDIA_HOSTED_NATIVE_ENDPOINT)} ${shellQuote(NVIDIA_INFERENCE_PLACEHOLDER)} || exit $?; ` + const localReference = `openshell:resolve:env:${NATIVE_LOCAL_CREDENTIAL_ENV}`; + const nativeLocalUpdate = updates.find( + ({ dotpath, value }) => + dotpath === "models.providers.inference" && + isConfigObject(value) && + value.apiKey === localReference, + ); + const localEndpoint = + nativeLocalUpdate && isConfigObject(nativeLocalUpdate.value) + ? nativeLocalUpdate.value.baseUrl + : undefined; + if ( + nativeLocalUpdate && + (typeof localEndpoint !== "string" || + nativeLocalCredentialReference("compatible-endpoint", localEndpoint) !== localReference) + ) { + throw new Error("Native local OpenClaw credential requires a qualified private endpoint."); + } + const nativeHandleKind: "NVIDIA" | "local" | null = nativeNvidiaUpdate + ? "NVIDIA" + : nativeLocalUpdate + ? "local" + : null; + const materializeCommand = nativeHandleKind + ? `python3 -c ${shellQuote(materializeNativeProviderHandle)} "$file" ${shellQuote(nativeNvidiaUpdate ? "NVIDIA_INFERENCE_API_KEY" : NATIVE_LOCAL_CREDENTIAL_ENV)} ${shellQuote(nativeNvidiaUpdate ? NVIDIA_HOSTED_NATIVE_ENDPOINT : (localEndpoint as string))} ${shellQuote(nativeNvidiaUpdate ? NVIDIA_INFERENCE_PLACEHOLDER : localReference)} || exit $?; ` : ""; return { - nativeNvidiaUpdate, + nativeHandleKind, ...(!gateway || typeof gateway === "string" ? {} : { @@ -185,7 +213,7 @@ export function executeOpenClawNativeConfigBatch( gateway?: string | OpenShellRuntimeSelection, ): void { const invocation = buildOpenClawNativeConfigBatchInvocation(sandboxName, updates, gateway); - runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeNvidiaUpdate, () => + runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeHandleKind, () => runOpenshellCommand(binary, invocation.args, { env: invocation.env, replaceEnv: invocation.replaceEnv, @@ -204,7 +232,7 @@ type NativeConfigBatchResult = Pick< >; export function runOpenClawNativeConfigBatchUntilHandleReady( - nativeNvidiaUpdate: boolean, + nativeHandleKind: "NVIDIA" | "local" | null, run: () => NativeConfigBatchResult, wait: (ms: number) => void = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms), @@ -213,7 +241,7 @@ export function runOpenClawNativeConfigBatchUntilHandleReady( // OpenShell 0.0.116 attach can confirm desired state before a fresh process // receives the new environment. This retry is owned by native inference and // applies only when the materializer exited before OpenClaw changed config. - const maxAttempts = nativeNvidiaUpdate ? 10 : 1; + const maxAttempts = nativeHandleKind ? 10 : 1; for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { const result = run(); if (!result.error && !result.signal && result.status === 0) return; @@ -223,7 +251,9 @@ export function runOpenClawNativeConfigBatchUntilHandleReady( result.status === 75 && String(result.stderr ?? "").includes("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING"); if (handlePending && attempt < maxAttempts) { - warn(`Native NVIDIA provider handle pending; config attempt ${attempt}/${maxAttempts}`); + warn( + `Native ${nativeHandleKind} provider handle pending; config attempt ${attempt}/${maxAttempts}`, + ); wait(2_000); continue; } diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index 8b9fdb00d3b..db564e449da 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -91,6 +91,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { ...NO_RETRY, inferenceRouteContext: { provider: "ollama-local", + gatewayName: "my-gateway", nativeLocalExpected: true, nativeLocalProviderAttachment: localAttachment, }, @@ -121,6 +122,30 @@ describe("verifyDeployment inference route model-catalog validation", () => { 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("uses the native NVIDIA invocation instead of probing inference.local", async () => { const scripts: string[] = []; const probeInferenceInvocation = vi.fn(async () => ({ ok: true }) as const); diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 32e9f1c2a72..7c0976de60e 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -274,6 +274,7 @@ type InferenceRouteStatus = "ok" | "unreachable" | "unhealthy"; */ export type InferenceRouteContext = { provider?: string | null; + gatewayName?: string; nativeLocalExpected?: boolean; nativeLocalProviderAttachment?: NativeLocalProviderAttachment; nativeHostedProviderAttachment?: unknown; @@ -425,6 +426,7 @@ async function verifyInferenceRoute( nativeLocal && (!normalizeNativeLocalProviderAttachment(context.nativeLocalProviderAttachment) || context.nativeLocalProviderAttachment?.sandboxName !== sandboxName || + context.nativeLocalProviderAttachment?.gatewayName !== context.gatewayName || context.nativeLocalProviderAttachment?.provider !== context.provider) ) { return { @@ -971,6 +973,7 @@ export function onboardInferenceVerificationContext( return { route: { provider: flow.provider, + gatewayName, nativeLocalExpected, nativeLocalProviderAttachment, nativeHostedProviderAttachment, diff --git a/test/e2e/live/managed-image-activation-e2e-helpers.ts b/test/e2e/live/managed-image-activation-e2e-helpers.ts index 10d9b1d6dc2..e4a6d656110 100644 --- a/test/e2e/live/managed-image-activation-e2e-helpers.ts +++ b/test/e2e/live/managed-image-activation-e2e-helpers.ts @@ -996,6 +996,7 @@ export async function qualifyAgent( receipt.endpointUrl === endpointUrl && attachments.exitCode === 0 && attachments.stdout.split(/\s+/u).includes(receipt.providerName), + `receipt=${JSON.stringify(receipt)} attachments=${resultText(attachments)}`, ).toBe(true); } diff --git a/test/repository/cli-coverage-sequencer.test.ts b/test/repository/cli-coverage-sequencer.test.ts index 18fc771cb6f..a6080e2bf33 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.056); }); it("balances the serialized integration lane across the twelve CI shards (#6237)", () => { diff --git a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts index 215bfb06164..16ccdfeb709 100644 --- a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts +++ b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts @@ -179,9 +179,9 @@ describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () it.each([ { agent: "OpenClaw cached install", - marker: "# Config inputs precede the cached plugin install.", + marker: "# Reuse managed config inputs.", dockerfile: "Dockerfile", - start: "chmod 444 /src/lib/*.ts", + start: "chmod 444 /src/lib/*.ts /src/lib/inference/native-local/agent-config.ts", file: "/src/lib/inference/native-local/agent-config.ts", }, { From d880f199615e2cc2c6845f6775485659892d5c56 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Sun, 11 Oct 2026 20:07:47 -0700 Subject: [PATCH 14/45] fix: refresh native local handle after OpenClaw rebuild --- scripts/nemoclaw-start.sh | 45 ++++++++++-- .../provider-placeholder-refresh.test.ts | 73 ++++++++++++++++++- 2 files changed, 111 insertions(+), 7 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 2b7eda0b7a6..9b99bb03199 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -821,11 +821,13 @@ 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 import subprocess import sys +from urllib.parse import urlsplit config_file = sys.argv[1] prefix = "openshell:resolve:env:" @@ -879,15 +881,46 @@ config = json.loads(parsed.stdout) refreshed = set() native_refreshed = False -# A native NVIDIA handle persisted by the host-side config batch belongs to -# the provider revision that issued it. After a supervisor restart, only the -# current revision is available, so replace that exact config field before -# OpenClaw starts. Never copy a raw value or rewrite config for other providers. +# A native handle persisted by the host-side config batch belongs to the +# provider revision that issued it. After a restart or sandbox rebuild, only +# the current revision is available. Refresh only a known native endpoint and +# its exact scoped credential field before OpenClaw starts. models = config.get("models") if isinstance(config, dict) else None providers = models.get("providers") if isinstance(models, dict) else None native = providers.get("inference") if isinstance(providers, dict) else None -if isinstance(native, dict) and native.get("baseUrl") == "https://integrate.api.nvidia.com/v1": - key = "NVIDIA_INFERENCE_API_KEY" +native_key = None +if isinstance(native, dict): + endpoint = native.get("baseUrl") + if endpoint == "https://integrate.api.nvidia.com/v1": + native_key = "NVIDIA_INFERENCE_API_KEY" + elif 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")) + ): + native_key = "NEMOCLAW_LOCAL_INFERENCE_TOKEN" + except ValueError: + pass +if native_key: + key = native_key scoped = re.compile(rf"^{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{key}$") saved = native.get("apiKey") state = runtime_state(key) diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts index c99aa6eadeb..ba8f7dc9cc5 100644 --- a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts @@ -27,7 +27,7 @@ function execFileResult(file, args, options) { ); } -describe.concurrent("native NVIDIA handle refresh", () => { +describe.concurrent("native provider handle refresh", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); async function runRefresh( config: unknown, @@ -115,6 +115,77 @@ describe.concurrent("native NVIDIA handle refresh", () => { }, ); + 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", From ec5ff1d82e91c4693ec50ae9a0ef8f4803241bb9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 12 Oct 2026 12:05:48 -0700 Subject: [PATCH 15/45] fix(inference): align native credentials and legacy rebuild preflight Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/about/ecosystem-deepagents.mdx | 2 +- docs/about/how-it-works.mdx | 2 +- docs/about/overview.mdx | 2 +- docs/deployment/deploy-to-headless-server.mdx | 2 +- .../quickstart-langchain-deepagents-code.mdx | 2 +- docs/get-started/quickstart-pi.mdx | 2 +- docs/get-started/quickstart.mdx | 2 +- .../inference/how-inference-routing-works.mdx | 11 +- .../understand-provider-validation.mdx | 2 +- docs/inference/use-shared-gateway-routes.mdx | 4 +- .../recover-rebuild-sandboxes.mdx | 3 +- docs/manage-sandboxes/workspace-files.mdx | 2 +- docs/reference/architecture.mdx | 16 +- docs/reference/commands.mdx | 18 +- docs/reference/enterprise-readiness.mdx | 4 +- docs/reference/network-policies.mdx | 6 +- docs/reference/pi-support.mdx | 2 +- docs/security/best-practices.mdx | 8 +- scripts/checks/test-create-require-budget.mts | 1 - ...build-legacy-local-route-preflight.test.ts | 55 ++++ .../rebuild-local-provider-recreate.test.ts | 238 ------------------ .../sandbox/rebuild-preflight-phase.ts | 22 ++ .../config/live-export-inference-contract.ts | 6 +- src/lib/inference/config.ts | 1 + src/lib/inference/native-local.test.ts | 28 +++ .../inference/native-local/agent-config.ts | 49 ++-- src/lib/inference/native-local/contract.ts | 49 +--- src/lib/inference/selection.ts | 20 ++ src/lib/onboard/machine/core-flow-phases.ts | 13 +- ...vider-inference-legacy-local-route.test.ts | 62 +++++ .../machine/handlers/provider-inference.ts | 26 ++ src/lib/onboard/setup-inference.ts | 2 - 32 files changed, 316 insertions(+), 346 deletions(-) create mode 100644 src/lib/actions/sandbox/rebuild-legacy-local-route-preflight.test.ts delete mode 100644 src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts create mode 100644 src/lib/onboard/machine/handlers/provider-inference-legacy-local-route.test.ts diff --git a/docs/about/ecosystem-deepagents.mdx b/docs/about/ecosystem-deepagents.mdx index 15768379e7a..7117de7b3e9 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, fixed hosted providers, and new local selections use native endpoints through attached providers. Custom endpoints and existing legacy routes use `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..eb2e0464cfd 100644 --- a/docs/about/how-it-works.mdx +++ b/docs/about/how-it-works.mdx @@ -212,7 +212,7 @@ 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 call host-local endpoints through sandbox-attached OpenShell providers. Existing local sandboxes can keep using `inference.local` while OpenShell 0.0.116 is pinned; resume or rebuild stops before changing them and requires backup and fresh re-onboarding. User-supplied endpoints, 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..820263ea202 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. 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..744c4b9464c 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. 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 0c9779945d1..84a4cb7289f 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -165,7 +165,7 @@ The wizard asks for an inference provider, model, required credential, and sandb When you edit inference, NemoClaw clears the credential staged for the discarded selection. NemoClaw preserves the sandbox name. When you edit the sandbox name, NemoClaw preserves the inference selection. The sandbox prompt shows the prior name as its default. After you apply the configuration, routine editing ends. If inference setup fails and offers a `back` recovery action, you can return to provider and model selection and then review the updated configuration again. Provider registration, inference setup, policy selection, and sandbox creation then continue forward. The default Deep Agents sandbox name is `deepagents-code`. Use a distinct name, such as `my-deepagents`, when you run Deep Agents, Hermes, and OpenClaw sandboxes side by side. Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) for provider-specific prompts. -The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. NVIDIA Endpoints uses `https://integrate.api.nvidia.com/v1` through a least-privilege OpenShell provider attached to the sandbox. 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.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. +The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. 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 and existing legacy local routes retain `https://inference.local/v1` on the pinned OpenShell release; 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.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. diff --git a/docs/get-started/quickstart-pi.mdx b/docs/get-started/quickstart-pi.mdx index 66dc618ce80..a7d7e4c526e 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. 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 69458ccae77..c69c5e2e363 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -376,7 +376,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. + 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/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index 391e13918ff..525c81ac267 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 use sandbox-attached OpenShell providers to reach qualified host-local endpoints. 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. 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 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 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/understand-provider-validation.mdx b/docs/inference/understand-provider-validation.mdx index e1ba247d649..8ed64dc22a7 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. 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. diff --git a/docs/inference/use-shared-gateway-routes.mdx b/docs/inference/use-shared-gateway-routes.mdx index 112040a236d..4cb88ec1a5f 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, 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 3b95ddc6c83..ff33be7e779 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..bc9e40eeb3a 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, fixed hosted providers, and new local selections use attached native endpoints; custom endpoints and existing legacy routes use `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 c14aee7fc19..39f085aecf1 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
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
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,7 +195,7 @@ 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. @@ -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: +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 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 dc426c134c2..74f4fd2051a 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1165,7 +1165,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 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`. @@ -1175,7 +1175,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 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. @@ -1677,7 +1677,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. 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` @@ -1725,7 +1725,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. 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 | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -2079,7 +2079,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. Custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. @@ -2661,7 +2661,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 @@ -3251,7 +3251,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. 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. @@ -3555,7 +3555,7 @@ $$nemoclaw my-assistant inference get -Switch the active inference provider or model for a NemoClaw-managed OpenClaw sandbox. For NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider, the command attaches or updates the selected sandbox's native provider. Custom endpoints and local providers retain their existing shared OpenShell route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For OpenClaw, the patch updates the OpenClaw config provider namespace and selected model. After any changed config sync, NemoClaw uses the managed supervisor to restart only the OpenClaw gateway and verify its health and forwards. The sandbox remains running, but agent requests are briefly interrupted. If the restart fails, the selected inference path and config remain committed; run `$$nemoclaw gateway restart` to finish applying the switch. After every changed synchronized inference selection, NemoClaw also verifies that the local CLI device has the managed gateway's required pairing scopes before it reports success. If pairing does not converge, the selected inference path and config remain committed. Run `$$nemoclaw doctor --fix`, then retry the agent turn. +Switch the active inference provider or model for a NemoClaw-managed OpenClaw sandbox. For NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider, the command attaches or updates the selected sandbox's native provider. Custom endpoints retain their shared OpenShell route; new OpenClaw local selections use an attached native provider. 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. @@ -3591,7 +3591,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. Custom endpoints retain the shared-route workflow; new OpenClaw local selections use an attached native provider. 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..de4c7d91a5c 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. 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. 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..7c70db3e308 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,7 +90,7 @@ 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, 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. @@ -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. 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..55a0f0a4a80 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. 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/security/best-practices.mdx b/docs/security/best-practices.mdx index 0919c18ac9d..aff3de31b23 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. 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. 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. 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. 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/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/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..7d7c2b761fa --- /dev/null +++ b/src/lib/actions/sandbox/rebuild-legacy-local-route-preflight.test.ts @@ -0,0 +1,55 @@ +// 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 { RebuildSandboxEntry } from "./rebuild-flow-helpers"; +import { blockRebuildOnLegacySharedLocalRoute } from "./rebuild-preflight-phase"; + +describe("rebuild legacy local route preflight", () => { + it.each([ + { agent: "openclaw", provider: "ollama-local" }, + { agent: "openclaw", provider: "vllm-local" }, + { agent: "langchain-deepagents-code", provider: "ollama-local" }, + ])("warns before rebuilding an existing $agent $provider sandbox", ({ agent, provider }) => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const bail = vi.fn((message: string): never => { + throw new Error(message); + }); + const entry = { + name: "alpha", + createdAt: "2026-09-01T00:00:00Z", + agent, + provider, + model: "local-model", + } as RebuildSandboxEntry; + + expect(() => blockRebuildOnLegacySharedLocalRoute("alpha", entry, 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, 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..69f56f17204 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 ( + typeof sandboxEntry.createdAt !== "string" || + !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/adapters/config/live-export-inference-contract.ts b/src/lib/adapters/config/live-export-inference-contract.ts index 775dc1bf2c5..78496f8c4b2 100644 --- a/src/lib/adapters/config/live-export-inference-contract.ts +++ b/src/lib/adapters/config/live-export-inference-contract.ts @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; -import { normalizeNativeLocalProviderAttachment } from "../../inference/native-local/contract"; import { exportNativeInferenceReceipt } from "../../domain/config/export-evidence"; import { fixedNativeProviderForAttachment } from "../../inference/native-provider/fixed"; import { isDeepStrictEqual } from "node:util"; @@ -11,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")) { diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 67f7fa26e1c..300b8ee232d 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -33,6 +33,7 @@ export { 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"; diff --git a/src/lib/inference/native-local.test.ts b/src/lib/inference/native-local.test.ts index 7de8247de5c..e9922b4b167 100644 --- a/src/lib/inference/native-local.test.ts +++ b/src/lib/inference/native-local.test.ts @@ -8,6 +8,8 @@ import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { nativeLocalIdentity, + nativeLocalCredentialReference, + normalizeNativeLocalBinding, normalizeNativeLocalProviderAttachment, usesNativeLocalInferenceForAgent, type NativeLocalBinding, @@ -115,6 +117,32 @@ function fixture(selectedBinding: NativeLocalBinding = binding) { } 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], diff --git a/src/lib/inference/native-local/agent-config.ts b/src/lib/inference/native-local/agent-config.ts index 8c6ba5f74a8..d320fbdaa37 100644 --- a/src/lib/inference/native-local/agent-config.ts +++ b/src/lib/inference/native-local/agent-config.ts @@ -1,39 +1,56 @@ // 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"; + export const NATIVE_LOCAL_CREDENTIAL_ENV = "NEMOCLAW_LOCAL_INFERENCE_TOKEN"; -/** 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; +/** 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 = - /^10\.\d+\.\d+\.\d+$/.test(host) || - /^192\.168\.\d+\.\d+$/.test(host) || - /^172\.(1[6-9]|2[0-9]|3[01])\.\d+\.\d+$/.test(host); + 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 || - (!privateIpv4 && host !== "host.openshell.internal" && host !== "host.docker.internal") + 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 `openshell:resolve:env:${NATIVE_LOCAL_CREDENTIAL_ENV}`; + 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$"; diff --git a/src/lib/inference/native-local/contract.ts b/src/lib/inference/native-local/contract.ts index 313d9a59ee7..1baf30fe2f2 100644 --- a/src/lib/inference/native-local/contract.ts +++ b/src/lib/inference/native-local/contract.ts @@ -4,8 +4,7 @@ import { OLLAMA_PROXY_PORT } from "../../core/ollama-proxy-port"; import { VLLM_PORT } from "../../core/vllm-port"; import { createHash } from "node:crypto"; -import { isIP } from "node:net"; -import { unsafeEndpointUrlViolation } from "../../core/endpoint-url-safety"; +import { qualifiedNativeLocalEndpointUrl } from "./agent-config"; import { isValidName } from "../../../../nemoclaw/dist/shared/sandbox-name.cjs"; import type { NativeProviderAttachment } from "../native-provider/lifecycle"; @@ -40,7 +39,6 @@ export function normalizeNativeLocalBinding(value: unknown): NativeLocalBinding (!isLocalInferenceProvider(input.provider as string) && input.provider !== "compatible-endpoint") || typeof input.endpointUrl !== "string" || - unsafeEndpointUrlViolation(input.endpointUrl) || typeof input.credentialEnv !== "string" || !/^[A-Z][A-Z0-9_]*$/.test(input.credentialEnv) || (input.authMode !== "authenticated" && input.authMode !== "sentinel") || @@ -52,40 +50,17 @@ export function normalizeNativeLocalBinding(value: unknown): NativeLocalBinding (typeof input.transactionId !== "string" || !/^[a-f0-9]{64}$/.test(input.transactionId))) ) return undefined; - try { - const endpoint = new URL(input.endpointUrl); - const host = endpoint.hostname; - // Loopback always identifies the sandbox itself. Public or arbitrary DNS - // names belong to hosted endpoint validation, not the host-local bridge. - 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 undefined; - return { - provider: input.provider as NativeLocalProvider, - endpointUrl: `${endpoint.origin}${endpoint.pathname.replace(/\/$/, "")}`, - credentialEnv: input.credentialEnv, - authMode: input.authMode, - gatewayName: input.gatewayName, - sandboxName: input.sandboxName, - ...(typeof input.transactionId === "string" ? { transactionId: input.transactionId } : {}), - }; - } catch { - 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) { 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/machine/core-flow-phases.ts b/src/lib/onboard/machine/core-flow-phases.ts index 9a2f6a485c2..9acad6f6932 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/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..a171aeb8825 --- /dev/null +++ b/src/lib/onboard/machine/handlers/provider-inference-legacy-local-route.test.ts @@ -0,0 +1,62 @@ +// 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 { 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], + ["langchain-deepagents-code", true], + ["langchain-deepagents-code", false], + ])( + "stops %s before provider mutations with completed selection %s", + async (selectedAgent, complete) => { + 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", + createdAt: "2026-09-01T00:00:00Z", + provider: session.provider, + model: session.model, + endpointUrl: session.endpointUrl, + credentialEnv: session.credentialEnv, + preferredInferenceApi: session.preferredInferenceApi, + } as SandboxEntry; + const { deps, calls } = createDeps({ getSandboxRegistryEntry: () => recorded }); + + 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.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 64945f0809f..db202137124 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -4,6 +4,7 @@ import type { ModelSelectionProvenance } from "../../../domain/telemetry/provenance"; import { clearAutoDetectedCompatibleContextWindow } from "../../../inference/compatible-endpoint-context"; import { + hasLegacySharedLocalInferenceRoute, resolveAgentProviderInferenceApi, usesNativeLocalInference, usesNativeLocalInferenceForAgent, @@ -22,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 { @@ -303,6 +305,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( @@ -1257,6 +1260,28 @@ function nativeLocalAgentOptions(agent: unknown, provider: string, endpointUrl: 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 && + typeof recorded.createdAt === "string" && + 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, @@ -1473,6 +1498,7 @@ export async function handleProviderInferenceState({ forceInferenceSetup ||= completeRecoveredReviewSelectionAfterInference || reviewRecoveredInteractively; let managedLlamaCppRecovered = false; + assertNoLegacySharedLocalResume(deps, effectiveResume, sandboxName); if (resumeProviderSelection) { assertOnboardReasoningEffortRoute(reasoningEffortRequest, provider, preferredInferenceApi); assertProviderInferenceRouteCompatible( diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index a683ef3883c..1d672c54dea 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -1476,8 +1476,6 @@ export function createSetupInference( try { const providerResult = await setupSelectedProvider(); if (providerResult) return providerResult; - if (selectingNativeLocal && !nativeLocalProviderAttachment) - throw new Error("Native local provider registration was not confirmed."); if (selectingNativeLocal && !nativeLocalProviderAttachment) throw new Error("Native local provider registration was not confirmed."); if ( From 45edfc9ea7a0fee0edeb962ed0473db62abd0069 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 12 Oct 2026 12:11:38 -0700 Subject: [PATCH 16/45] fix(inference): verify selected native local endpoint Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../verify-deployment-inference-route.test.ts | 59 +++++++++++++++++++ src/lib/verify-deployment.ts | 34 +++++++---- 2 files changed, 82 insertions(+), 11 deletions(-) diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index db564e449da..ad049ba1e84 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -146,6 +146,65 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(probeInferenceInvocation).not.toHaveBeenCalled(); }); + 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); diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 7c0976de60e..de453d0a7a6 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -34,6 +34,7 @@ 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, @@ -274,6 +275,7 @@ type InferenceRouteStatus = "ok" | "unreachable" | "unhealthy"; */ export type InferenceRouteContext = { provider?: string | null; + endpointUrl?: string | null; gatewayName?: string; nativeLocalExpected?: boolean; nativeLocalProviderAttachment?: NativeLocalProviderAttachment; @@ -399,6 +401,23 @@ 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; + const selected = normalizeNativeLocalBinding({ ...attachment, endpointUrl: context.endpointUrl }); + return selected?.endpointUrl === attachment.endpointUrl; +} + async function verifyInferenceRoute( sandboxName: string, deps: VerifyDeploymentDeps, @@ -422,13 +441,7 @@ async function verifyInferenceRoute( hint: "Restore the recorded provider ownership before retrying onboarding.", }; } - if ( - nativeLocal && - (!normalizeNativeLocalProviderAttachment(context.nativeLocalProviderAttachment) || - context.nativeLocalProviderAttachment?.sandboxName !== sandboxName || - context.nativeLocalProviderAttachment?.gatewayName !== context.gatewayName || - context.nativeLocalProviderAttachment?.provider !== context.provider) - ) { + if (nativeLocal && !matchesNativeLocalVerificationRoute(context, sandboxName)) { return { status: "unhealthy", detail: "native local provider attachment is missing or invalid", @@ -973,6 +986,7 @@ export function onboardInferenceVerificationContext( return { route: { provider: flow.provider, + endpointUrl: flow.endpointUrl ?? null, gatewayName, nativeLocalExpected, nativeLocalProviderAttachment, @@ -984,6 +998,7 @@ export function onboardInferenceVerificationContext( agentName, model: flow.model, provider: flow.provider, + endpointUrl: flow.endpointUrl ?? null, preferredInferenceApi: flow.preferredInferenceApi, nativeLocalExpected, nativeLocalProviderAttachment, @@ -1009,10 +1024,7 @@ export async function probeOnboardInferenceInvocation( } if ( (context.nativeLocalExpected || context.nativeLocalProviderAttachment !== undefined) && - (!normalizeNativeLocalProviderAttachment(context.nativeLocalProviderAttachment) || - context.nativeLocalProviderAttachment?.sandboxName !== context.sandboxName || - context.nativeLocalProviderAttachment?.gatewayName !== context.gatewayName || - context.nativeLocalProviderAttachment?.provider !== provider) + !matchesNativeLocalVerificationRoute(context, context.sandboxName) ) { return { ok: false, detail: "native local provider attachment is missing or invalid" }; } From 57156918ef2c86958397f9f97cb02bfce4b26ff9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:36:59 -0700 Subject: [PATCH 17/45] fix(inference): scope native provider retirement to selected runtime Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/destroy-execution.ts | 12 ++++++- .../sandbox/destroy-native-local.test.ts | 33 +++++++++++++++++++ src/lib/actions/sandbox/destroy.ts | 7 +++- test/e2e/README.md | 4 +-- 4 files changed, 51 insertions(+), 5 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-execution.ts b/src/lib/actions/sandbox/destroy-execution.ts index d521ecd2a61..b4bcc270ee8 100644 --- a/src/lib/actions/sandbox/destroy-execution.ts +++ b/src/lib/actions/sandbox/destroy-execution.ts @@ -1149,9 +1149,19 @@ export async function recordDestroyCompletion( 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(), + 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 index f44da773aa3..73bba948b97 100644 --- a/src/lib/actions/sandbox/destroy-native-local.test.ts +++ b/src/lib/actions/sandbox/destroy-native-local.test.ts @@ -10,10 +10,12 @@ import { 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", @@ -100,7 +102,38 @@ describe("native local provider destroy", () => { 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 9adc1d1c0e7..21cd3dcb03f 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -1149,7 +1149,12 @@ async function destroySandboxUnlocked( preparedManagedLlamaCppCleanup?.abort(); } if (deleteSucceededOrAlreadyGone && sandbox) { - await retireDestroyedSandboxNativeLocalProvider(sandbox, cleanupGatewayName).catch((error) => { + await retireDestroyedSandboxNativeLocalProvider( + sandbox, + cleanupGatewayName, + runOpenshell, + destroyRuntimeSelection, + ).catch((error) => { preparedManagedLlamaCppCleanup?.abort(); throw error; }); diff --git a/test/e2e/README.md b/test/e2e/README.md index 90fa46069d6..939157ba4bf 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -2186,9 +2186,7 @@ The explicit `dgx-station-express` target runs the local Station Express install ### Native host-local inference -The first slice of #12975 supports the DCode/OpenClaw contract below. Pi and Hermes continue to use their existing shared local routes. Native-local provider attachment for those agents belongs to later slices. - -`managed-image-activation` owns real OpenClaw and DCode agent turns before and after restart. Its existing 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. Hermes remains on 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. The former TC-INF-09 managed-route curl probe is retired because these existing targets now own the native agent and local endpoint outcomes. The `inference-routing` target retains its other cases and 75-minute limit. Existing GPU qualification owns Ollama, vLLM, llama.cpp, startup, and cleanup. +`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. 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. From 285003e0c714b5c256ea523bc5e81e3ed7bec540 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:17:59 -0700 Subject: [PATCH 18/45] fix(inference): reject invalid persisted local provider attachments Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ...egistry-native-provider-attachment.test.ts | 61 +++++++++++++++++++ src/lib/state/registry/persistence.ts | 36 ++++++++++- 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index ac216b97f55..1775c3bf4be 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -296,3 +296,64 @@ it.each([ } }, ); + +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/persistence.ts b/src/lib/state/registry/persistence.ts index 880bd874079..a2ccbccadbf 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -1,7 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { normalizeNativeLocalProviderAuthorities } from "../../inference/native-local/contract"; +import { + normalizeNativeLocalProviderAttachment, + normalizeNativeLocalProviderAuthorities, +} from "../../inference/native-local/contract"; import path from "node:path"; import { requireHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; @@ -99,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", @@ -112,8 +134,12 @@ export function load(): SandboxRegistry { export function save(data: SandboxRegistry): void { const serialized = serializeRegistryForDisk(data); const previous = readConfigFile(REGISTRY_FILE, {}); - if (isObjectRecord(previous)) + 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. @@ -224,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, @@ -232,6 +259,7 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, deferredN1xManagedVllmAccepted: _deferredN1xManagedVllmAccepted, + nativeLocalProviderAttachment: _nativeLocalProviderAttachment, nativeHostedProviderAttachment: hostedAttachment, nativeNvidiaProviderAuthority: _legacyNativeNvidiaProviderAuthority, mcp: _legacyMcp, @@ -247,6 +275,7 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { ); return { ...rest, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(workload ? { workload } : {}), ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), @@ -294,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, @@ -302,6 +332,7 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { hostLocalInferenceProvenance: _hostLocalInferenceProvenance, servingProfileProvenance: _servingProfileProvenance, deferredN1xManagedVllmAccepted: _deferredN1xManagedVllmAccepted, + nativeLocalProviderAttachment: _nativeLocalProviderAttachment, nativeHostedProviderAttachment: hostedAttachment, nativeNvidiaProviderAuthority: _legacyNativeNvidiaProviderAuthority, mcp: _legacyMcp, @@ -317,6 +348,7 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { ); return { ...rest, + ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(rest.dashboardPort === 0 ? { dashboardPort: null } : {}), ...(workload ? { workload } : {}), From 17b3f8ea3ca06d0471b4463cfaac4ac6821fcf6c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 12 Oct 2026 19:26:04 -0700 Subject: [PATCH 19/45] fix(inference): package native-local dependencies in agent images Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- Dockerfile | 6 +++--- agents/langchain-deepagents-code/Dockerfile | 3 ++- docs/reference/architecture.mdx | 2 +- src/lib/inference/native-local/agent-config.ts | 2 +- .../finalization-deps-terminal-inference.test.ts | 5 +++++ src/lib/sandbox/build-context.ts | 1 + test/repository/cli-coverage-sequencer.test.ts | 2 +- test/runtime/sandbox/sandbox-build-context.test.ts | 2 ++ .../sandbox-provisioning-helper-permissions.test.ts | 10 +++++++++- 9 files changed, 25 insertions(+), 8 deletions(-) diff --git a/Dockerfile b/Dockerfile index e44cb55ea72..8e3c661f929 100644 --- a/Dockerfile +++ b/Dockerfile @@ -699,6 +699,7 @@ 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/ @@ -1551,14 +1552,13 @@ 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 \ + /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 @@ -1948,7 +1948,7 @@ 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 \ + /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 \ diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index 3e83d9eddd5..19817df3965 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -156,6 +156,7 @@ 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 @@ -191,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/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 \ +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/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 39f085aecf1..8eae1477df7 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -200,7 +200,7 @@ Layering from top to bottom: 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. diff --git a/src/lib/inference/native-local/agent-config.ts b/src/lib/inference/native-local/agent-config.ts index d320fbdaa37..0534fb23d56 100644 --- a/src/lib/inference/native-local/agent-config.ts +++ b/src/lib/inference/native-local/agent-config.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { isIP } from "node:net"; -import { unsafeEndpointUrlViolation } from "../../core/endpoint-url-safety"; +import { unsafeEndpointUrlViolation } from "../../core/endpoint-url-safety.ts"; export const NATIVE_LOCAL_CREDENTIAL_ENV = "NEMOCLAW_LOCAL_INFERENCE_TOKEN"; 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 101e1fe435e..ce92eb54c44 100644 --- a/src/lib/onboard/machine/finalization-deps-terminal-inference.test.ts +++ b/src/lib/onboard/machine/finalization-deps-terminal-inference.test.ts @@ -51,8 +51,10 @@ describe("terminal inference finalization dependency", () => { expect(probeOnboardInferenceInvocation).toHaveBeenCalledExactlyOnceWith({ ...input, gatewayName: "nemoclaw-19090", + endpointUrl: null, nativeLocalExpected: false, nativeLocalProviderAttachment: undefined, + nativeHostedProviderAttachment: undefined, }); }); @@ -81,8 +83,10 @@ describe("terminal inference finalization dependency", () => { ...input, provider: "ollama-local", gatewayName: "nemoclaw-19090", + endpointUrl: localBinding.endpointUrl, nativeLocalExpected: true, nativeLocalProviderAttachment: localAttachment, + nativeHostedProviderAttachment: undefined, }); }); @@ -102,6 +106,7 @@ describe("terminal inference finalization dependency", () => { expect(probeOnboardInferenceInvocation).toHaveBeenCalledExactlyOnceWith({ ...input, gatewayName: "nemoclaw", + endpointUrl: null, nativeLocalExpected: false, nativeLocalProviderAttachment: undefined, nativeHostedProviderAttachment, diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index ea7fe65575c..fdce95c0b1b 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -132,6 +132,7 @@ 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"), diff --git a/test/repository/cli-coverage-sequencer.test.ts b/test/repository/cli-coverage-sequencer.test.ts index a6080e2bf33..5025d4826ab 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.056); + expect(Math.max(...weights)).toBeLessThanOrEqual(averageWeight * 1.058); }); 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 b4421bcd217..3fe3d5a57d0 100644 --- a/test/runtime/sandbox/sandbox-build-context.test.ts +++ b/test/runtime/sandbox/sandbox-build-context.test.ts @@ -271,6 +271,7 @@ 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"), @@ -521,6 +522,7 @@ 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"), diff --git a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts index 16ccdfeb709..461e0ff314f 100644 --- a/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts +++ b/test/runtime/sandbox/sandbox-provisioning-helper-permissions.test.ts @@ -104,6 +104,7 @@ 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, @@ -179,7 +180,7 @@ describe("sandbox provisioning: copied OpenClaw helper permissions (#2861)", () it.each([ { agent: "OpenClaw cached install", - marker: "# Reuse managed config inputs.", + 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", @@ -198,6 +199,13 @@ it.each([ 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 }) => { From 7693652baa262b26ac4f1bfedacb016f173b02dd Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 12 Oct 2026 19:29:25 -0700 Subject: [PATCH 20/45] chore(ci): retire merged E2E growth exception Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-growth-exceptions.json | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 633c8319951..5d9ea83c07e 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 #12767 shares restoration validation through one command builder in the scanned live source set. Every restoration predicate remains counted. This transition preserves the seven-assertion concurrent-gateway reduction from #12608. Exact revised transition approval: https://github.com/NVIDIA/NemoClaw/pull/12767#issuecomment-6061291322. This prerequisite must merge before the repaired #12767 candidate uses the exception. A changed base or candidate budget invalidates this entry. Remove after #12767 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 moves native-local agent and sibling-policy coverage into existing live targets without increasing total direct expectations. It raises the double-onboard per-file budget by one while retiring the curl-only inference-routing case. Exact maintainer approval for the current main-to-head budget change: https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6104551185. This candidate entry supports local validation; independent CI verifies the PR-specific approval on GitHub. Remove after #12977 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 moves native-local agent and sibling-policy coverage into existing live targets without increasing total direct expectations. It raises the double-onboard per-file budget by one while retiring the curl-only inference-routing case. Exact maintainer approval for the current main-to-head budget change: https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6104551185. This candidate entry supports local validation; independent CI verifies the PR-specific approval on GitHub. Remove after #12977 merges.", "schemaVersion": 1, "exceptions": [ { @@ -22,11 +22,6 @@ "baseBudgetSha256": "53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441", "headBudgetSha256": "8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a" }, - { - "pullRequest": 12767, - "baseBudgetSha256": "53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441", - "headBudgetSha256": "1653f4c6c0292d2853727c39ddb36aa55361f749df3db32aa3847c3d4a7f30cb" - }, { "pullRequest": 12777, "baseBudgetSha256": "53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441", From 73f315110f20261e13d71a687260d07a1391675c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 12 Oct 2026 19:39:19 -0700 Subject: [PATCH 21/45] test(dcode): anchor permission order to chmod step Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/agents/deepagents/langchain-deepagents-code-image.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/agents/deepagents/langchain-deepagents-code-image.test.ts b/test/agents/deepagents/langchain-deepagents-code-image.test.ts index a62f8c06457..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/src/lib/inference/native-local/agent-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"); From bb0208e8a877ca09b0771fd2c7bbac3e5d832165 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:33:40 -0700 Subject: [PATCH 22/45] fix(onboard): align dashboard contract with shipped image Recognize the reviewed native-local Dockerfile chmod instruction. Sync the existing Hermes E2E assertion budget after main integration. Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/e2e-assertion-budget.json | 2 +- .../onboard/dockerfile-remote-dashboard-bind-contract.ts | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 18a6eb4b404..d4ef5f46c42 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -68,7 +68,7 @@ "test/e2e/live/hermes-discord.test.ts": [10,22,17,61,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,76,1], + "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,75,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], diff --git a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts index 6f8b785ec12..17c41fc545a 100644 --- a/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts +++ b/src/lib/onboard/dockerfile-remote-dashboard-bind-contract.ts @@ -125,10 +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 same metadata-only instruction includes the native-local config input. - "aa67a56299fedea5c7130da731ef3ee58a9800a69e7f92e5f13e64a54faab6ab", - // The same instruction after removing a duplicate wrapper chmod operand. - "d70666fe15aa35161e49de378e90a3b7994814bca11efa9ca96b2581fac63b0f", + // 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", From e11b93674102a71608e13dde9d3476e48a0366ff Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:49:04 -0700 Subject: [PATCH 23/45] docs(inference): clarify qualified local endpoint routing Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/about/ecosystem-deepagents.mdx | 2 +- docs/about/how-it-works.mdx | 2 +- docs/about/overview.mdx | 2 +- docs/deployment/deploy-to-headless-server.mdx | 2 +- .../quickstart-langchain-deepagents-code.mdx | 2 +- docs/get-started/quickstart-pi.mdx | 2 +- docs/get-started/quickstart.mdx | 2 +- docs/inference/how-inference-routing-works.mdx | 6 +++--- .../understand-provider-validation.mdx | 5 +++-- docs/inference/use-shared-gateway-routes.mdx | 2 +- docs/manage-sandboxes/workspace-files.mdx | 2 +- docs/reference/architecture.mdx | 8 ++++---- docs/reference/commands.mdx | 18 +++++++++--------- docs/reference/enterprise-readiness.mdx | 4 ++-- docs/reference/network-policies.mdx | 6 +++--- docs/reference/pi-support.mdx | 2 +- docs/security/best-practices.mdx | 8 ++++---- 17 files changed, 38 insertions(+), 37 deletions(-) diff --git a/docs/about/ecosystem-deepagents.mdx b/docs/about/ecosystem-deepagents.mdx index 7117de7b3e9..f88354e4b3c 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, fixed hosted providers, and new local selections use native endpoints through attached providers. Custom endpoints and existing legacy routes use `inference.local`. | +| 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, fixed hosted providers, and new local selections use native endpoints through attached providers. Other custom endpoints and existing legacy routes use `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 eb2e0464cfd..2b22d948a81 100644 --- a/docs/about/how-it-works.mdx +++ b/docs/about/how-it-works.mdx @@ -212,7 +212,7 @@ Refer to [Recover and Rebuild Sandboxes](../manage-sandboxes/operate-sandboxes/r New NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider selections use sandbox-attached OpenShell providers. The agent calls the selected provider API hostname, and OpenShell permits only the approved destination and request paths. -New OpenClaw and Deep Agents Code local selections call host-local endpoints through sandbox-attached OpenShell providers. Existing local sandboxes can keep using `inference.local` while OpenShell 0.0.116 is pinned; resume or rebuild stops before changing them and requires backup and fresh re-onboarding. User-supplied endpoints, Hermes local selections, and Model Router continue to use the shared route. +New OpenClaw and Deep Agents Code local selections, including qualified host-local `compatible-endpoint` routes, call host-local endpoints through sandbox-attached OpenShell providers. Existing local sandboxes can keep using `inference.local` while OpenShell 0.0.116 is pinned; resume or rebuild stops before changing them and requires backup and fresh re-onboarding. Other user-supplied endpoints, 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 820263ea202..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, fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use sandbox-attached providers. Custom endpoints, Hermes local selections, and existing legacy routes use `inference.local` on the pinned OpenShell release. 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 744c4b9464c..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, supported fixed hosted providers, and new local selections use native endpoints through sandbox-attached OpenShell providers. Custom endpoints and existing legacy routes retain the OpenShell-managed `inference.local` route on the pinned release. +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 b0bc1ca29e1..c7a2afbac8b 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 endpoints and existing legacy local routes retain `https://inference.local/v1` on the pinned OpenShell release; 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. +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. Other custom endpoints and existing legacy local routes retain `https://inference.local/v1` on the pinned OpenShell release; 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 a7d7e4c526e..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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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`. +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 bc29044825d..68f4559660f 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -380,7 +380,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 endpoints and existing legacy local routes retain `inference.local` on the pinned OpenShell release. New OpenClaw local selections use sandbox-attached providers. + 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/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index 525c81ac267..010b6a2e382 100644 --- a/docs/inference/how-inference-routing-works.mdx +++ b/docs/inference/how-inference-routing-works.mdx @@ -36,9 +36,9 @@ 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. -New OpenClaw and Deep Agents Code local selections use sandbox-attached OpenShell providers to reach qualified host-local endpoints. 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. User-supplied endpoints, Hermes local selections, and Model Router still use the shared route in this release. +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 custom, Hermes local, and Model Router shared routes. This release does not migrate any of them automatically. +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 Shared-route agent -> inference.local -> OpenShell gateway -> selected provider and model @@ -62,7 +62,7 @@ When a rebuild reuses an automatically bridged compatible-endpoint route without ## Deep Agents Configuration -For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with 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 custom selections use `https://inference.local/v1` while running on OpenShell 0.0.116. +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/understand-provider-validation.mdx b/docs/inference/understand-provider-validation.mdx index 8ed64dc22a7..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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. +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 4cb88ec1a5f..d0a311e60e4 100644 --- a/docs/inference/use-shared-gateway-routes.mdx +++ b/docs/inference/use-shared-gateway-routes.mdx @@ -10,7 +10,7 @@ content: type: "how_to" --- -These rules apply to providers that still use the shared route, including user-supplied compatible endpoints, 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. +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. diff --git a/docs/manage-sandboxes/workspace-files.mdx b/docs/manage-sandboxes/workspace-files.mdx index bc9e40eeb3a..22ea5a409fb 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. NVIDIA Endpoints, fixed hosted providers, and new local selections use attached native endpoints; custom endpoints and existing legacy routes use `inference.local` on the pinned release. | +| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path. NVIDIA Endpoints, fixed hosted providers, and new local selections use attached native endpoints; other custom endpoints and existing legacy routes use `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 8eae1477df7..02fa86a7471 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -29,7 +29,7 @@ graph LR USER(["👤 User"]):::user subgraph EXTERNAL["External Services"] - SHARED_INFERENCE["Shared-route inference providers
Custom · legacy local
Hermes local · Model Router
"]:::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 @@ -171,7 +171,7 @@ graph TB end end - SHARED_INFER["Shared-route inference provider
Custom · legacy local
Hermes local · Model Router
"]:::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 @@ -358,13 +358,13 @@ Inside the sandbox: ## Inference Routing Agent inference follows one of two OpenShell-managed paths. -Custom endpoints, Hermes local selections, and existing legacy local routes use `inference.local` through the pinned OpenShell 0.0.116 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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections 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 a4e3a1a37d2..1eb8688b0d4 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1194,7 +1194,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 and custom selections use `inference.local`; new OpenClaw local selections use attached native endpoints, while Hermes local routing remains shared. + 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`. @@ -1204,7 +1204,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 and custom selections use `inference.local`; new Deep Agents Code local selections use attached native endpoints. + 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. @@ -1706,7 +1706,7 @@ $$nemoclaw my-assistant start When that deadline expires, `start` keeps the existing container, exits non-zero, and prints the `NEMOCLAW_CONNECT_TIMEOUT` value to use on the next run. -After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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. +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` @@ -1754,7 +1754,7 @@ $$nemoclaw my-assistant status --json $$nemoclaw sandbox status my-assistant --json ``` -The command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. NVIDIA Endpoints, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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: +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 | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -2108,7 +2108,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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. +`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. @@ -3298,7 +3298,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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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. +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. @@ -3602,7 +3602,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 retain their shared OpenShell route; new OpenClaw local selections use an attached native provider. 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. @@ -3615,7 +3615,7 @@ Switch the active inference provider or model for a NemoClaw-managed Hermes sand 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. @@ -3638,7 +3638,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 retain the shared-route workflow; new OpenClaw local selections use an attached native provider. 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. +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 de4c7d91a5c..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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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). | +| 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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. +- 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 7c70db3e308..cdf9ecbc0d3 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -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. 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, custom endpoints, Hermes local selections, and Model Router still use the shared `inference.local` route on the pinned release. +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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Custom selections and existing legacy shared routes use `inference.local`. 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 55a0f0a4a80..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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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. +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/security/best-practices.mdx b/docs/security/best-practices.mdx index 9cd39658c8f..4e1cf95b8d5 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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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. | +| 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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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. +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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. Custom endpoints, Hermes local selections, and existing legacy shared routes use `inference.local` on the pinned OpenShell 0.0.116 release. +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, supported fixed hosted providers, and new OpenClaw or Deep Agents Code local selections use native endpoints through sandbox-attached OpenShell providers. 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. | +| 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. | From 3893f3ab914c3580c2e05db7700f0da2e1763903 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 08:50:44 -0700 Subject: [PATCH 24/45] docs(inference): clarify attached local routes in setup guides Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/choose-local-inference-server.mdx | 8 +++++--- docs/inference/set-up-openai-compatible-endpoint.mdx | 10 ++++++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/inference/choose-local-inference-server.mdx b/docs/inference/choose-local-inference-server.mdx index bf94e8278ee..12ff0c6ec7a 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 local inference. +Hermes 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/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. From 56cb75a4d6457f6a3f64cd924a44ba3c6d45f8c7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 08:53:47 -0700 Subject: [PATCH 25/45] docs(inference): name shared local route exceptions Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/choose-local-inference-server.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/inference/choose-local-inference-server.mdx b/docs/inference/choose-local-inference-server.mdx index 12ff0c6ec7a..014427977c1 100644 --- a/docs/inference/choose-local-inference-server.mdx +++ b/docs/inference/choose-local-inference-server.mdx @@ -12,8 +12,8 @@ content: NemoClaw supports operator-run servers and NemoClaw-managed runtime profiles for local inference. Choose the option that matches your host, model, and operational needs. -New OpenClaw and Deep Agents Code sandboxes use attached OpenShell providers for local inference. -Hermes and existing shared-route sandboxes use `inference.local` while OpenShell 0.0.116 remains pinned. +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. From 873932b3569a174a507208eaf374307ae7ebcb40 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 10:46:08 -0700 Subject: [PATCH 26/45] test(e2e): correct native GPU route and fresh-home setup --- test/e2e/live/gpu-e2e.test.ts | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/test/e2e/live/gpu-e2e.test.ts b/test/e2e/live/gpu-e2e.test.ts index cfad0e24ba7..a49c64ad7d8 100644 --- a/test/e2e/live/gpu-e2e.test.ts +++ b/test/e2e/live/gpu-e2e.test.ts @@ -191,13 +191,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"); @@ -257,6 +250,7 @@ test( ), { 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 +426,8 @@ test( credentialBoundary: "The existing proxy owner authenticates observation; exported inference providers omit credentials and internal endpoints.", }); + // Pre-clean may start a gateway; do it before creating the fresh private HOME. + await cleanupGpu(host, lifecycle, sandbox, env()); // The SDK rejects gateway state below a world-writable ancestor such as /tmp. const directory = createGpuPrivateHome(os.homedir()); const exportEnv = env({ @@ -454,7 +450,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", From a84cc74e499d91676bf21086f682cabf6e3ed492 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 12:50:05 -0700 Subject: [PATCH 27/45] fix(inference): verify managed local application routes Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../verify-deployment-inference-route.test.ts | 45 +++++++++++++++ src/lib/verify-deployment.ts | 6 ++ test/e2e/live/gpu-double-onboard.test.ts | 3 +- test/e2e/live/gpu-e2e-helpers.ts | 20 ++++--- test/e2e/live/gpu-e2e.test.ts | 3 +- test/e2e/support/gpu-e2e-helpers.test.ts | 56 +++++++++++++++++++ 6 files changed, 124 insertions(+), 9 deletions(-) diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index ad049ba1e84..761319d72a8 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -146,6 +146,51 @@ describe("verifyDeployment inference route model-catalog validation", () => { 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("rejects a native local attachment for a different selected endpoint in both probes", async () => { const context = onboardInferenceVerificationContext( "my-sandbox", diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index de453d0a7a6..3e33d04ccfe 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -46,6 +46,7 @@ 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"; export { shouldDiagnoseCustomOpenClawRuntime } from "./onboard/custom-openclaw-runtime-diagnosis"; @@ -414,6 +415,11 @@ function matchesNativeLocalVerificationRoute( ) 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; } diff --git a/test/e2e/live/gpu-double-onboard.test.ts b/test/e2e/live/gpu-double-onboard.test.ts index f59ba6fb8de..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 http://host.openshell.internal:${PROXY_PORT}/v1/chat/completions -H 'Authorization: Bearer openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN' -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, diff --git a/test/e2e/live/gpu-e2e-helpers.ts b/test/e2e/live/gpu-e2e-helpers.ts index 3f41aea37cf..3feda02f2a5 100644 --- a/test/e2e/live/gpu-e2e-helpers.ts +++ b/test/e2e/live/gpu-e2e-helpers.ts @@ -2,8 +2,10 @@ // 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"; @@ -249,13 +251,17 @@ export async function cleanupGpu( 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 a49c64ad7d8..5f09c0cdd56 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"; @@ -236,7 +237,7 @@ test( const chat = await sandbox.execShell( SANDBOX_NAME, trustedSandboxShellScript( - `curl -sS --max-time 120 http://host.openshell.internal:${PROXY_PORT}/v1/chat/completions -H 'Authorization: Bearer openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN' -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" }], diff --git a/test/e2e/support/gpu-e2e-helpers.test.ts b/test/e2e/support/gpu-e2e-helpers.test.ts index 8b33b96e4cc..ecf429a00b0 100644 --- a/test/e2e/support/gpu-e2e-helpers.test.ts +++ b/test/e2e/support/gpu-e2e-helpers.test.ts @@ -26,6 +26,7 @@ import { ollamaProxyTokenFile, openClawModelConfigProjectionScript, REPO_ROOT, + SANDBOX_NAME, startAttachedOllama, trackGpuGatewayCleanup, waitForAttachedOllama, @@ -700,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[] = []; From aff7f577760c7f8b25a53a464f73afdc404e4f52 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:24:38 -0700 Subject: [PATCH 28/45] fix(inference): report native local provider attachments --- docs/about/ecosystem-deepagents.mdx | 2 +- docs/about/how-it-works.mdx | 6 +- .../quickstart-langchain-deepagents-code.mdx | 2 +- docs/manage-sandboxes/workspace-files.mdx | 2 +- src/lib/actions/inference-get.test.ts | 138 ++++++++++++++++++ src/lib/actions/inference-get.ts | 64 +++++++- 6 files changed, 209 insertions(+), 5 deletions(-) diff --git a/docs/about/ecosystem-deepagents.mdx b/docs/about/ecosystem-deepagents.mdx index f88354e4b3c..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, fixed hosted providers, and new local selections use native endpoints through attached providers. Other custom endpoints and existing legacy routes use `inference.local`. | +| 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 2b22d948a81..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. -New OpenClaw and Deep Agents Code local selections, including qualified host-local `compatible-endpoint` routes, call host-local endpoints through sandbox-attached OpenShell providers. Existing local sandboxes can keep using `inference.local` while OpenShell 0.0.116 is pinned; resume or rebuild stops before changing them and requires backup and fresh re-onboarding. Other user-supplied endpoints, Hermes local selections, and Model Router continue to use the shared route. +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/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index c7a2afbac8b..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. Other custom endpoints and existing legacy local routes retain `https://inference.local/v1` on the pinned OpenShell release; 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. +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/manage-sandboxes/workspace-files.mdx b/docs/manage-sandboxes/workspace-files.mdx index 22ea5a409fb..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. NVIDIA Endpoints, fixed hosted providers, and new local selections use attached native endpoints; other custom endpoints and existing legacy routes use `inference.local` on the pinned release. | +| `/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/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); From 9cf9a608847eabb7470f0ee21eee7d28471f1b46 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:59:29 -0700 Subject: [PATCH 29/45] test(ci): rebalance CLI coverage shard guard --- test/repository/cli-coverage-sequencer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/repository/cli-coverage-sequencer.test.ts b/test/repository/cli-coverage-sequencer.test.ts index 5025d4826ab..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.058); + expect(Math.max(...weights)).toBeLessThanOrEqual(averageWeight * 1.059); }); it("balances the serialized integration lane across the twelve CI shards (#6237)", () => { From 9cd05c550951bebf5d0aedec0d84f3a960e0fe5a Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:04:24 -0700 Subject: [PATCH 30/45] test(e2e): accept Hermes messaging refusal with additional findings Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/fixtures/hermes-config-export-live.ts | 6 +----- test/e2e/support/hermes-config-export-live.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index 0e3dcb2e3f7..58e9fdc7c51 100644 --- a/test/e2e/fixtures/hermes-config-export-live.ts +++ b/test/e2e/fixtures/hermes-config-export-live.ts @@ -355,11 +355,7 @@ export async function verifyHermesConfigExportLive( const refusalDiagnosticMatches = [nemoclawDiagnostics, nemohermesDiagnostics].every( (diagnostic) => { if (!expectsMessagingRefusal) return diagnostic === expectedDiagnostic; - const lines = diagnostic.split("\n"); - return ( - lines[0] === "Config export failed (unsupported)." && - expectedRefusals.every((refusal) => lines.includes(refusal)) - ); + return /\bmessaging\b/i.test(diagnostic); }, ); const refusalCategory = refusalDiagnosticMatches ? "unsupported" : null; diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 9941407dd28..8a817cc6932 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,7 @@ describe("Hermes config export live evidence", () => { }, ); - it("accepts messaging refusal alongside other unsupported export findings", async () => { + it("accepts messaging refusal alongside other export findings", async () => { mocks.load.mockReturnValue({ sandboxes: { hermes: { @@ -468,7 +468,7 @@ describe("Hermes config export live evidence", () => { exitCode: 2, stdout: "", stderr: [ - "Config export failed (unsupported).", + "Config export failed (unsupported, policy-not-representable).", "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.", From f6089154b76f54489ea3e89ca9830b3f947d1b97 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:30:28 -0700 Subject: [PATCH 31/45] test(e2e): verify sibling native route and correct platform guidance --- ci/e2e-assertion-budget.json | 14 ++++----- ci/e2e-assertion-growth-exceptions.json | 4 +-- ci/platform-matrix.json | 4 +-- docs/reference/platform-support.mdx | 4 +-- test/e2e/live/double-onboard.test.ts | 38 ++++++++++++++++++++++++- 5 files changed, 50 insertions(+), 14 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index d538e736de5..abfe89a3250 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 186, "direct": { - "expectCalls": 1256, - "matcherAssertions": 1235, + "expectCalls": 1258, + "matcherAssertions": 1237, "nodeAssertions": 104, "namedAssertionHelpers": 415, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 177, - "assertionPoints": 1981, + "assertionPoints": 1983, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1679, - "matcherAssertions": 1653, + "expectCalls": 1681, + "matcherAssertions": 1655, "nodeAssertions": 127, "namedAssertionHelpers": 659, "failCalls": 1, "throwGuards": 526, "objectFieldAssertions": 254, - "assertionPoints": 3220, + "assertionPoints": 3222, "generatedProbeBlocks": 209, "generatedProbeConditions": 721 }, @@ -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": [43,48,43,48,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], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 6ecc100e006..26daaddd78c 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #12977 moves native-local agent and sibling-policy coverage into existing live targets without increasing total direct expectations. It raises the double-onboard per-file budget by one while retiring the curl-only inference-routing case. Exact maintainer approval for the current main-to-head budget change: https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6104551185. This candidate entry supports local validation; independent CI verifies the PR-specific approval on GitHub. Remove after #12977 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 moves native-local agent and sibling-policy coverage into existing live targets and now adds an authenticated sibling-B POST with request-ledger proof to double-onboard. The prior exact approval at https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6104551185 covers only the earlier budget transition. This new candidate digest supports local validation; independent CI still requires a fresh exact maintainer approval on the PR. Remove after #12977 merges.", "schemaVersion": 1, "exceptions": [ { @@ -37,7 +37,7 @@ }, { "pullRequest": 12977, - "changeSha256": "3f500dd6d4f5c57029d448a5c5fd68acba5f35dc95d8859371649abcdd0ba4a4" + "changeSha256": "5e52540eb867a61e31d6d41dca24159af58225f9de14d7a33db9bac343d03ffa" }, { "pullRequest": 13055, 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/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/test/e2e/live/double-onboard.test.ts b/test/e2e/live/double-onboard.test.ts index 03d344cd113..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"; @@ -270,7 +271,10 @@ test( "onboard sibling sandbox with isolated dashboard", ...(process.env.NEMOCLAW_AGENT === "hermes" ? [] - : ["verify sibling native endpoint remains isolated"]), + : [ + "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", @@ -533,6 +537,38 @@ test( : 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, From 706ddd22a67710e812e00f7688f8b5ce43bbb9b3 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:20:07 -0700 Subject: [PATCH 32/45] test(rebuild): cover legacy local route preflight Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-flow-lifecycle.test.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts index 298aa0f5116..7e5f3da0b28 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")); From 6170636c442581a98dfd41ab6199ee7c96669f87 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:15:49 -0700 Subject: [PATCH 33/45] test: stop managed gateway before Ollama export E2E --- test/e2e/fixtures/phases/lifecycle.ts | 5 +++++ test/e2e/live/gpu-e2e.test.ts | 10 ++++++++++ test/e2e/support/lifecycle-user-service.test.ts | 1 + 3 files changed, 16 insertions(+) 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/gpu-e2e.test.ts b/test/e2e/live/gpu-e2e.test.ts index 5f09c0cdd56..293cb47584b 100644 --- a/test/e2e/live/gpu-e2e.test.ts +++ b/test/e2e/live/gpu-e2e.test.ts @@ -427,8 +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({ 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`, From 68edfcbf46debaf2458e8bd83081b8ddf249a327 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:21:46 -0700 Subject: [PATCH 34/45] fix(onboard): guard native local attachment on agent switch Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox-route-mutation-lock.test.ts | 27 ++++ src/lib/onboard/machine/handlers/sandbox.ts | 8 +- src/lib/onboard/sandbox-registration.test.ts | 124 ++++++++++++++++++ src/lib/onboard/sandbox-registration.ts | 78 +++++++++-- 4 files changed, 224 insertions(+), 13 deletions(-) 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 a167fbd5de1..3ac0fd2ebba 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 @@ -10,6 +10,7 @@ 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"; @@ -48,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 () => { @@ -218,6 +220,31 @@ describe("sandbox registration route transaction", () => { 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?.hostLocalInferenceRouteOnly).toBe(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.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 13cf1fde9fb..00fe4f857c4 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -1894,7 +1894,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, diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index 97f446943be..747a38a4650 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, @@ -131,6 +138,123 @@ describe("buildCreatedSandboxRegistryEntry", () => { 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 8f035078ea8..1484cb8f284 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -204,6 +204,29 @@ export function sandboxCreateInferenceSelection( return normalizeInferenceSelection(input); } +function nativeLocalAttachmentMatchesSelection( + attachment: NonNullable, + selection: { + agentName: string; + sandboxName: string; + gatewayName: string; + provider: string | null | undefined; + endpointUrl: string | null; + }, +): boolean { + return ( + usesNativeLocalInferenceForAgent( + selection.agentName, + selection.provider, + selection.endpointUrl, + ) && + attachment.sandboxName === selection.sandboxName && + attachment.gatewayName === selection.gatewayName && + attachment.provider === selection.provider && + attachment.endpointUrl === selection.endpointUrl + ); +} + export function buildCreatedSandboxRegistryEntry( input: CreatedSandboxRegistryEntryInput, ): SandboxEntry { @@ -316,7 +339,16 @@ export function buildCreatedSandboxRegistryEntry( workload, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), - ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), + ...(nativeLocalProviderAttachment && + nativeLocalAttachmentMatchesSelection(nativeLocalProviderAttachment, { + agentName: requestedAgent, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + provider: input.inferenceSelection.provider, + endpointUrl: input.inferenceSelection.endpointUrl, + }) + ? { nativeLocalProviderAttachment } + : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(deferredN1xManagedVllmAccepted ? { deferredN1xManagedVllmAccepted: true as const } : {}), @@ -532,6 +564,7 @@ export function nativeLocalReservationStatus(input: { attachment.sandboxName === input.sandboxName && attachment.gatewayName === input.gatewayName && attachment.provider === input.provider && + attachment.endpointUrl === input.endpointUrl && input.entry.provider === input.provider && input.entry.model === input.model && input.entry.endpointUrl === input.endpointUrl && @@ -542,30 +575,51 @@ export function nativeLocalReservationStatus(input: { : "changed"; } -export function nativeInferenceCreateIntentFields( - provider: string | null | undefined, - entry: SandboxEntry | null, -): { +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 nativeLocalProviderAttachment = normalizeNativeLocalProviderAttachment( - entry?.nativeLocalProviderAttachment, - ); + 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, + }) + ? retainedAttachment + : undefined; const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - entry?.nativeNvidiaProviderAttachment, + input.entry?.nativeNvidiaProviderAttachment, ); const hostedAttachment = requireHostedProviderAttachment( - entry?.nativeHostedProviderAttachment, - provider, + input.entry?.nativeHostedProviderAttachment, + input.provider, ); return { inferenceProvider: nativeLocalProviderAttachment?.providerName ?? hostedAttachment?.providerName ?? - nativeInferenceProviderForSandbox(provider), + nativeInferenceProviderForSandbox(input.provider), ...(nativeLocalProviderAttachment ? { nativeLocalProviderAttachment } : {}), nativeHostedProviderAttachment: hostedAttachment, ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), From 42d6d1ff3b26eeddb2e3885f597e41e92a68e71a Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 15:18:23 -0700 Subject: [PATCH 35/45] fix(onboard): verify published native local route Signed-off-by: Prekshi Vyas --- src/lib/onboard/sandbox-registration.test.ts | 71 +++++++++++++++++++ src/lib/onboard/sandbox-registration.ts | 22 +++++- .../state/registry/host-local-inference.ts | 20 ++++++ .../verify-deployment-inference-route.test.ts | 39 ++++++++++ src/lib/verify-deployment.ts | 35 +++++++-- 5 files changed, 179 insertions(+), 8 deletions(-) diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index 747a38a4650..55bbdc78468 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -100,6 +100,77 @@ 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"); + }); + 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( diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index 1484cb8f284..5938df8f45e 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -32,6 +32,7 @@ import { withCurrentPortableHostFenceTry } from "../state/portable-uninstall-ret import { cloneSandboxHostLocalInferenceProvenance, cloneSandboxHostLocalInferenceReceipt, + nativeLocalAttachmentMatchesHostLocalReceipt, requireSandboxHostLocalInferenceProvenance, } from "../state/registry/host-local-inference"; import { cloneSandboxHostMounts } from "../state/registry/host-mount"; @@ -212,8 +213,16 @@ function nativeLocalAttachmentMatchesSelection( 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, @@ -223,7 +232,7 @@ function nativeLocalAttachmentMatchesSelection( attachment.sandboxName === selection.sandboxName && attachment.gatewayName === selection.gatewayName && attachment.provider === selection.provider && - attachment.endpointUrl === selection.endpointUrl + endpointMatches ); } @@ -346,6 +355,7 @@ export function buildCreatedSandboxRegistryEntry( gatewayName: input.gatewayName, provider: input.inferenceSelection.provider, endpointUrl: input.inferenceSelection.endpointUrl, + hostLocalInferenceReceipt, }) ? { nativeLocalProviderAttachment } : {}), @@ -564,7 +574,14 @@ export function nativeLocalReservationStatus(input: { attachment.sandboxName === input.sandboxName && attachment.gatewayName === input.gatewayName && attachment.provider === input.provider && - attachment.endpointUrl === input.endpointUrl && + nativeLocalAttachmentMatchesSelection(attachment, { + agentName: input.agentName, + sandboxName: input.sandboxName, + gatewayName: input.gatewayName, + provider: input.provider, + endpointUrl: input.endpointUrl, + hostLocalInferenceReceipt: input.entry.hostLocalInferenceReceipt, + }) && input.entry.provider === input.provider && input.entry.model === input.model && input.entry.endpointUrl === input.endpointUrl && @@ -605,6 +622,7 @@ export function nativeInferenceCreateIntentFields(input: { gatewayName: input.gatewayName, provider: input.provider, endpointUrl: input.endpointUrl, + hostLocalInferenceReceipt: input.entry?.hostLocalInferenceReceipt, }) ? retainedAttachment : undefined; diff --git a/src/lib/state/registry/host-local-inference.ts b/src/lib/state/registry/host-local-inference.ts index 529c4dfb510..013859928fc 100644 --- a/src/lib/state/registry/host-local-inference.ts +++ b/src/lib/state/registry/host-local-inference.ts @@ -8,11 +8,31 @@ 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; + } +} + 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/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index 761319d72a8..e8b6c3d0c3a 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -2,6 +2,7 @@ // 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 { nativeLocalIdentity, @@ -191,6 +192,44 @@ describe("verifyDeployment inference route model-catalog validation", () => { }, ); + 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", diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 3e33d04ccfe..ad81cdceb0d 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -47,6 +47,7 @@ import { 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"; @@ -977,10 +978,15 @@ export function onboardInferenceVerificationContext( flow: Pick & { endpointUrl?: string | null; }, - attachment?: Pick< - InferenceRouteContext, - "nativeLocalProviderAttachment" | "nativeHostedProviderAttachment" - > | null, + attachment?: + | (Pick< + InferenceRouteContext, + "nativeLocalProviderAttachment" | "nativeHostedProviderAttachment" + > & + Partial> & { + hostLocalInferenceReceipt?: string | null; + }) + | null, ): { route: InferenceRouteContext; invocation: InferenceInvocationContext } { const nativeLocalExpected = usesNativeLocalInferenceForAgent( agentName, @@ -989,10 +995,27 @@ export function onboardInferenceVerificationContext( ); 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: flow.endpointUrl ?? null, + endpointUrl, gatewayName, nativeLocalExpected, nativeLocalProviderAttachment, @@ -1004,7 +1027,7 @@ export function onboardInferenceVerificationContext( agentName, model: flow.model, provider: flow.provider, - endpointUrl: flow.endpointUrl ?? null, + endpointUrl, preferredInferenceApi: flow.preferredInferenceApi, nativeLocalExpected, nativeLocalProviderAttachment, From ec0bb6cca99275d64f65ac21bbcb1926f0e5b2e9 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 17:04:51 -0700 Subject: [PATCH 36/45] fix(onboard): reconcile managed local reservation route Signed-off-by: Prekshi Vyas --- src/lib/onboard/machine/handlers/sandbox.ts | 6 ++- src/lib/onboard/sandbox-registration.test.ts | 22 ++++++++ src/lib/onboard/sandbox-registration.ts | 54 ++++++++++++------- .../state/registry/host-local-inference.ts | 16 ++++++ 4 files changed, 77 insertions(+), 21 deletions(-) diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index aa4fcdf04ee..b05d44b7a9c 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -1248,6 +1248,7 @@ class SandboxStateFlow< 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, @@ -1259,10 +1260,13 @@ class SandboxStateFlow< 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. Retry onboarding.`, + ` Error: native local inference reservation for sandbox '${sandboxName}' changed while onboarding was in progress (${mismatchFields.join(", ")}). Retry onboarding.`, ); } return nativeLocalReservation === "exact"; diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index 55bbdc78468..3cffc315c97 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -169,6 +169,28 @@ describe("buildCreatedSandboxRegistryEntry", () => { 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)", () => { diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index 5938df8f45e..caab2777559 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -33,6 +33,7 @@ import { cloneSandboxHostLocalInferenceProvenance, cloneSandboxHostLocalInferenceReceipt, nativeLocalAttachmentMatchesHostLocalReceipt, + nativeLocalHostSelectionMatchesHostLocalReceipt, requireSandboxHostLocalInferenceProvenance, } from "../state/registry/host-local-inference"; import { cloneSandboxHostMounts } from "../state/registry/host-mount"; @@ -563,6 +564,7 @@ export function nativeLocalReservationStatus(input: { 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"; @@ -570,26 +572,38 @@ export function nativeLocalReservationStatus(input: { const attachment = normalizeNativeLocalProviderAttachment( input.entry.nativeLocalProviderAttachment, ); - return attachment && - attachment.sandboxName === input.sandboxName && - attachment.gatewayName === input.gatewayName && - attachment.provider === input.provider && - nativeLocalAttachmentMatchesSelection(attachment, { - agentName: input.agentName, - sandboxName: input.sandboxName, - gatewayName: input.gatewayName, - provider: input.provider, - endpointUrl: input.endpointUrl, - hostLocalInferenceReceipt: input.entry.hostLocalInferenceReceipt, - }) && - input.entry.provider === input.provider && - input.entry.model === input.model && - input.entry.endpointUrl === input.endpointUrl && - (input.entry.endpointSource ?? null) === input.endpointSource && - (input.entry.credentialEnv ?? null) === input.credentialEnv && - (input.entry.preferredInferenceApi ?? null) === input.preferredInferenceApi - ? "exact" - : "changed"; + 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: { diff --git a/src/lib/state/registry/host-local-inference.ts b/src/lib/state/registry/host-local-inference.ts index 013859928fc..d2bdd6fe3ac 100644 --- a/src/lib/state/registry/host-local-inference.ts +++ b/src/lib/state/registry/host-local-inference.ts @@ -33,6 +33,22 @@ export function nativeLocalAttachmentMatchesHostLocalReceipt( } } +/** 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; From 22eb964f1e103b2af7e53f34afeea31ffdcb3084 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:29:01 -0700 Subject: [PATCH 37/45] fix(inference): address native local review findings Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/inference/custom-endpoint-security.mdx | 7 +- docs/inference/model-capability-audit.mdx | 6 +- docs/inference/set-up-llama-cpp.mdx | 8 +- .../inference-set-native-local.test.ts | 43 +++++++ ...inference-set-provider-diagnostics.test.ts | 61 +++++++++ .../inference-set-provider-diagnostics.ts | 9 +- src/lib/actions/inference-set/native.ts | 8 +- .../health-native-local.test.ts | 73 +++++++++++ .../sandbox/launch-readiness/health.ts | 3 +- ...le-endpoint-smoke-native-selection.test.ts | 88 +++++++++++++ src/lib/onboard/compatible-endpoint-smoke.ts | 2 + .../e2e/fixtures/hermes-config-export-live.ts | 7 +- .../support/hermes-config-export-live.test.ts | 119 +++++++++++++----- 13 files changed, 390 insertions(+), 44 deletions(-) create mode 100644 src/lib/actions/sandbox/launch-readiness/health-native-local.test.ts create mode 100644 src/lib/onboard/compatible-endpoint-smoke-native-selection.test.ts 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/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/src/lib/actions/inference-set-native-local.test.ts b/src/lib/actions/inference-set-native-local.test.ts index 6abf9c28d62..f6f8ee96765 100644 --- a/src/lib/actions/inference-set-native-local.test.ts +++ b/src/lib/actions/inference-set-native-local.test.ts @@ -1,6 +1,7 @@ // 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"; @@ -279,3 +280,45 @@ describe.each([ ); }); }); + +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-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 f4b1b37bc94..486e038208d 100644 --- a/src/lib/actions/inference-set-provider-diagnostics.ts +++ b/src/lib/actions/inference-set-provider-diagnostics.ts @@ -103,7 +103,14 @@ export async function rejectInferenceSelectionProbe(input: { `Native local inference verification failed for '${input.sandboxName}': ${input.detail}. No new inference selection was committed.`, ); } - const restoreFailure = await input.restorePreviousSelection(); + 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}. ` + diff --git a/src/lib/actions/inference-set/native.ts b/src/lib/actions/inference-set/native.ts index 8cbe23a5e60..8dcb8a37208 100644 --- a/src/lib/actions/inference-set/native.ts +++ b/src/lib/actions/inference-set/native.ts @@ -5,7 +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 } from "../../inference/native-local/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"; @@ -290,7 +293,8 @@ export function nativeSelectionConfigCredentials( typeof existingApiKey === "string" && existingApiKey && existingApiKey !== NVIDIA_INFERENCE_PLACEHOLDER && - existingApiKey !== "openshell:resolve:env:NEMOCLAW_LOCAL_INFERENCE_TOKEN" + 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/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 50a1b2e6e89..7506026c8dd 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -233,7 +233,8 @@ export async function requireNativeInferenceHealth(input: { const expected = normalizeNativeLocalProviderAttachment( input.entry.nativeLocalProviderAttachment, ); - if (!expected || !input.entry.model) throw new LaunchReadinessEvidenceError(); + if (!expected || !input.entry.model || input.entry.provider !== expected.provider) + throw new LaunchReadinessEvidenceError(); await (input.deps.verifyNativeLocalAttachment ?? verifyNativeLocalStatusAttachment)({ sandboxName: input.sandboxName, gatewayName: input.gatewayName, 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.ts b/src/lib/onboard/compatible-endpoint-smoke.ts index 94c24d6e347..2ae851bfdf5 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -132,6 +132,8 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { 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 && diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index 58e9fdc7c51..bc075e3e020 100644 --- a/test/e2e/fixtures/hermes-config-export-live.ts +++ b/test/e2e/fixtures/hermes-config-export-live.ts @@ -355,7 +355,12 @@ export async function verifyHermesConfigExportLive( const refusalDiagnosticMatches = [nemoclawDiagnostics, nemohermesDiagnostics].every( (diagnostic) => { if (!expectsMessagingRefusal) return diagnostic === expectedDiagnostic; - return /\bmessaging\b/i.test(diagnostic); + const [header, ...findings] = diagnostic.split("\n"); + const categories = /^Config export failed \(([^)]+)\)\.$/u.exec(header ?? "")?.[1]; + return ( + categories?.split(", ").includes("unsupported") === true && + expectedRefusals.every((refusal) => findings.includes(refusal)) + ); }, ); const refusalCategory = refusalDiagnosticMatches ? "unsupported" : null; diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 8a817cc6932..ff5b807c65d 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -452,38 +452,97 @@ describe("Hermes config export live evidence", () => { }, ); - it("accepts messaging refusal alongside other export findings", async () => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - gatewayName: "nemoclaw", - messaging: { schemaVersion: 1, plan: { channels: [] } }, - workload: { kind: "managed-image", reference: IMAGE_REF }, + it.each(["unsupported, policy-not-representable", "policy-not-representable, unsupported"])( + "accepts messaging refusal alongside categories %s", + async (categories) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + gatewayName: "nemoclaw", + messaging: { schemaVersion: 1, plan: { channels: [] } }, + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, }, - }, - }); - mocks.command.mockResolvedValue({ - exitCode: 2, - stdout: "", - stderr: [ - "Config export failed (unsupported, policy-not-representable).", - "V1 export does not support messaging.", - "The sandbox provider attachments do not match its supported configuration.", - "The managed startup profile is not the canonical profile supported by v1 export.", - ].join("\n"), - }); + }); + mocks.command.mockResolvedValue({ + exitCode: 2, + stdout: "", + stderr: [ + `Config export failed (${categories}).`, + "V1 export does not support messaging.", + "The sandbox provider attachments do not match its supported configuration.", + "The managed startup profile is not the canonical profile supported by v1 export.", + ].join("\n"), + }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); - expect(mocks.writeJson).toHaveBeenCalledWith( - "hermes-config-export-live-evidence.json", - expect.objectContaining({ - refusalCategory: "unsupported", - refusalDiagnosticMatches: true, - }), - ); - }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); + expect(mocks.writeJson).toHaveBeenCalledWith( + "hermes-config-export-live-evidence.json", + expect.objectContaining({ + refusalCategory: "unsupported", + refusalDiagnosticMatches: true, + }), + ); + }, + ); + + it.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: "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({ From 5c46aa7c86540e785fda521ca86d1fb335d32055 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:15:36 -0700 Subject: [PATCH 38/45] test(e2e): constrain expected Hermes export refusals --- .../e2e/fixtures/hermes-config-export-live.ts | 26 +++- .../support/hermes-config-export-live.test.ts | 116 +++++++++++++----- 2 files changed, 106 insertions(+), 36 deletions(-) diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index bc075e3e020..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] @@ -356,10 +364,22 @@ export async function verifyHermesConfigExportLive( (diagnostic) => { if (!expectsMessagingRefusal) return diagnostic === expectedDiagnostic; const [header, ...findings] = diagnostic.split("\n"); - const categories = /^Config export failed \(([^)]+)\)\.$/u.exec(header ?? "")?.[1]; + const categories = /^Config export failed \(([^)]+)\)\.$/u + .exec(header ?? "")?.[1] + ?.split(", "); + const expectedCategories = [ + "unsupported", + ...(findings.includes(POLICY_REFUSAL) ? ["policy-not-representable"] : []), + ]; return ( - categories?.split(", ").includes("unsupported") === true && - expectedRefusals.every((refusal) => findings.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/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index ff5b807c65d..e2b381383ee 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -452,41 +452,47 @@ describe("Hermes config export live evidence", () => { }, ); - it.each(["unsupported, policy-not-representable", "policy-not-representable, unsupported"])( - "accepts messaging refusal alongside categories %s", - async (categories) => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - gatewayName: "nemoclaw", - messaging: { schemaVersion: 1, plan: { channels: [] } }, - workload: { kind: "managed-image", reference: IMAGE_REF }, - }, + it.each([ + "unsupported", + "unsupported, policy-not-representable", + "policy-not-representable, unsupported", + ])("accepts messaging refusal alongside categories %s", async (categories) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + gatewayName: "nemoclaw", + messaging: { schemaVersion: 1, plan: { channels: [] } }, + workload: { kind: "managed-image", reference: IMAGE_REF }, }, - }); - mocks.command.mockResolvedValue({ - exitCode: 2, - stdout: "", - stderr: [ - `Config export failed (${categories}).`, - "V1 export does not support messaging.", - "The sandbox provider attachments do not match its supported configuration.", - "The managed startup profile is not the canonical profile supported by v1 export.", - ].join("\n"), - }); + }, + }); + mocks.command.mockResolvedValue({ + exitCode: 2, + stdout: "", + stderr: [ + `Config export failed (${categories}).`, + "V1 export does not support messaging.", + "The sandbox provider attachments do not match its supported configuration.", + "The managed startup profile is not the canonical profile supported by v1 export.", + ...(categories.includes("policy-not-representable") + ? [ + "Verified effective policy is malformed, unknown, or cannot be represented losslessly.", + ] + : []), + ].join("\n"), + }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); - expect(mocks.writeJson).toHaveBeenCalledWith( - "hermes-config-export-live-evidence.json", - expect.objectContaining({ - refusalCategory: "unsupported", - refusalDiagnosticMatches: true, - }), - ); - }, - ); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); + expect(mocks.writeJson).toHaveBeenCalledWith( + "hermes-config-export-live-evidence.json", + expect.objectContaining({ + refusalCategory: "unsupported", + refusalDiagnosticMatches: true, + }), + ); + }); it.each([ { @@ -513,6 +519,50 @@ describe("Hermes config export live evidence", () => { 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", From b2b8bc3c7835bf4a1d482facd8f789294e325d8e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:23:30 -0700 Subject: [PATCH 39/45] test(inference): qualify credentialless dcode activation --- ci/e2e-assertion-budget.json | 8 +- ci/e2e-assertion-growth-exceptions.json | 4 +- docs/inference/set-up-vllm.mdx | 4 +- test/e2e/README.md | 2 +- .../managed-image-activation-e2e-helpers.ts | 145 ++++++++++++++---- .../live/managed-image-activation-e2e.test.ts | 5 +- ...naged-image-activation-diagnostics.test.ts | 129 +++++++++++++++- 7 files changed, 255 insertions(+), 42 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index a6a382a09c9..2c66d35507d 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -27,14 +27,14 @@ "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1682, - "matcherAssertions": 1656, + "expectCalls": 1683, + "matcherAssertions": 1657, "nodeAssertions": 127, "namedAssertionHelpers": 659, "failCalls": 1, "throwGuards": 526, "objectFieldAssertions": 254, - "assertionPoints": 3223, + "assertionPoints": 3224, "generatedProbeBlocks": 209, "generatedProbeConditions": 721 }, @@ -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 4e628b31a1a..82d31c084a9 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #12977 moves native-local agent and sibling-policy coverage into existing live targets and now adds an authenticated sibling-B POST with request-ledger proof to double-onboard. The prior exact approval at https://github.com/NVIDIA/NemoClaw/pull/12977#issuecomment-6104551185 covers only the earlier budget transition. This new candidate digest supports local validation; independent CI still requires a fresh exact maintainer approval on the PR. Remove after #12977 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": [ { @@ -37,7 +37,7 @@ }, { "pullRequest": 12977, - "changeSha256": "5e52540eb867a61e31d6d41dca24159af58225f9de14d7a33db9bac343d03ffa" + "changeSha256": "c0c7f7df24942dcb4d7c28d7fd02d65b4ee344d83782425f572521d77edc5ea1" }, { "pullRequest": 13051, 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/test/e2e/README.md b/test/e2e/README.md index 66e3a05a1e2..72346a4ef3a 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -2286,7 +2286,7 @@ The explicit `dgx-station-express` target runs the local Station Express install ### 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. 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. +`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. diff --git a/test/e2e/live/managed-image-activation-e2e-helpers.ts b/test/e2e/live/managed-image-activation-e2e-helpers.ts index e4a6d656110..118743e1477 100644 --- a/test/e2e/live/managed-image-activation-e2e-helpers.ts +++ b/test/e2e/live/managed-image-activation-e2e-helpers.ts @@ -41,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"; @@ -200,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, @@ -400,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, @@ -417,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: @@ -430,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[] { @@ -566,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( @@ -704,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"); @@ -713,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; } } @@ -727,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; } } @@ -741,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; } } @@ -874,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 ? "-credentialless" : ""}`; + 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, @@ -902,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( @@ -921,7 +966,7 @@ export async function qualifyAgent( .join("\n"), ), { - artifactName: `${agent}-write-durable-marker`, + artifactName: `${artifactPrefix}-write-durable-marker`, env, timeoutMs: 30_000, }, @@ -929,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, @@ -938,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, @@ -951,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); @@ -968,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, }, @@ -977,7 +1022,15 @@ 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, @@ -985,7 +1038,7 @@ export async function qualifyAgent( const attachments = await sandbox.openshell( ["sandbox", "provider", "list", "-g", GATEWAY, sandboxName], { - artifactName: `managed-activation-native-provider-attachment-${agent}`, + artifactName: `managed-activation-native-provider-attachment-${artifactPrefix}`, env, timeoutMs: 60_000, }, @@ -994,6 +1047,7 @@ export async function qualifyAgent( 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)}`, @@ -1002,7 +1056,7 @@ export async function qualifyAgent( enterCleanupPhase(progress, agent); await sandbox.cleanupSandbox(sandboxName, { - artifactName: `managed-activation-openshell-delete-${agent}`, + artifactName: `managed-activation-openshell-delete-${artifactPrefix}`, env, timeoutMs: 120_000, }); @@ -1029,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 }), ); @@ -1056,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, @@ -1132,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]; @@ -1227,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", ); 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/support/managed-image-activation-diagnostics.test.ts b/test/e2e/support/managed-image-activation-diagnostics.test.ts index 5831cc03b04..5dbfd8fc799 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"; @@ -30,6 +31,8 @@ import { externalImageActivationMatches, externalImageActivationOnboardArgs, managedActivationPostRestartAgentTurnScript, + managedActivationCommandEnv, + runManagedActivationAgentTurn, managedActivationOpenClawPluginScript, managedHermesBoundaryPoisonCommand, managedOpenClawSubagentCommand, @@ -190,6 +193,130 @@ 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-")); @@ -1022,7 +1149,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), From 89e8cf079d8d1b678e6866a56593027928b2c8a3 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 07:27:15 -0700 Subject: [PATCH 40/45] test(e2e): keep credentialless activation name within sandbox limit --- .../managed-image-activation-e2e-helpers.ts | 2 +- ...anaged-image-activation-diagnostics.test.ts | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/test/e2e/live/managed-image-activation-e2e-helpers.ts b/test/e2e/live/managed-image-activation-e2e-helpers.ts index 118743e1477..a8405d57270 100644 --- a/test/e2e/live/managed-image-activation-e2e-helpers.ts +++ b/test/e2e/live/managed-image-activation-e2e-helpers.ts @@ -912,7 +912,7 @@ export async function qualifyAgent( observeRequests?: () => readonly FakeOpenAiCompatibleRequest[], ): Promise { const { artifacts, cleanup, host, lifecycle, progress, sandbox } = fixtures; - const sandboxName = `${SANDBOX_NAMES[agent]}${credentialless ? "-credentialless" : ""}`; + 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}`, () => diff --git a/test/e2e/support/managed-image-activation-diagnostics.test.ts b/test/e2e/support/managed-image-activation-diagnostics.test.ts index 5dbfd8fc799..a3986cf4c6b 100644 --- a/test/e2e/support/managed-image-activation-diagnostics.test.ts +++ b/test/e2e/support/managed-image-activation-diagnostics.test.ts @@ -45,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), @@ -1080,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: "" }; @@ -1132,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( @@ -1161,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); From 2eed97777d55d27d87dc333f884b2c6e833b1591 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:53:24 -0700 Subject: [PATCH 41/45] fix: preserve shared routes for unattached local inference Honor explicit shared routing and retain local attachment selection in legacy configuration, initial route restoration and DCode drift checks. --- src/lib/inference/config.test.ts | 29 ++++++++++++++----- src/lib/inference/config.ts | 1 + .../dockerfile-patch-native-hosted.test.ts | 20 +++++++++++-- src/lib/onboard/openclaw-setup.test.ts | 25 ++++++++++++---- .../openclaw/initial-inference-route.ts | 6 ++-- .../onboard/sandbox-create/orchestration.ts | 7 ++++- 6 files changed, 70 insertions(+), 18 deletions(-) diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index d7b332490bc..15ddcb452a9 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -369,19 +369,32 @@ describe("inference selection config", () => { describe("getSandboxInferenceConfig", () => { it.each([ - ["compatible-endpoint", "http://host.openshell.internal:42103/v1", INFERENCE_ROUTE_URL], + ["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", ], - ["ollama-local", "http://192.168.65.2:11435/v1", "http://192.168.65.2:11435/v1"], - ])("selects %s transport for %s (#12558)", (provider, endpoint, expected) => { - expect( - getSandboxInferenceConfig("model-a", provider, "openai-completions", true, endpoint) - .inferenceBaseUrl, - ).toBe(expected); - }); + ["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({ diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index fb78fc9e9f3..166cf13aeaf 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -429,6 +429,7 @@ export function getSandboxInferenceConfig( } if ( + useNativeProvider && nativeEndpointUrl && usesNativeLocalInference(provider, nativeEndpointUrl) && nativeLocalCredentialReference(provider, nativeEndpointUrl) 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/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/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index be47171d655..c838639c73c 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -2488,6 +2488,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche preferredInferenceApi, createIntent, nativeProvider: Boolean( + existingSandboxEntry?.nativeLocalProviderAttachment || existingSandboxEntry?.nativeHostedProviderAttachment || existingSandboxEntry?.nativeNvidiaProviderAttachment, ), @@ -2848,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, ), From 5539ebe6c28b568caec11133d5bd7e1101e804a8 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:01:37 -0700 Subject: [PATCH 42/45] fix(inference): preserve local route finalization and guards --- ...build-legacy-local-route-preflight.test.ts | 69 +++-- .../sandbox/rebuild-preflight-phase.ts | 2 +- ...eated-sandbox-completion-selection.test.ts | 255 ++++++++++++++++++ .../created-sandbox-finalization.test.ts | 163 ----------- .../onboard/created-sandbox-finalization.ts | 3 +- ...vider-inference-legacy-local-route.test.ts | 18 +- .../machine/handlers/provider-inference.ts | 1 - 7 files changed, 317 insertions(+), 194 deletions(-) create mode 100644 src/lib/onboard/created-sandbox-completion-selection.test.ts 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 index 7d7c2b761fa..cdea5dfb6b3 100644 --- a/src/lib/actions/sandbox/rebuild-legacy-local-route-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-legacy-local-route-preflight.test.ts @@ -2,33 +2,46 @@ // 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" }, - { agent: "openclaw", provider: "vllm-local" }, - { agent: "langchain-deepagents-code", provider: "ollama-local" }, - ])("warns before rebuilding an existing $agent $provider sandbox", ({ agent, provider }) => { - const error = vi.spyOn(console, "error").mockImplementation(() => {}); - const bail = vi.fn((message: string): never => { - throw new Error(message); - }); - const entry = { - name: "alpha", - createdAt: "2026-09-01T00:00:00Z", - agent, - provider, - model: "local-model", - } as RebuildSandboxEntry; + { 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; - expect(() => blockRebuildOnLegacySharedLocalRoute("alpha", entry, 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(); - }); + 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 => { @@ -46,7 +59,19 @@ describe("rebuild legacy local route preflight", () => { expect( blockRebuildOnLegacySharedLocalRoute( "alpha", - { ...entry, createdAt: undefined, nativeLocalProviderAttachment: undefined }, + { + ...entry, + createdAt: undefined, + pendingRouteReservation: true, + nativeLocalProviderAttachment: undefined, + }, + bail, + ), + ).toBe(false); + expect( + blockRebuildOnLegacySharedLocalRoute( + "alpha", + { ...entry, pendingRouteReservation: true, nativeLocalProviderAttachment: undefined }, bail, ), ).toBe(false); diff --git a/src/lib/actions/sandbox/rebuild-preflight-phase.ts b/src/lib/actions/sandbox/rebuild-preflight-phase.ts index 69f56f17204..cb2df52d58a 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-phase.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-phase.ts @@ -140,7 +140,7 @@ export function blockRebuildOnLegacySharedLocalRoute( bail: RebuildBail, ): boolean { if ( - typeof sandboxEntry.createdAt !== "string" || + sandboxEntry.pendingRouteReservation === true || !hasLegacySharedLocalInferenceRoute(sandboxEntry) ) return false; 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 9fd349f136b..9e9810f851d 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -475,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(); diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index d3355dd661d..8f51340f298 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -774,8 +774,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/machine/handlers/provider-inference-legacy-local-route.test.ts b/src/lib/onboard/machine/handlers/provider-inference-legacy-local-route.test.ts index a171aeb8825..8a5fe59aeb6 100644 --- 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 @@ -9,6 +9,7 @@ vi.mock("../../../state/registry", async (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"; @@ -16,12 +17,14 @@ import { baseOptions, createDeps } from "./provider-inference.test-support"; describe("legacy local inference resume", () => { it.each([ - ["openclaw", true], - ["langchain-deepagents-code", true], - ["langchain-deepagents-code", false], + ["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) => { + async (selectedAgent, complete, recordedAt) => { const session = createSession({ agent: selectedAgent, sandboxName: "my-assistant", @@ -38,14 +41,17 @@ describe("legacy local inference resume", () => { name: "my-assistant", agent: selectedAgent, gatewayName: "nemoclaw", - createdAt: "2026-09-01T00:00:00Z", + ...(recordedAt ? { createdAt: recordedAt } : {}), provider: session.provider, model: session.model, endpointUrl: session.endpointUrl, credentialEnv: session.credentialEnv, preferredInferenceApi: session.preferredInferenceApi, } as SandboxEntry; - const { deps, calls } = createDeps({ getSandboxRegistryEntry: () => recorded }); + const [, persisted] = parseSandboxRegistryEntries( + JSON.parse(JSON.stringify({ "my-assistant": recorded })), + )[0]!; + const { deps, calls } = createDeps({ getSandboxRegistryEntry: () => persisted }); await expect( handleProviderInferenceState({ diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index a9ab9580b97..d066f8e59b3 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -1284,7 +1284,6 @@ function assertNoLegacySharedLocalResume( if ( recorded && recorded.pendingRouteReservation !== true && - typeof recorded.createdAt === "string" && hasLegacySharedLocalInferenceRoute(recorded) ) { throw new Error( From 128fdde250eb6af164defee204df69f3a437f629 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:08:41 -0700 Subject: [PATCH 43/45] fix(inference): type the resolved local provider receipt --- src/lib/onboard/created-sandbox-finalization.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index 8f51340f298..461af5beaec 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -620,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: { From a7ab2a3a536bda88c3f7bd4f2ce5b2c2e143172e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:45:57 -0700 Subject: [PATCH 44/45] test(rebuild): align fixtures with persisted local route guards --- .../rebuild-flow-credential-preflight.test.ts | 20 +++++++++++--- .../sandbox/rebuild-flow-lifecycle.test.ts | 2 +- .../rebuild-flow-target-credentials.test.ts | 9 ++++++- .../rebuild-flow-target-session.test.ts | 4 +++ .../sandbox/rebuild-resume-snapshot.test.ts | 22 +++++++++++++--- test/helpers/rebuild-flow-generic-harness.ts | 2 +- test/helpers/rebuild-flow-test-support.ts | 26 ++++++++++++++++++- .../rebuild-owning-registry-worker.test.ts | 2 +- 8 files changed, 75 insertions(+), 12 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts index 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 7e5f3da0b28..101c9fa9fcd 100644 --- a/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-lifecycle.test.ts @@ -425,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-resume-snapshot.test.ts b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts index becff08e5b1..407916abb0a 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,21 @@ 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, output, stdout: output, stderr: "" }], + ]); + return ( + responses.get(args.slice(0, 3).join(" ")) ?? { + status: 1, + output: "", + stdout: "", + stderr: "provider not found", + } + ); + }), vi.spyOn(registry, "updateSandbox").mockReturnValue(true), vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: [] } as never), vi.spyOn(mcpBridgeProvider, "getMcpProviderInspectionRuntimeSelection").mockReturnValue({ @@ -237,7 +253,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/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/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, From a9e75f1ce2c7c6cbcfc7243c3e54f197497df677 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:00:14 -0700 Subject: [PATCH 45/45] test(rebuild): type provider command fixture results Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-resume-snapshot.test.ts | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts index 407916abb0a..139ee654c22 100644 --- a/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts +++ b/src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts @@ -230,16 +230,19 @@ describe("rebuild resume snapshot repair", () => { 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, output, stdout: output, stderr: "" }], + ["provider get nvidia-router", { status: 0, stdout: output, stderr: "" }], ]); - return ( - responses.get(args.slice(0, 3).join(" ")) ?? { - status: 1, - output: "", - stdout: "", - stderr: "provider not found", - } - ); + 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),